Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 };
108 enum tog_view_mode {
109 TOG_VIEW_SPLIT_NONE,
110 TOG_VIEW_SPLIT_VERT,
111 TOG_VIEW_SPLIT_HRZN
112 };
114 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
116 #define TOG_EOF_STRING "(END)"
118 struct commit_queue_entry {
119 TAILQ_ENTRY(commit_queue_entry) entry;
120 struct got_object_id *id;
121 struct got_commit_object *commit;
122 int idx;
123 };
124 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
125 struct commit_queue {
126 int ncommits;
127 struct commit_queue_head head;
128 };
130 struct tog_color {
131 STAILQ_ENTRY(tog_color) entry;
132 regex_t regex;
133 short colorpair;
134 };
135 STAILQ_HEAD(tog_colors, tog_color);
137 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
138 static struct got_reflist_object_id_map *tog_refs_idmap;
139 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
141 static const struct got_error *
142 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
143 struct got_reference* re2)
145 const char *name1 = got_ref_get_name(re1);
146 const char *name2 = got_ref_get_name(re2);
147 int isbackup1, isbackup2;
149 /* Sort backup refs towards the bottom of the list. */
150 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
151 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
152 if (!isbackup1 && isbackup2) {
153 *cmp = -1;
154 return NULL;
155 } else if (isbackup1 && !isbackup2) {
156 *cmp = 1;
157 return NULL;
160 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
161 return NULL;
164 static const struct got_error *
165 tog_load_refs(struct got_repository *repo, int sort_by_date)
167 const struct got_error *err;
169 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
170 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
171 repo);
172 if (err)
173 return err;
175 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
176 repo);
179 static void
180 tog_free_refs(void)
182 if (tog_refs_idmap) {
183 got_reflist_object_id_map_free(tog_refs_idmap);
184 tog_refs_idmap = NULL;
186 got_ref_list_free(&tog_refs);
189 static const struct got_error *
190 add_color(struct tog_colors *colors, const char *pattern,
191 int idx, short color)
193 const struct got_error *err = NULL;
194 struct tog_color *tc;
195 int regerr = 0;
197 if (idx < 1 || idx > COLOR_PAIRS - 1)
198 return NULL;
200 init_pair(idx, color, -1);
202 tc = calloc(1, sizeof(*tc));
203 if (tc == NULL)
204 return got_error_from_errno("calloc");
205 regerr = regcomp(&tc->regex, pattern,
206 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
207 if (regerr) {
208 static char regerr_msg[512];
209 static char err_msg[512];
210 regerror(regerr, &tc->regex, regerr_msg,
211 sizeof(regerr_msg));
212 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
213 regerr_msg);
214 err = got_error_msg(GOT_ERR_REGEX, err_msg);
215 free(tc);
216 return err;
218 tc->colorpair = idx;
219 STAILQ_INSERT_HEAD(colors, tc, entry);
220 return NULL;
223 static void
224 free_colors(struct tog_colors *colors)
226 struct tog_color *tc;
228 while (!STAILQ_EMPTY(colors)) {
229 tc = STAILQ_FIRST(colors);
230 STAILQ_REMOVE_HEAD(colors, entry);
231 regfree(&tc->regex);
232 free(tc);
236 static struct tog_color *
237 get_color(struct tog_colors *colors, int colorpair)
239 struct tog_color *tc = NULL;
241 STAILQ_FOREACH(tc, colors, entry) {
242 if (tc->colorpair == colorpair)
243 return tc;
246 return NULL;
249 static int
250 default_color_value(const char *envvar)
252 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
253 return COLOR_MAGENTA;
254 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
255 return COLOR_CYAN;
256 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
257 return COLOR_YELLOW;
258 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
259 return COLOR_GREEN;
260 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
261 return COLOR_MAGENTA;
262 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
263 return COLOR_MAGENTA;
264 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
265 return COLOR_CYAN;
266 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
267 return COLOR_GREEN;
268 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
269 return COLOR_GREEN;
270 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
271 return COLOR_CYAN;
272 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
273 return COLOR_YELLOW;
274 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
275 return COLOR_GREEN;
276 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
279 return COLOR_YELLOW;
280 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
281 return COLOR_CYAN;
283 return -1;
286 static int
287 get_color_value(const char *envvar)
289 const char *val = getenv(envvar);
291 if (val == NULL)
292 return default_color_value(envvar);
294 if (strcasecmp(val, "black") == 0)
295 return COLOR_BLACK;
296 if (strcasecmp(val, "red") == 0)
297 return COLOR_RED;
298 if (strcasecmp(val, "green") == 0)
299 return COLOR_GREEN;
300 if (strcasecmp(val, "yellow") == 0)
301 return COLOR_YELLOW;
302 if (strcasecmp(val, "blue") == 0)
303 return COLOR_BLUE;
304 if (strcasecmp(val, "magenta") == 0)
305 return COLOR_MAGENTA;
306 if (strcasecmp(val, "cyan") == 0)
307 return COLOR_CYAN;
308 if (strcasecmp(val, "white") == 0)
309 return COLOR_WHITE;
310 if (strcasecmp(val, "default") == 0)
311 return -1;
313 return default_color_value(envvar);
317 struct tog_diff_view_state {
318 struct got_object_id *id1, *id2;
319 const char *label1, *label2;
320 FILE *f, *f1, *f2;
321 int fd1, fd2;
322 int first_displayed_line;
323 int last_displayed_line;
324 int eof;
325 int diff_context;
326 int ignore_whitespace;
327 int force_text_diff;
328 struct got_repository *repo;
329 struct tog_colors colors;
330 size_t nlines;
331 off_t *line_offsets;
332 int matched_line;
333 int selected_line;
335 /* passed from log or blame view; may be NULL */
336 struct tog_view *parent_view;
337 };
339 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
340 static volatile sig_atomic_t tog_thread_error;
342 struct tog_log_thread_args {
343 pthread_cond_t need_commits;
344 pthread_cond_t commit_loaded;
345 int commits_needed;
346 int load_all;
347 struct got_commit_graph *graph;
348 struct commit_queue *commits;
349 const char *in_repo_path;
350 struct got_object_id *start_id;
351 struct got_repository *repo;
352 int *pack_fds;
353 int log_complete;
354 sig_atomic_t *quit;
355 struct commit_queue_entry **first_displayed_entry;
356 struct commit_queue_entry **selected_entry;
357 int *searching;
358 int *search_next_done;
359 regex_t *regex;
360 };
362 struct tog_log_view_state {
363 struct commit_queue commits;
364 struct commit_queue_entry *first_displayed_entry;
365 struct commit_queue_entry *last_displayed_entry;
366 struct commit_queue_entry *selected_entry;
367 int selected;
368 char *in_repo_path;
369 char *head_ref_name;
370 int log_branches;
371 struct got_repository *repo;
372 struct got_object_id *start_id;
373 sig_atomic_t quit;
374 pthread_t thread;
375 struct tog_log_thread_args thread_args;
376 struct commit_queue_entry *matched_entry;
377 struct commit_queue_entry *search_entry;
378 struct tog_colors colors;
379 };
381 #define TOG_COLOR_DIFF_MINUS 1
382 #define TOG_COLOR_DIFF_PLUS 2
383 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
384 #define TOG_COLOR_DIFF_META 4
385 #define TOG_COLOR_TREE_SUBMODULE 5
386 #define TOG_COLOR_TREE_SYMLINK 6
387 #define TOG_COLOR_TREE_DIRECTORY 7
388 #define TOG_COLOR_TREE_EXECUTABLE 8
389 #define TOG_COLOR_COMMIT 9
390 #define TOG_COLOR_AUTHOR 10
391 #define TOG_COLOR_DATE 11
392 #define TOG_COLOR_REFS_HEADS 12
393 #define TOG_COLOR_REFS_TAGS 13
394 #define TOG_COLOR_REFS_REMOTES 14
395 #define TOG_COLOR_REFS_BACKUP 15
397 struct tog_blame_cb_args {
398 struct tog_blame_line *lines; /* one per line */
399 int nlines;
401 struct tog_view *view;
402 struct got_object_id *commit_id;
403 int *quit;
404 };
406 struct tog_blame_thread_args {
407 const char *path;
408 struct got_repository *repo;
409 struct tog_blame_cb_args *cb_args;
410 int *complete;
411 got_cancel_cb cancel_cb;
412 void *cancel_arg;
413 };
415 struct tog_blame {
416 FILE *f;
417 off_t filesize;
418 struct tog_blame_line *lines;
419 int nlines;
420 off_t *line_offsets;
421 pthread_t thread;
422 struct tog_blame_thread_args thread_args;
423 struct tog_blame_cb_args cb_args;
424 const char *path;
425 int *pack_fds;
426 };
428 struct tog_blame_view_state {
429 int first_displayed_line;
430 int last_displayed_line;
431 int selected_line;
432 int last_diffed_line;
433 int blame_complete;
434 int eof;
435 int done;
436 struct got_object_id_queue blamed_commits;
437 struct got_object_qid *blamed_commit;
438 char *path;
439 struct got_repository *repo;
440 struct got_object_id *commit_id;
441 struct tog_blame blame;
442 int matched_line;
443 struct tog_colors colors;
444 };
446 struct tog_parent_tree {
447 TAILQ_ENTRY(tog_parent_tree) entry;
448 struct got_tree_object *tree;
449 struct got_tree_entry *first_displayed_entry;
450 struct got_tree_entry *selected_entry;
451 int selected;
452 };
454 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
456 struct tog_tree_view_state {
457 char *tree_label;
458 struct got_object_id *commit_id;/* commit which this tree belongs to */
459 struct got_tree_object *root; /* the commit's root tree entry */
460 struct got_tree_object *tree; /* currently displayed (sub-)tree */
461 struct got_tree_entry *first_displayed_entry;
462 struct got_tree_entry *last_displayed_entry;
463 struct got_tree_entry *selected_entry;
464 int ndisplayed, selected, show_ids;
465 struct tog_parent_trees parents; /* parent trees of current sub-tree */
466 char *head_ref_name;
467 struct got_repository *repo;
468 struct got_tree_entry *matched_entry;
469 struct tog_colors colors;
470 };
472 struct tog_reflist_entry {
473 TAILQ_ENTRY(tog_reflist_entry) entry;
474 struct got_reference *ref;
475 int idx;
476 };
478 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
480 struct tog_ref_view_state {
481 struct tog_reflist_head refs;
482 struct tog_reflist_entry *first_displayed_entry;
483 struct tog_reflist_entry *last_displayed_entry;
484 struct tog_reflist_entry *selected_entry;
485 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
486 struct got_repository *repo;
487 struct tog_reflist_entry *matched_entry;
488 struct tog_colors colors;
489 };
491 /*
492 * We implement two types of views: parent views and child views.
494 * The 'Tab' key switches focus between a parent view and its child view.
495 * Child views are shown side-by-side to their parent view, provided
496 * there is enough screen estate.
498 * When a new view is opened from within a parent view, this new view
499 * becomes a child view of the parent view, replacing any existing child.
501 * When a new view is opened from within a child view, this new view
502 * becomes a parent view which will obscure the views below until the
503 * user quits the new parent view by typing 'q'.
505 * This list of views contains parent views only.
506 * Child views are only pointed to by their parent view.
507 */
508 TAILQ_HEAD(tog_view_list_head, tog_view);
510 struct tog_view {
511 TAILQ_ENTRY(tog_view) entry;
512 WINDOW *window;
513 PANEL *panel;
514 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
515 int resized_y, resized_x; /* begin_y/x based on user resizing */
516 int maxx, x; /* max column and current start column */
517 int lines, cols; /* copies of LINES and COLS */
518 int nscrolled, offset; /* lines scrolled and hsplit line offset */
519 int ch, count; /* current keymap and count prefix */
520 int resized; /* set when in a resize event */
521 int focussed; /* Only set on one parent or child view at a time. */
522 int dying;
523 struct tog_view *parent;
524 struct tog_view *child;
526 /*
527 * This flag is initially set on parent views when a new child view
528 * is created. It gets toggled when the 'Tab' key switches focus
529 * between parent and child.
530 * The flag indicates whether focus should be passed on to our child
531 * view if this parent view gets picked for focus after another parent
532 * view was closed. This prevents child views from losing focus in such
533 * situations.
534 */
535 int focus_child;
537 enum tog_view_mode mode;
538 /* type-specific state */
539 enum tog_view_type type;
540 union {
541 struct tog_diff_view_state diff;
542 struct tog_log_view_state log;
543 struct tog_blame_view_state blame;
544 struct tog_tree_view_state tree;
545 struct tog_ref_view_state ref;
546 } state;
548 const struct got_error *(*show)(struct tog_view *);
549 const struct got_error *(*input)(struct tog_view **,
550 struct tog_view *, int);
551 const struct got_error *(*reset)(struct tog_view *);
552 const struct got_error *(*resize)(struct tog_view *, int);
553 const struct got_error *(*close)(struct tog_view *);
555 const struct got_error *(*search_start)(struct tog_view *);
556 const struct got_error *(*search_next)(struct tog_view *);
557 int search_started;
558 int searching;
559 #define TOG_SEARCH_FORWARD 1
560 #define TOG_SEARCH_BACKWARD 2
561 int search_next_done;
562 #define TOG_SEARCH_HAVE_MORE 1
563 #define TOG_SEARCH_NO_MORE 2
564 #define TOG_SEARCH_HAVE_NONE 3
565 regex_t regex;
566 regmatch_t regmatch;
567 };
569 static const struct got_error *open_diff_view(struct tog_view *,
570 struct got_object_id *, struct got_object_id *,
571 const char *, const char *, int, int, int, struct tog_view *,
572 struct got_repository *);
573 static const struct got_error *show_diff_view(struct tog_view *);
574 static const struct got_error *input_diff_view(struct tog_view **,
575 struct tog_view *, int);
576 static const struct got_error *reset_diff_view(struct tog_view *);
577 static const struct got_error* close_diff_view(struct tog_view *);
578 static const struct got_error *search_start_diff_view(struct tog_view *);
579 static const struct got_error *search_next_diff_view(struct tog_view *);
581 static const struct got_error *open_log_view(struct tog_view *,
582 struct got_object_id *, struct got_repository *,
583 const char *, const char *, int);
584 static const struct got_error * show_log_view(struct tog_view *);
585 static const struct got_error *input_log_view(struct tog_view **,
586 struct tog_view *, int);
587 static const struct got_error *resize_log_view(struct tog_view *, int);
588 static const struct got_error *close_log_view(struct tog_view *);
589 static const struct got_error *search_start_log_view(struct tog_view *);
590 static const struct got_error *search_next_log_view(struct tog_view *);
592 static const struct got_error *open_blame_view(struct tog_view *, char *,
593 struct got_object_id *, struct got_repository *);
594 static const struct got_error *show_blame_view(struct tog_view *);
595 static const struct got_error *input_blame_view(struct tog_view **,
596 struct tog_view *, int);
597 static const struct got_error *reset_blame_view(struct tog_view *);
598 static const struct got_error *close_blame_view(struct tog_view *);
599 static const struct got_error *search_start_blame_view(struct tog_view *);
600 static const struct got_error *search_next_blame_view(struct tog_view *);
602 static const struct got_error *open_tree_view(struct tog_view *,
603 struct got_object_id *, const char *, struct got_repository *);
604 static const struct got_error *show_tree_view(struct tog_view *);
605 static const struct got_error *input_tree_view(struct tog_view **,
606 struct tog_view *, int);
607 static const struct got_error *close_tree_view(struct tog_view *);
608 static const struct got_error *search_start_tree_view(struct tog_view *);
609 static const struct got_error *search_next_tree_view(struct tog_view *);
611 static const struct got_error *open_ref_view(struct tog_view *,
612 struct got_repository *);
613 static const struct got_error *show_ref_view(struct tog_view *);
614 static const struct got_error *input_ref_view(struct tog_view **,
615 struct tog_view *, int);
616 static const struct got_error *close_ref_view(struct tog_view *);
617 static const struct got_error *search_start_ref_view(struct tog_view *);
618 static const struct got_error *search_next_ref_view(struct tog_view *);
620 static volatile sig_atomic_t tog_sigwinch_received;
621 static volatile sig_atomic_t tog_sigpipe_received;
622 static volatile sig_atomic_t tog_sigcont_received;
623 static volatile sig_atomic_t tog_sigint_received;
624 static volatile sig_atomic_t tog_sigterm_received;
626 static void
627 tog_sigwinch(int signo)
629 tog_sigwinch_received = 1;
632 static void
633 tog_sigpipe(int signo)
635 tog_sigpipe_received = 1;
638 static void
639 tog_sigcont(int signo)
641 tog_sigcont_received = 1;
644 static void
645 tog_sigint(int signo)
647 tog_sigint_received = 1;
650 static void
651 tog_sigterm(int signo)
653 tog_sigterm_received = 1;
656 static int
657 tog_fatal_signal_received(void)
659 return (tog_sigpipe_received ||
660 tog_sigint_received || tog_sigint_received);
663 static const struct got_error *
664 view_close(struct tog_view *view)
666 const struct got_error *err = NULL, *child_err = NULL;
668 if (view->child) {
669 child_err = view_close(view->child);
670 view->child = NULL;
672 if (view->close)
673 err = view->close(view);
674 if (view->panel)
675 del_panel(view->panel);
676 if (view->window)
677 delwin(view->window);
678 free(view);
679 return err ? err : child_err;
682 static struct tog_view *
683 view_open(int nlines, int ncols, int begin_y, int begin_x,
684 enum tog_view_type type)
686 struct tog_view *view = calloc(1, sizeof(*view));
688 if (view == NULL)
689 return NULL;
691 view->type = type;
692 view->lines = LINES;
693 view->cols = COLS;
694 view->nlines = nlines ? nlines : LINES - begin_y;
695 view->ncols = ncols ? ncols : COLS - begin_x;
696 view->begin_y = begin_y;
697 view->begin_x = begin_x;
698 view->window = newwin(nlines, ncols, begin_y, begin_x);
699 if (view->window == NULL) {
700 view_close(view);
701 return NULL;
703 view->panel = new_panel(view->window);
704 if (view->panel == NULL ||
705 set_panel_userptr(view->panel, view) != OK) {
706 view_close(view);
707 return NULL;
710 keypad(view->window, TRUE);
711 return view;
714 static int
715 view_split_begin_x(int begin_x)
717 if (begin_x > 0 || COLS < 120)
718 return 0;
719 return (COLS - MAX(COLS / 2, 80));
722 /* XXX Stub till we decide what to do. */
723 static int
724 view_split_begin_y(int lines)
726 return lines * HSPLIT_SCALE;
729 static const struct got_error *view_resize(struct tog_view *);
731 static const struct got_error *
732 view_splitscreen(struct tog_view *view)
734 const struct got_error *err = NULL;
736 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
737 if (view->resized_y && view->resized_y < view->lines)
738 view->begin_y = view->resized_y;
739 else
740 view->begin_y = view_split_begin_y(view->nlines);
741 view->begin_x = 0;
742 } else if (!view->resized) {
743 if (view->resized_x && view->resized_x < view->cols - 1 &&
744 view->cols > 119)
745 view->begin_x = view->resized_x;
746 else
747 view->begin_x = view_split_begin_x(0);
748 view->begin_y = 0;
750 view->nlines = LINES - view->begin_y;
751 view->ncols = COLS - view->begin_x;
752 view->lines = LINES;
753 view->cols = COLS;
754 err = view_resize(view);
755 if (err)
756 return err;
758 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
759 view->parent->nlines = view->begin_y;
761 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
762 return got_error_from_errno("mvwin");
764 return NULL;
767 static const struct got_error *
768 view_fullscreen(struct tog_view *view)
770 const struct got_error *err = NULL;
772 view->begin_x = 0;
773 view->begin_y = view->resized ? view->begin_y : 0;
774 view->nlines = view->resized ? view->nlines : LINES;
775 view->ncols = COLS;
776 view->lines = LINES;
777 view->cols = COLS;
778 err = view_resize(view);
779 if (err)
780 return err;
782 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
783 return got_error_from_errno("mvwin");
785 return NULL;
788 static int
789 view_is_parent_view(struct tog_view *view)
791 return view->parent == NULL;
794 static int
795 view_is_splitscreen(struct tog_view *view)
797 return view->begin_x > 0 || view->begin_y > 0;
800 static int
801 view_is_fullscreen(struct tog_view *view)
803 return view->nlines == LINES && view->ncols == COLS;
806 static int
807 view_is_hsplit_top(struct tog_view *view)
809 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
810 view_is_splitscreen(view->child);
813 static void
814 view_border(struct tog_view *view)
816 PANEL *panel;
817 const struct tog_view *view_above;
819 if (view->parent)
820 return view_border(view->parent);
822 panel = panel_above(view->panel);
823 if (panel == NULL)
824 return;
826 view_above = panel_userptr(panel);
827 if (view->mode == TOG_VIEW_SPLIT_HRZN)
828 mvwhline(view->window, view_above->begin_y - 1,
829 view->begin_x, got_locale_is_utf8() ?
830 ACS_HLINE : '-', view->ncols);
831 else
832 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
833 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
836 static const struct got_error *view_init_hsplit(struct tog_view *, int);
837 static const struct got_error *request_log_commits(struct tog_view *);
838 static const struct got_error *offset_selection_down(struct tog_view *);
839 static void offset_selection_up(struct tog_view *);
840 static void view_get_split(struct tog_view *, int *, int *);
842 static const struct got_error *
843 view_resize(struct tog_view *view)
845 const struct got_error *err = NULL;
846 int dif, nlines, ncols;
848 dif = LINES - view->lines; /* line difference */
850 if (view->lines > LINES)
851 nlines = view->nlines - (view->lines - LINES);
852 else
853 nlines = view->nlines + (LINES - view->lines);
854 if (view->cols > COLS)
855 ncols = view->ncols - (view->cols - COLS);
856 else
857 ncols = view->ncols + (COLS - view->cols);
859 if (view->child) {
860 int hs = view->child->begin_y;
862 if (!view_is_fullscreen(view))
863 view->child->begin_x = view_split_begin_x(view->begin_x);
864 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
865 view->child->begin_x == 0) {
866 ncols = COLS;
868 view_fullscreen(view->child);
869 if (view->child->focussed)
870 show_panel(view->child->panel);
871 else
872 show_panel(view->panel);
873 } else {
874 ncols = view->child->begin_x;
876 view_splitscreen(view->child);
877 show_panel(view->child->panel);
879 /*
880 * XXX This is ugly and needs to be moved into the above
881 * logic but "works" for now and my attempts at moving it
882 * break either 'tab' or 'F' key maps in horizontal splits.
883 */
884 if (hs) {
885 err = view_splitscreen(view->child);
886 if (err)
887 return err;
888 if (dif < 0) { /* top split decreased */
889 err = offset_selection_down(view);
890 if (err)
891 return err;
893 view_border(view);
894 update_panels();
895 doupdate();
896 show_panel(view->child->panel);
897 nlines = view->nlines;
899 } else if (view->parent == NULL)
900 ncols = COLS;
902 if (view->resize && dif > 0) {
903 err = view->resize(view, dif);
904 if (err)
905 return err;
908 if (wresize(view->window, nlines, ncols) == ERR)
909 return got_error_from_errno("wresize");
910 if (replace_panel(view->panel, view->window) == ERR)
911 return got_error_from_errno("replace_panel");
912 wclear(view->window);
914 view->nlines = nlines;
915 view->ncols = ncols;
916 view->lines = LINES;
917 view->cols = COLS;
919 return NULL;
922 static const struct got_error *
923 resize_log_view(struct tog_view *view, int increase)
925 struct tog_log_view_state *s = &view->state.log;
926 const struct got_error *err = NULL;
927 int n = s->selected_entry->idx + view->lines - s->selected;
929 /*
930 * Request commits to account for the increased
931 * height so we have enough to populate the view.
932 */
933 if (s->commits.ncommits < n) {
934 view->nscrolled = n - s->commits.ncommits + increase + 1;
935 err = request_log_commits(view);
938 return err;
941 static void
942 view_adjust_offset(struct tog_view *view, int n)
944 if (n == 0)
945 return;
947 if (view->parent && view->parent->offset) {
948 if (view->parent->offset + n >= 0)
949 view->parent->offset += n;
950 else
951 view->parent->offset = 0;
952 } else if (view->offset) {
953 if (view->offset - n >= 0)
954 view->offset -= n;
955 else
956 view->offset = 0;
960 static const struct got_error *
961 view_resize_split(struct tog_view *view, int resize)
963 const struct got_error *err = NULL;
964 struct tog_view *v = NULL;
966 if (view->parent)
967 v = view->parent;
968 else
969 v = view;
971 if (!v->child || !view_is_splitscreen(v->child))
972 return NULL;
974 v->resized = v->child->resized = resize; /* lock for resize event */
976 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
977 int y = v->child->begin_y;
979 if (v->child->resized_y)
980 v->child->begin_y = v->child->resized_y;
981 if (view->parent)
982 v->child->begin_y -= resize;
983 else
984 v->child->begin_y += resize;
985 if (v->child->begin_y < 3) {
986 view->count = 0;
987 v->child->begin_y = 3;
988 } else if (v->child->begin_y > LINES - 1) {
989 view->count = 0;
990 v->child->begin_y = LINES - 1;
992 v->ncols = COLS;
993 v->child->ncols = COLS;
994 view_adjust_offset(view, resize);
995 err = view_init_hsplit(v, v->child->begin_y);
996 if (err)
997 return err;
998 v->child->resized_y = v->child->begin_y;
999 if (y > v->child->begin_y && v->child->type == TOG_VIEW_LOG)
1000 v->child->nscrolled = y - v->child->begin_y;
1001 else if (y < v->child->begin_y && v->type == TOG_VIEW_LOG)
1002 v->nscrolled = v->child->begin_y - y;
1003 } else {
1004 if (v->child->resized_x)
1005 v->child->begin_x = v->child->resized_x;
1006 if (view->parent)
1007 v->child->begin_x -= resize;
1008 else
1009 v->child->begin_x += resize;
1010 if (v->child->begin_x < 11) {
1011 view->count = 0;
1012 v->child->begin_x = 11;
1013 } else if (v->child->begin_x > COLS - 1) {
1014 view->count = 0;
1015 v->child->begin_x = COLS - 1;
1017 v->child->resized_x = v->child->begin_x;
1020 v->child->mode = v->mode;
1021 v->child->nlines = v->lines - v->child->begin_y;
1022 v->child->ncols = v->cols - v->child->begin_x;
1023 v->focus_child = 1;
1025 err = view_fullscreen(v);
1026 if (err)
1027 return err;
1028 err = view_splitscreen(v->child);
1029 if (err)
1030 return err;
1032 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1033 err = offset_selection_down(v->child);
1034 if (err)
1035 return err;
1038 if (v->nscrolled)
1039 err = request_log_commits(v);
1040 else if (v->child->nscrolled)
1041 err = request_log_commits(v->child);
1043 v->resized = v->child->resized = 0;
1045 return err;
1048 static void
1049 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1051 struct tog_view *v = src->child ? src->child : src;
1053 dst->resized_x = v->resized_x;
1054 dst->resized_y = v->resized_y;
1057 static const struct got_error *
1058 view_close_child(struct tog_view *view)
1060 const struct got_error *err = NULL;
1062 if (view->child == NULL)
1063 return NULL;
1065 err = view_close(view->child);
1066 view->child = NULL;
1067 return err;
1070 static const struct got_error *
1071 view_set_child(struct tog_view *view, struct tog_view *child)
1073 const struct got_error *err = NULL;
1075 view->child = child;
1076 child->parent = view;
1078 err = view_resize(view);
1079 if (err)
1080 return err;
1082 if (view->child->resized_x || view->child->resized_y)
1083 err = view_resize_split(view, 0);
1085 return err;
1088 static void
1089 tog_resizeterm(void)
1091 int cols, lines;
1092 struct winsize size;
1094 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1095 cols = 80; /* Default */
1096 lines = 24;
1097 } else {
1098 cols = size.ws_col;
1099 lines = size.ws_row;
1101 resize_term(lines, cols);
1104 static const struct got_error *
1105 view_search_start(struct tog_view *view)
1107 const struct got_error *err = NULL;
1108 struct tog_view *v = view;
1109 char pattern[1024];
1110 int ret;
1112 if (view->search_started) {
1113 regfree(&view->regex);
1114 view->searching = 0;
1115 memset(&view->regmatch, 0, sizeof(view->regmatch));
1117 view->search_started = 0;
1119 if (view->nlines < 1)
1120 return NULL;
1122 if (view_is_hsplit_top(view))
1123 v = view->child;
1125 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1126 wclrtoeol(v->window);
1128 nodelay(view->window, FALSE); /* block for search term input */
1129 nocbreak();
1130 echo();
1131 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1132 wrefresh(v->window);
1133 cbreak();
1134 noecho();
1135 nodelay(view->window, TRUE);
1136 if (ret == ERR)
1137 return NULL;
1139 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1140 err = view->search_start(view);
1141 if (err) {
1142 regfree(&view->regex);
1143 return err;
1145 view->search_started = 1;
1146 view->searching = TOG_SEARCH_FORWARD;
1147 view->search_next_done = 0;
1148 view->search_next(view);
1151 return NULL;
1154 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1155 static const struct got_error *
1156 switch_split(struct tog_view *view)
1158 const struct got_error *err = NULL;
1159 struct tog_view *v = NULL;
1161 if (view->parent)
1162 v = view->parent;
1163 else
1164 v = view;
1166 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1167 v->mode = TOG_VIEW_SPLIT_VERT;
1168 else
1169 v->mode = TOG_VIEW_SPLIT_HRZN;
1171 if (!v->child)
1172 return NULL;
1173 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1174 v->mode = TOG_VIEW_SPLIT_NONE;
1176 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1177 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1178 v->child->begin_y = v->child->resized_y;
1179 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1180 v->child->begin_x = v->child->resized_x;
1183 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1184 v->ncols = COLS;
1185 v->child->ncols = COLS;
1186 v->child->nscrolled = LINES - v->child->nlines;
1188 err = view_init_hsplit(v, v->child->begin_y);
1189 if (err)
1190 return err;
1192 v->child->mode = v->mode;
1193 v->child->nlines = v->lines - v->child->begin_y;
1194 v->focus_child = 1;
1196 err = view_fullscreen(v);
1197 if (err)
1198 return err;
1199 err = view_splitscreen(v->child);
1200 if (err)
1201 return err;
1203 if (v->mode == TOG_VIEW_SPLIT_NONE)
1204 v->mode = TOG_VIEW_SPLIT_VERT;
1205 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1206 err = offset_selection_down(v);
1207 err = offset_selection_down(v->child);
1208 } else {
1209 offset_selection_up(v);
1210 offset_selection_up(v->child);
1212 if (v->type == TOG_VIEW_LOG && v->nscrolled)
1213 err = request_log_commits(v);
1214 else if (v->child->type == TOG_VIEW_LOG && v->child->nscrolled)
1215 err = request_log_commits(v->child);
1217 return err;
1221 * Compute view->count from numeric input. Assign total to view->count and
1222 * return first non-numeric key entered.
1224 static int
1225 get_compound_key(struct tog_view *view, int c)
1227 struct tog_view *v = view;
1228 int x, n = 0;
1230 if (view_is_hsplit_top(view))
1231 v = view->child;
1232 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1233 v = view->parent;
1235 view->count = 0;
1236 cbreak(); /* block for input */
1237 wmove(v->window, v->nlines - 1, 0);
1238 wclrtoeol(v->window);
1239 waddch(v->window, ':');
1241 do {
1242 x = getcurx(v->window);
1243 if (x != ERR && x < view->ncols) {
1244 waddch(v->window, c);
1245 wrefresh(v->window);
1249 * Don't overflow. Max valid request should be the greatest
1250 * between the longest and total lines; cap at 10 million.
1252 if (n >= 9999999)
1253 n = 9999999;
1254 else
1255 n = n * 10 + (c - '0');
1256 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1258 /* Massage excessive or inapplicable values at the input handler. */
1259 view->count = n;
1261 return c;
1264 static const struct got_error *
1265 view_input(struct tog_view **new, int *done, struct tog_view *view,
1266 struct tog_view_list_head *views)
1268 const struct got_error *err = NULL;
1269 struct tog_view *v;
1270 int ch, errcode;
1272 *new = NULL;
1274 /* Clear "no matches" indicator. */
1275 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1276 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1277 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1278 view->count = 0;
1281 if (view->searching && !view->search_next_done) {
1282 errcode = pthread_mutex_unlock(&tog_mutex);
1283 if (errcode)
1284 return got_error_set_errno(errcode,
1285 "pthread_mutex_unlock");
1286 sched_yield();
1287 errcode = pthread_mutex_lock(&tog_mutex);
1288 if (errcode)
1289 return got_error_set_errno(errcode,
1290 "pthread_mutex_lock");
1291 view->search_next(view);
1292 return NULL;
1295 nodelay(view->window, FALSE);
1296 /* Allow threads to make progress while we are waiting for input. */
1297 errcode = pthread_mutex_unlock(&tog_mutex);
1298 if (errcode)
1299 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1300 /* If we have an unfinished count, let C-g or backspace abort. */
1301 if (view->count && --view->count) {
1302 cbreak();
1303 nodelay(view->window, TRUE);
1304 ch = wgetch(view->window);
1305 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1306 view->count = 0;
1307 else
1308 ch = view->ch;
1309 } else {
1310 ch = wgetch(view->window);
1311 if (ch >= '1' && ch <= '9')
1312 view->ch = ch = get_compound_key(view, ch);
1314 errcode = pthread_mutex_lock(&tog_mutex);
1315 if (errcode)
1316 return got_error_set_errno(errcode, "pthread_mutex_lock");
1317 nodelay(view->window, TRUE);
1319 if (tog_sigwinch_received || tog_sigcont_received) {
1320 tog_resizeterm();
1321 tog_sigwinch_received = 0;
1322 tog_sigcont_received = 0;
1323 TAILQ_FOREACH(v, views, entry) {
1324 err = view_resize(v);
1325 if (err)
1326 return err;
1327 err = v->input(new, v, KEY_RESIZE);
1328 if (err)
1329 return err;
1330 if (v->child) {
1331 err = view_resize(v->child);
1332 if (err)
1333 return err;
1334 err = v->child->input(new, v->child,
1335 KEY_RESIZE);
1336 if (err)
1337 return err;
1338 if (v->child->resized_x || v->child->resized_y) {
1339 err = view_resize_split(v, 0);
1340 if (err)
1341 return err;
1347 switch (ch) {
1348 case '\t':
1349 view->count = 0;
1350 if (view->child) {
1351 view->focussed = 0;
1352 view->child->focussed = 1;
1353 view->focus_child = 1;
1354 } else if (view->parent) {
1355 view->focussed = 0;
1356 view->parent->focussed = 1;
1357 view->parent->focus_child = 0;
1358 if (!view_is_splitscreen(view)) {
1359 if (view->mode == TOG_VIEW_SPLIT_HRZN &&
1360 view->parent->type == TOG_VIEW_LOG) {
1361 err = request_log_commits(view->parent);
1362 if (err)
1363 return err;
1365 offset_selection_up(view->parent);
1366 err = view_fullscreen(view->parent);
1367 if (err)
1368 return err;
1371 break;
1372 case 'q':
1373 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1374 if (view->parent->type == TOG_VIEW_LOG) {
1375 /* might need more commits to fill fullscreen */
1376 err = request_log_commits(view->parent);
1377 if (err)
1378 break;
1380 offset_selection_up(view->parent);
1382 err = view->input(new, view, ch);
1383 view->dying = 1;
1384 break;
1385 case 'Q':
1386 *done = 1;
1387 break;
1388 case 'F':
1389 view->count = 0;
1390 if (view_is_parent_view(view)) {
1391 if (view->child == NULL)
1392 break;
1393 if (view_is_splitscreen(view->child)) {
1394 view->focussed = 0;
1395 view->child->focussed = 1;
1396 err = view_fullscreen(view->child);
1397 } else {
1398 err = view_splitscreen(view->child);
1399 if (!err)
1400 err = view_resize_split(view, 0);
1402 if (err)
1403 break;
1404 err = view->child->input(new, view->child,
1405 KEY_RESIZE);
1406 } else {
1407 if (view_is_splitscreen(view)) {
1408 view->parent->focussed = 0;
1409 view->focussed = 1;
1410 err = view_fullscreen(view);
1411 } else {
1412 err = view_splitscreen(view);
1413 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1414 err = view_resize(view->parent);
1415 if (!err)
1416 err = view_resize_split(view, 0);
1418 if (err)
1419 break;
1420 err = view->input(new, view, KEY_RESIZE);
1422 if (err)
1423 break;
1424 if (view->type == TOG_VIEW_LOG) {
1425 err = request_log_commits(view);
1426 if (err)
1427 break;
1429 if (view->parent)
1430 err = offset_selection_down(view->parent);
1431 if (!err)
1432 err = offset_selection_down(view);
1433 break;
1434 case 'S':
1435 view->count = 0;
1436 err = switch_split(view);
1437 break;
1438 case '-':
1439 err = view_resize_split(view, -1);
1440 break;
1441 case '+':
1442 err = view_resize_split(view, 1);
1443 break;
1444 case KEY_RESIZE:
1445 break;
1446 case '/':
1447 view->count = 0;
1448 if (view->search_start)
1449 view_search_start(view);
1450 else
1451 err = view->input(new, view, ch);
1452 break;
1453 case 'N':
1454 case 'n':
1455 if (view->search_started && view->search_next) {
1456 view->searching = (ch == 'n' ?
1457 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1458 view->search_next_done = 0;
1459 view->search_next(view);
1460 } else
1461 err = view->input(new, view, ch);
1462 break;
1463 case 'A':
1464 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1465 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1466 else
1467 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1468 TAILQ_FOREACH(v, views, entry) {
1469 if (v->reset) {
1470 err = v->reset(v);
1471 if (err)
1472 return err;
1474 if (v->child && v->child->reset) {
1475 err = v->child->reset(v->child);
1476 if (err)
1477 return err;
1480 break;
1481 default:
1482 err = view->input(new, view, ch);
1483 break;
1486 return err;
1489 static int
1490 view_needs_focus_indication(struct tog_view *view)
1492 if (view_is_parent_view(view)) {
1493 if (view->child == NULL || view->child->focussed)
1494 return 0;
1495 if (!view_is_splitscreen(view->child))
1496 return 0;
1497 } else if (!view_is_splitscreen(view))
1498 return 0;
1500 return view->focussed;
1503 static const struct got_error *
1504 view_loop(struct tog_view *view)
1506 const struct got_error *err = NULL;
1507 struct tog_view_list_head views;
1508 struct tog_view *new_view;
1509 char *mode;
1510 int fast_refresh = 10;
1511 int done = 0, errcode;
1513 mode = getenv("TOG_VIEW_SPLIT_MODE");
1514 if (!mode || !(*mode == 'h' || *mode == 'H'))
1515 view->mode = TOG_VIEW_SPLIT_VERT;
1516 else
1517 view->mode = TOG_VIEW_SPLIT_HRZN;
1519 errcode = pthread_mutex_lock(&tog_mutex);
1520 if (errcode)
1521 return got_error_set_errno(errcode, "pthread_mutex_lock");
1523 TAILQ_INIT(&views);
1524 TAILQ_INSERT_HEAD(&views, view, entry);
1526 view->focussed = 1;
1527 err = view->show(view);
1528 if (err)
1529 return err;
1530 update_panels();
1531 doupdate();
1532 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1533 !tog_fatal_signal_received()) {
1534 /* Refresh fast during initialization, then become slower. */
1535 if (fast_refresh && fast_refresh-- == 0)
1536 halfdelay(10); /* switch to once per second */
1538 err = view_input(&new_view, &done, view, &views);
1539 if (err)
1540 break;
1541 if (view->dying) {
1542 struct tog_view *v, *prev = NULL;
1544 if (view_is_parent_view(view))
1545 prev = TAILQ_PREV(view, tog_view_list_head,
1546 entry);
1547 else if (view->parent)
1548 prev = view->parent;
1550 if (view->parent) {
1551 view->parent->child = NULL;
1552 view->parent->focus_child = 0;
1553 /* Restore fullscreen line height. */
1554 view->parent->nlines = view->parent->lines;
1555 err = view_resize(view->parent);
1556 if (err)
1557 break;
1558 /* Make resized splits persist. */
1559 view_transfer_size(view->parent, view);
1560 } else
1561 TAILQ_REMOVE(&views, view, entry);
1563 err = view_close(view);
1564 if (err)
1565 goto done;
1567 view = NULL;
1568 TAILQ_FOREACH(v, &views, entry) {
1569 if (v->focussed)
1570 break;
1572 if (view == NULL && new_view == NULL) {
1573 /* No view has focus. Try to pick one. */
1574 if (prev)
1575 view = prev;
1576 else if (!TAILQ_EMPTY(&views)) {
1577 view = TAILQ_LAST(&views,
1578 tog_view_list_head);
1580 if (view) {
1581 if (view->focus_child) {
1582 view->child->focussed = 1;
1583 view = view->child;
1584 } else
1585 view->focussed = 1;
1589 if (new_view) {
1590 struct tog_view *v, *t;
1591 /* Only allow one parent view per type. */
1592 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1593 if (v->type != new_view->type)
1594 continue;
1595 TAILQ_REMOVE(&views, v, entry);
1596 err = view_close(v);
1597 if (err)
1598 goto done;
1599 break;
1601 TAILQ_INSERT_TAIL(&views, new_view, entry);
1602 view = new_view;
1604 if (view) {
1605 if (view_is_parent_view(view)) {
1606 if (view->child && view->child->focussed)
1607 view = view->child;
1608 } else {
1609 if (view->parent && view->parent->focussed)
1610 view = view->parent;
1612 show_panel(view->panel);
1613 if (view->child && view_is_splitscreen(view->child))
1614 show_panel(view->child->panel);
1615 if (view->parent && view_is_splitscreen(view)) {
1616 err = view->parent->show(view->parent);
1617 if (err)
1618 goto done;
1620 err = view->show(view);
1621 if (err)
1622 goto done;
1623 if (view->child) {
1624 err = view->child->show(view->child);
1625 if (err)
1626 goto done;
1628 update_panels();
1629 doupdate();
1632 done:
1633 while (!TAILQ_EMPTY(&views)) {
1634 const struct got_error *close_err;
1635 view = TAILQ_FIRST(&views);
1636 TAILQ_REMOVE(&views, view, entry);
1637 close_err = view_close(view);
1638 if (close_err && err == NULL)
1639 err = close_err;
1642 errcode = pthread_mutex_unlock(&tog_mutex);
1643 if (errcode && err == NULL)
1644 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1646 return err;
1649 __dead static void
1650 usage_log(void)
1652 endwin();
1653 fprintf(stderr,
1654 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1655 getprogname());
1656 exit(1);
1659 /* Create newly allocated wide-character string equivalent to a byte string. */
1660 static const struct got_error *
1661 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1663 char *vis = NULL;
1664 const struct got_error *err = NULL;
1666 *ws = NULL;
1667 *wlen = mbstowcs(NULL, s, 0);
1668 if (*wlen == (size_t)-1) {
1669 int vislen;
1670 if (errno != EILSEQ)
1671 return got_error_from_errno("mbstowcs");
1673 /* byte string invalid in current encoding; try to "fix" it */
1674 err = got_mbsavis(&vis, &vislen, s);
1675 if (err)
1676 return err;
1677 *wlen = mbstowcs(NULL, vis, 0);
1678 if (*wlen == (size_t)-1) {
1679 err = got_error_from_errno("mbstowcs"); /* give up */
1680 goto done;
1684 *ws = calloc(*wlen + 1, sizeof(**ws));
1685 if (*ws == NULL) {
1686 err = got_error_from_errno("calloc");
1687 goto done;
1690 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1691 err = got_error_from_errno("mbstowcs");
1692 done:
1693 free(vis);
1694 if (err) {
1695 free(*ws);
1696 *ws = NULL;
1697 *wlen = 0;
1699 return err;
1702 static const struct got_error *
1703 expand_tab(char **ptr, const char *src)
1705 char *dst;
1706 size_t len, n, idx = 0, sz = 0;
1708 *ptr = NULL;
1709 n = len = strlen(src);
1710 dst = malloc(n + 1);
1711 if (dst == NULL)
1712 return got_error_from_errno("malloc");
1714 while (idx < len && src[idx]) {
1715 const char c = src[idx];
1717 if (c == '\t') {
1718 size_t nb = TABSIZE - sz % TABSIZE;
1719 char *p;
1721 p = realloc(dst, n + nb);
1722 if (p == NULL) {
1723 free(dst);
1724 return got_error_from_errno("realloc");
1727 dst = p;
1728 n += nb;
1729 memset(dst + sz, ' ', nb);
1730 sz += nb;
1731 } else
1732 dst[sz++] = src[idx];
1733 ++idx;
1736 dst[sz] = '\0';
1737 *ptr = dst;
1738 return NULL;
1742 * Advance at most n columns from wline starting at offset off.
1743 * Return the index to the first character after the span operation.
1744 * Return the combined column width of all spanned wide character in
1745 * *rcol.
1747 static int
1748 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1750 int width, i, cols = 0;
1752 if (n == 0) {
1753 *rcol = cols;
1754 return off;
1757 for (i = off; wline[i] != L'\0'; ++i) {
1758 if (wline[i] == L'\t')
1759 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1760 else
1761 width = wcwidth(wline[i]);
1763 if (width == -1) {
1764 width = 1;
1765 wline[i] = L'.';
1768 if (cols + width > n)
1769 break;
1770 cols += width;
1773 *rcol = cols;
1774 return i;
1778 * Format a line for display, ensuring that it won't overflow a width limit.
1779 * With scrolling, the width returned refers to the scrolled version of the
1780 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1782 static const struct got_error *
1783 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1784 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1786 const struct got_error *err = NULL;
1787 int cols;
1788 wchar_t *wline = NULL;
1789 char *exstr = NULL;
1790 size_t wlen;
1791 int i, scrollx;
1793 *wlinep = NULL;
1794 *widthp = 0;
1796 if (expand) {
1797 err = expand_tab(&exstr, line);
1798 if (err)
1799 return err;
1802 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1803 free(exstr);
1804 if (err)
1805 return err;
1807 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1809 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1810 wline[wlen - 1] = L'\0';
1811 wlen--;
1813 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1814 wline[wlen - 1] = L'\0';
1815 wlen--;
1818 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1819 wline[i] = L'\0';
1821 if (widthp)
1822 *widthp = cols;
1823 if (scrollxp)
1824 *scrollxp = scrollx;
1825 if (err)
1826 free(wline);
1827 else
1828 *wlinep = wline;
1829 return err;
1832 static const struct got_error*
1833 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1834 struct got_object_id *id, struct got_repository *repo)
1836 static const struct got_error *err = NULL;
1837 struct got_reflist_entry *re;
1838 char *s;
1839 const char *name;
1841 *refs_str = NULL;
1843 TAILQ_FOREACH(re, refs, entry) {
1844 struct got_tag_object *tag = NULL;
1845 struct got_object_id *ref_id;
1846 int cmp;
1848 name = got_ref_get_name(re->ref);
1849 if (strcmp(name, GOT_REF_HEAD) == 0)
1850 continue;
1851 if (strncmp(name, "refs/", 5) == 0)
1852 name += 5;
1853 if (strncmp(name, "got/", 4) == 0 &&
1854 strncmp(name, "got/backup/", 11) != 0)
1855 continue;
1856 if (strncmp(name, "heads/", 6) == 0)
1857 name += 6;
1858 if (strncmp(name, "remotes/", 8) == 0) {
1859 name += 8;
1860 s = strstr(name, "/" GOT_REF_HEAD);
1861 if (s != NULL && s[strlen(s)] == '\0')
1862 continue;
1864 err = got_ref_resolve(&ref_id, repo, re->ref);
1865 if (err)
1866 break;
1867 if (strncmp(name, "tags/", 5) == 0) {
1868 err = got_object_open_as_tag(&tag, repo, ref_id);
1869 if (err) {
1870 if (err->code != GOT_ERR_OBJ_TYPE) {
1871 free(ref_id);
1872 break;
1874 /* Ref points at something other than a tag. */
1875 err = NULL;
1876 tag = NULL;
1879 cmp = got_object_id_cmp(tag ?
1880 got_object_tag_get_object_id(tag) : ref_id, id);
1881 free(ref_id);
1882 if (tag)
1883 got_object_tag_close(tag);
1884 if (cmp != 0)
1885 continue;
1886 s = *refs_str;
1887 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1888 s ? ", " : "", name) == -1) {
1889 err = got_error_from_errno("asprintf");
1890 free(s);
1891 *refs_str = NULL;
1892 break;
1894 free(s);
1897 return err;
1900 static const struct got_error *
1901 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1902 int col_tab_align)
1904 char *smallerthan;
1906 smallerthan = strchr(author, '<');
1907 if (smallerthan && smallerthan[1] != '\0')
1908 author = smallerthan + 1;
1909 author[strcspn(author, "@>")] = '\0';
1910 return format_line(wauthor, author_width, NULL, author, 0, limit,
1911 col_tab_align, 0);
1914 static const struct got_error *
1915 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1916 struct got_object_id *id, const size_t date_display_cols,
1917 int author_display_cols)
1919 struct tog_log_view_state *s = &view->state.log;
1920 const struct got_error *err = NULL;
1921 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1922 char *logmsg0 = NULL, *logmsg = NULL;
1923 char *author = NULL;
1924 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1925 int author_width, logmsg_width;
1926 char *newline, *line = NULL;
1927 int col, limit, scrollx;
1928 const int avail = view->ncols;
1929 struct tm tm;
1930 time_t committer_time;
1931 struct tog_color *tc;
1933 committer_time = got_object_commit_get_committer_time(commit);
1934 if (gmtime_r(&committer_time, &tm) == NULL)
1935 return got_error_from_errno("gmtime_r");
1936 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1937 return got_error(GOT_ERR_NO_SPACE);
1939 if (avail <= date_display_cols)
1940 limit = MIN(sizeof(datebuf) - 1, avail);
1941 else
1942 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1943 tc = get_color(&s->colors, TOG_COLOR_DATE);
1944 if (tc)
1945 wattr_on(view->window,
1946 COLOR_PAIR(tc->colorpair), NULL);
1947 waddnstr(view->window, datebuf, limit);
1948 if (tc)
1949 wattr_off(view->window,
1950 COLOR_PAIR(tc->colorpair), NULL);
1951 col = limit;
1952 if (col > avail)
1953 goto done;
1955 if (avail >= 120) {
1956 char *id_str;
1957 err = got_object_id_str(&id_str, id);
1958 if (err)
1959 goto done;
1960 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1961 if (tc)
1962 wattr_on(view->window,
1963 COLOR_PAIR(tc->colorpair), NULL);
1964 wprintw(view->window, "%.8s ", id_str);
1965 if (tc)
1966 wattr_off(view->window,
1967 COLOR_PAIR(tc->colorpair), NULL);
1968 free(id_str);
1969 col += 9;
1970 if (col > avail)
1971 goto done;
1974 author = strdup(got_object_commit_get_author(commit));
1975 if (author == NULL) {
1976 err = got_error_from_errno("strdup");
1977 goto done;
1979 err = format_author(&wauthor, &author_width, author, avail - col, col);
1980 if (err)
1981 goto done;
1982 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1983 if (tc)
1984 wattr_on(view->window,
1985 COLOR_PAIR(tc->colorpair), NULL);
1986 waddwstr(view->window, wauthor);
1987 if (tc)
1988 wattr_off(view->window,
1989 COLOR_PAIR(tc->colorpair), NULL);
1990 col += author_width;
1991 while (col < avail && author_width < author_display_cols + 2) {
1992 waddch(view->window, ' ');
1993 col++;
1994 author_width++;
1996 if (col > avail)
1997 goto done;
1999 err = got_object_commit_get_logmsg(&logmsg0, commit);
2000 if (err)
2001 goto done;
2002 logmsg = logmsg0;
2003 while (*logmsg == '\n')
2004 logmsg++;
2005 newline = strchr(logmsg, '\n');
2006 if (newline)
2007 *newline = '\0';
2008 limit = avail - col;
2009 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2010 limit--; /* for the border */
2011 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2012 limit, col, 1);
2013 if (err)
2014 goto done;
2015 waddwstr(view->window, &wlogmsg[scrollx]);
2016 col += MAX(logmsg_width, 0);
2017 while (col < avail) {
2018 waddch(view->window, ' ');
2019 col++;
2021 done:
2022 free(logmsg0);
2023 free(wlogmsg);
2024 free(author);
2025 free(wauthor);
2026 free(line);
2027 return err;
2030 static struct commit_queue_entry *
2031 alloc_commit_queue_entry(struct got_commit_object *commit,
2032 struct got_object_id *id)
2034 struct commit_queue_entry *entry;
2036 entry = calloc(1, sizeof(*entry));
2037 if (entry == NULL)
2038 return NULL;
2040 entry->id = id;
2041 entry->commit = commit;
2042 return entry;
2045 static void
2046 pop_commit(struct commit_queue *commits)
2048 struct commit_queue_entry *entry;
2050 entry = TAILQ_FIRST(&commits->head);
2051 TAILQ_REMOVE(&commits->head, entry, entry);
2052 got_object_commit_close(entry->commit);
2053 commits->ncommits--;
2054 /* Don't free entry->id! It is owned by the commit graph. */
2055 free(entry);
2058 static void
2059 free_commits(struct commit_queue *commits)
2061 while (!TAILQ_EMPTY(&commits->head))
2062 pop_commit(commits);
2065 static const struct got_error *
2066 match_commit(int *have_match, struct got_object_id *id,
2067 struct got_commit_object *commit, regex_t *regex)
2069 const struct got_error *err = NULL;
2070 regmatch_t regmatch;
2071 char *id_str = NULL, *logmsg = NULL;
2073 *have_match = 0;
2075 err = got_object_id_str(&id_str, id);
2076 if (err)
2077 return err;
2079 err = got_object_commit_get_logmsg(&logmsg, commit);
2080 if (err)
2081 goto done;
2083 if (regexec(regex, got_object_commit_get_author(commit), 1,
2084 &regmatch, 0) == 0 ||
2085 regexec(regex, got_object_commit_get_committer(commit), 1,
2086 &regmatch, 0) == 0 ||
2087 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2088 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2089 *have_match = 1;
2090 done:
2091 free(id_str);
2092 free(logmsg);
2093 return err;
2096 static const struct got_error *
2097 queue_commits(struct tog_log_thread_args *a)
2099 const struct got_error *err = NULL;
2102 * We keep all commits open throughout the lifetime of the log
2103 * view in order to avoid having to re-fetch commits from disk
2104 * while updating the display.
2106 do {
2107 struct got_object_id *id;
2108 struct got_commit_object *commit;
2109 struct commit_queue_entry *entry;
2110 int errcode;
2112 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2113 NULL, NULL);
2114 if (err || id == NULL)
2115 break;
2117 err = got_object_open_as_commit(&commit, a->repo, id);
2118 if (err)
2119 break;
2120 entry = alloc_commit_queue_entry(commit, id);
2121 if (entry == NULL) {
2122 err = got_error_from_errno("alloc_commit_queue_entry");
2123 break;
2126 errcode = pthread_mutex_lock(&tog_mutex);
2127 if (errcode) {
2128 err = got_error_set_errno(errcode,
2129 "pthread_mutex_lock");
2130 break;
2133 entry->idx = a->commits->ncommits;
2134 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2135 a->commits->ncommits++;
2137 if (*a->searching == TOG_SEARCH_FORWARD &&
2138 !*a->search_next_done) {
2139 int have_match;
2140 err = match_commit(&have_match, id, commit, a->regex);
2141 if (err)
2142 break;
2143 if (have_match)
2144 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2147 errcode = pthread_mutex_unlock(&tog_mutex);
2148 if (errcode && err == NULL)
2149 err = got_error_set_errno(errcode,
2150 "pthread_mutex_unlock");
2151 if (err)
2152 break;
2153 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2155 return err;
2158 static void
2159 select_commit(struct tog_log_view_state *s)
2161 struct commit_queue_entry *entry;
2162 int ncommits = 0;
2164 entry = s->first_displayed_entry;
2165 while (entry) {
2166 if (ncommits == s->selected) {
2167 s->selected_entry = entry;
2168 break;
2170 entry = TAILQ_NEXT(entry, entry);
2171 ncommits++;
2175 static const struct got_error *
2176 draw_commits(struct tog_view *view)
2178 const struct got_error *err = NULL;
2179 struct tog_log_view_state *s = &view->state.log;
2180 struct commit_queue_entry *entry = s->selected_entry;
2181 const int limit = view->nlines;
2182 int width;
2183 int ncommits, author_cols = 4;
2184 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2185 char *refs_str = NULL;
2186 wchar_t *wline;
2187 struct tog_color *tc;
2188 static const size_t date_display_cols = 12;
2190 if (s->selected_entry &&
2191 !(view->searching && view->search_next_done == 0)) {
2192 struct got_reflist_head *refs;
2193 err = got_object_id_str(&id_str, s->selected_entry->id);
2194 if (err)
2195 return err;
2196 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2197 s->selected_entry->id);
2198 if (refs) {
2199 err = build_refs_str(&refs_str, refs,
2200 s->selected_entry->id, s->repo);
2201 if (err)
2202 goto done;
2206 if (s->thread_args.commits_needed == 0)
2207 halfdelay(10); /* disable fast refresh */
2209 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2210 if (asprintf(&ncommits_str, " [%d/%d] %s",
2211 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2212 (view->searching && !view->search_next_done) ?
2213 "searching..." : "loading...") == -1) {
2214 err = got_error_from_errno("asprintf");
2215 goto done;
2217 } else {
2218 const char *search_str = NULL;
2220 if (view->searching) {
2221 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2222 search_str = "no more matches";
2223 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2224 search_str = "no matches found";
2225 else if (!view->search_next_done)
2226 search_str = "searching...";
2229 if (asprintf(&ncommits_str, " [%d/%d] %s",
2230 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2231 search_str ? search_str :
2232 (refs_str ? refs_str : "")) == -1) {
2233 err = got_error_from_errno("asprintf");
2234 goto done;
2238 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2239 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2240 "........................................",
2241 s->in_repo_path, ncommits_str) == -1) {
2242 err = got_error_from_errno("asprintf");
2243 header = NULL;
2244 goto done;
2246 } else if (asprintf(&header, "commit %s%s",
2247 id_str ? id_str : "........................................",
2248 ncommits_str) == -1) {
2249 err = got_error_from_errno("asprintf");
2250 header = NULL;
2251 goto done;
2253 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2254 if (err)
2255 goto done;
2257 werase(view->window);
2259 if (view_needs_focus_indication(view))
2260 wstandout(view->window);
2261 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2262 if (tc)
2263 wattr_on(view->window,
2264 COLOR_PAIR(tc->colorpair), NULL);
2265 waddwstr(view->window, wline);
2266 if (tc)
2267 wattr_off(view->window,
2268 COLOR_PAIR(tc->colorpair), NULL);
2269 while (width < view->ncols) {
2270 waddch(view->window, ' ');
2271 width++;
2273 if (view_needs_focus_indication(view))
2274 wstandend(view->window);
2275 free(wline);
2276 if (limit <= 1)
2277 goto done;
2279 /* Grow author column size if necessary, and set view->maxx. */
2280 entry = s->first_displayed_entry;
2281 ncommits = 0;
2282 view->maxx = 0;
2283 while (entry) {
2284 char *author, *eol, *msg, *msg0;
2285 wchar_t *wauthor, *wmsg;
2286 int width;
2287 if (ncommits >= limit - 1)
2288 break;
2289 author = strdup(got_object_commit_get_author(entry->commit));
2290 if (author == NULL) {
2291 err = got_error_from_errno("strdup");
2292 goto done;
2294 err = format_author(&wauthor, &width, author, COLS,
2295 date_display_cols);
2296 if (author_cols < width)
2297 author_cols = width;
2298 free(wauthor);
2299 free(author);
2300 err = got_object_commit_get_logmsg(&msg0, entry->commit);
2301 if (err)
2302 goto done;
2303 msg = msg0;
2304 while (*msg == '\n')
2305 ++msg;
2306 if ((eol = strchr(msg, '\n')))
2307 *eol = '\0';
2308 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2309 date_display_cols + author_cols, 0);
2310 if (err)
2311 goto done;
2312 view->maxx = MAX(view->maxx, width);
2313 free(msg0);
2314 free(wmsg);
2315 ncommits++;
2316 entry = TAILQ_NEXT(entry, entry);
2319 entry = s->first_displayed_entry;
2320 s->last_displayed_entry = s->first_displayed_entry;
2321 ncommits = 0;
2322 while (entry) {
2323 if (ncommits >= limit - 1)
2324 break;
2325 if (ncommits == s->selected)
2326 wstandout(view->window);
2327 err = draw_commit(view, entry->commit, entry->id,
2328 date_display_cols, author_cols);
2329 if (ncommits == s->selected)
2330 wstandend(view->window);
2331 if (err)
2332 goto done;
2333 ncommits++;
2334 s->last_displayed_entry = entry;
2335 entry = TAILQ_NEXT(entry, entry);
2338 view_border(view);
2339 done:
2340 free(id_str);
2341 free(refs_str);
2342 free(ncommits_str);
2343 free(header);
2344 return err;
2347 static void
2348 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2350 struct commit_queue_entry *entry;
2351 int nscrolled = 0;
2353 entry = TAILQ_FIRST(&s->commits.head);
2354 if (s->first_displayed_entry == entry)
2355 return;
2357 entry = s->first_displayed_entry;
2358 while (entry && nscrolled < maxscroll) {
2359 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2360 if (entry) {
2361 s->first_displayed_entry = entry;
2362 nscrolled++;
2367 static const struct got_error *
2368 trigger_log_thread(struct tog_view *view, int wait)
2370 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2371 int errcode;
2373 halfdelay(1); /* fast refresh while loading commits */
2375 while (!ta->log_complete && !tog_thread_error &&
2376 (ta->commits_needed > 0 || ta->load_all)) {
2377 /* Wake the log thread. */
2378 errcode = pthread_cond_signal(&ta->need_commits);
2379 if (errcode)
2380 return got_error_set_errno(errcode,
2381 "pthread_cond_signal");
2384 * The mutex will be released while the view loop waits
2385 * in wgetch(), at which time the log thread will run.
2387 if (!wait)
2388 break;
2390 /* Display progress update in log view. */
2391 show_log_view(view);
2392 update_panels();
2393 doupdate();
2395 /* Wait right here while next commit is being loaded. */
2396 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2397 if (errcode)
2398 return got_error_set_errno(errcode,
2399 "pthread_cond_wait");
2401 /* Display progress update in log view. */
2402 show_log_view(view);
2403 update_panels();
2404 doupdate();
2407 return NULL;
2410 static const struct got_error *
2411 request_log_commits(struct tog_view *view)
2413 struct tog_log_view_state *state = &view->state.log;
2414 const struct got_error *err = NULL;
2416 if (state->thread_args.log_complete)
2417 return NULL;
2419 state->thread_args.commits_needed += view->nscrolled;
2420 err = trigger_log_thread(view, 1);
2421 view->nscrolled = 0;
2423 return err;
2426 static const struct got_error *
2427 log_scroll_down(struct tog_view *view, int maxscroll)
2429 struct tog_log_view_state *s = &view->state.log;
2430 const struct got_error *err = NULL;
2431 struct commit_queue_entry *pentry;
2432 int nscrolled = 0, ncommits_needed;
2434 if (s->last_displayed_entry == NULL)
2435 return NULL;
2437 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2438 if (s->commits.ncommits < ncommits_needed &&
2439 !s->thread_args.log_complete) {
2441 * Ask the log thread for required amount of commits.
2443 s->thread_args.commits_needed += maxscroll;
2444 err = trigger_log_thread(view, 1);
2445 if (err)
2446 return err;
2449 do {
2450 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2451 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2452 break;
2454 s->last_displayed_entry = pentry ?
2455 pentry : s->last_displayed_entry;;
2457 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2458 if (pentry == NULL)
2459 break;
2460 s->first_displayed_entry = pentry;
2461 } while (++nscrolled < maxscroll);
2463 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2464 view->nscrolled += nscrolled;
2465 else
2466 view->nscrolled = 0;
2468 return err;
2471 static const struct got_error *
2472 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2473 struct got_commit_object *commit, struct got_object_id *commit_id,
2474 struct tog_view *log_view, struct got_repository *repo)
2476 const struct got_error *err;
2477 struct got_object_qid *parent_id;
2478 struct tog_view *diff_view;
2480 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2481 if (diff_view == NULL)
2482 return got_error_from_errno("view_open");
2484 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2485 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2486 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2487 if (err == NULL)
2488 *new_view = diff_view;
2489 return err;
2492 static const struct got_error *
2493 tree_view_visit_subtree(struct tog_tree_view_state *s,
2494 struct got_tree_object *subtree)
2496 struct tog_parent_tree *parent;
2498 parent = calloc(1, sizeof(*parent));
2499 if (parent == NULL)
2500 return got_error_from_errno("calloc");
2502 parent->tree = s->tree;
2503 parent->first_displayed_entry = s->first_displayed_entry;
2504 parent->selected_entry = s->selected_entry;
2505 parent->selected = s->selected;
2506 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2507 s->tree = subtree;
2508 s->selected = 0;
2509 s->first_displayed_entry = NULL;
2510 return NULL;
2513 static const struct got_error *
2514 tree_view_walk_path(struct tog_tree_view_state *s,
2515 struct got_commit_object *commit, const char *path)
2517 const struct got_error *err = NULL;
2518 struct got_tree_object *tree = NULL;
2519 const char *p;
2520 char *slash, *subpath = NULL;
2522 /* Walk the path and open corresponding tree objects. */
2523 p = path;
2524 while (*p) {
2525 struct got_tree_entry *te;
2526 struct got_object_id *tree_id;
2527 char *te_name;
2529 while (p[0] == '/')
2530 p++;
2532 /* Ensure the correct subtree entry is selected. */
2533 slash = strchr(p, '/');
2534 if (slash == NULL)
2535 te_name = strdup(p);
2536 else
2537 te_name = strndup(p, slash - p);
2538 if (te_name == NULL) {
2539 err = got_error_from_errno("strndup");
2540 break;
2542 te = got_object_tree_find_entry(s->tree, te_name);
2543 if (te == NULL) {
2544 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2545 free(te_name);
2546 break;
2548 free(te_name);
2549 s->first_displayed_entry = s->selected_entry = te;
2551 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2552 break; /* jump to this file's entry */
2554 slash = strchr(p, '/');
2555 if (slash)
2556 subpath = strndup(path, slash - path);
2557 else
2558 subpath = strdup(path);
2559 if (subpath == NULL) {
2560 err = got_error_from_errno("strdup");
2561 break;
2564 err = got_object_id_by_path(&tree_id, s->repo, commit,
2565 subpath);
2566 if (err)
2567 break;
2569 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2570 free(tree_id);
2571 if (err)
2572 break;
2574 err = tree_view_visit_subtree(s, tree);
2575 if (err) {
2576 got_object_tree_close(tree);
2577 break;
2579 if (slash == NULL)
2580 break;
2581 free(subpath);
2582 subpath = NULL;
2583 p = slash;
2586 free(subpath);
2587 return err;
2590 static const struct got_error *
2591 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2592 struct commit_queue_entry *entry, const char *path,
2593 const char *head_ref_name, struct got_repository *repo)
2595 const struct got_error *err = NULL;
2596 struct tog_tree_view_state *s;
2597 struct tog_view *tree_view;
2599 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2600 if (tree_view == NULL)
2601 return got_error_from_errno("view_open");
2603 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2604 if (err)
2605 return err;
2606 s = &tree_view->state.tree;
2608 *new_view = tree_view;
2610 if (got_path_is_root_dir(path))
2611 return NULL;
2613 return tree_view_walk_path(s, entry->commit, path);
2616 static const struct got_error *
2617 block_signals_used_by_main_thread(void)
2619 sigset_t sigset;
2620 int errcode;
2622 if (sigemptyset(&sigset) == -1)
2623 return got_error_from_errno("sigemptyset");
2625 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2626 if (sigaddset(&sigset, SIGWINCH) == -1)
2627 return got_error_from_errno("sigaddset");
2628 if (sigaddset(&sigset, SIGCONT) == -1)
2629 return got_error_from_errno("sigaddset");
2630 if (sigaddset(&sigset, SIGINT) == -1)
2631 return got_error_from_errno("sigaddset");
2632 if (sigaddset(&sigset, SIGTERM) == -1)
2633 return got_error_from_errno("sigaddset");
2635 /* ncurses handles SIGTSTP */
2636 if (sigaddset(&sigset, SIGTSTP) == -1)
2637 return got_error_from_errno("sigaddset");
2639 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2640 if (errcode)
2641 return got_error_set_errno(errcode, "pthread_sigmask");
2643 return NULL;
2646 static void *
2647 log_thread(void *arg)
2649 const struct got_error *err = NULL;
2650 int errcode = 0;
2651 struct tog_log_thread_args *a = arg;
2652 int done = 0;
2655 * Sync startup with main thread such that we begin our
2656 * work once view_input() has released the mutex.
2658 errcode = pthread_mutex_lock(&tog_mutex);
2659 if (errcode) {
2660 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2661 return (void *)err;
2664 err = block_signals_used_by_main_thread();
2665 if (err) {
2666 pthread_mutex_unlock(&tog_mutex);
2667 goto done;
2670 while (!done && !err && !tog_fatal_signal_received()) {
2671 errcode = pthread_mutex_unlock(&tog_mutex);
2672 if (errcode) {
2673 err = got_error_set_errno(errcode,
2674 "pthread_mutex_unlock");
2675 goto done;
2677 err = queue_commits(a);
2678 if (err) {
2679 if (err->code != GOT_ERR_ITER_COMPLETED)
2680 goto done;
2681 err = NULL;
2682 done = 1;
2683 } else if (a->commits_needed > 0 && !a->load_all)
2684 a->commits_needed--;
2686 errcode = pthread_mutex_lock(&tog_mutex);
2687 if (errcode) {
2688 err = got_error_set_errno(errcode,
2689 "pthread_mutex_lock");
2690 goto done;
2691 } else if (*a->quit)
2692 done = 1;
2693 else if (*a->first_displayed_entry == NULL) {
2694 *a->first_displayed_entry =
2695 TAILQ_FIRST(&a->commits->head);
2696 *a->selected_entry = *a->first_displayed_entry;
2699 errcode = pthread_cond_signal(&a->commit_loaded);
2700 if (errcode) {
2701 err = got_error_set_errno(errcode,
2702 "pthread_cond_signal");
2703 pthread_mutex_unlock(&tog_mutex);
2704 goto done;
2707 if (done)
2708 a->commits_needed = 0;
2709 else {
2710 if (a->commits_needed == 0 && !a->load_all) {
2711 errcode = pthread_cond_wait(&a->need_commits,
2712 &tog_mutex);
2713 if (errcode) {
2714 err = got_error_set_errno(errcode,
2715 "pthread_cond_wait");
2716 pthread_mutex_unlock(&tog_mutex);
2717 goto done;
2719 if (*a->quit)
2720 done = 1;
2724 a->log_complete = 1;
2725 errcode = pthread_mutex_unlock(&tog_mutex);
2726 if (errcode)
2727 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2728 done:
2729 if (err) {
2730 tog_thread_error = 1;
2731 pthread_cond_signal(&a->commit_loaded);
2733 return (void *)err;
2736 static const struct got_error *
2737 stop_log_thread(struct tog_log_view_state *s)
2739 const struct got_error *err = NULL, *thread_err = NULL;
2740 int errcode;
2742 if (s->thread) {
2743 s->quit = 1;
2744 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2745 if (errcode)
2746 return got_error_set_errno(errcode,
2747 "pthread_cond_signal");
2748 errcode = pthread_mutex_unlock(&tog_mutex);
2749 if (errcode)
2750 return got_error_set_errno(errcode,
2751 "pthread_mutex_unlock");
2752 errcode = pthread_join(s->thread, (void **)&thread_err);
2753 if (errcode)
2754 return got_error_set_errno(errcode, "pthread_join");
2755 errcode = pthread_mutex_lock(&tog_mutex);
2756 if (errcode)
2757 return got_error_set_errno(errcode,
2758 "pthread_mutex_lock");
2759 s->thread = NULL;
2762 if (s->thread_args.repo) {
2763 err = got_repo_close(s->thread_args.repo);
2764 s->thread_args.repo = NULL;
2767 if (s->thread_args.pack_fds) {
2768 const struct got_error *pack_err =
2769 got_repo_pack_fds_close(s->thread_args.pack_fds);
2770 if (err == NULL)
2771 err = pack_err;
2772 s->thread_args.pack_fds = NULL;
2775 if (s->thread_args.graph) {
2776 got_commit_graph_close(s->thread_args.graph);
2777 s->thread_args.graph = NULL;
2780 return err ? err : thread_err;
2783 static const struct got_error *
2784 close_log_view(struct tog_view *view)
2786 const struct got_error *err = NULL;
2787 struct tog_log_view_state *s = &view->state.log;
2788 int errcode;
2790 err = stop_log_thread(s);
2792 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2793 if (errcode && err == NULL)
2794 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2796 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2797 if (errcode && err == NULL)
2798 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2800 free_commits(&s->commits);
2801 free(s->in_repo_path);
2802 s->in_repo_path = NULL;
2803 free(s->start_id);
2804 s->start_id = NULL;
2805 free(s->head_ref_name);
2806 s->head_ref_name = NULL;
2807 return err;
2810 static const struct got_error *
2811 search_start_log_view(struct tog_view *view)
2813 struct tog_log_view_state *s = &view->state.log;
2815 s->matched_entry = NULL;
2816 s->search_entry = NULL;
2817 return NULL;
2820 static const struct got_error *
2821 search_next_log_view(struct tog_view *view)
2823 const struct got_error *err = NULL;
2824 struct tog_log_view_state *s = &view->state.log;
2825 struct commit_queue_entry *entry;
2827 /* Display progress update in log view. */
2828 show_log_view(view);
2829 update_panels();
2830 doupdate();
2832 if (s->search_entry) {
2833 int errcode, ch;
2834 errcode = pthread_mutex_unlock(&tog_mutex);
2835 if (errcode)
2836 return got_error_set_errno(errcode,
2837 "pthread_mutex_unlock");
2838 ch = wgetch(view->window);
2839 errcode = pthread_mutex_lock(&tog_mutex);
2840 if (errcode)
2841 return got_error_set_errno(errcode,
2842 "pthread_mutex_lock");
2843 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2844 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2845 return NULL;
2847 if (view->searching == TOG_SEARCH_FORWARD)
2848 entry = TAILQ_NEXT(s->search_entry, entry);
2849 else
2850 entry = TAILQ_PREV(s->search_entry,
2851 commit_queue_head, entry);
2852 } else if (s->matched_entry) {
2853 int matched_idx = s->matched_entry->idx;
2854 int selected_idx = s->selected_entry->idx;
2857 * If the user has moved the cursor after we hit a match,
2858 * the position from where we should continue searching
2859 * might have changed.
2861 if (view->searching == TOG_SEARCH_FORWARD) {
2862 if (matched_idx > selected_idx)
2863 entry = TAILQ_NEXT(s->selected_entry, entry);
2864 else
2865 entry = TAILQ_NEXT(s->matched_entry, entry);
2866 } else {
2867 if (matched_idx < selected_idx)
2868 entry = TAILQ_PREV(s->selected_entry,
2869 commit_queue_head, entry);
2870 else
2871 entry = TAILQ_PREV(s->matched_entry,
2872 commit_queue_head, entry);
2874 } else {
2875 entry = s->selected_entry;
2878 while (1) {
2879 int have_match = 0;
2881 if (entry == NULL) {
2882 if (s->thread_args.log_complete ||
2883 view->searching == TOG_SEARCH_BACKWARD) {
2884 view->search_next_done =
2885 (s->matched_entry == NULL ?
2886 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2887 s->search_entry = NULL;
2888 return NULL;
2891 * Poke the log thread for more commits and return,
2892 * allowing the main loop to make progress. Search
2893 * will resume at s->search_entry once we come back.
2895 s->thread_args.commits_needed++;
2896 return trigger_log_thread(view, 0);
2899 err = match_commit(&have_match, entry->id, entry->commit,
2900 &view->regex);
2901 if (err)
2902 break;
2903 if (have_match) {
2904 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2905 s->matched_entry = entry;
2906 break;
2909 s->search_entry = entry;
2910 if (view->searching == TOG_SEARCH_FORWARD)
2911 entry = TAILQ_NEXT(entry, entry);
2912 else
2913 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2916 if (s->matched_entry) {
2917 int cur = s->selected_entry->idx;
2918 while (cur < s->matched_entry->idx) {
2919 err = input_log_view(NULL, view, KEY_DOWN);
2920 if (err)
2921 return err;
2922 cur++;
2924 while (cur > s->matched_entry->idx) {
2925 err = input_log_view(NULL, view, KEY_UP);
2926 if (err)
2927 return err;
2928 cur--;
2932 s->search_entry = NULL;
2934 return NULL;
2937 static const struct got_error *
2938 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2939 struct got_repository *repo, const char *head_ref_name,
2940 const char *in_repo_path, int log_branches)
2942 const struct got_error *err = NULL;
2943 struct tog_log_view_state *s = &view->state.log;
2944 struct got_repository *thread_repo = NULL;
2945 struct got_commit_graph *thread_graph = NULL;
2946 int errcode;
2948 if (in_repo_path != s->in_repo_path) {
2949 free(s->in_repo_path);
2950 s->in_repo_path = strdup(in_repo_path);
2951 if (s->in_repo_path == NULL)
2952 return got_error_from_errno("strdup");
2955 /* The commit queue only contains commits being displayed. */
2956 TAILQ_INIT(&s->commits.head);
2957 s->commits.ncommits = 0;
2959 s->repo = repo;
2960 if (head_ref_name) {
2961 s->head_ref_name = strdup(head_ref_name);
2962 if (s->head_ref_name == NULL) {
2963 err = got_error_from_errno("strdup");
2964 goto done;
2967 s->start_id = got_object_id_dup(start_id);
2968 if (s->start_id == NULL) {
2969 err = got_error_from_errno("got_object_id_dup");
2970 goto done;
2972 s->log_branches = log_branches;
2974 STAILQ_INIT(&s->colors);
2975 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2976 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2977 get_color_value("TOG_COLOR_COMMIT"));
2978 if (err)
2979 goto done;
2980 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2981 get_color_value("TOG_COLOR_AUTHOR"));
2982 if (err) {
2983 free_colors(&s->colors);
2984 goto done;
2986 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2987 get_color_value("TOG_COLOR_DATE"));
2988 if (err) {
2989 free_colors(&s->colors);
2990 goto done;
2994 view->show = show_log_view;
2995 view->input = input_log_view;
2996 view->resize = resize_log_view;
2997 view->close = close_log_view;
2998 view->search_start = search_start_log_view;
2999 view->search_next = search_next_log_view;
3001 if (s->thread_args.pack_fds == NULL) {
3002 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3003 if (err)
3004 goto done;
3006 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3007 s->thread_args.pack_fds);
3008 if (err)
3009 goto done;
3010 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3011 !s->log_branches);
3012 if (err)
3013 goto done;
3014 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3015 s->repo, NULL, NULL);
3016 if (err)
3017 goto done;
3019 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3020 if (errcode) {
3021 err = got_error_set_errno(errcode, "pthread_cond_init");
3022 goto done;
3024 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3025 if (errcode) {
3026 err = got_error_set_errno(errcode, "pthread_cond_init");
3027 goto done;
3030 s->thread_args.commits_needed = view->nlines;
3031 s->thread_args.graph = thread_graph;
3032 s->thread_args.commits = &s->commits;
3033 s->thread_args.in_repo_path = s->in_repo_path;
3034 s->thread_args.start_id = s->start_id;
3035 s->thread_args.repo = thread_repo;
3036 s->thread_args.log_complete = 0;
3037 s->thread_args.quit = &s->quit;
3038 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3039 s->thread_args.selected_entry = &s->selected_entry;
3040 s->thread_args.searching = &view->searching;
3041 s->thread_args.search_next_done = &view->search_next_done;
3042 s->thread_args.regex = &view->regex;
3043 done:
3044 if (err)
3045 close_log_view(view);
3046 return err;
3049 static const struct got_error *
3050 show_log_view(struct tog_view *view)
3052 const struct got_error *err;
3053 struct tog_log_view_state *s = &view->state.log;
3055 if (s->thread == NULL) {
3056 int errcode = pthread_create(&s->thread, NULL, log_thread,
3057 &s->thread_args);
3058 if (errcode)
3059 return got_error_set_errno(errcode, "pthread_create");
3060 if (s->thread_args.commits_needed > 0) {
3061 err = trigger_log_thread(view, 1);
3062 if (err)
3063 return err;
3067 return draw_commits(view);
3070 static void
3071 log_move_cursor_up(struct tog_view *view, int page, int home)
3073 struct tog_log_view_state *s = &view->state.log;
3075 if (s->selected_entry->idx == 0)
3076 view->count = 0;
3077 if (s->first_displayed_entry == NULL)
3078 return;
3080 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3081 || home)
3082 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3084 if (!page && !home && s->selected > 0)
3085 --s->selected;
3086 else
3087 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3089 select_commit(s);
3090 return;
3093 static const struct got_error *
3094 log_move_cursor_down(struct tog_view *view, int page)
3096 struct tog_log_view_state *s = &view->state.log;
3097 struct commit_queue_entry *first;
3098 const struct got_error *err = NULL;
3100 first = s->first_displayed_entry;
3101 if (first == NULL) {
3102 view->count = 0;
3103 return NULL;
3106 if (s->thread_args.log_complete &&
3107 s->selected_entry->idx >= s->commits.ncommits - 1)
3108 return NULL;
3110 if (!page) {
3111 int eos = view->nlines - 2;
3113 if (view_is_hsplit_top(view))
3114 --eos; /* border consumes the last line */
3115 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3116 ++s->selected;
3117 else
3118 err = log_scroll_down(view, 1);
3119 } else if (s->thread_args.load_all) {
3120 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3121 s->selected += MIN(s->last_displayed_entry->idx -
3122 s->selected_entry->idx, page + 1);
3123 else
3124 err = log_scroll_down(view, MIN(page,
3125 s->commits.ncommits - s->selected_entry->idx - 1));
3126 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3127 } else {
3128 err = log_scroll_down(view, page);
3129 if (err)
3130 return err;
3131 if (first == s->first_displayed_entry && s->selected <
3132 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
3133 s->selected = MIN(s->commits.ncommits - 1, page);
3136 if (err)
3137 return err;
3140 * We might necessarily overshoot in horizontal
3141 * splits; if so, select the last displayed commit.
3143 s->selected = MIN(s->selected,
3144 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3146 select_commit(s);
3148 if (s->thread_args.log_complete &&
3149 s->selected_entry->idx == s->commits.ncommits - 1)
3150 view->count = 0;
3152 return NULL;
3155 static void
3156 view_get_split(struct tog_view *view, int *y, int *x)
3158 *x = 0;
3159 *y = 0;
3161 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3162 if (view->child && view->child->resized_y)
3163 *y = view->child->resized_y;
3164 else if (view->resized_y)
3165 *y = view->resized_y;
3166 else
3167 *y = view_split_begin_y(view->lines);
3168 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3169 if (view->child && view->child->resized_x)
3170 *x = view->child->resized_x;
3171 else if (view->resized_x)
3172 *x = view->resized_x;
3173 else
3174 *x = view_split_begin_x(view->begin_x);
3178 /* Split view horizontally at y and offset view->state->selected line. */
3179 static const struct got_error *
3180 view_init_hsplit(struct tog_view *view, int y)
3182 const struct got_error *err = NULL;
3184 view->nlines = y;
3185 view->ncols = COLS;
3186 err = view_resize(view);
3187 if (err)
3188 return err;
3190 err = offset_selection_down(view);
3192 return err;
3195 static const struct got_error *
3196 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3198 const struct got_error *err = NULL;
3199 struct tog_log_view_state *s = &view->state.log;
3200 struct tog_view *diff_view = NULL, *tree_view = NULL;
3201 struct tog_view *ref_view = NULL;
3202 struct commit_queue_entry *entry;
3203 int begin_x = 0, begin_y = 0, eos, n, nscroll;
3205 if (s->thread_args.load_all) {
3206 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3207 s->thread_args.load_all = 0;
3208 else if (s->thread_args.log_complete) {
3209 err = log_move_cursor_down(view, s->commits.ncommits);
3210 s->thread_args.load_all = 0;
3212 return err;
3215 eos = nscroll = view->nlines - 1;
3216 if (view_is_hsplit_top(view))
3217 --eos; /* border */
3219 switch (ch) {
3220 case 'q':
3221 s->quit = 1;
3222 break;
3223 case '0':
3224 view->x = 0;
3225 break;
3226 case '$':
3227 view->x = MAX(view->maxx - view->ncols / 2, 0);
3228 view->count = 0;
3229 break;
3230 case KEY_RIGHT:
3231 case 'l':
3232 if (view->x + view->ncols / 2 < view->maxx)
3233 view->x += 2; /* move two columns right */
3234 else
3235 view->count = 0;
3236 break;
3237 case KEY_LEFT:
3238 case 'h':
3239 view->x -= MIN(view->x, 2); /* move two columns back */
3240 if (view->x <= 0)
3241 view->count = 0;
3242 break;
3243 case 'k':
3244 case KEY_UP:
3245 case '<':
3246 case ',':
3247 case CTRL('p'):
3248 log_move_cursor_up(view, 0, 0);
3249 break;
3250 case 'g':
3251 case KEY_HOME:
3252 log_move_cursor_up(view, 0, 1);
3253 view->count = 0;
3254 break;
3255 case CTRL('u'):
3256 case 'u':
3257 nscroll /= 2;
3258 /* FALL THROUGH */
3259 case KEY_PPAGE:
3260 case CTRL('b'):
3261 case 'b':
3262 log_move_cursor_up(view, nscroll, 0);
3263 break;
3264 case 'j':
3265 case KEY_DOWN:
3266 case '>':
3267 case '.':
3268 case CTRL('n'):
3269 err = log_move_cursor_down(view, 0);
3270 break;
3271 case 'G':
3272 case KEY_END: {
3273 /* We don't know yet how many commits, so we're forced to
3274 * traverse them all. */
3275 view->count = 0;
3276 if (!s->thread_args.log_complete) {
3277 s->thread_args.load_all = 1;
3278 return trigger_log_thread(view, 0);
3281 s->selected = 0;
3282 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3283 for (n = 0; n < eos; n++) {
3284 if (entry == NULL)
3285 break;
3286 s->first_displayed_entry = entry;
3287 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3289 if (n > 0)
3290 s->selected = n - 1;
3291 select_commit(s);
3292 break;
3294 case CTRL('d'):
3295 case 'd':
3296 nscroll /= 2;
3297 /* FALL THROUGH */
3298 case KEY_NPAGE:
3299 case CTRL('f'):
3300 case 'f':
3301 case ' ':
3302 err = log_move_cursor_down(view, nscroll);
3303 break;
3304 case KEY_RESIZE:
3305 if (s->selected > view->nlines - 2)
3306 s->selected = view->nlines - 2;
3307 if (s->selected > s->commits.ncommits - 1)
3308 s->selected = s->commits.ncommits - 1;
3309 select_commit(s);
3310 if (s->commits.ncommits < view->nlines - 1 &&
3311 !s->thread_args.log_complete) {
3312 s->thread_args.commits_needed += (view->nlines - 1) -
3313 s->commits.ncommits;
3314 err = trigger_log_thread(view, 1);
3316 break;
3317 case KEY_ENTER:
3318 case '\r':
3319 view->count = 0;
3320 if (s->selected_entry == NULL)
3321 break;
3323 /* get dimensions--don't split till initialisation succeeds */
3324 if (view_is_parent_view(view))
3325 view_get_split(view, &begin_y, &begin_x);
3327 err = open_diff_view_for_commit(&diff_view, begin_y, begin_x,
3328 s->selected_entry->commit, s->selected_entry->id,
3329 view, s->repo);
3330 if (err)
3331 break;
3333 if (view_is_parent_view(view) &&
3334 view->mode == TOG_VIEW_SPLIT_HRZN) { /* safe to split */
3335 err = view_init_hsplit(view, begin_y);
3336 if (err)
3337 break;
3340 view->focussed = 0;
3341 diff_view->focussed = 1;
3342 diff_view->mode = view->mode;
3343 diff_view->nlines = view->lines - begin_y;
3345 if (view_is_parent_view(view)) {
3346 view_transfer_size(diff_view, view);
3347 err = view_close_child(view);
3348 if (err)
3349 return err;
3350 err = view_set_child(view, diff_view);
3351 if (err)
3352 return err;
3353 view->focus_child = 1;
3354 } else
3355 *new_view = diff_view;
3356 break;
3357 case 't':
3358 view->count = 0;
3359 if (s->selected_entry == NULL)
3360 break;
3361 if (view_is_parent_view(view))
3362 view_get_split(view, &begin_y, &begin_x);
3363 err = browse_commit_tree(&tree_view, begin_y, begin_x,
3364 s->selected_entry, s->in_repo_path, s->head_ref_name,
3365 s->repo);
3366 if (err)
3367 break;
3368 if (view_is_parent_view(view) &&
3369 view->mode == TOG_VIEW_SPLIT_HRZN) {
3370 err = view_init_hsplit(view, begin_y);
3371 if (err)
3372 break;
3374 view->focussed = 0;
3375 tree_view->focussed = 1;
3376 tree_view->mode = view->mode;
3377 tree_view->nlines = view->lines - begin_y;
3378 if (view_is_parent_view(view)) {
3379 view_transfer_size(tree_view, view);
3380 err = view_close_child(view);
3381 if (err)
3382 return err;
3383 err = view_set_child(view, tree_view);
3384 if (err)
3385 return err;
3386 view->focus_child = 1;
3387 } else
3388 *new_view = tree_view;
3389 break;
3390 case KEY_BACKSPACE:
3391 case CTRL('l'):
3392 case 'B':
3393 view->count = 0;
3394 if (ch == KEY_BACKSPACE &&
3395 got_path_is_root_dir(s->in_repo_path))
3396 break;
3397 err = stop_log_thread(s);
3398 if (err)
3399 return err;
3400 if (ch == KEY_BACKSPACE) {
3401 char *parent_path;
3402 err = got_path_dirname(&parent_path, s->in_repo_path);
3403 if (err)
3404 return err;
3405 free(s->in_repo_path);
3406 s->in_repo_path = parent_path;
3407 s->thread_args.in_repo_path = s->in_repo_path;
3408 } else if (ch == CTRL('l')) {
3409 struct got_object_id *start_id;
3410 err = got_repo_match_object_id(&start_id, NULL,
3411 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3412 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3413 if (err)
3414 return err;
3415 free(s->start_id);
3416 s->start_id = start_id;
3417 s->thread_args.start_id = s->start_id;
3418 } else /* 'B' */
3419 s->log_branches = !s->log_branches;
3421 if (s->thread_args.pack_fds == NULL) {
3422 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3423 if (err)
3424 return err;
3426 err = got_repo_open(&s->thread_args.repo,
3427 got_repo_get_path(s->repo), NULL,
3428 s->thread_args.pack_fds);
3429 if (err)
3430 return err;
3431 tog_free_refs();
3432 err = tog_load_refs(s->repo, 0);
3433 if (err)
3434 return err;
3435 err = got_commit_graph_open(&s->thread_args.graph,
3436 s->in_repo_path, !s->log_branches);
3437 if (err)
3438 return err;
3439 err = got_commit_graph_iter_start(s->thread_args.graph,
3440 s->start_id, s->repo, NULL, NULL);
3441 if (err)
3442 return err;
3443 free_commits(&s->commits);
3444 s->first_displayed_entry = NULL;
3445 s->last_displayed_entry = NULL;
3446 s->selected_entry = NULL;
3447 s->selected = 0;
3448 s->thread_args.log_complete = 0;
3449 s->quit = 0;
3450 s->thread_args.commits_needed = view->lines;
3451 s->matched_entry = NULL;
3452 s->search_entry = NULL;
3453 break;
3454 case 'r':
3455 view->count = 0;
3456 if (view_is_parent_view(view))
3457 view_get_split(view, &begin_y, &begin_x);
3458 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
3459 if (ref_view == NULL)
3460 return got_error_from_errno("view_open");
3461 err = open_ref_view(ref_view, s->repo);
3462 if (err) {
3463 view_close(ref_view);
3464 return err;
3466 if (view_is_parent_view(view) &&
3467 view->mode == TOG_VIEW_SPLIT_HRZN) {
3468 err = view_init_hsplit(view, begin_y);
3469 if (err)
3470 break;
3472 view->focussed = 0;
3473 ref_view->focussed = 1;
3474 ref_view->mode = view->mode;
3475 ref_view->nlines = view->lines - begin_y;
3476 if (view_is_parent_view(view)) {
3477 view_transfer_size(ref_view, view);
3478 err = view_close_child(view);
3479 if (err)
3480 return err;
3481 err = view_set_child(view, ref_view);
3482 if (err)
3483 return err;
3484 view->focus_child = 1;
3485 } else
3486 *new_view = ref_view;
3487 break;
3488 default:
3489 view->count = 0;
3490 break;
3493 return err;
3496 static const struct got_error *
3497 apply_unveil(const char *repo_path, const char *worktree_path)
3499 const struct got_error *error;
3501 #ifdef PROFILE
3502 if (unveil("gmon.out", "rwc") != 0)
3503 return got_error_from_errno2("unveil", "gmon.out");
3504 #endif
3505 if (repo_path && unveil(repo_path, "r") != 0)
3506 return got_error_from_errno2("unveil", repo_path);
3508 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3509 return got_error_from_errno2("unveil", worktree_path);
3511 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3512 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3514 error = got_privsep_unveil_exec_helpers();
3515 if (error != NULL)
3516 return error;
3518 if (unveil(NULL, NULL) != 0)
3519 return got_error_from_errno("unveil");
3521 return NULL;
3524 static void
3525 init_curses(void)
3528 * Override default signal handlers before starting ncurses.
3529 * This should prevent ncurses from installing its own
3530 * broken cleanup() signal handler.
3532 signal(SIGWINCH, tog_sigwinch);
3533 signal(SIGPIPE, tog_sigpipe);
3534 signal(SIGCONT, tog_sigcont);
3535 signal(SIGINT, tog_sigint);
3536 signal(SIGTERM, tog_sigterm);
3538 initscr();
3539 cbreak();
3540 halfdelay(1); /* Do fast refresh while initial view is loading. */
3541 noecho();
3542 nonl();
3543 intrflush(stdscr, FALSE);
3544 keypad(stdscr, TRUE);
3545 curs_set(0);
3546 if (getenv("TOG_COLORS") != NULL) {
3547 start_color();
3548 use_default_colors();
3552 static const struct got_error *
3553 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3554 struct got_repository *repo, struct got_worktree *worktree)
3556 const struct got_error *err = NULL;
3558 if (argc == 0) {
3559 *in_repo_path = strdup("/");
3560 if (*in_repo_path == NULL)
3561 return got_error_from_errno("strdup");
3562 return NULL;
3565 if (worktree) {
3566 const char *prefix = got_worktree_get_path_prefix(worktree);
3567 char *p;
3569 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3570 if (err)
3571 return err;
3572 if (asprintf(in_repo_path, "%s%s%s", prefix,
3573 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3574 p) == -1) {
3575 err = got_error_from_errno("asprintf");
3576 *in_repo_path = NULL;
3578 free(p);
3579 } else
3580 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3582 return err;
3585 static const struct got_error *
3586 cmd_log(int argc, char *argv[])
3588 const struct got_error *error;
3589 struct got_repository *repo = NULL;
3590 struct got_worktree *worktree = NULL;
3591 struct got_object_id *start_id = NULL;
3592 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3593 char *start_commit = NULL, *label = NULL;
3594 struct got_reference *ref = NULL;
3595 const char *head_ref_name = NULL;
3596 int ch, log_branches = 0;
3597 struct tog_view *view;
3598 int *pack_fds = NULL;
3600 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3601 switch (ch) {
3602 case 'b':
3603 log_branches = 1;
3604 break;
3605 case 'c':
3606 start_commit = optarg;
3607 break;
3608 case 'r':
3609 repo_path = realpath(optarg, NULL);
3610 if (repo_path == NULL)
3611 return got_error_from_errno2("realpath",
3612 optarg);
3613 break;
3614 default:
3615 usage_log();
3616 /* NOTREACHED */
3620 argc -= optind;
3621 argv += optind;
3623 if (argc > 1)
3624 usage_log();
3626 error = got_repo_pack_fds_open(&pack_fds);
3627 if (error != NULL)
3628 goto done;
3630 if (repo_path == NULL) {
3631 cwd = getcwd(NULL, 0);
3632 if (cwd == NULL)
3633 return got_error_from_errno("getcwd");
3634 error = got_worktree_open(&worktree, cwd);
3635 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3636 goto done;
3637 if (worktree)
3638 repo_path =
3639 strdup(got_worktree_get_repo_path(worktree));
3640 else
3641 repo_path = strdup(cwd);
3642 if (repo_path == NULL) {
3643 error = got_error_from_errno("strdup");
3644 goto done;
3648 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3649 if (error != NULL)
3650 goto done;
3652 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3653 repo, worktree);
3654 if (error)
3655 goto done;
3657 init_curses();
3659 error = apply_unveil(got_repo_get_path(repo),
3660 worktree ? got_worktree_get_root_path(worktree) : NULL);
3661 if (error)
3662 goto done;
3664 /* already loaded by tog_log_with_path()? */
3665 if (TAILQ_EMPTY(&tog_refs)) {
3666 error = tog_load_refs(repo, 0);
3667 if (error)
3668 goto done;
3671 if (start_commit == NULL) {
3672 error = got_repo_match_object_id(&start_id, &label,
3673 worktree ? got_worktree_get_head_ref_name(worktree) :
3674 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3675 if (error)
3676 goto done;
3677 head_ref_name = label;
3678 } else {
3679 error = got_ref_open(&ref, repo, start_commit, 0);
3680 if (error == NULL)
3681 head_ref_name = got_ref_get_name(ref);
3682 else if (error->code != GOT_ERR_NOT_REF)
3683 goto done;
3684 error = got_repo_match_object_id(&start_id, NULL,
3685 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3686 if (error)
3687 goto done;
3690 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3691 if (view == NULL) {
3692 error = got_error_from_errno("view_open");
3693 goto done;
3695 error = open_log_view(view, start_id, repo, head_ref_name,
3696 in_repo_path, log_branches);
3697 if (error)
3698 goto done;
3699 if (worktree) {
3700 /* Release work tree lock. */
3701 got_worktree_close(worktree);
3702 worktree = NULL;
3704 error = view_loop(view);
3705 done:
3706 free(in_repo_path);
3707 free(repo_path);
3708 free(cwd);
3709 free(start_id);
3710 free(label);
3711 if (ref)
3712 got_ref_close(ref);
3713 if (repo) {
3714 const struct got_error *close_err = got_repo_close(repo);
3715 if (error == NULL)
3716 error = close_err;
3718 if (worktree)
3719 got_worktree_close(worktree);
3720 if (pack_fds) {
3721 const struct got_error *pack_err =
3722 got_repo_pack_fds_close(pack_fds);
3723 if (error == NULL)
3724 error = pack_err;
3726 tog_free_refs();
3727 return error;
3730 __dead static void
3731 usage_diff(void)
3733 endwin();
3734 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3735 "[-w] object1 object2\n", getprogname());
3736 exit(1);
3739 static int
3740 match_line(const char *line, regex_t *regex, size_t nmatch,
3741 regmatch_t *regmatch)
3743 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3746 static struct tog_color *
3747 match_color(struct tog_colors *colors, const char *line)
3749 struct tog_color *tc = NULL;
3751 STAILQ_FOREACH(tc, colors, entry) {
3752 if (match_line(line, &tc->regex, 0, NULL))
3753 return tc;
3756 return NULL;
3759 static const struct got_error *
3760 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3761 WINDOW *window, int skipcol, regmatch_t *regmatch)
3763 const struct got_error *err = NULL;
3764 char *exstr = NULL;
3765 wchar_t *wline = NULL;
3766 int rme, rms, n, width, scrollx;
3767 int width0 = 0, width1 = 0, width2 = 0;
3768 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3770 *wtotal = 0;
3772 rms = regmatch->rm_so;
3773 rme = regmatch->rm_eo;
3775 err = expand_tab(&exstr, line);
3776 if (err)
3777 return err;
3779 /* Split the line into 3 segments, according to match offsets. */
3780 seg0 = strndup(exstr, rms);
3781 if (seg0 == NULL) {
3782 err = got_error_from_errno("strndup");
3783 goto done;
3785 seg1 = strndup(exstr + rms, rme - rms);
3786 if (seg1 == NULL) {
3787 err = got_error_from_errno("strndup");
3788 goto done;
3790 seg2 = strdup(exstr + rme);
3791 if (seg2 == NULL) {
3792 err = got_error_from_errno("strndup");
3793 goto done;
3796 /* draw up to matched token if we haven't scrolled past it */
3797 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3798 col_tab_align, 1);
3799 if (err)
3800 goto done;
3801 n = MAX(width0 - skipcol, 0);
3802 if (n) {
3803 free(wline);
3804 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3805 wlimit, col_tab_align, 1);
3806 if (err)
3807 goto done;
3808 waddwstr(window, &wline[scrollx]);
3809 wlimit -= width;
3810 *wtotal += width;
3813 if (wlimit > 0) {
3814 int i = 0, w = 0;
3815 size_t wlen;
3817 free(wline);
3818 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3819 col_tab_align, 1);
3820 if (err)
3821 goto done;
3822 wlen = wcslen(wline);
3823 while (i < wlen) {
3824 width = wcwidth(wline[i]);
3825 if (width == -1) {
3826 /* should not happen, tabs are expanded */
3827 err = got_error(GOT_ERR_RANGE);
3828 goto done;
3830 if (width0 + w + width > skipcol)
3831 break;
3832 w += width;
3833 i++;
3835 /* draw (visible part of) matched token (if scrolled into it) */
3836 if (width1 - w > 0) {
3837 wattron(window, A_STANDOUT);
3838 waddwstr(window, &wline[i]);
3839 wattroff(window, A_STANDOUT);
3840 wlimit -= (width1 - w);
3841 *wtotal += (width1 - w);
3845 if (wlimit > 0) { /* draw rest of line */
3846 free(wline);
3847 if (skipcol > width0 + width1) {
3848 err = format_line(&wline, &width2, &scrollx, seg2,
3849 skipcol - (width0 + width1), wlimit,
3850 col_tab_align, 1);
3851 if (err)
3852 goto done;
3853 waddwstr(window, &wline[scrollx]);
3854 } else {
3855 err = format_line(&wline, &width2, NULL, seg2, 0,
3856 wlimit, col_tab_align, 1);
3857 if (err)
3858 goto done;
3859 waddwstr(window, wline);
3861 *wtotal += width2;
3863 done:
3864 free(wline);
3865 free(exstr);
3866 free(seg0);
3867 free(seg1);
3868 free(seg2);
3869 return err;
3872 static const struct got_error *
3873 draw_file(struct tog_view *view, const char *header)
3875 struct tog_diff_view_state *s = &view->state.diff;
3876 regmatch_t *regmatch = &view->regmatch;
3877 const struct got_error *err;
3878 int nprinted = 0;
3879 char *line;
3880 size_t linesize = 0;
3881 ssize_t linelen;
3882 struct tog_color *tc;
3883 wchar_t *wline;
3884 int width;
3885 int max_lines = view->nlines;
3886 int nlines = s->nlines;
3887 off_t line_offset;
3889 line_offset = s->line_offsets[s->first_displayed_line - 1];
3890 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3891 return got_error_from_errno("fseek");
3893 werase(view->window);
3895 if (header) {
3896 if (asprintf(&line, "[%d/%d] %s",
3897 s->first_displayed_line - 1 + s->selected_line, nlines,
3898 header) == -1)
3899 return got_error_from_errno("asprintf");
3900 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3901 0, 0);
3902 free(line);
3903 if (err)
3904 return err;
3906 if (view_needs_focus_indication(view))
3907 wstandout(view->window);
3908 waddwstr(view->window, wline);
3909 free(wline);
3910 wline = NULL;
3911 if (view_needs_focus_indication(view))
3912 wstandend(view->window);
3913 if (width <= view->ncols - 1)
3914 waddch(view->window, '\n');
3916 if (max_lines <= 1)
3917 return NULL;
3918 max_lines--;
3921 s->eof = 0;
3922 view->maxx = 0;
3923 line = NULL;
3924 while (max_lines > 0 && nprinted < max_lines) {
3925 linelen = getline(&line, &linesize, s->f);
3926 if (linelen == -1) {
3927 if (feof(s->f)) {
3928 s->eof = 1;
3929 break;
3931 free(line);
3932 return got_ferror(s->f, GOT_ERR_IO);
3935 /* Set view->maxx based on full line length. */
3936 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3937 view->x ? 1 : 0);
3938 if (err) {
3939 free(line);
3940 return err;
3942 view->maxx = MAX(view->maxx, width);
3943 free(wline);
3944 wline = NULL;
3946 tc = match_color(&s->colors, line);
3947 if (tc)
3948 wattr_on(view->window,
3949 COLOR_PAIR(tc->colorpair), NULL);
3950 if (s->first_displayed_line + nprinted == s->matched_line &&
3951 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3952 err = add_matched_line(&width, line, view->ncols, 0,
3953 view->window, view->x, regmatch);
3954 if (err) {
3955 free(line);
3956 return err;
3958 } else {
3959 int skip;
3960 err = format_line(&wline, &width, &skip, line,
3961 view->x, view->ncols, 0, view->x ? 1 : 0);
3962 if (err) {
3963 free(line);
3964 return err;
3966 waddwstr(view->window, &wline[skip]);
3967 free(wline);
3968 wline = NULL;
3970 if (tc)
3971 wattr_off(view->window,
3972 COLOR_PAIR(tc->colorpair), NULL);
3973 if (width <= view->ncols - 1)
3974 waddch(view->window, '\n');
3975 nprinted++;
3977 free(line);
3978 if (nprinted >= 1)
3979 s->last_displayed_line = s->first_displayed_line +
3980 (nprinted - 1);
3981 else
3982 s->last_displayed_line = s->first_displayed_line;
3984 view_border(view);
3986 if (s->eof) {
3987 while (nprinted < view->nlines) {
3988 waddch(view->window, '\n');
3989 nprinted++;
3992 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3993 view->ncols, 0, 0);
3994 if (err) {
3995 return err;
3998 wstandout(view->window);
3999 waddwstr(view->window, wline);
4000 free(wline);
4001 wline = NULL;
4002 wstandend(view->window);
4005 return NULL;
4008 static char *
4009 get_datestr(time_t *time, char *datebuf)
4011 struct tm mytm, *tm;
4012 char *p, *s;
4014 tm = gmtime_r(time, &mytm);
4015 if (tm == NULL)
4016 return NULL;
4017 s = asctime_r(tm, datebuf);
4018 if (s == NULL)
4019 return NULL;
4020 p = strchr(s, '\n');
4021 if (p)
4022 *p = '\0';
4023 return s;
4026 static const struct got_error *
4027 get_changed_paths(struct got_pathlist_head *paths,
4028 struct got_commit_object *commit, struct got_repository *repo)
4030 const struct got_error *err = NULL;
4031 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4032 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4033 struct got_object_qid *qid;
4035 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4036 if (qid != NULL) {
4037 struct got_commit_object *pcommit;
4038 err = got_object_open_as_commit(&pcommit, repo,
4039 &qid->id);
4040 if (err)
4041 return err;
4043 tree_id1 = got_object_id_dup(
4044 got_object_commit_get_tree_id(pcommit));
4045 if (tree_id1 == NULL) {
4046 got_object_commit_close(pcommit);
4047 return got_error_from_errno("got_object_id_dup");
4049 got_object_commit_close(pcommit);
4053 if (tree_id1) {
4054 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4055 if (err)
4056 goto done;
4059 tree_id2 = got_object_commit_get_tree_id(commit);
4060 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4061 if (err)
4062 goto done;
4064 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4065 got_diff_tree_collect_changed_paths, paths, 0);
4066 done:
4067 if (tree1)
4068 got_object_tree_close(tree1);
4069 if (tree2)
4070 got_object_tree_close(tree2);
4071 free(tree_id1);
4072 return err;
4075 static const struct got_error *
4076 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
4078 off_t *p;
4080 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
4081 if (p == NULL)
4082 return got_error_from_errno("reallocarray");
4083 *line_offsets = p;
4084 (*line_offsets)[*nlines] = off;
4085 (*nlines)++;
4086 return NULL;
4089 static const struct got_error *
4090 write_commit_info(off_t **line_offsets, size_t *nlines,
4091 struct got_object_id *commit_id, struct got_reflist_head *refs,
4092 struct got_repository *repo, FILE *outfile)
4094 const struct got_error *err = NULL;
4095 char datebuf[26], *datestr;
4096 struct got_commit_object *commit;
4097 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4098 time_t committer_time;
4099 const char *author, *committer;
4100 char *refs_str = NULL;
4101 struct got_pathlist_head changed_paths;
4102 struct got_pathlist_entry *pe;
4103 off_t outoff = 0;
4104 int n;
4106 TAILQ_INIT(&changed_paths);
4108 if (refs) {
4109 err = build_refs_str(&refs_str, refs, commit_id, repo);
4110 if (err)
4111 return err;
4114 err = got_object_open_as_commit(&commit, repo, commit_id);
4115 if (err)
4116 return err;
4118 err = got_object_id_str(&id_str, commit_id);
4119 if (err) {
4120 err = got_error_from_errno("got_object_id_str");
4121 goto done;
4124 err = add_line_offset(line_offsets, nlines, 0);
4125 if (err)
4126 goto done;
4128 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4129 refs_str ? refs_str : "", refs_str ? ")" : "");
4130 if (n < 0) {
4131 err = got_error_from_errno("fprintf");
4132 goto done;
4134 outoff += n;
4135 err = add_line_offset(line_offsets, nlines, outoff);
4136 if (err)
4137 goto done;
4139 n = fprintf(outfile, "from: %s\n",
4140 got_object_commit_get_author(commit));
4141 if (n < 0) {
4142 err = got_error_from_errno("fprintf");
4143 goto done;
4145 outoff += n;
4146 err = add_line_offset(line_offsets, nlines, outoff);
4147 if (err)
4148 goto done;
4150 committer_time = got_object_commit_get_committer_time(commit);
4151 datestr = get_datestr(&committer_time, datebuf);
4152 if (datestr) {
4153 n = fprintf(outfile, "date: %s UTC\n", datestr);
4154 if (n < 0) {
4155 err = got_error_from_errno("fprintf");
4156 goto done;
4158 outoff += n;
4159 err = add_line_offset(line_offsets, nlines, outoff);
4160 if (err)
4161 goto done;
4163 author = got_object_commit_get_author(commit);
4164 committer = got_object_commit_get_committer(commit);
4165 if (strcmp(author, committer) != 0) {
4166 n = fprintf(outfile, "via: %s\n", committer);
4167 if (n < 0) {
4168 err = got_error_from_errno("fprintf");
4169 goto done;
4171 outoff += n;
4172 err = add_line_offset(line_offsets, nlines, outoff);
4173 if (err)
4174 goto done;
4176 if (got_object_commit_get_nparents(commit) > 1) {
4177 const struct got_object_id_queue *parent_ids;
4178 struct got_object_qid *qid;
4179 int pn = 1;
4180 parent_ids = got_object_commit_get_parent_ids(commit);
4181 STAILQ_FOREACH(qid, parent_ids, entry) {
4182 err = got_object_id_str(&id_str, &qid->id);
4183 if (err)
4184 goto done;
4185 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4186 if (n < 0) {
4187 err = got_error_from_errno("fprintf");
4188 goto done;
4190 outoff += n;
4191 err = add_line_offset(line_offsets, nlines, outoff);
4192 if (err)
4193 goto done;
4194 free(id_str);
4195 id_str = NULL;
4199 err = got_object_commit_get_logmsg(&logmsg, commit);
4200 if (err)
4201 goto done;
4202 s = logmsg;
4203 while ((line = strsep(&s, "\n")) != NULL) {
4204 n = fprintf(outfile, "%s\n", line);
4205 if (n < 0) {
4206 err = got_error_from_errno("fprintf");
4207 goto done;
4209 outoff += n;
4210 err = add_line_offset(line_offsets, nlines, outoff);
4211 if (err)
4212 goto done;
4215 err = get_changed_paths(&changed_paths, commit, repo);
4216 if (err)
4217 goto done;
4218 TAILQ_FOREACH(pe, &changed_paths, entry) {
4219 struct got_diff_changed_path *cp = pe->data;
4220 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4221 if (n < 0) {
4222 err = got_error_from_errno("fprintf");
4223 goto done;
4225 outoff += n;
4226 err = add_line_offset(line_offsets, nlines, outoff);
4227 if (err)
4228 goto done;
4229 free((char *)pe->path);
4230 free(pe->data);
4233 fputc('\n', outfile);
4234 outoff++;
4235 err = add_line_offset(line_offsets, nlines, outoff);
4236 done:
4237 got_pathlist_free(&changed_paths);
4238 free(id_str);
4239 free(logmsg);
4240 free(refs_str);
4241 got_object_commit_close(commit);
4242 if (err) {
4243 free(*line_offsets);
4244 *line_offsets = NULL;
4245 *nlines = 0;
4247 return err;
4250 static const struct got_error *
4251 create_diff(struct tog_diff_view_state *s)
4253 const struct got_error *err = NULL;
4254 FILE *f = NULL;
4255 int obj_type;
4257 free(s->line_offsets);
4258 s->line_offsets = malloc(sizeof(off_t));
4259 if (s->line_offsets == NULL)
4260 return got_error_from_errno("malloc");
4261 s->nlines = 0;
4263 f = got_opentemp();
4264 if (f == NULL) {
4265 err = got_error_from_errno("got_opentemp");
4266 goto done;
4268 if (s->f && fclose(s->f) == EOF) {
4269 err = got_error_from_errno("fclose");
4270 goto done;
4272 s->f = f;
4274 if (s->id1)
4275 err = got_object_get_type(&obj_type, s->repo, s->id1);
4276 else
4277 err = got_object_get_type(&obj_type, s->repo, s->id2);
4278 if (err)
4279 goto done;
4281 switch (obj_type) {
4282 case GOT_OBJ_TYPE_BLOB:
4283 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
4284 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4285 s->label1, s->label2, tog_diff_algo, s->diff_context,
4286 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4287 break;
4288 case GOT_OBJ_TYPE_TREE:
4289 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
4290 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4291 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4292 s->force_text_diff, s->repo, s->f);
4293 break;
4294 case GOT_OBJ_TYPE_COMMIT: {
4295 const struct got_object_id_queue *parent_ids;
4296 struct got_object_qid *pid;
4297 struct got_commit_object *commit2;
4298 struct got_reflist_head *refs;
4300 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4301 if (err)
4302 goto done;
4303 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4304 /* Show commit info if we're diffing to a parent/root commit. */
4305 if (s->id1 == NULL) {
4306 err = write_commit_info(&s->line_offsets, &s->nlines,
4307 s->id2, refs, s->repo, s->f);
4308 if (err)
4309 goto done;
4310 } else {
4311 parent_ids = got_object_commit_get_parent_ids(commit2);
4312 STAILQ_FOREACH(pid, parent_ids, entry) {
4313 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4314 err = write_commit_info(
4315 &s->line_offsets, &s->nlines,
4316 s->id2, refs, s->repo, s->f);
4317 if (err)
4318 goto done;
4319 break;
4323 got_object_commit_close(commit2);
4325 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4326 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4327 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4328 s->force_text_diff, s->repo, s->f);
4329 break;
4331 default:
4332 err = got_error(GOT_ERR_OBJ_TYPE);
4333 break;
4335 if (err)
4336 goto done;
4337 done:
4338 if (s->f && fflush(s->f) != 0 && err == NULL)
4339 err = got_error_from_errno("fflush");
4340 return err;
4343 static void
4344 diff_view_indicate_progress(struct tog_view *view)
4346 mvwaddstr(view->window, 0, 0, "diffing...");
4347 update_panels();
4348 doupdate();
4351 static const struct got_error *
4352 search_start_diff_view(struct tog_view *view)
4354 struct tog_diff_view_state *s = &view->state.diff;
4356 s->matched_line = 0;
4357 return NULL;
4360 static const struct got_error *
4361 search_next_diff_view(struct tog_view *view)
4363 struct tog_diff_view_state *s = &view->state.diff;
4364 const struct got_error *err = NULL;
4365 int lineno;
4366 char *line = NULL;
4367 size_t linesize = 0;
4368 ssize_t linelen;
4370 if (!view->searching) {
4371 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4372 return NULL;
4375 if (s->matched_line) {
4376 if (view->searching == TOG_SEARCH_FORWARD)
4377 lineno = s->matched_line + 1;
4378 else
4379 lineno = s->matched_line - 1;
4380 } else
4381 lineno = s->first_displayed_line;
4383 while (1) {
4384 off_t offset;
4386 if (lineno <= 0 || lineno > s->nlines) {
4387 if (s->matched_line == 0) {
4388 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4389 break;
4392 if (view->searching == TOG_SEARCH_FORWARD)
4393 lineno = 1;
4394 else
4395 lineno = s->nlines;
4398 offset = s->line_offsets[lineno - 1];
4399 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4400 free(line);
4401 return got_error_from_errno("fseeko");
4403 linelen = getline(&line, &linesize, s->f);
4404 if (linelen != -1) {
4405 char *exstr;
4406 err = expand_tab(&exstr, line);
4407 if (err)
4408 break;
4409 if (match_line(exstr, &view->regex, 1,
4410 &view->regmatch)) {
4411 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4412 s->matched_line = lineno;
4413 free(exstr);
4414 break;
4416 free(exstr);
4418 if (view->searching == TOG_SEARCH_FORWARD)
4419 lineno++;
4420 else
4421 lineno--;
4423 free(line);
4425 if (s->matched_line) {
4426 s->first_displayed_line = s->matched_line;
4427 s->selected_line = 1;
4430 return err;
4433 static const struct got_error *
4434 close_diff_view(struct tog_view *view)
4436 const struct got_error *err = NULL;
4437 struct tog_diff_view_state *s = &view->state.diff;
4439 free(s->id1);
4440 s->id1 = NULL;
4441 free(s->id2);
4442 s->id2 = NULL;
4443 if (s->f && fclose(s->f) == EOF)
4444 err = got_error_from_errno("fclose");
4445 s->f = NULL;
4446 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4447 err = got_error_from_errno("fclose");
4448 s->f1 = NULL;
4449 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4450 err = got_error_from_errno("fclose");
4451 s->f2 = NULL;
4452 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4453 err = got_error_from_errno("close");
4454 s->fd1 = -1;
4455 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4456 err = got_error_from_errno("close");
4457 s->fd2 = -1;
4458 free_colors(&s->colors);
4459 free(s->line_offsets);
4460 s->line_offsets = NULL;
4461 s->nlines = 0;
4462 return err;
4465 static const struct got_error *
4466 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4467 struct got_object_id *id2, const char *label1, const char *label2,
4468 int diff_context, int ignore_whitespace, int force_text_diff,
4469 struct tog_view *parent_view, struct got_repository *repo)
4471 const struct got_error *err;
4472 struct tog_diff_view_state *s = &view->state.diff;
4474 memset(s, 0, sizeof(*s));
4475 s->fd1 = -1;
4476 s->fd2 = -1;
4478 if (id1 != NULL && id2 != NULL) {
4479 int type1, type2;
4480 err = got_object_get_type(&type1, repo, id1);
4481 if (err)
4482 return err;
4483 err = got_object_get_type(&type2, repo, id2);
4484 if (err)
4485 return err;
4487 if (type1 != type2)
4488 return got_error(GOT_ERR_OBJ_TYPE);
4490 s->first_displayed_line = 1;
4491 s->last_displayed_line = view->nlines;
4492 s->selected_line = 1;
4493 s->repo = repo;
4494 s->id1 = id1;
4495 s->id2 = id2;
4496 s->label1 = label1;
4497 s->label2 = label2;
4499 if (id1) {
4500 s->id1 = got_object_id_dup(id1);
4501 if (s->id1 == NULL)
4502 return got_error_from_errno("got_object_id_dup");
4503 } else
4504 s->id1 = NULL;
4506 s->id2 = got_object_id_dup(id2);
4507 if (s->id2 == NULL) {
4508 err = got_error_from_errno("got_object_id_dup");
4509 goto done;
4512 s->f1 = got_opentemp();
4513 if (s->f1 == NULL) {
4514 err = got_error_from_errno("got_opentemp");
4515 goto done;
4518 s->f2 = got_opentemp();
4519 if (s->f2 == NULL) {
4520 err = got_error_from_errno("got_opentemp");
4521 goto done;
4524 s->fd1 = got_opentempfd();
4525 if (s->fd1 == -1) {
4526 err = got_error_from_errno("got_opentempfd");
4527 goto done;
4530 s->fd2 = got_opentempfd();
4531 if (s->fd2 == -1) {
4532 err = got_error_from_errno("got_opentempfd");
4533 goto done;
4536 s->first_displayed_line = 1;
4537 s->last_displayed_line = view->nlines;
4538 s->diff_context = diff_context;
4539 s->ignore_whitespace = ignore_whitespace;
4540 s->force_text_diff = force_text_diff;
4541 s->parent_view = parent_view;
4542 s->repo = repo;
4544 STAILQ_INIT(&s->colors);
4545 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4546 err = add_color(&s->colors,
4547 "^-", TOG_COLOR_DIFF_MINUS,
4548 get_color_value("TOG_COLOR_DIFF_MINUS"));
4549 if (err)
4550 goto done;
4551 err = add_color(&s->colors, "^\\+",
4552 TOG_COLOR_DIFF_PLUS,
4553 get_color_value("TOG_COLOR_DIFF_PLUS"));
4554 if (err)
4555 goto done;
4556 err = add_color(&s->colors,
4557 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4558 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4559 if (err)
4560 goto done;
4562 err = add_color(&s->colors,
4563 "^(commit [0-9a-f]|parent [0-9]|"
4564 "(blob|file|tree|commit) [-+] |"
4565 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4566 get_color_value("TOG_COLOR_DIFF_META"));
4567 if (err)
4568 goto done;
4570 err = add_color(&s->colors,
4571 "^(from|via): ", TOG_COLOR_AUTHOR,
4572 get_color_value("TOG_COLOR_AUTHOR"));
4573 if (err)
4574 goto done;
4576 err = add_color(&s->colors,
4577 "^date: ", TOG_COLOR_DATE,
4578 get_color_value("TOG_COLOR_DATE"));
4579 if (err)
4580 goto done;
4583 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4584 view_is_splitscreen(view))
4585 show_log_view(parent_view); /* draw border */
4586 diff_view_indicate_progress(view);
4588 err = create_diff(s);
4590 view->show = show_diff_view;
4591 view->input = input_diff_view;
4592 view->reset = reset_diff_view;
4593 view->close = close_diff_view;
4594 view->search_start = search_start_diff_view;
4595 view->search_next = search_next_diff_view;
4596 done:
4597 if (err)
4598 close_diff_view(view);
4599 return err;
4602 static const struct got_error *
4603 show_diff_view(struct tog_view *view)
4605 const struct got_error *err;
4606 struct tog_diff_view_state *s = &view->state.diff;
4607 char *id_str1 = NULL, *id_str2, *header;
4608 const char *label1, *label2;
4610 if (s->id1) {
4611 err = got_object_id_str(&id_str1, s->id1);
4612 if (err)
4613 return err;
4614 label1 = s->label1 ? : id_str1;
4615 } else
4616 label1 = "/dev/null";
4618 err = got_object_id_str(&id_str2, s->id2);
4619 if (err)
4620 return err;
4621 label2 = s->label2 ? : id_str2;
4623 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4624 err = got_error_from_errno("asprintf");
4625 free(id_str1);
4626 free(id_str2);
4627 return err;
4629 free(id_str1);
4630 free(id_str2);
4632 err = draw_file(view, header);
4633 free(header);
4634 return err;
4637 static const struct got_error *
4638 set_selected_commit(struct tog_diff_view_state *s,
4639 struct commit_queue_entry *entry)
4641 const struct got_error *err;
4642 const struct got_object_id_queue *parent_ids;
4643 struct got_commit_object *selected_commit;
4644 struct got_object_qid *pid;
4646 free(s->id2);
4647 s->id2 = got_object_id_dup(entry->id);
4648 if (s->id2 == NULL)
4649 return got_error_from_errno("got_object_id_dup");
4651 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4652 if (err)
4653 return err;
4654 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4655 free(s->id1);
4656 pid = STAILQ_FIRST(parent_ids);
4657 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4658 got_object_commit_close(selected_commit);
4659 return NULL;
4662 static const struct got_error *
4663 reset_diff_view(struct tog_view *view)
4665 struct tog_diff_view_state *s = &view->state.diff;
4667 view->count = 0;
4668 wclear(view->window);
4669 s->first_displayed_line = 1;
4670 s->last_displayed_line = view->nlines;
4671 s->matched_line = 0;
4672 diff_view_indicate_progress(view);
4673 return create_diff(s);
4676 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4677 int, int, int);
4678 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4679 int, int);
4681 static const struct got_error *
4682 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4684 const struct got_error *err = NULL;
4685 struct tog_diff_view_state *s = &view->state.diff;
4686 struct tog_log_view_state *ls;
4687 struct commit_queue_entry *old_selected_entry;
4688 char *line = NULL;
4689 size_t linesize = 0;
4690 ssize_t linelen;
4691 int i, nscroll = view->nlines - 1, up = 0;
4693 switch (ch) {
4694 case '0':
4695 view->x = 0;
4696 break;
4697 case '$':
4698 view->x = MAX(view->maxx - view->ncols / 3, 0);
4699 view->count = 0;
4700 break;
4701 case KEY_RIGHT:
4702 case 'l':
4703 if (view->x + view->ncols / 3 < view->maxx)
4704 view->x += 2; /* move two columns right */
4705 else
4706 view->count = 0;
4707 break;
4708 case KEY_LEFT:
4709 case 'h':
4710 view->x -= MIN(view->x, 2); /* move two columns back */
4711 if (view->x <= 0)
4712 view->count = 0;
4713 break;
4714 case 'a':
4715 case 'w':
4716 if (ch == 'a')
4717 s->force_text_diff = !s->force_text_diff;
4718 if (ch == 'w')
4719 s->ignore_whitespace = !s->ignore_whitespace;
4720 err = reset_diff_view(view);
4721 break;
4722 case 'g':
4723 case KEY_HOME:
4724 s->first_displayed_line = 1;
4725 view->count = 0;
4726 break;
4727 case 'G':
4728 case KEY_END:
4729 view->count = 0;
4730 if (s->eof)
4731 break;
4733 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4734 s->eof = 1;
4735 break;
4736 case 'k':
4737 case KEY_UP:
4738 case CTRL('p'):
4739 if (s->first_displayed_line > 1)
4740 s->first_displayed_line--;
4741 else
4742 view->count = 0;
4743 break;
4744 case CTRL('u'):
4745 case 'u':
4746 nscroll /= 2;
4747 /* FALL THROUGH */
4748 case KEY_PPAGE:
4749 case CTRL('b'):
4750 case 'b':
4751 if (s->first_displayed_line == 1) {
4752 view->count = 0;
4753 break;
4755 i = 0;
4756 while (i++ < nscroll && s->first_displayed_line > 1)
4757 s->first_displayed_line--;
4758 break;
4759 case 'j':
4760 case KEY_DOWN:
4761 case CTRL('n'):
4762 if (!s->eof)
4763 s->first_displayed_line++;
4764 else
4765 view->count = 0;
4766 break;
4767 case CTRL('d'):
4768 case 'd':
4769 nscroll /= 2;
4770 /* FALL THROUGH */
4771 case KEY_NPAGE:
4772 case CTRL('f'):
4773 case 'f':
4774 case ' ':
4775 if (s->eof) {
4776 view->count = 0;
4777 break;
4779 i = 0;
4780 while (!s->eof && i++ < nscroll) {
4781 linelen = getline(&line, &linesize, s->f);
4782 s->first_displayed_line++;
4783 if (linelen == -1) {
4784 if (feof(s->f)) {
4785 s->eof = 1;
4786 } else
4787 err = got_ferror(s->f, GOT_ERR_IO);
4788 break;
4791 free(line);
4792 break;
4793 case '[':
4794 if (s->diff_context > 0) {
4795 s->diff_context--;
4796 s->matched_line = 0;
4797 diff_view_indicate_progress(view);
4798 err = create_diff(s);
4799 if (s->first_displayed_line + view->nlines - 1 >
4800 s->nlines) {
4801 s->first_displayed_line = 1;
4802 s->last_displayed_line = view->nlines;
4804 } else
4805 view->count = 0;
4806 break;
4807 case ']':
4808 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4809 s->diff_context++;
4810 s->matched_line = 0;
4811 diff_view_indicate_progress(view);
4812 err = create_diff(s);
4813 } else
4814 view->count = 0;
4815 break;
4816 case '<':
4817 case ',':
4818 up = 1;
4819 /* FALL THROUGH */
4820 case '>':
4821 case '.':
4822 if (s->parent_view == NULL) {
4823 view->count = 0;
4824 break;
4826 s->parent_view->count = view->count;
4828 if (s->parent_view->type == TOG_VIEW_LOG) {
4829 ls = &s->parent_view->state.log;
4830 old_selected_entry = ls->selected_entry;
4832 err = input_log_view(NULL, s->parent_view,
4833 up ? KEY_UP : KEY_DOWN);
4834 if (err)
4835 break;
4836 view->count = s->parent_view->count;
4838 if (old_selected_entry == ls->selected_entry)
4839 break;
4841 err = set_selected_commit(s, ls->selected_entry);
4842 if (err)
4843 break;
4844 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4845 struct tog_blame_view_state *bs;
4846 struct got_object_id *id, *prev_id;
4848 bs = &s->parent_view->state.blame;
4849 prev_id = get_annotation_for_line(bs->blame.lines,
4850 bs->blame.nlines, bs->last_diffed_line);
4852 err = input_blame_view(&view, s->parent_view,
4853 up ? KEY_UP : KEY_DOWN);
4854 if (err)
4855 break;
4856 view->count = s->parent_view->count;
4858 if (prev_id == NULL)
4859 break;
4860 id = get_selected_commit_id(bs->blame.lines,
4861 bs->blame.nlines, bs->first_displayed_line,
4862 bs->selected_line);
4863 if (id == NULL)
4864 break;
4866 if (!got_object_id_cmp(prev_id, id))
4867 break;
4869 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
4870 if (err)
4871 break;
4873 s->first_displayed_line = 1;
4874 s->last_displayed_line = view->nlines;
4875 s->matched_line = 0;
4876 view->x = 0;
4878 diff_view_indicate_progress(view);
4879 err = create_diff(s);
4880 break;
4881 default:
4882 view->count = 0;
4883 break;
4886 return err;
4889 static const struct got_error *
4890 cmd_diff(int argc, char *argv[])
4892 const struct got_error *error = NULL;
4893 struct got_repository *repo = NULL;
4894 struct got_worktree *worktree = NULL;
4895 struct got_object_id *id1 = NULL, *id2 = NULL;
4896 char *repo_path = NULL, *cwd = NULL;
4897 char *id_str1 = NULL, *id_str2 = NULL;
4898 char *label1 = NULL, *label2 = NULL;
4899 int diff_context = 3, ignore_whitespace = 0;
4900 int ch, force_text_diff = 0;
4901 const char *errstr;
4902 struct tog_view *view;
4903 int *pack_fds = NULL;
4905 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4906 switch (ch) {
4907 case 'a':
4908 force_text_diff = 1;
4909 break;
4910 case 'C':
4911 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4912 &errstr);
4913 if (errstr != NULL)
4914 errx(1, "number of context lines is %s: %s",
4915 errstr, errstr);
4916 break;
4917 case 'r':
4918 repo_path = realpath(optarg, NULL);
4919 if (repo_path == NULL)
4920 return got_error_from_errno2("realpath",
4921 optarg);
4922 got_path_strip_trailing_slashes(repo_path);
4923 break;
4924 case 'w':
4925 ignore_whitespace = 1;
4926 break;
4927 default:
4928 usage_diff();
4929 /* NOTREACHED */
4933 argc -= optind;
4934 argv += optind;
4936 if (argc == 0) {
4937 usage_diff(); /* TODO show local worktree changes */
4938 } else if (argc == 2) {
4939 id_str1 = argv[0];
4940 id_str2 = argv[1];
4941 } else
4942 usage_diff();
4944 error = got_repo_pack_fds_open(&pack_fds);
4945 if (error)
4946 goto done;
4948 if (repo_path == NULL) {
4949 cwd = getcwd(NULL, 0);
4950 if (cwd == NULL)
4951 return got_error_from_errno("getcwd");
4952 error = got_worktree_open(&worktree, cwd);
4953 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4954 goto done;
4955 if (worktree)
4956 repo_path =
4957 strdup(got_worktree_get_repo_path(worktree));
4958 else
4959 repo_path = strdup(cwd);
4960 if (repo_path == NULL) {
4961 error = got_error_from_errno("strdup");
4962 goto done;
4966 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4967 if (error)
4968 goto done;
4970 init_curses();
4972 error = apply_unveil(got_repo_get_path(repo), NULL);
4973 if (error)
4974 goto done;
4976 error = tog_load_refs(repo, 0);
4977 if (error)
4978 goto done;
4980 error = got_repo_match_object_id(&id1, &label1, id_str1,
4981 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4982 if (error)
4983 goto done;
4985 error = got_repo_match_object_id(&id2, &label2, id_str2,
4986 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4987 if (error)
4988 goto done;
4990 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4991 if (view == NULL) {
4992 error = got_error_from_errno("view_open");
4993 goto done;
4995 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4996 ignore_whitespace, force_text_diff, NULL, repo);
4997 if (error)
4998 goto done;
4999 error = view_loop(view);
5000 done:
5001 free(label1);
5002 free(label2);
5003 free(repo_path);
5004 free(cwd);
5005 if (repo) {
5006 const struct got_error *close_err = got_repo_close(repo);
5007 if (error == NULL)
5008 error = close_err;
5010 if (worktree)
5011 got_worktree_close(worktree);
5012 if (pack_fds) {
5013 const struct got_error *pack_err =
5014 got_repo_pack_fds_close(pack_fds);
5015 if (error == NULL)
5016 error = pack_err;
5018 tog_free_refs();
5019 return error;
5022 __dead static void
5023 usage_blame(void)
5025 endwin();
5026 fprintf(stderr,
5027 "usage: %s blame [-c commit] [-r repository-path] path\n",
5028 getprogname());
5029 exit(1);
5032 struct tog_blame_line {
5033 int annotated;
5034 struct got_object_id *id;
5037 static const struct got_error *
5038 draw_blame(struct tog_view *view)
5040 struct tog_blame_view_state *s = &view->state.blame;
5041 struct tog_blame *blame = &s->blame;
5042 regmatch_t *regmatch = &view->regmatch;
5043 const struct got_error *err;
5044 int lineno = 0, nprinted = 0;
5045 char *line = NULL;
5046 size_t linesize = 0;
5047 ssize_t linelen;
5048 wchar_t *wline;
5049 int width;
5050 struct tog_blame_line *blame_line;
5051 struct got_object_id *prev_id = NULL;
5052 char *id_str;
5053 struct tog_color *tc;
5055 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5056 if (err)
5057 return err;
5059 rewind(blame->f);
5060 werase(view->window);
5062 if (asprintf(&line, "commit %s", id_str) == -1) {
5063 err = got_error_from_errno("asprintf");
5064 free(id_str);
5065 return err;
5068 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5069 free(line);
5070 line = NULL;
5071 if (err)
5072 return err;
5073 if (view_needs_focus_indication(view))
5074 wstandout(view->window);
5075 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5076 if (tc)
5077 wattr_on(view->window,
5078 COLOR_PAIR(tc->colorpair), NULL);
5079 waddwstr(view->window, wline);
5080 if (tc)
5081 wattr_off(view->window,
5082 COLOR_PAIR(tc->colorpair), NULL);
5083 if (view_needs_focus_indication(view))
5084 wstandend(view->window);
5085 free(wline);
5086 wline = NULL;
5087 if (width < view->ncols - 1)
5088 waddch(view->window, '\n');
5090 if (asprintf(&line, "[%d/%d] %s%s",
5091 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5092 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5093 free(id_str);
5094 return got_error_from_errno("asprintf");
5096 free(id_str);
5097 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5098 free(line);
5099 line = NULL;
5100 if (err)
5101 return err;
5102 waddwstr(view->window, wline);
5103 free(wline);
5104 wline = NULL;
5105 if (width < view->ncols - 1)
5106 waddch(view->window, '\n');
5108 s->eof = 0;
5109 view->maxx = 0;
5110 while (nprinted < view->nlines - 2) {
5111 linelen = getline(&line, &linesize, blame->f);
5112 if (linelen == -1) {
5113 if (feof(blame->f)) {
5114 s->eof = 1;
5115 break;
5117 free(line);
5118 return got_ferror(blame->f, GOT_ERR_IO);
5120 if (++lineno < s->first_displayed_line)
5121 continue;
5123 /* Set view->maxx based on full line length. */
5124 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5125 if (err) {
5126 free(line);
5127 return err;
5129 free(wline);
5130 wline = NULL;
5131 view->maxx = MAX(view->maxx, width);
5133 if (nprinted == s->selected_line - 1)
5134 wstandout(view->window);
5136 if (blame->nlines > 0) {
5137 blame_line = &blame->lines[lineno - 1];
5138 if (blame_line->annotated && prev_id &&
5139 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5140 !(nprinted == s->selected_line - 1)) {
5141 waddstr(view->window, " ");
5142 } else if (blame_line->annotated) {
5143 char *id_str;
5144 err = got_object_id_str(&id_str,
5145 blame_line->id);
5146 if (err) {
5147 free(line);
5148 return err;
5150 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5151 if (tc)
5152 wattr_on(view->window,
5153 COLOR_PAIR(tc->colorpair), NULL);
5154 wprintw(view->window, "%.8s", id_str);
5155 if (tc)
5156 wattr_off(view->window,
5157 COLOR_PAIR(tc->colorpair), NULL);
5158 free(id_str);
5159 prev_id = blame_line->id;
5160 } else {
5161 waddstr(view->window, "........");
5162 prev_id = NULL;
5164 } else {
5165 waddstr(view->window, "........");
5166 prev_id = NULL;
5169 if (nprinted == s->selected_line - 1)
5170 wstandend(view->window);
5171 waddstr(view->window, " ");
5173 if (view->ncols <= 9) {
5174 width = 9;
5175 } else if (s->first_displayed_line + nprinted ==
5176 s->matched_line &&
5177 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5178 err = add_matched_line(&width, line, view->ncols - 9, 9,
5179 view->window, view->x, regmatch);
5180 if (err) {
5181 free(line);
5182 return err;
5184 width += 9;
5185 } else {
5186 int skip;
5187 err = format_line(&wline, &width, &skip, line,
5188 view->x, view->ncols - 9, 9, 1);
5189 if (err) {
5190 free(line);
5191 return err;
5193 waddwstr(view->window, &wline[skip]);
5194 width += 9;
5195 free(wline);
5196 wline = NULL;
5199 if (width <= view->ncols - 1)
5200 waddch(view->window, '\n');
5201 if (++nprinted == 1)
5202 s->first_displayed_line = lineno;
5204 free(line);
5205 s->last_displayed_line = lineno;
5207 view_border(view);
5209 return NULL;
5212 static const struct got_error *
5213 blame_cb(void *arg, int nlines, int lineno,
5214 struct got_commit_object *commit, struct got_object_id *id)
5216 const struct got_error *err = NULL;
5217 struct tog_blame_cb_args *a = arg;
5218 struct tog_blame_line *line;
5219 int errcode;
5221 if (nlines != a->nlines ||
5222 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5223 return got_error(GOT_ERR_RANGE);
5225 errcode = pthread_mutex_lock(&tog_mutex);
5226 if (errcode)
5227 return got_error_set_errno(errcode, "pthread_mutex_lock");
5229 if (*a->quit) { /* user has quit the blame view */
5230 err = got_error(GOT_ERR_ITER_COMPLETED);
5231 goto done;
5234 if (lineno == -1)
5235 goto done; /* no change in this commit */
5237 line = &a->lines[lineno - 1];
5238 if (line->annotated)
5239 goto done;
5241 line->id = got_object_id_dup(id);
5242 if (line->id == NULL) {
5243 err = got_error_from_errno("got_object_id_dup");
5244 goto done;
5246 line->annotated = 1;
5247 done:
5248 errcode = pthread_mutex_unlock(&tog_mutex);
5249 if (errcode)
5250 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5251 return err;
5254 static void *
5255 blame_thread(void *arg)
5257 const struct got_error *err, *close_err;
5258 struct tog_blame_thread_args *ta = arg;
5259 struct tog_blame_cb_args *a = ta->cb_args;
5260 int errcode, fd1 = -1, fd2 = -1;
5261 FILE *f1 = NULL, *f2 = NULL;
5263 fd1 = got_opentempfd();
5264 if (fd1 == -1)
5265 return (void *)got_error_from_errno("got_opentempfd");
5267 fd2 = got_opentempfd();
5268 if (fd2 == -1) {
5269 err = got_error_from_errno("got_opentempfd");
5270 goto done;
5273 f1 = got_opentemp();
5274 if (f1 == NULL) {
5275 err = (void *)got_error_from_errno("got_opentemp");
5276 goto done;
5278 f2 = got_opentemp();
5279 if (f2 == NULL) {
5280 err = (void *)got_error_from_errno("got_opentemp");
5281 goto done;
5284 err = block_signals_used_by_main_thread();
5285 if (err)
5286 goto done;
5288 err = got_blame(ta->path, a->commit_id, ta->repo,
5289 tog_diff_algo, blame_cb, ta->cb_args,
5290 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5291 if (err && err->code == GOT_ERR_CANCELLED)
5292 err = NULL;
5294 errcode = pthread_mutex_lock(&tog_mutex);
5295 if (errcode) {
5296 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5297 goto done;
5300 close_err = got_repo_close(ta->repo);
5301 if (err == NULL)
5302 err = close_err;
5303 ta->repo = NULL;
5304 *ta->complete = 1;
5306 errcode = pthread_mutex_unlock(&tog_mutex);
5307 if (errcode && err == NULL)
5308 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5310 done:
5311 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5312 err = got_error_from_errno("close");
5313 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5314 err = got_error_from_errno("close");
5315 if (f1 && fclose(f1) == EOF && err == NULL)
5316 err = got_error_from_errno("fclose");
5317 if (f2 && fclose(f2) == EOF && err == NULL)
5318 err = got_error_from_errno("fclose");
5320 return (void *)err;
5323 static struct got_object_id *
5324 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5325 int first_displayed_line, int selected_line)
5327 struct tog_blame_line *line;
5329 if (nlines <= 0)
5330 return NULL;
5332 line = &lines[first_displayed_line - 1 + selected_line - 1];
5333 if (!line->annotated)
5334 return NULL;
5336 return line->id;
5339 static struct got_object_id *
5340 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5341 int lineno)
5343 struct tog_blame_line *line;
5345 if (nlines <= 0 || lineno >= nlines)
5346 return NULL;
5348 line = &lines[lineno - 1];
5349 if (!line->annotated)
5350 return NULL;
5352 return line->id;
5355 static const struct got_error *
5356 stop_blame(struct tog_blame *blame)
5358 const struct got_error *err = NULL;
5359 int i;
5361 if (blame->thread) {
5362 int errcode;
5363 errcode = pthread_mutex_unlock(&tog_mutex);
5364 if (errcode)
5365 return got_error_set_errno(errcode,
5366 "pthread_mutex_unlock");
5367 errcode = pthread_join(blame->thread, (void **)&err);
5368 if (errcode)
5369 return got_error_set_errno(errcode, "pthread_join");
5370 errcode = pthread_mutex_lock(&tog_mutex);
5371 if (errcode)
5372 return got_error_set_errno(errcode,
5373 "pthread_mutex_lock");
5374 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5375 err = NULL;
5376 blame->thread = NULL;
5378 if (blame->thread_args.repo) {
5379 const struct got_error *close_err;
5380 close_err = got_repo_close(blame->thread_args.repo);
5381 if (err == NULL)
5382 err = close_err;
5383 blame->thread_args.repo = NULL;
5385 if (blame->f) {
5386 if (fclose(blame->f) == EOF && err == NULL)
5387 err = got_error_from_errno("fclose");
5388 blame->f = NULL;
5390 if (blame->lines) {
5391 for (i = 0; i < blame->nlines; i++)
5392 free(blame->lines[i].id);
5393 free(blame->lines);
5394 blame->lines = NULL;
5396 free(blame->cb_args.commit_id);
5397 blame->cb_args.commit_id = NULL;
5398 if (blame->pack_fds) {
5399 const struct got_error *pack_err =
5400 got_repo_pack_fds_close(blame->pack_fds);
5401 if (err == NULL)
5402 err = pack_err;
5403 blame->pack_fds = NULL;
5405 return err;
5408 static const struct got_error *
5409 cancel_blame_view(void *arg)
5411 const struct got_error *err = NULL;
5412 int *done = arg;
5413 int errcode;
5415 errcode = pthread_mutex_lock(&tog_mutex);
5416 if (errcode)
5417 return got_error_set_errno(errcode,
5418 "pthread_mutex_unlock");
5420 if (*done)
5421 err = got_error(GOT_ERR_CANCELLED);
5423 errcode = pthread_mutex_unlock(&tog_mutex);
5424 if (errcode)
5425 return got_error_set_errno(errcode,
5426 "pthread_mutex_lock");
5428 return err;
5431 static const struct got_error *
5432 run_blame(struct tog_view *view)
5434 struct tog_blame_view_state *s = &view->state.blame;
5435 struct tog_blame *blame = &s->blame;
5436 const struct got_error *err = NULL;
5437 struct got_commit_object *commit = NULL;
5438 struct got_blob_object *blob = NULL;
5439 struct got_repository *thread_repo = NULL;
5440 struct got_object_id *obj_id = NULL;
5441 int obj_type, fd = -1;
5442 int *pack_fds = NULL;
5444 err = got_object_open_as_commit(&commit, s->repo,
5445 &s->blamed_commit->id);
5446 if (err)
5447 return err;
5449 fd = got_opentempfd();
5450 if (fd == -1) {
5451 err = got_error_from_errno("got_opentempfd");
5452 goto done;
5455 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5456 if (err)
5457 goto done;
5459 err = got_object_get_type(&obj_type, s->repo, obj_id);
5460 if (err)
5461 goto done;
5463 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5464 err = got_error(GOT_ERR_OBJ_TYPE);
5465 goto done;
5468 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5469 if (err)
5470 goto done;
5471 blame->f = got_opentemp();
5472 if (blame->f == NULL) {
5473 err = got_error_from_errno("got_opentemp");
5474 goto done;
5476 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5477 &blame->line_offsets, blame->f, blob);
5478 if (err)
5479 goto done;
5480 if (blame->nlines == 0) {
5481 s->blame_complete = 1;
5482 goto done;
5485 /* Don't include \n at EOF in the blame line count. */
5486 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5487 blame->nlines--;
5489 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5490 if (blame->lines == NULL) {
5491 err = got_error_from_errno("calloc");
5492 goto done;
5495 err = got_repo_pack_fds_open(&pack_fds);
5496 if (err)
5497 goto done;
5498 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5499 pack_fds);
5500 if (err)
5501 goto done;
5503 blame->pack_fds = pack_fds;
5504 blame->cb_args.view = view;
5505 blame->cb_args.lines = blame->lines;
5506 blame->cb_args.nlines = blame->nlines;
5507 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5508 if (blame->cb_args.commit_id == NULL) {
5509 err = got_error_from_errno("got_object_id_dup");
5510 goto done;
5512 blame->cb_args.quit = &s->done;
5514 blame->thread_args.path = s->path;
5515 blame->thread_args.repo = thread_repo;
5516 blame->thread_args.cb_args = &blame->cb_args;
5517 blame->thread_args.complete = &s->blame_complete;
5518 blame->thread_args.cancel_cb = cancel_blame_view;
5519 blame->thread_args.cancel_arg = &s->done;
5520 s->blame_complete = 0;
5522 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5523 s->first_displayed_line = 1;
5524 s->last_displayed_line = view->nlines;
5525 s->selected_line = 1;
5527 s->matched_line = 0;
5529 done:
5530 if (commit)
5531 got_object_commit_close(commit);
5532 if (fd != -1 && close(fd) == -1 && err == NULL)
5533 err = got_error_from_errno("close");
5534 if (blob)
5535 got_object_blob_close(blob);
5536 free(obj_id);
5537 if (err)
5538 stop_blame(blame);
5539 return err;
5542 static const struct got_error *
5543 open_blame_view(struct tog_view *view, char *path,
5544 struct got_object_id *commit_id, struct got_repository *repo)
5546 const struct got_error *err = NULL;
5547 struct tog_blame_view_state *s = &view->state.blame;
5549 STAILQ_INIT(&s->blamed_commits);
5551 s->path = strdup(path);
5552 if (s->path == NULL)
5553 return got_error_from_errno("strdup");
5555 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5556 if (err) {
5557 free(s->path);
5558 return err;
5561 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5562 s->first_displayed_line = 1;
5563 s->last_displayed_line = view->nlines;
5564 s->selected_line = 1;
5565 s->blame_complete = 0;
5566 s->repo = repo;
5567 s->commit_id = commit_id;
5568 memset(&s->blame, 0, sizeof(s->blame));
5570 STAILQ_INIT(&s->colors);
5571 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5572 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5573 get_color_value("TOG_COLOR_COMMIT"));
5574 if (err)
5575 return err;
5578 view->show = show_blame_view;
5579 view->input = input_blame_view;
5580 view->reset = reset_blame_view;
5581 view->close = close_blame_view;
5582 view->search_start = search_start_blame_view;
5583 view->search_next = search_next_blame_view;
5585 return run_blame(view);
5588 static const struct got_error *
5589 close_blame_view(struct tog_view *view)
5591 const struct got_error *err = NULL;
5592 struct tog_blame_view_state *s = &view->state.blame;
5594 if (s->blame.thread)
5595 err = stop_blame(&s->blame);
5597 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5598 struct got_object_qid *blamed_commit;
5599 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5600 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5601 got_object_qid_free(blamed_commit);
5604 free(s->path);
5605 free_colors(&s->colors);
5606 return err;
5609 static const struct got_error *
5610 search_start_blame_view(struct tog_view *view)
5612 struct tog_blame_view_state *s = &view->state.blame;
5614 s->matched_line = 0;
5615 return NULL;
5618 static const struct got_error *
5619 search_next_blame_view(struct tog_view *view)
5621 struct tog_blame_view_state *s = &view->state.blame;
5622 const struct got_error *err = NULL;
5623 int lineno;
5624 char *line = NULL;
5625 size_t linesize = 0;
5626 ssize_t linelen;
5628 if (!view->searching) {
5629 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5630 return NULL;
5633 if (s->matched_line) {
5634 if (view->searching == TOG_SEARCH_FORWARD)
5635 lineno = s->matched_line + 1;
5636 else
5637 lineno = s->matched_line - 1;
5638 } else
5639 lineno = s->first_displayed_line - 1 + s->selected_line;
5641 while (1) {
5642 off_t offset;
5644 if (lineno <= 0 || lineno > s->blame.nlines) {
5645 if (s->matched_line == 0) {
5646 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5647 break;
5650 if (view->searching == TOG_SEARCH_FORWARD)
5651 lineno = 1;
5652 else
5653 lineno = s->blame.nlines;
5656 offset = s->blame.line_offsets[lineno - 1];
5657 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5658 free(line);
5659 return got_error_from_errno("fseeko");
5661 linelen = getline(&line, &linesize, s->blame.f);
5662 if (linelen != -1) {
5663 char *exstr;
5664 err = expand_tab(&exstr, line);
5665 if (err)
5666 break;
5667 if (match_line(exstr, &view->regex, 1,
5668 &view->regmatch)) {
5669 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5670 s->matched_line = lineno;
5671 free(exstr);
5672 break;
5674 free(exstr);
5676 if (view->searching == TOG_SEARCH_FORWARD)
5677 lineno++;
5678 else
5679 lineno--;
5681 free(line);
5683 if (s->matched_line) {
5684 s->first_displayed_line = s->matched_line;
5685 s->selected_line = 1;
5688 return err;
5691 static const struct got_error *
5692 show_blame_view(struct tog_view *view)
5694 const struct got_error *err = NULL;
5695 struct tog_blame_view_state *s = &view->state.blame;
5696 int errcode;
5698 if (s->blame.thread == NULL && !s->blame_complete) {
5699 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5700 &s->blame.thread_args);
5701 if (errcode)
5702 return got_error_set_errno(errcode, "pthread_create");
5704 halfdelay(1); /* fast refresh while annotating */
5707 if (s->blame_complete)
5708 halfdelay(10); /* disable fast refresh */
5710 err = draw_blame(view);
5712 view_border(view);
5713 return err;
5716 static const struct got_error *
5717 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5719 const struct got_error *err = NULL, *thread_err = NULL;
5720 struct tog_view *diff_view;
5721 struct tog_blame_view_state *s = &view->state.blame;
5722 int eos, nscroll, begin_y = 0, begin_x = 0;
5724 eos = nscroll = view->nlines - 2;
5725 if (view_is_hsplit_top(view))
5726 --eos; /* border */
5728 switch (ch) {
5729 case '0':
5730 view->x = 0;
5731 break;
5732 case '$':
5733 view->x = MAX(view->maxx - view->ncols / 3, 0);
5734 view->count = 0;
5735 break;
5736 case KEY_RIGHT:
5737 case 'l':
5738 if (view->x + view->ncols / 3 < view->maxx)
5739 view->x += 2; /* move two columns right */
5740 else
5741 view->count = 0;
5742 break;
5743 case KEY_LEFT:
5744 case 'h':
5745 view->x -= MIN(view->x, 2); /* move two columns back */
5746 if (view->x <= 0)
5747 view->count = 0;
5748 break;
5749 case 'q':
5750 s->done = 1;
5751 break;
5752 case 'g':
5753 case KEY_HOME:
5754 s->selected_line = 1;
5755 s->first_displayed_line = 1;
5756 view->count = 0;
5757 break;
5758 case 'G':
5759 case KEY_END:
5760 if (s->blame.nlines < eos) {
5761 s->selected_line = s->blame.nlines;
5762 s->first_displayed_line = 1;
5763 } else {
5764 s->selected_line = eos;
5765 s->first_displayed_line = s->blame.nlines - (eos - 1);
5767 view->count = 0;
5768 break;
5769 case 'k':
5770 case KEY_UP:
5771 case CTRL('p'):
5772 if (s->selected_line > 1)
5773 s->selected_line--;
5774 else if (s->selected_line == 1 &&
5775 s->first_displayed_line > 1)
5776 s->first_displayed_line--;
5777 else
5778 view->count = 0;
5779 break;
5780 case CTRL('u'):
5781 case 'u':
5782 nscroll /= 2;
5783 /* FALL THROUGH */
5784 case KEY_PPAGE:
5785 case CTRL('b'):
5786 case 'b':
5787 if (s->first_displayed_line == 1) {
5788 if (view->count > 1)
5789 nscroll += nscroll;
5790 s->selected_line = MAX(1, s->selected_line - nscroll);
5791 view->count = 0;
5792 break;
5794 if (s->first_displayed_line > nscroll)
5795 s->first_displayed_line -= nscroll;
5796 else
5797 s->first_displayed_line = 1;
5798 break;
5799 case 'j':
5800 case KEY_DOWN:
5801 case CTRL('n'):
5802 if (s->selected_line < eos && s->first_displayed_line +
5803 s->selected_line <= s->blame.nlines)
5804 s->selected_line++;
5805 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5806 s->first_displayed_line++;
5807 else
5808 view->count = 0;
5809 break;
5810 case 'c':
5811 case 'p': {
5812 struct got_object_id *id = NULL;
5814 view->count = 0;
5815 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5816 s->first_displayed_line, s->selected_line);
5817 if (id == NULL)
5818 break;
5819 if (ch == 'p') {
5820 struct got_commit_object *commit, *pcommit;
5821 struct got_object_qid *pid;
5822 struct got_object_id *blob_id = NULL;
5823 int obj_type;
5824 err = got_object_open_as_commit(&commit,
5825 s->repo, id);
5826 if (err)
5827 break;
5828 pid = STAILQ_FIRST(
5829 got_object_commit_get_parent_ids(commit));
5830 if (pid == NULL) {
5831 got_object_commit_close(commit);
5832 break;
5834 /* Check if path history ends here. */
5835 err = got_object_open_as_commit(&pcommit,
5836 s->repo, &pid->id);
5837 if (err)
5838 break;
5839 err = got_object_id_by_path(&blob_id, s->repo,
5840 pcommit, s->path);
5841 got_object_commit_close(pcommit);
5842 if (err) {
5843 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5844 err = NULL;
5845 got_object_commit_close(commit);
5846 break;
5848 err = got_object_get_type(&obj_type, s->repo,
5849 blob_id);
5850 free(blob_id);
5851 /* Can't blame non-blob type objects. */
5852 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5853 got_object_commit_close(commit);
5854 break;
5856 err = got_object_qid_alloc(&s->blamed_commit,
5857 &pid->id);
5858 got_object_commit_close(commit);
5859 } else {
5860 if (got_object_id_cmp(id,
5861 &s->blamed_commit->id) == 0)
5862 break;
5863 err = got_object_qid_alloc(&s->blamed_commit,
5864 id);
5866 if (err)
5867 break;
5868 s->done = 1;
5869 thread_err = stop_blame(&s->blame);
5870 s->done = 0;
5871 if (thread_err)
5872 break;
5873 STAILQ_INSERT_HEAD(&s->blamed_commits,
5874 s->blamed_commit, entry);
5875 err = run_blame(view);
5876 if (err)
5877 break;
5878 break;
5880 case 'C': {
5881 struct got_object_qid *first;
5883 view->count = 0;
5884 first = STAILQ_FIRST(&s->blamed_commits);
5885 if (!got_object_id_cmp(&first->id, s->commit_id))
5886 break;
5887 s->done = 1;
5888 thread_err = stop_blame(&s->blame);
5889 s->done = 0;
5890 if (thread_err)
5891 break;
5892 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5893 got_object_qid_free(s->blamed_commit);
5894 s->blamed_commit =
5895 STAILQ_FIRST(&s->blamed_commits);
5896 err = run_blame(view);
5897 if (err)
5898 break;
5899 break;
5901 case KEY_ENTER:
5902 case '\r': {
5903 struct got_object_id *id = NULL;
5904 struct got_object_qid *pid;
5905 struct got_commit_object *commit = NULL;
5907 view->count = 0;
5908 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5909 s->first_displayed_line, s->selected_line);
5910 if (id == NULL)
5911 break;
5912 err = got_object_open_as_commit(&commit, s->repo, id);
5913 if (err)
5914 break;
5915 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5916 if (*new_view) {
5917 /* traversed from diff view, release diff resources */
5918 err = close_diff_view(*new_view);
5919 if (err)
5920 break;
5921 diff_view = *new_view;
5922 } else {
5923 if (view_is_parent_view(view))
5924 view_get_split(view, &begin_y, &begin_x);
5926 diff_view = view_open(0, 0, begin_y, begin_x,
5927 TOG_VIEW_DIFF);
5928 if (diff_view == NULL) {
5929 got_object_commit_close(commit);
5930 err = got_error_from_errno("view_open");
5931 break;
5934 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5935 id, NULL, NULL, 3, 0, 0, view, s->repo);
5936 got_object_commit_close(commit);
5937 if (err) {
5938 view_close(diff_view);
5939 break;
5941 s->last_diffed_line = s->first_displayed_line - 1 +
5942 s->selected_line;
5943 if (*new_view)
5944 break; /* still open from active diff view */
5945 if (view_is_parent_view(view) &&
5946 view->mode == TOG_VIEW_SPLIT_HRZN) {
5947 err = view_init_hsplit(view, begin_y);
5948 if (err)
5949 break;
5952 view->focussed = 0;
5953 diff_view->focussed = 1;
5954 diff_view->mode = view->mode;
5955 diff_view->nlines = view->lines - begin_y;
5956 if (view_is_parent_view(view)) {
5957 view_transfer_size(diff_view, view);
5958 err = view_close_child(view);
5959 if (err)
5960 break;
5961 err = view_set_child(view, diff_view);
5962 if (err)
5963 break;
5964 view->focus_child = 1;
5965 } else
5966 *new_view = diff_view;
5967 if (err)
5968 break;
5969 break;
5971 case CTRL('d'):
5972 case 'd':
5973 nscroll /= 2;
5974 /* FALL THROUGH */
5975 case KEY_NPAGE:
5976 case CTRL('f'):
5977 case 'f':
5978 case ' ':
5979 if (s->last_displayed_line >= s->blame.nlines &&
5980 s->selected_line >= MIN(s->blame.nlines,
5981 view->nlines - 2)) {
5982 view->count = 0;
5983 break;
5985 if (s->last_displayed_line >= s->blame.nlines &&
5986 s->selected_line < view->nlines - 2) {
5987 s->selected_line +=
5988 MIN(nscroll, s->last_displayed_line -
5989 s->first_displayed_line - s->selected_line + 1);
5991 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5992 s->first_displayed_line += nscroll;
5993 else
5994 s->first_displayed_line =
5995 s->blame.nlines - (view->nlines - 3);
5996 break;
5997 case KEY_RESIZE:
5998 if (s->selected_line > view->nlines - 2) {
5999 s->selected_line = MIN(s->blame.nlines,
6000 view->nlines - 2);
6002 break;
6003 default:
6004 view->count = 0;
6005 break;
6007 return thread_err ? thread_err : err;
6010 static const struct got_error *
6011 reset_blame_view(struct tog_view *view)
6013 const struct got_error *err;
6014 struct tog_blame_view_state *s = &view->state.blame;
6016 view->count = 0;
6017 s->done = 1;
6018 err = stop_blame(&s->blame);
6019 s->done = 0;
6020 if (err)
6021 return err;
6022 return run_blame(view);
6025 static const struct got_error *
6026 cmd_blame(int argc, char *argv[])
6028 const struct got_error *error;
6029 struct got_repository *repo = NULL;
6030 struct got_worktree *worktree = NULL;
6031 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6032 char *link_target = NULL;
6033 struct got_object_id *commit_id = NULL;
6034 struct got_commit_object *commit = NULL;
6035 char *commit_id_str = NULL;
6036 int ch;
6037 struct tog_view *view;
6038 int *pack_fds = NULL;
6040 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6041 switch (ch) {
6042 case 'c':
6043 commit_id_str = optarg;
6044 break;
6045 case 'r':
6046 repo_path = realpath(optarg, NULL);
6047 if (repo_path == NULL)
6048 return got_error_from_errno2("realpath",
6049 optarg);
6050 break;
6051 default:
6052 usage_blame();
6053 /* NOTREACHED */
6057 argc -= optind;
6058 argv += optind;
6060 if (argc != 1)
6061 usage_blame();
6063 error = got_repo_pack_fds_open(&pack_fds);
6064 if (error != NULL)
6065 goto done;
6067 if (repo_path == NULL) {
6068 cwd = getcwd(NULL, 0);
6069 if (cwd == NULL)
6070 return got_error_from_errno("getcwd");
6071 error = got_worktree_open(&worktree, cwd);
6072 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6073 goto done;
6074 if (worktree)
6075 repo_path =
6076 strdup(got_worktree_get_repo_path(worktree));
6077 else
6078 repo_path = strdup(cwd);
6079 if (repo_path == NULL) {
6080 error = got_error_from_errno("strdup");
6081 goto done;
6085 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6086 if (error != NULL)
6087 goto done;
6089 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6090 worktree);
6091 if (error)
6092 goto done;
6094 init_curses();
6096 error = apply_unveil(got_repo_get_path(repo), NULL);
6097 if (error)
6098 goto done;
6100 error = tog_load_refs(repo, 0);
6101 if (error)
6102 goto done;
6104 if (commit_id_str == NULL) {
6105 struct got_reference *head_ref;
6106 error = got_ref_open(&head_ref, repo, worktree ?
6107 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6108 if (error != NULL)
6109 goto done;
6110 error = got_ref_resolve(&commit_id, repo, head_ref);
6111 got_ref_close(head_ref);
6112 } else {
6113 error = got_repo_match_object_id(&commit_id, NULL,
6114 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6116 if (error != NULL)
6117 goto done;
6119 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6120 if (view == NULL) {
6121 error = got_error_from_errno("view_open");
6122 goto done;
6125 error = got_object_open_as_commit(&commit, repo, commit_id);
6126 if (error)
6127 goto done;
6129 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6130 commit, repo);
6131 if (error)
6132 goto done;
6134 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6135 commit_id, repo);
6136 if (error)
6137 goto done;
6138 if (worktree) {
6139 /* Release work tree lock. */
6140 got_worktree_close(worktree);
6141 worktree = NULL;
6143 error = view_loop(view);
6144 done:
6145 free(repo_path);
6146 free(in_repo_path);
6147 free(link_target);
6148 free(cwd);
6149 free(commit_id);
6150 if (commit)
6151 got_object_commit_close(commit);
6152 if (worktree)
6153 got_worktree_close(worktree);
6154 if (repo) {
6155 const struct got_error *close_err = got_repo_close(repo);
6156 if (error == NULL)
6157 error = close_err;
6159 if (pack_fds) {
6160 const struct got_error *pack_err =
6161 got_repo_pack_fds_close(pack_fds);
6162 if (error == NULL)
6163 error = pack_err;
6165 tog_free_refs();
6166 return error;
6169 static const struct got_error *
6170 draw_tree_entries(struct tog_view *view, const char *parent_path)
6172 struct tog_tree_view_state *s = &view->state.tree;
6173 const struct got_error *err = NULL;
6174 struct got_tree_entry *te;
6175 wchar_t *wline;
6176 struct tog_color *tc;
6177 int width, n, i, nentries;
6178 int limit = view->nlines;
6180 s->ndisplayed = 0;
6181 if (view_is_hsplit_top(view))
6182 --limit; /* border */
6184 werase(view->window);
6186 if (limit == 0)
6187 return NULL;
6189 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6190 0, 0);
6191 if (err)
6192 return err;
6193 if (view_needs_focus_indication(view))
6194 wstandout(view->window);
6195 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6196 if (tc)
6197 wattr_on(view->window,
6198 COLOR_PAIR(tc->colorpair), NULL);
6199 waddwstr(view->window, wline);
6200 if (tc)
6201 wattr_off(view->window,
6202 COLOR_PAIR(tc->colorpair), NULL);
6203 if (view_needs_focus_indication(view))
6204 wstandend(view->window);
6205 free(wline);
6206 wline = NULL;
6207 if (width < view->ncols - 1)
6208 waddch(view->window, '\n');
6209 if (--limit <= 0)
6210 return NULL;
6211 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6212 0, 0);
6213 if (err)
6214 return err;
6215 waddwstr(view->window, wline);
6216 free(wline);
6217 wline = NULL;
6218 if (width < view->ncols - 1)
6219 waddch(view->window, '\n');
6220 if (--limit <= 0)
6221 return NULL;
6222 waddch(view->window, '\n');
6223 if (--limit <= 0)
6224 return NULL;
6226 if (s->first_displayed_entry == NULL) {
6227 te = got_object_tree_get_first_entry(s->tree);
6228 if (s->selected == 0) {
6229 if (view->focussed)
6230 wstandout(view->window);
6231 s->selected_entry = NULL;
6233 waddstr(view->window, " ..\n"); /* parent directory */
6234 if (s->selected == 0 && view->focussed)
6235 wstandend(view->window);
6236 s->ndisplayed++;
6237 if (--limit <= 0)
6238 return NULL;
6239 n = 1;
6240 } else {
6241 n = 0;
6242 te = s->first_displayed_entry;
6245 nentries = got_object_tree_get_nentries(s->tree);
6246 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6247 char *line = NULL, *id_str = NULL, *link_target = NULL;
6248 const char *modestr = "";
6249 mode_t mode;
6251 te = got_object_tree_get_entry(s->tree, i);
6252 mode = got_tree_entry_get_mode(te);
6254 if (s->show_ids) {
6255 err = got_object_id_str(&id_str,
6256 got_tree_entry_get_id(te));
6257 if (err)
6258 return got_error_from_errno(
6259 "got_object_id_str");
6261 if (got_object_tree_entry_is_submodule(te))
6262 modestr = "$";
6263 else if (S_ISLNK(mode)) {
6264 int i;
6266 err = got_tree_entry_get_symlink_target(&link_target,
6267 te, s->repo);
6268 if (err) {
6269 free(id_str);
6270 return err;
6272 for (i = 0; i < strlen(link_target); i++) {
6273 if (!isprint((unsigned char)link_target[i]))
6274 link_target[i] = '?';
6276 modestr = "@";
6278 else if (S_ISDIR(mode))
6279 modestr = "/";
6280 else if (mode & S_IXUSR)
6281 modestr = "*";
6282 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6283 got_tree_entry_get_name(te), modestr,
6284 link_target ? " -> ": "",
6285 link_target ? link_target : "") == -1) {
6286 free(id_str);
6287 free(link_target);
6288 return got_error_from_errno("asprintf");
6290 free(id_str);
6291 free(link_target);
6292 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6293 0, 0);
6294 if (err) {
6295 free(line);
6296 break;
6298 if (n == s->selected) {
6299 if (view->focussed)
6300 wstandout(view->window);
6301 s->selected_entry = te;
6303 tc = match_color(&s->colors, line);
6304 if (tc)
6305 wattr_on(view->window,
6306 COLOR_PAIR(tc->colorpair), NULL);
6307 waddwstr(view->window, wline);
6308 if (tc)
6309 wattr_off(view->window,
6310 COLOR_PAIR(tc->colorpair), NULL);
6311 if (width < view->ncols - 1)
6312 waddch(view->window, '\n');
6313 if (n == s->selected && view->focussed)
6314 wstandend(view->window);
6315 free(line);
6316 free(wline);
6317 wline = NULL;
6318 n++;
6319 s->ndisplayed++;
6320 s->last_displayed_entry = te;
6321 if (--limit <= 0)
6322 break;
6325 return err;
6328 static void
6329 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6331 struct got_tree_entry *te;
6332 int isroot = s->tree == s->root;
6333 int i = 0;
6335 if (s->first_displayed_entry == NULL)
6336 return;
6338 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6339 while (i++ < maxscroll) {
6340 if (te == NULL) {
6341 if (!isroot)
6342 s->first_displayed_entry = NULL;
6343 break;
6345 s->first_displayed_entry = te;
6346 te = got_tree_entry_get_prev(s->tree, te);
6350 static const struct got_error *
6351 tree_scroll_down(struct tog_view *view, int maxscroll)
6353 struct tog_tree_view_state *s = &view->state.tree;
6354 struct got_tree_entry *next, *last;
6355 int n = 0;
6357 if (s->first_displayed_entry)
6358 next = got_tree_entry_get_next(s->tree,
6359 s->first_displayed_entry);
6360 else
6361 next = got_object_tree_get_first_entry(s->tree);
6363 last = s->last_displayed_entry;
6364 while (next && n++ < maxscroll) {
6365 if (last)
6366 last = got_tree_entry_get_next(s->tree, last);
6367 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6368 s->first_displayed_entry = next;
6369 next = got_tree_entry_get_next(s->tree, next);
6373 return NULL;
6376 static const struct got_error *
6377 tree_entry_path(char **path, struct tog_parent_trees *parents,
6378 struct got_tree_entry *te)
6380 const struct got_error *err = NULL;
6381 struct tog_parent_tree *pt;
6382 size_t len = 2; /* for leading slash and NUL */
6384 TAILQ_FOREACH(pt, parents, entry)
6385 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6386 + 1 /* slash */;
6387 if (te)
6388 len += strlen(got_tree_entry_get_name(te));
6390 *path = calloc(1, len);
6391 if (path == NULL)
6392 return got_error_from_errno("calloc");
6394 (*path)[0] = '/';
6395 pt = TAILQ_LAST(parents, tog_parent_trees);
6396 while (pt) {
6397 const char *name = got_tree_entry_get_name(pt->selected_entry);
6398 if (strlcat(*path, name, len) >= len) {
6399 err = got_error(GOT_ERR_NO_SPACE);
6400 goto done;
6402 if (strlcat(*path, "/", len) >= len) {
6403 err = got_error(GOT_ERR_NO_SPACE);
6404 goto done;
6406 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6408 if (te) {
6409 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6410 err = got_error(GOT_ERR_NO_SPACE);
6411 goto done;
6414 done:
6415 if (err) {
6416 free(*path);
6417 *path = NULL;
6419 return err;
6422 static const struct got_error *
6423 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6424 struct got_tree_entry *te, struct tog_parent_trees *parents,
6425 struct got_object_id *commit_id, struct got_repository *repo)
6427 const struct got_error *err = NULL;
6428 char *path;
6429 struct tog_view *blame_view;
6431 *new_view = NULL;
6433 err = tree_entry_path(&path, parents, te);
6434 if (err)
6435 return err;
6437 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6438 if (blame_view == NULL) {
6439 err = got_error_from_errno("view_open");
6440 goto done;
6443 err = open_blame_view(blame_view, path, commit_id, repo);
6444 if (err) {
6445 if (err->code == GOT_ERR_CANCELLED)
6446 err = NULL;
6447 view_close(blame_view);
6448 } else
6449 *new_view = blame_view;
6450 done:
6451 free(path);
6452 return err;
6455 static const struct got_error *
6456 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6457 struct tog_tree_view_state *s)
6459 struct tog_view *log_view;
6460 const struct got_error *err = NULL;
6461 char *path;
6463 *new_view = NULL;
6465 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6466 if (log_view == NULL)
6467 return got_error_from_errno("view_open");
6469 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6470 if (err)
6471 return err;
6473 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6474 path, 0);
6475 if (err)
6476 view_close(log_view);
6477 else
6478 *new_view = log_view;
6479 free(path);
6480 return err;
6483 static const struct got_error *
6484 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6485 const char *head_ref_name, struct got_repository *repo)
6487 const struct got_error *err = NULL;
6488 char *commit_id_str = NULL;
6489 struct tog_tree_view_state *s = &view->state.tree;
6490 struct got_commit_object *commit = NULL;
6492 TAILQ_INIT(&s->parents);
6493 STAILQ_INIT(&s->colors);
6495 s->commit_id = got_object_id_dup(commit_id);
6496 if (s->commit_id == NULL)
6497 return got_error_from_errno("got_object_id_dup");
6499 err = got_object_open_as_commit(&commit, repo, commit_id);
6500 if (err)
6501 goto done;
6504 * The root is opened here and will be closed when the view is closed.
6505 * Any visited subtrees and their path-wise parents are opened and
6506 * closed on demand.
6508 err = got_object_open_as_tree(&s->root, repo,
6509 got_object_commit_get_tree_id(commit));
6510 if (err)
6511 goto done;
6512 s->tree = s->root;
6514 err = got_object_id_str(&commit_id_str, commit_id);
6515 if (err != NULL)
6516 goto done;
6518 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6519 err = got_error_from_errno("asprintf");
6520 goto done;
6523 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6524 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6525 if (head_ref_name) {
6526 s->head_ref_name = strdup(head_ref_name);
6527 if (s->head_ref_name == NULL) {
6528 err = got_error_from_errno("strdup");
6529 goto done;
6532 s->repo = repo;
6534 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6535 err = add_color(&s->colors, "\\$$",
6536 TOG_COLOR_TREE_SUBMODULE,
6537 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6538 if (err)
6539 goto done;
6540 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6541 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6542 if (err)
6543 goto done;
6544 err = add_color(&s->colors, "/$",
6545 TOG_COLOR_TREE_DIRECTORY,
6546 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6547 if (err)
6548 goto done;
6550 err = add_color(&s->colors, "\\*$",
6551 TOG_COLOR_TREE_EXECUTABLE,
6552 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6553 if (err)
6554 goto done;
6556 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6557 get_color_value("TOG_COLOR_COMMIT"));
6558 if (err)
6559 goto done;
6562 view->show = show_tree_view;
6563 view->input = input_tree_view;
6564 view->close = close_tree_view;
6565 view->search_start = search_start_tree_view;
6566 view->search_next = search_next_tree_view;
6567 done:
6568 free(commit_id_str);
6569 if (commit)
6570 got_object_commit_close(commit);
6571 if (err)
6572 close_tree_view(view);
6573 return err;
6576 static const struct got_error *
6577 close_tree_view(struct tog_view *view)
6579 struct tog_tree_view_state *s = &view->state.tree;
6581 free_colors(&s->colors);
6582 free(s->tree_label);
6583 s->tree_label = NULL;
6584 free(s->commit_id);
6585 s->commit_id = NULL;
6586 free(s->head_ref_name);
6587 s->head_ref_name = NULL;
6588 while (!TAILQ_EMPTY(&s->parents)) {
6589 struct tog_parent_tree *parent;
6590 parent = TAILQ_FIRST(&s->parents);
6591 TAILQ_REMOVE(&s->parents, parent, entry);
6592 if (parent->tree != s->root)
6593 got_object_tree_close(parent->tree);
6594 free(parent);
6597 if (s->tree != NULL && s->tree != s->root)
6598 got_object_tree_close(s->tree);
6599 if (s->root)
6600 got_object_tree_close(s->root);
6601 return NULL;
6604 static const struct got_error *
6605 search_start_tree_view(struct tog_view *view)
6607 struct tog_tree_view_state *s = &view->state.tree;
6609 s->matched_entry = NULL;
6610 return NULL;
6613 static int
6614 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6616 regmatch_t regmatch;
6618 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6619 0) == 0;
6622 static const struct got_error *
6623 search_next_tree_view(struct tog_view *view)
6625 struct tog_tree_view_state *s = &view->state.tree;
6626 struct got_tree_entry *te = NULL;
6628 if (!view->searching) {
6629 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6630 return NULL;
6633 if (s->matched_entry) {
6634 if (view->searching == TOG_SEARCH_FORWARD) {
6635 if (s->selected_entry)
6636 te = got_tree_entry_get_next(s->tree,
6637 s->selected_entry);
6638 else
6639 te = got_object_tree_get_first_entry(s->tree);
6640 } else {
6641 if (s->selected_entry == NULL)
6642 te = got_object_tree_get_last_entry(s->tree);
6643 else
6644 te = got_tree_entry_get_prev(s->tree,
6645 s->selected_entry);
6647 } else {
6648 if (s->selected_entry)
6649 te = s->selected_entry;
6650 else if (view->searching == TOG_SEARCH_FORWARD)
6651 te = got_object_tree_get_first_entry(s->tree);
6652 else
6653 te = got_object_tree_get_last_entry(s->tree);
6656 while (1) {
6657 if (te == NULL) {
6658 if (s->matched_entry == NULL) {
6659 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6660 return NULL;
6662 if (view->searching == TOG_SEARCH_FORWARD)
6663 te = got_object_tree_get_first_entry(s->tree);
6664 else
6665 te = got_object_tree_get_last_entry(s->tree);
6668 if (match_tree_entry(te, &view->regex)) {
6669 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6670 s->matched_entry = te;
6671 break;
6674 if (view->searching == TOG_SEARCH_FORWARD)
6675 te = got_tree_entry_get_next(s->tree, te);
6676 else
6677 te = got_tree_entry_get_prev(s->tree, te);
6680 if (s->matched_entry) {
6681 s->first_displayed_entry = s->matched_entry;
6682 s->selected = 0;
6685 return NULL;
6688 static const struct got_error *
6689 show_tree_view(struct tog_view *view)
6691 const struct got_error *err = NULL;
6692 struct tog_tree_view_state *s = &view->state.tree;
6693 char *parent_path;
6695 err = tree_entry_path(&parent_path, &s->parents, NULL);
6696 if (err)
6697 return err;
6699 err = draw_tree_entries(view, parent_path);
6700 free(parent_path);
6702 view_border(view);
6703 return err;
6706 static const struct got_error *
6707 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6709 const struct got_error *err = NULL;
6710 struct tog_tree_view_state *s = &view->state.tree;
6711 struct tog_view *log_view, *ref_view;
6712 struct got_tree_entry *te;
6713 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 3;
6715 switch (ch) {
6716 case 'i':
6717 s->show_ids = !s->show_ids;
6718 view->count = 0;
6719 break;
6720 case 'l':
6721 view->count = 0;
6722 if (!s->selected_entry)
6723 break;
6724 if (view_is_parent_view(view))
6725 view_get_split(view, &begin_y, &begin_x);
6726 err = log_selected_tree_entry(&log_view, begin_y, begin_x, s);
6727 if (view_is_parent_view(view) &&
6728 view->mode == TOG_VIEW_SPLIT_HRZN) {
6729 err = view_init_hsplit(view, begin_y);
6730 if (err)
6731 break;
6733 view->focussed = 0;
6734 log_view->focussed = 1;
6735 log_view->mode = view->mode;
6736 log_view->nlines = view->lines - begin_y;
6737 if (view_is_parent_view(view)) {
6738 view_transfer_size(log_view, view);
6739 err = view_close_child(view);
6740 if (err)
6741 return err;
6742 err = view_set_child(view, log_view);
6743 if (err)
6744 return err;
6745 view->focus_child = 1;
6746 } else
6747 *new_view = log_view;
6748 break;
6749 case 'r':
6750 view->count = 0;
6751 if (view_is_parent_view(view))
6752 view_get_split(view, &begin_y, &begin_x);
6753 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
6754 if (ref_view == NULL)
6755 return got_error_from_errno("view_open");
6756 err = open_ref_view(ref_view, s->repo);
6757 if (err) {
6758 view_close(ref_view);
6759 return err;
6761 if (view_is_parent_view(view) &&
6762 view->mode == TOG_VIEW_SPLIT_HRZN) {
6763 err = view_init_hsplit(view, begin_y);
6764 if (err)
6765 break;
6767 view->focussed = 0;
6768 ref_view->focussed = 1;
6769 ref_view->mode = view->mode;
6770 ref_view->nlines = view->lines - begin_y;
6771 if (view_is_parent_view(view)) {
6772 view_transfer_size(ref_view, view);
6773 err = view_close_child(view);
6774 if (err)
6775 return err;
6776 err = view_set_child(view, ref_view);
6777 if (err)
6778 return err;
6779 view->focus_child = 1;
6780 } else
6781 *new_view = ref_view;
6782 break;
6783 case 'g':
6784 case KEY_HOME:
6785 s->selected = 0;
6786 view->count = 0;
6787 if (s->tree == s->root)
6788 s->first_displayed_entry =
6789 got_object_tree_get_first_entry(s->tree);
6790 else
6791 s->first_displayed_entry = NULL;
6792 break;
6793 case 'G':
6794 case KEY_END: {
6795 int eos = view->nlines - 3;
6797 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6798 --eos; /* border */
6799 s->selected = 0;
6800 view->count = 0;
6801 te = got_object_tree_get_last_entry(s->tree);
6802 for (n = 0; n < eos; n++) {
6803 if (te == NULL) {
6804 if (s->tree != s->root) {
6805 s->first_displayed_entry = NULL;
6806 n++;
6808 break;
6810 s->first_displayed_entry = te;
6811 te = got_tree_entry_get_prev(s->tree, te);
6813 if (n > 0)
6814 s->selected = n - 1;
6815 break;
6817 case 'k':
6818 case KEY_UP:
6819 case CTRL('p'):
6820 if (s->selected > 0) {
6821 s->selected--;
6822 break;
6824 tree_scroll_up(s, 1);
6825 if (s->selected_entry == NULL ||
6826 (s->tree == s->root && s->selected_entry ==
6827 got_object_tree_get_first_entry(s->tree)))
6828 view->count = 0;
6829 break;
6830 case CTRL('u'):
6831 case 'u':
6832 nscroll /= 2;
6833 /* FALL THROUGH */
6834 case KEY_PPAGE:
6835 case CTRL('b'):
6836 case 'b':
6837 if (s->tree == s->root) {
6838 if (got_object_tree_get_first_entry(s->tree) ==
6839 s->first_displayed_entry)
6840 s->selected -= MIN(s->selected, nscroll);
6841 } else {
6842 if (s->first_displayed_entry == NULL)
6843 s->selected -= MIN(s->selected, nscroll);
6845 tree_scroll_up(s, MAX(0, nscroll));
6846 if (s->selected_entry == NULL ||
6847 (s->tree == s->root && s->selected_entry ==
6848 got_object_tree_get_first_entry(s->tree)))
6849 view->count = 0;
6850 break;
6851 case 'j':
6852 case KEY_DOWN:
6853 case CTRL('n'):
6854 if (s->selected < s->ndisplayed - 1) {
6855 s->selected++;
6856 break;
6858 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6859 == NULL) {
6860 /* can't scroll any further */
6861 view->count = 0;
6862 break;
6864 tree_scroll_down(view, 1);
6865 break;
6866 case CTRL('d'):
6867 case 'd':
6868 nscroll /= 2;
6869 /* FALL THROUGH */
6870 case KEY_NPAGE:
6871 case CTRL('f'):
6872 case 'f':
6873 case ' ':
6874 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6875 == NULL) {
6876 /* can't scroll any further; move cursor down */
6877 if (s->selected < s->ndisplayed - 1)
6878 s->selected += MIN(nscroll,
6879 s->ndisplayed - s->selected - 1);
6880 else
6881 view->count = 0;
6882 break;
6884 tree_scroll_down(view, nscroll);
6885 break;
6886 case KEY_ENTER:
6887 case '\r':
6888 case KEY_BACKSPACE:
6889 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6890 struct tog_parent_tree *parent;
6891 /* user selected '..' */
6892 if (s->tree == s->root) {
6893 view->count = 0;
6894 break;
6896 parent = TAILQ_FIRST(&s->parents);
6897 TAILQ_REMOVE(&s->parents, parent,
6898 entry);
6899 got_object_tree_close(s->tree);
6900 s->tree = parent->tree;
6901 s->first_displayed_entry =
6902 parent->first_displayed_entry;
6903 s->selected_entry =
6904 parent->selected_entry;
6905 s->selected = parent->selected;
6906 if (s->selected > view->nlines - 3) {
6907 err = offset_selection_down(view);
6908 if (err)
6909 break;
6911 free(parent);
6912 } else if (S_ISDIR(got_tree_entry_get_mode(
6913 s->selected_entry))) {
6914 struct got_tree_object *subtree;
6915 view->count = 0;
6916 err = got_object_open_as_tree(&subtree, s->repo,
6917 got_tree_entry_get_id(s->selected_entry));
6918 if (err)
6919 break;
6920 err = tree_view_visit_subtree(s, subtree);
6921 if (err) {
6922 got_object_tree_close(subtree);
6923 break;
6925 } else if (S_ISREG(got_tree_entry_get_mode(
6926 s->selected_entry))) {
6927 struct tog_view *blame_view;
6928 int begin_x = 0, begin_y = 0;
6930 if (view_is_parent_view(view))
6931 view_get_split(view, &begin_y, &begin_x);
6933 err = blame_tree_entry(&blame_view, begin_y, begin_x,
6934 s->selected_entry, &s->parents,
6935 s->commit_id, s->repo);
6936 if (err)
6937 break;
6939 if (view_is_parent_view(view) &&
6940 view->mode == TOG_VIEW_SPLIT_HRZN) {
6941 err = view_init_hsplit(view, begin_y);
6942 if (err)
6943 break;
6946 view->count = 0;
6947 view->focussed = 0;
6948 blame_view->focussed = 1;
6949 blame_view->mode = view->mode;
6950 blame_view->nlines = view->lines - begin_y;
6951 if (view_is_parent_view(view)) {
6952 view_transfer_size(blame_view, view);
6953 err = view_close_child(view);
6954 if (err)
6955 return err;
6956 err = view_set_child(view, blame_view);
6957 if (err)
6958 return err;
6959 view->focus_child = 1;
6960 } else
6961 *new_view = blame_view;
6963 break;
6964 case KEY_RESIZE:
6965 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6966 s->selected = view->nlines - 4;
6967 view->count = 0;
6968 break;
6969 default:
6970 view->count = 0;
6971 break;
6974 return err;
6977 __dead static void
6978 usage_tree(void)
6980 endwin();
6981 fprintf(stderr,
6982 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6983 getprogname());
6984 exit(1);
6987 static const struct got_error *
6988 cmd_tree(int argc, char *argv[])
6990 const struct got_error *error;
6991 struct got_repository *repo = NULL;
6992 struct got_worktree *worktree = NULL;
6993 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6994 struct got_object_id *commit_id = NULL;
6995 struct got_commit_object *commit = NULL;
6996 const char *commit_id_arg = NULL;
6997 char *label = NULL;
6998 struct got_reference *ref = NULL;
6999 const char *head_ref_name = NULL;
7000 int ch;
7001 struct tog_view *view;
7002 int *pack_fds = NULL;
7004 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7005 switch (ch) {
7006 case 'c':
7007 commit_id_arg = optarg;
7008 break;
7009 case 'r':
7010 repo_path = realpath(optarg, NULL);
7011 if (repo_path == NULL)
7012 return got_error_from_errno2("realpath",
7013 optarg);
7014 break;
7015 default:
7016 usage_tree();
7017 /* NOTREACHED */
7021 argc -= optind;
7022 argv += optind;
7024 if (argc > 1)
7025 usage_tree();
7027 error = got_repo_pack_fds_open(&pack_fds);
7028 if (error != NULL)
7029 goto done;
7031 if (repo_path == NULL) {
7032 cwd = getcwd(NULL, 0);
7033 if (cwd == NULL)
7034 return got_error_from_errno("getcwd");
7035 error = got_worktree_open(&worktree, cwd);
7036 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7037 goto done;
7038 if (worktree)
7039 repo_path =
7040 strdup(got_worktree_get_repo_path(worktree));
7041 else
7042 repo_path = strdup(cwd);
7043 if (repo_path == NULL) {
7044 error = got_error_from_errno("strdup");
7045 goto done;
7049 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7050 if (error != NULL)
7051 goto done;
7053 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7054 repo, worktree);
7055 if (error)
7056 goto done;
7058 init_curses();
7060 error = apply_unveil(got_repo_get_path(repo), NULL);
7061 if (error)
7062 goto done;
7064 error = tog_load_refs(repo, 0);
7065 if (error)
7066 goto done;
7068 if (commit_id_arg == NULL) {
7069 error = got_repo_match_object_id(&commit_id, &label,
7070 worktree ? got_worktree_get_head_ref_name(worktree) :
7071 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7072 if (error)
7073 goto done;
7074 head_ref_name = label;
7075 } else {
7076 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7077 if (error == NULL)
7078 head_ref_name = got_ref_get_name(ref);
7079 else if (error->code != GOT_ERR_NOT_REF)
7080 goto done;
7081 error = got_repo_match_object_id(&commit_id, NULL,
7082 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7083 if (error)
7084 goto done;
7087 error = got_object_open_as_commit(&commit, repo, commit_id);
7088 if (error)
7089 goto done;
7091 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7092 if (view == NULL) {
7093 error = got_error_from_errno("view_open");
7094 goto done;
7096 error = open_tree_view(view, commit_id, head_ref_name, repo);
7097 if (error)
7098 goto done;
7099 if (!got_path_is_root_dir(in_repo_path)) {
7100 error = tree_view_walk_path(&view->state.tree, commit,
7101 in_repo_path);
7102 if (error)
7103 goto done;
7106 if (worktree) {
7107 /* Release work tree lock. */
7108 got_worktree_close(worktree);
7109 worktree = NULL;
7111 error = view_loop(view);
7112 done:
7113 free(repo_path);
7114 free(cwd);
7115 free(commit_id);
7116 free(label);
7117 if (ref)
7118 got_ref_close(ref);
7119 if (repo) {
7120 const struct got_error *close_err = got_repo_close(repo);
7121 if (error == NULL)
7122 error = close_err;
7124 if (pack_fds) {
7125 const struct got_error *pack_err =
7126 got_repo_pack_fds_close(pack_fds);
7127 if (error == NULL)
7128 error = pack_err;
7130 tog_free_refs();
7131 return error;
7134 static const struct got_error *
7135 ref_view_load_refs(struct tog_ref_view_state *s)
7137 struct got_reflist_entry *sre;
7138 struct tog_reflist_entry *re;
7140 s->nrefs = 0;
7141 TAILQ_FOREACH(sre, &tog_refs, entry) {
7142 if (strncmp(got_ref_get_name(sre->ref),
7143 "refs/got/", 9) == 0 &&
7144 strncmp(got_ref_get_name(sre->ref),
7145 "refs/got/backup/", 16) != 0)
7146 continue;
7148 re = malloc(sizeof(*re));
7149 if (re == NULL)
7150 return got_error_from_errno("malloc");
7152 re->ref = got_ref_dup(sre->ref);
7153 if (re->ref == NULL)
7154 return got_error_from_errno("got_ref_dup");
7155 re->idx = s->nrefs++;
7156 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7159 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7160 return NULL;
7163 static void
7164 ref_view_free_refs(struct tog_ref_view_state *s)
7166 struct tog_reflist_entry *re;
7168 while (!TAILQ_EMPTY(&s->refs)) {
7169 re = TAILQ_FIRST(&s->refs);
7170 TAILQ_REMOVE(&s->refs, re, entry);
7171 got_ref_close(re->ref);
7172 free(re);
7176 static const struct got_error *
7177 open_ref_view(struct tog_view *view, struct got_repository *repo)
7179 const struct got_error *err = NULL;
7180 struct tog_ref_view_state *s = &view->state.ref;
7182 s->selected_entry = 0;
7183 s->repo = repo;
7185 TAILQ_INIT(&s->refs);
7186 STAILQ_INIT(&s->colors);
7188 err = ref_view_load_refs(s);
7189 if (err)
7190 return err;
7192 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7193 err = add_color(&s->colors, "^refs/heads/",
7194 TOG_COLOR_REFS_HEADS,
7195 get_color_value("TOG_COLOR_REFS_HEADS"));
7196 if (err)
7197 goto done;
7199 err = add_color(&s->colors, "^refs/tags/",
7200 TOG_COLOR_REFS_TAGS,
7201 get_color_value("TOG_COLOR_REFS_TAGS"));
7202 if (err)
7203 goto done;
7205 err = add_color(&s->colors, "^refs/remotes/",
7206 TOG_COLOR_REFS_REMOTES,
7207 get_color_value("TOG_COLOR_REFS_REMOTES"));
7208 if (err)
7209 goto done;
7211 err = add_color(&s->colors, "^refs/got/backup/",
7212 TOG_COLOR_REFS_BACKUP,
7213 get_color_value("TOG_COLOR_REFS_BACKUP"));
7214 if (err)
7215 goto done;
7218 view->show = show_ref_view;
7219 view->input = input_ref_view;
7220 view->close = close_ref_view;
7221 view->search_start = search_start_ref_view;
7222 view->search_next = search_next_ref_view;
7223 done:
7224 if (err)
7225 free_colors(&s->colors);
7226 return err;
7229 static const struct got_error *
7230 close_ref_view(struct tog_view *view)
7232 struct tog_ref_view_state *s = &view->state.ref;
7234 ref_view_free_refs(s);
7235 free_colors(&s->colors);
7237 return NULL;
7240 static const struct got_error *
7241 resolve_reflist_entry(struct got_object_id **commit_id,
7242 struct tog_reflist_entry *re, struct got_repository *repo)
7244 const struct got_error *err = NULL;
7245 struct got_object_id *obj_id;
7246 struct got_tag_object *tag = NULL;
7247 int obj_type;
7249 *commit_id = NULL;
7251 err = got_ref_resolve(&obj_id, repo, re->ref);
7252 if (err)
7253 return err;
7255 err = got_object_get_type(&obj_type, repo, obj_id);
7256 if (err)
7257 goto done;
7259 switch (obj_type) {
7260 case GOT_OBJ_TYPE_COMMIT:
7261 *commit_id = obj_id;
7262 break;
7263 case GOT_OBJ_TYPE_TAG:
7264 err = got_object_open_as_tag(&tag, repo, obj_id);
7265 if (err)
7266 goto done;
7267 free(obj_id);
7268 err = got_object_get_type(&obj_type, repo,
7269 got_object_tag_get_object_id(tag));
7270 if (err)
7271 goto done;
7272 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7273 err = got_error(GOT_ERR_OBJ_TYPE);
7274 goto done;
7276 *commit_id = got_object_id_dup(
7277 got_object_tag_get_object_id(tag));
7278 if (*commit_id == NULL) {
7279 err = got_error_from_errno("got_object_id_dup");
7280 goto done;
7282 break;
7283 default:
7284 err = got_error(GOT_ERR_OBJ_TYPE);
7285 break;
7288 done:
7289 if (tag)
7290 got_object_tag_close(tag);
7291 if (err) {
7292 free(*commit_id);
7293 *commit_id = NULL;
7295 return err;
7298 static const struct got_error *
7299 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7300 struct tog_reflist_entry *re, struct got_repository *repo)
7302 struct tog_view *log_view;
7303 const struct got_error *err = NULL;
7304 struct got_object_id *commit_id = NULL;
7306 *new_view = NULL;
7308 err = resolve_reflist_entry(&commit_id, re, repo);
7309 if (err) {
7310 if (err->code != GOT_ERR_OBJ_TYPE)
7311 return err;
7312 else
7313 return NULL;
7316 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7317 if (log_view == NULL) {
7318 err = got_error_from_errno("view_open");
7319 goto done;
7322 err = open_log_view(log_view, commit_id, repo,
7323 got_ref_get_name(re->ref), "", 0);
7324 done:
7325 if (err)
7326 view_close(log_view);
7327 else
7328 *new_view = log_view;
7329 free(commit_id);
7330 return err;
7333 static void
7334 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7336 struct tog_reflist_entry *re;
7337 int i = 0;
7339 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7340 return;
7342 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7343 while (i++ < maxscroll) {
7344 if (re == NULL)
7345 break;
7346 s->first_displayed_entry = re;
7347 re = TAILQ_PREV(re, tog_reflist_head, entry);
7351 static const struct got_error *
7352 ref_scroll_down(struct tog_view *view, int maxscroll)
7354 struct tog_ref_view_state *s = &view->state.ref;
7355 struct tog_reflist_entry *next, *last;
7356 int n = 0;
7358 if (s->first_displayed_entry)
7359 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7360 else
7361 next = TAILQ_FIRST(&s->refs);
7363 last = s->last_displayed_entry;
7364 while (next && n++ < maxscroll) {
7365 if (last)
7366 last = TAILQ_NEXT(last, entry);
7367 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7368 s->first_displayed_entry = next;
7369 next = TAILQ_NEXT(next, entry);
7373 return NULL;
7376 static const struct got_error *
7377 search_start_ref_view(struct tog_view *view)
7379 struct tog_ref_view_state *s = &view->state.ref;
7381 s->matched_entry = NULL;
7382 return NULL;
7385 static int
7386 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7388 regmatch_t regmatch;
7390 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7391 0) == 0;
7394 static const struct got_error *
7395 search_next_ref_view(struct tog_view *view)
7397 struct tog_ref_view_state *s = &view->state.ref;
7398 struct tog_reflist_entry *re = NULL;
7400 if (!view->searching) {
7401 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7402 return NULL;
7405 if (s->matched_entry) {
7406 if (view->searching == TOG_SEARCH_FORWARD) {
7407 if (s->selected_entry)
7408 re = TAILQ_NEXT(s->selected_entry, entry);
7409 else
7410 re = TAILQ_PREV(s->selected_entry,
7411 tog_reflist_head, entry);
7412 } else {
7413 if (s->selected_entry == NULL)
7414 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7415 else
7416 re = TAILQ_PREV(s->selected_entry,
7417 tog_reflist_head, entry);
7419 } else {
7420 if (s->selected_entry)
7421 re = s->selected_entry;
7422 else if (view->searching == TOG_SEARCH_FORWARD)
7423 re = TAILQ_FIRST(&s->refs);
7424 else
7425 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7428 while (1) {
7429 if (re == NULL) {
7430 if (s->matched_entry == NULL) {
7431 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7432 return NULL;
7434 if (view->searching == TOG_SEARCH_FORWARD)
7435 re = TAILQ_FIRST(&s->refs);
7436 else
7437 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7440 if (match_reflist_entry(re, &view->regex)) {
7441 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7442 s->matched_entry = re;
7443 break;
7446 if (view->searching == TOG_SEARCH_FORWARD)
7447 re = TAILQ_NEXT(re, entry);
7448 else
7449 re = TAILQ_PREV(re, tog_reflist_head, entry);
7452 if (s->matched_entry) {
7453 s->first_displayed_entry = s->matched_entry;
7454 s->selected = 0;
7457 return NULL;
7460 static const struct got_error *
7461 show_ref_view(struct tog_view *view)
7463 const struct got_error *err = NULL;
7464 struct tog_ref_view_state *s = &view->state.ref;
7465 struct tog_reflist_entry *re;
7466 char *line = NULL;
7467 wchar_t *wline;
7468 struct tog_color *tc;
7469 int width, n;
7470 int limit = view->nlines;
7472 werase(view->window);
7474 s->ndisplayed = 0;
7475 if (view_is_hsplit_top(view))
7476 --limit; /* border */
7478 if (limit == 0)
7479 return NULL;
7481 re = s->first_displayed_entry;
7483 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7484 s->nrefs) == -1)
7485 return got_error_from_errno("asprintf");
7487 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7488 if (err) {
7489 free(line);
7490 return err;
7492 if (view_needs_focus_indication(view))
7493 wstandout(view->window);
7494 waddwstr(view->window, wline);
7495 if (view_needs_focus_indication(view))
7496 wstandend(view->window);
7497 free(wline);
7498 wline = NULL;
7499 free(line);
7500 line = NULL;
7501 if (width < view->ncols - 1)
7502 waddch(view->window, '\n');
7503 if (--limit <= 0)
7504 return NULL;
7506 n = 0;
7507 while (re && limit > 0) {
7508 char *line = NULL;
7509 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7511 if (s->show_date) {
7512 struct got_commit_object *ci;
7513 struct got_tag_object *tag;
7514 struct got_object_id *id;
7515 struct tm tm;
7516 time_t t;
7518 err = got_ref_resolve(&id, s->repo, re->ref);
7519 if (err)
7520 return err;
7521 err = got_object_open_as_tag(&tag, s->repo, id);
7522 if (err) {
7523 if (err->code != GOT_ERR_OBJ_TYPE) {
7524 free(id);
7525 return err;
7527 err = got_object_open_as_commit(&ci, s->repo,
7528 id);
7529 if (err) {
7530 free(id);
7531 return err;
7533 t = got_object_commit_get_committer_time(ci);
7534 got_object_commit_close(ci);
7535 } else {
7536 t = got_object_tag_get_tagger_time(tag);
7537 got_object_tag_close(tag);
7539 free(id);
7540 if (gmtime_r(&t, &tm) == NULL)
7541 return got_error_from_errno("gmtime_r");
7542 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7543 return got_error(GOT_ERR_NO_SPACE);
7545 if (got_ref_is_symbolic(re->ref)) {
7546 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7547 ymd : "", got_ref_get_name(re->ref),
7548 got_ref_get_symref_target(re->ref)) == -1)
7549 return got_error_from_errno("asprintf");
7550 } else if (s->show_ids) {
7551 struct got_object_id *id;
7552 char *id_str;
7553 err = got_ref_resolve(&id, s->repo, re->ref);
7554 if (err)
7555 return err;
7556 err = got_object_id_str(&id_str, id);
7557 if (err) {
7558 free(id);
7559 return err;
7561 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7562 got_ref_get_name(re->ref), id_str) == -1) {
7563 err = got_error_from_errno("asprintf");
7564 free(id);
7565 free(id_str);
7566 return err;
7568 free(id);
7569 free(id_str);
7570 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7571 got_ref_get_name(re->ref)) == -1)
7572 return got_error_from_errno("asprintf");
7574 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7575 0, 0);
7576 if (err) {
7577 free(line);
7578 return err;
7580 if (n == s->selected) {
7581 if (view->focussed)
7582 wstandout(view->window);
7583 s->selected_entry = re;
7585 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7586 if (tc)
7587 wattr_on(view->window,
7588 COLOR_PAIR(tc->colorpair), NULL);
7589 waddwstr(view->window, wline);
7590 if (tc)
7591 wattr_off(view->window,
7592 COLOR_PAIR(tc->colorpair), NULL);
7593 if (width < view->ncols - 1)
7594 waddch(view->window, '\n');
7595 if (n == s->selected && view->focussed)
7596 wstandend(view->window);
7597 free(line);
7598 free(wline);
7599 wline = NULL;
7600 n++;
7601 s->ndisplayed++;
7602 s->last_displayed_entry = re;
7604 limit--;
7605 re = TAILQ_NEXT(re, entry);
7608 view_border(view);
7609 return err;
7612 static const struct got_error *
7613 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7614 struct tog_reflist_entry *re, struct got_repository *repo)
7616 const struct got_error *err = NULL;
7617 struct got_object_id *commit_id = NULL;
7618 struct tog_view *tree_view;
7620 *new_view = NULL;
7622 err = resolve_reflist_entry(&commit_id, re, repo);
7623 if (err) {
7624 if (err->code != GOT_ERR_OBJ_TYPE)
7625 return err;
7626 else
7627 return NULL;
7631 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7632 if (tree_view == NULL) {
7633 err = got_error_from_errno("view_open");
7634 goto done;
7637 err = open_tree_view(tree_view, commit_id,
7638 got_ref_get_name(re->ref), repo);
7639 if (err)
7640 goto done;
7642 *new_view = tree_view;
7643 done:
7644 free(commit_id);
7645 return err;
7647 static const struct got_error *
7648 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7650 const struct got_error *err = NULL;
7651 struct tog_ref_view_state *s = &view->state.ref;
7652 struct tog_view *log_view, *tree_view;
7653 struct tog_reflist_entry *re;
7654 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 1;
7656 switch (ch) {
7657 case 'i':
7658 s->show_ids = !s->show_ids;
7659 view->count = 0;
7660 break;
7661 case 'm':
7662 s->show_date = !s->show_date;
7663 view->count = 0;
7664 break;
7665 case 'o':
7666 s->sort_by_date = !s->sort_by_date;
7667 view->count = 0;
7668 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7669 got_ref_cmp_by_commit_timestamp_descending :
7670 tog_ref_cmp_by_name, s->repo);
7671 if (err)
7672 break;
7673 got_reflist_object_id_map_free(tog_refs_idmap);
7674 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7675 &tog_refs, s->repo);
7676 if (err)
7677 break;
7678 ref_view_free_refs(s);
7679 err = ref_view_load_refs(s);
7680 break;
7681 case KEY_ENTER:
7682 case '\r':
7683 view->count = 0;
7684 if (!s->selected_entry)
7685 break;
7686 if (view_is_parent_view(view))
7687 view_get_split(view, &begin_y, &begin_x);
7689 err = log_ref_entry(&log_view, begin_y, begin_x,
7690 s->selected_entry, s->repo);
7691 if (err)
7692 break;
7694 if (view_is_parent_view(view) &&
7695 view->mode == TOG_VIEW_SPLIT_HRZN) {
7696 err = view_init_hsplit(view, begin_y);
7697 if (err)
7698 break;
7701 view->focussed = 0;
7702 log_view->focussed = 1;
7703 log_view->mode = view->mode;
7704 log_view->nlines = view->lines - begin_y;
7705 if (view_is_parent_view(view)) {
7706 view_transfer_size(log_view, view);
7707 err = view_close_child(view);
7708 if (err)
7709 return err;
7710 err = view_set_child(view, log_view);
7711 if (err)
7712 return err;
7713 view->focus_child = 1;
7714 } else
7715 *new_view = log_view;
7716 break;
7717 case 't':
7718 view->count = 0;
7719 if (!s->selected_entry)
7720 break;
7721 if (view_is_parent_view(view))
7722 view_get_split(view, &begin_y, &begin_x);
7723 err = browse_ref_tree(&tree_view, begin_y, begin_x,
7724 s->selected_entry, s->repo);
7725 if (err || tree_view == NULL)
7726 break;
7727 if (view_is_parent_view(view) &&
7728 view->mode == TOG_VIEW_SPLIT_HRZN) {
7729 err = view_init_hsplit(view, begin_y);
7730 if (err)
7731 break;
7733 view->focussed = 0;
7734 tree_view->focussed = 1;
7735 tree_view->mode = view->mode;
7736 tree_view->nlines = view->lines - begin_y;
7737 if (view_is_parent_view(view)) {
7738 view_transfer_size(tree_view, view);
7739 err = view_close_child(view);
7740 if (err)
7741 return err;
7742 err = view_set_child(view, tree_view);
7743 if (err)
7744 return err;
7745 view->focus_child = 1;
7746 } else
7747 *new_view = tree_view;
7748 break;
7749 case 'g':
7750 case KEY_HOME:
7751 s->selected = 0;
7752 view->count = 0;
7753 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7754 break;
7755 case 'G':
7756 case KEY_END: {
7757 int eos = view->nlines - 1;
7759 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7760 --eos; /* border */
7761 s->selected = 0;
7762 view->count = 0;
7763 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7764 for (n = 0; n < eos; n++) {
7765 if (re == NULL)
7766 break;
7767 s->first_displayed_entry = re;
7768 re = TAILQ_PREV(re, tog_reflist_head, entry);
7770 if (n > 0)
7771 s->selected = n - 1;
7772 break;
7774 case 'k':
7775 case KEY_UP:
7776 case CTRL('p'):
7777 if (s->selected > 0) {
7778 s->selected--;
7779 break;
7781 ref_scroll_up(s, 1);
7782 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7783 view->count = 0;
7784 break;
7785 case CTRL('u'):
7786 case 'u':
7787 nscroll /= 2;
7788 /* FALL THROUGH */
7789 case KEY_PPAGE:
7790 case CTRL('b'):
7791 case 'b':
7792 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7793 s->selected -= MIN(nscroll, s->selected);
7794 ref_scroll_up(s, MAX(0, nscroll));
7795 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7796 view->count = 0;
7797 break;
7798 case 'j':
7799 case KEY_DOWN:
7800 case CTRL('n'):
7801 if (s->selected < s->ndisplayed - 1) {
7802 s->selected++;
7803 break;
7805 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7806 /* can't scroll any further */
7807 view->count = 0;
7808 break;
7810 ref_scroll_down(view, 1);
7811 break;
7812 case CTRL('d'):
7813 case 'd':
7814 nscroll /= 2;
7815 /* FALL THROUGH */
7816 case KEY_NPAGE:
7817 case CTRL('f'):
7818 case 'f':
7819 case ' ':
7820 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7821 /* can't scroll any further; move cursor down */
7822 if (s->selected < s->ndisplayed - 1)
7823 s->selected += MIN(nscroll,
7824 s->ndisplayed - s->selected - 1);
7825 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7826 s->selected += s->ndisplayed - s->selected - 1;
7827 view->count = 0;
7828 break;
7830 ref_scroll_down(view, nscroll);
7831 break;
7832 case CTRL('l'):
7833 view->count = 0;
7834 tog_free_refs();
7835 err = tog_load_refs(s->repo, s->sort_by_date);
7836 if (err)
7837 break;
7838 ref_view_free_refs(s);
7839 err = ref_view_load_refs(s);
7840 break;
7841 case KEY_RESIZE:
7842 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7843 s->selected = view->nlines - 2;
7844 break;
7845 default:
7846 view->count = 0;
7847 break;
7850 return err;
7853 __dead static void
7854 usage_ref(void)
7856 endwin();
7857 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7858 getprogname());
7859 exit(1);
7862 static const struct got_error *
7863 cmd_ref(int argc, char *argv[])
7865 const struct got_error *error;
7866 struct got_repository *repo = NULL;
7867 struct got_worktree *worktree = NULL;
7868 char *cwd = NULL, *repo_path = NULL;
7869 int ch;
7870 struct tog_view *view;
7871 int *pack_fds = NULL;
7873 while ((ch = getopt(argc, argv, "r:")) != -1) {
7874 switch (ch) {
7875 case 'r':
7876 repo_path = realpath(optarg, NULL);
7877 if (repo_path == NULL)
7878 return got_error_from_errno2("realpath",
7879 optarg);
7880 break;
7881 default:
7882 usage_ref();
7883 /* NOTREACHED */
7887 argc -= optind;
7888 argv += optind;
7890 if (argc > 1)
7891 usage_ref();
7893 error = got_repo_pack_fds_open(&pack_fds);
7894 if (error != NULL)
7895 goto done;
7897 if (repo_path == NULL) {
7898 cwd = getcwd(NULL, 0);
7899 if (cwd == NULL)
7900 return got_error_from_errno("getcwd");
7901 error = got_worktree_open(&worktree, cwd);
7902 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7903 goto done;
7904 if (worktree)
7905 repo_path =
7906 strdup(got_worktree_get_repo_path(worktree));
7907 else
7908 repo_path = strdup(cwd);
7909 if (repo_path == NULL) {
7910 error = got_error_from_errno("strdup");
7911 goto done;
7915 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7916 if (error != NULL)
7917 goto done;
7919 init_curses();
7921 error = apply_unveil(got_repo_get_path(repo), NULL);
7922 if (error)
7923 goto done;
7925 error = tog_load_refs(repo, 0);
7926 if (error)
7927 goto done;
7929 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7930 if (view == NULL) {
7931 error = got_error_from_errno("view_open");
7932 goto done;
7935 error = open_ref_view(view, repo);
7936 if (error)
7937 goto done;
7939 if (worktree) {
7940 /* Release work tree lock. */
7941 got_worktree_close(worktree);
7942 worktree = NULL;
7944 error = view_loop(view);
7945 done:
7946 free(repo_path);
7947 free(cwd);
7948 if (repo) {
7949 const struct got_error *close_err = got_repo_close(repo);
7950 if (close_err)
7951 error = close_err;
7953 if (pack_fds) {
7954 const struct got_error *pack_err =
7955 got_repo_pack_fds_close(pack_fds);
7956 if (error == NULL)
7957 error = pack_err;
7959 tog_free_refs();
7960 return error;
7964 * If view was scrolled down to move the selected line into view when opening a
7965 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7967 static void
7968 offset_selection_up(struct tog_view *view)
7970 switch (view->type) {
7971 case TOG_VIEW_BLAME: {
7972 struct tog_blame_view_state *s = &view->state.blame;
7973 if (s->first_displayed_line == 1) {
7974 s->selected_line = MAX(s->selected_line - view->offset,
7975 1);
7976 break;
7978 if (s->first_displayed_line > view->offset)
7979 s->first_displayed_line -= view->offset;
7980 else
7981 s->first_displayed_line = 1;
7982 s->selected_line += view->offset;
7983 break;
7985 case TOG_VIEW_LOG:
7986 log_scroll_up(&view->state.log, view->offset);
7987 view->state.log.selected += view->offset;
7988 break;
7989 case TOG_VIEW_REF:
7990 ref_scroll_up(&view->state.ref, view->offset);
7991 view->state.ref.selected += view->offset;
7992 break;
7993 case TOG_VIEW_TREE:
7994 tree_scroll_up(&view->state.tree, view->offset);
7995 view->state.tree.selected += view->offset;
7996 break;
7997 default:
7998 break;
8001 view->offset = 0;
8005 * If the selected line is in the section of screen covered by the bottom split,
8006 * scroll down offset lines to move it into view and index its new position.
8008 static const struct got_error *
8009 offset_selection_down(struct tog_view *view)
8011 const struct got_error *err = NULL;
8012 const struct got_error *(*scrolld)(struct tog_view *, int);
8013 int *selected = NULL;
8014 int header, offset;
8016 switch (view->type) {
8017 case TOG_VIEW_BLAME: {
8018 struct tog_blame_view_state *s = &view->state.blame;
8019 header = 3;
8020 scrolld = NULL;
8021 if (s->selected_line > view->nlines - header) {
8022 offset = abs(view->nlines - s->selected_line - header);
8023 s->first_displayed_line += offset;
8024 s->selected_line -= offset;
8025 view->offset = offset;
8027 break;
8029 case TOG_VIEW_LOG: {
8030 struct tog_log_view_state *s = &view->state.log;
8031 scrolld = &log_scroll_down;
8032 header = view_is_parent_view(view) ? 3 : 2;
8033 selected = &s->selected;
8034 break;
8036 case TOG_VIEW_REF: {
8037 struct tog_ref_view_state *s = &view->state.ref;
8038 scrolld = &ref_scroll_down;
8039 header = 3;
8040 selected = &s->selected;
8041 break;
8043 case TOG_VIEW_TREE: {
8044 struct tog_tree_view_state *s = &view->state.tree;
8045 scrolld = &tree_scroll_down;
8046 header = 5;
8047 selected = &s->selected;
8048 break;
8050 default:
8051 selected = NULL;
8052 scrolld = NULL;
8053 header = 0;
8054 break;
8057 if (selected && *selected > view->nlines - header) {
8058 offset = abs(view->nlines - *selected - header);
8059 view->offset = offset;
8060 if (scrolld && offset) {
8061 err = scrolld(view, offset);
8062 *selected -= offset;
8066 return err;
8069 static void
8070 list_commands(FILE *fp)
8072 size_t i;
8074 fprintf(fp, "commands:");
8075 for (i = 0; i < nitems(tog_commands); i++) {
8076 const struct tog_cmd *cmd = &tog_commands[i];
8077 fprintf(fp, " %s", cmd->name);
8079 fputc('\n', fp);
8082 __dead static void
8083 usage(int hflag, int status)
8085 FILE *fp = (status == 0) ? stdout : stderr;
8087 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8088 getprogname());
8089 if (hflag) {
8090 fprintf(fp, "lazy usage: %s path\n", getprogname());
8091 list_commands(fp);
8093 exit(status);
8096 static char **
8097 make_argv(int argc, ...)
8099 va_list ap;
8100 char **argv;
8101 int i;
8103 va_start(ap, argc);
8105 argv = calloc(argc, sizeof(char *));
8106 if (argv == NULL)
8107 err(1, "calloc");
8108 for (i = 0; i < argc; i++) {
8109 argv[i] = strdup(va_arg(ap, char *));
8110 if (argv[i] == NULL)
8111 err(1, "strdup");
8114 va_end(ap);
8115 return argv;
8119 * Try to convert 'tog path' into a 'tog log path' command.
8120 * The user could simply have mistyped the command rather than knowingly
8121 * provided a path. So check whether argv[0] can in fact be resolved
8122 * to a path in the HEAD commit and print a special error if not.
8123 * This hack is for mpi@ <3
8125 static const struct got_error *
8126 tog_log_with_path(int argc, char *argv[])
8128 const struct got_error *error = NULL, *close_err;
8129 const struct tog_cmd *cmd = NULL;
8130 struct got_repository *repo = NULL;
8131 struct got_worktree *worktree = NULL;
8132 struct got_object_id *commit_id = NULL, *id = NULL;
8133 struct got_commit_object *commit = NULL;
8134 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8135 char *commit_id_str = NULL, **cmd_argv = NULL;
8136 int *pack_fds = NULL;
8138 cwd = getcwd(NULL, 0);
8139 if (cwd == NULL)
8140 return got_error_from_errno("getcwd");
8142 error = got_repo_pack_fds_open(&pack_fds);
8143 if (error != NULL)
8144 goto done;
8146 error = got_worktree_open(&worktree, cwd);
8147 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8148 goto done;
8150 if (worktree)
8151 repo_path = strdup(got_worktree_get_repo_path(worktree));
8152 else
8153 repo_path = strdup(cwd);
8154 if (repo_path == NULL) {
8155 error = got_error_from_errno("strdup");
8156 goto done;
8159 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8160 if (error != NULL)
8161 goto done;
8163 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8164 repo, worktree);
8165 if (error)
8166 goto done;
8168 error = tog_load_refs(repo, 0);
8169 if (error)
8170 goto done;
8171 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8172 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8173 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8174 if (error)
8175 goto done;
8177 if (worktree) {
8178 got_worktree_close(worktree);
8179 worktree = NULL;
8182 error = got_object_open_as_commit(&commit, repo, commit_id);
8183 if (error)
8184 goto done;
8186 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8187 if (error) {
8188 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8189 goto done;
8190 fprintf(stderr, "%s: '%s' is no known command or path\n",
8191 getprogname(), argv[0]);
8192 usage(1, 1);
8193 /* not reached */
8196 close_err = got_repo_close(repo);
8197 if (error == NULL)
8198 error = close_err;
8199 repo = NULL;
8201 error = got_object_id_str(&commit_id_str, commit_id);
8202 if (error)
8203 goto done;
8205 cmd = &tog_commands[0]; /* log */
8206 argc = 4;
8207 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8208 error = cmd->cmd_main(argc, cmd_argv);
8209 done:
8210 if (repo) {
8211 close_err = got_repo_close(repo);
8212 if (error == NULL)
8213 error = close_err;
8215 if (commit)
8216 got_object_commit_close(commit);
8217 if (worktree)
8218 got_worktree_close(worktree);
8219 if (pack_fds) {
8220 const struct got_error *pack_err =
8221 got_repo_pack_fds_close(pack_fds);
8222 if (error == NULL)
8223 error = pack_err;
8225 free(id);
8226 free(commit_id_str);
8227 free(commit_id);
8228 free(cwd);
8229 free(repo_path);
8230 free(in_repo_path);
8231 if (cmd_argv) {
8232 int i;
8233 for (i = 0; i < argc; i++)
8234 free(cmd_argv[i]);
8235 free(cmd_argv);
8237 tog_free_refs();
8238 return error;
8241 int
8242 main(int argc, char *argv[])
8244 const struct got_error *error = NULL;
8245 const struct tog_cmd *cmd = NULL;
8246 int ch, hflag = 0, Vflag = 0;
8247 char **cmd_argv = NULL;
8248 static const struct option longopts[] = {
8249 { "version", no_argument, NULL, 'V' },
8250 { NULL, 0, NULL, 0}
8252 char *diff_algo_str = NULL;
8254 setlocale(LC_CTYPE, "");
8256 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8257 switch (ch) {
8258 case 'h':
8259 hflag = 1;
8260 break;
8261 case 'V':
8262 Vflag = 1;
8263 break;
8264 default:
8265 usage(hflag, 1);
8266 /* NOTREACHED */
8270 argc -= optind;
8271 argv += optind;
8272 optind = 1;
8273 optreset = 1;
8275 if (Vflag) {
8276 got_version_print_str();
8277 return 0;
8280 #ifndef PROFILE
8281 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8282 NULL) == -1)
8283 err(1, "pledge");
8284 #endif
8286 if (argc == 0) {
8287 if (hflag)
8288 usage(hflag, 0);
8289 /* Build an argument vector which runs a default command. */
8290 cmd = &tog_commands[0];
8291 argc = 1;
8292 cmd_argv = make_argv(argc, cmd->name);
8293 } else {
8294 size_t i;
8296 /* Did the user specify a command? */
8297 for (i = 0; i < nitems(tog_commands); i++) {
8298 if (strncmp(tog_commands[i].name, argv[0],
8299 strlen(argv[0])) == 0) {
8300 cmd = &tog_commands[i];
8301 break;
8306 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8307 if (diff_algo_str) {
8308 if (strcasecmp(diff_algo_str, "patience") == 0)
8309 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8310 if (strcasecmp(diff_algo_str, "myers") == 0)
8311 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8314 if (cmd == NULL) {
8315 if (argc != 1)
8316 usage(0, 1);
8317 /* No command specified; try log with a path */
8318 error = tog_log_with_path(argc, argv);
8319 } else {
8320 if (hflag)
8321 cmd->cmd_usage();
8322 else
8323 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8326 endwin();
8327 putchar('\n');
8328 if (cmd_argv) {
8329 int i;
8330 for (i = 0; i < argc; i++)
8331 free(cmd_argv[i]);
8332 free(cmd_argv);
8335 if (error && error->code != GOT_ERR_CANCELLED)
8336 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8337 return 0;