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 col += author_width;
2053 while (col < avail && author_width < author_display_cols + 2) {
2054 waddch(view->window, ' ');
2055 col++;
2056 author_width++;
2058 if (tc)
2059 wattr_off(view->window,
2060 COLOR_PAIR(tc->colorpair), NULL);
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, COLOR_PAIR(tc->colorpair), NULL);
2339 waddwstr(view->window, wline);
2340 while (width < view->ncols) {
2341 waddch(view->window, ' ');
2342 width++;
2344 if (tc)
2345 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2346 if (view_needs_focus_indication(view))
2347 wstandend(view->window);
2348 free(wline);
2349 if (limit <= 1)
2350 goto done;
2352 /* Grow author column size if necessary, and set view->maxx. */
2353 entry = s->first_displayed_entry;
2354 ncommits = 0;
2355 view->maxx = 0;
2356 while (entry) {
2357 struct got_commit_object *c = entry->commit;
2358 char *author, *eol, *msg, *msg0;
2359 wchar_t *wauthor, *wmsg;
2360 int width;
2361 if (ncommits >= limit - 1)
2362 break;
2363 if (s->use_committer)
2364 author = strdup(got_object_commit_get_committer(c));
2365 else
2366 author = strdup(got_object_commit_get_author(c));
2367 if (author == NULL) {
2368 err = got_error_from_errno("strdup");
2369 goto done;
2371 err = format_author(&wauthor, &width, author, COLS,
2372 date_display_cols);
2373 if (author_cols < width)
2374 author_cols = width;
2375 free(wauthor);
2376 free(author);
2377 if (err)
2378 goto done;
2379 err = got_object_commit_get_logmsg(&msg0, c);
2380 if (err)
2381 goto done;
2382 msg = msg0;
2383 while (*msg == '\n')
2384 ++msg;
2385 if ((eol = strchr(msg, '\n')))
2386 *eol = '\0';
2387 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2388 date_display_cols + author_cols, 0);
2389 if (err)
2390 goto done;
2391 view->maxx = MAX(view->maxx, width);
2392 free(msg0);
2393 free(wmsg);
2394 ncommits++;
2395 entry = TAILQ_NEXT(entry, entry);
2398 entry = s->first_displayed_entry;
2399 s->last_displayed_entry = s->first_displayed_entry;
2400 ncommits = 0;
2401 while (entry) {
2402 if (ncommits >= limit - 1)
2403 break;
2404 if (ncommits == s->selected)
2405 wstandout(view->window);
2406 err = draw_commit(view, entry->commit, entry->id,
2407 date_display_cols, author_cols);
2408 if (ncommits == s->selected)
2409 wstandend(view->window);
2410 if (err)
2411 goto done;
2412 ncommits++;
2413 s->last_displayed_entry = entry;
2414 entry = TAILQ_NEXT(entry, entry);
2417 view_border(view);
2418 done:
2419 free(id_str);
2420 free(refs_str);
2421 free(ncommits_str);
2422 free(header);
2423 return err;
2426 static void
2427 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2429 struct commit_queue_entry *entry;
2430 int nscrolled = 0;
2432 entry = TAILQ_FIRST(&s->commits.head);
2433 if (s->first_displayed_entry == entry)
2434 return;
2436 entry = s->first_displayed_entry;
2437 while (entry && nscrolled < maxscroll) {
2438 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2439 if (entry) {
2440 s->first_displayed_entry = entry;
2441 nscrolled++;
2446 static const struct got_error *
2447 trigger_log_thread(struct tog_view *view, int wait)
2449 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2450 int errcode;
2452 halfdelay(1); /* fast refresh while loading commits */
2454 while (!ta->log_complete && !tog_thread_error &&
2455 (ta->commits_needed > 0 || ta->load_all)) {
2456 /* Wake the log thread. */
2457 errcode = pthread_cond_signal(&ta->need_commits);
2458 if (errcode)
2459 return got_error_set_errno(errcode,
2460 "pthread_cond_signal");
2463 * The mutex will be released while the view loop waits
2464 * in wgetch(), at which time the log thread will run.
2466 if (!wait)
2467 break;
2469 /* Display progress update in log view. */
2470 show_log_view(view);
2471 update_panels();
2472 doupdate();
2474 /* Wait right here while next commit is being loaded. */
2475 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2476 if (errcode)
2477 return got_error_set_errno(errcode,
2478 "pthread_cond_wait");
2480 /* Display progress update in log view. */
2481 show_log_view(view);
2482 update_panels();
2483 doupdate();
2486 return NULL;
2489 static const struct got_error *
2490 request_log_commits(struct tog_view *view)
2492 struct tog_log_view_state *state = &view->state.log;
2493 const struct got_error *err = NULL;
2495 if (state->thread_args.log_complete)
2496 return NULL;
2498 state->thread_args.commits_needed += view->nscrolled;
2499 err = trigger_log_thread(view, 1);
2500 view->nscrolled = 0;
2502 return err;
2505 static const struct got_error *
2506 log_scroll_down(struct tog_view *view, int maxscroll)
2508 struct tog_log_view_state *s = &view->state.log;
2509 const struct got_error *err = NULL;
2510 struct commit_queue_entry *pentry;
2511 int nscrolled = 0, ncommits_needed;
2513 if (s->last_displayed_entry == NULL)
2514 return NULL;
2516 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2517 if (s->commits.ncommits < ncommits_needed &&
2518 !s->thread_args.log_complete) {
2520 * Ask the log thread for required amount of commits.
2522 s->thread_args.commits_needed +=
2523 ncommits_needed - s->commits.ncommits;
2524 err = trigger_log_thread(view, 1);
2525 if (err)
2526 return err;
2529 do {
2530 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2531 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2532 break;
2534 s->last_displayed_entry = pentry ?
2535 pentry : s->last_displayed_entry;;
2537 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2538 if (pentry == NULL)
2539 break;
2540 s->first_displayed_entry = pentry;
2541 } while (++nscrolled < maxscroll);
2543 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2544 view->nscrolled += nscrolled;
2545 else
2546 view->nscrolled = 0;
2548 return err;
2551 static const struct got_error *
2552 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2553 struct got_commit_object *commit, struct got_object_id *commit_id,
2554 struct tog_view *log_view, struct got_repository *repo)
2556 const struct got_error *err;
2557 struct got_object_qid *parent_id;
2558 struct tog_view *diff_view;
2560 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2561 if (diff_view == NULL)
2562 return got_error_from_errno("view_open");
2564 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2565 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2566 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2567 if (err == NULL)
2568 *new_view = diff_view;
2569 return err;
2572 static const struct got_error *
2573 tree_view_visit_subtree(struct tog_tree_view_state *s,
2574 struct got_tree_object *subtree)
2576 struct tog_parent_tree *parent;
2578 parent = calloc(1, sizeof(*parent));
2579 if (parent == NULL)
2580 return got_error_from_errno("calloc");
2582 parent->tree = s->tree;
2583 parent->first_displayed_entry = s->first_displayed_entry;
2584 parent->selected_entry = s->selected_entry;
2585 parent->selected = s->selected;
2586 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2587 s->tree = subtree;
2588 s->selected = 0;
2589 s->first_displayed_entry = NULL;
2590 return NULL;
2593 static const struct got_error *
2594 tree_view_walk_path(struct tog_tree_view_state *s,
2595 struct got_commit_object *commit, const char *path)
2597 const struct got_error *err = NULL;
2598 struct got_tree_object *tree = NULL;
2599 const char *p;
2600 char *slash, *subpath = NULL;
2602 /* Walk the path and open corresponding tree objects. */
2603 p = path;
2604 while (*p) {
2605 struct got_tree_entry *te;
2606 struct got_object_id *tree_id;
2607 char *te_name;
2609 while (p[0] == '/')
2610 p++;
2612 /* Ensure the correct subtree entry is selected. */
2613 slash = strchr(p, '/');
2614 if (slash == NULL)
2615 te_name = strdup(p);
2616 else
2617 te_name = strndup(p, slash - p);
2618 if (te_name == NULL) {
2619 err = got_error_from_errno("strndup");
2620 break;
2622 te = got_object_tree_find_entry(s->tree, te_name);
2623 if (te == NULL) {
2624 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2625 free(te_name);
2626 break;
2628 free(te_name);
2629 s->first_displayed_entry = s->selected_entry = te;
2631 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2632 break; /* jump to this file's entry */
2634 slash = strchr(p, '/');
2635 if (slash)
2636 subpath = strndup(path, slash - path);
2637 else
2638 subpath = strdup(path);
2639 if (subpath == NULL) {
2640 err = got_error_from_errno("strdup");
2641 break;
2644 err = got_object_id_by_path(&tree_id, s->repo, commit,
2645 subpath);
2646 if (err)
2647 break;
2649 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2650 free(tree_id);
2651 if (err)
2652 break;
2654 err = tree_view_visit_subtree(s, tree);
2655 if (err) {
2656 got_object_tree_close(tree);
2657 break;
2659 if (slash == NULL)
2660 break;
2661 free(subpath);
2662 subpath = NULL;
2663 p = slash;
2666 free(subpath);
2667 return err;
2670 static const struct got_error *
2671 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2672 struct commit_queue_entry *entry, const char *path,
2673 const char *head_ref_name, struct got_repository *repo)
2675 const struct got_error *err = NULL;
2676 struct tog_tree_view_state *s;
2677 struct tog_view *tree_view;
2679 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2680 if (tree_view == NULL)
2681 return got_error_from_errno("view_open");
2683 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2684 if (err)
2685 return err;
2686 s = &tree_view->state.tree;
2688 *new_view = tree_view;
2690 if (got_path_is_root_dir(path))
2691 return NULL;
2693 return tree_view_walk_path(s, entry->commit, path);
2696 static const struct got_error *
2697 block_signals_used_by_main_thread(void)
2699 sigset_t sigset;
2700 int errcode;
2702 if (sigemptyset(&sigset) == -1)
2703 return got_error_from_errno("sigemptyset");
2705 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2706 if (sigaddset(&sigset, SIGWINCH) == -1)
2707 return got_error_from_errno("sigaddset");
2708 if (sigaddset(&sigset, SIGCONT) == -1)
2709 return got_error_from_errno("sigaddset");
2710 if (sigaddset(&sigset, SIGINT) == -1)
2711 return got_error_from_errno("sigaddset");
2712 if (sigaddset(&sigset, SIGTERM) == -1)
2713 return got_error_from_errno("sigaddset");
2715 /* ncurses handles SIGTSTP */
2716 if (sigaddset(&sigset, SIGTSTP) == -1)
2717 return got_error_from_errno("sigaddset");
2719 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2720 if (errcode)
2721 return got_error_set_errno(errcode, "pthread_sigmask");
2723 return NULL;
2726 static void *
2727 log_thread(void *arg)
2729 const struct got_error *err = NULL;
2730 int errcode = 0;
2731 struct tog_log_thread_args *a = arg;
2732 int done = 0;
2735 * Sync startup with main thread such that we begin our
2736 * work once view_input() has released the mutex.
2738 errcode = pthread_mutex_lock(&tog_mutex);
2739 if (errcode) {
2740 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2741 return (void *)err;
2744 err = block_signals_used_by_main_thread();
2745 if (err) {
2746 pthread_mutex_unlock(&tog_mutex);
2747 goto done;
2750 while (!done && !err && !tog_fatal_signal_received()) {
2751 errcode = pthread_mutex_unlock(&tog_mutex);
2752 if (errcode) {
2753 err = got_error_set_errno(errcode,
2754 "pthread_mutex_unlock");
2755 goto done;
2757 err = queue_commits(a);
2758 if (err) {
2759 if (err->code != GOT_ERR_ITER_COMPLETED)
2760 goto done;
2761 err = NULL;
2762 done = 1;
2763 } else if (a->commits_needed > 0 && !a->load_all)
2764 a->commits_needed--;
2766 errcode = pthread_mutex_lock(&tog_mutex);
2767 if (errcode) {
2768 err = got_error_set_errno(errcode,
2769 "pthread_mutex_lock");
2770 goto done;
2771 } else if (*a->quit)
2772 done = 1;
2773 else if (*a->first_displayed_entry == NULL) {
2774 *a->first_displayed_entry =
2775 TAILQ_FIRST(&a->commits->head);
2776 *a->selected_entry = *a->first_displayed_entry;
2779 errcode = pthread_cond_signal(&a->commit_loaded);
2780 if (errcode) {
2781 err = got_error_set_errno(errcode,
2782 "pthread_cond_signal");
2783 pthread_mutex_unlock(&tog_mutex);
2784 goto done;
2787 if (done)
2788 a->commits_needed = 0;
2789 else {
2790 if (a->commits_needed == 0 && !a->load_all) {
2791 errcode = pthread_cond_wait(&a->need_commits,
2792 &tog_mutex);
2793 if (errcode) {
2794 err = got_error_set_errno(errcode,
2795 "pthread_cond_wait");
2796 pthread_mutex_unlock(&tog_mutex);
2797 goto done;
2799 if (*a->quit)
2800 done = 1;
2804 a->log_complete = 1;
2805 errcode = pthread_mutex_unlock(&tog_mutex);
2806 if (errcode)
2807 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2808 done:
2809 if (err) {
2810 tog_thread_error = 1;
2811 pthread_cond_signal(&a->commit_loaded);
2813 return (void *)err;
2816 static const struct got_error *
2817 stop_log_thread(struct tog_log_view_state *s)
2819 const struct got_error *err = NULL, *thread_err = NULL;
2820 int errcode;
2822 if (s->thread) {
2823 s->quit = 1;
2824 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2825 if (errcode)
2826 return got_error_set_errno(errcode,
2827 "pthread_cond_signal");
2828 errcode = pthread_mutex_unlock(&tog_mutex);
2829 if (errcode)
2830 return got_error_set_errno(errcode,
2831 "pthread_mutex_unlock");
2832 errcode = pthread_join(s->thread, (void **)&thread_err);
2833 if (errcode)
2834 return got_error_set_errno(errcode, "pthread_join");
2835 errcode = pthread_mutex_lock(&tog_mutex);
2836 if (errcode)
2837 return got_error_set_errno(errcode,
2838 "pthread_mutex_lock");
2839 s->thread = 0; //NULL;
2842 if (s->thread_args.repo) {
2843 err = got_repo_close(s->thread_args.repo);
2844 s->thread_args.repo = NULL;
2847 if (s->thread_args.pack_fds) {
2848 const struct got_error *pack_err =
2849 got_repo_pack_fds_close(s->thread_args.pack_fds);
2850 if (err == NULL)
2851 err = pack_err;
2852 s->thread_args.pack_fds = NULL;
2855 if (s->thread_args.graph) {
2856 got_commit_graph_close(s->thread_args.graph);
2857 s->thread_args.graph = NULL;
2860 return err ? err : thread_err;
2863 static const struct got_error *
2864 close_log_view(struct tog_view *view)
2866 const struct got_error *err = NULL;
2867 struct tog_log_view_state *s = &view->state.log;
2868 int errcode;
2870 err = stop_log_thread(s);
2872 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2873 if (errcode && err == NULL)
2874 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2876 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2877 if (errcode && err == NULL)
2878 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2880 free_commits(&s->commits);
2881 free(s->in_repo_path);
2882 s->in_repo_path = NULL;
2883 free(s->start_id);
2884 s->start_id = NULL;
2885 free(s->head_ref_name);
2886 s->head_ref_name = NULL;
2887 return err;
2890 static const struct got_error *
2891 search_start_log_view(struct tog_view *view)
2893 struct tog_log_view_state *s = &view->state.log;
2895 s->matched_entry = NULL;
2896 s->search_entry = NULL;
2897 return NULL;
2900 static const struct got_error *
2901 search_next_log_view(struct tog_view *view)
2903 const struct got_error *err = NULL;
2904 struct tog_log_view_state *s = &view->state.log;
2905 struct commit_queue_entry *entry;
2907 /* Display progress update in log view. */
2908 show_log_view(view);
2909 update_panels();
2910 doupdate();
2912 if (s->search_entry) {
2913 int errcode, ch;
2914 errcode = pthread_mutex_unlock(&tog_mutex);
2915 if (errcode)
2916 return got_error_set_errno(errcode,
2917 "pthread_mutex_unlock");
2918 ch = wgetch(view->window);
2919 errcode = pthread_mutex_lock(&tog_mutex);
2920 if (errcode)
2921 return got_error_set_errno(errcode,
2922 "pthread_mutex_lock");
2923 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2924 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2925 return NULL;
2927 if (view->searching == TOG_SEARCH_FORWARD)
2928 entry = TAILQ_NEXT(s->search_entry, entry);
2929 else
2930 entry = TAILQ_PREV(s->search_entry,
2931 commit_queue_head, entry);
2932 } else if (s->matched_entry) {
2933 int matched_idx = s->matched_entry->idx;
2934 int selected_idx = s->selected_entry->idx;
2937 * If the user has moved the cursor after we hit a match,
2938 * the position from where we should continue searching
2939 * might have changed.
2941 if (view->searching == TOG_SEARCH_FORWARD) {
2942 if (matched_idx > selected_idx)
2943 entry = TAILQ_NEXT(s->selected_entry, entry);
2944 else
2945 entry = TAILQ_NEXT(s->matched_entry, entry);
2946 } else {
2947 if (matched_idx < selected_idx)
2948 entry = TAILQ_PREV(s->selected_entry,
2949 commit_queue_head, entry);
2950 else
2951 entry = TAILQ_PREV(s->matched_entry,
2952 commit_queue_head, entry);
2954 } else {
2955 entry = s->selected_entry;
2958 while (1) {
2959 int have_match = 0;
2961 if (entry == NULL) {
2962 if (s->thread_args.log_complete ||
2963 view->searching == TOG_SEARCH_BACKWARD) {
2964 view->search_next_done =
2965 (s->matched_entry == NULL ?
2966 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2967 s->search_entry = NULL;
2968 return NULL;
2971 * Poke the log thread for more commits and return,
2972 * allowing the main loop to make progress. Search
2973 * will resume at s->search_entry once we come back.
2975 s->thread_args.commits_needed++;
2976 return trigger_log_thread(view, 0);
2979 err = match_commit(&have_match, entry->id, entry->commit,
2980 &view->regex);
2981 if (err)
2982 break;
2983 if (have_match) {
2984 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2985 s->matched_entry = entry;
2986 break;
2989 s->search_entry = entry;
2990 if (view->searching == TOG_SEARCH_FORWARD)
2991 entry = TAILQ_NEXT(entry, entry);
2992 else
2993 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2996 if (s->matched_entry) {
2997 int cur = s->selected_entry->idx;
2998 while (cur < s->matched_entry->idx) {
2999 err = input_log_view(NULL, view, KEY_DOWN);
3000 if (err)
3001 return err;
3002 cur++;
3004 while (cur > s->matched_entry->idx) {
3005 err = input_log_view(NULL, view, KEY_UP);
3006 if (err)
3007 return err;
3008 cur--;
3012 s->search_entry = NULL;
3014 return NULL;
3017 static const struct got_error *
3018 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3019 struct got_repository *repo, const char *head_ref_name,
3020 const char *in_repo_path, int log_branches)
3022 const struct got_error *err = NULL;
3023 struct tog_log_view_state *s = &view->state.log;
3024 struct got_repository *thread_repo = NULL;
3025 struct got_commit_graph *thread_graph = NULL;
3026 int errcode;
3028 if (in_repo_path != s->in_repo_path) {
3029 free(s->in_repo_path);
3030 s->in_repo_path = strdup(in_repo_path);
3031 if (s->in_repo_path == NULL)
3032 return got_error_from_errno("strdup");
3035 /* The commit queue only contains commits being displayed. */
3036 TAILQ_INIT(&s->commits.head);
3037 s->commits.ncommits = 0;
3039 s->repo = repo;
3040 if (head_ref_name) {
3041 s->head_ref_name = strdup(head_ref_name);
3042 if (s->head_ref_name == NULL) {
3043 err = got_error_from_errno("strdup");
3044 goto done;
3047 s->start_id = got_object_id_dup(start_id);
3048 if (s->start_id == NULL) {
3049 err = got_error_from_errno("got_object_id_dup");
3050 goto done;
3052 s->log_branches = log_branches;
3054 STAILQ_INIT(&s->colors);
3055 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3056 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3057 get_color_value("TOG_COLOR_COMMIT"));
3058 if (err)
3059 goto done;
3060 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3061 get_color_value("TOG_COLOR_AUTHOR"));
3062 if (err) {
3063 free_colors(&s->colors);
3064 goto done;
3066 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3067 get_color_value("TOG_COLOR_DATE"));
3068 if (err) {
3069 free_colors(&s->colors);
3070 goto done;
3074 view->show = show_log_view;
3075 view->input = input_log_view;
3076 view->resize = resize_log_view;
3077 view->close = close_log_view;
3078 view->search_start = search_start_log_view;
3079 view->search_next = search_next_log_view;
3081 if (s->thread_args.pack_fds == NULL) {
3082 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3083 if (err)
3084 goto done;
3086 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3087 s->thread_args.pack_fds);
3088 if (err)
3089 goto done;
3090 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3091 !s->log_branches);
3092 if (err)
3093 goto done;
3094 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3095 s->repo, NULL, NULL);
3096 if (err)
3097 goto done;
3099 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3100 if (errcode) {
3101 err = got_error_set_errno(errcode, "pthread_cond_init");
3102 goto done;
3104 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3105 if (errcode) {
3106 err = got_error_set_errno(errcode, "pthread_cond_init");
3107 goto done;
3110 s->thread_args.commits_needed = view->nlines;
3111 s->thread_args.graph = thread_graph;
3112 s->thread_args.commits = &s->commits;
3113 s->thread_args.in_repo_path = s->in_repo_path;
3114 s->thread_args.start_id = s->start_id;
3115 s->thread_args.repo = thread_repo;
3116 s->thread_args.log_complete = 0;
3117 s->thread_args.quit = &s->quit;
3118 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3119 s->thread_args.selected_entry = &s->selected_entry;
3120 s->thread_args.searching = &view->searching;
3121 s->thread_args.search_next_done = &view->search_next_done;
3122 s->thread_args.regex = &view->regex;
3123 done:
3124 if (err)
3125 close_log_view(view);
3126 return err;
3129 static const struct got_error *
3130 show_log_view(struct tog_view *view)
3132 const struct got_error *err;
3133 struct tog_log_view_state *s = &view->state.log;
3135 if (s->thread == 0) { //NULL) {
3136 int errcode = pthread_create(&s->thread, NULL, log_thread,
3137 &s->thread_args);
3138 if (errcode)
3139 return got_error_set_errno(errcode, "pthread_create");
3140 if (s->thread_args.commits_needed > 0) {
3141 err = trigger_log_thread(view, 1);
3142 if (err)
3143 return err;
3147 return draw_commits(view);
3150 static void
3151 log_move_cursor_up(struct tog_view *view, int page, int home)
3153 struct tog_log_view_state *s = &view->state.log;
3155 if (s->selected_entry->idx == 0)
3156 view->count = 0;
3157 if (s->first_displayed_entry == NULL)
3158 return;
3160 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3161 || home)
3162 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3164 if (!page && !home && s->selected > 0)
3165 --s->selected;
3166 else
3167 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3169 select_commit(s);
3170 return;
3173 static const struct got_error *
3174 log_move_cursor_down(struct tog_view *view, int page)
3176 struct tog_log_view_state *s = &view->state.log;
3177 const struct got_error *err = NULL;
3178 int eos = view->nlines - 2;
3180 if (s->thread_args.log_complete &&
3181 s->selected_entry->idx >= s->commits.ncommits - 1)
3182 return NULL;
3184 if (view_is_hsplit_top(view))
3185 --eos; /* border consumes the last line */
3187 if (!page) {
3188 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3189 ++s->selected;
3190 else
3191 err = log_scroll_down(view, 1);
3192 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3193 struct commit_queue_entry *entry;
3194 int n;
3196 s->selected = 0;
3197 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3198 s->last_displayed_entry = entry;
3199 for (n = 0; n <= eos; n++) {
3200 if (entry == NULL)
3201 break;
3202 s->first_displayed_entry = entry;
3203 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3205 if (n > 0)
3206 s->selected = n - 1;
3207 } else {
3208 if (s->last_displayed_entry->idx == s->commits.ncommits - 1 &&
3209 s->thread_args.log_complete)
3210 s->selected += MIN(page,
3211 s->commits.ncommits - s->selected_entry->idx - 1);
3212 else
3213 err = log_scroll_down(view, page);
3215 if (err)
3216 return err;
3219 * We might necessarily overshoot in horizontal
3220 * splits; if so, select the last displayed commit.
3222 if (s->first_displayed_entry && s->last_displayed_entry) {
3223 s->selected = MIN(s->selected,
3224 s->last_displayed_entry->idx -
3225 s->first_displayed_entry->idx);
3228 select_commit(s);
3230 if (s->thread_args.log_complete &&
3231 s->selected_entry->idx == s->commits.ncommits - 1)
3232 view->count = 0;
3234 return NULL;
3237 static void
3238 view_get_split(struct tog_view *view, int *y, int *x)
3240 *x = 0;
3241 *y = 0;
3243 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3244 if (view->child && view->child->resized_y)
3245 *y = view->child->resized_y;
3246 else if (view->resized_y)
3247 *y = view->resized_y;
3248 else
3249 *y = view_split_begin_y(view->lines);
3250 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3251 if (view->child && view->child->resized_x)
3252 *x = view->child->resized_x;
3253 else if (view->resized_x)
3254 *x = view->resized_x;
3255 else
3256 *x = view_split_begin_x(view->begin_x);
3260 /* Split view horizontally at y and offset view->state->selected line. */
3261 static const struct got_error *
3262 view_init_hsplit(struct tog_view *view, int y)
3264 const struct got_error *err = NULL;
3266 view->nlines = y;
3267 view->ncols = COLS;
3268 err = view_resize(view);
3269 if (err)
3270 return err;
3272 err = offset_selection_down(view);
3274 return err;
3277 static const struct got_error *
3278 log_goto_line(struct tog_view *view, int nlines)
3280 const struct got_error *err = NULL;
3281 struct tog_log_view_state *s = &view->state.log;
3282 int g, idx = s->selected_entry->idx;
3284 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3285 return NULL;
3287 g = view->gline;
3288 view->gline = 0;
3290 if (g >= s->first_displayed_entry->idx + 1 &&
3291 g <= s->last_displayed_entry->idx + 1 &&
3292 g - s->first_displayed_entry->idx - 1 < nlines) {
3293 s->selected = g - s->first_displayed_entry->idx - 1;
3294 select_commit(s);
3295 return NULL;
3298 if (idx + 1 < g) {
3299 err = log_move_cursor_down(view, g - idx - 1);
3300 if (!err && g > s->selected_entry->idx + 1)
3301 err = log_move_cursor_down(view,
3302 g - s->first_displayed_entry->idx - 1);
3303 if (err)
3304 return err;
3305 } else if (idx + 1 > g)
3306 log_move_cursor_up(view, idx - g + 1, 0);
3308 if (g < nlines && s->first_displayed_entry->idx == 0)
3309 s->selected = g - 1;
3311 select_commit(s);
3312 return NULL;
3316 static const struct got_error *
3317 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3319 const struct got_error *err = NULL;
3320 struct tog_log_view_state *s = &view->state.log;
3321 int eos, nscroll;
3323 if (s->thread_args.load_all) {
3324 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3325 s->thread_args.load_all = 0;
3326 else if (s->thread_args.log_complete) {
3327 err = log_move_cursor_down(view, s->commits.ncommits);
3328 s->thread_args.load_all = 0;
3330 if (err)
3331 return err;
3334 eos = nscroll = view->nlines - 1;
3335 if (view_is_hsplit_top(view))
3336 --eos; /* border */
3338 if (view->gline)
3339 return log_goto_line(view, eos);
3341 switch (ch) {
3342 case 'q':
3343 s->quit = 1;
3344 break;
3345 case '0':
3346 view->x = 0;
3347 break;
3348 case '$':
3349 view->x = MAX(view->maxx - view->ncols / 2, 0);
3350 view->count = 0;
3351 break;
3352 case KEY_RIGHT:
3353 case 'l':
3354 if (view->x + view->ncols / 2 < view->maxx)
3355 view->x += 2; /* move two columns right */
3356 else
3357 view->count = 0;
3358 break;
3359 case KEY_LEFT:
3360 case 'h':
3361 view->x -= MIN(view->x, 2); /* move two columns back */
3362 if (view->x <= 0)
3363 view->count = 0;
3364 break;
3365 case 'k':
3366 case KEY_UP:
3367 case '<':
3368 case ',':
3369 case CTRL('p'):
3370 log_move_cursor_up(view, 0, 0);
3371 break;
3372 case 'g':
3373 case KEY_HOME:
3374 log_move_cursor_up(view, 0, 1);
3375 view->count = 0;
3376 break;
3377 case CTRL('u'):
3378 case 'u':
3379 nscroll /= 2;
3380 /* FALL THROUGH */
3381 case KEY_PPAGE:
3382 case CTRL('b'):
3383 case 'b':
3384 log_move_cursor_up(view, nscroll, 0);
3385 break;
3386 case 'j':
3387 case KEY_DOWN:
3388 case '>':
3389 case '.':
3390 case CTRL('n'):
3391 err = log_move_cursor_down(view, 0);
3392 break;
3393 case '@':
3394 s->use_committer = !s->use_committer;
3395 break;
3396 case 'G':
3397 case KEY_END: {
3398 /* We don't know yet how many commits, so we're forced to
3399 * traverse them all. */
3400 view->count = 0;
3401 s->thread_args.load_all = 1;
3402 if (!s->thread_args.log_complete)
3403 return trigger_log_thread(view, 0);
3404 err = log_move_cursor_down(view, s->commits.ncommits);
3405 s->thread_args.load_all = 0;
3406 break;
3408 case CTRL('d'):
3409 case 'd':
3410 nscroll /= 2;
3411 /* FALL THROUGH */
3412 case KEY_NPAGE:
3413 case CTRL('f'):
3414 case 'f':
3415 case ' ':
3416 err = log_move_cursor_down(view, nscroll);
3417 break;
3418 case KEY_RESIZE:
3419 if (s->selected > view->nlines - 2)
3420 s->selected = view->nlines - 2;
3421 if (s->selected > s->commits.ncommits - 1)
3422 s->selected = s->commits.ncommits - 1;
3423 select_commit(s);
3424 if (s->commits.ncommits < view->nlines - 1 &&
3425 !s->thread_args.log_complete) {
3426 s->thread_args.commits_needed += (view->nlines - 1) -
3427 s->commits.ncommits;
3428 err = trigger_log_thread(view, 1);
3430 break;
3431 case KEY_ENTER:
3432 case '\r':
3433 view->count = 0;
3434 if (s->selected_entry == NULL)
3435 break;
3436 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3437 break;
3438 case 'T':
3439 view->count = 0;
3440 if (s->selected_entry == NULL)
3441 break;
3442 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3443 break;
3444 case KEY_BACKSPACE:
3445 case CTRL('l'):
3446 case 'B':
3447 view->count = 0;
3448 if (ch == KEY_BACKSPACE &&
3449 got_path_is_root_dir(s->in_repo_path))
3450 break;
3451 err = stop_log_thread(s);
3452 if (err)
3453 return err;
3454 if (ch == KEY_BACKSPACE) {
3455 char *parent_path;
3456 err = got_path_dirname(&parent_path, s->in_repo_path);
3457 if (err)
3458 return err;
3459 free(s->in_repo_path);
3460 s->in_repo_path = parent_path;
3461 s->thread_args.in_repo_path = s->in_repo_path;
3462 } else if (ch == CTRL('l')) {
3463 struct got_object_id *start_id;
3464 err = got_repo_match_object_id(&start_id, NULL,
3465 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3466 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3467 if (err)
3468 return err;
3469 free(s->start_id);
3470 s->start_id = start_id;
3471 s->thread_args.start_id = s->start_id;
3472 } else /* 'B' */
3473 s->log_branches = !s->log_branches;
3475 if (s->thread_args.pack_fds == NULL) {
3476 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3477 if (err)
3478 return err;
3480 err = got_repo_open(&s->thread_args.repo,
3481 got_repo_get_path(s->repo), NULL,
3482 s->thread_args.pack_fds);
3483 if (err)
3484 return err;
3485 tog_free_refs();
3486 err = tog_load_refs(s->repo, 0);
3487 if (err)
3488 return err;
3489 err = got_commit_graph_open(&s->thread_args.graph,
3490 s->in_repo_path, !s->log_branches);
3491 if (err)
3492 return err;
3493 err = got_commit_graph_iter_start(s->thread_args.graph,
3494 s->start_id, s->repo, NULL, NULL);
3495 if (err)
3496 return err;
3497 free_commits(&s->commits);
3498 s->first_displayed_entry = NULL;
3499 s->last_displayed_entry = NULL;
3500 s->selected_entry = NULL;
3501 s->selected = 0;
3502 s->thread_args.log_complete = 0;
3503 s->quit = 0;
3504 s->thread_args.commits_needed = view->lines;
3505 s->matched_entry = NULL;
3506 s->search_entry = NULL;
3507 view->offset = 0;
3508 break;
3509 case 'R':
3510 view->count = 0;
3511 err = view_request_new(new_view, view, TOG_VIEW_REF);
3512 break;
3513 default:
3514 view->count = 0;
3515 break;
3518 return err;
3521 static const struct got_error *
3522 apply_unveil(const char *repo_path, const char *worktree_path)
3524 const struct got_error *error;
3526 #ifdef PROFILE
3527 if (unveil("gmon.out", "rwc") != 0)
3528 return got_error_from_errno2("unveil", "gmon.out");
3529 #endif
3530 if (repo_path && unveil(repo_path, "r") != 0)
3531 return got_error_from_errno2("unveil", repo_path);
3533 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3534 return got_error_from_errno2("unveil", worktree_path);
3536 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3537 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3539 error = got_privsep_unveil_exec_helpers();
3540 if (error != NULL)
3541 return error;
3543 if (unveil(NULL, NULL) != 0)
3544 return got_error_from_errno("unveil");
3546 return NULL;
3549 static void
3550 init_curses(void)
3553 * Override default signal handlers before starting ncurses.
3554 * This should prevent ncurses from installing its own
3555 * broken cleanup() signal handler.
3557 signal(SIGWINCH, tog_sigwinch);
3558 signal(SIGPIPE, tog_sigpipe);
3559 signal(SIGCONT, tog_sigcont);
3560 signal(SIGINT, tog_sigint);
3561 signal(SIGTERM, tog_sigterm);
3563 initscr();
3564 cbreak();
3565 halfdelay(1); /* Do fast refresh while initial view is loading. */
3566 noecho();
3567 nonl();
3568 intrflush(stdscr, FALSE);
3569 keypad(stdscr, TRUE);
3570 curs_set(0);
3571 if (getenv("TOG_COLORS") != NULL) {
3572 start_color();
3573 use_default_colors();
3577 static const struct got_error *
3578 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3579 struct got_repository *repo, struct got_worktree *worktree)
3581 const struct got_error *err = NULL;
3583 if (argc == 0) {
3584 *in_repo_path = strdup("/");
3585 if (*in_repo_path == NULL)
3586 return got_error_from_errno("strdup");
3587 return NULL;
3590 if (worktree) {
3591 const char *prefix = got_worktree_get_path_prefix(worktree);
3592 char *p;
3594 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3595 if (err)
3596 return err;
3597 if (asprintf(in_repo_path, "%s%s%s", prefix,
3598 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3599 p) == -1) {
3600 err = got_error_from_errno("asprintf");
3601 *in_repo_path = NULL;
3603 free(p);
3604 } else
3605 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3607 return err;
3610 static const struct got_error *
3611 cmd_log(int argc, char *argv[])
3613 const struct got_error *error;
3614 struct got_repository *repo = NULL;
3615 struct got_worktree *worktree = NULL;
3616 struct got_object_id *start_id = NULL;
3617 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3618 char *start_commit = NULL, *label = NULL;
3619 struct got_reference *ref = NULL;
3620 const char *head_ref_name = NULL;
3621 int ch, log_branches = 0;
3622 struct tog_view *view;
3623 int *pack_fds = NULL;
3625 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3626 switch (ch) {
3627 case 'b':
3628 log_branches = 1;
3629 break;
3630 case 'c':
3631 start_commit = optarg;
3632 break;
3633 case 'r':
3634 repo_path = realpath(optarg, NULL);
3635 if (repo_path == NULL)
3636 return got_error_from_errno2("realpath",
3637 optarg);
3638 break;
3639 default:
3640 usage_log();
3641 /* NOTREACHED */
3645 argc -= optind;
3646 argv += optind;
3648 if (argc > 1)
3649 usage_log();
3651 error = got_repo_pack_fds_open(&pack_fds);
3652 if (error != NULL)
3653 goto done;
3655 if (repo_path == NULL) {
3656 cwd = getcwd(NULL, 0);
3657 if (cwd == NULL)
3658 return got_error_from_errno("getcwd");
3659 error = got_worktree_open(&worktree, cwd);
3660 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3661 goto done;
3662 if (worktree)
3663 repo_path =
3664 strdup(got_worktree_get_repo_path(worktree));
3665 else
3666 repo_path = strdup(cwd);
3667 if (repo_path == NULL) {
3668 error = got_error_from_errno("strdup");
3669 goto done;
3673 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3674 if (error != NULL)
3675 goto done;
3677 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3678 repo, worktree);
3679 if (error)
3680 goto done;
3682 init_curses();
3684 error = apply_unveil(got_repo_get_path(repo),
3685 worktree ? got_worktree_get_root_path(worktree) : NULL);
3686 if (error)
3687 goto done;
3689 /* already loaded by tog_log_with_path()? */
3690 if (TAILQ_EMPTY(&tog_refs)) {
3691 error = tog_load_refs(repo, 0);
3692 if (error)
3693 goto done;
3696 if (start_commit == NULL) {
3697 error = got_repo_match_object_id(&start_id, &label,
3698 worktree ? got_worktree_get_head_ref_name(worktree) :
3699 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3700 if (error)
3701 goto done;
3702 head_ref_name = label;
3703 } else {
3704 error = got_ref_open(&ref, repo, start_commit, 0);
3705 if (error == NULL)
3706 head_ref_name = got_ref_get_name(ref);
3707 else if (error->code != GOT_ERR_NOT_REF)
3708 goto done;
3709 error = got_repo_match_object_id(&start_id, NULL,
3710 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3711 if (error)
3712 goto done;
3715 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3716 if (view == NULL) {
3717 error = got_error_from_errno("view_open");
3718 goto done;
3720 error = open_log_view(view, start_id, repo, head_ref_name,
3721 in_repo_path, log_branches);
3722 if (error)
3723 goto done;
3724 if (worktree) {
3725 /* Release work tree lock. */
3726 got_worktree_close(worktree);
3727 worktree = NULL;
3729 error = view_loop(view);
3730 done:
3731 free(in_repo_path);
3732 free(repo_path);
3733 free(cwd);
3734 free(start_id);
3735 free(label);
3736 if (ref)
3737 got_ref_close(ref);
3738 if (repo) {
3739 const struct got_error *close_err = got_repo_close(repo);
3740 if (error == NULL)
3741 error = close_err;
3743 if (worktree)
3744 got_worktree_close(worktree);
3745 if (pack_fds) {
3746 const struct got_error *pack_err =
3747 got_repo_pack_fds_close(pack_fds);
3748 if (error == NULL)
3749 error = pack_err;
3751 tog_free_refs();
3752 return error;
3755 __dead static void
3756 usage_diff(void)
3758 endwin();
3759 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
3760 "object1 object2\n", getprogname());
3761 exit(1);
3764 static int
3765 match_line(const char *line, regex_t *regex, size_t nmatch,
3766 regmatch_t *regmatch)
3768 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3771 static struct tog_color *
3772 match_color(struct tog_colors *colors, const char *line)
3774 struct tog_color *tc = NULL;
3776 STAILQ_FOREACH(tc, colors, entry) {
3777 if (match_line(line, &tc->regex, 0, NULL))
3778 return tc;
3781 return NULL;
3784 static const struct got_error *
3785 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3786 WINDOW *window, int skipcol, regmatch_t *regmatch)
3788 const struct got_error *err = NULL;
3789 char *exstr = NULL;
3790 wchar_t *wline = NULL;
3791 int rme, rms, n, width, scrollx;
3792 int width0 = 0, width1 = 0, width2 = 0;
3793 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3795 *wtotal = 0;
3797 rms = regmatch->rm_so;
3798 rme = regmatch->rm_eo;
3800 err = expand_tab(&exstr, line);
3801 if (err)
3802 return err;
3804 /* Split the line into 3 segments, according to match offsets. */
3805 seg0 = strndup(exstr, rms);
3806 if (seg0 == NULL) {
3807 err = got_error_from_errno("strndup");
3808 goto done;
3810 seg1 = strndup(exstr + rms, rme - rms);
3811 if (seg1 == NULL) {
3812 err = got_error_from_errno("strndup");
3813 goto done;
3815 seg2 = strdup(exstr + rme);
3816 if (seg2 == NULL) {
3817 err = got_error_from_errno("strndup");
3818 goto done;
3821 /* draw up to matched token if we haven't scrolled past it */
3822 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3823 col_tab_align, 1);
3824 if (err)
3825 goto done;
3826 n = MAX(width0 - skipcol, 0);
3827 if (n) {
3828 free(wline);
3829 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3830 wlimit, col_tab_align, 1);
3831 if (err)
3832 goto done;
3833 waddwstr(window, &wline[scrollx]);
3834 wlimit -= width;
3835 *wtotal += width;
3838 if (wlimit > 0) {
3839 int i = 0, w = 0;
3840 size_t wlen;
3842 free(wline);
3843 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3844 col_tab_align, 1);
3845 if (err)
3846 goto done;
3847 wlen = wcslen(wline);
3848 while (i < wlen) {
3849 width = wcwidth(wline[i]);
3850 if (width == -1) {
3851 /* should not happen, tabs are expanded */
3852 err = got_error(GOT_ERR_RANGE);
3853 goto done;
3855 if (width0 + w + width > skipcol)
3856 break;
3857 w += width;
3858 i++;
3860 /* draw (visible part of) matched token (if scrolled into it) */
3861 if (width1 - w > 0) {
3862 wattron(window, A_STANDOUT);
3863 waddwstr(window, &wline[i]);
3864 wattroff(window, A_STANDOUT);
3865 wlimit -= (width1 - w);
3866 *wtotal += (width1 - w);
3870 if (wlimit > 0) { /* draw rest of line */
3871 free(wline);
3872 if (skipcol > width0 + width1) {
3873 err = format_line(&wline, &width2, &scrollx, seg2,
3874 skipcol - (width0 + width1), wlimit,
3875 col_tab_align, 1);
3876 if (err)
3877 goto done;
3878 waddwstr(window, &wline[scrollx]);
3879 } else {
3880 err = format_line(&wline, &width2, NULL, seg2, 0,
3881 wlimit, col_tab_align, 1);
3882 if (err)
3883 goto done;
3884 waddwstr(window, wline);
3886 *wtotal += width2;
3888 done:
3889 free(wline);
3890 free(exstr);
3891 free(seg0);
3892 free(seg1);
3893 free(seg2);
3894 return err;
3897 static int
3898 gotoline(struct tog_view *view, int *lineno, int *nprinted)
3900 FILE *f = NULL;
3901 int *eof, *first, *selected;
3903 if (view->type == TOG_VIEW_DIFF) {
3904 struct tog_diff_view_state *s = &view->state.diff;
3906 first = &s->first_displayed_line;
3907 selected = first;
3908 eof = &s->eof;
3909 f = s->f;
3910 } else if (view->type == TOG_VIEW_BLAME) {
3911 struct tog_blame_view_state *s = &view->state.blame;
3913 first = &s->first_displayed_line;
3914 selected = &s->selected_line;
3915 eof = &s->eof;
3916 f = s->blame.f;
3917 } else
3918 return 0;
3920 /* Center gline in the middle of the page like vi(1). */
3921 if (*lineno < view->gline - (view->nlines - 3) / 2)
3922 return 0;
3923 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
3924 rewind(f);
3925 *eof = 0;
3926 *first = 1;
3927 *lineno = 0;
3928 *nprinted = 0;
3929 return 0;
3932 *selected = view->gline <= (view->nlines - 3) / 2 ?
3933 view->gline : (view->nlines - 3) / 2 + 1;
3934 view->gline = 0;
3936 return 1;
3939 static const struct got_error *
3940 draw_file(struct tog_view *view, const char *header)
3942 struct tog_diff_view_state *s = &view->state.diff;
3943 regmatch_t *regmatch = &view->regmatch;
3944 const struct got_error *err;
3945 int nprinted = 0;
3946 char *line;
3947 size_t linesize = 0;
3948 ssize_t linelen;
3949 wchar_t *wline;
3950 int width;
3951 int max_lines = view->nlines;
3952 int nlines = s->nlines;
3953 off_t line_offset;
3955 s->lineno = s->first_displayed_line - 1;
3956 line_offset = s->lines[s->first_displayed_line - 1].offset;
3957 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3958 return got_error_from_errno("fseek");
3960 werase(view->window);
3962 if (view->gline > s->nlines - 1)
3963 view->gline = s->nlines - 1;
3965 if (header) {
3966 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
3967 1 : view->gline - (view->nlines - 3) / 2 :
3968 s->lineno + s->selected_line;
3970 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
3971 return got_error_from_errno("asprintf");
3972 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3973 0, 0);
3974 free(line);
3975 if (err)
3976 return err;
3978 if (view_needs_focus_indication(view))
3979 wstandout(view->window);
3980 waddwstr(view->window, wline);
3981 free(wline);
3982 wline = NULL;
3983 while (width++ < view->ncols)
3984 waddch(view->window, ' ');
3985 if (view_needs_focus_indication(view))
3986 wstandend(view->window);
3988 if (max_lines <= 1)
3989 return NULL;
3990 max_lines--;
3993 s->eof = 0;
3994 view->maxx = 0;
3995 line = NULL;
3996 while (max_lines > 0 && nprinted < max_lines) {
3997 enum got_diff_line_type linetype;
3998 attr_t attr = 0;
4000 linelen = getline(&line, &linesize, s->f);
4001 if (linelen == -1) {
4002 if (feof(s->f)) {
4003 s->eof = 1;
4004 break;
4006 free(line);
4007 return got_ferror(s->f, GOT_ERR_IO);
4010 if (++s->lineno < s->first_displayed_line)
4011 continue;
4012 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4013 continue;
4014 if (s->lineno == view->hiline)
4015 attr = A_STANDOUT;
4017 /* Set view->maxx based on full line length. */
4018 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4019 view->x ? 1 : 0);
4020 if (err) {
4021 free(line);
4022 return err;
4024 view->maxx = MAX(view->maxx, width);
4025 free(wline);
4026 wline = NULL;
4028 linetype = s->lines[s->lineno].type;
4029 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4030 linetype < GOT_DIFF_LINE_CONTEXT)
4031 attr |= COLOR_PAIR(linetype);
4032 if (attr)
4033 wattron(view->window, attr);
4034 if (s->first_displayed_line + nprinted == s->matched_line &&
4035 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4036 err = add_matched_line(&width, line, view->ncols, 0,
4037 view->window, view->x, regmatch);
4038 if (err) {
4039 free(line);
4040 return err;
4042 } else {
4043 int skip;
4044 err = format_line(&wline, &width, &skip, line,
4045 view->x, view->ncols, 0, view->x ? 1 : 0);
4046 if (err) {
4047 free(line);
4048 return err;
4050 waddwstr(view->window, &wline[skip]);
4051 free(wline);
4052 wline = NULL;
4054 if (s->lineno == view->hiline) {
4055 /* highlight full gline length */
4056 while (width++ < view->ncols)
4057 waddch(view->window, ' ');
4058 } else {
4059 if (width <= view->ncols - 1)
4060 waddch(view->window, '\n');
4062 if (attr)
4063 wattroff(view->window, attr);
4064 if (++nprinted == 1)
4065 s->first_displayed_line = s->lineno;
4067 free(line);
4068 if (nprinted >= 1)
4069 s->last_displayed_line = s->first_displayed_line +
4070 (nprinted - 1);
4071 else
4072 s->last_displayed_line = s->first_displayed_line;
4074 view_border(view);
4076 if (s->eof) {
4077 while (nprinted < view->nlines) {
4078 waddch(view->window, '\n');
4079 nprinted++;
4082 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4083 view->ncols, 0, 0);
4084 if (err) {
4085 return err;
4088 wstandout(view->window);
4089 waddwstr(view->window, wline);
4090 free(wline);
4091 wline = NULL;
4092 wstandend(view->window);
4095 return NULL;
4098 static char *
4099 get_datestr(time_t *time, char *datebuf)
4101 struct tm mytm, *tm;
4102 char *p, *s;
4104 tm = gmtime_r(time, &mytm);
4105 if (tm == NULL)
4106 return NULL;
4107 s = asctime_r(tm, datebuf);
4108 if (s == NULL)
4109 return NULL;
4110 p = strchr(s, '\n');
4111 if (p)
4112 *p = '\0';
4113 return s;
4116 static const struct got_error *
4117 get_changed_paths(struct got_pathlist_head *paths,
4118 struct got_commit_object *commit, struct got_repository *repo)
4120 const struct got_error *err = NULL;
4121 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4122 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4123 struct got_object_qid *qid;
4125 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4126 if (qid != NULL) {
4127 struct got_commit_object *pcommit;
4128 err = got_object_open_as_commit(&pcommit, repo,
4129 &qid->id);
4130 if (err)
4131 return err;
4133 tree_id1 = got_object_id_dup(
4134 got_object_commit_get_tree_id(pcommit));
4135 if (tree_id1 == NULL) {
4136 got_object_commit_close(pcommit);
4137 return got_error_from_errno("got_object_id_dup");
4139 got_object_commit_close(pcommit);
4143 if (tree_id1) {
4144 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4145 if (err)
4146 goto done;
4149 tree_id2 = got_object_commit_get_tree_id(commit);
4150 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4151 if (err)
4152 goto done;
4154 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4155 got_diff_tree_collect_changed_paths, paths, 0);
4156 done:
4157 if (tree1)
4158 got_object_tree_close(tree1);
4159 if (tree2)
4160 got_object_tree_close(tree2);
4161 free(tree_id1);
4162 return err;
4165 static const struct got_error *
4166 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4167 off_t off, uint8_t type)
4169 struct got_diff_line *p;
4171 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4172 if (p == NULL)
4173 return got_error_from_errno("reallocarray");
4174 *lines = p;
4175 (*lines)[*nlines].offset = off;
4176 (*lines)[*nlines].type = type;
4177 (*nlines)++;
4179 return NULL;
4182 static const struct got_error *
4183 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4184 struct got_object_id *commit_id, struct got_reflist_head *refs,
4185 struct got_repository *repo, FILE *outfile)
4187 const struct got_error *err = NULL;
4188 char datebuf[26], *datestr;
4189 struct got_commit_object *commit;
4190 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4191 time_t committer_time;
4192 const char *author, *committer;
4193 char *refs_str = NULL;
4194 struct got_pathlist_head changed_paths;
4195 struct got_pathlist_entry *pe;
4196 off_t outoff = 0;
4197 int n;
4199 TAILQ_INIT(&changed_paths);
4201 if (refs) {
4202 err = build_refs_str(&refs_str, refs, commit_id, repo);
4203 if (err)
4204 return err;
4207 err = got_object_open_as_commit(&commit, repo, commit_id);
4208 if (err)
4209 return err;
4211 err = got_object_id_str(&id_str, commit_id);
4212 if (err) {
4213 err = got_error_from_errno("got_object_id_str");
4214 goto done;
4217 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4218 if (err)
4219 goto done;
4221 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4222 refs_str ? refs_str : "", refs_str ? ")" : "");
4223 if (n < 0) {
4224 err = got_error_from_errno("fprintf");
4225 goto done;
4227 outoff += n;
4228 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4229 if (err)
4230 goto done;
4232 n = fprintf(outfile, "from: %s\n",
4233 got_object_commit_get_author(commit));
4234 if (n < 0) {
4235 err = got_error_from_errno("fprintf");
4236 goto done;
4238 outoff += n;
4239 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4240 if (err)
4241 goto done;
4243 committer_time = got_object_commit_get_committer_time(commit);
4244 datestr = get_datestr(&committer_time, datebuf);
4245 if (datestr) {
4246 n = fprintf(outfile, "date: %s UTC\n", datestr);
4247 if (n < 0) {
4248 err = got_error_from_errno("fprintf");
4249 goto done;
4251 outoff += n;
4252 err = add_line_metadata(lines, nlines, outoff,
4253 GOT_DIFF_LINE_DATE);
4254 if (err)
4255 goto done;
4257 author = got_object_commit_get_author(commit);
4258 committer = got_object_commit_get_committer(commit);
4259 if (strcmp(author, committer) != 0) {
4260 n = fprintf(outfile, "via: %s\n", committer);
4261 if (n < 0) {
4262 err = got_error_from_errno("fprintf");
4263 goto done;
4265 outoff += n;
4266 err = add_line_metadata(lines, nlines, outoff,
4267 GOT_DIFF_LINE_AUTHOR);
4268 if (err)
4269 goto done;
4271 if (got_object_commit_get_nparents(commit) > 1) {
4272 const struct got_object_id_queue *parent_ids;
4273 struct got_object_qid *qid;
4274 int pn = 1;
4275 parent_ids = got_object_commit_get_parent_ids(commit);
4276 STAILQ_FOREACH(qid, parent_ids, entry) {
4277 err = got_object_id_str(&id_str, &qid->id);
4278 if (err)
4279 goto done;
4280 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4281 if (n < 0) {
4282 err = got_error_from_errno("fprintf");
4283 goto done;
4285 outoff += n;
4286 err = add_line_metadata(lines, nlines, outoff,
4287 GOT_DIFF_LINE_META);
4288 if (err)
4289 goto done;
4290 free(id_str);
4291 id_str = NULL;
4295 err = got_object_commit_get_logmsg(&logmsg, commit);
4296 if (err)
4297 goto done;
4298 s = logmsg;
4299 while ((line = strsep(&s, "\n")) != NULL) {
4300 n = fprintf(outfile, "%s\n", line);
4301 if (n < 0) {
4302 err = got_error_from_errno("fprintf");
4303 goto done;
4305 outoff += n;
4306 err = add_line_metadata(lines, nlines, outoff,
4307 GOT_DIFF_LINE_LOGMSG);
4308 if (err)
4309 goto done;
4312 err = get_changed_paths(&changed_paths, commit, repo);
4313 if (err)
4314 goto done;
4315 TAILQ_FOREACH(pe, &changed_paths, entry) {
4316 struct got_diff_changed_path *cp = pe->data;
4317 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4318 if (n < 0) {
4319 err = got_error_from_errno("fprintf");
4320 goto done;
4322 outoff += n;
4323 err = add_line_metadata(lines, nlines, outoff,
4324 GOT_DIFF_LINE_CHANGES);
4325 if (err)
4326 goto done;
4327 free((char *)pe->path);
4328 free(pe->data);
4331 fputc('\n', outfile);
4332 outoff++;
4333 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4334 done:
4335 got_pathlist_free(&changed_paths);
4336 free(id_str);
4337 free(logmsg);
4338 free(refs_str);
4339 got_object_commit_close(commit);
4340 if (err) {
4341 free(*lines);
4342 *lines = NULL;
4343 *nlines = 0;
4345 return err;
4348 static const struct got_error *
4349 create_diff(struct tog_diff_view_state *s)
4351 const struct got_error *err = NULL;
4352 FILE *f = NULL;
4353 int obj_type;
4355 free(s->lines);
4356 s->lines = malloc(sizeof(*s->lines));
4357 if (s->lines == NULL)
4358 return got_error_from_errno("malloc");
4359 s->nlines = 0;
4361 f = got_opentemp();
4362 if (f == NULL) {
4363 err = got_error_from_errno("got_opentemp");
4364 goto done;
4366 if (s->f && fclose(s->f) == EOF) {
4367 err = got_error_from_errno("fclose");
4368 goto done;
4370 s->f = f;
4372 if (s->id1)
4373 err = got_object_get_type(&obj_type, s->repo, s->id1);
4374 else
4375 err = got_object_get_type(&obj_type, s->repo, s->id2);
4376 if (err)
4377 goto done;
4379 switch (obj_type) {
4380 case GOT_OBJ_TYPE_BLOB:
4381 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4382 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4383 s->label1, s->label2, tog_diff_algo, s->diff_context,
4384 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4385 break;
4386 case GOT_OBJ_TYPE_TREE:
4387 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4388 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4389 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4390 s->force_text_diff, s->repo, s->f);
4391 break;
4392 case GOT_OBJ_TYPE_COMMIT: {
4393 const struct got_object_id_queue *parent_ids;
4394 struct got_object_qid *pid;
4395 struct got_commit_object *commit2;
4396 struct got_reflist_head *refs;
4398 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4399 if (err)
4400 goto done;
4401 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4402 /* Show commit info if we're diffing to a parent/root commit. */
4403 if (s->id1 == NULL) {
4404 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4405 refs, s->repo, s->f);
4406 if (err)
4407 goto done;
4408 } else {
4409 parent_ids = got_object_commit_get_parent_ids(commit2);
4410 STAILQ_FOREACH(pid, parent_ids, entry) {
4411 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4412 err = write_commit_info(&s->lines,
4413 &s->nlines, s->id2, refs, s->repo,
4414 s->f);
4415 if (err)
4416 goto done;
4417 break;
4421 got_object_commit_close(commit2);
4423 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4424 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4425 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4426 s->force_text_diff, s->repo, s->f);
4427 break;
4429 default:
4430 err = got_error(GOT_ERR_OBJ_TYPE);
4431 break;
4433 done:
4434 if (s->f && fflush(s->f) != 0 && err == NULL)
4435 err = got_error_from_errno("fflush");
4436 return err;
4439 static void
4440 diff_view_indicate_progress(struct tog_view *view)
4442 mvwaddstr(view->window, 0, 0, "diffing...");
4443 update_panels();
4444 doupdate();
4447 static const struct got_error *
4448 search_start_diff_view(struct tog_view *view)
4450 struct tog_diff_view_state *s = &view->state.diff;
4452 s->matched_line = 0;
4453 return NULL;
4456 static const struct got_error *
4457 search_next_diff_view(struct tog_view *view)
4459 struct tog_diff_view_state *s = &view->state.diff;
4460 const struct got_error *err = NULL;
4461 int lineno;
4462 char *line = NULL;
4463 size_t linesize = 0;
4464 ssize_t linelen;
4466 if (!view->searching) {
4467 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4468 return NULL;
4471 if (s->matched_line) {
4472 if (view->searching == TOG_SEARCH_FORWARD)
4473 lineno = s->matched_line + 1;
4474 else
4475 lineno = s->matched_line - 1;
4476 } else
4477 lineno = s->first_displayed_line;
4479 while (1) {
4480 off_t offset;
4482 if (lineno <= 0 || lineno > s->nlines) {
4483 if (s->matched_line == 0) {
4484 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4485 break;
4488 if (view->searching == TOG_SEARCH_FORWARD)
4489 lineno = 1;
4490 else
4491 lineno = s->nlines;
4494 offset = s->lines[lineno - 1].offset;
4495 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4496 free(line);
4497 return got_error_from_errno("fseeko");
4499 linelen = getline(&line, &linesize, s->f);
4500 if (linelen != -1) {
4501 char *exstr;
4502 err = expand_tab(&exstr, line);
4503 if (err)
4504 break;
4505 if (match_line(exstr, &view->regex, 1,
4506 &view->regmatch)) {
4507 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4508 s->matched_line = lineno;
4509 free(exstr);
4510 break;
4512 free(exstr);
4514 if (view->searching == TOG_SEARCH_FORWARD)
4515 lineno++;
4516 else
4517 lineno--;
4519 free(line);
4521 if (s->matched_line) {
4522 s->first_displayed_line = s->matched_line;
4523 s->selected_line = 1;
4526 return err;
4529 static const struct got_error *
4530 close_diff_view(struct tog_view *view)
4532 const struct got_error *err = NULL;
4533 struct tog_diff_view_state *s = &view->state.diff;
4535 free(s->id1);
4536 s->id1 = NULL;
4537 free(s->id2);
4538 s->id2 = NULL;
4539 if (s->f && fclose(s->f) == EOF)
4540 err = got_error_from_errno("fclose");
4541 s->f = NULL;
4542 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4543 err = got_error_from_errno("fclose");
4544 s->f1 = NULL;
4545 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4546 err = got_error_from_errno("fclose");
4547 s->f2 = NULL;
4548 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4549 err = got_error_from_errno("close");
4550 s->fd1 = -1;
4551 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4552 err = got_error_from_errno("close");
4553 s->fd2 = -1;
4554 free(s->lines);
4555 s->lines = NULL;
4556 s->nlines = 0;
4557 return err;
4560 static const struct got_error *
4561 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4562 struct got_object_id *id2, const char *label1, const char *label2,
4563 int diff_context, int ignore_whitespace, int force_text_diff,
4564 struct tog_view *parent_view, struct got_repository *repo)
4566 const struct got_error *err;
4567 struct tog_diff_view_state *s = &view->state.diff;
4569 memset(s, 0, sizeof(*s));
4570 s->fd1 = -1;
4571 s->fd2 = -1;
4573 if (id1 != NULL && id2 != NULL) {
4574 int type1, type2;
4575 err = got_object_get_type(&type1, repo, id1);
4576 if (err)
4577 return err;
4578 err = got_object_get_type(&type2, repo, id2);
4579 if (err)
4580 return err;
4582 if (type1 != type2)
4583 return got_error(GOT_ERR_OBJ_TYPE);
4585 s->first_displayed_line = 1;
4586 s->last_displayed_line = view->nlines;
4587 s->selected_line = 1;
4588 s->repo = repo;
4589 s->id1 = id1;
4590 s->id2 = id2;
4591 s->label1 = label1;
4592 s->label2 = label2;
4594 if (id1) {
4595 s->id1 = got_object_id_dup(id1);
4596 if (s->id1 == NULL)
4597 return got_error_from_errno("got_object_id_dup");
4598 } else
4599 s->id1 = NULL;
4601 s->id2 = got_object_id_dup(id2);
4602 if (s->id2 == NULL) {
4603 err = got_error_from_errno("got_object_id_dup");
4604 goto done;
4607 s->f1 = got_opentemp();
4608 if (s->f1 == NULL) {
4609 err = got_error_from_errno("got_opentemp");
4610 goto done;
4613 s->f2 = got_opentemp();
4614 if (s->f2 == NULL) {
4615 err = got_error_from_errno("got_opentemp");
4616 goto done;
4619 s->fd1 = got_opentempfd();
4620 if (s->fd1 == -1) {
4621 err = got_error_from_errno("got_opentempfd");
4622 goto done;
4625 s->fd2 = got_opentempfd();
4626 if (s->fd2 == -1) {
4627 err = got_error_from_errno("got_opentempfd");
4628 goto done;
4631 s->first_displayed_line = 1;
4632 s->last_displayed_line = view->nlines;
4633 s->diff_context = diff_context;
4634 s->ignore_whitespace = ignore_whitespace;
4635 s->force_text_diff = force_text_diff;
4636 s->parent_view = parent_view;
4637 s->repo = repo;
4639 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4640 int rc;
4642 rc = init_pair(GOT_DIFF_LINE_MINUS,
4643 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
4644 if (rc != ERR)
4645 rc = init_pair(GOT_DIFF_LINE_PLUS,
4646 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
4647 if (rc != ERR)
4648 rc = init_pair(GOT_DIFF_LINE_HUNK,
4649 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
4650 if (rc != ERR)
4651 rc = init_pair(GOT_DIFF_LINE_META,
4652 get_color_value("TOG_COLOR_DIFF_META"), -1);
4653 if (rc != ERR)
4654 rc = init_pair(GOT_DIFF_LINE_CHANGES,
4655 get_color_value("TOG_COLOR_DIFF_META"), -1);
4656 if (rc != ERR)
4657 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
4658 get_color_value("TOG_COLOR_DIFF_META"), -1);
4659 if (rc != ERR)
4660 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
4661 get_color_value("TOG_COLOR_DIFF_META"), -1);
4662 if (rc != ERR)
4663 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
4664 get_color_value("TOG_COLOR_AUTHOR"), -1);
4665 if (rc != ERR)
4666 rc = init_pair(GOT_DIFF_LINE_DATE,
4667 get_color_value("TOG_COLOR_DATE"), -1);
4668 if (rc == ERR) {
4669 err = got_error(GOT_ERR_RANGE);
4670 goto done;
4674 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4675 view_is_splitscreen(view))
4676 show_log_view(parent_view); /* draw border */
4677 diff_view_indicate_progress(view);
4679 err = create_diff(s);
4681 view->show = show_diff_view;
4682 view->input = input_diff_view;
4683 view->reset = reset_diff_view;
4684 view->close = close_diff_view;
4685 view->search_start = search_start_diff_view;
4686 view->search_next = search_next_diff_view;
4687 done:
4688 if (err)
4689 close_diff_view(view);
4690 return err;
4693 static const struct got_error *
4694 show_diff_view(struct tog_view *view)
4696 const struct got_error *err;
4697 struct tog_diff_view_state *s = &view->state.diff;
4698 char *id_str1 = NULL, *id_str2, *header;
4699 const char *label1, *label2;
4701 if (s->id1) {
4702 err = got_object_id_str(&id_str1, s->id1);
4703 if (err)
4704 return err;
4705 label1 = s->label1 ? s->label1 : id_str1;
4706 } else
4707 label1 = "/dev/null";
4709 err = got_object_id_str(&id_str2, s->id2);
4710 if (err)
4711 return err;
4712 label2 = s->label2 ? s->label2 : id_str2;
4714 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4715 err = got_error_from_errno("asprintf");
4716 free(id_str1);
4717 free(id_str2);
4718 return err;
4720 free(id_str1);
4721 free(id_str2);
4723 err = draw_file(view, header);
4724 free(header);
4725 return err;
4728 static const struct got_error *
4729 set_selected_commit(struct tog_diff_view_state *s,
4730 struct commit_queue_entry *entry)
4732 const struct got_error *err;
4733 const struct got_object_id_queue *parent_ids;
4734 struct got_commit_object *selected_commit;
4735 struct got_object_qid *pid;
4737 free(s->id2);
4738 s->id2 = got_object_id_dup(entry->id);
4739 if (s->id2 == NULL)
4740 return got_error_from_errno("got_object_id_dup");
4742 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4743 if (err)
4744 return err;
4745 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4746 free(s->id1);
4747 pid = STAILQ_FIRST(parent_ids);
4748 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4749 got_object_commit_close(selected_commit);
4750 return NULL;
4753 static const struct got_error *
4754 reset_diff_view(struct tog_view *view)
4756 struct tog_diff_view_state *s = &view->state.diff;
4758 view->count = 0;
4759 wclear(view->window);
4760 s->first_displayed_line = 1;
4761 s->last_displayed_line = view->nlines;
4762 s->matched_line = 0;
4763 diff_view_indicate_progress(view);
4764 return create_diff(s);
4767 static void
4768 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4770 int start, i;
4772 i = start = s->first_displayed_line - 1;
4774 while (s->lines[i].type != type) {
4775 if (i == 0)
4776 i = s->nlines - 1;
4777 if (--i == start)
4778 return; /* do nothing, requested type not in file */
4781 s->selected_line = 1;
4782 s->first_displayed_line = i;
4785 static void
4786 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4788 int start, i;
4790 i = start = s->first_displayed_line + 1;
4792 while (s->lines[i].type != type) {
4793 if (i == s->nlines - 1)
4794 i = 0;
4795 if (++i == start)
4796 return; /* do nothing, requested type not in file */
4799 s->selected_line = 1;
4800 s->first_displayed_line = i;
4803 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4804 int, int, int);
4805 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4806 int, int);
4808 static const struct got_error *
4809 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4811 const struct got_error *err = NULL;
4812 struct tog_diff_view_state *s = &view->state.diff;
4813 struct tog_log_view_state *ls;
4814 struct commit_queue_entry *old_selected_entry;
4815 char *line = NULL;
4816 size_t linesize = 0;
4817 ssize_t linelen;
4818 int i, nscroll = view->nlines - 1, up = 0;
4820 s->lineno = s->first_displayed_line - 1 + s->selected_line;
4822 switch (ch) {
4823 case '0':
4824 view->x = 0;
4825 break;
4826 case '$':
4827 view->x = MAX(view->maxx - view->ncols / 3, 0);
4828 view->count = 0;
4829 break;
4830 case KEY_RIGHT:
4831 case 'l':
4832 if (view->x + view->ncols / 3 < view->maxx)
4833 view->x += 2; /* move two columns right */
4834 else
4835 view->count = 0;
4836 break;
4837 case KEY_LEFT:
4838 case 'h':
4839 view->x -= MIN(view->x, 2); /* move two columns back */
4840 if (view->x <= 0)
4841 view->count = 0;
4842 break;
4843 case 'a':
4844 case 'w':
4845 if (ch == 'a')
4846 s->force_text_diff = !s->force_text_diff;
4847 if (ch == 'w')
4848 s->ignore_whitespace = !s->ignore_whitespace;
4849 err = reset_diff_view(view);
4850 break;
4851 case 'g':
4852 case KEY_HOME:
4853 s->first_displayed_line = 1;
4854 view->count = 0;
4855 break;
4856 case 'G':
4857 case KEY_END:
4858 view->count = 0;
4859 if (s->eof)
4860 break;
4862 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4863 s->eof = 1;
4864 break;
4865 case 'k':
4866 case KEY_UP:
4867 case CTRL('p'):
4868 if (s->first_displayed_line > 1)
4869 s->first_displayed_line--;
4870 else
4871 view->count = 0;
4872 break;
4873 case CTRL('u'):
4874 case 'u':
4875 nscroll /= 2;
4876 /* FALL THROUGH */
4877 case KEY_PPAGE:
4878 case CTRL('b'):
4879 case 'b':
4880 if (s->first_displayed_line == 1) {
4881 view->count = 0;
4882 break;
4884 i = 0;
4885 while (i++ < nscroll && s->first_displayed_line > 1)
4886 s->first_displayed_line--;
4887 break;
4888 case 'j':
4889 case KEY_DOWN:
4890 case CTRL('n'):
4891 if (!s->eof)
4892 s->first_displayed_line++;
4893 else
4894 view->count = 0;
4895 break;
4896 case CTRL('d'):
4897 case 'd':
4898 nscroll /= 2;
4899 /* FALL THROUGH */
4900 case KEY_NPAGE:
4901 case CTRL('f'):
4902 case 'f':
4903 case ' ':
4904 if (s->eof) {
4905 view->count = 0;
4906 break;
4908 i = 0;
4909 while (!s->eof && i++ < nscroll) {
4910 linelen = getline(&line, &linesize, s->f);
4911 s->first_displayed_line++;
4912 if (linelen == -1) {
4913 if (feof(s->f)) {
4914 s->eof = 1;
4915 } else
4916 err = got_ferror(s->f, GOT_ERR_IO);
4917 break;
4920 free(line);
4921 break;
4922 case '(':
4923 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
4924 break;
4925 case ')':
4926 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
4927 break;
4928 case '{':
4929 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
4930 break;
4931 case '}':
4932 diff_next_index(s, GOT_DIFF_LINE_HUNK);
4933 break;
4934 case '[':
4935 if (s->diff_context > 0) {
4936 s->diff_context--;
4937 s->matched_line = 0;
4938 diff_view_indicate_progress(view);
4939 err = create_diff(s);
4940 if (s->first_displayed_line + view->nlines - 1 >
4941 s->nlines) {
4942 s->first_displayed_line = 1;
4943 s->last_displayed_line = view->nlines;
4945 } else
4946 view->count = 0;
4947 break;
4948 case ']':
4949 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4950 s->diff_context++;
4951 s->matched_line = 0;
4952 diff_view_indicate_progress(view);
4953 err = create_diff(s);
4954 } else
4955 view->count = 0;
4956 break;
4957 case '<':
4958 case ',':
4959 case 'K':
4960 up = 1;
4961 /* FALL THROUGH */
4962 case '>':
4963 case '.':
4964 case 'J':
4965 if (s->parent_view == NULL) {
4966 view->count = 0;
4967 break;
4969 s->parent_view->count = view->count;
4971 if (s->parent_view->type == TOG_VIEW_LOG) {
4972 ls = &s->parent_view->state.log;
4973 old_selected_entry = ls->selected_entry;
4975 err = input_log_view(NULL, s->parent_view,
4976 up ? KEY_UP : KEY_DOWN);
4977 if (err)
4978 break;
4979 view->count = s->parent_view->count;
4981 if (old_selected_entry == ls->selected_entry)
4982 break;
4984 err = set_selected_commit(s, ls->selected_entry);
4985 if (err)
4986 break;
4987 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4988 struct tog_blame_view_state *bs;
4989 struct got_object_id *id, *prev_id;
4991 bs = &s->parent_view->state.blame;
4992 prev_id = get_annotation_for_line(bs->blame.lines,
4993 bs->blame.nlines, bs->last_diffed_line);
4995 err = input_blame_view(&view, s->parent_view,
4996 up ? KEY_UP : KEY_DOWN);
4997 if (err)
4998 break;
4999 view->count = s->parent_view->count;
5001 if (prev_id == NULL)
5002 break;
5003 id = get_selected_commit_id(bs->blame.lines,
5004 bs->blame.nlines, bs->first_displayed_line,
5005 bs->selected_line);
5006 if (id == NULL)
5007 break;
5009 if (!got_object_id_cmp(prev_id, id))
5010 break;
5012 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5013 if (err)
5014 break;
5016 s->first_displayed_line = 1;
5017 s->last_displayed_line = view->nlines;
5018 s->matched_line = 0;
5019 view->x = 0;
5021 diff_view_indicate_progress(view);
5022 err = create_diff(s);
5023 break;
5024 default:
5025 view->count = 0;
5026 break;
5029 return err;
5032 static const struct got_error *
5033 cmd_diff(int argc, char *argv[])
5035 const struct got_error *error = NULL;
5036 struct got_repository *repo = NULL;
5037 struct got_worktree *worktree = NULL;
5038 struct got_object_id *id1 = NULL, *id2 = NULL;
5039 char *repo_path = NULL, *cwd = NULL;
5040 char *id_str1 = NULL, *id_str2 = NULL;
5041 char *label1 = NULL, *label2 = NULL;
5042 int diff_context = 3, ignore_whitespace = 0;
5043 int ch, force_text_diff = 0;
5044 const char *errstr;
5045 struct tog_view *view;
5046 int *pack_fds = NULL;
5048 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5049 switch (ch) {
5050 case 'a':
5051 force_text_diff = 1;
5052 break;
5053 case 'C':
5054 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5055 &errstr);
5056 if (errstr != NULL)
5057 errx(1, "number of context lines is %s: %s",
5058 errstr, errstr);
5059 break;
5060 case 'r':
5061 repo_path = realpath(optarg, NULL);
5062 if (repo_path == NULL)
5063 return got_error_from_errno2("realpath",
5064 optarg);
5065 got_path_strip_trailing_slashes(repo_path);
5066 break;
5067 case 'w':
5068 ignore_whitespace = 1;
5069 break;
5070 default:
5071 usage_diff();
5072 /* NOTREACHED */
5076 argc -= optind;
5077 argv += optind;
5079 if (argc == 0) {
5080 usage_diff(); /* TODO show local worktree changes */
5081 } else if (argc == 2) {
5082 id_str1 = argv[0];
5083 id_str2 = argv[1];
5084 } else
5085 usage_diff();
5087 error = got_repo_pack_fds_open(&pack_fds);
5088 if (error)
5089 goto done;
5091 if (repo_path == NULL) {
5092 cwd = getcwd(NULL, 0);
5093 if (cwd == NULL)
5094 return got_error_from_errno("getcwd");
5095 error = got_worktree_open(&worktree, cwd);
5096 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5097 goto done;
5098 if (worktree)
5099 repo_path =
5100 strdup(got_worktree_get_repo_path(worktree));
5101 else
5102 repo_path = strdup(cwd);
5103 if (repo_path == NULL) {
5104 error = got_error_from_errno("strdup");
5105 goto done;
5109 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5110 if (error)
5111 goto done;
5113 init_curses();
5115 error = apply_unveil(got_repo_get_path(repo), NULL);
5116 if (error)
5117 goto done;
5119 error = tog_load_refs(repo, 0);
5120 if (error)
5121 goto done;
5123 error = got_repo_match_object_id(&id1, &label1, id_str1,
5124 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5125 if (error)
5126 goto done;
5128 error = got_repo_match_object_id(&id2, &label2, id_str2,
5129 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5130 if (error)
5131 goto done;
5133 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5134 if (view == NULL) {
5135 error = got_error_from_errno("view_open");
5136 goto done;
5138 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5139 ignore_whitespace, force_text_diff, NULL, repo);
5140 if (error)
5141 goto done;
5142 error = view_loop(view);
5143 done:
5144 free(label1);
5145 free(label2);
5146 free(repo_path);
5147 free(cwd);
5148 if (repo) {
5149 const struct got_error *close_err = got_repo_close(repo);
5150 if (error == NULL)
5151 error = close_err;
5153 if (worktree)
5154 got_worktree_close(worktree);
5155 if (pack_fds) {
5156 const struct got_error *pack_err =
5157 got_repo_pack_fds_close(pack_fds);
5158 if (error == NULL)
5159 error = pack_err;
5161 tog_free_refs();
5162 return error;
5165 __dead static void
5166 usage_blame(void)
5168 endwin();
5169 fprintf(stderr,
5170 "usage: %s blame [-c commit] [-r repository-path] path\n",
5171 getprogname());
5172 exit(1);
5175 struct tog_blame_line {
5176 int annotated;
5177 struct got_object_id *id;
5180 static const struct got_error *
5181 draw_blame(struct tog_view *view)
5183 struct tog_blame_view_state *s = &view->state.blame;
5184 struct tog_blame *blame = &s->blame;
5185 regmatch_t *regmatch = &view->regmatch;
5186 const struct got_error *err;
5187 int lineno = 0, nprinted = 0;
5188 char *line = NULL;
5189 size_t linesize = 0;
5190 ssize_t linelen;
5191 wchar_t *wline;
5192 int width;
5193 struct tog_blame_line *blame_line;
5194 struct got_object_id *prev_id = NULL;
5195 char *id_str;
5196 struct tog_color *tc;
5198 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5199 if (err)
5200 return err;
5202 rewind(blame->f);
5203 werase(view->window);
5205 if (asprintf(&line, "commit %s", id_str) == -1) {
5206 err = got_error_from_errno("asprintf");
5207 free(id_str);
5208 return err;
5211 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5212 free(line);
5213 line = NULL;
5214 if (err)
5215 return err;
5216 if (view_needs_focus_indication(view))
5217 wstandout(view->window);
5218 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5219 if (tc)
5220 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5221 waddwstr(view->window, wline);
5222 while (width++ < view->ncols)
5223 waddch(view->window, ' ');
5224 if (tc)
5225 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5226 if (view_needs_focus_indication(view))
5227 wstandend(view->window);
5228 free(wline);
5229 wline = NULL;
5231 if (view->gline > blame->nlines)
5232 view->gline = blame->nlines;
5234 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5235 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5236 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5237 free(id_str);
5238 return got_error_from_errno("asprintf");
5240 free(id_str);
5241 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5242 free(line);
5243 line = NULL;
5244 if (err)
5245 return err;
5246 waddwstr(view->window, wline);
5247 free(wline);
5248 wline = NULL;
5249 if (width < view->ncols - 1)
5250 waddch(view->window, '\n');
5252 s->eof = 0;
5253 view->maxx = 0;
5254 while (nprinted < view->nlines - 2) {
5255 linelen = getline(&line, &linesize, blame->f);
5256 if (linelen == -1) {
5257 if (feof(blame->f)) {
5258 s->eof = 1;
5259 break;
5261 free(line);
5262 return got_ferror(blame->f, GOT_ERR_IO);
5264 if (++lineno < s->first_displayed_line)
5265 continue;
5266 if (view->gline && !gotoline(view, &lineno, &nprinted))
5267 continue;
5269 /* Set view->maxx based on full line length. */
5270 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5271 if (err) {
5272 free(line);
5273 return err;
5275 free(wline);
5276 wline = NULL;
5277 view->maxx = MAX(view->maxx, width);
5279 if (nprinted == s->selected_line - 1)
5280 wstandout(view->window);
5282 if (blame->nlines > 0) {
5283 blame_line = &blame->lines[lineno - 1];
5284 if (blame_line->annotated && prev_id &&
5285 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5286 !(nprinted == s->selected_line - 1)) {
5287 waddstr(view->window, " ");
5288 } else if (blame_line->annotated) {
5289 char *id_str;
5290 err = got_object_id_str(&id_str,
5291 blame_line->id);
5292 if (err) {
5293 free(line);
5294 return err;
5296 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5297 if (tc)
5298 wattr_on(view->window,
5299 COLOR_PAIR(tc->colorpair), NULL);
5300 wprintw(view->window, "%.8s", id_str);
5301 if (tc)
5302 wattr_off(view->window,
5303 COLOR_PAIR(tc->colorpair), NULL);
5304 free(id_str);
5305 prev_id = blame_line->id;
5306 } else {
5307 waddstr(view->window, "........");
5308 prev_id = NULL;
5310 } else {
5311 waddstr(view->window, "........");
5312 prev_id = NULL;
5315 if (nprinted == s->selected_line - 1)
5316 wstandend(view->window);
5317 waddstr(view->window, " ");
5319 if (view->ncols <= 9) {
5320 width = 9;
5321 } else if (s->first_displayed_line + nprinted ==
5322 s->matched_line &&
5323 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5324 err = add_matched_line(&width, line, view->ncols - 9, 9,
5325 view->window, view->x, regmatch);
5326 if (err) {
5327 free(line);
5328 return err;
5330 width += 9;
5331 } else {
5332 int skip;
5333 err = format_line(&wline, &width, &skip, line,
5334 view->x, view->ncols - 9, 9, 1);
5335 if (err) {
5336 free(line);
5337 return err;
5339 waddwstr(view->window, &wline[skip]);
5340 width += 9;
5341 free(wline);
5342 wline = NULL;
5345 if (width <= view->ncols - 1)
5346 waddch(view->window, '\n');
5347 if (++nprinted == 1)
5348 s->first_displayed_line = lineno;
5350 free(line);
5351 s->last_displayed_line = lineno;
5353 view_border(view);
5355 return NULL;
5358 static const struct got_error *
5359 blame_cb(void *arg, int nlines, int lineno,
5360 struct got_commit_object *commit, struct got_object_id *id)
5362 const struct got_error *err = NULL;
5363 struct tog_blame_cb_args *a = arg;
5364 struct tog_blame_line *line;
5365 int errcode;
5367 if (nlines != a->nlines ||
5368 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5369 return got_error(GOT_ERR_RANGE);
5371 errcode = pthread_mutex_lock(&tog_mutex);
5372 if (errcode)
5373 return got_error_set_errno(errcode, "pthread_mutex_lock");
5375 if (*a->quit) { /* user has quit the blame view */
5376 err = got_error(GOT_ERR_ITER_COMPLETED);
5377 goto done;
5380 if (lineno == -1)
5381 goto done; /* no change in this commit */
5383 line = &a->lines[lineno - 1];
5384 if (line->annotated)
5385 goto done;
5387 line->id = got_object_id_dup(id);
5388 if (line->id == NULL) {
5389 err = got_error_from_errno("got_object_id_dup");
5390 goto done;
5392 line->annotated = 1;
5393 done:
5394 errcode = pthread_mutex_unlock(&tog_mutex);
5395 if (errcode)
5396 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5397 return err;
5400 static void *
5401 blame_thread(void *arg)
5403 const struct got_error *err, *close_err;
5404 struct tog_blame_thread_args *ta = arg;
5405 struct tog_blame_cb_args *a = ta->cb_args;
5406 int errcode, fd1 = -1, fd2 = -1;
5407 FILE *f1 = NULL, *f2 = NULL;
5409 fd1 = got_opentempfd();
5410 if (fd1 == -1)
5411 return (void *)got_error_from_errno("got_opentempfd");
5413 fd2 = got_opentempfd();
5414 if (fd2 == -1) {
5415 err = got_error_from_errno("got_opentempfd");
5416 goto done;
5419 f1 = got_opentemp();
5420 if (f1 == NULL) {
5421 err = (void *)got_error_from_errno("got_opentemp");
5422 goto done;
5424 f2 = got_opentemp();
5425 if (f2 == NULL) {
5426 err = (void *)got_error_from_errno("got_opentemp");
5427 goto done;
5430 err = block_signals_used_by_main_thread();
5431 if (err)
5432 goto done;
5434 err = got_blame(ta->path, a->commit_id, ta->repo,
5435 tog_diff_algo, blame_cb, ta->cb_args,
5436 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5437 if (err && err->code == GOT_ERR_CANCELLED)
5438 err = NULL;
5440 errcode = pthread_mutex_lock(&tog_mutex);
5441 if (errcode) {
5442 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5443 goto done;
5446 close_err = got_repo_close(ta->repo);
5447 if (err == NULL)
5448 err = close_err;
5449 ta->repo = NULL;
5450 *ta->complete = 1;
5452 errcode = pthread_mutex_unlock(&tog_mutex);
5453 if (errcode && err == NULL)
5454 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5456 done:
5457 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5458 err = got_error_from_errno("close");
5459 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5460 err = got_error_from_errno("close");
5461 if (f1 && fclose(f1) == EOF && err == NULL)
5462 err = got_error_from_errno("fclose");
5463 if (f2 && fclose(f2) == EOF && err == NULL)
5464 err = got_error_from_errno("fclose");
5466 return (void *)err;
5469 static struct got_object_id *
5470 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5471 int first_displayed_line, int selected_line)
5473 struct tog_blame_line *line;
5475 if (nlines <= 0)
5476 return NULL;
5478 line = &lines[first_displayed_line - 1 + selected_line - 1];
5479 if (!line->annotated)
5480 return NULL;
5482 return line->id;
5485 static struct got_object_id *
5486 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5487 int lineno)
5489 struct tog_blame_line *line;
5491 if (nlines <= 0 || lineno >= nlines)
5492 return NULL;
5494 line = &lines[lineno - 1];
5495 if (!line->annotated)
5496 return NULL;
5498 return line->id;
5501 static const struct got_error *
5502 stop_blame(struct tog_blame *blame)
5504 const struct got_error *err = NULL;
5505 int i;
5507 if (blame->thread) {
5508 int errcode;
5509 errcode = pthread_mutex_unlock(&tog_mutex);
5510 if (errcode)
5511 return got_error_set_errno(errcode,
5512 "pthread_mutex_unlock");
5513 errcode = pthread_join(blame->thread, (void **)&err);
5514 if (errcode)
5515 return got_error_set_errno(errcode, "pthread_join");
5516 errcode = pthread_mutex_lock(&tog_mutex);
5517 if (errcode)
5518 return got_error_set_errno(errcode,
5519 "pthread_mutex_lock");
5520 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5521 err = NULL;
5522 blame->thread = 0; //NULL;
5524 if (blame->thread_args.repo) {
5525 const struct got_error *close_err;
5526 close_err = got_repo_close(blame->thread_args.repo);
5527 if (err == NULL)
5528 err = close_err;
5529 blame->thread_args.repo = NULL;
5531 if (blame->f) {
5532 if (fclose(blame->f) == EOF && err == NULL)
5533 err = got_error_from_errno("fclose");
5534 blame->f = NULL;
5536 if (blame->lines) {
5537 for (i = 0; i < blame->nlines; i++)
5538 free(blame->lines[i].id);
5539 free(blame->lines);
5540 blame->lines = NULL;
5542 free(blame->cb_args.commit_id);
5543 blame->cb_args.commit_id = NULL;
5544 if (blame->pack_fds) {
5545 const struct got_error *pack_err =
5546 got_repo_pack_fds_close(blame->pack_fds);
5547 if (err == NULL)
5548 err = pack_err;
5549 blame->pack_fds = NULL;
5551 return err;
5554 static const struct got_error *
5555 cancel_blame_view(void *arg)
5557 const struct got_error *err = NULL;
5558 int *done = arg;
5559 int errcode;
5561 errcode = pthread_mutex_lock(&tog_mutex);
5562 if (errcode)
5563 return got_error_set_errno(errcode,
5564 "pthread_mutex_unlock");
5566 if (*done)
5567 err = got_error(GOT_ERR_CANCELLED);
5569 errcode = pthread_mutex_unlock(&tog_mutex);
5570 if (errcode)
5571 return got_error_set_errno(errcode,
5572 "pthread_mutex_lock");
5574 return err;
5577 static const struct got_error *
5578 run_blame(struct tog_view *view)
5580 struct tog_blame_view_state *s = &view->state.blame;
5581 struct tog_blame *blame = &s->blame;
5582 const struct got_error *err = NULL;
5583 struct got_commit_object *commit = NULL;
5584 struct got_blob_object *blob = NULL;
5585 struct got_repository *thread_repo = NULL;
5586 struct got_object_id *obj_id = NULL;
5587 int obj_type, fd = -1;
5588 int *pack_fds = NULL;
5590 err = got_object_open_as_commit(&commit, s->repo,
5591 &s->blamed_commit->id);
5592 if (err)
5593 return err;
5595 fd = got_opentempfd();
5596 if (fd == -1) {
5597 err = got_error_from_errno("got_opentempfd");
5598 goto done;
5601 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5602 if (err)
5603 goto done;
5605 err = got_object_get_type(&obj_type, s->repo, obj_id);
5606 if (err)
5607 goto done;
5609 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5610 err = got_error(GOT_ERR_OBJ_TYPE);
5611 goto done;
5614 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5615 if (err)
5616 goto done;
5617 blame->f = got_opentemp();
5618 if (blame->f == NULL) {
5619 err = got_error_from_errno("got_opentemp");
5620 goto done;
5622 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5623 &blame->line_offsets, blame->f, blob);
5624 if (err)
5625 goto done;
5626 if (blame->nlines == 0) {
5627 s->blame_complete = 1;
5628 goto done;
5631 /* Don't include \n at EOF in the blame line count. */
5632 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5633 blame->nlines--;
5635 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5636 if (blame->lines == NULL) {
5637 err = got_error_from_errno("calloc");
5638 goto done;
5641 err = got_repo_pack_fds_open(&pack_fds);
5642 if (err)
5643 goto done;
5644 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5645 pack_fds);
5646 if (err)
5647 goto done;
5649 blame->pack_fds = pack_fds;
5650 blame->cb_args.view = view;
5651 blame->cb_args.lines = blame->lines;
5652 blame->cb_args.nlines = blame->nlines;
5653 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5654 if (blame->cb_args.commit_id == NULL) {
5655 err = got_error_from_errno("got_object_id_dup");
5656 goto done;
5658 blame->cb_args.quit = &s->done;
5660 blame->thread_args.path = s->path;
5661 blame->thread_args.repo = thread_repo;
5662 blame->thread_args.cb_args = &blame->cb_args;
5663 blame->thread_args.complete = &s->blame_complete;
5664 blame->thread_args.cancel_cb = cancel_blame_view;
5665 blame->thread_args.cancel_arg = &s->done;
5666 s->blame_complete = 0;
5668 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5669 s->first_displayed_line = 1;
5670 s->last_displayed_line = view->nlines;
5671 s->selected_line = 1;
5673 s->matched_line = 0;
5675 done:
5676 if (commit)
5677 got_object_commit_close(commit);
5678 if (fd != -1 && close(fd) == -1 && err == NULL)
5679 err = got_error_from_errno("close");
5680 if (blob)
5681 got_object_blob_close(blob);
5682 free(obj_id);
5683 if (err)
5684 stop_blame(blame);
5685 return err;
5688 static const struct got_error *
5689 open_blame_view(struct tog_view *view, char *path,
5690 struct got_object_id *commit_id, struct got_repository *repo)
5692 const struct got_error *err = NULL;
5693 struct tog_blame_view_state *s = &view->state.blame;
5695 STAILQ_INIT(&s->blamed_commits);
5697 s->path = strdup(path);
5698 if (s->path == NULL)
5699 return got_error_from_errno("strdup");
5701 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5702 if (err) {
5703 free(s->path);
5704 return err;
5707 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5708 s->first_displayed_line = 1;
5709 s->last_displayed_line = view->nlines;
5710 s->selected_line = 1;
5711 s->blame_complete = 0;
5712 s->repo = repo;
5713 s->commit_id = commit_id;
5714 memset(&s->blame, 0, sizeof(s->blame));
5716 STAILQ_INIT(&s->colors);
5717 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5718 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5719 get_color_value("TOG_COLOR_COMMIT"));
5720 if (err)
5721 return err;
5724 view->show = show_blame_view;
5725 view->input = input_blame_view;
5726 view->reset = reset_blame_view;
5727 view->close = close_blame_view;
5728 view->search_start = search_start_blame_view;
5729 view->search_next = search_next_blame_view;
5731 return run_blame(view);
5734 static const struct got_error *
5735 close_blame_view(struct tog_view *view)
5737 const struct got_error *err = NULL;
5738 struct tog_blame_view_state *s = &view->state.blame;
5740 if (s->blame.thread)
5741 err = stop_blame(&s->blame);
5743 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5744 struct got_object_qid *blamed_commit;
5745 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5746 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5747 got_object_qid_free(blamed_commit);
5750 free(s->path);
5751 free_colors(&s->colors);
5752 return err;
5755 static const struct got_error *
5756 search_start_blame_view(struct tog_view *view)
5758 struct tog_blame_view_state *s = &view->state.blame;
5760 s->matched_line = 0;
5761 return NULL;
5764 static const struct got_error *
5765 search_next_blame_view(struct tog_view *view)
5767 struct tog_blame_view_state *s = &view->state.blame;
5768 const struct got_error *err = NULL;
5769 int lineno;
5770 char *line = NULL;
5771 size_t linesize = 0;
5772 ssize_t linelen;
5774 if (!view->searching) {
5775 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5776 return NULL;
5779 if (s->matched_line) {
5780 if (view->searching == TOG_SEARCH_FORWARD)
5781 lineno = s->matched_line + 1;
5782 else
5783 lineno = s->matched_line - 1;
5784 } else
5785 lineno = s->first_displayed_line - 1 + s->selected_line;
5787 while (1) {
5788 off_t offset;
5790 if (lineno <= 0 || lineno > s->blame.nlines) {
5791 if (s->matched_line == 0) {
5792 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5793 break;
5796 if (view->searching == TOG_SEARCH_FORWARD)
5797 lineno = 1;
5798 else
5799 lineno = s->blame.nlines;
5802 offset = s->blame.line_offsets[lineno - 1];
5803 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5804 free(line);
5805 return got_error_from_errno("fseeko");
5807 linelen = getline(&line, &linesize, s->blame.f);
5808 if (linelen != -1) {
5809 char *exstr;
5810 err = expand_tab(&exstr, line);
5811 if (err)
5812 break;
5813 if (match_line(exstr, &view->regex, 1,
5814 &view->regmatch)) {
5815 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5816 s->matched_line = lineno;
5817 free(exstr);
5818 break;
5820 free(exstr);
5822 if (view->searching == TOG_SEARCH_FORWARD)
5823 lineno++;
5824 else
5825 lineno--;
5827 free(line);
5829 if (s->matched_line) {
5830 s->first_displayed_line = s->matched_line;
5831 s->selected_line = 1;
5834 return err;
5837 static const struct got_error *
5838 show_blame_view(struct tog_view *view)
5840 const struct got_error *err = NULL;
5841 struct tog_blame_view_state *s = &view->state.blame;
5842 int errcode;
5844 if (s->blame.thread == 0 && !s->blame_complete) {
5845 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5846 &s->blame.thread_args);
5847 if (errcode)
5848 return got_error_set_errno(errcode, "pthread_create");
5850 halfdelay(1); /* fast refresh while annotating */
5853 if (s->blame_complete)
5854 halfdelay(10); /* disable fast refresh */
5856 err = draw_blame(view);
5858 view_border(view);
5859 return err;
5862 static const struct got_error *
5863 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5864 struct got_repository *repo, struct got_object_id *id)
5866 struct tog_view *log_view;
5867 const struct got_error *err = NULL;
5869 *new_view = NULL;
5871 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5872 if (log_view == NULL)
5873 return got_error_from_errno("view_open");
5875 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5876 if (err)
5877 view_close(log_view);
5878 else
5879 *new_view = log_view;
5881 return err;
5884 static const struct got_error *
5885 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5887 const struct got_error *err = NULL, *thread_err = NULL;
5888 struct tog_view *diff_view;
5889 struct tog_blame_view_state *s = &view->state.blame;
5890 int eos, nscroll, begin_y = 0, begin_x = 0;
5892 eos = nscroll = view->nlines - 2;
5893 if (view_is_hsplit_top(view))
5894 --eos; /* border */
5896 switch (ch) {
5897 case '0':
5898 view->x = 0;
5899 break;
5900 case '$':
5901 view->x = MAX(view->maxx - view->ncols / 3, 0);
5902 view->count = 0;
5903 break;
5904 case KEY_RIGHT:
5905 case 'l':
5906 if (view->x + view->ncols / 3 < view->maxx)
5907 view->x += 2; /* move two columns right */
5908 else
5909 view->count = 0;
5910 break;
5911 case KEY_LEFT:
5912 case 'h':
5913 view->x -= MIN(view->x, 2); /* move two columns back */
5914 if (view->x <= 0)
5915 view->count = 0;
5916 break;
5917 case 'q':
5918 s->done = 1;
5919 break;
5920 case 'g':
5921 case KEY_HOME:
5922 s->selected_line = 1;
5923 s->first_displayed_line = 1;
5924 view->count = 0;
5925 break;
5926 case 'G':
5927 case KEY_END:
5928 if (s->blame.nlines < eos) {
5929 s->selected_line = s->blame.nlines;
5930 s->first_displayed_line = 1;
5931 } else {
5932 s->selected_line = eos;
5933 s->first_displayed_line = s->blame.nlines - (eos - 1);
5935 view->count = 0;
5936 break;
5937 case 'k':
5938 case KEY_UP:
5939 case CTRL('p'):
5940 if (s->selected_line > 1)
5941 s->selected_line--;
5942 else if (s->selected_line == 1 &&
5943 s->first_displayed_line > 1)
5944 s->first_displayed_line--;
5945 else
5946 view->count = 0;
5947 break;
5948 case CTRL('u'):
5949 case 'u':
5950 nscroll /= 2;
5951 /* FALL THROUGH */
5952 case KEY_PPAGE:
5953 case CTRL('b'):
5954 case 'b':
5955 if (s->first_displayed_line == 1) {
5956 if (view->count > 1)
5957 nscroll += nscroll;
5958 s->selected_line = MAX(1, s->selected_line - nscroll);
5959 view->count = 0;
5960 break;
5962 if (s->first_displayed_line > nscroll)
5963 s->first_displayed_line -= nscroll;
5964 else
5965 s->first_displayed_line = 1;
5966 break;
5967 case 'j':
5968 case KEY_DOWN:
5969 case CTRL('n'):
5970 if (s->selected_line < eos && s->first_displayed_line +
5971 s->selected_line <= s->blame.nlines)
5972 s->selected_line++;
5973 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5974 s->first_displayed_line++;
5975 else
5976 view->count = 0;
5977 break;
5978 case 'c':
5979 case 'p': {
5980 struct got_object_id *id = NULL;
5982 view->count = 0;
5983 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5984 s->first_displayed_line, s->selected_line);
5985 if (id == NULL)
5986 break;
5987 if (ch == 'p') {
5988 struct got_commit_object *commit, *pcommit;
5989 struct got_object_qid *pid;
5990 struct got_object_id *blob_id = NULL;
5991 int obj_type;
5992 err = got_object_open_as_commit(&commit,
5993 s->repo, id);
5994 if (err)
5995 break;
5996 pid = STAILQ_FIRST(
5997 got_object_commit_get_parent_ids(commit));
5998 if (pid == NULL) {
5999 got_object_commit_close(commit);
6000 break;
6002 /* Check if path history ends here. */
6003 err = got_object_open_as_commit(&pcommit,
6004 s->repo, &pid->id);
6005 if (err)
6006 break;
6007 err = got_object_id_by_path(&blob_id, s->repo,
6008 pcommit, s->path);
6009 got_object_commit_close(pcommit);
6010 if (err) {
6011 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6012 err = NULL;
6013 got_object_commit_close(commit);
6014 break;
6016 err = got_object_get_type(&obj_type, s->repo,
6017 blob_id);
6018 free(blob_id);
6019 /* Can't blame non-blob type objects. */
6020 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6021 got_object_commit_close(commit);
6022 break;
6024 err = got_object_qid_alloc(&s->blamed_commit,
6025 &pid->id);
6026 got_object_commit_close(commit);
6027 } else {
6028 if (got_object_id_cmp(id,
6029 &s->blamed_commit->id) == 0)
6030 break;
6031 err = got_object_qid_alloc(&s->blamed_commit,
6032 id);
6034 if (err)
6035 break;
6036 s->done = 1;
6037 thread_err = stop_blame(&s->blame);
6038 s->done = 0;
6039 if (thread_err)
6040 break;
6041 STAILQ_INSERT_HEAD(&s->blamed_commits,
6042 s->blamed_commit, entry);
6043 err = run_blame(view);
6044 if (err)
6045 break;
6046 break;
6048 case 'C': {
6049 struct got_object_qid *first;
6051 view->count = 0;
6052 first = STAILQ_FIRST(&s->blamed_commits);
6053 if (!got_object_id_cmp(&first->id, s->commit_id))
6054 break;
6055 s->done = 1;
6056 thread_err = stop_blame(&s->blame);
6057 s->done = 0;
6058 if (thread_err)
6059 break;
6060 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6061 got_object_qid_free(s->blamed_commit);
6062 s->blamed_commit =
6063 STAILQ_FIRST(&s->blamed_commits);
6064 err = run_blame(view);
6065 if (err)
6066 break;
6067 break;
6069 case 'L':
6070 view->count = 0;
6071 s->id_to_log = get_selected_commit_id(s->blame.lines,
6072 s->blame.nlines, s->first_displayed_line, s->selected_line);
6073 if (s->id_to_log)
6074 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6075 break;
6076 case KEY_ENTER:
6077 case '\r': {
6078 struct got_object_id *id = NULL;
6079 struct got_object_qid *pid;
6080 struct got_commit_object *commit = NULL;
6082 view->count = 0;
6083 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6084 s->first_displayed_line, s->selected_line);
6085 if (id == NULL)
6086 break;
6087 err = got_object_open_as_commit(&commit, s->repo, id);
6088 if (err)
6089 break;
6090 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6091 if (*new_view) {
6092 /* traversed from diff view, release diff resources */
6093 err = close_diff_view(*new_view);
6094 if (err)
6095 break;
6096 diff_view = *new_view;
6097 } else {
6098 if (view_is_parent_view(view))
6099 view_get_split(view, &begin_y, &begin_x);
6101 diff_view = view_open(0, 0, begin_y, begin_x,
6102 TOG_VIEW_DIFF);
6103 if (diff_view == NULL) {
6104 got_object_commit_close(commit);
6105 err = got_error_from_errno("view_open");
6106 break;
6109 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6110 id, NULL, NULL, 3, 0, 0, view, s->repo);
6111 got_object_commit_close(commit);
6112 if (err) {
6113 view_close(diff_view);
6114 break;
6116 s->last_diffed_line = s->first_displayed_line - 1 +
6117 s->selected_line;
6118 if (*new_view)
6119 break; /* still open from active diff view */
6120 if (view_is_parent_view(view) &&
6121 view->mode == TOG_VIEW_SPLIT_HRZN) {
6122 err = view_init_hsplit(view, begin_y);
6123 if (err)
6124 break;
6127 view->focussed = 0;
6128 diff_view->focussed = 1;
6129 diff_view->mode = view->mode;
6130 diff_view->nlines = view->lines - begin_y;
6131 if (view_is_parent_view(view)) {
6132 view_transfer_size(diff_view, view);
6133 err = view_close_child(view);
6134 if (err)
6135 break;
6136 err = view_set_child(view, diff_view);
6137 if (err)
6138 break;
6139 view->focus_child = 1;
6140 } else
6141 *new_view = diff_view;
6142 if (err)
6143 break;
6144 break;
6146 case CTRL('d'):
6147 case 'd':
6148 nscroll /= 2;
6149 /* FALL THROUGH */
6150 case KEY_NPAGE:
6151 case CTRL('f'):
6152 case 'f':
6153 case ' ':
6154 if (s->last_displayed_line >= s->blame.nlines &&
6155 s->selected_line >= MIN(s->blame.nlines,
6156 view->nlines - 2)) {
6157 view->count = 0;
6158 break;
6160 if (s->last_displayed_line >= s->blame.nlines &&
6161 s->selected_line < view->nlines - 2) {
6162 s->selected_line +=
6163 MIN(nscroll, s->last_displayed_line -
6164 s->first_displayed_line - s->selected_line + 1);
6166 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6167 s->first_displayed_line += nscroll;
6168 else
6169 s->first_displayed_line =
6170 s->blame.nlines - (view->nlines - 3);
6171 break;
6172 case KEY_RESIZE:
6173 if (s->selected_line > view->nlines - 2) {
6174 s->selected_line = MIN(s->blame.nlines,
6175 view->nlines - 2);
6177 break;
6178 default:
6179 view->count = 0;
6180 break;
6182 return thread_err ? thread_err : err;
6185 static const struct got_error *
6186 reset_blame_view(struct tog_view *view)
6188 const struct got_error *err;
6189 struct tog_blame_view_state *s = &view->state.blame;
6191 view->count = 0;
6192 s->done = 1;
6193 err = stop_blame(&s->blame);
6194 s->done = 0;
6195 if (err)
6196 return err;
6197 return run_blame(view);
6200 static const struct got_error *
6201 cmd_blame(int argc, char *argv[])
6203 const struct got_error *error;
6204 struct got_repository *repo = NULL;
6205 struct got_worktree *worktree = NULL;
6206 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6207 char *link_target = NULL;
6208 struct got_object_id *commit_id = NULL;
6209 struct got_commit_object *commit = NULL;
6210 char *commit_id_str = NULL;
6211 int ch;
6212 struct tog_view *view;
6213 int *pack_fds = NULL;
6215 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6216 switch (ch) {
6217 case 'c':
6218 commit_id_str = optarg;
6219 break;
6220 case 'r':
6221 repo_path = realpath(optarg, NULL);
6222 if (repo_path == NULL)
6223 return got_error_from_errno2("realpath",
6224 optarg);
6225 break;
6226 default:
6227 usage_blame();
6228 /* NOTREACHED */
6232 argc -= optind;
6233 argv += optind;
6235 if (argc != 1)
6236 usage_blame();
6238 error = got_repo_pack_fds_open(&pack_fds);
6239 if (error != NULL)
6240 goto done;
6242 if (repo_path == NULL) {
6243 cwd = getcwd(NULL, 0);
6244 if (cwd == NULL)
6245 return got_error_from_errno("getcwd");
6246 error = got_worktree_open(&worktree, cwd);
6247 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6248 goto done;
6249 if (worktree)
6250 repo_path =
6251 strdup(got_worktree_get_repo_path(worktree));
6252 else
6253 repo_path = strdup(cwd);
6254 if (repo_path == NULL) {
6255 error = got_error_from_errno("strdup");
6256 goto done;
6260 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6261 if (error != NULL)
6262 goto done;
6264 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6265 worktree);
6266 if (error)
6267 goto done;
6269 init_curses();
6271 error = apply_unveil(got_repo_get_path(repo), NULL);
6272 if (error)
6273 goto done;
6275 error = tog_load_refs(repo, 0);
6276 if (error)
6277 goto done;
6279 if (commit_id_str == NULL) {
6280 struct got_reference *head_ref;
6281 error = got_ref_open(&head_ref, repo, worktree ?
6282 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6283 if (error != NULL)
6284 goto done;
6285 error = got_ref_resolve(&commit_id, repo, head_ref);
6286 got_ref_close(head_ref);
6287 } else {
6288 error = got_repo_match_object_id(&commit_id, NULL,
6289 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6291 if (error != NULL)
6292 goto done;
6294 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6295 if (view == NULL) {
6296 error = got_error_from_errno("view_open");
6297 goto done;
6300 error = got_object_open_as_commit(&commit, repo, commit_id);
6301 if (error)
6302 goto done;
6304 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6305 commit, repo);
6306 if (error)
6307 goto done;
6309 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6310 commit_id, repo);
6311 if (error)
6312 goto done;
6313 if (worktree) {
6314 /* Release work tree lock. */
6315 got_worktree_close(worktree);
6316 worktree = NULL;
6318 error = view_loop(view);
6319 done:
6320 free(repo_path);
6321 free(in_repo_path);
6322 free(link_target);
6323 free(cwd);
6324 free(commit_id);
6325 if (commit)
6326 got_object_commit_close(commit);
6327 if (worktree)
6328 got_worktree_close(worktree);
6329 if (repo) {
6330 const struct got_error *close_err = got_repo_close(repo);
6331 if (error == NULL)
6332 error = close_err;
6334 if (pack_fds) {
6335 const struct got_error *pack_err =
6336 got_repo_pack_fds_close(pack_fds);
6337 if (error == NULL)
6338 error = pack_err;
6340 tog_free_refs();
6341 return error;
6344 static const struct got_error *
6345 draw_tree_entries(struct tog_view *view, const char *parent_path)
6347 struct tog_tree_view_state *s = &view->state.tree;
6348 const struct got_error *err = NULL;
6349 struct got_tree_entry *te;
6350 wchar_t *wline;
6351 char *index = NULL;
6352 struct tog_color *tc;
6353 int width, n, nentries, i = 1;
6354 int limit = view->nlines;
6356 s->ndisplayed = 0;
6357 if (view_is_hsplit_top(view))
6358 --limit; /* border */
6360 werase(view->window);
6362 if (limit == 0)
6363 return NULL;
6365 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6366 0, 0);
6367 if (err)
6368 return err;
6369 if (view_needs_focus_indication(view))
6370 wstandout(view->window);
6371 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6372 if (tc)
6373 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6374 waddwstr(view->window, wline);
6375 free(wline);
6376 wline = NULL;
6377 while (width++ < view->ncols)
6378 waddch(view->window, ' ');
6379 if (tc)
6380 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6381 if (view_needs_focus_indication(view))
6382 wstandend(view->window);
6383 if (--limit <= 0)
6384 return NULL;
6386 i += s->selected;
6387 if (s->first_displayed_entry) {
6388 i += got_tree_entry_get_index(s->first_displayed_entry);
6389 if (s->tree != s->root)
6390 ++i; /* account for ".." entry */
6392 nentries = got_object_tree_get_nentries(s->tree);
6393 if (asprintf(&index, "[%d/%d] %s",
6394 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6395 return got_error_from_errno("asprintf");
6396 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6397 free(index);
6398 if (err)
6399 return err;
6400 waddwstr(view->window, wline);
6401 free(wline);
6402 wline = NULL;
6403 if (width < view->ncols - 1)
6404 waddch(view->window, '\n');
6405 if (--limit <= 0)
6406 return NULL;
6407 waddch(view->window, '\n');
6408 if (--limit <= 0)
6409 return NULL;
6411 if (s->first_displayed_entry == NULL) {
6412 te = got_object_tree_get_first_entry(s->tree);
6413 if (s->selected == 0) {
6414 if (view->focussed)
6415 wstandout(view->window);
6416 s->selected_entry = NULL;
6418 waddstr(view->window, " ..\n"); /* parent directory */
6419 if (s->selected == 0 && view->focussed)
6420 wstandend(view->window);
6421 s->ndisplayed++;
6422 if (--limit <= 0)
6423 return NULL;
6424 n = 1;
6425 } else {
6426 n = 0;
6427 te = s->first_displayed_entry;
6430 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6431 char *line = NULL, *id_str = NULL, *link_target = NULL;
6432 const char *modestr = "";
6433 mode_t mode;
6435 te = got_object_tree_get_entry(s->tree, i);
6436 mode = got_tree_entry_get_mode(te);
6438 if (s->show_ids) {
6439 err = got_object_id_str(&id_str,
6440 got_tree_entry_get_id(te));
6441 if (err)
6442 return got_error_from_errno(
6443 "got_object_id_str");
6445 if (got_object_tree_entry_is_submodule(te))
6446 modestr = "$";
6447 else if (S_ISLNK(mode)) {
6448 int i;
6450 err = got_tree_entry_get_symlink_target(&link_target,
6451 te, s->repo);
6452 if (err) {
6453 free(id_str);
6454 return err;
6456 for (i = 0; i < strlen(link_target); i++) {
6457 if (!isprint((unsigned char)link_target[i]))
6458 link_target[i] = '?';
6460 modestr = "@";
6462 else if (S_ISDIR(mode))
6463 modestr = "/";
6464 else if (mode & S_IXUSR)
6465 modestr = "*";
6466 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6467 got_tree_entry_get_name(te), modestr,
6468 link_target ? " -> ": "",
6469 link_target ? link_target : "") == -1) {
6470 free(id_str);
6471 free(link_target);
6472 return got_error_from_errno("asprintf");
6474 free(id_str);
6475 free(link_target);
6476 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6477 0, 0);
6478 if (err) {
6479 free(line);
6480 break;
6482 if (n == s->selected) {
6483 if (view->focussed)
6484 wstandout(view->window);
6485 s->selected_entry = te;
6487 tc = match_color(&s->colors, line);
6488 if (tc)
6489 wattr_on(view->window,
6490 COLOR_PAIR(tc->colorpair), NULL);
6491 waddwstr(view->window, wline);
6492 if (tc)
6493 wattr_off(view->window,
6494 COLOR_PAIR(tc->colorpair), NULL);
6495 if (width < view->ncols - 1)
6496 waddch(view->window, '\n');
6497 if (n == s->selected && view->focussed)
6498 wstandend(view->window);
6499 free(line);
6500 free(wline);
6501 wline = NULL;
6502 n++;
6503 s->ndisplayed++;
6504 s->last_displayed_entry = te;
6505 if (--limit <= 0)
6506 break;
6509 return err;
6512 static void
6513 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6515 struct got_tree_entry *te;
6516 int isroot = s->tree == s->root;
6517 int i = 0;
6519 if (s->first_displayed_entry == NULL)
6520 return;
6522 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6523 while (i++ < maxscroll) {
6524 if (te == NULL) {
6525 if (!isroot)
6526 s->first_displayed_entry = NULL;
6527 break;
6529 s->first_displayed_entry = te;
6530 te = got_tree_entry_get_prev(s->tree, te);
6534 static const struct got_error *
6535 tree_scroll_down(struct tog_view *view, int maxscroll)
6537 struct tog_tree_view_state *s = &view->state.tree;
6538 struct got_tree_entry *next, *last;
6539 int n = 0;
6541 if (s->first_displayed_entry)
6542 next = got_tree_entry_get_next(s->tree,
6543 s->first_displayed_entry);
6544 else
6545 next = got_object_tree_get_first_entry(s->tree);
6547 last = s->last_displayed_entry;
6548 while (next && n++ < maxscroll) {
6549 if (last) {
6550 s->last_displayed_entry = last;
6551 last = got_tree_entry_get_next(s->tree, last);
6553 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6554 s->first_displayed_entry = next;
6555 next = got_tree_entry_get_next(s->tree, next);
6559 return NULL;
6562 static const struct got_error *
6563 tree_entry_path(char **path, struct tog_parent_trees *parents,
6564 struct got_tree_entry *te)
6566 const struct got_error *err = NULL;
6567 struct tog_parent_tree *pt;
6568 size_t len = 2; /* for leading slash and NUL */
6570 TAILQ_FOREACH(pt, parents, entry)
6571 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6572 + 1 /* slash */;
6573 if (te)
6574 len += strlen(got_tree_entry_get_name(te));
6576 *path = calloc(1, len);
6577 if (path == NULL)
6578 return got_error_from_errno("calloc");
6580 (*path)[0] = '/';
6581 pt = TAILQ_LAST(parents, tog_parent_trees);
6582 while (pt) {
6583 const char *name = got_tree_entry_get_name(pt->selected_entry);
6584 if (strlcat(*path, name, len) >= len) {
6585 err = got_error(GOT_ERR_NO_SPACE);
6586 goto done;
6588 if (strlcat(*path, "/", len) >= len) {
6589 err = got_error(GOT_ERR_NO_SPACE);
6590 goto done;
6592 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6594 if (te) {
6595 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6596 err = got_error(GOT_ERR_NO_SPACE);
6597 goto done;
6600 done:
6601 if (err) {
6602 free(*path);
6603 *path = NULL;
6605 return err;
6608 static const struct got_error *
6609 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6610 struct got_tree_entry *te, struct tog_parent_trees *parents,
6611 struct got_object_id *commit_id, struct got_repository *repo)
6613 const struct got_error *err = NULL;
6614 char *path;
6615 struct tog_view *blame_view;
6617 *new_view = NULL;
6619 err = tree_entry_path(&path, parents, te);
6620 if (err)
6621 return err;
6623 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6624 if (blame_view == NULL) {
6625 err = got_error_from_errno("view_open");
6626 goto done;
6629 err = open_blame_view(blame_view, path, commit_id, repo);
6630 if (err) {
6631 if (err->code == GOT_ERR_CANCELLED)
6632 err = NULL;
6633 view_close(blame_view);
6634 } else
6635 *new_view = blame_view;
6636 done:
6637 free(path);
6638 return err;
6641 static const struct got_error *
6642 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6643 struct tog_tree_view_state *s)
6645 struct tog_view *log_view;
6646 const struct got_error *err = NULL;
6647 char *path;
6649 *new_view = NULL;
6651 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6652 if (log_view == NULL)
6653 return got_error_from_errno("view_open");
6655 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6656 if (err)
6657 return err;
6659 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6660 path, 0);
6661 if (err)
6662 view_close(log_view);
6663 else
6664 *new_view = log_view;
6665 free(path);
6666 return err;
6669 static const struct got_error *
6670 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6671 const char *head_ref_name, struct got_repository *repo)
6673 const struct got_error *err = NULL;
6674 char *commit_id_str = NULL;
6675 struct tog_tree_view_state *s = &view->state.tree;
6676 struct got_commit_object *commit = NULL;
6678 TAILQ_INIT(&s->parents);
6679 STAILQ_INIT(&s->colors);
6681 s->commit_id = got_object_id_dup(commit_id);
6682 if (s->commit_id == NULL)
6683 return got_error_from_errno("got_object_id_dup");
6685 err = got_object_open_as_commit(&commit, repo, commit_id);
6686 if (err)
6687 goto done;
6690 * The root is opened here and will be closed when the view is closed.
6691 * Any visited subtrees and their path-wise parents are opened and
6692 * closed on demand.
6694 err = got_object_open_as_tree(&s->root, repo,
6695 got_object_commit_get_tree_id(commit));
6696 if (err)
6697 goto done;
6698 s->tree = s->root;
6700 err = got_object_id_str(&commit_id_str, commit_id);
6701 if (err != NULL)
6702 goto done;
6704 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6705 err = got_error_from_errno("asprintf");
6706 goto done;
6709 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6710 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6711 if (head_ref_name) {
6712 s->head_ref_name = strdup(head_ref_name);
6713 if (s->head_ref_name == NULL) {
6714 err = got_error_from_errno("strdup");
6715 goto done;
6718 s->repo = repo;
6720 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6721 err = add_color(&s->colors, "\\$$",
6722 TOG_COLOR_TREE_SUBMODULE,
6723 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6724 if (err)
6725 goto done;
6726 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6727 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6728 if (err)
6729 goto done;
6730 err = add_color(&s->colors, "/$",
6731 TOG_COLOR_TREE_DIRECTORY,
6732 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6733 if (err)
6734 goto done;
6736 err = add_color(&s->colors, "\\*$",
6737 TOG_COLOR_TREE_EXECUTABLE,
6738 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6739 if (err)
6740 goto done;
6742 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6743 get_color_value("TOG_COLOR_COMMIT"));
6744 if (err)
6745 goto done;
6748 view->show = show_tree_view;
6749 view->input = input_tree_view;
6750 view->close = close_tree_view;
6751 view->search_start = search_start_tree_view;
6752 view->search_next = search_next_tree_view;
6753 done:
6754 free(commit_id_str);
6755 if (commit)
6756 got_object_commit_close(commit);
6757 if (err)
6758 close_tree_view(view);
6759 return err;
6762 static const struct got_error *
6763 close_tree_view(struct tog_view *view)
6765 struct tog_tree_view_state *s = &view->state.tree;
6767 free_colors(&s->colors);
6768 free(s->tree_label);
6769 s->tree_label = NULL;
6770 free(s->commit_id);
6771 s->commit_id = NULL;
6772 free(s->head_ref_name);
6773 s->head_ref_name = NULL;
6774 while (!TAILQ_EMPTY(&s->parents)) {
6775 struct tog_parent_tree *parent;
6776 parent = TAILQ_FIRST(&s->parents);
6777 TAILQ_REMOVE(&s->parents, parent, entry);
6778 if (parent->tree != s->root)
6779 got_object_tree_close(parent->tree);
6780 free(parent);
6783 if (s->tree != NULL && s->tree != s->root)
6784 got_object_tree_close(s->tree);
6785 if (s->root)
6786 got_object_tree_close(s->root);
6787 return NULL;
6790 static const struct got_error *
6791 search_start_tree_view(struct tog_view *view)
6793 struct tog_tree_view_state *s = &view->state.tree;
6795 s->matched_entry = NULL;
6796 return NULL;
6799 static int
6800 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6802 regmatch_t regmatch;
6804 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6805 0) == 0;
6808 static const struct got_error *
6809 search_next_tree_view(struct tog_view *view)
6811 struct tog_tree_view_state *s = &view->state.tree;
6812 struct got_tree_entry *te = NULL;
6814 if (!view->searching) {
6815 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6816 return NULL;
6819 if (s->matched_entry) {
6820 if (view->searching == TOG_SEARCH_FORWARD) {
6821 if (s->selected_entry)
6822 te = got_tree_entry_get_next(s->tree,
6823 s->selected_entry);
6824 else
6825 te = got_object_tree_get_first_entry(s->tree);
6826 } else {
6827 if (s->selected_entry == NULL)
6828 te = got_object_tree_get_last_entry(s->tree);
6829 else
6830 te = got_tree_entry_get_prev(s->tree,
6831 s->selected_entry);
6833 } else {
6834 if (s->selected_entry)
6835 te = s->selected_entry;
6836 else if (view->searching == TOG_SEARCH_FORWARD)
6837 te = got_object_tree_get_first_entry(s->tree);
6838 else
6839 te = got_object_tree_get_last_entry(s->tree);
6842 while (1) {
6843 if (te == NULL) {
6844 if (s->matched_entry == NULL) {
6845 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6846 return NULL;
6848 if (view->searching == TOG_SEARCH_FORWARD)
6849 te = got_object_tree_get_first_entry(s->tree);
6850 else
6851 te = got_object_tree_get_last_entry(s->tree);
6854 if (match_tree_entry(te, &view->regex)) {
6855 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6856 s->matched_entry = te;
6857 break;
6860 if (view->searching == TOG_SEARCH_FORWARD)
6861 te = got_tree_entry_get_next(s->tree, te);
6862 else
6863 te = got_tree_entry_get_prev(s->tree, te);
6866 if (s->matched_entry) {
6867 s->first_displayed_entry = s->matched_entry;
6868 s->selected = 0;
6871 return NULL;
6874 static const struct got_error *
6875 show_tree_view(struct tog_view *view)
6877 const struct got_error *err = NULL;
6878 struct tog_tree_view_state *s = &view->state.tree;
6879 char *parent_path;
6881 err = tree_entry_path(&parent_path, &s->parents, NULL);
6882 if (err)
6883 return err;
6885 err = draw_tree_entries(view, parent_path);
6886 free(parent_path);
6888 view_border(view);
6889 return err;
6892 static const struct got_error *
6893 tree_goto_line(struct tog_view *view, int nlines)
6895 const struct got_error *err = NULL;
6896 struct tog_tree_view_state *s = &view->state.tree;
6897 struct got_tree_entry **fte, **lte, **ste;
6898 int g, last, first = 1, i = 1;
6899 int root = s->tree == s->root;
6900 int off = root ? 1 : 2;
6902 g = view->gline;
6903 view->gline = 0;
6905 if (g == 0)
6906 g = 1;
6907 else if (g > got_object_tree_get_nentries(s->tree))
6908 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
6910 fte = &s->first_displayed_entry;
6911 lte = &s->last_displayed_entry;
6912 ste = &s->selected_entry;
6914 if (*fte != NULL) {
6915 first = got_tree_entry_get_index(*fte);
6916 first += off; /* account for ".." */
6918 last = got_tree_entry_get_index(*lte);
6919 last += off;
6921 if (g >= first && g <= last && g - first < nlines) {
6922 s->selected = g - first;
6923 return NULL; /* gline is on the current page */
6926 if (*ste != NULL) {
6927 i = got_tree_entry_get_index(*ste);
6928 i += off;
6931 if (i < g) {
6932 err = tree_scroll_down(view, g - i);
6933 if (err)
6934 return err;
6935 if (got_tree_entry_get_index(*lte) >=
6936 got_object_tree_get_nentries(s->tree) - 1 &&
6937 first + s->selected < g &&
6938 s->selected < s->ndisplayed - 1) {
6939 first = got_tree_entry_get_index(*fte);
6940 first += off;
6941 s->selected = g - first;
6943 } else if (i > g)
6944 tree_scroll_up(s, i - g);
6946 if (g < nlines &&
6947 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
6948 s->selected = g - 1;
6950 return NULL;
6953 static const struct got_error *
6954 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6956 const struct got_error *err = NULL;
6957 struct tog_tree_view_state *s = &view->state.tree;
6958 struct got_tree_entry *te;
6959 int n, nscroll = view->nlines - 3;
6961 if (view->gline)
6962 return tree_goto_line(view, nscroll);
6964 switch (ch) {
6965 case 'i':
6966 s->show_ids = !s->show_ids;
6967 view->count = 0;
6968 break;
6969 case 'L':
6970 view->count = 0;
6971 if (!s->selected_entry)
6972 break;
6973 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6974 break;
6975 case 'R':
6976 view->count = 0;
6977 err = view_request_new(new_view, view, TOG_VIEW_REF);
6978 break;
6979 case 'g':
6980 case KEY_HOME:
6981 s->selected = 0;
6982 view->count = 0;
6983 if (s->tree == s->root)
6984 s->first_displayed_entry =
6985 got_object_tree_get_first_entry(s->tree);
6986 else
6987 s->first_displayed_entry = NULL;
6988 break;
6989 case 'G':
6990 case KEY_END: {
6991 int eos = view->nlines - 3;
6993 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6994 --eos; /* border */
6995 s->selected = 0;
6996 view->count = 0;
6997 te = got_object_tree_get_last_entry(s->tree);
6998 for (n = 0; n < eos; n++) {
6999 if (te == NULL) {
7000 if (s->tree != s->root) {
7001 s->first_displayed_entry = NULL;
7002 n++;
7004 break;
7006 s->first_displayed_entry = te;
7007 te = got_tree_entry_get_prev(s->tree, te);
7009 if (n > 0)
7010 s->selected = n - 1;
7011 break;
7013 case 'k':
7014 case KEY_UP:
7015 case CTRL('p'):
7016 if (s->selected > 0) {
7017 s->selected--;
7018 break;
7020 tree_scroll_up(s, 1);
7021 if (s->selected_entry == NULL ||
7022 (s->tree == s->root && s->selected_entry ==
7023 got_object_tree_get_first_entry(s->tree)))
7024 view->count = 0;
7025 break;
7026 case CTRL('u'):
7027 case 'u':
7028 nscroll /= 2;
7029 /* FALL THROUGH */
7030 case KEY_PPAGE:
7031 case CTRL('b'):
7032 case 'b':
7033 if (s->tree == s->root) {
7034 if (got_object_tree_get_first_entry(s->tree) ==
7035 s->first_displayed_entry)
7036 s->selected -= MIN(s->selected, nscroll);
7037 } else {
7038 if (s->first_displayed_entry == NULL)
7039 s->selected -= MIN(s->selected, nscroll);
7041 tree_scroll_up(s, MAX(0, nscroll));
7042 if (s->selected_entry == NULL ||
7043 (s->tree == s->root && s->selected_entry ==
7044 got_object_tree_get_first_entry(s->tree)))
7045 view->count = 0;
7046 break;
7047 case 'j':
7048 case KEY_DOWN:
7049 case CTRL('n'):
7050 if (s->selected < s->ndisplayed - 1) {
7051 s->selected++;
7052 break;
7054 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7055 == NULL) {
7056 /* can't scroll any further */
7057 view->count = 0;
7058 break;
7060 tree_scroll_down(view, 1);
7061 break;
7062 case CTRL('d'):
7063 case 'd':
7064 nscroll /= 2;
7065 /* FALL THROUGH */
7066 case KEY_NPAGE:
7067 case CTRL('f'):
7068 case 'f':
7069 case ' ':
7070 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7071 == NULL) {
7072 /* can't scroll any further; move cursor down */
7073 if (s->selected < s->ndisplayed - 1)
7074 s->selected += MIN(nscroll,
7075 s->ndisplayed - s->selected - 1);
7076 else
7077 view->count = 0;
7078 break;
7080 tree_scroll_down(view, nscroll);
7081 break;
7082 case KEY_ENTER:
7083 case '\r':
7084 case KEY_BACKSPACE:
7085 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7086 struct tog_parent_tree *parent;
7087 /* user selected '..' */
7088 if (s->tree == s->root) {
7089 view->count = 0;
7090 break;
7092 parent = TAILQ_FIRST(&s->parents);
7093 TAILQ_REMOVE(&s->parents, parent,
7094 entry);
7095 got_object_tree_close(s->tree);
7096 s->tree = parent->tree;
7097 s->first_displayed_entry =
7098 parent->first_displayed_entry;
7099 s->selected_entry =
7100 parent->selected_entry;
7101 s->selected = parent->selected;
7102 if (s->selected > view->nlines - 3) {
7103 err = offset_selection_down(view);
7104 if (err)
7105 break;
7107 free(parent);
7108 } else if (S_ISDIR(got_tree_entry_get_mode(
7109 s->selected_entry))) {
7110 struct got_tree_object *subtree;
7111 view->count = 0;
7112 err = got_object_open_as_tree(&subtree, s->repo,
7113 got_tree_entry_get_id(s->selected_entry));
7114 if (err)
7115 break;
7116 err = tree_view_visit_subtree(s, subtree);
7117 if (err) {
7118 got_object_tree_close(subtree);
7119 break;
7121 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7122 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7123 break;
7124 case KEY_RESIZE:
7125 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7126 s->selected = view->nlines - 4;
7127 view->count = 0;
7128 break;
7129 default:
7130 view->count = 0;
7131 break;
7134 return err;
7137 __dead static void
7138 usage_tree(void)
7140 endwin();
7141 fprintf(stderr,
7142 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7143 getprogname());
7144 exit(1);
7147 static const struct got_error *
7148 cmd_tree(int argc, char *argv[])
7150 const struct got_error *error;
7151 struct got_repository *repo = NULL;
7152 struct got_worktree *worktree = NULL;
7153 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7154 struct got_object_id *commit_id = NULL;
7155 struct got_commit_object *commit = NULL;
7156 const char *commit_id_arg = NULL;
7157 char *label = NULL;
7158 struct got_reference *ref = NULL;
7159 const char *head_ref_name = NULL;
7160 int ch;
7161 struct tog_view *view;
7162 int *pack_fds = NULL;
7164 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7165 switch (ch) {
7166 case 'c':
7167 commit_id_arg = optarg;
7168 break;
7169 case 'r':
7170 repo_path = realpath(optarg, NULL);
7171 if (repo_path == NULL)
7172 return got_error_from_errno2("realpath",
7173 optarg);
7174 break;
7175 default:
7176 usage_tree();
7177 /* NOTREACHED */
7181 argc -= optind;
7182 argv += optind;
7184 if (argc > 1)
7185 usage_tree();
7187 error = got_repo_pack_fds_open(&pack_fds);
7188 if (error != NULL)
7189 goto done;
7191 if (repo_path == NULL) {
7192 cwd = getcwd(NULL, 0);
7193 if (cwd == NULL)
7194 return got_error_from_errno("getcwd");
7195 error = got_worktree_open(&worktree, cwd);
7196 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7197 goto done;
7198 if (worktree)
7199 repo_path =
7200 strdup(got_worktree_get_repo_path(worktree));
7201 else
7202 repo_path = strdup(cwd);
7203 if (repo_path == NULL) {
7204 error = got_error_from_errno("strdup");
7205 goto done;
7209 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7210 if (error != NULL)
7211 goto done;
7213 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7214 repo, worktree);
7215 if (error)
7216 goto done;
7218 init_curses();
7220 error = apply_unveil(got_repo_get_path(repo), NULL);
7221 if (error)
7222 goto done;
7224 error = tog_load_refs(repo, 0);
7225 if (error)
7226 goto done;
7228 if (commit_id_arg == NULL) {
7229 error = got_repo_match_object_id(&commit_id, &label,
7230 worktree ? got_worktree_get_head_ref_name(worktree) :
7231 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7232 if (error)
7233 goto done;
7234 head_ref_name = label;
7235 } else {
7236 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7237 if (error == NULL)
7238 head_ref_name = got_ref_get_name(ref);
7239 else if (error->code != GOT_ERR_NOT_REF)
7240 goto done;
7241 error = got_repo_match_object_id(&commit_id, NULL,
7242 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7243 if (error)
7244 goto done;
7247 error = got_object_open_as_commit(&commit, repo, commit_id);
7248 if (error)
7249 goto done;
7251 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7252 if (view == NULL) {
7253 error = got_error_from_errno("view_open");
7254 goto done;
7256 error = open_tree_view(view, commit_id, head_ref_name, repo);
7257 if (error)
7258 goto done;
7259 if (!got_path_is_root_dir(in_repo_path)) {
7260 error = tree_view_walk_path(&view->state.tree, commit,
7261 in_repo_path);
7262 if (error)
7263 goto done;
7266 if (worktree) {
7267 /* Release work tree lock. */
7268 got_worktree_close(worktree);
7269 worktree = NULL;
7271 error = view_loop(view);
7272 done:
7273 free(repo_path);
7274 free(cwd);
7275 free(commit_id);
7276 free(label);
7277 if (ref)
7278 got_ref_close(ref);
7279 if (repo) {
7280 const struct got_error *close_err = got_repo_close(repo);
7281 if (error == NULL)
7282 error = close_err;
7284 if (pack_fds) {
7285 const struct got_error *pack_err =
7286 got_repo_pack_fds_close(pack_fds);
7287 if (error == NULL)
7288 error = pack_err;
7290 tog_free_refs();
7291 return error;
7294 static const struct got_error *
7295 ref_view_load_refs(struct tog_ref_view_state *s)
7297 struct got_reflist_entry *sre;
7298 struct tog_reflist_entry *re;
7300 s->nrefs = 0;
7301 TAILQ_FOREACH(sre, &tog_refs, entry) {
7302 if (strncmp(got_ref_get_name(sre->ref),
7303 "refs/got/", 9) == 0 &&
7304 strncmp(got_ref_get_name(sre->ref),
7305 "refs/got/backup/", 16) != 0)
7306 continue;
7308 re = malloc(sizeof(*re));
7309 if (re == NULL)
7310 return got_error_from_errno("malloc");
7312 re->ref = got_ref_dup(sre->ref);
7313 if (re->ref == NULL)
7314 return got_error_from_errno("got_ref_dup");
7315 re->idx = s->nrefs++;
7316 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7319 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7320 return NULL;
7323 static void
7324 ref_view_free_refs(struct tog_ref_view_state *s)
7326 struct tog_reflist_entry *re;
7328 while (!TAILQ_EMPTY(&s->refs)) {
7329 re = TAILQ_FIRST(&s->refs);
7330 TAILQ_REMOVE(&s->refs, re, entry);
7331 got_ref_close(re->ref);
7332 free(re);
7336 static const struct got_error *
7337 open_ref_view(struct tog_view *view, struct got_repository *repo)
7339 const struct got_error *err = NULL;
7340 struct tog_ref_view_state *s = &view->state.ref;
7342 s->selected_entry = 0;
7343 s->repo = repo;
7345 TAILQ_INIT(&s->refs);
7346 STAILQ_INIT(&s->colors);
7348 err = ref_view_load_refs(s);
7349 if (err)
7350 return err;
7352 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7353 err = add_color(&s->colors, "^refs/heads/",
7354 TOG_COLOR_REFS_HEADS,
7355 get_color_value("TOG_COLOR_REFS_HEADS"));
7356 if (err)
7357 goto done;
7359 err = add_color(&s->colors, "^refs/tags/",
7360 TOG_COLOR_REFS_TAGS,
7361 get_color_value("TOG_COLOR_REFS_TAGS"));
7362 if (err)
7363 goto done;
7365 err = add_color(&s->colors, "^refs/remotes/",
7366 TOG_COLOR_REFS_REMOTES,
7367 get_color_value("TOG_COLOR_REFS_REMOTES"));
7368 if (err)
7369 goto done;
7371 err = add_color(&s->colors, "^refs/got/backup/",
7372 TOG_COLOR_REFS_BACKUP,
7373 get_color_value("TOG_COLOR_REFS_BACKUP"));
7374 if (err)
7375 goto done;
7378 view->show = show_ref_view;
7379 view->input = input_ref_view;
7380 view->close = close_ref_view;
7381 view->search_start = search_start_ref_view;
7382 view->search_next = search_next_ref_view;
7383 done:
7384 if (err)
7385 free_colors(&s->colors);
7386 return err;
7389 static const struct got_error *
7390 close_ref_view(struct tog_view *view)
7392 struct tog_ref_view_state *s = &view->state.ref;
7394 ref_view_free_refs(s);
7395 free_colors(&s->colors);
7397 return NULL;
7400 static const struct got_error *
7401 resolve_reflist_entry(struct got_object_id **commit_id,
7402 struct tog_reflist_entry *re, struct got_repository *repo)
7404 const struct got_error *err = NULL;
7405 struct got_object_id *obj_id;
7406 struct got_tag_object *tag = NULL;
7407 int obj_type;
7409 *commit_id = NULL;
7411 err = got_ref_resolve(&obj_id, repo, re->ref);
7412 if (err)
7413 return err;
7415 err = got_object_get_type(&obj_type, repo, obj_id);
7416 if (err)
7417 goto done;
7419 switch (obj_type) {
7420 case GOT_OBJ_TYPE_COMMIT:
7421 *commit_id = obj_id;
7422 break;
7423 case GOT_OBJ_TYPE_TAG:
7424 err = got_object_open_as_tag(&tag, repo, obj_id);
7425 if (err)
7426 goto done;
7427 free(obj_id);
7428 err = got_object_get_type(&obj_type, repo,
7429 got_object_tag_get_object_id(tag));
7430 if (err)
7431 goto done;
7432 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7433 err = got_error(GOT_ERR_OBJ_TYPE);
7434 goto done;
7436 *commit_id = got_object_id_dup(
7437 got_object_tag_get_object_id(tag));
7438 if (*commit_id == NULL) {
7439 err = got_error_from_errno("got_object_id_dup");
7440 goto done;
7442 break;
7443 default:
7444 err = got_error(GOT_ERR_OBJ_TYPE);
7445 break;
7448 done:
7449 if (tag)
7450 got_object_tag_close(tag);
7451 if (err) {
7452 free(*commit_id);
7453 *commit_id = NULL;
7455 return err;
7458 static const struct got_error *
7459 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7460 struct tog_reflist_entry *re, struct got_repository *repo)
7462 struct tog_view *log_view;
7463 const struct got_error *err = NULL;
7464 struct got_object_id *commit_id = NULL;
7466 *new_view = NULL;
7468 err = resolve_reflist_entry(&commit_id, re, repo);
7469 if (err) {
7470 if (err->code != GOT_ERR_OBJ_TYPE)
7471 return err;
7472 else
7473 return NULL;
7476 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7477 if (log_view == NULL) {
7478 err = got_error_from_errno("view_open");
7479 goto done;
7482 err = open_log_view(log_view, commit_id, repo,
7483 got_ref_get_name(re->ref), "", 0);
7484 done:
7485 if (err)
7486 view_close(log_view);
7487 else
7488 *new_view = log_view;
7489 free(commit_id);
7490 return err;
7493 static void
7494 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7496 struct tog_reflist_entry *re;
7497 int i = 0;
7499 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7500 return;
7502 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7503 while (i++ < maxscroll) {
7504 if (re == NULL)
7505 break;
7506 s->first_displayed_entry = re;
7507 re = TAILQ_PREV(re, tog_reflist_head, entry);
7511 static const struct got_error *
7512 ref_scroll_down(struct tog_view *view, int maxscroll)
7514 struct tog_ref_view_state *s = &view->state.ref;
7515 struct tog_reflist_entry *next, *last;
7516 int n = 0;
7518 if (s->first_displayed_entry)
7519 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7520 else
7521 next = TAILQ_FIRST(&s->refs);
7523 last = s->last_displayed_entry;
7524 while (next && n++ < maxscroll) {
7525 if (last) {
7526 s->last_displayed_entry = last;
7527 last = TAILQ_NEXT(last, entry);
7529 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7530 s->first_displayed_entry = next;
7531 next = TAILQ_NEXT(next, entry);
7535 return NULL;
7538 static const struct got_error *
7539 search_start_ref_view(struct tog_view *view)
7541 struct tog_ref_view_state *s = &view->state.ref;
7543 s->matched_entry = NULL;
7544 return NULL;
7547 static int
7548 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7550 regmatch_t regmatch;
7552 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7553 0) == 0;
7556 static const struct got_error *
7557 search_next_ref_view(struct tog_view *view)
7559 struct tog_ref_view_state *s = &view->state.ref;
7560 struct tog_reflist_entry *re = NULL;
7562 if (!view->searching) {
7563 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7564 return NULL;
7567 if (s->matched_entry) {
7568 if (view->searching == TOG_SEARCH_FORWARD) {
7569 if (s->selected_entry)
7570 re = TAILQ_NEXT(s->selected_entry, entry);
7571 else
7572 re = TAILQ_PREV(s->selected_entry,
7573 tog_reflist_head, entry);
7574 } else {
7575 if (s->selected_entry == NULL)
7576 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7577 else
7578 re = TAILQ_PREV(s->selected_entry,
7579 tog_reflist_head, entry);
7581 } else {
7582 if (s->selected_entry)
7583 re = s->selected_entry;
7584 else if (view->searching == TOG_SEARCH_FORWARD)
7585 re = TAILQ_FIRST(&s->refs);
7586 else
7587 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7590 while (1) {
7591 if (re == NULL) {
7592 if (s->matched_entry == NULL) {
7593 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7594 return NULL;
7596 if (view->searching == TOG_SEARCH_FORWARD)
7597 re = TAILQ_FIRST(&s->refs);
7598 else
7599 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7602 if (match_reflist_entry(re, &view->regex)) {
7603 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7604 s->matched_entry = re;
7605 break;
7608 if (view->searching == TOG_SEARCH_FORWARD)
7609 re = TAILQ_NEXT(re, entry);
7610 else
7611 re = TAILQ_PREV(re, tog_reflist_head, entry);
7614 if (s->matched_entry) {
7615 s->first_displayed_entry = s->matched_entry;
7616 s->selected = 0;
7619 return NULL;
7622 static const struct got_error *
7623 show_ref_view(struct tog_view *view)
7625 const struct got_error *err = NULL;
7626 struct tog_ref_view_state *s = &view->state.ref;
7627 struct tog_reflist_entry *re;
7628 char *line = NULL;
7629 wchar_t *wline;
7630 struct tog_color *tc;
7631 int width, n;
7632 int limit = view->nlines;
7634 werase(view->window);
7636 s->ndisplayed = 0;
7637 if (view_is_hsplit_top(view))
7638 --limit; /* border */
7640 if (limit == 0)
7641 return NULL;
7643 re = s->first_displayed_entry;
7645 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7646 s->nrefs) == -1)
7647 return got_error_from_errno("asprintf");
7649 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7650 if (err) {
7651 free(line);
7652 return err;
7654 if (view_needs_focus_indication(view))
7655 wstandout(view->window);
7656 waddwstr(view->window, wline);
7657 while (width++ < view->ncols)
7658 waddch(view->window, ' ');
7659 if (view_needs_focus_indication(view))
7660 wstandend(view->window);
7661 free(wline);
7662 wline = NULL;
7663 free(line);
7664 line = NULL;
7665 if (--limit <= 0)
7666 return NULL;
7668 n = 0;
7669 while (re && limit > 0) {
7670 char *line = NULL;
7671 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7673 if (s->show_date) {
7674 struct got_commit_object *ci;
7675 struct got_tag_object *tag;
7676 struct got_object_id *id;
7677 struct tm tm;
7678 time_t t;
7680 err = got_ref_resolve(&id, s->repo, re->ref);
7681 if (err)
7682 return err;
7683 err = got_object_open_as_tag(&tag, s->repo, id);
7684 if (err) {
7685 if (err->code != GOT_ERR_OBJ_TYPE) {
7686 free(id);
7687 return err;
7689 err = got_object_open_as_commit(&ci, s->repo,
7690 id);
7691 if (err) {
7692 free(id);
7693 return err;
7695 t = got_object_commit_get_committer_time(ci);
7696 got_object_commit_close(ci);
7697 } else {
7698 t = got_object_tag_get_tagger_time(tag);
7699 got_object_tag_close(tag);
7701 free(id);
7702 if (gmtime_r(&t, &tm) == NULL)
7703 return got_error_from_errno("gmtime_r");
7704 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7705 return got_error(GOT_ERR_NO_SPACE);
7707 if (got_ref_is_symbolic(re->ref)) {
7708 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7709 ymd : "", got_ref_get_name(re->ref),
7710 got_ref_get_symref_target(re->ref)) == -1)
7711 return got_error_from_errno("asprintf");
7712 } else if (s->show_ids) {
7713 struct got_object_id *id;
7714 char *id_str;
7715 err = got_ref_resolve(&id, s->repo, re->ref);
7716 if (err)
7717 return err;
7718 err = got_object_id_str(&id_str, id);
7719 if (err) {
7720 free(id);
7721 return err;
7723 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7724 got_ref_get_name(re->ref), id_str) == -1) {
7725 err = got_error_from_errno("asprintf");
7726 free(id);
7727 free(id_str);
7728 return err;
7730 free(id);
7731 free(id_str);
7732 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7733 got_ref_get_name(re->ref)) == -1)
7734 return got_error_from_errno("asprintf");
7736 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7737 0, 0);
7738 if (err) {
7739 free(line);
7740 return err;
7742 if (n == s->selected) {
7743 if (view->focussed)
7744 wstandout(view->window);
7745 s->selected_entry = re;
7747 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7748 if (tc)
7749 wattr_on(view->window,
7750 COLOR_PAIR(tc->colorpair), NULL);
7751 waddwstr(view->window, wline);
7752 if (tc)
7753 wattr_off(view->window,
7754 COLOR_PAIR(tc->colorpair), NULL);
7755 if (width < view->ncols - 1)
7756 waddch(view->window, '\n');
7757 if (n == s->selected && view->focussed)
7758 wstandend(view->window);
7759 free(line);
7760 free(wline);
7761 wline = NULL;
7762 n++;
7763 s->ndisplayed++;
7764 s->last_displayed_entry = re;
7766 limit--;
7767 re = TAILQ_NEXT(re, entry);
7770 view_border(view);
7771 return err;
7774 static const struct got_error *
7775 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7776 struct tog_reflist_entry *re, struct got_repository *repo)
7778 const struct got_error *err = NULL;
7779 struct got_object_id *commit_id = NULL;
7780 struct tog_view *tree_view;
7782 *new_view = NULL;
7784 err = resolve_reflist_entry(&commit_id, re, repo);
7785 if (err) {
7786 if (err->code != GOT_ERR_OBJ_TYPE)
7787 return err;
7788 else
7789 return NULL;
7793 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7794 if (tree_view == NULL) {
7795 err = got_error_from_errno("view_open");
7796 goto done;
7799 err = open_tree_view(tree_view, commit_id,
7800 got_ref_get_name(re->ref), repo);
7801 if (err)
7802 goto done;
7804 *new_view = tree_view;
7805 done:
7806 free(commit_id);
7807 return err;
7810 static const struct got_error *
7811 ref_goto_line(struct tog_view *view, int nlines)
7813 const struct got_error *err = NULL;
7814 struct tog_ref_view_state *s = &view->state.ref;
7815 int g, idx = s->selected_entry->idx;
7817 g = view->gline;
7818 view->gline = 0;
7820 if (g == 0)
7821 g = 1;
7822 else if (g > s->nrefs)
7823 g = s->nrefs;
7825 if (g >= s->first_displayed_entry->idx + 1 &&
7826 g <= s->last_displayed_entry->idx + 1 &&
7827 g - s->first_displayed_entry->idx - 1 < nlines) {
7828 s->selected = g - s->first_displayed_entry->idx - 1;
7829 return NULL;
7832 if (idx + 1 < g) {
7833 err = ref_scroll_down(view, g - idx - 1);
7834 if (err)
7835 return err;
7836 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
7837 s->first_displayed_entry->idx + s->selected < g &&
7838 s->selected < s->ndisplayed - 1)
7839 s->selected = g - s->first_displayed_entry->idx - 1;
7840 } else if (idx + 1 > g)
7841 ref_scroll_up(s, idx - g + 1);
7843 if (g < nlines && s->first_displayed_entry->idx == 0)
7844 s->selected = g - 1;
7846 return NULL;
7850 static const struct got_error *
7851 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7853 const struct got_error *err = NULL;
7854 struct tog_ref_view_state *s = &view->state.ref;
7855 struct tog_reflist_entry *re;
7856 int n, nscroll = view->nlines - 1;
7858 if (view->gline)
7859 return ref_goto_line(view, nscroll);
7861 switch (ch) {
7862 case 'i':
7863 s->show_ids = !s->show_ids;
7864 view->count = 0;
7865 break;
7866 case 'm':
7867 s->show_date = !s->show_date;
7868 view->count = 0;
7869 break;
7870 case 'o':
7871 s->sort_by_date = !s->sort_by_date;
7872 view->count = 0;
7873 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7874 got_ref_cmp_by_commit_timestamp_descending :
7875 tog_ref_cmp_by_name, s->repo);
7876 if (err)
7877 break;
7878 got_reflist_object_id_map_free(tog_refs_idmap);
7879 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7880 &tog_refs, s->repo);
7881 if (err)
7882 break;
7883 ref_view_free_refs(s);
7884 err = ref_view_load_refs(s);
7885 break;
7886 case KEY_ENTER:
7887 case '\r':
7888 view->count = 0;
7889 if (!s->selected_entry)
7890 break;
7891 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7892 break;
7893 case 'T':
7894 view->count = 0;
7895 if (!s->selected_entry)
7896 break;
7897 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7898 break;
7899 case 'g':
7900 case KEY_HOME:
7901 s->selected = 0;
7902 view->count = 0;
7903 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7904 break;
7905 case 'G':
7906 case KEY_END: {
7907 int eos = view->nlines - 1;
7909 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7910 --eos; /* border */
7911 s->selected = 0;
7912 view->count = 0;
7913 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7914 for (n = 0; n < eos; n++) {
7915 if (re == NULL)
7916 break;
7917 s->first_displayed_entry = re;
7918 re = TAILQ_PREV(re, tog_reflist_head, entry);
7920 if (n > 0)
7921 s->selected = n - 1;
7922 break;
7924 case 'k':
7925 case KEY_UP:
7926 case CTRL('p'):
7927 if (s->selected > 0) {
7928 s->selected--;
7929 break;
7931 ref_scroll_up(s, 1);
7932 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7933 view->count = 0;
7934 break;
7935 case CTRL('u'):
7936 case 'u':
7937 nscroll /= 2;
7938 /* FALL THROUGH */
7939 case KEY_PPAGE:
7940 case CTRL('b'):
7941 case 'b':
7942 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7943 s->selected -= MIN(nscroll, s->selected);
7944 ref_scroll_up(s, MAX(0, nscroll));
7945 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7946 view->count = 0;
7947 break;
7948 case 'j':
7949 case KEY_DOWN:
7950 case CTRL('n'):
7951 if (s->selected < s->ndisplayed - 1) {
7952 s->selected++;
7953 break;
7955 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7956 /* can't scroll any further */
7957 view->count = 0;
7958 break;
7960 ref_scroll_down(view, 1);
7961 break;
7962 case CTRL('d'):
7963 case 'd':
7964 nscroll /= 2;
7965 /* FALL THROUGH */
7966 case KEY_NPAGE:
7967 case CTRL('f'):
7968 case 'f':
7969 case ' ':
7970 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7971 /* can't scroll any further; move cursor down */
7972 if (s->selected < s->ndisplayed - 1)
7973 s->selected += MIN(nscroll,
7974 s->ndisplayed - s->selected - 1);
7975 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7976 s->selected += s->ndisplayed - s->selected - 1;
7977 view->count = 0;
7978 break;
7980 ref_scroll_down(view, nscroll);
7981 break;
7982 case CTRL('l'):
7983 view->count = 0;
7984 tog_free_refs();
7985 err = tog_load_refs(s->repo, s->sort_by_date);
7986 if (err)
7987 break;
7988 ref_view_free_refs(s);
7989 err = ref_view_load_refs(s);
7990 break;
7991 case KEY_RESIZE:
7992 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7993 s->selected = view->nlines - 2;
7994 break;
7995 default:
7996 view->count = 0;
7997 break;
8000 return err;
8003 __dead static void
8004 usage_ref(void)
8006 endwin();
8007 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8008 getprogname());
8009 exit(1);
8012 static const struct got_error *
8013 cmd_ref(int argc, char *argv[])
8015 const struct got_error *error;
8016 struct got_repository *repo = NULL;
8017 struct got_worktree *worktree = NULL;
8018 char *cwd = NULL, *repo_path = NULL;
8019 int ch;
8020 struct tog_view *view;
8021 int *pack_fds = NULL;
8023 while ((ch = getopt(argc, argv, "r:")) != -1) {
8024 switch (ch) {
8025 case 'r':
8026 repo_path = realpath(optarg, NULL);
8027 if (repo_path == NULL)
8028 return got_error_from_errno2("realpath",
8029 optarg);
8030 break;
8031 default:
8032 usage_ref();
8033 /* NOTREACHED */
8037 argc -= optind;
8038 argv += optind;
8040 if (argc > 1)
8041 usage_ref();
8043 error = got_repo_pack_fds_open(&pack_fds);
8044 if (error != NULL)
8045 goto done;
8047 if (repo_path == NULL) {
8048 cwd = getcwd(NULL, 0);
8049 if (cwd == NULL)
8050 return got_error_from_errno("getcwd");
8051 error = got_worktree_open(&worktree, cwd);
8052 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8053 goto done;
8054 if (worktree)
8055 repo_path =
8056 strdup(got_worktree_get_repo_path(worktree));
8057 else
8058 repo_path = strdup(cwd);
8059 if (repo_path == NULL) {
8060 error = got_error_from_errno("strdup");
8061 goto done;
8065 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8066 if (error != NULL)
8067 goto done;
8069 init_curses();
8071 error = apply_unveil(got_repo_get_path(repo), NULL);
8072 if (error)
8073 goto done;
8075 error = tog_load_refs(repo, 0);
8076 if (error)
8077 goto done;
8079 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8080 if (view == NULL) {
8081 error = got_error_from_errno("view_open");
8082 goto done;
8085 error = open_ref_view(view, repo);
8086 if (error)
8087 goto done;
8089 if (worktree) {
8090 /* Release work tree lock. */
8091 got_worktree_close(worktree);
8092 worktree = NULL;
8094 error = view_loop(view);
8095 done:
8096 free(repo_path);
8097 free(cwd);
8098 if (repo) {
8099 const struct got_error *close_err = got_repo_close(repo);
8100 if (close_err)
8101 error = close_err;
8103 if (pack_fds) {
8104 const struct got_error *pack_err =
8105 got_repo_pack_fds_close(pack_fds);
8106 if (error == NULL)
8107 error = pack_err;
8109 tog_free_refs();
8110 return error;
8113 static const struct got_error *
8114 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8115 enum tog_view_type request, int y, int x)
8117 const struct got_error *err = NULL;
8119 *new_view = NULL;
8121 switch (request) {
8122 case TOG_VIEW_DIFF:
8123 if (view->type == TOG_VIEW_LOG) {
8124 struct tog_log_view_state *s = &view->state.log;
8126 err = open_diff_view_for_commit(new_view, y, x,
8127 s->selected_entry->commit, s->selected_entry->id,
8128 view, s->repo);
8129 } else
8130 return got_error_msg(GOT_ERR_NOT_IMPL,
8131 "parent/child view pair not supported");
8132 break;
8133 case TOG_VIEW_BLAME:
8134 if (view->type == TOG_VIEW_TREE) {
8135 struct tog_tree_view_state *s = &view->state.tree;
8137 err = blame_tree_entry(new_view, y, x,
8138 s->selected_entry, &s->parents, s->commit_id,
8139 s->repo);
8140 } else
8141 return got_error_msg(GOT_ERR_NOT_IMPL,
8142 "parent/child view pair not supported");
8143 break;
8144 case TOG_VIEW_LOG:
8145 if (view->type == TOG_VIEW_BLAME)
8146 err = log_annotated_line(new_view, y, x,
8147 view->state.blame.repo, view->state.blame.id_to_log);
8148 else if (view->type == TOG_VIEW_TREE)
8149 err = log_selected_tree_entry(new_view, y, x,
8150 &view->state.tree);
8151 else if (view->type == TOG_VIEW_REF)
8152 err = log_ref_entry(new_view, y, x,
8153 view->state.ref.selected_entry,
8154 view->state.ref.repo);
8155 else
8156 return got_error_msg(GOT_ERR_NOT_IMPL,
8157 "parent/child view pair not supported");
8158 break;
8159 case TOG_VIEW_TREE:
8160 if (view->type == TOG_VIEW_LOG)
8161 err = browse_commit_tree(new_view, y, x,
8162 view->state.log.selected_entry,
8163 view->state.log.in_repo_path,
8164 view->state.log.head_ref_name,
8165 view->state.log.repo);
8166 else if (view->type == TOG_VIEW_REF)
8167 err = browse_ref_tree(new_view, y, x,
8168 view->state.ref.selected_entry,
8169 view->state.ref.repo);
8170 else
8171 return got_error_msg(GOT_ERR_NOT_IMPL,
8172 "parent/child view pair not supported");
8173 break;
8174 case TOG_VIEW_REF:
8175 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8176 if (*new_view == NULL)
8177 return got_error_from_errno("view_open");
8178 if (view->type == TOG_VIEW_LOG)
8179 err = open_ref_view(*new_view, view->state.log.repo);
8180 else if (view->type == TOG_VIEW_TREE)
8181 err = open_ref_view(*new_view, view->state.tree.repo);
8182 else
8183 err = got_error_msg(GOT_ERR_NOT_IMPL,
8184 "parent/child view pair not supported");
8185 if (err)
8186 view_close(*new_view);
8187 break;
8188 default:
8189 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8192 return err;
8196 * If view was scrolled down to move the selected line into view when opening a
8197 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8199 static void
8200 offset_selection_up(struct tog_view *view)
8202 switch (view->type) {
8203 case TOG_VIEW_BLAME: {
8204 struct tog_blame_view_state *s = &view->state.blame;
8205 if (s->first_displayed_line == 1) {
8206 s->selected_line = MAX(s->selected_line - view->offset,
8207 1);
8208 break;
8210 if (s->first_displayed_line > view->offset)
8211 s->first_displayed_line -= view->offset;
8212 else
8213 s->first_displayed_line = 1;
8214 s->selected_line += view->offset;
8215 break;
8217 case TOG_VIEW_LOG:
8218 log_scroll_up(&view->state.log, view->offset);
8219 view->state.log.selected += view->offset;
8220 break;
8221 case TOG_VIEW_REF:
8222 ref_scroll_up(&view->state.ref, view->offset);
8223 view->state.ref.selected += view->offset;
8224 break;
8225 case TOG_VIEW_TREE:
8226 tree_scroll_up(&view->state.tree, view->offset);
8227 view->state.tree.selected += view->offset;
8228 break;
8229 default:
8230 break;
8233 view->offset = 0;
8237 * If the selected line is in the section of screen covered by the bottom split,
8238 * scroll down offset lines to move it into view and index its new position.
8240 static const struct got_error *
8241 offset_selection_down(struct tog_view *view)
8243 const struct got_error *err = NULL;
8244 const struct got_error *(*scrolld)(struct tog_view *, int);
8245 int *selected = NULL;
8246 int header, offset;
8248 switch (view->type) {
8249 case TOG_VIEW_BLAME: {
8250 struct tog_blame_view_state *s = &view->state.blame;
8251 header = 3;
8252 scrolld = NULL;
8253 if (s->selected_line > view->nlines - header) {
8254 offset = abs(view->nlines - s->selected_line - header);
8255 s->first_displayed_line += offset;
8256 s->selected_line -= offset;
8257 view->offset = offset;
8259 break;
8261 case TOG_VIEW_LOG: {
8262 struct tog_log_view_state *s = &view->state.log;
8263 scrolld = &log_scroll_down;
8264 header = view_is_parent_view(view) ? 3 : 2;
8265 selected = &s->selected;
8266 break;
8268 case TOG_VIEW_REF: {
8269 struct tog_ref_view_state *s = &view->state.ref;
8270 scrolld = &ref_scroll_down;
8271 header = 3;
8272 selected = &s->selected;
8273 break;
8275 case TOG_VIEW_TREE: {
8276 struct tog_tree_view_state *s = &view->state.tree;
8277 scrolld = &tree_scroll_down;
8278 header = 5;
8279 selected = &s->selected;
8280 break;
8282 default:
8283 selected = NULL;
8284 scrolld = NULL;
8285 header = 0;
8286 break;
8289 if (selected && *selected > view->nlines - header) {
8290 offset = abs(view->nlines - *selected - header);
8291 view->offset = offset;
8292 if (scrolld && offset) {
8293 err = scrolld(view, offset);
8294 *selected -= offset;
8298 return err;
8301 static void
8302 list_commands(FILE *fp)
8304 size_t i;
8306 fprintf(fp, "commands:");
8307 for (i = 0; i < nitems(tog_commands); i++) {
8308 const struct tog_cmd *cmd = &tog_commands[i];
8309 fprintf(fp, " %s", cmd->name);
8311 fputc('\n', fp);
8314 __dead static void
8315 usage(int hflag, int status)
8317 FILE *fp = (status == 0) ? stdout : stderr;
8319 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8320 getprogname());
8321 if (hflag) {
8322 fprintf(fp, "lazy usage: %s path\n", getprogname());
8323 list_commands(fp);
8325 exit(status);
8328 static char **
8329 make_argv(int argc, ...)
8331 va_list ap;
8332 char **argv;
8333 int i;
8335 va_start(ap, argc);
8337 argv = calloc(argc, sizeof(char *));
8338 if (argv == NULL)
8339 err(1, "calloc");
8340 for (i = 0; i < argc; i++) {
8341 argv[i] = strdup(va_arg(ap, char *));
8342 if (argv[i] == NULL)
8343 err(1, "strdup");
8346 va_end(ap);
8347 return argv;
8351 * Try to convert 'tog path' into a 'tog log path' command.
8352 * The user could simply have mistyped the command rather than knowingly
8353 * provided a path. So check whether argv[0] can in fact be resolved
8354 * to a path in the HEAD commit and print a special error if not.
8355 * This hack is for mpi@ <3
8357 static const struct got_error *
8358 tog_log_with_path(int argc, char *argv[])
8360 const struct got_error *error = NULL, *close_err;
8361 const struct tog_cmd *cmd = NULL;
8362 struct got_repository *repo = NULL;
8363 struct got_worktree *worktree = NULL;
8364 struct got_object_id *commit_id = NULL, *id = NULL;
8365 struct got_commit_object *commit = NULL;
8366 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8367 char *commit_id_str = NULL, **cmd_argv = NULL;
8368 int *pack_fds = NULL;
8370 cwd = getcwd(NULL, 0);
8371 if (cwd == NULL)
8372 return got_error_from_errno("getcwd");
8374 error = got_repo_pack_fds_open(&pack_fds);
8375 if (error != NULL)
8376 goto done;
8378 error = got_worktree_open(&worktree, cwd);
8379 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8380 goto done;
8382 if (worktree)
8383 repo_path = strdup(got_worktree_get_repo_path(worktree));
8384 else
8385 repo_path = strdup(cwd);
8386 if (repo_path == NULL) {
8387 error = got_error_from_errno("strdup");
8388 goto done;
8391 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8392 if (error != NULL)
8393 goto done;
8395 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8396 repo, worktree);
8397 if (error)
8398 goto done;
8400 error = tog_load_refs(repo, 0);
8401 if (error)
8402 goto done;
8403 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8404 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8405 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8406 if (error)
8407 goto done;
8409 if (worktree) {
8410 got_worktree_close(worktree);
8411 worktree = NULL;
8414 error = got_object_open_as_commit(&commit, repo, commit_id);
8415 if (error)
8416 goto done;
8418 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8419 if (error) {
8420 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8421 goto done;
8422 fprintf(stderr, "%s: '%s' is no known command or path\n",
8423 getprogname(), argv[0]);
8424 usage(1, 1);
8425 /* not reached */
8428 error = got_object_id_str(&commit_id_str, commit_id);
8429 if (error)
8430 goto done;
8432 cmd = &tog_commands[0]; /* log */
8433 argc = 4;
8434 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8435 error = cmd->cmd_main(argc, cmd_argv);
8436 done:
8437 if (repo) {
8438 close_err = got_repo_close(repo);
8439 if (error == NULL)
8440 error = close_err;
8442 if (commit)
8443 got_object_commit_close(commit);
8444 if (worktree)
8445 got_worktree_close(worktree);
8446 if (pack_fds) {
8447 const struct got_error *pack_err =
8448 got_repo_pack_fds_close(pack_fds);
8449 if (error == NULL)
8450 error = pack_err;
8452 free(id);
8453 free(commit_id_str);
8454 free(commit_id);
8455 free(cwd);
8456 free(repo_path);
8457 free(in_repo_path);
8458 if (cmd_argv) {
8459 int i;
8460 for (i = 0; i < argc; i++)
8461 free(cmd_argv[i]);
8462 free(cmd_argv);
8464 tog_free_refs();
8465 return error;
8468 int
8469 main(int argc, char *argv[])
8471 const struct got_error *error = NULL;
8472 const struct tog_cmd *cmd = NULL;
8473 int ch, hflag = 0, Vflag = 0;
8474 char **cmd_argv = NULL;
8475 static const struct option longopts[] = {
8476 { "version", no_argument, NULL, 'V' },
8477 { NULL, 0, NULL, 0}
8479 char *diff_algo_str = NULL;
8481 if (!isatty(STDIN_FILENO))
8482 errx(1, "standard input is not a tty");
8484 setlocale(LC_CTYPE, "");
8486 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8487 switch (ch) {
8488 case 'h':
8489 hflag = 1;
8490 break;
8491 case 'V':
8492 Vflag = 1;
8493 break;
8494 default:
8495 usage(hflag, 1);
8496 /* NOTREACHED */
8500 argc -= optind;
8501 argv += optind;
8502 optind = 1;
8503 optreset = 1;
8505 if (Vflag) {
8506 got_version_print_str();
8507 return 0;
8510 #ifndef PROFILE
8511 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8512 NULL) == -1)
8513 err(1, "pledge");
8514 #endif
8516 if (argc == 0) {
8517 if (hflag)
8518 usage(hflag, 0);
8519 /* Build an argument vector which runs a default command. */
8520 cmd = &tog_commands[0];
8521 argc = 1;
8522 cmd_argv = make_argv(argc, cmd->name);
8523 } else {
8524 size_t i;
8526 /* Did the user specify a command? */
8527 for (i = 0; i < nitems(tog_commands); i++) {
8528 if (strncmp(tog_commands[i].name, argv[0],
8529 strlen(argv[0])) == 0) {
8530 cmd = &tog_commands[i];
8531 break;
8536 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8537 if (diff_algo_str) {
8538 if (strcasecmp(diff_algo_str, "patience") == 0)
8539 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8540 if (strcasecmp(diff_algo_str, "myers") == 0)
8541 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8544 if (cmd == NULL) {
8545 if (argc != 1)
8546 usage(0, 1);
8547 /* No command specified; try log with a path */
8548 error = tog_log_with_path(argc, argv);
8549 } else {
8550 if (hflag)
8551 cmd->cmd_usage();
8552 else
8553 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8556 endwin();
8557 putchar('\n');
8558 if (cmd_argv) {
8559 int i;
8560 for (i = 0; i < argc; i++)
8561 free(cmd_argv[i]);
8562 free(cmd_argv);
8565 if (error && error->code != GOT_ERR_CANCELLED)
8566 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8567 return 0;