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/stat.h>
18 #include <sys/ioctl.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #if defined(__FreeBSD__) || defined(__APPLE__)
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #endif
25 #include <curses.h>
26 #include <panel.h>
27 #include <locale.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_compat.h"
46 #include "got_version.h"
47 #include "got_error.h"
48 #include "got_object.h"
49 #include "got_reference.h"
50 #include "got_repository.h"
51 #include "got_diff.h"
52 #include "got_opentemp.h"
53 #include "got_utf8.h"
54 #include "got_cancel.h"
55 #include "got_commit_graph.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_path.h"
59 #include "got_worktree.h"
61 #ifndef MIN
62 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
63 #endif
65 #ifndef MAX
66 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
67 #endif
69 #ifndef CTRL
70 #define CTRL(x) ((x) & 0x1f)
71 #endif
73 #ifndef nitems
74 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
75 #endif
77 struct tog_cmd {
78 const char *name;
79 const struct got_error *(*cmd_main)(int, char *[]);
80 void (*cmd_usage)(void);
81 };
83 __dead static void usage(int, int);
84 __dead static void usage_log(void);
85 __dead static void usage_diff(void);
86 __dead static void usage_blame(void);
87 __dead static void usage_tree(void);
88 __dead static void usage_ref(void);
90 static const struct got_error* cmd_log(int, char *[]);
91 static const struct got_error* cmd_diff(int, char *[]);
92 static const struct got_error* cmd_blame(int, char *[]);
93 static const struct got_error* cmd_tree(int, char *[]);
94 static const struct got_error* cmd_ref(int, char *[]);
96 static const struct tog_cmd tog_commands[] = {
97 { "log", cmd_log, usage_log },
98 { "diff", cmd_diff, usage_diff },
99 { "blame", cmd_blame, usage_blame },
100 { "tree", cmd_tree, usage_tree },
101 { "ref", cmd_ref, usage_ref },
102 };
104 enum tog_view_type {
105 TOG_VIEW_DIFF,
106 TOG_VIEW_LOG,
107 TOG_VIEW_BLAME,
108 TOG_VIEW_TREE,
109 TOG_VIEW_REF,
110 };
112 enum tog_view_mode {
113 TOG_VIEW_SPLIT_NONE,
114 TOG_VIEW_SPLIT_VERT,
115 TOG_VIEW_SPLIT_HRZN
116 };
118 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
120 #define TOG_EOF_STRING "(END)"
122 struct commit_queue_entry {
123 TAILQ_ENTRY(commit_queue_entry) entry;
124 struct got_object_id *id;
125 struct got_commit_object *commit;
126 int idx;
127 };
128 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
129 struct commit_queue {
130 int ncommits;
131 struct commit_queue_head head;
132 };
134 struct tog_color {
135 STAILQ_ENTRY(tog_color) entry;
136 regex_t regex;
137 short colorpair;
138 };
139 STAILQ_HEAD(tog_colors, tog_color);
141 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
142 static struct got_reflist_object_id_map *tog_refs_idmap;
143 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
145 static const struct got_error *
146 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
147 struct got_reference* re2)
149 const char *name1 = got_ref_get_name(re1);
150 const char *name2 = got_ref_get_name(re2);
151 int isbackup1, isbackup2;
153 /* Sort backup refs towards the bottom of the list. */
154 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
155 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
156 if (!isbackup1 && isbackup2) {
157 *cmp = -1;
158 return NULL;
159 } else if (isbackup1 && !isbackup2) {
160 *cmp = 1;
161 return NULL;
164 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
165 return NULL;
168 static const struct got_error *
169 tog_load_refs(struct got_repository *repo, int sort_by_date)
171 const struct got_error *err;
173 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
174 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
175 repo);
176 if (err)
177 return err;
179 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
180 repo);
183 static void
184 tog_free_refs(void)
186 if (tog_refs_idmap) {
187 got_reflist_object_id_map_free(tog_refs_idmap);
188 tog_refs_idmap = NULL;
190 got_ref_list_free(&tog_refs);
193 static const struct got_error *
194 add_color(struct tog_colors *colors, const char *pattern,
195 int idx, short color)
197 const struct got_error *err = NULL;
198 struct tog_color *tc;
199 int regerr = 0;
201 if (idx < 1 || idx > COLOR_PAIRS - 1)
202 return NULL;
204 init_pair(idx, color, -1);
206 tc = calloc(1, sizeof(*tc));
207 if (tc == NULL)
208 return got_error_from_errno("calloc");
209 regerr = regcomp(&tc->regex, pattern,
210 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
211 if (regerr) {
212 static char regerr_msg[512];
213 static char err_msg[512];
214 regerror(regerr, &tc->regex, regerr_msg,
215 sizeof(regerr_msg));
216 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
217 regerr_msg);
218 err = got_error_msg(GOT_ERR_REGEX, err_msg);
219 free(tc);
220 return err;
222 tc->colorpair = idx;
223 STAILQ_INSERT_HEAD(colors, tc, entry);
224 return NULL;
227 static void
228 free_colors(struct tog_colors *colors)
230 struct tog_color *tc;
232 while (!STAILQ_EMPTY(colors)) {
233 tc = STAILQ_FIRST(colors);
234 STAILQ_REMOVE_HEAD(colors, entry);
235 regfree(&tc->regex);
236 free(tc);
240 static struct tog_color *
241 get_color(struct tog_colors *colors, int colorpair)
243 struct tog_color *tc = NULL;
245 STAILQ_FOREACH(tc, colors, entry) {
246 if (tc->colorpair == colorpair)
247 return tc;
250 return NULL;
253 static int
254 default_color_value(const char *envvar)
256 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
257 return COLOR_MAGENTA;
258 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
259 return COLOR_CYAN;
260 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
261 return COLOR_YELLOW;
262 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
263 return COLOR_GREEN;
264 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
265 return COLOR_MAGENTA;
266 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
271 return COLOR_GREEN;
272 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
275 return COLOR_CYAN;
276 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
277 return COLOR_YELLOW;
278 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
279 return COLOR_GREEN;
280 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
283 return COLOR_YELLOW;
284 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
285 return COLOR_CYAN;
287 return -1;
290 static int
291 get_color_value(const char *envvar)
293 const char *val = getenv(envvar);
295 if (val == NULL)
296 return default_color_value(envvar);
298 if (strcasecmp(val, "black") == 0)
299 return COLOR_BLACK;
300 if (strcasecmp(val, "red") == 0)
301 return COLOR_RED;
302 if (strcasecmp(val, "green") == 0)
303 return COLOR_GREEN;
304 if (strcasecmp(val, "yellow") == 0)
305 return COLOR_YELLOW;
306 if (strcasecmp(val, "blue") == 0)
307 return COLOR_BLUE;
308 if (strcasecmp(val, "magenta") == 0)
309 return COLOR_MAGENTA;
310 if (strcasecmp(val, "cyan") == 0)
311 return COLOR_CYAN;
312 if (strcasecmp(val, "white") == 0)
313 return COLOR_WHITE;
314 if (strcasecmp(val, "default") == 0)
315 return -1;
317 return default_color_value(envvar);
321 struct tog_diff_view_state {
322 struct got_object_id *id1, *id2;
323 const char *label1, *label2;
324 FILE *f, *f1, *f2;
325 int fd1, fd2;
326 int first_displayed_line;
327 int last_displayed_line;
328 int eof;
329 int diff_context;
330 int ignore_whitespace;
331 int force_text_diff;
332 struct got_repository *repo;
333 struct tog_colors colors;
334 size_t nlines;
335 off_t *line_offsets;
336 int matched_line;
337 int selected_line;
339 /* passed from log or blame view; may be NULL */
340 struct tog_view *parent_view;
341 };
343 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
344 static volatile sig_atomic_t tog_thread_error;
346 struct tog_log_thread_args {
347 pthread_cond_t need_commits;
348 pthread_cond_t commit_loaded;
349 int commits_needed;
350 int load_all;
351 struct got_commit_graph *graph;
352 struct commit_queue *commits;
353 const char *in_repo_path;
354 struct got_object_id *start_id;
355 struct got_repository *repo;
356 int *pack_fds;
357 int log_complete;
358 sig_atomic_t *quit;
359 struct commit_queue_entry **first_displayed_entry;
360 struct commit_queue_entry **selected_entry;
361 int *searching;
362 int *search_next_done;
363 regex_t *regex;
364 };
366 struct tog_log_view_state {
367 struct commit_queue commits;
368 struct commit_queue_entry *first_displayed_entry;
369 struct commit_queue_entry *last_displayed_entry;
370 struct commit_queue_entry *selected_entry;
371 int selected;
372 char *in_repo_path;
373 char *head_ref_name;
374 int log_branches;
375 struct got_repository *repo;
376 struct got_object_id *start_id;
377 sig_atomic_t quit;
378 pthread_t thread;
379 struct tog_log_thread_args thread_args;
380 struct commit_queue_entry *matched_entry;
381 struct commit_queue_entry *search_entry;
382 struct tog_colors colors;
383 };
385 #define TOG_COLOR_DIFF_MINUS 1
386 #define TOG_COLOR_DIFF_PLUS 2
387 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
388 #define TOG_COLOR_DIFF_META 4
389 #define TOG_COLOR_TREE_SUBMODULE 5
390 #define TOG_COLOR_TREE_SYMLINK 6
391 #define TOG_COLOR_TREE_DIRECTORY 7
392 #define TOG_COLOR_TREE_EXECUTABLE 8
393 #define TOG_COLOR_COMMIT 9
394 #define TOG_COLOR_AUTHOR 10
395 #define TOG_COLOR_DATE 11
396 #define TOG_COLOR_REFS_HEADS 12
397 #define TOG_COLOR_REFS_TAGS 13
398 #define TOG_COLOR_REFS_REMOTES 14
399 #define TOG_COLOR_REFS_BACKUP 15
401 struct tog_blame_cb_args {
402 struct tog_blame_line *lines; /* one per line */
403 int nlines;
405 struct tog_view *view;
406 struct got_object_id *commit_id;
407 int *quit;
408 };
410 struct tog_blame_thread_args {
411 const char *path;
412 struct got_repository *repo;
413 struct tog_blame_cb_args *cb_args;
414 int *complete;
415 got_cancel_cb cancel_cb;
416 void *cancel_arg;
417 };
419 struct tog_blame {
420 FILE *f;
421 off_t filesize;
422 struct tog_blame_line *lines;
423 int nlines;
424 off_t *line_offsets;
425 pthread_t thread;
426 struct tog_blame_thread_args thread_args;
427 struct tog_blame_cb_args cb_args;
428 const char *path;
429 int *pack_fds;
430 };
432 struct tog_blame_view_state {
433 int first_displayed_line;
434 int last_displayed_line;
435 int selected_line;
436 int last_diffed_line;
437 int blame_complete;
438 int eof;
439 int done;
440 struct got_object_id_queue blamed_commits;
441 struct got_object_qid *blamed_commit;
442 char *path;
443 struct got_repository *repo;
444 struct got_object_id *commit_id;
445 struct tog_blame blame;
446 int matched_line;
447 struct tog_colors colors;
448 };
450 struct tog_parent_tree {
451 TAILQ_ENTRY(tog_parent_tree) entry;
452 struct got_tree_object *tree;
453 struct got_tree_entry *first_displayed_entry;
454 struct got_tree_entry *selected_entry;
455 int selected;
456 };
458 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
460 struct tog_tree_view_state {
461 char *tree_label;
462 struct got_object_id *commit_id;/* commit which this tree belongs to */
463 struct got_tree_object *root; /* the commit's root tree entry */
464 struct got_tree_object *tree; /* currently displayed (sub-)tree */
465 struct got_tree_entry *first_displayed_entry;
466 struct got_tree_entry *last_displayed_entry;
467 struct got_tree_entry *selected_entry;
468 int ndisplayed, selected, show_ids;
469 struct tog_parent_trees parents; /* parent trees of current sub-tree */
470 char *head_ref_name;
471 struct got_repository *repo;
472 struct got_tree_entry *matched_entry;
473 struct tog_colors colors;
474 };
476 struct tog_reflist_entry {
477 TAILQ_ENTRY(tog_reflist_entry) entry;
478 struct got_reference *ref;
479 int idx;
480 };
482 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
484 struct tog_ref_view_state {
485 struct tog_reflist_head refs;
486 struct tog_reflist_entry *first_displayed_entry;
487 struct tog_reflist_entry *last_displayed_entry;
488 struct tog_reflist_entry *selected_entry;
489 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
490 struct got_repository *repo;
491 struct tog_reflist_entry *matched_entry;
492 struct tog_colors colors;
493 };
495 /*
496 * We implement two types of views: parent views and child views.
498 * The 'Tab' key switches focus between a parent view and its child view.
499 * Child views are shown side-by-side to their parent view, provided
500 * there is enough screen estate.
502 * When a new view is opened from within a parent view, this new view
503 * becomes a child view of the parent view, replacing any existing child.
505 * When a new view is opened from within a child view, this new view
506 * becomes a parent view which will obscure the views below until the
507 * user quits the new parent view by typing 'q'.
509 * This list of views contains parent views only.
510 * Child views are only pointed to by their parent view.
511 */
512 TAILQ_HEAD(tog_view_list_head, tog_view);
514 struct tog_view {
515 TAILQ_ENTRY(tog_view) entry;
516 WINDOW *window;
517 PANEL *panel;
518 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
519 int resized_y, resized_x; /* begin_y/x based on user resizing */
520 int maxx, x; /* max column and current start column */
521 int lines, cols; /* copies of LINES and COLS */
522 int nscrolled, offset; /* lines scrolled and hsplit line offset */
523 int ch, count; /* current keymap and count prefix */
524 int resize; /* set when in a resize event */
525 int focussed; /* Only set on one parent or child view at a time. */
526 int dying;
527 struct tog_view *parent;
528 struct tog_view *child;
530 /*
531 * This flag is initially set on parent views when a new child view
532 * is created. It gets toggled when the 'Tab' key switches focus
533 * between parent and child.
534 * The flag indicates whether focus should be passed on to our child
535 * view if this parent view gets picked for focus after another parent
536 * view was closed. This prevents child views from losing focus in such
537 * situations.
538 */
539 int focus_child;
541 enum tog_view_mode mode;
542 /* type-specific state */
543 enum tog_view_type type;
544 union {
545 struct tog_diff_view_state diff;
546 struct tog_log_view_state log;
547 struct tog_blame_view_state blame;
548 struct tog_tree_view_state tree;
549 struct tog_ref_view_state ref;
550 } state;
552 const struct got_error *(*show)(struct tog_view *);
553 const struct got_error *(*input)(struct tog_view **,
554 struct tog_view *, int);
555 const struct got_error *(*reset)(struct tog_view *);
556 const struct got_error *(*close)(struct tog_view *);
558 const struct got_error *(*search_start)(struct tog_view *);
559 const struct got_error *(*search_next)(struct tog_view *);
560 int search_started;
561 int searching;
562 #define TOG_SEARCH_FORWARD 1
563 #define TOG_SEARCH_BACKWARD 2
564 int search_next_done;
565 #define TOG_SEARCH_HAVE_MORE 1
566 #define TOG_SEARCH_NO_MORE 2
567 #define TOG_SEARCH_HAVE_NONE 3
568 regex_t regex;
569 regmatch_t regmatch;
570 };
572 static const struct got_error *open_diff_view(struct tog_view *,
573 struct got_object_id *, struct got_object_id *,
574 const char *, const char *, int, int, int, struct tog_view *,
575 struct got_repository *);
576 static const struct got_error *show_diff_view(struct tog_view *);
577 static const struct got_error *input_diff_view(struct tog_view **,
578 struct tog_view *, int);
579 static const struct got_error *reset_diff_view(struct tog_view *);
580 static const struct got_error* close_diff_view(struct tog_view *);
581 static const struct got_error *search_start_diff_view(struct tog_view *);
582 static const struct got_error *search_next_diff_view(struct tog_view *);
584 static const struct got_error *open_log_view(struct tog_view *,
585 struct got_object_id *, struct got_repository *,
586 const char *, const char *, int);
587 static const struct got_error * show_log_view(struct tog_view *);
588 static const struct got_error *input_log_view(struct tog_view **,
589 struct tog_view *, int);
590 static const struct got_error *close_log_view(struct tog_view *);
591 static const struct got_error *search_start_log_view(struct tog_view *);
592 static const struct got_error *search_next_log_view(struct tog_view *);
594 static const struct got_error *open_blame_view(struct tog_view *, char *,
595 struct got_object_id *, struct got_repository *);
596 static const struct got_error *show_blame_view(struct tog_view *);
597 static const struct got_error *input_blame_view(struct tog_view **,
598 struct tog_view *, int);
599 static const struct got_error *reset_blame_view(struct tog_view *);
600 static const struct got_error *close_blame_view(struct tog_view *);
601 static const struct got_error *search_start_blame_view(struct tog_view *);
602 static const struct got_error *search_next_blame_view(struct tog_view *);
604 static const struct got_error *open_tree_view(struct tog_view *,
605 struct got_object_id *, const char *, struct got_repository *);
606 static const struct got_error *show_tree_view(struct tog_view *);
607 static const struct got_error *input_tree_view(struct tog_view **,
608 struct tog_view *, int);
609 static const struct got_error *close_tree_view(struct tog_view *);
610 static const struct got_error *search_start_tree_view(struct tog_view *);
611 static const struct got_error *search_next_tree_view(struct tog_view *);
613 static const struct got_error *open_ref_view(struct tog_view *,
614 struct got_repository *);
615 static const struct got_error *show_ref_view(struct tog_view *);
616 static const struct got_error *input_ref_view(struct tog_view **,
617 struct tog_view *, int);
618 static const struct got_error *close_ref_view(struct tog_view *);
619 static const struct got_error *search_start_ref_view(struct tog_view *);
620 static const struct got_error *search_next_ref_view(struct tog_view *);
622 static volatile sig_atomic_t tog_sigwinch_received;
623 static volatile sig_atomic_t tog_sigpipe_received;
624 static volatile sig_atomic_t tog_sigcont_received;
625 static volatile sig_atomic_t tog_sigint_received;
626 static volatile sig_atomic_t tog_sigterm_received;
628 static void
629 tog_sigwinch(int signo)
631 tog_sigwinch_received = 1;
634 static void
635 tog_sigpipe(int signo)
637 tog_sigpipe_received = 1;
640 static void
641 tog_sigcont(int signo)
643 tog_sigcont_received = 1;
646 static void
647 tog_sigint(int signo)
649 tog_sigint_received = 1;
652 static void
653 tog_sigterm(int signo)
655 tog_sigterm_received = 1;
658 static int
659 tog_fatal_signal_received(void)
661 return (tog_sigpipe_received ||
662 tog_sigint_received || tog_sigint_received);
665 static const struct got_error *
666 view_close(struct tog_view *view)
668 const struct got_error *err = NULL, *child_err = NULL;
670 if (view->child) {
671 child_err = view_close(view->child);
672 view->child = NULL;
674 if (view->close)
675 err = view->close(view);
676 if (view->panel)
677 del_panel(view->panel);
678 if (view->window)
679 delwin(view->window);
680 free(view);
681 return err ? err : child_err;
684 static struct tog_view *
685 view_open(int nlines, int ncols, int begin_y, int begin_x,
686 enum tog_view_type type)
688 struct tog_view *view = calloc(1, sizeof(*view));
690 if (view == NULL)
691 return NULL;
693 view->type = type;
694 view->lines = LINES;
695 view->cols = COLS;
696 view->nlines = nlines ? nlines : LINES - begin_y;
697 view->ncols = ncols ? ncols : COLS - begin_x;
698 view->begin_y = begin_y;
699 view->begin_x = begin_x;
700 view->window = newwin(nlines, ncols, begin_y, begin_x);
701 if (view->window == NULL) {
702 view_close(view);
703 return NULL;
705 view->panel = new_panel(view->window);
706 if (view->panel == NULL ||
707 set_panel_userptr(view->panel, view) != OK) {
708 view_close(view);
709 return NULL;
712 keypad(view->window, TRUE);
713 return view;
716 static int
717 view_split_begin_x(int begin_x)
719 if (begin_x > 0 || COLS < 120)
720 return 0;
721 return (COLS - MAX(COLS / 2, 80));
724 /* XXX Stub till we decide what to do. */
725 static int
726 view_split_begin_y(int lines)
728 return lines * HSPLIT_SCALE;
731 static const struct got_error *view_resize(struct tog_view *);
733 static const struct got_error *
734 view_splitscreen(struct tog_view *view)
736 const struct got_error *err = NULL;
738 if (!view->resize && view->mode == TOG_VIEW_SPLIT_HRZN) {
739 if (view->resized_y && view->resized_y < view->lines)
740 view->begin_y = view->resized_y;
741 else
742 view->begin_y = view_split_begin_y(view->nlines);
743 view->begin_x = 0;
744 } else if (!view->resize) {
745 if (view->resized_x && view->resized_x < view->cols - 1 &&
746 view->cols > 119)
747 view->begin_x = view->resized_x;
748 else
749 view->begin_x = view_split_begin_x(0);
750 view->begin_y = 0;
752 view->nlines = LINES - view->begin_y;
753 view->ncols = COLS - view->begin_x;
754 view->lines = LINES;
755 view->cols = COLS;
756 err = view_resize(view);
757 if (err)
758 return err;
760 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
761 view->parent->nlines = view->begin_y;
763 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
764 return got_error_from_errno("mvwin");
766 return NULL;
769 static const struct got_error *
770 view_fullscreen(struct tog_view *view)
772 const struct got_error *err = NULL;
774 view->begin_x = 0;
775 view->begin_y = view->resize ? view->begin_y : 0;
776 view->nlines = view->resize ? view->nlines : LINES;
777 view->ncols = COLS;
778 view->lines = LINES;
779 view->cols = COLS;
780 err = view_resize(view);
781 if (err)
782 return err;
784 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
785 return got_error_from_errno("mvwin");
787 return NULL;
790 static int
791 view_is_parent_view(struct tog_view *view)
793 return view->parent == NULL;
796 static int
797 view_is_splitscreen(struct tog_view *view)
799 return view->begin_x > 0 || view->begin_y > 0;
802 static int
803 view_is_fullscreen(struct tog_view *view)
805 return view->nlines == LINES && view->ncols == COLS;
808 static int
809 view_is_hsplit_top(struct tog_view *view)
811 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
812 view_is_splitscreen(view->child);
815 static void
816 view_border(struct tog_view *view)
818 PANEL *panel;
819 const struct tog_view *view_above;
821 if (view->parent)
822 return view_border(view->parent);
824 panel = panel_above(view->panel);
825 if (panel == NULL)
826 return;
828 view_above = panel_userptr(panel);
829 if (view->mode == TOG_VIEW_SPLIT_HRZN)
830 mvwhline(view->window, view_above->begin_y - 1,
831 view->begin_x, got_locale_is_utf8() ?
832 ACS_HLINE : '-', view->ncols);
833 else
834 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
835 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
838 static const struct got_error *view_init_hsplit(struct tog_view *, int);
839 static const struct got_error *request_log_commits(struct tog_view *);
840 static const struct got_error *offset_selection_down(struct tog_view *);
841 static void offset_selection_up(struct tog_view *);
842 static void view_get_split(struct tog_view *, int *, int *);
844 static const struct got_error *
845 view_resize(struct tog_view *view)
847 const struct got_error *err = NULL;
848 int dif, nlines, ncols;
850 dif = LINES - view->lines; /* line difference */
852 if (view->lines > LINES)
853 nlines = view->nlines - (view->lines - LINES);
854 else
855 nlines = view->nlines + (LINES - view->lines);
856 if (view->cols > COLS)
857 ncols = view->ncols - (view->cols - COLS);
858 else
859 ncols = view->ncols + (COLS - view->cols);
861 if (view->child) {
862 int hs = view->child->begin_y;
864 if (!view_is_fullscreen(view))
865 view->child->begin_x = view_split_begin_x(view->begin_x);
866 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
867 view->child->begin_x == 0) {
868 ncols = COLS;
870 view_fullscreen(view->child);
871 if (view->child->focussed)
872 show_panel(view->child->panel);
873 else
874 show_panel(view->panel);
875 } else {
876 ncols = view->child->begin_x;
878 view_splitscreen(view->child);
879 show_panel(view->child->panel);
881 /*
882 * Request commits if terminal height was increased in a log
883 * view so we have enough commits loaded to populate the view.
884 */
885 if (view->type == TOG_VIEW_LOG && dif > 0) {
886 struct tog_log_view_state *ts = &view->state.log;
888 if (ts->commits.ncommits < ts->selected_entry->idx +
889 view->lines - ts->selected) {
890 view->nscrolled = ts->selected_entry->idx +
891 view->lines - ts->selected -
892 ts->commits.ncommits + dif;
893 err = request_log_commits(view);
894 if (err)
895 return err;
899 /*
900 * XXX This is ugly and needs to be moved into the above
901 * logic but "works" for now and my attempts at moving it
902 * break either 'tab' or 'F' key maps in horizontal splits.
903 */
904 if (hs) {
905 err = view_splitscreen(view->child);
906 if (err)
907 return err;
908 if (dif < 0) { /* top split decreased */
909 err = offset_selection_down(view);
910 if (err)
911 return err;
913 view_border(view);
914 update_panels();
915 doupdate();
916 show_panel(view->child->panel);
917 nlines = view->nlines;
919 } else if (view->parent == NULL)
920 ncols = COLS;
922 if (wresize(view->window, nlines, ncols) == ERR)
923 return got_error_from_errno("wresize");
924 if (replace_panel(view->panel, view->window) == ERR)
925 return got_error_from_errno("replace_panel");
926 wclear(view->window);
928 view->nlines = nlines;
929 view->ncols = ncols;
930 view->lines = LINES;
931 view->cols = COLS;
933 return NULL;
936 static void
937 view_adjust_offset(struct tog_view *view, int n)
939 if (n == 0)
940 return;
942 if (view->parent && view->parent->offset) {
943 if (view->parent->offset + n >= 0)
944 view->parent->offset += n;
945 else
946 view->parent->offset = 0;
947 } else if (view->offset) {
948 if (view->offset - n >= 0)
949 view->offset -= n;
950 else
951 view->offset = 0;
955 static const struct got_error *
956 view_resize_split(struct tog_view *view, int resize)
958 const struct got_error *err = NULL;
959 struct tog_view *v = NULL;
961 if (view->parent)
962 v = view->parent;
963 else
964 v = view;
966 if (!v->child || !view_is_splitscreen(v->child))
967 return NULL;
969 v->resize = v->child->resize = resize; /* lock for resize event */
971 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
972 int y = v->child->begin_y;
974 if (v->child->resized_y)
975 v->child->begin_y = v->child->resized_y;
976 if (view->parent)
977 v->child->begin_y -= resize;
978 else
979 v->child->begin_y += resize;
980 if (v->child->begin_y < 3) {
981 view->count = 0;
982 v->child->begin_y = 3;
983 } else if (v->child->begin_y > LINES - 1) {
984 view->count = 0;
985 v->child->begin_y = LINES - 1;
987 v->ncols = COLS;
988 v->child->ncols = COLS;
989 view_adjust_offset(view, resize);
990 err = view_init_hsplit(v, v->child->begin_y);
991 if (err)
992 return err;
993 v->child->resized_y = v->child->begin_y;
994 if (y > v->child->begin_y && v->child->type == TOG_VIEW_LOG)
995 v->child->nscrolled = y - v->child->begin_y;
996 else if (y < v->child->begin_y && v->type == TOG_VIEW_LOG)
997 v->nscrolled = v->child->begin_y - y;
998 } else {
999 if (v->child->resized_x)
1000 v->child->begin_x = v->child->resized_x;
1001 if (view->parent)
1002 v->child->begin_x -= resize;
1003 else
1004 v->child->begin_x += resize;
1005 if (v->child->begin_x < 11) {
1006 view->count = 0;
1007 v->child->begin_x = 11;
1008 } else if (v->child->begin_x > COLS - 1) {
1009 view->count = 0;
1010 v->child->begin_x = COLS - 1;
1012 v->child->resized_x = v->child->begin_x;
1015 v->child->mode = v->mode;
1016 v->child->nlines = v->lines - v->child->begin_y;
1017 v->child->ncols = v->cols - v->child->begin_x;
1018 v->focus_child = 1;
1020 err = view_fullscreen(v);
1021 if (err)
1022 return err;
1023 err = view_splitscreen(v->child);
1024 if (err)
1025 return err;
1027 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1028 err = offset_selection_down(v->child);
1029 if (err)
1030 return err;
1033 if (v->nscrolled)
1034 err = request_log_commits(v);
1035 else if (v->child->nscrolled)
1036 err = request_log_commits(v->child);
1038 v->resize = v->child->resize = 0;
1040 return err;
1043 static void
1044 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1046 struct tog_view *v = src->child ? src->child : src;
1048 dst->resized_x = v->resized_x;
1049 dst->resized_y = v->resized_y;
1052 static const struct got_error *
1053 view_close_child(struct tog_view *view)
1055 const struct got_error *err = NULL;
1057 if (view->child == NULL)
1058 return NULL;
1060 err = view_close(view->child);
1061 view->child = NULL;
1062 return err;
1065 static const struct got_error *
1066 view_set_child(struct tog_view *view, struct tog_view *child)
1068 const struct got_error *err = NULL;
1070 view->child = child;
1071 child->parent = view;
1073 err = view_resize(view);
1074 if (err)
1075 return err;
1077 if (view->child->resized_x || view->child->resized_y)
1078 err = view_resize_split(view, 0);
1080 return err;
1083 static void
1084 tog_resizeterm(void)
1086 int cols, lines;
1087 struct winsize size;
1089 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1090 cols = 80; /* Default */
1091 lines = 24;
1092 } else {
1093 cols = size.ws_col;
1094 lines = size.ws_row;
1096 resize_term(lines, cols);
1099 static const struct got_error *
1100 view_search_start(struct tog_view *view)
1102 const struct got_error *err = NULL;
1103 struct tog_view *v = view;
1104 char pattern[1024];
1105 int ret;
1107 if (view->search_started) {
1108 regfree(&view->regex);
1109 view->searching = 0;
1110 memset(&view->regmatch, 0, sizeof(view->regmatch));
1112 view->search_started = 0;
1114 if (view->nlines < 1)
1115 return NULL;
1117 if (view_is_hsplit_top(view))
1118 v = view->child;
1120 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1121 wclrtoeol(v->window);
1123 nodelay(view->window, FALSE); /* block for search term input */
1124 nocbreak();
1125 echo();
1126 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1127 wrefresh(v->window);
1128 cbreak();
1129 noecho();
1130 nodelay(view->window, TRUE);
1131 if (ret == ERR)
1132 return NULL;
1134 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1135 err = view->search_start(view);
1136 if (err) {
1137 regfree(&view->regex);
1138 return err;
1140 view->search_started = 1;
1141 view->searching = TOG_SEARCH_FORWARD;
1142 view->search_next_done = 0;
1143 view->search_next(view);
1146 return NULL;
1149 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1150 static const struct got_error *
1151 switch_split(struct tog_view *view)
1153 const struct got_error *err = NULL;
1154 struct tog_view *v = NULL;
1156 if (view->parent)
1157 v = view->parent;
1158 else
1159 v = view;
1161 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1162 v->mode = TOG_VIEW_SPLIT_VERT;
1163 else
1164 v->mode = TOG_VIEW_SPLIT_HRZN;
1166 if (!v->child)
1167 return NULL;
1168 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1169 v->mode = TOG_VIEW_SPLIT_NONE;
1171 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1172 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1173 v->child->begin_y = v->child->resized_y;
1174 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1175 v->child->begin_x = v->child->resized_x;
1178 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1179 v->ncols = COLS;
1180 v->child->ncols = COLS;
1181 v->child->nscrolled = LINES - v->child->nlines;
1183 err = view_init_hsplit(v, v->child->begin_y);
1184 if (err)
1185 return err;
1187 v->child->mode = v->mode;
1188 v->child->nlines = v->lines - v->child->begin_y;
1189 v->focus_child = 1;
1191 err = view_fullscreen(v);
1192 if (err)
1193 return err;
1194 err = view_splitscreen(v->child);
1195 if (err)
1196 return err;
1198 if (v->mode == TOG_VIEW_SPLIT_NONE)
1199 v->mode = TOG_VIEW_SPLIT_VERT;
1200 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1201 err = offset_selection_down(v);
1202 err = offset_selection_down(v->child);
1203 } else {
1204 offset_selection_up(v);
1205 offset_selection_up(v->child);
1207 if (v->type == TOG_VIEW_LOG && v->nscrolled)
1208 err = request_log_commits(v);
1209 else if (v->child->type == TOG_VIEW_LOG && v->child->nscrolled)
1210 err = request_log_commits(v->child);
1212 return err;
1216 * Compute view->count from numeric input. Assign total to view->count and
1217 * return first non-numeric key entered.
1219 static int
1220 get_compound_key(struct tog_view *view, int c)
1222 struct tog_view *v = view;
1223 int x, n = 0;
1225 if (view_is_hsplit_top(view))
1226 v = view->child;
1227 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1228 v = view->parent;
1230 view->count = 0;
1231 cbreak(); /* block for input */
1232 wmove(v->window, v->nlines - 1, 0);
1233 wclrtoeol(v->window);
1234 waddch(v->window, ':');
1236 do {
1237 x = getcurx(v->window);
1238 if (x != ERR && x < view->ncols) {
1239 waddch(v->window, c);
1240 wrefresh(v->window);
1244 * Don't overflow. Max valid request should be the greatest
1245 * between the longest and total lines; cap at 10 million.
1247 if (n >= 9999999)
1248 n = 9999999;
1249 else
1250 n = n * 10 + (c - '0');
1251 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1253 /* Massage excessive or inapplicable values at the input handler. */
1254 view->count = n;
1256 return c;
1259 static const struct got_error *
1260 view_input(struct tog_view **new, int *done, struct tog_view *view,
1261 struct tog_view_list_head *views)
1263 const struct got_error *err = NULL;
1264 struct tog_view *v;
1265 int ch, errcode;
1267 *new = NULL;
1269 /* Clear "no matches" indicator. */
1270 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1271 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1272 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1273 view->count = 0;
1276 if (view->searching && !view->search_next_done) {
1277 errcode = pthread_mutex_unlock(&tog_mutex);
1278 if (errcode)
1279 return got_error_set_errno(errcode,
1280 "pthread_mutex_unlock");
1281 sched_yield();
1282 errcode = pthread_mutex_lock(&tog_mutex);
1283 if (errcode)
1284 return got_error_set_errno(errcode,
1285 "pthread_mutex_lock");
1286 view->search_next(view);
1287 return NULL;
1290 nodelay(view->window, FALSE);
1291 /* Allow threads to make progress while we are waiting for input. */
1292 errcode = pthread_mutex_unlock(&tog_mutex);
1293 if (errcode)
1294 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1295 /* If we have an unfinished count, let C-g or backspace abort. */
1296 if (view->count && --view->count) {
1297 cbreak();
1298 nodelay(view->window, TRUE);
1299 ch = wgetch(view->window);
1300 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1301 view->count = 0;
1302 else
1303 ch = view->ch;
1304 } else {
1305 ch = wgetch(view->window);
1306 if (ch >= '1' && ch <= '9')
1307 view->ch = ch = get_compound_key(view, ch);
1309 errcode = pthread_mutex_lock(&tog_mutex);
1310 if (errcode)
1311 return got_error_set_errno(errcode, "pthread_mutex_lock");
1312 nodelay(view->window, TRUE);
1314 if (tog_sigwinch_received || tog_sigcont_received) {
1315 tog_resizeterm();
1316 tog_sigwinch_received = 0;
1317 tog_sigcont_received = 0;
1318 TAILQ_FOREACH(v, views, entry) {
1319 err = view_resize(v);
1320 if (err)
1321 return err;
1322 err = v->input(new, v, KEY_RESIZE);
1323 if (err)
1324 return err;
1325 if (v->child) {
1326 err = view_resize(v->child);
1327 if (err)
1328 return err;
1329 err = v->child->input(new, v->child,
1330 KEY_RESIZE);
1331 if (err)
1332 return err;
1333 if (v->child->resized_x || v->child->resized_y) {
1334 err = view_resize_split(v, 0);
1335 if (err)
1336 return err;
1342 switch (ch) {
1343 case '\t':
1344 view->count = 0;
1345 if (view->child) {
1346 view->focussed = 0;
1347 view->child->focussed = 1;
1348 view->focus_child = 1;
1349 } else if (view->parent) {
1350 view->focussed = 0;
1351 view->parent->focussed = 1;
1352 view->parent->focus_child = 0;
1353 if (!view_is_splitscreen(view)) {
1354 if (view->mode == TOG_VIEW_SPLIT_HRZN &&
1355 view->parent->type == TOG_VIEW_LOG) {
1356 err = request_log_commits(view->parent);
1357 if (err)
1358 return err;
1360 offset_selection_up(view->parent);
1361 err = view_fullscreen(view->parent);
1362 if (err)
1363 return err;
1366 break;
1367 case 'q':
1368 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1369 if (view->parent->type == TOG_VIEW_LOG) {
1370 /* might need more commits to fill fullscreen */
1371 err = request_log_commits(view->parent);
1372 if (err)
1373 break;
1375 offset_selection_up(view->parent);
1377 err = view->input(new, view, ch);
1378 view->dying = 1;
1379 break;
1380 case 'Q':
1381 *done = 1;
1382 break;
1383 case 'F':
1384 view->count = 0;
1385 if (view_is_parent_view(view)) {
1386 if (view->child == NULL)
1387 break;
1388 if (view_is_splitscreen(view->child)) {
1389 view->focussed = 0;
1390 view->child->focussed = 1;
1391 err = view_fullscreen(view->child);
1392 } else {
1393 err = view_splitscreen(view->child);
1394 if (!err)
1395 err = view_resize_split(view, 0);
1397 if (err)
1398 break;
1399 err = view->child->input(new, view->child,
1400 KEY_RESIZE);
1401 } else {
1402 if (view_is_splitscreen(view)) {
1403 view->parent->focussed = 0;
1404 view->focussed = 1;
1405 err = view_fullscreen(view);
1406 } else {
1407 err = view_splitscreen(view);
1408 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1409 err = view_resize(view->parent);
1410 if (!err)
1411 err = view_resize_split(view, 0);
1413 if (err)
1414 break;
1415 err = view->input(new, view, KEY_RESIZE);
1417 if (err)
1418 break;
1419 if (view->type == TOG_VIEW_LOG) {
1420 err = request_log_commits(view);
1421 if (err)
1422 break;
1424 if (view->parent)
1425 err = offset_selection_down(view->parent);
1426 if (!err)
1427 err = offset_selection_down(view);
1428 break;
1429 case 'S':
1430 view->count = 0;
1431 err = switch_split(view);
1432 break;
1433 case '-':
1434 err = view_resize_split(view, -1);
1435 break;
1436 case '+':
1437 err = view_resize_split(view, 1);
1438 break;
1439 case KEY_RESIZE:
1440 break;
1441 case '/':
1442 view->count = 0;
1443 if (view->search_start)
1444 view_search_start(view);
1445 else
1446 err = view->input(new, view, ch);
1447 break;
1448 case 'N':
1449 case 'n':
1450 if (view->search_started && view->search_next) {
1451 view->searching = (ch == 'n' ?
1452 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1453 view->search_next_done = 0;
1454 view->search_next(view);
1455 } else
1456 err = view->input(new, view, ch);
1457 break;
1458 case 'A':
1459 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1460 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1461 else
1462 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1463 TAILQ_FOREACH(v, views, entry) {
1464 if (v->reset) {
1465 err = v->reset(v);
1466 if (err)
1467 return err;
1469 if (v->child && v->child->reset) {
1470 err = v->child->reset(v->child);
1471 if (err)
1472 return err;
1475 break;
1476 default:
1477 err = view->input(new, view, ch);
1478 break;
1481 return err;
1484 static int
1485 view_needs_focus_indication(struct tog_view *view)
1487 if (view_is_parent_view(view)) {
1488 if (view->child == NULL || view->child->focussed)
1489 return 0;
1490 if (!view_is_splitscreen(view->child))
1491 return 0;
1492 } else if (!view_is_splitscreen(view))
1493 return 0;
1495 return view->focussed;
1498 static const struct got_error *
1499 view_loop(struct tog_view *view)
1501 const struct got_error *err = NULL;
1502 struct tog_view_list_head views;
1503 struct tog_view *new_view;
1504 char *mode;
1505 int fast_refresh = 10;
1506 int done = 0, errcode;
1508 mode = getenv("TOG_VIEW_SPLIT_MODE");
1509 if (!mode || !(*mode == 'h' || *mode == 'H'))
1510 view->mode = TOG_VIEW_SPLIT_VERT;
1511 else
1512 view->mode = TOG_VIEW_SPLIT_HRZN;
1514 errcode = pthread_mutex_lock(&tog_mutex);
1515 if (errcode)
1516 return got_error_set_errno(errcode, "pthread_mutex_lock");
1518 TAILQ_INIT(&views);
1519 TAILQ_INSERT_HEAD(&views, view, entry);
1521 view->focussed = 1;
1522 err = view->show(view);
1523 if (err)
1524 return err;
1525 update_panels();
1526 doupdate();
1527 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1528 !tog_fatal_signal_received()) {
1529 /* Refresh fast during initialization, then become slower. */
1530 if (fast_refresh && fast_refresh-- == 0)
1531 halfdelay(10); /* switch to once per second */
1533 err = view_input(&new_view, &done, view, &views);
1534 if (err)
1535 break;
1536 if (view->dying) {
1537 struct tog_view *v, *prev = NULL;
1539 if (view_is_parent_view(view))
1540 prev = TAILQ_PREV(view, tog_view_list_head,
1541 entry);
1542 else if (view->parent)
1543 prev = view->parent;
1545 if (view->parent) {
1546 view->parent->child = NULL;
1547 view->parent->focus_child = 0;
1548 /* Restore fullscreen line height. */
1549 view->parent->nlines = view->parent->lines;
1550 err = view_resize(view->parent);
1551 if (err)
1552 break;
1553 /* Make resized splits persist. */
1554 view_transfer_size(view->parent, view);
1555 } else
1556 TAILQ_REMOVE(&views, view, entry);
1558 err = view_close(view);
1559 if (err)
1560 goto done;
1562 view = NULL;
1563 TAILQ_FOREACH(v, &views, entry) {
1564 if (v->focussed)
1565 break;
1567 if (view == NULL && new_view == NULL) {
1568 /* No view has focus. Try to pick one. */
1569 if (prev)
1570 view = prev;
1571 else if (!TAILQ_EMPTY(&views)) {
1572 view = TAILQ_LAST(&views,
1573 tog_view_list_head);
1575 if (view) {
1576 if (view->focus_child) {
1577 view->child->focussed = 1;
1578 view = view->child;
1579 } else
1580 view->focussed = 1;
1584 if (new_view) {
1585 struct tog_view *v, *t;
1586 /* Only allow one parent view per type. */
1587 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1588 if (v->type != new_view->type)
1589 continue;
1590 TAILQ_REMOVE(&views, v, entry);
1591 err = view_close(v);
1592 if (err)
1593 goto done;
1594 break;
1596 TAILQ_INSERT_TAIL(&views, new_view, entry);
1597 view = new_view;
1599 if (view) {
1600 if (view_is_parent_view(view)) {
1601 if (view->child && view->child->focussed)
1602 view = view->child;
1603 } else {
1604 if (view->parent && view->parent->focussed)
1605 view = view->parent;
1607 show_panel(view->panel);
1608 if (view->child && view_is_splitscreen(view->child))
1609 show_panel(view->child->panel);
1610 if (view->parent && view_is_splitscreen(view)) {
1611 err = view->parent->show(view->parent);
1612 if (err)
1613 goto done;
1615 err = view->show(view);
1616 if (err)
1617 goto done;
1618 if (view->child) {
1619 err = view->child->show(view->child);
1620 if (err)
1621 goto done;
1623 update_panels();
1624 doupdate();
1627 done:
1628 while (!TAILQ_EMPTY(&views)) {
1629 const struct got_error *close_err;
1630 view = TAILQ_FIRST(&views);
1631 TAILQ_REMOVE(&views, view, entry);
1632 close_err = view_close(view);
1633 if (close_err && err == NULL)
1634 err = close_err;
1637 errcode = pthread_mutex_unlock(&tog_mutex);
1638 if (errcode && err == NULL)
1639 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1641 return err;
1644 __dead static void
1645 usage_log(void)
1647 endwin();
1648 fprintf(stderr,
1649 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1650 getprogname());
1651 exit(1);
1654 /* Create newly allocated wide-character string equivalent to a byte string. */
1655 static const struct got_error *
1656 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1658 char *vis = NULL;
1659 const struct got_error *err = NULL;
1661 *ws = NULL;
1662 *wlen = mbstowcs(NULL, s, 0);
1663 if (*wlen == (size_t)-1) {
1664 int vislen;
1665 if (errno != EILSEQ)
1666 return got_error_from_errno("mbstowcs");
1668 /* byte string invalid in current encoding; try to "fix" it */
1669 err = got_mbsavis(&vis, &vislen, s);
1670 if (err)
1671 return err;
1672 *wlen = mbstowcs(NULL, vis, 0);
1673 if (*wlen == (size_t)-1) {
1674 err = got_error_from_errno("mbstowcs"); /* give up */
1675 goto done;
1679 *ws = calloc(*wlen + 1, sizeof(**ws));
1680 if (*ws == NULL) {
1681 err = got_error_from_errno("calloc");
1682 goto done;
1685 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1686 err = got_error_from_errno("mbstowcs");
1687 done:
1688 free(vis);
1689 if (err) {
1690 free(*ws);
1691 *ws = NULL;
1692 *wlen = 0;
1694 return err;
1697 static const struct got_error *
1698 expand_tab(char **ptr, const char *src)
1700 char *dst;
1701 size_t len, n, idx = 0, sz = 0;
1703 *ptr = NULL;
1704 n = len = strlen(src);
1705 dst = malloc(n + 1);
1706 if (dst == NULL)
1707 return got_error_from_errno("malloc");
1709 while (idx < len && src[idx]) {
1710 const char c = src[idx];
1712 if (c == '\t') {
1713 size_t nb = TABSIZE - sz % TABSIZE;
1714 char *p;
1716 p = realloc(dst, n + nb);
1717 if (p == NULL) {
1718 free(dst);
1719 return got_error_from_errno("realloc");
1722 dst = p;
1723 n += nb;
1724 memset(dst + sz, ' ', nb);
1725 sz += nb;
1726 } else
1727 dst[sz++] = src[idx];
1728 ++idx;
1731 dst[sz] = '\0';
1732 *ptr = dst;
1733 return NULL;
1737 * Advance at most n columns from wline starting at offset off.
1738 * Return the index to the first character after the span operation.
1739 * Return the combined column width of all spanned wide character in
1740 * *rcol.
1742 static int
1743 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1745 int width, i, cols = 0;
1747 if (n == 0) {
1748 *rcol = cols;
1749 return off;
1752 for (i = off; wline[i] != L'\0'; ++i) {
1753 if (wline[i] == L'\t')
1754 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1755 else
1756 width = wcwidth(wline[i]);
1758 if (width == -1) {
1759 width = 1;
1760 wline[i] = L'.';
1763 if (cols + width > n)
1764 break;
1765 cols += width;
1768 *rcol = cols;
1769 return i;
1773 * Format a line for display, ensuring that it won't overflow a width limit.
1774 * With scrolling, the width returned refers to the scrolled version of the
1775 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1777 static const struct got_error *
1778 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1779 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1781 const struct got_error *err = NULL;
1782 int cols;
1783 wchar_t *wline = NULL;
1784 char *exstr = NULL;
1785 size_t wlen;
1786 int i, scrollx;
1788 *wlinep = NULL;
1789 *widthp = 0;
1791 if (expand) {
1792 err = expand_tab(&exstr, line);
1793 if (err)
1794 return err;
1797 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1798 free(exstr);
1799 if (err)
1800 return err;
1802 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1804 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1805 wline[wlen - 1] = L'\0';
1806 wlen--;
1808 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1809 wline[wlen - 1] = L'\0';
1810 wlen--;
1813 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1814 wline[i] = L'\0';
1816 if (widthp)
1817 *widthp = cols;
1818 if (scrollxp)
1819 *scrollxp = scrollx;
1820 if (err)
1821 free(wline);
1822 else
1823 *wlinep = wline;
1824 return err;
1827 static const struct got_error*
1828 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1829 struct got_object_id *id, struct got_repository *repo)
1831 static const struct got_error *err = NULL;
1832 struct got_reflist_entry *re;
1833 char *s;
1834 const char *name;
1836 *refs_str = NULL;
1838 TAILQ_FOREACH(re, refs, entry) {
1839 struct got_tag_object *tag = NULL;
1840 struct got_object_id *ref_id;
1841 int cmp;
1843 name = got_ref_get_name(re->ref);
1844 if (strcmp(name, GOT_REF_HEAD) == 0)
1845 continue;
1846 if (strncmp(name, "refs/", 5) == 0)
1847 name += 5;
1848 if (strncmp(name, "got/", 4) == 0 &&
1849 strncmp(name, "got/backup/", 11) != 0)
1850 continue;
1851 if (strncmp(name, "heads/", 6) == 0)
1852 name += 6;
1853 if (strncmp(name, "remotes/", 8) == 0) {
1854 name += 8;
1855 s = strstr(name, "/" GOT_REF_HEAD);
1856 if (s != NULL && s[strlen(s)] == '\0')
1857 continue;
1859 err = got_ref_resolve(&ref_id, repo, re->ref);
1860 if (err)
1861 break;
1862 if (strncmp(name, "tags/", 5) == 0) {
1863 err = got_object_open_as_tag(&tag, repo, ref_id);
1864 if (err) {
1865 if (err->code != GOT_ERR_OBJ_TYPE) {
1866 free(ref_id);
1867 break;
1869 /* Ref points at something other than a tag. */
1870 err = NULL;
1871 tag = NULL;
1874 cmp = got_object_id_cmp(tag ?
1875 got_object_tag_get_object_id(tag) : ref_id, id);
1876 free(ref_id);
1877 if (tag)
1878 got_object_tag_close(tag);
1879 if (cmp != 0)
1880 continue;
1881 s = *refs_str;
1882 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1883 s ? ", " : "", name) == -1) {
1884 err = got_error_from_errno("asprintf");
1885 free(s);
1886 *refs_str = NULL;
1887 break;
1889 free(s);
1892 return err;
1895 static const struct got_error *
1896 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1897 int col_tab_align)
1899 char *smallerthan;
1901 smallerthan = strchr(author, '<');
1902 if (smallerthan && smallerthan[1] != '\0')
1903 author = smallerthan + 1;
1904 author[strcspn(author, "@>")] = '\0';
1905 return format_line(wauthor, author_width, NULL, author, 0, limit,
1906 col_tab_align, 0);
1909 static const struct got_error *
1910 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1911 struct got_object_id *id, const size_t date_display_cols,
1912 int author_display_cols)
1914 struct tog_log_view_state *s = &view->state.log;
1915 const struct got_error *err = NULL;
1916 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1917 char *logmsg0 = NULL, *logmsg = NULL;
1918 char *author = NULL;
1919 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1920 int author_width, logmsg_width;
1921 char *newline, *line = NULL;
1922 int col, limit, scrollx;
1923 const int avail = view->ncols;
1924 struct tm tm;
1925 time_t committer_time;
1926 struct tog_color *tc;
1928 committer_time = got_object_commit_get_committer_time(commit);
1929 if (gmtime_r(&committer_time, &tm) == NULL)
1930 return got_error_from_errno("gmtime_r");
1931 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1932 return got_error(GOT_ERR_NO_SPACE);
1934 if (avail <= date_display_cols)
1935 limit = MIN(sizeof(datebuf) - 1, avail);
1936 else
1937 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1938 tc = get_color(&s->colors, TOG_COLOR_DATE);
1939 if (tc)
1940 wattr_on(view->window,
1941 COLOR_PAIR(tc->colorpair), NULL);
1942 waddnstr(view->window, datebuf, limit);
1943 if (tc)
1944 wattr_off(view->window,
1945 COLOR_PAIR(tc->colorpair), NULL);
1946 col = limit;
1947 if (col > avail)
1948 goto done;
1950 if (avail >= 120) {
1951 char *id_str;
1952 err = got_object_id_str(&id_str, id);
1953 if (err)
1954 goto done;
1955 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1956 if (tc)
1957 wattr_on(view->window,
1958 COLOR_PAIR(tc->colorpair), NULL);
1959 wprintw(view->window, "%.8s ", id_str);
1960 if (tc)
1961 wattr_off(view->window,
1962 COLOR_PAIR(tc->colorpair), NULL);
1963 free(id_str);
1964 col += 9;
1965 if (col > avail)
1966 goto done;
1969 author = strdup(got_object_commit_get_author(commit));
1970 if (author == NULL) {
1971 err = got_error_from_errno("strdup");
1972 goto done;
1974 err = format_author(&wauthor, &author_width, author, avail - col, col);
1975 if (err)
1976 goto done;
1977 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1978 if (tc)
1979 wattr_on(view->window,
1980 COLOR_PAIR(tc->colorpair), NULL);
1981 waddwstr(view->window, wauthor);
1982 if (tc)
1983 wattr_off(view->window,
1984 COLOR_PAIR(tc->colorpair), NULL);
1985 col += author_width;
1986 while (col < avail && author_width < author_display_cols + 2) {
1987 waddch(view->window, ' ');
1988 col++;
1989 author_width++;
1991 if (col > avail)
1992 goto done;
1994 err = got_object_commit_get_logmsg(&logmsg0, commit);
1995 if (err)
1996 goto done;
1997 logmsg = logmsg0;
1998 while (*logmsg == '\n')
1999 logmsg++;
2000 newline = strchr(logmsg, '\n');
2001 if (newline)
2002 *newline = '\0';
2003 limit = avail - col;
2004 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2005 limit--; /* for the border */
2006 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2007 limit, col, 1);
2008 if (err)
2009 goto done;
2010 waddwstr(view->window, &wlogmsg[scrollx]);
2011 col += MAX(logmsg_width, 0);
2012 while (col < avail) {
2013 waddch(view->window, ' ');
2014 col++;
2016 done:
2017 free(logmsg0);
2018 free(wlogmsg);
2019 free(author);
2020 free(wauthor);
2021 free(line);
2022 return err;
2025 static struct commit_queue_entry *
2026 alloc_commit_queue_entry(struct got_commit_object *commit,
2027 struct got_object_id *id)
2029 struct commit_queue_entry *entry;
2031 entry = calloc(1, sizeof(*entry));
2032 if (entry == NULL)
2033 return NULL;
2035 entry->id = id;
2036 entry->commit = commit;
2037 return entry;
2040 static void
2041 pop_commit(struct commit_queue *commits)
2043 struct commit_queue_entry *entry;
2045 entry = TAILQ_FIRST(&commits->head);
2046 TAILQ_REMOVE(&commits->head, entry, entry);
2047 got_object_commit_close(entry->commit);
2048 commits->ncommits--;
2049 /* Don't free entry->id! It is owned by the commit graph. */
2050 free(entry);
2053 static void
2054 free_commits(struct commit_queue *commits)
2056 while (!TAILQ_EMPTY(&commits->head))
2057 pop_commit(commits);
2060 static const struct got_error *
2061 match_commit(int *have_match, struct got_object_id *id,
2062 struct got_commit_object *commit, regex_t *regex)
2064 const struct got_error *err = NULL;
2065 regmatch_t regmatch;
2066 char *id_str = NULL, *logmsg = NULL;
2068 *have_match = 0;
2070 err = got_object_id_str(&id_str, id);
2071 if (err)
2072 return err;
2074 err = got_object_commit_get_logmsg(&logmsg, commit);
2075 if (err)
2076 goto done;
2078 if (regexec(regex, got_object_commit_get_author(commit), 1,
2079 &regmatch, 0) == 0 ||
2080 regexec(regex, got_object_commit_get_committer(commit), 1,
2081 &regmatch, 0) == 0 ||
2082 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2083 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2084 *have_match = 1;
2085 done:
2086 free(id_str);
2087 free(logmsg);
2088 return err;
2091 static const struct got_error *
2092 queue_commits(struct tog_log_thread_args *a)
2094 const struct got_error *err = NULL;
2097 * We keep all commits open throughout the lifetime of the log
2098 * view in order to avoid having to re-fetch commits from disk
2099 * while updating the display.
2101 do {
2102 struct got_object_id *id;
2103 struct got_commit_object *commit;
2104 struct commit_queue_entry *entry;
2105 int errcode;
2107 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2108 NULL, NULL);
2109 if (err || id == NULL)
2110 break;
2112 err = got_object_open_as_commit(&commit, a->repo, id);
2113 if (err)
2114 break;
2115 entry = alloc_commit_queue_entry(commit, id);
2116 if (entry == NULL) {
2117 err = got_error_from_errno("alloc_commit_queue_entry");
2118 break;
2121 errcode = pthread_mutex_lock(&tog_mutex);
2122 if (errcode) {
2123 err = got_error_set_errno(errcode,
2124 "pthread_mutex_lock");
2125 break;
2128 entry->idx = a->commits->ncommits;
2129 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2130 a->commits->ncommits++;
2132 if (*a->searching == TOG_SEARCH_FORWARD &&
2133 !*a->search_next_done) {
2134 int have_match;
2135 err = match_commit(&have_match, id, commit, a->regex);
2136 if (err)
2137 break;
2138 if (have_match)
2139 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2142 errcode = pthread_mutex_unlock(&tog_mutex);
2143 if (errcode && err == NULL)
2144 err = got_error_set_errno(errcode,
2145 "pthread_mutex_unlock");
2146 if (err)
2147 break;
2148 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2150 return err;
2153 static void
2154 select_commit(struct tog_log_view_state *s)
2156 struct commit_queue_entry *entry;
2157 int ncommits = 0;
2159 entry = s->first_displayed_entry;
2160 while (entry) {
2161 if (ncommits == s->selected) {
2162 s->selected_entry = entry;
2163 break;
2165 entry = TAILQ_NEXT(entry, entry);
2166 ncommits++;
2170 static const struct got_error *
2171 draw_commits(struct tog_view *view)
2173 const struct got_error *err = NULL;
2174 struct tog_log_view_state *s = &view->state.log;
2175 struct commit_queue_entry *entry = s->selected_entry;
2176 const int limit = view->nlines;
2177 int width;
2178 int ncommits, author_cols = 4;
2179 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2180 char *refs_str = NULL;
2181 wchar_t *wline;
2182 struct tog_color *tc;
2183 static const size_t date_display_cols = 12;
2185 if (s->selected_entry &&
2186 !(view->searching && view->search_next_done == 0)) {
2187 struct got_reflist_head *refs;
2188 err = got_object_id_str(&id_str, s->selected_entry->id);
2189 if (err)
2190 return err;
2191 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2192 s->selected_entry->id);
2193 if (refs) {
2194 err = build_refs_str(&refs_str, refs,
2195 s->selected_entry->id, s->repo);
2196 if (err)
2197 goto done;
2201 if (s->thread_args.commits_needed == 0)
2202 halfdelay(10); /* disable fast refresh */
2204 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2205 if (asprintf(&ncommits_str, " [%d/%d] %s",
2206 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2207 (view->searching && !view->search_next_done) ?
2208 "searching..." : "loading...") == -1) {
2209 err = got_error_from_errno("asprintf");
2210 goto done;
2212 } else {
2213 const char *search_str = NULL;
2215 if (view->searching) {
2216 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2217 search_str = "no more matches";
2218 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2219 search_str = "no matches found";
2220 else if (!view->search_next_done)
2221 search_str = "searching...";
2224 if (asprintf(&ncommits_str, " [%d/%d] %s",
2225 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2226 search_str ? search_str :
2227 (refs_str ? refs_str : "")) == -1) {
2228 err = got_error_from_errno("asprintf");
2229 goto done;
2233 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2234 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2235 "........................................",
2236 s->in_repo_path, ncommits_str) == -1) {
2237 err = got_error_from_errno("asprintf");
2238 header = NULL;
2239 goto done;
2241 } else if (asprintf(&header, "commit %s%s",
2242 id_str ? id_str : "........................................",
2243 ncommits_str) == -1) {
2244 err = got_error_from_errno("asprintf");
2245 header = NULL;
2246 goto done;
2248 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2249 if (err)
2250 goto done;
2252 werase(view->window);
2254 if (view_needs_focus_indication(view))
2255 wstandout(view->window);
2256 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2257 if (tc)
2258 wattr_on(view->window,
2259 COLOR_PAIR(tc->colorpair), NULL);
2260 waddwstr(view->window, wline);
2261 if (tc)
2262 wattr_off(view->window,
2263 COLOR_PAIR(tc->colorpair), NULL);
2264 while (width < view->ncols) {
2265 waddch(view->window, ' ');
2266 width++;
2268 if (view_needs_focus_indication(view))
2269 wstandend(view->window);
2270 free(wline);
2271 if (limit <= 1)
2272 goto done;
2274 /* Grow author column size if necessary, and set view->maxx. */
2275 entry = s->first_displayed_entry;
2276 ncommits = 0;
2277 view->maxx = 0;
2278 while (entry) {
2279 char *author, *eol, *msg, *msg0;
2280 wchar_t *wauthor, *wmsg;
2281 int width;
2282 if (ncommits >= limit - 1)
2283 break;
2284 author = strdup(got_object_commit_get_author(entry->commit));
2285 if (author == NULL) {
2286 err = got_error_from_errno("strdup");
2287 goto done;
2289 err = format_author(&wauthor, &width, author, COLS,
2290 date_display_cols);
2291 if (author_cols < width)
2292 author_cols = width;
2293 free(wauthor);
2294 free(author);
2295 err = got_object_commit_get_logmsg(&msg0, entry->commit);
2296 if (err)
2297 goto done;
2298 msg = msg0;
2299 while (*msg == '\n')
2300 ++msg;
2301 if ((eol = strchr(msg, '\n')))
2302 *eol = '\0';
2303 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2304 date_display_cols + author_cols, 0);
2305 if (err)
2306 goto done;
2307 view->maxx = MAX(view->maxx, width);
2308 free(msg0);
2309 free(wmsg);
2310 ncommits++;
2311 entry = TAILQ_NEXT(entry, entry);
2314 entry = s->first_displayed_entry;
2315 s->last_displayed_entry = s->first_displayed_entry;
2316 ncommits = 0;
2317 while (entry) {
2318 if (ncommits >= limit - 1)
2319 break;
2320 if (ncommits == s->selected)
2321 wstandout(view->window);
2322 err = draw_commit(view, entry->commit, entry->id,
2323 date_display_cols, author_cols);
2324 if (ncommits == s->selected)
2325 wstandend(view->window);
2326 if (err)
2327 goto done;
2328 ncommits++;
2329 s->last_displayed_entry = entry;
2330 entry = TAILQ_NEXT(entry, entry);
2333 view_border(view);
2334 done:
2335 free(id_str);
2336 free(refs_str);
2337 free(ncommits_str);
2338 free(header);
2339 return err;
2342 static void
2343 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2345 struct commit_queue_entry *entry;
2346 int nscrolled = 0;
2348 entry = TAILQ_FIRST(&s->commits.head);
2349 if (s->first_displayed_entry == entry)
2350 return;
2352 entry = s->first_displayed_entry;
2353 while (entry && nscrolled < maxscroll) {
2354 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2355 if (entry) {
2356 s->first_displayed_entry = entry;
2357 nscrolled++;
2362 static const struct got_error *
2363 trigger_log_thread(struct tog_view *view, int wait)
2365 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2366 int errcode;
2368 halfdelay(1); /* fast refresh while loading commits */
2370 while (!ta->log_complete && !tog_thread_error &&
2371 (ta->commits_needed > 0 || ta->load_all)) {
2372 /* Wake the log thread. */
2373 errcode = pthread_cond_signal(&ta->need_commits);
2374 if (errcode)
2375 return got_error_set_errno(errcode,
2376 "pthread_cond_signal");
2379 * The mutex will be released while the view loop waits
2380 * in wgetch(), at which time the log thread will run.
2382 if (!wait)
2383 break;
2385 /* Display progress update in log view. */
2386 show_log_view(view);
2387 update_panels();
2388 doupdate();
2390 /* Wait right here while next commit is being loaded. */
2391 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2392 if (errcode)
2393 return got_error_set_errno(errcode,
2394 "pthread_cond_wait");
2396 /* Display progress update in log view. */
2397 show_log_view(view);
2398 update_panels();
2399 doupdate();
2402 return NULL;
2405 static const struct got_error *
2406 request_log_commits(struct tog_view *view)
2408 struct tog_log_view_state *state = &view->state.log;
2409 const struct got_error *err = NULL;
2411 if (state->thread_args.log_complete)
2412 return NULL;
2414 state->thread_args.commits_needed += view->nscrolled;
2415 err = trigger_log_thread(view, 1);
2416 view->nscrolled = 0;
2418 return err;
2421 static const struct got_error *
2422 log_scroll_down(struct tog_view *view, int maxscroll)
2424 struct tog_log_view_state *s = &view->state.log;
2425 const struct got_error *err = NULL;
2426 struct commit_queue_entry *pentry;
2427 int nscrolled = 0, ncommits_needed;
2429 if (s->last_displayed_entry == NULL)
2430 return NULL;
2432 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2433 if (s->commits.ncommits < ncommits_needed &&
2434 !s->thread_args.log_complete) {
2436 * Ask the log thread for required amount of commits.
2438 s->thread_args.commits_needed += maxscroll;
2439 err = trigger_log_thread(view, 1);
2440 if (err)
2441 return err;
2444 do {
2445 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2446 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2447 break;
2449 s->last_displayed_entry = pentry ?
2450 pentry : s->last_displayed_entry;;
2452 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2453 if (pentry == NULL)
2454 break;
2455 s->first_displayed_entry = pentry;
2456 } while (++nscrolled < maxscroll);
2458 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2459 view->nscrolled += nscrolled;
2460 else
2461 view->nscrolled = 0;
2463 return err;
2466 static const struct got_error *
2467 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2468 struct got_commit_object *commit, struct got_object_id *commit_id,
2469 struct tog_view *log_view, struct got_repository *repo)
2471 const struct got_error *err;
2472 struct got_object_qid *parent_id;
2473 struct tog_view *diff_view;
2475 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2476 if (diff_view == NULL)
2477 return got_error_from_errno("view_open");
2479 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2480 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2481 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2482 if (err == NULL)
2483 *new_view = diff_view;
2484 return err;
2487 static const struct got_error *
2488 tree_view_visit_subtree(struct tog_tree_view_state *s,
2489 struct got_tree_object *subtree)
2491 struct tog_parent_tree *parent;
2493 parent = calloc(1, sizeof(*parent));
2494 if (parent == NULL)
2495 return got_error_from_errno("calloc");
2497 parent->tree = s->tree;
2498 parent->first_displayed_entry = s->first_displayed_entry;
2499 parent->selected_entry = s->selected_entry;
2500 parent->selected = s->selected;
2501 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2502 s->tree = subtree;
2503 s->selected = 0;
2504 s->first_displayed_entry = NULL;
2505 return NULL;
2508 static const struct got_error *
2509 tree_view_walk_path(struct tog_tree_view_state *s,
2510 struct got_commit_object *commit, const char *path)
2512 const struct got_error *err = NULL;
2513 struct got_tree_object *tree = NULL;
2514 const char *p;
2515 char *slash, *subpath = NULL;
2517 /* Walk the path and open corresponding tree objects. */
2518 p = path;
2519 while (*p) {
2520 struct got_tree_entry *te;
2521 struct got_object_id *tree_id;
2522 char *te_name;
2524 while (p[0] == '/')
2525 p++;
2527 /* Ensure the correct subtree entry is selected. */
2528 slash = strchr(p, '/');
2529 if (slash == NULL)
2530 te_name = strdup(p);
2531 else
2532 te_name = strndup(p, slash - p);
2533 if (te_name == NULL) {
2534 err = got_error_from_errno("strndup");
2535 break;
2537 te = got_object_tree_find_entry(s->tree, te_name);
2538 if (te == NULL) {
2539 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2540 free(te_name);
2541 break;
2543 free(te_name);
2544 s->first_displayed_entry = s->selected_entry = te;
2546 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2547 break; /* jump to this file's entry */
2549 slash = strchr(p, '/');
2550 if (slash)
2551 subpath = strndup(path, slash - path);
2552 else
2553 subpath = strdup(path);
2554 if (subpath == NULL) {
2555 err = got_error_from_errno("strdup");
2556 break;
2559 err = got_object_id_by_path(&tree_id, s->repo, commit,
2560 subpath);
2561 if (err)
2562 break;
2564 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2565 free(tree_id);
2566 if (err)
2567 break;
2569 err = tree_view_visit_subtree(s, tree);
2570 if (err) {
2571 got_object_tree_close(tree);
2572 break;
2574 if (slash == NULL)
2575 break;
2576 free(subpath);
2577 subpath = NULL;
2578 p = slash;
2581 free(subpath);
2582 return err;
2585 static const struct got_error *
2586 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2587 struct commit_queue_entry *entry, const char *path,
2588 const char *head_ref_name, struct got_repository *repo)
2590 const struct got_error *err = NULL;
2591 struct tog_tree_view_state *s;
2592 struct tog_view *tree_view;
2594 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2595 if (tree_view == NULL)
2596 return got_error_from_errno("view_open");
2598 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2599 if (err)
2600 return err;
2601 s = &tree_view->state.tree;
2603 *new_view = tree_view;
2605 if (got_path_is_root_dir(path))
2606 return NULL;
2608 return tree_view_walk_path(s, entry->commit, path);
2611 static const struct got_error *
2612 block_signals_used_by_main_thread(void)
2614 sigset_t sigset;
2615 int errcode;
2617 if (sigemptyset(&sigset) == -1)
2618 return got_error_from_errno("sigemptyset");
2620 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2621 if (sigaddset(&sigset, SIGWINCH) == -1)
2622 return got_error_from_errno("sigaddset");
2623 if (sigaddset(&sigset, SIGCONT) == -1)
2624 return got_error_from_errno("sigaddset");
2625 if (sigaddset(&sigset, SIGINT) == -1)
2626 return got_error_from_errno("sigaddset");
2627 if (sigaddset(&sigset, SIGTERM) == -1)
2628 return got_error_from_errno("sigaddset");
2630 /* ncurses handles SIGTSTP */
2631 if (sigaddset(&sigset, SIGTSTP) == -1)
2632 return got_error_from_errno("sigaddset");
2634 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2635 if (errcode)
2636 return got_error_set_errno(errcode, "pthread_sigmask");
2638 return NULL;
2641 static void *
2642 log_thread(void *arg)
2644 const struct got_error *err = NULL;
2645 int errcode = 0;
2646 struct tog_log_thread_args *a = arg;
2647 int done = 0;
2650 * Sync startup with main thread such that we begin our
2651 * work once view_input() has released the mutex.
2653 errcode = pthread_mutex_lock(&tog_mutex);
2654 if (errcode) {
2655 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2656 return (void *)err;
2659 err = block_signals_used_by_main_thread();
2660 if (err) {
2661 pthread_mutex_unlock(&tog_mutex);
2662 goto done;
2665 while (!done && !err && !tog_fatal_signal_received()) {
2666 errcode = pthread_mutex_unlock(&tog_mutex);
2667 if (errcode) {
2668 err = got_error_set_errno(errcode,
2669 "pthread_mutex_unlock");
2670 goto done;
2672 err = queue_commits(a);
2673 if (err) {
2674 if (err->code != GOT_ERR_ITER_COMPLETED)
2675 goto done;
2676 err = NULL;
2677 done = 1;
2678 } else if (a->commits_needed > 0 && !a->load_all)
2679 a->commits_needed--;
2681 errcode = pthread_mutex_lock(&tog_mutex);
2682 if (errcode) {
2683 err = got_error_set_errno(errcode,
2684 "pthread_mutex_lock");
2685 goto done;
2686 } else if (*a->quit)
2687 done = 1;
2688 else if (*a->first_displayed_entry == NULL) {
2689 *a->first_displayed_entry =
2690 TAILQ_FIRST(&a->commits->head);
2691 *a->selected_entry = *a->first_displayed_entry;
2694 errcode = pthread_cond_signal(&a->commit_loaded);
2695 if (errcode) {
2696 err = got_error_set_errno(errcode,
2697 "pthread_cond_signal");
2698 pthread_mutex_unlock(&tog_mutex);
2699 goto done;
2702 if (done)
2703 a->commits_needed = 0;
2704 else {
2705 if (a->commits_needed == 0 && !a->load_all) {
2706 errcode = pthread_cond_wait(&a->need_commits,
2707 &tog_mutex);
2708 if (errcode) {
2709 err = got_error_set_errno(errcode,
2710 "pthread_cond_wait");
2711 pthread_mutex_unlock(&tog_mutex);
2712 goto done;
2714 if (*a->quit)
2715 done = 1;
2719 a->log_complete = 1;
2720 errcode = pthread_mutex_unlock(&tog_mutex);
2721 if (errcode)
2722 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2723 done:
2724 if (err) {
2725 tog_thread_error = 1;
2726 pthread_cond_signal(&a->commit_loaded);
2728 return (void *)err;
2731 static const struct got_error *
2732 stop_log_thread(struct tog_log_view_state *s)
2734 const struct got_error *err = NULL, *thread_err = NULL;
2735 int errcode;
2737 if (s->thread) {
2738 s->quit = 1;
2739 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2740 if (errcode)
2741 return got_error_set_errno(errcode,
2742 "pthread_cond_signal");
2743 errcode = pthread_mutex_unlock(&tog_mutex);
2744 if (errcode)
2745 return got_error_set_errno(errcode,
2746 "pthread_mutex_unlock");
2747 errcode = pthread_join(s->thread, (void **)&thread_err);
2748 if (errcode)
2749 return got_error_set_errno(errcode, "pthread_join");
2750 errcode = pthread_mutex_lock(&tog_mutex);
2751 if (errcode)
2752 return got_error_set_errno(errcode,
2753 "pthread_mutex_lock");
2754 s->thread = 0; //NULL;
2757 if (s->thread_args.repo) {
2758 err = got_repo_close(s->thread_args.repo);
2759 s->thread_args.repo = NULL;
2762 if (s->thread_args.pack_fds) {
2763 const struct got_error *pack_err =
2764 got_repo_pack_fds_close(s->thread_args.pack_fds);
2765 if (err == NULL)
2766 err = pack_err;
2767 s->thread_args.pack_fds = NULL;
2770 if (s->thread_args.graph) {
2771 got_commit_graph_close(s->thread_args.graph);
2772 s->thread_args.graph = NULL;
2775 return err ? err : thread_err;
2778 static const struct got_error *
2779 close_log_view(struct tog_view *view)
2781 const struct got_error *err = NULL;
2782 struct tog_log_view_state *s = &view->state.log;
2783 int errcode;
2785 err = stop_log_thread(s);
2787 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2788 if (errcode && err == NULL)
2789 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2791 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2792 if (errcode && err == NULL)
2793 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2795 free_commits(&s->commits);
2796 free(s->in_repo_path);
2797 s->in_repo_path = NULL;
2798 free(s->start_id);
2799 s->start_id = NULL;
2800 free(s->head_ref_name);
2801 s->head_ref_name = NULL;
2802 return err;
2805 static const struct got_error *
2806 search_start_log_view(struct tog_view *view)
2808 struct tog_log_view_state *s = &view->state.log;
2810 s->matched_entry = NULL;
2811 s->search_entry = NULL;
2812 return NULL;
2815 static const struct got_error *
2816 search_next_log_view(struct tog_view *view)
2818 const struct got_error *err = NULL;
2819 struct tog_log_view_state *s = &view->state.log;
2820 struct commit_queue_entry *entry;
2822 /* Display progress update in log view. */
2823 show_log_view(view);
2824 update_panels();
2825 doupdate();
2827 if (s->search_entry) {
2828 int errcode, ch;
2829 errcode = pthread_mutex_unlock(&tog_mutex);
2830 if (errcode)
2831 return got_error_set_errno(errcode,
2832 "pthread_mutex_unlock");
2833 ch = wgetch(view->window);
2834 errcode = pthread_mutex_lock(&tog_mutex);
2835 if (errcode)
2836 return got_error_set_errno(errcode,
2837 "pthread_mutex_lock");
2838 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2839 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2840 return NULL;
2842 if (view->searching == TOG_SEARCH_FORWARD)
2843 entry = TAILQ_NEXT(s->search_entry, entry);
2844 else
2845 entry = TAILQ_PREV(s->search_entry,
2846 commit_queue_head, entry);
2847 } else if (s->matched_entry) {
2848 int matched_idx = s->matched_entry->idx;
2849 int selected_idx = s->selected_entry->idx;
2852 * If the user has moved the cursor after we hit a match,
2853 * the position from where we should continue searching
2854 * might have changed.
2856 if (view->searching == TOG_SEARCH_FORWARD) {
2857 if (matched_idx > selected_idx)
2858 entry = TAILQ_NEXT(s->selected_entry, entry);
2859 else
2860 entry = TAILQ_NEXT(s->matched_entry, entry);
2861 } else {
2862 if (matched_idx < selected_idx)
2863 entry = TAILQ_PREV(s->selected_entry,
2864 commit_queue_head, entry);
2865 else
2866 entry = TAILQ_PREV(s->matched_entry,
2867 commit_queue_head, entry);
2869 } else {
2870 entry = s->selected_entry;
2873 while (1) {
2874 int have_match = 0;
2876 if (entry == NULL) {
2877 if (s->thread_args.log_complete ||
2878 view->searching == TOG_SEARCH_BACKWARD) {
2879 view->search_next_done =
2880 (s->matched_entry == NULL ?
2881 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2882 s->search_entry = NULL;
2883 return NULL;
2886 * Poke the log thread for more commits and return,
2887 * allowing the main loop to make progress. Search
2888 * will resume at s->search_entry once we come back.
2890 s->thread_args.commits_needed++;
2891 return trigger_log_thread(view, 0);
2894 err = match_commit(&have_match, entry->id, entry->commit,
2895 &view->regex);
2896 if (err)
2897 break;
2898 if (have_match) {
2899 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2900 s->matched_entry = entry;
2901 break;
2904 s->search_entry = entry;
2905 if (view->searching == TOG_SEARCH_FORWARD)
2906 entry = TAILQ_NEXT(entry, entry);
2907 else
2908 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2911 if (s->matched_entry) {
2912 int cur = s->selected_entry->idx;
2913 while (cur < s->matched_entry->idx) {
2914 err = input_log_view(NULL, view, KEY_DOWN);
2915 if (err)
2916 return err;
2917 cur++;
2919 while (cur > s->matched_entry->idx) {
2920 err = input_log_view(NULL, view, KEY_UP);
2921 if (err)
2922 return err;
2923 cur--;
2927 s->search_entry = NULL;
2929 return NULL;
2932 static const struct got_error *
2933 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2934 struct got_repository *repo, const char *head_ref_name,
2935 const char *in_repo_path, int log_branches)
2937 const struct got_error *err = NULL;
2938 struct tog_log_view_state *s = &view->state.log;
2939 struct got_repository *thread_repo = NULL;
2940 struct got_commit_graph *thread_graph = NULL;
2941 int errcode;
2943 if (in_repo_path != s->in_repo_path) {
2944 free(s->in_repo_path);
2945 s->in_repo_path = strdup(in_repo_path);
2946 if (s->in_repo_path == NULL)
2947 return got_error_from_errno("strdup");
2950 /* The commit queue only contains commits being displayed. */
2951 TAILQ_INIT(&s->commits.head);
2952 s->commits.ncommits = 0;
2954 s->repo = repo;
2955 if (head_ref_name) {
2956 s->head_ref_name = strdup(head_ref_name);
2957 if (s->head_ref_name == NULL) {
2958 err = got_error_from_errno("strdup");
2959 goto done;
2962 s->start_id = got_object_id_dup(start_id);
2963 if (s->start_id == NULL) {
2964 err = got_error_from_errno("got_object_id_dup");
2965 goto done;
2967 s->log_branches = log_branches;
2969 STAILQ_INIT(&s->colors);
2970 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2971 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2972 get_color_value("TOG_COLOR_COMMIT"));
2973 if (err)
2974 goto done;
2975 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2976 get_color_value("TOG_COLOR_AUTHOR"));
2977 if (err) {
2978 free_colors(&s->colors);
2979 goto done;
2981 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2982 get_color_value("TOG_COLOR_DATE"));
2983 if (err) {
2984 free_colors(&s->colors);
2985 goto done;
2989 view->show = show_log_view;
2990 view->input = input_log_view;
2991 view->close = close_log_view;
2992 view->search_start = search_start_log_view;
2993 view->search_next = search_next_log_view;
2995 if (s->thread_args.pack_fds == NULL) {
2996 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2997 if (err)
2998 goto done;
3000 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3001 s->thread_args.pack_fds);
3002 if (err)
3003 goto done;
3004 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3005 !s->log_branches);
3006 if (err)
3007 goto done;
3008 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3009 s->repo, NULL, NULL);
3010 if (err)
3011 goto done;
3013 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3014 if (errcode) {
3015 err = got_error_set_errno(errcode, "pthread_cond_init");
3016 goto done;
3018 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3019 if (errcode) {
3020 err = got_error_set_errno(errcode, "pthread_cond_init");
3021 goto done;
3024 s->thread_args.commits_needed = view->nlines;
3025 s->thread_args.graph = thread_graph;
3026 s->thread_args.commits = &s->commits;
3027 s->thread_args.in_repo_path = s->in_repo_path;
3028 s->thread_args.start_id = s->start_id;
3029 s->thread_args.repo = thread_repo;
3030 s->thread_args.log_complete = 0;
3031 s->thread_args.quit = &s->quit;
3032 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3033 s->thread_args.selected_entry = &s->selected_entry;
3034 s->thread_args.searching = &view->searching;
3035 s->thread_args.search_next_done = &view->search_next_done;
3036 s->thread_args.regex = &view->regex;
3037 done:
3038 if (err)
3039 close_log_view(view);
3040 return err;
3043 static const struct got_error *
3044 show_log_view(struct tog_view *view)
3046 const struct got_error *err;
3047 struct tog_log_view_state *s = &view->state.log;
3049 if (s->thread == 0) { //NULL) {
3050 int errcode = pthread_create(&s->thread, NULL, log_thread,
3051 &s->thread_args);
3052 if (errcode)
3053 return got_error_set_errno(errcode, "pthread_create");
3054 if (s->thread_args.commits_needed > 0) {
3055 err = trigger_log_thread(view, 1);
3056 if (err)
3057 return err;
3061 return draw_commits(view);
3064 static void
3065 log_move_cursor_up(struct tog_view *view, int page, int home)
3067 struct tog_log_view_state *s = &view->state.log;
3069 if (s->selected_entry->idx == 0)
3070 view->count = 0;
3071 if (s->first_displayed_entry == NULL)
3072 return;
3074 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3075 || home)
3076 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3078 if (!page && !home && s->selected > 0)
3079 --s->selected;
3080 else
3081 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3083 select_commit(s);
3084 return;
3087 static const struct got_error *
3088 log_move_cursor_down(struct tog_view *view, int page)
3090 struct tog_log_view_state *s = &view->state.log;
3091 struct commit_queue_entry *first;
3092 const struct got_error *err = NULL;
3094 first = s->first_displayed_entry;
3095 if (first == NULL) {
3096 view->count = 0;
3097 return NULL;
3100 if (s->thread_args.log_complete &&
3101 s->selected_entry->idx >= s->commits.ncommits - 1)
3102 return NULL;
3104 if (!page) {
3105 int eos = view->nlines - 2;
3107 if (view_is_hsplit_top(view))
3108 --eos; /* border consumes the last line */
3109 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3110 ++s->selected;
3111 else
3112 err = log_scroll_down(view, 1);
3113 } else if (s->thread_args.load_all) {
3114 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3115 s->selected += MIN(s->last_displayed_entry->idx -
3116 s->selected_entry->idx, page + 1);
3117 else
3118 err = log_scroll_down(view, MIN(page,
3119 s->commits.ncommits - s->selected_entry->idx - 1));
3120 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3121 } else {
3122 err = log_scroll_down(view, page);
3123 if (err)
3124 return err;
3125 if (first == s->first_displayed_entry && s->selected <
3126 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
3127 s->selected = MIN(s->commits.ncommits - 1, page);
3130 if (err)
3131 return err;
3134 * We might necessarily overshoot in horizontal
3135 * splits; if so, select the last displayed commit.
3137 s->selected = MIN(s->selected,
3138 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3140 select_commit(s);
3142 if (s->thread_args.log_complete &&
3143 s->selected_entry->idx == s->commits.ncommits - 1)
3144 view->count = 0;
3146 return NULL;
3149 static void
3150 view_get_split(struct tog_view *view, int *y, int *x)
3152 *x = 0;
3153 *y = 0;
3155 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3156 if (view->child && view->child->resized_y)
3157 *y = view->child->resized_y;
3158 else if (view->resized_y)
3159 *y = view->resized_y;
3160 else
3161 *y = view_split_begin_y(view->lines);
3162 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3163 if (view->child && view->child->resized_x)
3164 *x = view->child->resized_x;
3165 else if (view->resized_x)
3166 *x = view->resized_x;
3167 else
3168 *x = view_split_begin_x(view->begin_x);
3172 /* Split view horizontally at y and offset view->state->selected line. */
3173 static const struct got_error *
3174 view_init_hsplit(struct tog_view *view, int y)
3176 const struct got_error *err = NULL;
3178 view->nlines = y;
3179 view->ncols = COLS;
3180 err = view_resize(view);
3181 if (err)
3182 return err;
3184 err = offset_selection_down(view);
3186 return err;
3189 static const struct got_error *
3190 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3192 const struct got_error *err = NULL;
3193 struct tog_log_view_state *s = &view->state.log;
3194 struct tog_view *diff_view = NULL, *tree_view = NULL;
3195 struct tog_view *ref_view = NULL;
3196 struct commit_queue_entry *entry;
3197 int begin_x = 0, begin_y = 0, eos, n, nscroll;
3199 if (s->thread_args.load_all) {
3200 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3201 s->thread_args.load_all = 0;
3202 else if (s->thread_args.log_complete) {
3203 err = log_move_cursor_down(view, s->commits.ncommits);
3204 s->thread_args.load_all = 0;
3206 return err;
3209 eos = nscroll = view->nlines - 1;
3210 if (view_is_hsplit_top(view))
3211 --eos; /* border */
3213 switch (ch) {
3214 case 'q':
3215 s->quit = 1;
3216 break;
3217 case '0':
3218 view->x = 0;
3219 break;
3220 case '$':
3221 view->x = MAX(view->maxx - view->ncols / 2, 0);
3222 view->count = 0;
3223 break;
3224 case KEY_RIGHT:
3225 case 'l':
3226 if (view->x + view->ncols / 2 < view->maxx)
3227 view->x += 2; /* move two columns right */
3228 else
3229 view->count = 0;
3230 break;
3231 case KEY_LEFT:
3232 case 'h':
3233 view->x -= MIN(view->x, 2); /* move two columns back */
3234 if (view->x <= 0)
3235 view->count = 0;
3236 break;
3237 case 'k':
3238 case KEY_UP:
3239 case '<':
3240 case ',':
3241 case CTRL('p'):
3242 log_move_cursor_up(view, 0, 0);
3243 break;
3244 case 'g':
3245 case KEY_HOME:
3246 log_move_cursor_up(view, 0, 1);
3247 view->count = 0;
3248 break;
3249 case CTRL('u'):
3250 case 'u':
3251 nscroll /= 2;
3252 /* FALL THROUGH */
3253 case KEY_PPAGE:
3254 case CTRL('b'):
3255 case 'b':
3256 log_move_cursor_up(view, nscroll, 0);
3257 break;
3258 case 'j':
3259 case KEY_DOWN:
3260 case '>':
3261 case '.':
3262 case CTRL('n'):
3263 err = log_move_cursor_down(view, 0);
3264 break;
3265 case 'G':
3266 case KEY_END: {
3267 /* We don't know yet how many commits, so we're forced to
3268 * traverse them all. */
3269 view->count = 0;
3270 if (!s->thread_args.log_complete) {
3271 s->thread_args.load_all = 1;
3272 return trigger_log_thread(view, 0);
3275 s->selected = 0;
3276 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3277 for (n = 0; n < eos; n++) {
3278 if (entry == NULL)
3279 break;
3280 s->first_displayed_entry = entry;
3281 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3283 if (n > 0)
3284 s->selected = n - 1;
3285 select_commit(s);
3286 break;
3288 case CTRL('d'):
3289 case 'd':
3290 nscroll /= 2;
3291 /* FALL THROUGH */
3292 case KEY_NPAGE:
3293 case CTRL('f'):
3294 case 'f':
3295 case ' ':
3296 err = log_move_cursor_down(view, nscroll);
3297 break;
3298 case KEY_RESIZE:
3299 if (s->selected > view->nlines - 2)
3300 s->selected = view->nlines - 2;
3301 if (s->selected > s->commits.ncommits - 1)
3302 s->selected = s->commits.ncommits - 1;
3303 select_commit(s);
3304 if (s->commits.ncommits < view->nlines - 1 &&
3305 !s->thread_args.log_complete) {
3306 s->thread_args.commits_needed += (view->nlines - 1) -
3307 s->commits.ncommits;
3308 err = trigger_log_thread(view, 1);
3310 break;
3311 case KEY_ENTER:
3312 case '\r':
3313 view->count = 0;
3314 if (s->selected_entry == NULL)
3315 break;
3317 /* get dimensions--don't split till initialisation succeeds */
3318 if (view_is_parent_view(view))
3319 view_get_split(view, &begin_y, &begin_x);
3321 err = open_diff_view_for_commit(&diff_view, begin_y, begin_x,
3322 s->selected_entry->commit, s->selected_entry->id,
3323 view, s->repo);
3324 if (err)
3325 break;
3327 if (view_is_parent_view(view) &&
3328 view->mode == TOG_VIEW_SPLIT_HRZN) { /* safe to split */
3329 err = view_init_hsplit(view, begin_y);
3330 if (err)
3331 break;
3334 view->focussed = 0;
3335 diff_view->focussed = 1;
3336 diff_view->mode = view->mode;
3337 diff_view->nlines = view->lines - begin_y;
3339 if (view_is_parent_view(view)) {
3340 view_transfer_size(diff_view, view);
3341 err = view_close_child(view);
3342 if (err)
3343 return err;
3344 err = view_set_child(view, diff_view);
3345 if (err)
3346 return err;
3347 view->focus_child = 1;
3348 } else
3349 *new_view = diff_view;
3350 break;
3351 case 't':
3352 view->count = 0;
3353 if (s->selected_entry == NULL)
3354 break;
3355 if (view_is_parent_view(view))
3356 view_get_split(view, &begin_y, &begin_x);
3357 err = browse_commit_tree(&tree_view, begin_y, begin_x,
3358 s->selected_entry, s->in_repo_path, s->head_ref_name,
3359 s->repo);
3360 if (err)
3361 break;
3362 if (view_is_parent_view(view) &&
3363 view->mode == TOG_VIEW_SPLIT_HRZN) {
3364 err = view_init_hsplit(view, begin_y);
3365 if (err)
3366 break;
3368 view->focussed = 0;
3369 tree_view->focussed = 1;
3370 tree_view->mode = view->mode;
3371 tree_view->nlines = view->lines - begin_y;
3372 if (view_is_parent_view(view)) {
3373 view_transfer_size(tree_view, view);
3374 err = view_close_child(view);
3375 if (err)
3376 return err;
3377 err = view_set_child(view, tree_view);
3378 if (err)
3379 return err;
3380 view->focus_child = 1;
3381 } else
3382 *new_view = tree_view;
3383 break;
3384 case KEY_BACKSPACE:
3385 case CTRL('l'):
3386 case 'B':
3387 view->count = 0;
3388 if (ch == KEY_BACKSPACE &&
3389 got_path_is_root_dir(s->in_repo_path))
3390 break;
3391 err = stop_log_thread(s);
3392 if (err)
3393 return err;
3394 if (ch == KEY_BACKSPACE) {
3395 char *parent_path;
3396 err = got_path_dirname(&parent_path, s->in_repo_path);
3397 if (err)
3398 return err;
3399 free(s->in_repo_path);
3400 s->in_repo_path = parent_path;
3401 s->thread_args.in_repo_path = s->in_repo_path;
3402 } else if (ch == CTRL('l')) {
3403 struct got_object_id *start_id;
3404 err = got_repo_match_object_id(&start_id, NULL,
3405 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3406 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3407 if (err)
3408 return err;
3409 free(s->start_id);
3410 s->start_id = start_id;
3411 s->thread_args.start_id = s->start_id;
3412 } else /* 'B' */
3413 s->log_branches = !s->log_branches;
3415 if (s->thread_args.pack_fds == NULL) {
3416 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3417 if (err)
3418 return err;
3420 err = got_repo_open(&s->thread_args.repo,
3421 got_repo_get_path(s->repo), NULL,
3422 s->thread_args.pack_fds);
3423 if (err)
3424 return err;
3425 tog_free_refs();
3426 err = tog_load_refs(s->repo, 0);
3427 if (err)
3428 return err;
3429 err = got_commit_graph_open(&s->thread_args.graph,
3430 s->in_repo_path, !s->log_branches);
3431 if (err)
3432 return err;
3433 err = got_commit_graph_iter_start(s->thread_args.graph,
3434 s->start_id, s->repo, NULL, NULL);
3435 if (err)
3436 return err;
3437 free_commits(&s->commits);
3438 s->first_displayed_entry = NULL;
3439 s->last_displayed_entry = NULL;
3440 s->selected_entry = NULL;
3441 s->selected = 0;
3442 s->thread_args.log_complete = 0;
3443 s->quit = 0;
3444 s->thread_args.commits_needed = view->lines;
3445 s->matched_entry = NULL;
3446 s->search_entry = NULL;
3447 break;
3448 case 'r':
3449 view->count = 0;
3450 if (view_is_parent_view(view))
3451 view_get_split(view, &begin_y, &begin_x);
3452 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
3453 if (ref_view == NULL)
3454 return got_error_from_errno("view_open");
3455 err = open_ref_view(ref_view, s->repo);
3456 if (err) {
3457 view_close(ref_view);
3458 return err;
3460 if (view_is_parent_view(view) &&
3461 view->mode == TOG_VIEW_SPLIT_HRZN) {
3462 err = view_init_hsplit(view, begin_y);
3463 if (err)
3464 break;
3466 view->focussed = 0;
3467 ref_view->focussed = 1;
3468 ref_view->mode = view->mode;
3469 ref_view->nlines = view->lines - begin_y;
3470 if (view_is_parent_view(view)) {
3471 view_transfer_size(ref_view, view);
3472 err = view_close_child(view);
3473 if (err)
3474 return err;
3475 err = view_set_child(view, ref_view);
3476 if (err)
3477 return err;
3478 view->focus_child = 1;
3479 } else
3480 *new_view = ref_view;
3481 break;
3482 default:
3483 view->count = 0;
3484 break;
3487 return err;
3490 static const struct got_error *
3491 apply_unveil(const char *repo_path, const char *worktree_path)
3493 const struct got_error *error;
3495 #ifdef PROFILE
3496 if (unveil("gmon.out", "rwc") != 0)
3497 return got_error_from_errno2("unveil", "gmon.out");
3498 #endif
3499 if (repo_path && unveil(repo_path, "r") != 0)
3500 return got_error_from_errno2("unveil", repo_path);
3502 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3503 return got_error_from_errno2("unveil", worktree_path);
3505 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3506 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3508 error = got_privsep_unveil_exec_helpers();
3509 if (error != NULL)
3510 return error;
3512 if (unveil(NULL, NULL) != 0)
3513 return got_error_from_errno("unveil");
3515 return NULL;
3518 static void
3519 init_curses(void)
3522 * Override default signal handlers before starting ncurses.
3523 * This should prevent ncurses from installing its own
3524 * broken cleanup() signal handler.
3526 signal(SIGWINCH, tog_sigwinch);
3527 signal(SIGPIPE, tog_sigpipe);
3528 signal(SIGCONT, tog_sigcont);
3529 signal(SIGINT, tog_sigint);
3530 signal(SIGTERM, tog_sigterm);
3532 initscr();
3533 cbreak();
3534 halfdelay(1); /* Do fast refresh while initial view is loading. */
3535 noecho();
3536 nonl();
3537 intrflush(stdscr, FALSE);
3538 keypad(stdscr, TRUE);
3539 curs_set(0);
3540 if (getenv("TOG_COLORS") != NULL) {
3541 start_color();
3542 use_default_colors();
3546 static const struct got_error *
3547 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3548 struct got_repository *repo, struct got_worktree *worktree)
3550 const struct got_error *err = NULL;
3552 if (argc == 0) {
3553 *in_repo_path = strdup("/");
3554 if (*in_repo_path == NULL)
3555 return got_error_from_errno("strdup");
3556 return NULL;
3559 if (worktree) {
3560 const char *prefix = got_worktree_get_path_prefix(worktree);
3561 char *p;
3563 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3564 if (err)
3565 return err;
3566 if (asprintf(in_repo_path, "%s%s%s", prefix,
3567 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3568 p) == -1) {
3569 err = got_error_from_errno("asprintf");
3570 *in_repo_path = NULL;
3572 free(p);
3573 } else
3574 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3576 return err;
3579 static const struct got_error *
3580 cmd_log(int argc, char *argv[])
3582 const struct got_error *error;
3583 struct got_repository *repo = NULL;
3584 struct got_worktree *worktree = NULL;
3585 struct got_object_id *start_id = NULL;
3586 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3587 char *start_commit = NULL, *label = NULL;
3588 struct got_reference *ref = NULL;
3589 const char *head_ref_name = NULL;
3590 int ch, log_branches = 0;
3591 struct tog_view *view;
3592 int *pack_fds = NULL;
3594 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3595 switch (ch) {
3596 case 'b':
3597 log_branches = 1;
3598 break;
3599 case 'c':
3600 start_commit = optarg;
3601 break;
3602 case 'r':
3603 repo_path = realpath(optarg, NULL);
3604 if (repo_path == NULL)
3605 return got_error_from_errno2("realpath",
3606 optarg);
3607 break;
3608 default:
3609 usage_log();
3610 /* NOTREACHED */
3614 argc -= optind;
3615 argv += optind;
3617 if (argc > 1)
3618 usage_log();
3620 error = got_repo_pack_fds_open(&pack_fds);
3621 if (error != NULL)
3622 goto done;
3624 if (repo_path == NULL) {
3625 cwd = getcwd(NULL, 0);
3626 if (cwd == NULL)
3627 return got_error_from_errno("getcwd");
3628 error = got_worktree_open(&worktree, cwd);
3629 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3630 goto done;
3631 if (worktree)
3632 repo_path =
3633 strdup(got_worktree_get_repo_path(worktree));
3634 else
3635 repo_path = strdup(cwd);
3636 if (repo_path == NULL) {
3637 error = got_error_from_errno("strdup");
3638 goto done;
3642 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3643 if (error != NULL)
3644 goto done;
3646 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3647 repo, worktree);
3648 if (error)
3649 goto done;
3651 init_curses();
3653 error = apply_unveil(got_repo_get_path(repo),
3654 worktree ? got_worktree_get_root_path(worktree) : NULL);
3655 if (error)
3656 goto done;
3658 /* already loaded by tog_log_with_path()? */
3659 if (TAILQ_EMPTY(&tog_refs)) {
3660 error = tog_load_refs(repo, 0);
3661 if (error)
3662 goto done;
3665 if (start_commit == NULL) {
3666 error = got_repo_match_object_id(&start_id, &label,
3667 worktree ? got_worktree_get_head_ref_name(worktree) :
3668 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3669 if (error)
3670 goto done;
3671 head_ref_name = label;
3672 } else {
3673 error = got_ref_open(&ref, repo, start_commit, 0);
3674 if (error == NULL)
3675 head_ref_name = got_ref_get_name(ref);
3676 else if (error->code != GOT_ERR_NOT_REF)
3677 goto done;
3678 error = got_repo_match_object_id(&start_id, NULL,
3679 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3680 if (error)
3681 goto done;
3684 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3685 if (view == NULL) {
3686 error = got_error_from_errno("view_open");
3687 goto done;
3689 error = open_log_view(view, start_id, repo, head_ref_name,
3690 in_repo_path, log_branches);
3691 if (error)
3692 goto done;
3693 if (worktree) {
3694 /* Release work tree lock. */
3695 got_worktree_close(worktree);
3696 worktree = NULL;
3698 error = view_loop(view);
3699 done:
3700 free(in_repo_path);
3701 free(repo_path);
3702 free(cwd);
3703 free(start_id);
3704 free(label);
3705 if (ref)
3706 got_ref_close(ref);
3707 if (repo) {
3708 const struct got_error *close_err = got_repo_close(repo);
3709 if (error == NULL)
3710 error = close_err;
3712 if (worktree)
3713 got_worktree_close(worktree);
3714 if (pack_fds) {
3715 const struct got_error *pack_err =
3716 got_repo_pack_fds_close(pack_fds);
3717 if (error == NULL)
3718 error = pack_err;
3720 tog_free_refs();
3721 return error;
3724 __dead static void
3725 usage_diff(void)
3727 endwin();
3728 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3729 "[-w] object1 object2\n", getprogname());
3730 exit(1);
3733 static int
3734 match_line(const char *line, regex_t *regex, size_t nmatch,
3735 regmatch_t *regmatch)
3737 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3740 static struct tog_color *
3741 match_color(struct tog_colors *colors, const char *line)
3743 struct tog_color *tc = NULL;
3745 STAILQ_FOREACH(tc, colors, entry) {
3746 if (match_line(line, &tc->regex, 0, NULL))
3747 return tc;
3750 return NULL;
3753 static const struct got_error *
3754 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3755 WINDOW *window, int skipcol, regmatch_t *regmatch)
3757 const struct got_error *err = NULL;
3758 char *exstr = NULL;
3759 wchar_t *wline = NULL;
3760 int rme, rms, n, width, scrollx;
3761 int width0 = 0, width1 = 0, width2 = 0;
3762 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3764 *wtotal = 0;
3766 rms = regmatch->rm_so;
3767 rme = regmatch->rm_eo;
3769 err = expand_tab(&exstr, line);
3770 if (err)
3771 return err;
3773 /* Split the line into 3 segments, according to match offsets. */
3774 seg0 = strndup(exstr, rms);
3775 if (seg0 == NULL) {
3776 err = got_error_from_errno("strndup");
3777 goto done;
3779 seg1 = strndup(exstr + rms, rme - rms);
3780 if (seg1 == NULL) {
3781 err = got_error_from_errno("strndup");
3782 goto done;
3784 seg2 = strdup(exstr + rme);
3785 if (seg2 == NULL) {
3786 err = got_error_from_errno("strndup");
3787 goto done;
3790 /* draw up to matched token if we haven't scrolled past it */
3791 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3792 col_tab_align, 1);
3793 if (err)
3794 goto done;
3795 n = MAX(width0 - skipcol, 0);
3796 if (n) {
3797 free(wline);
3798 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3799 wlimit, col_tab_align, 1);
3800 if (err)
3801 goto done;
3802 waddwstr(window, &wline[scrollx]);
3803 wlimit -= width;
3804 *wtotal += width;
3807 if (wlimit > 0) {
3808 int i = 0, w = 0;
3809 size_t wlen;
3811 free(wline);
3812 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3813 col_tab_align, 1);
3814 if (err)
3815 goto done;
3816 wlen = wcslen(wline);
3817 while (i < wlen) {
3818 width = wcwidth(wline[i]);
3819 if (width == -1) {
3820 /* should not happen, tabs are expanded */
3821 err = got_error(GOT_ERR_RANGE);
3822 goto done;
3824 if (width0 + w + width > skipcol)
3825 break;
3826 w += width;
3827 i++;
3829 /* draw (visible part of) matched token (if scrolled into it) */
3830 if (width1 - w > 0) {
3831 wattron(window, A_STANDOUT);
3832 waddwstr(window, &wline[i]);
3833 wattroff(window, A_STANDOUT);
3834 wlimit -= (width1 - w);
3835 *wtotal += (width1 - w);
3839 if (wlimit > 0) { /* draw rest of line */
3840 free(wline);
3841 if (skipcol > width0 + width1) {
3842 err = format_line(&wline, &width2, &scrollx, seg2,
3843 skipcol - (width0 + width1), wlimit,
3844 col_tab_align, 1);
3845 if (err)
3846 goto done;
3847 waddwstr(window, &wline[scrollx]);
3848 } else {
3849 err = format_line(&wline, &width2, NULL, seg2, 0,
3850 wlimit, col_tab_align, 1);
3851 if (err)
3852 goto done;
3853 waddwstr(window, wline);
3855 *wtotal += width2;
3857 done:
3858 free(wline);
3859 free(exstr);
3860 free(seg0);
3861 free(seg1);
3862 free(seg2);
3863 return err;
3866 static const struct got_error *
3867 draw_file(struct tog_view *view, const char *header)
3869 struct tog_diff_view_state *s = &view->state.diff;
3870 regmatch_t *regmatch = &view->regmatch;
3871 const struct got_error *err;
3872 int nprinted = 0;
3873 char *line;
3874 size_t linesize = 0;
3875 ssize_t linelen;
3876 struct tog_color *tc;
3877 wchar_t *wline;
3878 int width;
3879 int max_lines = view->nlines;
3880 int nlines = s->nlines;
3881 off_t line_offset;
3883 line_offset = s->line_offsets[s->first_displayed_line - 1];
3884 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3885 return got_error_from_errno("fseek");
3887 werase(view->window);
3889 if (header) {
3890 if (asprintf(&line, "[%d/%d] %s",
3891 s->first_displayed_line - 1 + s->selected_line, nlines,
3892 header) == -1)
3893 return got_error_from_errno("asprintf");
3894 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3895 0, 0);
3896 free(line);
3897 if (err)
3898 return err;
3900 if (view_needs_focus_indication(view))
3901 wstandout(view->window);
3902 waddwstr(view->window, wline);
3903 free(wline);
3904 wline = NULL;
3905 if (view_needs_focus_indication(view))
3906 wstandend(view->window);
3907 if (width <= view->ncols - 1)
3908 waddch(view->window, '\n');
3910 if (max_lines <= 1)
3911 return NULL;
3912 max_lines--;
3915 s->eof = 0;
3916 view->maxx = 0;
3917 line = NULL;
3918 while (max_lines > 0 && nprinted < max_lines) {
3919 linelen = getline(&line, &linesize, s->f);
3920 if (linelen == -1) {
3921 if (feof(s->f)) {
3922 s->eof = 1;
3923 break;
3925 free(line);
3926 return got_ferror(s->f, GOT_ERR_IO);
3929 /* Set view->maxx based on full line length. */
3930 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3931 view->x ? 1 : 0);
3932 if (err) {
3933 free(line);
3934 return err;
3936 view->maxx = MAX(view->maxx, width);
3937 free(wline);
3938 wline = NULL;
3940 tc = match_color(&s->colors, line);
3941 if (tc)
3942 wattr_on(view->window,
3943 COLOR_PAIR(tc->colorpair), NULL);
3944 if (s->first_displayed_line + nprinted == s->matched_line &&
3945 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3946 err = add_matched_line(&width, line, view->ncols, 0,
3947 view->window, view->x, regmatch);
3948 if (err) {
3949 free(line);
3950 return err;
3952 } else {
3953 int skip;
3954 err = format_line(&wline, &width, &skip, line,
3955 view->x, view->ncols, 0, view->x ? 1 : 0);
3956 if (err) {
3957 free(line);
3958 return err;
3960 waddwstr(view->window, &wline[skip]);
3961 free(wline);
3962 wline = NULL;
3964 if (tc)
3965 wattr_off(view->window,
3966 COLOR_PAIR(tc->colorpair), NULL);
3967 if (width <= view->ncols - 1)
3968 waddch(view->window, '\n');
3969 nprinted++;
3971 free(line);
3972 if (nprinted >= 1)
3973 s->last_displayed_line = s->first_displayed_line +
3974 (nprinted - 1);
3975 else
3976 s->last_displayed_line = s->first_displayed_line;
3978 view_border(view);
3980 if (s->eof) {
3981 while (nprinted < view->nlines) {
3982 waddch(view->window, '\n');
3983 nprinted++;
3986 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3987 view->ncols, 0, 0);
3988 if (err) {
3989 return err;
3992 wstandout(view->window);
3993 waddwstr(view->window, wline);
3994 free(wline);
3995 wline = NULL;
3996 wstandend(view->window);
3999 return NULL;
4002 static char *
4003 get_datestr(time_t *time, char *datebuf)
4005 struct tm mytm, *tm;
4006 char *p, *s;
4008 tm = gmtime_r(time, &mytm);
4009 if (tm == NULL)
4010 return NULL;
4011 s = asctime_r(tm, datebuf);
4012 if (s == NULL)
4013 return NULL;
4014 p = strchr(s, '\n');
4015 if (p)
4016 *p = '\0';
4017 return s;
4020 static const struct got_error *
4021 get_changed_paths(struct got_pathlist_head *paths,
4022 struct got_commit_object *commit, struct got_repository *repo)
4024 const struct got_error *err = NULL;
4025 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4026 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4027 struct got_object_qid *qid;
4029 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4030 if (qid != NULL) {
4031 struct got_commit_object *pcommit;
4032 err = got_object_open_as_commit(&pcommit, repo,
4033 &qid->id);
4034 if (err)
4035 return err;
4037 tree_id1 = got_object_id_dup(
4038 got_object_commit_get_tree_id(pcommit));
4039 if (tree_id1 == NULL) {
4040 got_object_commit_close(pcommit);
4041 return got_error_from_errno("got_object_id_dup");
4043 got_object_commit_close(pcommit);
4047 if (tree_id1) {
4048 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4049 if (err)
4050 goto done;
4053 tree_id2 = got_object_commit_get_tree_id(commit);
4054 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4055 if (err)
4056 goto done;
4058 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4059 got_diff_tree_collect_changed_paths, paths, 0);
4060 done:
4061 if (tree1)
4062 got_object_tree_close(tree1);
4063 if (tree2)
4064 got_object_tree_close(tree2);
4065 free(tree_id1);
4066 return err;
4069 static const struct got_error *
4070 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
4072 off_t *p;
4074 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
4075 if (p == NULL)
4076 return got_error_from_errno("reallocarray");
4077 *line_offsets = p;
4078 (*line_offsets)[*nlines] = off;
4079 (*nlines)++;
4080 return NULL;
4083 static const struct got_error *
4084 write_commit_info(off_t **line_offsets, size_t *nlines,
4085 struct got_object_id *commit_id, struct got_reflist_head *refs,
4086 struct got_repository *repo, FILE *outfile)
4088 const struct got_error *err = NULL;
4089 char datebuf[26], *datestr;
4090 struct got_commit_object *commit;
4091 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4092 time_t committer_time;
4093 const char *author, *committer;
4094 char *refs_str = NULL;
4095 struct got_pathlist_head changed_paths;
4096 struct got_pathlist_entry *pe;
4097 off_t outoff = 0;
4098 int n;
4100 TAILQ_INIT(&changed_paths);
4102 if (refs) {
4103 err = build_refs_str(&refs_str, refs, commit_id, repo);
4104 if (err)
4105 return err;
4108 err = got_object_open_as_commit(&commit, repo, commit_id);
4109 if (err)
4110 return err;
4112 err = got_object_id_str(&id_str, commit_id);
4113 if (err) {
4114 err = got_error_from_errno("got_object_id_str");
4115 goto done;
4118 err = add_line_offset(line_offsets, nlines, 0);
4119 if (err)
4120 goto done;
4122 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4123 refs_str ? refs_str : "", refs_str ? ")" : "");
4124 if (n < 0) {
4125 err = got_error_from_errno("fprintf");
4126 goto done;
4128 outoff += n;
4129 err = add_line_offset(line_offsets, nlines, outoff);
4130 if (err)
4131 goto done;
4133 n = fprintf(outfile, "from: %s\n",
4134 got_object_commit_get_author(commit));
4135 if (n < 0) {
4136 err = got_error_from_errno("fprintf");
4137 goto done;
4139 outoff += n;
4140 err = add_line_offset(line_offsets, nlines, outoff);
4141 if (err)
4142 goto done;
4144 committer_time = got_object_commit_get_committer_time(commit);
4145 datestr = get_datestr(&committer_time, datebuf);
4146 if (datestr) {
4147 n = fprintf(outfile, "date: %s UTC\n", datestr);
4148 if (n < 0) {
4149 err = got_error_from_errno("fprintf");
4150 goto done;
4152 outoff += n;
4153 err = add_line_offset(line_offsets, nlines, outoff);
4154 if (err)
4155 goto done;
4157 author = got_object_commit_get_author(commit);
4158 committer = got_object_commit_get_committer(commit);
4159 if (strcmp(author, committer) != 0) {
4160 n = fprintf(outfile, "via: %s\n", committer);
4161 if (n < 0) {
4162 err = got_error_from_errno("fprintf");
4163 goto done;
4165 outoff += n;
4166 err = add_line_offset(line_offsets, nlines, outoff);
4167 if (err)
4168 goto done;
4170 if (got_object_commit_get_nparents(commit) > 1) {
4171 const struct got_object_id_queue *parent_ids;
4172 struct got_object_qid *qid;
4173 int pn = 1;
4174 parent_ids = got_object_commit_get_parent_ids(commit);
4175 STAILQ_FOREACH(qid, parent_ids, entry) {
4176 err = got_object_id_str(&id_str, &qid->id);
4177 if (err)
4178 goto done;
4179 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4180 if (n < 0) {
4181 err = got_error_from_errno("fprintf");
4182 goto done;
4184 outoff += n;
4185 err = add_line_offset(line_offsets, nlines, outoff);
4186 if (err)
4187 goto done;
4188 free(id_str);
4189 id_str = NULL;
4193 err = got_object_commit_get_logmsg(&logmsg, commit);
4194 if (err)
4195 goto done;
4196 s = logmsg;
4197 while ((line = strsep(&s, "\n")) != NULL) {
4198 n = fprintf(outfile, "%s\n", line);
4199 if (n < 0) {
4200 err = got_error_from_errno("fprintf");
4201 goto done;
4203 outoff += n;
4204 err = add_line_offset(line_offsets, nlines, outoff);
4205 if (err)
4206 goto done;
4209 err = get_changed_paths(&changed_paths, commit, repo);
4210 if (err)
4211 goto done;
4212 TAILQ_FOREACH(pe, &changed_paths, entry) {
4213 struct got_diff_changed_path *cp = pe->data;
4214 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4215 if (n < 0) {
4216 err = got_error_from_errno("fprintf");
4217 goto done;
4219 outoff += n;
4220 err = add_line_offset(line_offsets, nlines, outoff);
4221 if (err)
4222 goto done;
4223 free((char *)pe->path);
4224 free(pe->data);
4227 fputc('\n', outfile);
4228 outoff++;
4229 err = add_line_offset(line_offsets, nlines, outoff);
4230 done:
4231 got_pathlist_free(&changed_paths);
4232 free(id_str);
4233 free(logmsg);
4234 free(refs_str);
4235 got_object_commit_close(commit);
4236 if (err) {
4237 free(*line_offsets);
4238 *line_offsets = NULL;
4239 *nlines = 0;
4241 return err;
4244 static const struct got_error *
4245 create_diff(struct tog_diff_view_state *s)
4247 const struct got_error *err = NULL;
4248 FILE *f = NULL;
4249 int obj_type;
4251 free(s->line_offsets);
4252 s->line_offsets = malloc(sizeof(off_t));
4253 if (s->line_offsets == NULL)
4254 return got_error_from_errno("malloc");
4255 s->nlines = 0;
4257 f = got_opentemp();
4258 if (f == NULL) {
4259 err = got_error_from_errno("got_opentemp");
4260 goto done;
4262 if (s->f && fclose(s->f) == EOF) {
4263 err = got_error_from_errno("fclose");
4264 goto done;
4266 s->f = f;
4268 if (s->id1)
4269 err = got_object_get_type(&obj_type, s->repo, s->id1);
4270 else
4271 err = got_object_get_type(&obj_type, s->repo, s->id2);
4272 if (err)
4273 goto done;
4275 switch (obj_type) {
4276 case GOT_OBJ_TYPE_BLOB:
4277 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
4278 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4279 s->label1, s->label2, tog_diff_algo, s->diff_context,
4280 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4281 break;
4282 case GOT_OBJ_TYPE_TREE:
4283 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
4284 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4285 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4286 s->force_text_diff, s->repo, s->f);
4287 break;
4288 case GOT_OBJ_TYPE_COMMIT: {
4289 const struct got_object_id_queue *parent_ids;
4290 struct got_object_qid *pid;
4291 struct got_commit_object *commit2;
4292 struct got_reflist_head *refs;
4294 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4295 if (err)
4296 goto done;
4297 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4298 /* Show commit info if we're diffing to a parent/root commit. */
4299 if (s->id1 == NULL) {
4300 err = write_commit_info(&s->line_offsets, &s->nlines,
4301 s->id2, refs, s->repo, s->f);
4302 if (err)
4303 goto done;
4304 } else {
4305 parent_ids = got_object_commit_get_parent_ids(commit2);
4306 STAILQ_FOREACH(pid, parent_ids, entry) {
4307 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4308 err = write_commit_info(
4309 &s->line_offsets, &s->nlines,
4310 s->id2, refs, s->repo, s->f);
4311 if (err)
4312 goto done;
4313 break;
4317 got_object_commit_close(commit2);
4319 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4320 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4321 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4322 s->force_text_diff, s->repo, s->f);
4323 break;
4325 default:
4326 err = got_error(GOT_ERR_OBJ_TYPE);
4327 break;
4329 if (err)
4330 goto done;
4331 done:
4332 if (s->f && fflush(s->f) != 0 && err == NULL)
4333 err = got_error_from_errno("fflush");
4334 return err;
4337 static void
4338 diff_view_indicate_progress(struct tog_view *view)
4340 mvwaddstr(view->window, 0, 0, "diffing...");
4341 update_panels();
4342 doupdate();
4345 static const struct got_error *
4346 search_start_diff_view(struct tog_view *view)
4348 struct tog_diff_view_state *s = &view->state.diff;
4350 s->matched_line = 0;
4351 return NULL;
4354 static const struct got_error *
4355 search_next_diff_view(struct tog_view *view)
4357 struct tog_diff_view_state *s = &view->state.diff;
4358 const struct got_error *err = NULL;
4359 int lineno;
4360 char *line = NULL;
4361 size_t linesize = 0;
4362 ssize_t linelen;
4364 if (!view->searching) {
4365 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4366 return NULL;
4369 if (s->matched_line) {
4370 if (view->searching == TOG_SEARCH_FORWARD)
4371 lineno = s->matched_line + 1;
4372 else
4373 lineno = s->matched_line - 1;
4374 } else
4375 lineno = s->first_displayed_line;
4377 while (1) {
4378 off_t offset;
4380 if (lineno <= 0 || lineno > s->nlines) {
4381 if (s->matched_line == 0) {
4382 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4383 break;
4386 if (view->searching == TOG_SEARCH_FORWARD)
4387 lineno = 1;
4388 else
4389 lineno = s->nlines;
4392 offset = s->line_offsets[lineno - 1];
4393 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4394 free(line);
4395 return got_error_from_errno("fseeko");
4397 linelen = getline(&line, &linesize, s->f);
4398 if (linelen != -1) {
4399 char *exstr;
4400 err = expand_tab(&exstr, line);
4401 if (err)
4402 break;
4403 if (match_line(exstr, &view->regex, 1,
4404 &view->regmatch)) {
4405 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4406 s->matched_line = lineno;
4407 free(exstr);
4408 break;
4410 free(exstr);
4412 if (view->searching == TOG_SEARCH_FORWARD)
4413 lineno++;
4414 else
4415 lineno--;
4417 free(line);
4419 if (s->matched_line) {
4420 s->first_displayed_line = s->matched_line;
4421 s->selected_line = 1;
4424 return err;
4427 static const struct got_error *
4428 close_diff_view(struct tog_view *view)
4430 const struct got_error *err = NULL;
4431 struct tog_diff_view_state *s = &view->state.diff;
4433 free(s->id1);
4434 s->id1 = NULL;
4435 free(s->id2);
4436 s->id2 = NULL;
4437 if (s->f && fclose(s->f) == EOF)
4438 err = got_error_from_errno("fclose");
4439 s->f = NULL;
4440 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4441 err = got_error_from_errno("fclose");
4442 s->f1 = NULL;
4443 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4444 err = got_error_from_errno("fclose");
4445 s->f2 = NULL;
4446 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4447 err = got_error_from_errno("close");
4448 s->fd1 = -1;
4449 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4450 err = got_error_from_errno("close");
4451 s->fd2 = -1;
4452 free_colors(&s->colors);
4453 free(s->line_offsets);
4454 s->line_offsets = NULL;
4455 s->nlines = 0;
4456 return err;
4459 static const struct got_error *
4460 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4461 struct got_object_id *id2, const char *label1, const char *label2,
4462 int diff_context, int ignore_whitespace, int force_text_diff,
4463 struct tog_view *parent_view, struct got_repository *repo)
4465 const struct got_error *err;
4466 struct tog_diff_view_state *s = &view->state.diff;
4468 memset(s, 0, sizeof(*s));
4469 s->fd1 = -1;
4470 s->fd2 = -1;
4472 if (id1 != NULL && id2 != NULL) {
4473 int type1, type2;
4474 err = got_object_get_type(&type1, repo, id1);
4475 if (err)
4476 return err;
4477 err = got_object_get_type(&type2, repo, id2);
4478 if (err)
4479 return err;
4481 if (type1 != type2)
4482 return got_error(GOT_ERR_OBJ_TYPE);
4484 s->first_displayed_line = 1;
4485 s->last_displayed_line = view->nlines;
4486 s->selected_line = 1;
4487 s->repo = repo;
4488 s->id1 = id1;
4489 s->id2 = id2;
4490 s->label1 = label1;
4491 s->label2 = label2;
4493 if (id1) {
4494 s->id1 = got_object_id_dup(id1);
4495 if (s->id1 == NULL)
4496 return got_error_from_errno("got_object_id_dup");
4497 } else
4498 s->id1 = NULL;
4500 s->id2 = got_object_id_dup(id2);
4501 if (s->id2 == NULL) {
4502 err = got_error_from_errno("got_object_id_dup");
4503 goto done;
4506 s->f1 = got_opentemp();
4507 if (s->f1 == NULL) {
4508 err = got_error_from_errno("got_opentemp");
4509 goto done;
4512 s->f2 = got_opentemp();
4513 if (s->f2 == NULL) {
4514 err = got_error_from_errno("got_opentemp");
4515 goto done;
4518 s->fd1 = got_opentempfd();
4519 if (s->fd1 == -1) {
4520 err = got_error_from_errno("got_opentempfd");
4521 goto done;
4524 s->fd2 = got_opentempfd();
4525 if (s->fd2 == -1) {
4526 err = got_error_from_errno("got_opentempfd");
4527 goto done;
4530 s->first_displayed_line = 1;
4531 s->last_displayed_line = view->nlines;
4532 s->diff_context = diff_context;
4533 s->ignore_whitespace = ignore_whitespace;
4534 s->force_text_diff = force_text_diff;
4535 s->parent_view = parent_view;
4536 s->repo = repo;
4538 STAILQ_INIT(&s->colors);
4539 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4540 err = add_color(&s->colors,
4541 "^-", TOG_COLOR_DIFF_MINUS,
4542 get_color_value("TOG_COLOR_DIFF_MINUS"));
4543 if (err)
4544 goto done;
4545 err = add_color(&s->colors, "^\\+",
4546 TOG_COLOR_DIFF_PLUS,
4547 get_color_value("TOG_COLOR_DIFF_PLUS"));
4548 if (err)
4549 goto done;
4550 err = add_color(&s->colors,
4551 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4552 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4553 if (err)
4554 goto done;
4556 err = add_color(&s->colors,
4557 "^(commit [0-9a-f]|parent [0-9]|"
4558 "(blob|file|tree|commit) [-+] |"
4559 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4560 get_color_value("TOG_COLOR_DIFF_META"));
4561 if (err)
4562 goto done;
4564 err = add_color(&s->colors,
4565 "^(from|via): ", TOG_COLOR_AUTHOR,
4566 get_color_value("TOG_COLOR_AUTHOR"));
4567 if (err)
4568 goto done;
4570 err = add_color(&s->colors,
4571 "^date: ", TOG_COLOR_DATE,
4572 get_color_value("TOG_COLOR_DATE"));
4573 if (err)
4574 goto done;
4577 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4578 view_is_splitscreen(view))
4579 show_log_view(parent_view); /* draw border */
4580 diff_view_indicate_progress(view);
4582 err = create_diff(s);
4584 view->show = show_diff_view;
4585 view->input = input_diff_view;
4586 view->reset = reset_diff_view;
4587 view->close = close_diff_view;
4588 view->search_start = search_start_diff_view;
4589 view->search_next = search_next_diff_view;
4590 done:
4591 if (err)
4592 close_diff_view(view);
4593 return err;
4596 static const struct got_error *
4597 show_diff_view(struct tog_view *view)
4599 const struct got_error *err;
4600 struct tog_diff_view_state *s = &view->state.diff;
4601 char *id_str1 = NULL, *id_str2, *header;
4602 const char *label1, *label2;
4604 if (s->id1) {
4605 err = got_object_id_str(&id_str1, s->id1);
4606 if (err)
4607 return err;
4608 label1 = s->label1 ? : id_str1;
4609 } else
4610 label1 = "/dev/null";
4612 err = got_object_id_str(&id_str2, s->id2);
4613 if (err)
4614 return err;
4615 label2 = s->label2 ? : id_str2;
4617 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4618 err = got_error_from_errno("asprintf");
4619 free(id_str1);
4620 free(id_str2);
4621 return err;
4623 free(id_str1);
4624 free(id_str2);
4626 err = draw_file(view, header);
4627 free(header);
4628 return err;
4631 static const struct got_error *
4632 set_selected_commit(struct tog_diff_view_state *s,
4633 struct commit_queue_entry *entry)
4635 const struct got_error *err;
4636 const struct got_object_id_queue *parent_ids;
4637 struct got_commit_object *selected_commit;
4638 struct got_object_qid *pid;
4640 free(s->id2);
4641 s->id2 = got_object_id_dup(entry->id);
4642 if (s->id2 == NULL)
4643 return got_error_from_errno("got_object_id_dup");
4645 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4646 if (err)
4647 return err;
4648 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4649 free(s->id1);
4650 pid = STAILQ_FIRST(parent_ids);
4651 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4652 got_object_commit_close(selected_commit);
4653 return NULL;
4656 static const struct got_error *
4657 reset_diff_view(struct tog_view *view)
4659 struct tog_diff_view_state *s = &view->state.diff;
4661 view->count = 0;
4662 wclear(view->window);
4663 s->first_displayed_line = 1;
4664 s->last_displayed_line = view->nlines;
4665 s->matched_line = 0;
4666 diff_view_indicate_progress(view);
4667 return create_diff(s);
4670 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4671 int, int, int);
4672 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4673 int, int);
4675 static const struct got_error *
4676 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4678 const struct got_error *err = NULL;
4679 struct tog_diff_view_state *s = &view->state.diff;
4680 struct tog_log_view_state *ls;
4681 struct commit_queue_entry *old_selected_entry;
4682 char *line = NULL;
4683 size_t linesize = 0;
4684 ssize_t linelen;
4685 int i, nscroll = view->nlines - 1, up = 0;
4687 switch (ch) {
4688 case '0':
4689 view->x = 0;
4690 break;
4691 case '$':
4692 view->x = MAX(view->maxx - view->ncols / 3, 0);
4693 view->count = 0;
4694 break;
4695 case KEY_RIGHT:
4696 case 'l':
4697 if (view->x + view->ncols / 3 < view->maxx)
4698 view->x += 2; /* move two columns right */
4699 else
4700 view->count = 0;
4701 break;
4702 case KEY_LEFT:
4703 case 'h':
4704 view->x -= MIN(view->x, 2); /* move two columns back */
4705 if (view->x <= 0)
4706 view->count = 0;
4707 break;
4708 case 'a':
4709 case 'w':
4710 if (ch == 'a')
4711 s->force_text_diff = !s->force_text_diff;
4712 if (ch == 'w')
4713 s->ignore_whitespace = !s->ignore_whitespace;
4714 err = reset_diff_view(view);
4715 break;
4716 case 'g':
4717 case KEY_HOME:
4718 s->first_displayed_line = 1;
4719 view->count = 0;
4720 break;
4721 case 'G':
4722 case KEY_END:
4723 view->count = 0;
4724 if (s->eof)
4725 break;
4727 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4728 s->eof = 1;
4729 break;
4730 case 'k':
4731 case KEY_UP:
4732 case CTRL('p'):
4733 if (s->first_displayed_line > 1)
4734 s->first_displayed_line--;
4735 else
4736 view->count = 0;
4737 break;
4738 case CTRL('u'):
4739 case 'u':
4740 nscroll /= 2;
4741 /* FALL THROUGH */
4742 case KEY_PPAGE:
4743 case CTRL('b'):
4744 case 'b':
4745 if (s->first_displayed_line == 1) {
4746 view->count = 0;
4747 break;
4749 i = 0;
4750 while (i++ < nscroll && s->first_displayed_line > 1)
4751 s->first_displayed_line--;
4752 break;
4753 case 'j':
4754 case KEY_DOWN:
4755 case CTRL('n'):
4756 if (!s->eof)
4757 s->first_displayed_line++;
4758 else
4759 view->count = 0;
4760 break;
4761 case CTRL('d'):
4762 case 'd':
4763 nscroll /= 2;
4764 /* FALL THROUGH */
4765 case KEY_NPAGE:
4766 case CTRL('f'):
4767 case 'f':
4768 case ' ':
4769 if (s->eof) {
4770 view->count = 0;
4771 break;
4773 i = 0;
4774 while (!s->eof && i++ < nscroll) {
4775 linelen = getline(&line, &linesize, s->f);
4776 s->first_displayed_line++;
4777 if (linelen == -1) {
4778 if (feof(s->f)) {
4779 s->eof = 1;
4780 } else
4781 err = got_ferror(s->f, GOT_ERR_IO);
4782 break;
4785 free(line);
4786 break;
4787 case '[':
4788 if (s->diff_context > 0) {
4789 s->diff_context--;
4790 s->matched_line = 0;
4791 diff_view_indicate_progress(view);
4792 err = create_diff(s);
4793 if (s->first_displayed_line + view->nlines - 1 >
4794 s->nlines) {
4795 s->first_displayed_line = 1;
4796 s->last_displayed_line = view->nlines;
4798 } else
4799 view->count = 0;
4800 break;
4801 case ']':
4802 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4803 s->diff_context++;
4804 s->matched_line = 0;
4805 diff_view_indicate_progress(view);
4806 err = create_diff(s);
4807 } else
4808 view->count = 0;
4809 break;
4810 case '<':
4811 case ',':
4812 up = 1;
4813 /* FALL THROUGH */
4814 case '>':
4815 case '.':
4816 if (s->parent_view == NULL) {
4817 view->count = 0;
4818 break;
4820 s->parent_view->count = view->count;
4822 if (s->parent_view->type == TOG_VIEW_LOG) {
4823 ls = &s->parent_view->state.log;
4824 old_selected_entry = ls->selected_entry;
4826 err = input_log_view(NULL, s->parent_view,
4827 up ? KEY_UP : KEY_DOWN);
4828 if (err)
4829 break;
4830 view->count = s->parent_view->count;
4832 if (old_selected_entry == ls->selected_entry)
4833 break;
4835 err = set_selected_commit(s, ls->selected_entry);
4836 if (err)
4837 break;
4838 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4839 struct tog_blame_view_state *bs;
4840 struct got_object_id *id, *prev_id;
4842 bs = &s->parent_view->state.blame;
4843 prev_id = get_annotation_for_line(bs->blame.lines,
4844 bs->blame.nlines, bs->last_diffed_line);
4846 err = input_blame_view(&view, s->parent_view,
4847 up ? KEY_UP : KEY_DOWN);
4848 if (err)
4849 break;
4850 view->count = s->parent_view->count;
4852 if (prev_id == NULL)
4853 break;
4854 id = get_selected_commit_id(bs->blame.lines,
4855 bs->blame.nlines, bs->first_displayed_line,
4856 bs->selected_line);
4857 if (id == NULL)
4858 break;
4860 if (!got_object_id_cmp(prev_id, id))
4861 break;
4863 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
4864 if (err)
4865 break;
4867 s->first_displayed_line = 1;
4868 s->last_displayed_line = view->nlines;
4869 s->matched_line = 0;
4870 view->x = 0;
4872 diff_view_indicate_progress(view);
4873 err = create_diff(s);
4874 break;
4875 default:
4876 view->count = 0;
4877 break;
4880 return err;
4883 static const struct got_error *
4884 cmd_diff(int argc, char *argv[])
4886 const struct got_error *error = NULL;
4887 struct got_repository *repo = NULL;
4888 struct got_worktree *worktree = NULL;
4889 struct got_object_id *id1 = NULL, *id2 = NULL;
4890 char *repo_path = NULL, *cwd = NULL;
4891 char *id_str1 = NULL, *id_str2 = NULL;
4892 char *label1 = NULL, *label2 = NULL;
4893 int diff_context = 3, ignore_whitespace = 0;
4894 int ch, force_text_diff = 0;
4895 const char *errstr;
4896 struct tog_view *view;
4897 int *pack_fds = NULL;
4899 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4900 switch (ch) {
4901 case 'a':
4902 force_text_diff = 1;
4903 break;
4904 case 'C':
4905 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4906 &errstr);
4907 if (errstr != NULL)
4908 errx(1, "number of context lines is %s: %s",
4909 errstr, errstr);
4910 break;
4911 case 'r':
4912 repo_path = realpath(optarg, NULL);
4913 if (repo_path == NULL)
4914 return got_error_from_errno2("realpath",
4915 optarg);
4916 got_path_strip_trailing_slashes(repo_path);
4917 break;
4918 case 'w':
4919 ignore_whitespace = 1;
4920 break;
4921 default:
4922 usage_diff();
4923 /* NOTREACHED */
4927 argc -= optind;
4928 argv += optind;
4930 if (argc == 0) {
4931 usage_diff(); /* TODO show local worktree changes */
4932 } else if (argc == 2) {
4933 id_str1 = argv[0];
4934 id_str2 = argv[1];
4935 } else
4936 usage_diff();
4938 error = got_repo_pack_fds_open(&pack_fds);
4939 if (error)
4940 goto done;
4942 if (repo_path == NULL) {
4943 cwd = getcwd(NULL, 0);
4944 if (cwd == NULL)
4945 return got_error_from_errno("getcwd");
4946 error = got_worktree_open(&worktree, cwd);
4947 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4948 goto done;
4949 if (worktree)
4950 repo_path =
4951 strdup(got_worktree_get_repo_path(worktree));
4952 else
4953 repo_path = strdup(cwd);
4954 if (repo_path == NULL) {
4955 error = got_error_from_errno("strdup");
4956 goto done;
4960 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4961 if (error)
4962 goto done;
4964 init_curses();
4966 error = apply_unveil(got_repo_get_path(repo), NULL);
4967 if (error)
4968 goto done;
4970 error = tog_load_refs(repo, 0);
4971 if (error)
4972 goto done;
4974 error = got_repo_match_object_id(&id1, &label1, id_str1,
4975 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4976 if (error)
4977 goto done;
4979 error = got_repo_match_object_id(&id2, &label2, id_str2,
4980 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4981 if (error)
4982 goto done;
4984 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4985 if (view == NULL) {
4986 error = got_error_from_errno("view_open");
4987 goto done;
4989 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4990 ignore_whitespace, force_text_diff, NULL, repo);
4991 if (error)
4992 goto done;
4993 error = view_loop(view);
4994 done:
4995 free(label1);
4996 free(label2);
4997 free(repo_path);
4998 free(cwd);
4999 if (repo) {
5000 const struct got_error *close_err = got_repo_close(repo);
5001 if (error == NULL)
5002 error = close_err;
5004 if (worktree)
5005 got_worktree_close(worktree);
5006 if (pack_fds) {
5007 const struct got_error *pack_err =
5008 got_repo_pack_fds_close(pack_fds);
5009 if (error == NULL)
5010 error = pack_err;
5012 tog_free_refs();
5013 return error;
5016 __dead static void
5017 usage_blame(void)
5019 endwin();
5020 fprintf(stderr,
5021 "usage: %s blame [-c commit] [-r repository-path] path\n",
5022 getprogname());
5023 exit(1);
5026 struct tog_blame_line {
5027 int annotated;
5028 struct got_object_id *id;
5031 static const struct got_error *
5032 draw_blame(struct tog_view *view)
5034 struct tog_blame_view_state *s = &view->state.blame;
5035 struct tog_blame *blame = &s->blame;
5036 regmatch_t *regmatch = &view->regmatch;
5037 const struct got_error *err;
5038 int lineno = 0, nprinted = 0;
5039 char *line = NULL;
5040 size_t linesize = 0;
5041 ssize_t linelen;
5042 wchar_t *wline;
5043 int width;
5044 struct tog_blame_line *blame_line;
5045 struct got_object_id *prev_id = NULL;
5046 char *id_str;
5047 struct tog_color *tc;
5049 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5050 if (err)
5051 return err;
5053 rewind(blame->f);
5054 werase(view->window);
5056 if (asprintf(&line, "commit %s", id_str) == -1) {
5057 err = got_error_from_errno("asprintf");
5058 free(id_str);
5059 return err;
5062 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5063 free(line);
5064 line = NULL;
5065 if (err)
5066 return err;
5067 if (view_needs_focus_indication(view))
5068 wstandout(view->window);
5069 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5070 if (tc)
5071 wattr_on(view->window,
5072 COLOR_PAIR(tc->colorpair), NULL);
5073 waddwstr(view->window, wline);
5074 if (tc)
5075 wattr_off(view->window,
5076 COLOR_PAIR(tc->colorpair), NULL);
5077 if (view_needs_focus_indication(view))
5078 wstandend(view->window);
5079 free(wline);
5080 wline = NULL;
5081 if (width < view->ncols - 1)
5082 waddch(view->window, '\n');
5084 if (asprintf(&line, "[%d/%d] %s%s",
5085 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5086 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5087 free(id_str);
5088 return got_error_from_errno("asprintf");
5090 free(id_str);
5091 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5092 free(line);
5093 line = NULL;
5094 if (err)
5095 return err;
5096 waddwstr(view->window, wline);
5097 free(wline);
5098 wline = NULL;
5099 if (width < view->ncols - 1)
5100 waddch(view->window, '\n');
5102 s->eof = 0;
5103 view->maxx = 0;
5104 while (nprinted < view->nlines - 2) {
5105 linelen = getline(&line, &linesize, blame->f);
5106 if (linelen == -1) {
5107 if (feof(blame->f)) {
5108 s->eof = 1;
5109 break;
5111 free(line);
5112 return got_ferror(blame->f, GOT_ERR_IO);
5114 if (++lineno < s->first_displayed_line)
5115 continue;
5117 /* Set view->maxx based on full line length. */
5118 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5119 if (err) {
5120 free(line);
5121 return err;
5123 free(wline);
5124 wline = NULL;
5125 view->maxx = MAX(view->maxx, width);
5127 if (nprinted == s->selected_line - 1)
5128 wstandout(view->window);
5130 if (blame->nlines > 0) {
5131 blame_line = &blame->lines[lineno - 1];
5132 if (blame_line->annotated && prev_id &&
5133 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5134 !(nprinted == s->selected_line - 1)) {
5135 waddstr(view->window, " ");
5136 } else if (blame_line->annotated) {
5137 char *id_str;
5138 err = got_object_id_str(&id_str,
5139 blame_line->id);
5140 if (err) {
5141 free(line);
5142 return err;
5144 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5145 if (tc)
5146 wattr_on(view->window,
5147 COLOR_PAIR(tc->colorpair), NULL);
5148 wprintw(view->window, "%.8s", id_str);
5149 if (tc)
5150 wattr_off(view->window,
5151 COLOR_PAIR(tc->colorpair), NULL);
5152 free(id_str);
5153 prev_id = blame_line->id;
5154 } else {
5155 waddstr(view->window, "........");
5156 prev_id = NULL;
5158 } else {
5159 waddstr(view->window, "........");
5160 prev_id = NULL;
5163 if (nprinted == s->selected_line - 1)
5164 wstandend(view->window);
5165 waddstr(view->window, " ");
5167 if (view->ncols <= 9) {
5168 width = 9;
5169 } else if (s->first_displayed_line + nprinted ==
5170 s->matched_line &&
5171 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5172 err = add_matched_line(&width, line, view->ncols - 9, 9,
5173 view->window, view->x, regmatch);
5174 if (err) {
5175 free(line);
5176 return err;
5178 width += 9;
5179 } else {
5180 int skip;
5181 err = format_line(&wline, &width, &skip, line,
5182 view->x, view->ncols - 9, 9, 1);
5183 if (err) {
5184 free(line);
5185 return err;
5187 waddwstr(view->window, &wline[skip]);
5188 width += 9;
5189 free(wline);
5190 wline = NULL;
5193 if (width <= view->ncols - 1)
5194 waddch(view->window, '\n');
5195 if (++nprinted == 1)
5196 s->first_displayed_line = lineno;
5198 free(line);
5199 s->last_displayed_line = lineno;
5201 view_border(view);
5203 return NULL;
5206 static const struct got_error *
5207 blame_cb(void *arg, int nlines, int lineno,
5208 struct got_commit_object *commit, struct got_object_id *id)
5210 const struct got_error *err = NULL;
5211 struct tog_blame_cb_args *a = arg;
5212 struct tog_blame_line *line;
5213 int errcode;
5215 if (nlines != a->nlines ||
5216 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5217 return got_error(GOT_ERR_RANGE);
5219 errcode = pthread_mutex_lock(&tog_mutex);
5220 if (errcode)
5221 return got_error_set_errno(errcode, "pthread_mutex_lock");
5223 if (*a->quit) { /* user has quit the blame view */
5224 err = got_error(GOT_ERR_ITER_COMPLETED);
5225 goto done;
5228 if (lineno == -1)
5229 goto done; /* no change in this commit */
5231 line = &a->lines[lineno - 1];
5232 if (line->annotated)
5233 goto done;
5235 line->id = got_object_id_dup(id);
5236 if (line->id == NULL) {
5237 err = got_error_from_errno("got_object_id_dup");
5238 goto done;
5240 line->annotated = 1;
5241 done:
5242 errcode = pthread_mutex_unlock(&tog_mutex);
5243 if (errcode)
5244 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5245 return err;
5248 static void *
5249 blame_thread(void *arg)
5251 const struct got_error *err, *close_err;
5252 struct tog_blame_thread_args *ta = arg;
5253 struct tog_blame_cb_args *a = ta->cb_args;
5254 int errcode, fd1 = -1, fd2 = -1;
5255 FILE *f1 = NULL, *f2 = NULL;
5257 fd1 = got_opentempfd();
5258 if (fd1 == -1)
5259 return (void *)got_error_from_errno("got_opentempfd");
5261 fd2 = got_opentempfd();
5262 if (fd2 == -1) {
5263 err = got_error_from_errno("got_opentempfd");
5264 goto done;
5267 f1 = got_opentemp();
5268 if (f1 == NULL) {
5269 err = (void *)got_error_from_errno("got_opentemp");
5270 goto done;
5272 f2 = got_opentemp();
5273 if (f2 == NULL) {
5274 err = (void *)got_error_from_errno("got_opentemp");
5275 goto done;
5278 err = block_signals_used_by_main_thread();
5279 if (err)
5280 goto done;
5282 err = got_blame(ta->path, a->commit_id, ta->repo,
5283 tog_diff_algo, blame_cb, ta->cb_args,
5284 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5285 if (err && err->code == GOT_ERR_CANCELLED)
5286 err = NULL;
5288 errcode = pthread_mutex_lock(&tog_mutex);
5289 if (errcode) {
5290 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5291 goto done;
5294 close_err = got_repo_close(ta->repo);
5295 if (err == NULL)
5296 err = close_err;
5297 ta->repo = NULL;
5298 *ta->complete = 1;
5300 errcode = pthread_mutex_unlock(&tog_mutex);
5301 if (errcode && err == NULL)
5302 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5304 done:
5305 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5306 err = got_error_from_errno("close");
5307 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5308 err = got_error_from_errno("close");
5309 if (f1 && fclose(f1) == EOF && err == NULL)
5310 err = got_error_from_errno("fclose");
5311 if (f2 && fclose(f2) == EOF && err == NULL)
5312 err = got_error_from_errno("fclose");
5314 return (void *)err;
5317 static struct got_object_id *
5318 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5319 int first_displayed_line, int selected_line)
5321 struct tog_blame_line *line;
5323 if (nlines <= 0)
5324 return NULL;
5326 line = &lines[first_displayed_line - 1 + selected_line - 1];
5327 if (!line->annotated)
5328 return NULL;
5330 return line->id;
5333 static struct got_object_id *
5334 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5335 int lineno)
5337 struct tog_blame_line *line;
5339 if (nlines <= 0 || lineno >= nlines)
5340 return NULL;
5342 line = &lines[lineno - 1];
5343 if (!line->annotated)
5344 return NULL;
5346 return line->id;
5349 static const struct got_error *
5350 stop_blame(struct tog_blame *blame)
5352 const struct got_error *err = NULL;
5353 int i;
5355 if (blame->thread) {
5356 int errcode;
5357 errcode = pthread_mutex_unlock(&tog_mutex);
5358 if (errcode)
5359 return got_error_set_errno(errcode,
5360 "pthread_mutex_unlock");
5361 errcode = pthread_join(blame->thread, (void **)&err);
5362 if (errcode)
5363 return got_error_set_errno(errcode, "pthread_join");
5364 errcode = pthread_mutex_lock(&tog_mutex);
5365 if (errcode)
5366 return got_error_set_errno(errcode,
5367 "pthread_mutex_lock");
5368 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5369 err = NULL;
5370 blame->thread = 0; //NULL;
5372 if (blame->thread_args.repo) {
5373 const struct got_error *close_err;
5374 close_err = got_repo_close(blame->thread_args.repo);
5375 if (err == NULL)
5376 err = close_err;
5377 blame->thread_args.repo = NULL;
5379 if (blame->f) {
5380 if (fclose(blame->f) == EOF && err == NULL)
5381 err = got_error_from_errno("fclose");
5382 blame->f = NULL;
5384 if (blame->lines) {
5385 for (i = 0; i < blame->nlines; i++)
5386 free(blame->lines[i].id);
5387 free(blame->lines);
5388 blame->lines = NULL;
5390 free(blame->cb_args.commit_id);
5391 blame->cb_args.commit_id = NULL;
5392 if (blame->pack_fds) {
5393 const struct got_error *pack_err =
5394 got_repo_pack_fds_close(blame->pack_fds);
5395 if (err == NULL)
5396 err = pack_err;
5397 blame->pack_fds = NULL;
5399 return err;
5402 static const struct got_error *
5403 cancel_blame_view(void *arg)
5405 const struct got_error *err = NULL;
5406 int *done = arg;
5407 int errcode;
5409 errcode = pthread_mutex_lock(&tog_mutex);
5410 if (errcode)
5411 return got_error_set_errno(errcode,
5412 "pthread_mutex_unlock");
5414 if (*done)
5415 err = got_error(GOT_ERR_CANCELLED);
5417 errcode = pthread_mutex_unlock(&tog_mutex);
5418 if (errcode)
5419 return got_error_set_errno(errcode,
5420 "pthread_mutex_lock");
5422 return err;
5425 static const struct got_error *
5426 run_blame(struct tog_view *view)
5428 struct tog_blame_view_state *s = &view->state.blame;
5429 struct tog_blame *blame = &s->blame;
5430 const struct got_error *err = NULL;
5431 struct got_commit_object *commit = NULL;
5432 struct got_blob_object *blob = NULL;
5433 struct got_repository *thread_repo = NULL;
5434 struct got_object_id *obj_id = NULL;
5435 int obj_type, fd = -1;
5436 int *pack_fds = NULL;
5438 err = got_object_open_as_commit(&commit, s->repo,
5439 &s->blamed_commit->id);
5440 if (err)
5441 return err;
5443 fd = got_opentempfd();
5444 if (fd == -1) {
5445 err = got_error_from_errno("got_opentempfd");
5446 goto done;
5449 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5450 if (err)
5451 goto done;
5453 err = got_object_get_type(&obj_type, s->repo, obj_id);
5454 if (err)
5455 goto done;
5457 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5458 err = got_error(GOT_ERR_OBJ_TYPE);
5459 goto done;
5462 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5463 if (err)
5464 goto done;
5465 blame->f = got_opentemp();
5466 if (blame->f == NULL) {
5467 err = got_error_from_errno("got_opentemp");
5468 goto done;
5470 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5471 &blame->line_offsets, blame->f, blob);
5472 if (err)
5473 goto done;
5474 if (blame->nlines == 0) {
5475 s->blame_complete = 1;
5476 goto done;
5479 /* Don't include \n at EOF in the blame line count. */
5480 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5481 blame->nlines--;
5483 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5484 if (blame->lines == NULL) {
5485 err = got_error_from_errno("calloc");
5486 goto done;
5489 err = got_repo_pack_fds_open(&pack_fds);
5490 if (err)
5491 goto done;
5492 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5493 pack_fds);
5494 if (err)
5495 goto done;
5497 blame->pack_fds = pack_fds;
5498 blame->cb_args.view = view;
5499 blame->cb_args.lines = blame->lines;
5500 blame->cb_args.nlines = blame->nlines;
5501 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5502 if (blame->cb_args.commit_id == NULL) {
5503 err = got_error_from_errno("got_object_id_dup");
5504 goto done;
5506 blame->cb_args.quit = &s->done;
5508 blame->thread_args.path = s->path;
5509 blame->thread_args.repo = thread_repo;
5510 blame->thread_args.cb_args = &blame->cb_args;
5511 blame->thread_args.complete = &s->blame_complete;
5512 blame->thread_args.cancel_cb = cancel_blame_view;
5513 blame->thread_args.cancel_arg = &s->done;
5514 s->blame_complete = 0;
5516 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5517 s->first_displayed_line = 1;
5518 s->last_displayed_line = view->nlines;
5519 s->selected_line = 1;
5521 s->matched_line = 0;
5523 done:
5524 if (commit)
5525 got_object_commit_close(commit);
5526 if (fd != -1 && close(fd) == -1 && err == NULL)
5527 err = got_error_from_errno("close");
5528 if (blob)
5529 got_object_blob_close(blob);
5530 free(obj_id);
5531 if (err)
5532 stop_blame(blame);
5533 return err;
5536 static const struct got_error *
5537 open_blame_view(struct tog_view *view, char *path,
5538 struct got_object_id *commit_id, struct got_repository *repo)
5540 const struct got_error *err = NULL;
5541 struct tog_blame_view_state *s = &view->state.blame;
5543 STAILQ_INIT(&s->blamed_commits);
5545 s->path = strdup(path);
5546 if (s->path == NULL)
5547 return got_error_from_errno("strdup");
5549 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5550 if (err) {
5551 free(s->path);
5552 return err;
5555 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5556 s->first_displayed_line = 1;
5557 s->last_displayed_line = view->nlines;
5558 s->selected_line = 1;
5559 s->blame_complete = 0;
5560 s->repo = repo;
5561 s->commit_id = commit_id;
5562 memset(&s->blame, 0, sizeof(s->blame));
5564 STAILQ_INIT(&s->colors);
5565 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5566 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5567 get_color_value("TOG_COLOR_COMMIT"));
5568 if (err)
5569 return err;
5572 view->show = show_blame_view;
5573 view->input = input_blame_view;
5574 view->reset = reset_blame_view;
5575 view->close = close_blame_view;
5576 view->search_start = search_start_blame_view;
5577 view->search_next = search_next_blame_view;
5579 return run_blame(view);
5582 static const struct got_error *
5583 close_blame_view(struct tog_view *view)
5585 const struct got_error *err = NULL;
5586 struct tog_blame_view_state *s = &view->state.blame;
5588 if (s->blame.thread)
5589 err = stop_blame(&s->blame);
5591 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5592 struct got_object_qid *blamed_commit;
5593 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5594 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5595 got_object_qid_free(blamed_commit);
5598 free(s->path);
5599 free_colors(&s->colors);
5600 return err;
5603 static const struct got_error *
5604 search_start_blame_view(struct tog_view *view)
5606 struct tog_blame_view_state *s = &view->state.blame;
5608 s->matched_line = 0;
5609 return NULL;
5612 static const struct got_error *
5613 search_next_blame_view(struct tog_view *view)
5615 struct tog_blame_view_state *s = &view->state.blame;
5616 const struct got_error *err = NULL;
5617 int lineno;
5618 char *line = NULL;
5619 size_t linesize = 0;
5620 ssize_t linelen;
5622 if (!view->searching) {
5623 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5624 return NULL;
5627 if (s->matched_line) {
5628 if (view->searching == TOG_SEARCH_FORWARD)
5629 lineno = s->matched_line + 1;
5630 else
5631 lineno = s->matched_line - 1;
5632 } else
5633 lineno = s->first_displayed_line - 1 + s->selected_line;
5635 while (1) {
5636 off_t offset;
5638 if (lineno <= 0 || lineno > s->blame.nlines) {
5639 if (s->matched_line == 0) {
5640 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5641 break;
5644 if (view->searching == TOG_SEARCH_FORWARD)
5645 lineno = 1;
5646 else
5647 lineno = s->blame.nlines;
5650 offset = s->blame.line_offsets[lineno - 1];
5651 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5652 free(line);
5653 return got_error_from_errno("fseeko");
5655 linelen = getline(&line, &linesize, s->blame.f);
5656 if (linelen != -1) {
5657 char *exstr;
5658 err = expand_tab(&exstr, line);
5659 if (err)
5660 break;
5661 if (match_line(exstr, &view->regex, 1,
5662 &view->regmatch)) {
5663 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5664 s->matched_line = lineno;
5665 free(exstr);
5666 break;
5668 free(exstr);
5670 if (view->searching == TOG_SEARCH_FORWARD)
5671 lineno++;
5672 else
5673 lineno--;
5675 free(line);
5677 if (s->matched_line) {
5678 s->first_displayed_line = s->matched_line;
5679 s->selected_line = 1;
5682 return err;
5685 static const struct got_error *
5686 show_blame_view(struct tog_view *view)
5688 const struct got_error *err = NULL;
5689 struct tog_blame_view_state *s = &view->state.blame;
5690 int errcode;
5692 if (s->blame.thread == 0 && !s->blame_complete) {
5693 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5694 &s->blame.thread_args);
5695 if (errcode)
5696 return got_error_set_errno(errcode, "pthread_create");
5698 halfdelay(1); /* fast refresh while annotating */
5701 if (s->blame_complete)
5702 halfdelay(10); /* disable fast refresh */
5704 err = draw_blame(view);
5706 view_border(view);
5707 return err;
5710 static const struct got_error *
5711 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5713 const struct got_error *err = NULL, *thread_err = NULL;
5714 struct tog_view *diff_view;
5715 struct tog_blame_view_state *s = &view->state.blame;
5716 int eos, nscroll, begin_y = 0, begin_x = 0;
5718 eos = nscroll = view->nlines - 2;
5719 if (view_is_hsplit_top(view))
5720 --eos; /* border */
5722 switch (ch) {
5723 case '0':
5724 view->x = 0;
5725 break;
5726 case '$':
5727 view->x = MAX(view->maxx - view->ncols / 3, 0);
5728 view->count = 0;
5729 break;
5730 case KEY_RIGHT:
5731 case 'l':
5732 if (view->x + view->ncols / 3 < view->maxx)
5733 view->x += 2; /* move two columns right */
5734 else
5735 view->count = 0;
5736 break;
5737 case KEY_LEFT:
5738 case 'h':
5739 view->x -= MIN(view->x, 2); /* move two columns back */
5740 if (view->x <= 0)
5741 view->count = 0;
5742 break;
5743 case 'q':
5744 s->done = 1;
5745 break;
5746 case 'g':
5747 case KEY_HOME:
5748 s->selected_line = 1;
5749 s->first_displayed_line = 1;
5750 view->count = 0;
5751 break;
5752 case 'G':
5753 case KEY_END:
5754 if (s->blame.nlines < eos) {
5755 s->selected_line = s->blame.nlines;
5756 s->first_displayed_line = 1;
5757 } else {
5758 s->selected_line = eos;
5759 s->first_displayed_line = s->blame.nlines - (eos - 1);
5761 view->count = 0;
5762 break;
5763 case 'k':
5764 case KEY_UP:
5765 case CTRL('p'):
5766 if (s->selected_line > 1)
5767 s->selected_line--;
5768 else if (s->selected_line == 1 &&
5769 s->first_displayed_line > 1)
5770 s->first_displayed_line--;
5771 else
5772 view->count = 0;
5773 break;
5774 case CTRL('u'):
5775 case 'u':
5776 nscroll /= 2;
5777 /* FALL THROUGH */
5778 case KEY_PPAGE:
5779 case CTRL('b'):
5780 case 'b':
5781 if (s->first_displayed_line == 1) {
5782 if (view->count > 1)
5783 nscroll += nscroll;
5784 s->selected_line = MAX(1, s->selected_line - nscroll);
5785 view->count = 0;
5786 break;
5788 if (s->first_displayed_line > nscroll)
5789 s->first_displayed_line -= nscroll;
5790 else
5791 s->first_displayed_line = 1;
5792 break;
5793 case 'j':
5794 case KEY_DOWN:
5795 case CTRL('n'):
5796 if (s->selected_line < eos && s->first_displayed_line +
5797 s->selected_line <= s->blame.nlines)
5798 s->selected_line++;
5799 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5800 s->first_displayed_line++;
5801 else
5802 view->count = 0;
5803 break;
5804 case 'c':
5805 case 'p': {
5806 struct got_object_id *id = NULL;
5808 view->count = 0;
5809 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5810 s->first_displayed_line, s->selected_line);
5811 if (id == NULL)
5812 break;
5813 if (ch == 'p') {
5814 struct got_commit_object *commit, *pcommit;
5815 struct got_object_qid *pid;
5816 struct got_object_id *blob_id = NULL;
5817 int obj_type;
5818 err = got_object_open_as_commit(&commit,
5819 s->repo, id);
5820 if (err)
5821 break;
5822 pid = STAILQ_FIRST(
5823 got_object_commit_get_parent_ids(commit));
5824 if (pid == NULL) {
5825 got_object_commit_close(commit);
5826 break;
5828 /* Check if path history ends here. */
5829 err = got_object_open_as_commit(&pcommit,
5830 s->repo, &pid->id);
5831 if (err)
5832 break;
5833 err = got_object_id_by_path(&blob_id, s->repo,
5834 pcommit, s->path);
5835 got_object_commit_close(pcommit);
5836 if (err) {
5837 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5838 err = NULL;
5839 got_object_commit_close(commit);
5840 break;
5842 err = got_object_get_type(&obj_type, s->repo,
5843 blob_id);
5844 free(blob_id);
5845 /* Can't blame non-blob type objects. */
5846 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5847 got_object_commit_close(commit);
5848 break;
5850 err = got_object_qid_alloc(&s->blamed_commit,
5851 &pid->id);
5852 got_object_commit_close(commit);
5853 } else {
5854 if (got_object_id_cmp(id,
5855 &s->blamed_commit->id) == 0)
5856 break;
5857 err = got_object_qid_alloc(&s->blamed_commit,
5858 id);
5860 if (err)
5861 break;
5862 s->done = 1;
5863 thread_err = stop_blame(&s->blame);
5864 s->done = 0;
5865 if (thread_err)
5866 break;
5867 STAILQ_INSERT_HEAD(&s->blamed_commits,
5868 s->blamed_commit, entry);
5869 err = run_blame(view);
5870 if (err)
5871 break;
5872 break;
5874 case 'C': {
5875 struct got_object_qid *first;
5877 view->count = 0;
5878 first = STAILQ_FIRST(&s->blamed_commits);
5879 if (!got_object_id_cmp(&first->id, s->commit_id))
5880 break;
5881 s->done = 1;
5882 thread_err = stop_blame(&s->blame);
5883 s->done = 0;
5884 if (thread_err)
5885 break;
5886 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5887 got_object_qid_free(s->blamed_commit);
5888 s->blamed_commit =
5889 STAILQ_FIRST(&s->blamed_commits);
5890 err = run_blame(view);
5891 if (err)
5892 break;
5893 break;
5895 case KEY_ENTER:
5896 case '\r': {
5897 struct got_object_id *id = NULL;
5898 struct got_object_qid *pid;
5899 struct got_commit_object *commit = NULL;
5901 view->count = 0;
5902 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5903 s->first_displayed_line, s->selected_line);
5904 if (id == NULL)
5905 break;
5906 err = got_object_open_as_commit(&commit, s->repo, id);
5907 if (err)
5908 break;
5909 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5910 if (*new_view) {
5911 /* traversed from diff view, release diff resources */
5912 err = close_diff_view(*new_view);
5913 if (err)
5914 break;
5915 diff_view = *new_view;
5916 } else {
5917 if (view_is_parent_view(view))
5918 view_get_split(view, &begin_y, &begin_x);
5920 diff_view = view_open(0, 0, begin_y, begin_x,
5921 TOG_VIEW_DIFF);
5922 if (diff_view == NULL) {
5923 got_object_commit_close(commit);
5924 err = got_error_from_errno("view_open");
5925 break;
5928 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5929 id, NULL, NULL, 3, 0, 0, view, s->repo);
5930 got_object_commit_close(commit);
5931 if (err) {
5932 view_close(diff_view);
5933 break;
5935 s->last_diffed_line = s->first_displayed_line - 1 +
5936 s->selected_line;
5937 if (*new_view)
5938 break; /* still open from active diff view */
5939 if (view_is_parent_view(view) &&
5940 view->mode == TOG_VIEW_SPLIT_HRZN) {
5941 err = view_init_hsplit(view, begin_y);
5942 if (err)
5943 break;
5946 view->focussed = 0;
5947 diff_view->focussed = 1;
5948 diff_view->mode = view->mode;
5949 diff_view->nlines = view->lines - begin_y;
5950 if (view_is_parent_view(view)) {
5951 view_transfer_size(diff_view, view);
5952 err = view_close_child(view);
5953 if (err)
5954 break;
5955 err = view_set_child(view, diff_view);
5956 if (err)
5957 break;
5958 view->focus_child = 1;
5959 } else
5960 *new_view = diff_view;
5961 if (err)
5962 break;
5963 break;
5965 case CTRL('d'):
5966 case 'd':
5967 nscroll /= 2;
5968 /* FALL THROUGH */
5969 case KEY_NPAGE:
5970 case CTRL('f'):
5971 case 'f':
5972 case ' ':
5973 if (s->last_displayed_line >= s->blame.nlines &&
5974 s->selected_line >= MIN(s->blame.nlines,
5975 view->nlines - 2)) {
5976 view->count = 0;
5977 break;
5979 if (s->last_displayed_line >= s->blame.nlines &&
5980 s->selected_line < view->nlines - 2) {
5981 s->selected_line +=
5982 MIN(nscroll, s->last_displayed_line -
5983 s->first_displayed_line - s->selected_line + 1);
5985 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5986 s->first_displayed_line += nscroll;
5987 else
5988 s->first_displayed_line =
5989 s->blame.nlines - (view->nlines - 3);
5990 break;
5991 case KEY_RESIZE:
5992 if (s->selected_line > view->nlines - 2) {
5993 s->selected_line = MIN(s->blame.nlines,
5994 view->nlines - 2);
5996 break;
5997 default:
5998 view->count = 0;
5999 break;
6001 return thread_err ? thread_err : err;
6004 static const struct got_error *
6005 reset_blame_view(struct tog_view *view)
6007 const struct got_error *err;
6008 struct tog_blame_view_state *s = &view->state.blame;
6010 view->count = 0;
6011 s->done = 1;
6012 err = stop_blame(&s->blame);
6013 s->done = 0;
6014 if (err)
6015 return err;
6016 return run_blame(view);
6019 static const struct got_error *
6020 cmd_blame(int argc, char *argv[])
6022 const struct got_error *error;
6023 struct got_repository *repo = NULL;
6024 struct got_worktree *worktree = NULL;
6025 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6026 char *link_target = NULL;
6027 struct got_object_id *commit_id = NULL;
6028 struct got_commit_object *commit = NULL;
6029 char *commit_id_str = NULL;
6030 int ch;
6031 struct tog_view *view;
6032 int *pack_fds = NULL;
6034 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6035 switch (ch) {
6036 case 'c':
6037 commit_id_str = optarg;
6038 break;
6039 case 'r':
6040 repo_path = realpath(optarg, NULL);
6041 if (repo_path == NULL)
6042 return got_error_from_errno2("realpath",
6043 optarg);
6044 break;
6045 default:
6046 usage_blame();
6047 /* NOTREACHED */
6051 argc -= optind;
6052 argv += optind;
6054 if (argc != 1)
6055 usage_blame();
6057 error = got_repo_pack_fds_open(&pack_fds);
6058 if (error != NULL)
6059 goto done;
6061 if (repo_path == NULL) {
6062 cwd = getcwd(NULL, 0);
6063 if (cwd == NULL)
6064 return got_error_from_errno("getcwd");
6065 error = got_worktree_open(&worktree, cwd);
6066 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6067 goto done;
6068 if (worktree)
6069 repo_path =
6070 strdup(got_worktree_get_repo_path(worktree));
6071 else
6072 repo_path = strdup(cwd);
6073 if (repo_path == NULL) {
6074 error = got_error_from_errno("strdup");
6075 goto done;
6079 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6080 if (error != NULL)
6081 goto done;
6083 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6084 worktree);
6085 if (error)
6086 goto done;
6088 init_curses();
6090 error = apply_unveil(got_repo_get_path(repo), NULL);
6091 if (error)
6092 goto done;
6094 error = tog_load_refs(repo, 0);
6095 if (error)
6096 goto done;
6098 if (commit_id_str == NULL) {
6099 struct got_reference *head_ref;
6100 error = got_ref_open(&head_ref, repo, worktree ?
6101 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6102 if (error != NULL)
6103 goto done;
6104 error = got_ref_resolve(&commit_id, repo, head_ref);
6105 got_ref_close(head_ref);
6106 } else {
6107 error = got_repo_match_object_id(&commit_id, NULL,
6108 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6110 if (error != NULL)
6111 goto done;
6113 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6114 if (view == NULL) {
6115 error = got_error_from_errno("view_open");
6116 goto done;
6119 error = got_object_open_as_commit(&commit, repo, commit_id);
6120 if (error)
6121 goto done;
6123 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6124 commit, repo);
6125 if (error)
6126 goto done;
6128 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6129 commit_id, repo);
6130 if (error)
6131 goto done;
6132 if (worktree) {
6133 /* Release work tree lock. */
6134 got_worktree_close(worktree);
6135 worktree = NULL;
6137 error = view_loop(view);
6138 done:
6139 free(repo_path);
6140 free(in_repo_path);
6141 free(link_target);
6142 free(cwd);
6143 free(commit_id);
6144 if (commit)
6145 got_object_commit_close(commit);
6146 if (worktree)
6147 got_worktree_close(worktree);
6148 if (repo) {
6149 const struct got_error *close_err = got_repo_close(repo);
6150 if (error == NULL)
6151 error = close_err;
6153 if (pack_fds) {
6154 const struct got_error *pack_err =
6155 got_repo_pack_fds_close(pack_fds);
6156 if (error == NULL)
6157 error = pack_err;
6159 tog_free_refs();
6160 return error;
6163 static const struct got_error *
6164 draw_tree_entries(struct tog_view *view, const char *parent_path)
6166 struct tog_tree_view_state *s = &view->state.tree;
6167 const struct got_error *err = NULL;
6168 struct got_tree_entry *te;
6169 wchar_t *wline;
6170 struct tog_color *tc;
6171 int width, n, i, nentries;
6172 int limit = view->nlines;
6174 s->ndisplayed = 0;
6175 if (view_is_hsplit_top(view))
6176 --limit; /* border */
6178 werase(view->window);
6180 if (limit == 0)
6181 return NULL;
6183 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6184 0, 0);
6185 if (err)
6186 return err;
6187 if (view_needs_focus_indication(view))
6188 wstandout(view->window);
6189 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6190 if (tc)
6191 wattr_on(view->window,
6192 COLOR_PAIR(tc->colorpair), NULL);
6193 waddwstr(view->window, wline);
6194 if (tc)
6195 wattr_off(view->window,
6196 COLOR_PAIR(tc->colorpair), NULL);
6197 if (view_needs_focus_indication(view))
6198 wstandend(view->window);
6199 free(wline);
6200 wline = NULL;
6201 if (width < view->ncols - 1)
6202 waddch(view->window, '\n');
6203 if (--limit <= 0)
6204 return NULL;
6205 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6206 0, 0);
6207 if (err)
6208 return err;
6209 waddwstr(view->window, wline);
6210 free(wline);
6211 wline = NULL;
6212 if (width < view->ncols - 1)
6213 waddch(view->window, '\n');
6214 if (--limit <= 0)
6215 return NULL;
6216 waddch(view->window, '\n');
6217 if (--limit <= 0)
6218 return NULL;
6220 if (s->first_displayed_entry == NULL) {
6221 te = got_object_tree_get_first_entry(s->tree);
6222 if (s->selected == 0) {
6223 if (view->focussed)
6224 wstandout(view->window);
6225 s->selected_entry = NULL;
6227 waddstr(view->window, " ..\n"); /* parent directory */
6228 if (s->selected == 0 && view->focussed)
6229 wstandend(view->window);
6230 s->ndisplayed++;
6231 if (--limit <= 0)
6232 return NULL;
6233 n = 1;
6234 } else {
6235 n = 0;
6236 te = s->first_displayed_entry;
6239 nentries = got_object_tree_get_nentries(s->tree);
6240 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6241 char *line = NULL, *id_str = NULL, *link_target = NULL;
6242 const char *modestr = "";
6243 mode_t mode;
6245 te = got_object_tree_get_entry(s->tree, i);
6246 mode = got_tree_entry_get_mode(te);
6248 if (s->show_ids) {
6249 err = got_object_id_str(&id_str,
6250 got_tree_entry_get_id(te));
6251 if (err)
6252 return got_error_from_errno(
6253 "got_object_id_str");
6255 if (got_object_tree_entry_is_submodule(te))
6256 modestr = "$";
6257 else if (S_ISLNK(mode)) {
6258 int i;
6260 err = got_tree_entry_get_symlink_target(&link_target,
6261 te, s->repo);
6262 if (err) {
6263 free(id_str);
6264 return err;
6266 for (i = 0; i < strlen(link_target); i++) {
6267 if (!isprint((unsigned char)link_target[i]))
6268 link_target[i] = '?';
6270 modestr = "@";
6272 else if (S_ISDIR(mode))
6273 modestr = "/";
6274 else if (mode & S_IXUSR)
6275 modestr = "*";
6276 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6277 got_tree_entry_get_name(te), modestr,
6278 link_target ? " -> ": "",
6279 link_target ? link_target : "") == -1) {
6280 free(id_str);
6281 free(link_target);
6282 return got_error_from_errno("asprintf");
6284 free(id_str);
6285 free(link_target);
6286 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6287 0, 0);
6288 if (err) {
6289 free(line);
6290 break;
6292 if (n == s->selected) {
6293 if (view->focussed)
6294 wstandout(view->window);
6295 s->selected_entry = te;
6297 tc = match_color(&s->colors, line);
6298 if (tc)
6299 wattr_on(view->window,
6300 COLOR_PAIR(tc->colorpair), NULL);
6301 waddwstr(view->window, wline);
6302 if (tc)
6303 wattr_off(view->window,
6304 COLOR_PAIR(tc->colorpair), NULL);
6305 if (width < view->ncols - 1)
6306 waddch(view->window, '\n');
6307 if (n == s->selected && view->focussed)
6308 wstandend(view->window);
6309 free(line);
6310 free(wline);
6311 wline = NULL;
6312 n++;
6313 s->ndisplayed++;
6314 s->last_displayed_entry = te;
6315 if (--limit <= 0)
6316 break;
6319 return err;
6322 static void
6323 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6325 struct got_tree_entry *te;
6326 int isroot = s->tree == s->root;
6327 int i = 0;
6329 if (s->first_displayed_entry == NULL)
6330 return;
6332 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6333 while (i++ < maxscroll) {
6334 if (te == NULL) {
6335 if (!isroot)
6336 s->first_displayed_entry = NULL;
6337 break;
6339 s->first_displayed_entry = te;
6340 te = got_tree_entry_get_prev(s->tree, te);
6344 static const struct got_error *
6345 tree_scroll_down(struct tog_view *view, int maxscroll)
6347 struct tog_tree_view_state *s = &view->state.tree;
6348 struct got_tree_entry *next, *last;
6349 int n = 0;
6351 if (s->first_displayed_entry)
6352 next = got_tree_entry_get_next(s->tree,
6353 s->first_displayed_entry);
6354 else
6355 next = got_object_tree_get_first_entry(s->tree);
6357 last = s->last_displayed_entry;
6358 while (next && n++ < maxscroll) {
6359 if (last)
6360 last = got_tree_entry_get_next(s->tree, last);
6361 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6362 s->first_displayed_entry = next;
6363 next = got_tree_entry_get_next(s->tree, next);
6367 return NULL;
6370 static const struct got_error *
6371 tree_entry_path(char **path, struct tog_parent_trees *parents,
6372 struct got_tree_entry *te)
6374 const struct got_error *err = NULL;
6375 struct tog_parent_tree *pt;
6376 size_t len = 2; /* for leading slash and NUL */
6378 TAILQ_FOREACH(pt, parents, entry)
6379 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6380 + 1 /* slash */;
6381 if (te)
6382 len += strlen(got_tree_entry_get_name(te));
6384 *path = calloc(1, len);
6385 if (path == NULL)
6386 return got_error_from_errno("calloc");
6388 (*path)[0] = '/';
6389 pt = TAILQ_LAST(parents, tog_parent_trees);
6390 while (pt) {
6391 const char *name = got_tree_entry_get_name(pt->selected_entry);
6392 if (strlcat(*path, name, len) >= len) {
6393 err = got_error(GOT_ERR_NO_SPACE);
6394 goto done;
6396 if (strlcat(*path, "/", len) >= len) {
6397 err = got_error(GOT_ERR_NO_SPACE);
6398 goto done;
6400 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6402 if (te) {
6403 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6404 err = got_error(GOT_ERR_NO_SPACE);
6405 goto done;
6408 done:
6409 if (err) {
6410 free(*path);
6411 *path = NULL;
6413 return err;
6416 static const struct got_error *
6417 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6418 struct got_tree_entry *te, struct tog_parent_trees *parents,
6419 struct got_object_id *commit_id, struct got_repository *repo)
6421 const struct got_error *err = NULL;
6422 char *path;
6423 struct tog_view *blame_view;
6425 *new_view = NULL;
6427 err = tree_entry_path(&path, parents, te);
6428 if (err)
6429 return err;
6431 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6432 if (blame_view == NULL) {
6433 err = got_error_from_errno("view_open");
6434 goto done;
6437 err = open_blame_view(blame_view, path, commit_id, repo);
6438 if (err) {
6439 if (err->code == GOT_ERR_CANCELLED)
6440 err = NULL;
6441 view_close(blame_view);
6442 } else
6443 *new_view = blame_view;
6444 done:
6445 free(path);
6446 return err;
6449 static const struct got_error *
6450 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6451 struct tog_tree_view_state *s)
6453 struct tog_view *log_view;
6454 const struct got_error *err = NULL;
6455 char *path;
6457 *new_view = NULL;
6459 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6460 if (log_view == NULL)
6461 return got_error_from_errno("view_open");
6463 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6464 if (err)
6465 return err;
6467 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6468 path, 0);
6469 if (err)
6470 view_close(log_view);
6471 else
6472 *new_view = log_view;
6473 free(path);
6474 return err;
6477 static const struct got_error *
6478 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6479 const char *head_ref_name, struct got_repository *repo)
6481 const struct got_error *err = NULL;
6482 char *commit_id_str = NULL;
6483 struct tog_tree_view_state *s = &view->state.tree;
6484 struct got_commit_object *commit = NULL;
6486 TAILQ_INIT(&s->parents);
6487 STAILQ_INIT(&s->colors);
6489 s->commit_id = got_object_id_dup(commit_id);
6490 if (s->commit_id == NULL)
6491 return got_error_from_errno("got_object_id_dup");
6493 err = got_object_open_as_commit(&commit, repo, commit_id);
6494 if (err)
6495 goto done;
6498 * The root is opened here and will be closed when the view is closed.
6499 * Any visited subtrees and their path-wise parents are opened and
6500 * closed on demand.
6502 err = got_object_open_as_tree(&s->root, repo,
6503 got_object_commit_get_tree_id(commit));
6504 if (err)
6505 goto done;
6506 s->tree = s->root;
6508 err = got_object_id_str(&commit_id_str, commit_id);
6509 if (err != NULL)
6510 goto done;
6512 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6513 err = got_error_from_errno("asprintf");
6514 goto done;
6517 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6518 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6519 if (head_ref_name) {
6520 s->head_ref_name = strdup(head_ref_name);
6521 if (s->head_ref_name == NULL) {
6522 err = got_error_from_errno("strdup");
6523 goto done;
6526 s->repo = repo;
6528 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6529 err = add_color(&s->colors, "\\$$",
6530 TOG_COLOR_TREE_SUBMODULE,
6531 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6532 if (err)
6533 goto done;
6534 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6535 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6536 if (err)
6537 goto done;
6538 err = add_color(&s->colors, "/$",
6539 TOG_COLOR_TREE_DIRECTORY,
6540 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6541 if (err)
6542 goto done;
6544 err = add_color(&s->colors, "\\*$",
6545 TOG_COLOR_TREE_EXECUTABLE,
6546 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6547 if (err)
6548 goto done;
6550 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6551 get_color_value("TOG_COLOR_COMMIT"));
6552 if (err)
6553 goto done;
6556 view->show = show_tree_view;
6557 view->input = input_tree_view;
6558 view->close = close_tree_view;
6559 view->search_start = search_start_tree_view;
6560 view->search_next = search_next_tree_view;
6561 done:
6562 free(commit_id_str);
6563 if (commit)
6564 got_object_commit_close(commit);
6565 if (err)
6566 close_tree_view(view);
6567 return err;
6570 static const struct got_error *
6571 close_tree_view(struct tog_view *view)
6573 struct tog_tree_view_state *s = &view->state.tree;
6575 free_colors(&s->colors);
6576 free(s->tree_label);
6577 s->tree_label = NULL;
6578 free(s->commit_id);
6579 s->commit_id = NULL;
6580 free(s->head_ref_name);
6581 s->head_ref_name = NULL;
6582 while (!TAILQ_EMPTY(&s->parents)) {
6583 struct tog_parent_tree *parent;
6584 parent = TAILQ_FIRST(&s->parents);
6585 TAILQ_REMOVE(&s->parents, parent, entry);
6586 if (parent->tree != s->root)
6587 got_object_tree_close(parent->tree);
6588 free(parent);
6591 if (s->tree != NULL && s->tree != s->root)
6592 got_object_tree_close(s->tree);
6593 if (s->root)
6594 got_object_tree_close(s->root);
6595 return NULL;
6598 static const struct got_error *
6599 search_start_tree_view(struct tog_view *view)
6601 struct tog_tree_view_state *s = &view->state.tree;
6603 s->matched_entry = NULL;
6604 return NULL;
6607 static int
6608 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6610 regmatch_t regmatch;
6612 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6613 0) == 0;
6616 static const struct got_error *
6617 search_next_tree_view(struct tog_view *view)
6619 struct tog_tree_view_state *s = &view->state.tree;
6620 struct got_tree_entry *te = NULL;
6622 if (!view->searching) {
6623 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6624 return NULL;
6627 if (s->matched_entry) {
6628 if (view->searching == TOG_SEARCH_FORWARD) {
6629 if (s->selected_entry)
6630 te = got_tree_entry_get_next(s->tree,
6631 s->selected_entry);
6632 else
6633 te = got_object_tree_get_first_entry(s->tree);
6634 } else {
6635 if (s->selected_entry == NULL)
6636 te = got_object_tree_get_last_entry(s->tree);
6637 else
6638 te = got_tree_entry_get_prev(s->tree,
6639 s->selected_entry);
6641 } else {
6642 if (s->selected_entry)
6643 te = s->selected_entry;
6644 else if (view->searching == TOG_SEARCH_FORWARD)
6645 te = got_object_tree_get_first_entry(s->tree);
6646 else
6647 te = got_object_tree_get_last_entry(s->tree);
6650 while (1) {
6651 if (te == NULL) {
6652 if (s->matched_entry == NULL) {
6653 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6654 return NULL;
6656 if (view->searching == TOG_SEARCH_FORWARD)
6657 te = got_object_tree_get_first_entry(s->tree);
6658 else
6659 te = got_object_tree_get_last_entry(s->tree);
6662 if (match_tree_entry(te, &view->regex)) {
6663 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6664 s->matched_entry = te;
6665 break;
6668 if (view->searching == TOG_SEARCH_FORWARD)
6669 te = got_tree_entry_get_next(s->tree, te);
6670 else
6671 te = got_tree_entry_get_prev(s->tree, te);
6674 if (s->matched_entry) {
6675 s->first_displayed_entry = s->matched_entry;
6676 s->selected = 0;
6679 return NULL;
6682 static const struct got_error *
6683 show_tree_view(struct tog_view *view)
6685 const struct got_error *err = NULL;
6686 struct tog_tree_view_state *s = &view->state.tree;
6687 char *parent_path;
6689 err = tree_entry_path(&parent_path, &s->parents, NULL);
6690 if (err)
6691 return err;
6693 err = draw_tree_entries(view, parent_path);
6694 free(parent_path);
6696 view_border(view);
6697 return err;
6700 static const struct got_error *
6701 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6703 const struct got_error *err = NULL;
6704 struct tog_tree_view_state *s = &view->state.tree;
6705 struct tog_view *log_view, *ref_view;
6706 struct got_tree_entry *te;
6707 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 3;
6709 switch (ch) {
6710 case 'i':
6711 s->show_ids = !s->show_ids;
6712 view->count = 0;
6713 break;
6714 case 'l':
6715 view->count = 0;
6716 if (!s->selected_entry)
6717 break;
6718 if (view_is_parent_view(view))
6719 view_get_split(view, &begin_y, &begin_x);
6720 err = log_selected_tree_entry(&log_view, begin_y, begin_x, s);
6721 if (view_is_parent_view(view) &&
6722 view->mode == TOG_VIEW_SPLIT_HRZN) {
6723 err = view_init_hsplit(view, begin_y);
6724 if (err)
6725 break;
6727 view->focussed = 0;
6728 log_view->focussed = 1;
6729 log_view->mode = view->mode;
6730 log_view->nlines = view->lines - begin_y;
6731 if (view_is_parent_view(view)) {
6732 view_transfer_size(log_view, view);
6733 err = view_close_child(view);
6734 if (err)
6735 return err;
6736 err = view_set_child(view, log_view);
6737 if (err)
6738 return err;
6739 view->focus_child = 1;
6740 } else
6741 *new_view = log_view;
6742 break;
6743 case 'r':
6744 view->count = 0;
6745 if (view_is_parent_view(view))
6746 view_get_split(view, &begin_y, &begin_x);
6747 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
6748 if (ref_view == NULL)
6749 return got_error_from_errno("view_open");
6750 err = open_ref_view(ref_view, s->repo);
6751 if (err) {
6752 view_close(ref_view);
6753 return err;
6755 if (view_is_parent_view(view) &&
6756 view->mode == TOG_VIEW_SPLIT_HRZN) {
6757 err = view_init_hsplit(view, begin_y);
6758 if (err)
6759 break;
6761 view->focussed = 0;
6762 ref_view->focussed = 1;
6763 ref_view->mode = view->mode;
6764 ref_view->nlines = view->lines - begin_y;
6765 if (view_is_parent_view(view)) {
6766 view_transfer_size(ref_view, view);
6767 err = view_close_child(view);
6768 if (err)
6769 return err;
6770 err = view_set_child(view, ref_view);
6771 if (err)
6772 return err;
6773 view->focus_child = 1;
6774 } else
6775 *new_view = ref_view;
6776 break;
6777 case 'g':
6778 case KEY_HOME:
6779 s->selected = 0;
6780 view->count = 0;
6781 if (s->tree == s->root)
6782 s->first_displayed_entry =
6783 got_object_tree_get_first_entry(s->tree);
6784 else
6785 s->first_displayed_entry = NULL;
6786 break;
6787 case 'G':
6788 case KEY_END: {
6789 int eos = view->nlines - 3;
6791 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6792 --eos; /* border */
6793 s->selected = 0;
6794 view->count = 0;
6795 te = got_object_tree_get_last_entry(s->tree);
6796 for (n = 0; n < eos; n++) {
6797 if (te == NULL) {
6798 if(s->tree != s->root) {
6799 s->first_displayed_entry = NULL;
6800 n++;
6802 break;
6804 s->first_displayed_entry = te;
6805 te = got_tree_entry_get_prev(s->tree, te);
6807 if (n > 0)
6808 s->selected = n - 1;
6809 break;
6811 case 'k':
6812 case KEY_UP:
6813 case CTRL('p'):
6814 if (s->selected > 0) {
6815 s->selected--;
6816 break;
6818 tree_scroll_up(s, 1);
6819 if (s->selected_entry == NULL ||
6820 (s->tree == s->root && s->selected_entry ==
6821 got_object_tree_get_first_entry(s->tree)))
6822 view->count = 0;
6823 break;
6824 case CTRL('u'):
6825 case 'u':
6826 nscroll /= 2;
6827 /* FALL THROUGH */
6828 case KEY_PPAGE:
6829 case CTRL('b'):
6830 case 'b':
6831 if (s->tree == s->root) {
6832 if (got_object_tree_get_first_entry(s->tree) ==
6833 s->first_displayed_entry)
6834 s->selected -= MIN(s->selected, nscroll);
6835 } else {
6836 if (s->first_displayed_entry == NULL)
6837 s->selected -= MIN(s->selected, nscroll);
6839 tree_scroll_up(s, MAX(0, nscroll));
6840 if (s->selected_entry == NULL ||
6841 (s->tree == s->root && s->selected_entry ==
6842 got_object_tree_get_first_entry(s->tree)))
6843 view->count = 0;
6844 break;
6845 case 'j':
6846 case KEY_DOWN:
6847 case CTRL('n'):
6848 if (s->selected < s->ndisplayed - 1) {
6849 s->selected++;
6850 break;
6852 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6853 == NULL) {
6854 /* can't scroll any further */
6855 view->count = 0;
6856 break;
6858 tree_scroll_down(view, 1);
6859 break;
6860 case CTRL('d'):
6861 case 'd':
6862 nscroll /= 2;
6863 /* FALL THROUGH */
6864 case KEY_NPAGE:
6865 case CTRL('f'):
6866 case 'f':
6867 case ' ':
6868 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6869 == NULL) {
6870 /* can't scroll any further; move cursor down */
6871 if (s->selected < s->ndisplayed - 1)
6872 s->selected += MIN(nscroll,
6873 s->ndisplayed - s->selected - 1);
6874 else
6875 view->count = 0;
6876 break;
6878 tree_scroll_down(view, nscroll);
6879 break;
6880 case KEY_ENTER:
6881 case '\r':
6882 case KEY_BACKSPACE:
6883 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6884 struct tog_parent_tree *parent;
6885 /* user selected '..' */
6886 if (s->tree == s->root) {
6887 view->count = 0;
6888 break;
6890 parent = TAILQ_FIRST(&s->parents);
6891 TAILQ_REMOVE(&s->parents, parent,
6892 entry);
6893 got_object_tree_close(s->tree);
6894 s->tree = parent->tree;
6895 s->first_displayed_entry =
6896 parent->first_displayed_entry;
6897 s->selected_entry =
6898 parent->selected_entry;
6899 s->selected = parent->selected;
6900 if (s->selected > view->nlines - 3) {
6901 err = offset_selection_down(view);
6902 if (err)
6903 break;
6905 free(parent);
6906 } else if (S_ISDIR(got_tree_entry_get_mode(
6907 s->selected_entry))) {
6908 struct got_tree_object *subtree;
6909 view->count = 0;
6910 err = got_object_open_as_tree(&subtree, s->repo,
6911 got_tree_entry_get_id(s->selected_entry));
6912 if (err)
6913 break;
6914 err = tree_view_visit_subtree(s, subtree);
6915 if (err) {
6916 got_object_tree_close(subtree);
6917 break;
6919 } else if (S_ISREG(got_tree_entry_get_mode(
6920 s->selected_entry))) {
6921 struct tog_view *blame_view;
6922 int begin_x = 0, begin_y = 0;
6924 if (view_is_parent_view(view))
6925 view_get_split(view, &begin_y, &begin_x);
6927 err = blame_tree_entry(&blame_view, begin_y, begin_x,
6928 s->selected_entry, &s->parents,
6929 s->commit_id, s->repo);
6930 if (err)
6931 break;
6933 if (view_is_parent_view(view) &&
6934 view->mode == TOG_VIEW_SPLIT_HRZN) {
6935 err = view_init_hsplit(view, begin_y);
6936 if (err)
6937 break;
6940 view->count = 0;
6941 view->focussed = 0;
6942 blame_view->focussed = 1;
6943 blame_view->mode = view->mode;
6944 blame_view->nlines = view->lines - begin_y;
6945 if (view_is_parent_view(view)) {
6946 view_transfer_size(blame_view, view);
6947 err = view_close_child(view);
6948 if (err)
6949 return err;
6950 err = view_set_child(view, blame_view);
6951 if (err)
6952 return err;
6953 view->focus_child = 1;
6954 } else
6955 *new_view = blame_view;
6957 break;
6958 case KEY_RESIZE:
6959 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6960 s->selected = view->nlines - 4;
6961 view->count = 0;
6962 break;
6963 default:
6964 view->count = 0;
6965 break;
6968 return err;
6971 __dead static void
6972 usage_tree(void)
6974 endwin();
6975 fprintf(stderr,
6976 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6977 getprogname());
6978 exit(1);
6981 static const struct got_error *
6982 cmd_tree(int argc, char *argv[])
6984 const struct got_error *error;
6985 struct got_repository *repo = NULL;
6986 struct got_worktree *worktree = NULL;
6987 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6988 struct got_object_id *commit_id = NULL;
6989 struct got_commit_object *commit = NULL;
6990 const char *commit_id_arg = NULL;
6991 char *label = NULL;
6992 struct got_reference *ref = NULL;
6993 const char *head_ref_name = NULL;
6994 int ch;
6995 struct tog_view *view;
6996 int *pack_fds = NULL;
6998 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6999 switch (ch) {
7000 case 'c':
7001 commit_id_arg = optarg;
7002 break;
7003 case 'r':
7004 repo_path = realpath(optarg, NULL);
7005 if (repo_path == NULL)
7006 return got_error_from_errno2("realpath",
7007 optarg);
7008 break;
7009 default:
7010 usage_tree();
7011 /* NOTREACHED */
7015 argc -= optind;
7016 argv += optind;
7018 if (argc > 1)
7019 usage_tree();
7021 error = got_repo_pack_fds_open(&pack_fds);
7022 if (error != NULL)
7023 goto done;
7025 if (repo_path == NULL) {
7026 cwd = getcwd(NULL, 0);
7027 if (cwd == NULL)
7028 return got_error_from_errno("getcwd");
7029 error = got_worktree_open(&worktree, cwd);
7030 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7031 goto done;
7032 if (worktree)
7033 repo_path =
7034 strdup(got_worktree_get_repo_path(worktree));
7035 else
7036 repo_path = strdup(cwd);
7037 if (repo_path == NULL) {
7038 error = got_error_from_errno("strdup");
7039 goto done;
7043 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7044 if (error != NULL)
7045 goto done;
7047 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7048 repo, worktree);
7049 if (error)
7050 goto done;
7052 init_curses();
7054 error = apply_unveil(got_repo_get_path(repo), NULL);
7055 if (error)
7056 goto done;
7058 error = tog_load_refs(repo, 0);
7059 if (error)
7060 goto done;
7062 if (commit_id_arg == NULL) {
7063 error = got_repo_match_object_id(&commit_id, &label,
7064 worktree ? got_worktree_get_head_ref_name(worktree) :
7065 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7066 if (error)
7067 goto done;
7068 head_ref_name = label;
7069 } else {
7070 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7071 if (error == NULL)
7072 head_ref_name = got_ref_get_name(ref);
7073 else if (error->code != GOT_ERR_NOT_REF)
7074 goto done;
7075 error = got_repo_match_object_id(&commit_id, NULL,
7076 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7077 if (error)
7078 goto done;
7081 error = got_object_open_as_commit(&commit, repo, commit_id);
7082 if (error)
7083 goto done;
7085 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7086 if (view == NULL) {
7087 error = got_error_from_errno("view_open");
7088 goto done;
7090 error = open_tree_view(view, commit_id, head_ref_name, repo);
7091 if (error)
7092 goto done;
7093 if (!got_path_is_root_dir(in_repo_path)) {
7094 error = tree_view_walk_path(&view->state.tree, commit,
7095 in_repo_path);
7096 if (error)
7097 goto done;
7100 if (worktree) {
7101 /* Release work tree lock. */
7102 got_worktree_close(worktree);
7103 worktree = NULL;
7105 error = view_loop(view);
7106 done:
7107 free(repo_path);
7108 free(cwd);
7109 free(commit_id);
7110 free(label);
7111 if (ref)
7112 got_ref_close(ref);
7113 if (repo) {
7114 const struct got_error *close_err = got_repo_close(repo);
7115 if (error == NULL)
7116 error = close_err;
7118 if (pack_fds) {
7119 const struct got_error *pack_err =
7120 got_repo_pack_fds_close(pack_fds);
7121 if (error == NULL)
7122 error = pack_err;
7124 tog_free_refs();
7125 return error;
7128 static const struct got_error *
7129 ref_view_load_refs(struct tog_ref_view_state *s)
7131 struct got_reflist_entry *sre;
7132 struct tog_reflist_entry *re;
7134 s->nrefs = 0;
7135 TAILQ_FOREACH(sre, &tog_refs, entry) {
7136 if (strncmp(got_ref_get_name(sre->ref),
7137 "refs/got/", 9) == 0 &&
7138 strncmp(got_ref_get_name(sre->ref),
7139 "refs/got/backup/", 16) != 0)
7140 continue;
7142 re = malloc(sizeof(*re));
7143 if (re == NULL)
7144 return got_error_from_errno("malloc");
7146 re->ref = got_ref_dup(sre->ref);
7147 if (re->ref == NULL)
7148 return got_error_from_errno("got_ref_dup");
7149 re->idx = s->nrefs++;
7150 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7153 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7154 return NULL;
7157 static void
7158 ref_view_free_refs(struct tog_ref_view_state *s)
7160 struct tog_reflist_entry *re;
7162 while (!TAILQ_EMPTY(&s->refs)) {
7163 re = TAILQ_FIRST(&s->refs);
7164 TAILQ_REMOVE(&s->refs, re, entry);
7165 got_ref_close(re->ref);
7166 free(re);
7170 static const struct got_error *
7171 open_ref_view(struct tog_view *view, struct got_repository *repo)
7173 const struct got_error *err = NULL;
7174 struct tog_ref_view_state *s = &view->state.ref;
7176 s->selected_entry = 0;
7177 s->repo = repo;
7179 TAILQ_INIT(&s->refs);
7180 STAILQ_INIT(&s->colors);
7182 err = ref_view_load_refs(s);
7183 if (err)
7184 return err;
7186 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7187 err = add_color(&s->colors, "^refs/heads/",
7188 TOG_COLOR_REFS_HEADS,
7189 get_color_value("TOG_COLOR_REFS_HEADS"));
7190 if (err)
7191 goto done;
7193 err = add_color(&s->colors, "^refs/tags/",
7194 TOG_COLOR_REFS_TAGS,
7195 get_color_value("TOG_COLOR_REFS_TAGS"));
7196 if (err)
7197 goto done;
7199 err = add_color(&s->colors, "^refs/remotes/",
7200 TOG_COLOR_REFS_REMOTES,
7201 get_color_value("TOG_COLOR_REFS_REMOTES"));
7202 if (err)
7203 goto done;
7205 err = add_color(&s->colors, "^refs/got/backup/",
7206 TOG_COLOR_REFS_BACKUP,
7207 get_color_value("TOG_COLOR_REFS_BACKUP"));
7208 if (err)
7209 goto done;
7212 view->show = show_ref_view;
7213 view->input = input_ref_view;
7214 view->close = close_ref_view;
7215 view->search_start = search_start_ref_view;
7216 view->search_next = search_next_ref_view;
7217 done:
7218 if (err)
7219 free_colors(&s->colors);
7220 return err;
7223 static const struct got_error *
7224 close_ref_view(struct tog_view *view)
7226 struct tog_ref_view_state *s = &view->state.ref;
7228 ref_view_free_refs(s);
7229 free_colors(&s->colors);
7231 return NULL;
7234 static const struct got_error *
7235 resolve_reflist_entry(struct got_object_id **commit_id,
7236 struct tog_reflist_entry *re, struct got_repository *repo)
7238 const struct got_error *err = NULL;
7239 struct got_object_id *obj_id;
7240 struct got_tag_object *tag = NULL;
7241 int obj_type;
7243 *commit_id = NULL;
7245 err = got_ref_resolve(&obj_id, repo, re->ref);
7246 if (err)
7247 return err;
7249 err = got_object_get_type(&obj_type, repo, obj_id);
7250 if (err)
7251 goto done;
7253 switch (obj_type) {
7254 case GOT_OBJ_TYPE_COMMIT:
7255 *commit_id = obj_id;
7256 break;
7257 case GOT_OBJ_TYPE_TAG:
7258 err = got_object_open_as_tag(&tag, repo, obj_id);
7259 if (err)
7260 goto done;
7261 free(obj_id);
7262 err = got_object_get_type(&obj_type, repo,
7263 got_object_tag_get_object_id(tag));
7264 if (err)
7265 goto done;
7266 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7267 err = got_error(GOT_ERR_OBJ_TYPE);
7268 goto done;
7270 *commit_id = got_object_id_dup(
7271 got_object_tag_get_object_id(tag));
7272 if (*commit_id == NULL) {
7273 err = got_error_from_errno("got_object_id_dup");
7274 goto done;
7276 break;
7277 default:
7278 err = got_error(GOT_ERR_OBJ_TYPE);
7279 break;
7282 done:
7283 if (tag)
7284 got_object_tag_close(tag);
7285 if (err) {
7286 free(*commit_id);
7287 *commit_id = NULL;
7289 return err;
7292 static const struct got_error *
7293 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7294 struct tog_reflist_entry *re, struct got_repository *repo)
7296 struct tog_view *log_view;
7297 const struct got_error *err = NULL;
7298 struct got_object_id *commit_id = NULL;
7300 *new_view = NULL;
7302 err = resolve_reflist_entry(&commit_id, re, repo);
7303 if (err) {
7304 if (err->code != GOT_ERR_OBJ_TYPE)
7305 return err;
7306 else
7307 return NULL;
7310 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7311 if (log_view == NULL) {
7312 err = got_error_from_errno("view_open");
7313 goto done;
7316 err = open_log_view(log_view, commit_id, repo,
7317 got_ref_get_name(re->ref), "", 0);
7318 done:
7319 if (err)
7320 view_close(log_view);
7321 else
7322 *new_view = log_view;
7323 free(commit_id);
7324 return err;
7327 static void
7328 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7330 struct tog_reflist_entry *re;
7331 int i = 0;
7333 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7334 return;
7336 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7337 while (i++ < maxscroll) {
7338 if (re == NULL)
7339 break;
7340 s->first_displayed_entry = re;
7341 re = TAILQ_PREV(re, tog_reflist_head, entry);
7345 static const struct got_error *
7346 ref_scroll_down(struct tog_view *view, int maxscroll)
7348 struct tog_ref_view_state *s = &view->state.ref;
7349 struct tog_reflist_entry *next, *last;
7350 int n = 0;
7352 if (s->first_displayed_entry)
7353 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7354 else
7355 next = TAILQ_FIRST(&s->refs);
7357 last = s->last_displayed_entry;
7358 while (next && n++ < maxscroll) {
7359 if (last)
7360 last = TAILQ_NEXT(last, entry);
7361 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7362 s->first_displayed_entry = next;
7363 next = TAILQ_NEXT(next, entry);
7367 return NULL;
7370 static const struct got_error *
7371 search_start_ref_view(struct tog_view *view)
7373 struct tog_ref_view_state *s = &view->state.ref;
7375 s->matched_entry = NULL;
7376 return NULL;
7379 static int
7380 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7382 regmatch_t regmatch;
7384 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7385 0) == 0;
7388 static const struct got_error *
7389 search_next_ref_view(struct tog_view *view)
7391 struct tog_ref_view_state *s = &view->state.ref;
7392 struct tog_reflist_entry *re = NULL;
7394 if (!view->searching) {
7395 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7396 return NULL;
7399 if (s->matched_entry) {
7400 if (view->searching == TOG_SEARCH_FORWARD) {
7401 if (s->selected_entry)
7402 re = TAILQ_NEXT(s->selected_entry, entry);
7403 else
7404 re = TAILQ_PREV(s->selected_entry,
7405 tog_reflist_head, entry);
7406 } else {
7407 if (s->selected_entry == NULL)
7408 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7409 else
7410 re = TAILQ_PREV(s->selected_entry,
7411 tog_reflist_head, entry);
7413 } else {
7414 if (s->selected_entry)
7415 re = s->selected_entry;
7416 else if (view->searching == TOG_SEARCH_FORWARD)
7417 re = TAILQ_FIRST(&s->refs);
7418 else
7419 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7422 while (1) {
7423 if (re == NULL) {
7424 if (s->matched_entry == NULL) {
7425 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7426 return NULL;
7428 if (view->searching == TOG_SEARCH_FORWARD)
7429 re = TAILQ_FIRST(&s->refs);
7430 else
7431 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7434 if (match_reflist_entry(re, &view->regex)) {
7435 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7436 s->matched_entry = re;
7437 break;
7440 if (view->searching == TOG_SEARCH_FORWARD)
7441 re = TAILQ_NEXT(re, entry);
7442 else
7443 re = TAILQ_PREV(re, tog_reflist_head, entry);
7446 if (s->matched_entry) {
7447 s->first_displayed_entry = s->matched_entry;
7448 s->selected = 0;
7451 return NULL;
7454 static const struct got_error *
7455 show_ref_view(struct tog_view *view)
7457 const struct got_error *err = NULL;
7458 struct tog_ref_view_state *s = &view->state.ref;
7459 struct tog_reflist_entry *re;
7460 char *line = NULL;
7461 wchar_t *wline;
7462 struct tog_color *tc;
7463 int width, n;
7464 int limit = view->nlines;
7466 werase(view->window);
7468 s->ndisplayed = 0;
7469 if (view_is_hsplit_top(view))
7470 --limit; /* border */
7472 if (limit == 0)
7473 return NULL;
7475 re = s->first_displayed_entry;
7477 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7478 s->nrefs) == -1)
7479 return got_error_from_errno("asprintf");
7481 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7482 if (err) {
7483 free(line);
7484 return err;
7486 if (view_needs_focus_indication(view))
7487 wstandout(view->window);
7488 waddwstr(view->window, wline);
7489 if (view_needs_focus_indication(view))
7490 wstandend(view->window);
7491 free(wline);
7492 wline = NULL;
7493 free(line);
7494 line = NULL;
7495 if (width < view->ncols - 1)
7496 waddch(view->window, '\n');
7497 if (--limit <= 0)
7498 return NULL;
7500 n = 0;
7501 while (re && limit > 0) {
7502 char *line = NULL;
7503 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7505 if (s->show_date) {
7506 struct got_commit_object *ci;
7507 struct got_tag_object *tag;
7508 struct got_object_id *id;
7509 struct tm tm;
7510 time_t t;
7512 err = got_ref_resolve(&id, s->repo, re->ref);
7513 if (err)
7514 return err;
7515 err = got_object_open_as_tag(&tag, s->repo, id);
7516 if (err) {
7517 if (err->code != GOT_ERR_OBJ_TYPE) {
7518 free(id);
7519 return err;
7521 err = got_object_open_as_commit(&ci, s->repo,
7522 id);
7523 if (err) {
7524 free(id);
7525 return err;
7527 t = got_object_commit_get_committer_time(ci);
7528 got_object_commit_close(ci);
7529 } else {
7530 t = got_object_tag_get_tagger_time(tag);
7531 got_object_tag_close(tag);
7533 free(id);
7534 if (gmtime_r(&t, &tm) == NULL)
7535 return got_error_from_errno("gmtime_r");
7536 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7537 return got_error(GOT_ERR_NO_SPACE);
7539 if (got_ref_is_symbolic(re->ref)) {
7540 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7541 ymd : "", got_ref_get_name(re->ref),
7542 got_ref_get_symref_target(re->ref)) == -1)
7543 return got_error_from_errno("asprintf");
7544 } else if (s->show_ids) {
7545 struct got_object_id *id;
7546 char *id_str;
7547 err = got_ref_resolve(&id, s->repo, re->ref);
7548 if (err)
7549 return err;
7550 err = got_object_id_str(&id_str, id);
7551 if (err) {
7552 free(id);
7553 return err;
7555 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7556 got_ref_get_name(re->ref), id_str) == -1) {
7557 err = got_error_from_errno("asprintf");
7558 free(id);
7559 free(id_str);
7560 return err;
7562 free(id);
7563 free(id_str);
7564 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7565 got_ref_get_name(re->ref)) == -1)
7566 return got_error_from_errno("asprintf");
7568 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7569 0, 0);
7570 if (err) {
7571 free(line);
7572 return err;
7574 if (n == s->selected) {
7575 if (view->focussed)
7576 wstandout(view->window);
7577 s->selected_entry = re;
7579 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7580 if (tc)
7581 wattr_on(view->window,
7582 COLOR_PAIR(tc->colorpair), NULL);
7583 waddwstr(view->window, wline);
7584 if (tc)
7585 wattr_off(view->window,
7586 COLOR_PAIR(tc->colorpair), NULL);
7587 if (width < view->ncols - 1)
7588 waddch(view->window, '\n');
7589 if (n == s->selected && view->focussed)
7590 wstandend(view->window);
7591 free(line);
7592 free(wline);
7593 wline = NULL;
7594 n++;
7595 s->ndisplayed++;
7596 s->last_displayed_entry = re;
7598 limit--;
7599 re = TAILQ_NEXT(re, entry);
7602 view_border(view);
7603 return err;
7606 static const struct got_error *
7607 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7608 struct tog_reflist_entry *re, struct got_repository *repo)
7610 const struct got_error *err = NULL;
7611 struct got_object_id *commit_id = NULL;
7612 struct tog_view *tree_view;
7614 *new_view = NULL;
7616 err = resolve_reflist_entry(&commit_id, re, repo);
7617 if (err) {
7618 if (err->code != GOT_ERR_OBJ_TYPE)
7619 return err;
7620 else
7621 return NULL;
7625 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7626 if (tree_view == NULL) {
7627 err = got_error_from_errno("view_open");
7628 goto done;
7631 err = open_tree_view(tree_view, commit_id,
7632 got_ref_get_name(re->ref), repo);
7633 if (err)
7634 goto done;
7636 *new_view = tree_view;
7637 done:
7638 free(commit_id);
7639 return err;
7641 static const struct got_error *
7642 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7644 const struct got_error *err = NULL;
7645 struct tog_ref_view_state *s = &view->state.ref;
7646 struct tog_view *log_view, *tree_view;
7647 struct tog_reflist_entry *re;
7648 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 1;
7650 switch (ch) {
7651 case 'i':
7652 s->show_ids = !s->show_ids;
7653 view->count = 0;
7654 break;
7655 case 'm':
7656 s->show_date = !s->show_date;
7657 view->count = 0;
7658 break;
7659 case 'o':
7660 s->sort_by_date = !s->sort_by_date;
7661 view->count = 0;
7662 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7663 got_ref_cmp_by_commit_timestamp_descending :
7664 tog_ref_cmp_by_name, s->repo);
7665 if (err)
7666 break;
7667 got_reflist_object_id_map_free(tog_refs_idmap);
7668 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7669 &tog_refs, s->repo);
7670 if (err)
7671 break;
7672 ref_view_free_refs(s);
7673 err = ref_view_load_refs(s);
7674 break;
7675 case KEY_ENTER:
7676 case '\r':
7677 view->count = 0;
7678 if (!s->selected_entry)
7679 break;
7680 if (view_is_parent_view(view))
7681 view_get_split(view, &begin_y, &begin_x);
7683 err = log_ref_entry(&log_view, begin_y, begin_x,
7684 s->selected_entry, s->repo);
7685 if (err)
7686 break;
7688 if (view_is_parent_view(view) &&
7689 view->mode == TOG_VIEW_SPLIT_HRZN) {
7690 err = view_init_hsplit(view, begin_y);
7691 if (err)
7692 break;
7695 view->focussed = 0;
7696 log_view->focussed = 1;
7697 log_view->mode = view->mode;
7698 log_view->nlines = view->lines - begin_y;
7699 if (view_is_parent_view(view)) {
7700 view_transfer_size(log_view, view);
7701 err = view_close_child(view);
7702 if (err)
7703 return err;
7704 err = view_set_child(view, log_view);
7705 if (err)
7706 return err;
7707 view->focus_child = 1;
7708 } else
7709 *new_view = log_view;
7710 break;
7711 case 't':
7712 view->count = 0;
7713 if (!s->selected_entry)
7714 break;
7715 if (view_is_parent_view(view))
7716 view_get_split(view, &begin_y, &begin_x);
7717 err = browse_ref_tree(&tree_view, begin_y, begin_x,
7718 s->selected_entry, s->repo);
7719 if (err || tree_view == NULL)
7720 break;
7721 if (view_is_parent_view(view) &&
7722 view->mode == TOG_VIEW_SPLIT_HRZN) {
7723 err = view_init_hsplit(view, begin_y);
7724 if (err)
7725 break;
7727 view->focussed = 0;
7728 tree_view->focussed = 1;
7729 tree_view->mode = view->mode;
7730 tree_view->nlines = view->lines - begin_y;
7731 if (view_is_parent_view(view)) {
7732 view_transfer_size(tree_view, view);
7733 err = view_close_child(view);
7734 if (err)
7735 return err;
7736 err = view_set_child(view, tree_view);
7737 if (err)
7738 return err;
7739 view->focus_child = 1;
7740 } else
7741 *new_view = tree_view;
7742 break;
7743 case 'g':
7744 case KEY_HOME:
7745 s->selected = 0;
7746 view->count = 0;
7747 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7748 break;
7749 case 'G':
7750 case KEY_END: {
7751 int eos = view->nlines - 1;
7753 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7754 --eos; /* border */
7755 s->selected = 0;
7756 view->count = 0;
7757 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7758 for (n = 0; n < eos; n++) {
7759 if (re == NULL)
7760 break;
7761 s->first_displayed_entry = re;
7762 re = TAILQ_PREV(re, tog_reflist_head, entry);
7764 if (n > 0)
7765 s->selected = n - 1;
7766 break;
7768 case 'k':
7769 case KEY_UP:
7770 case CTRL('p'):
7771 if (s->selected > 0) {
7772 s->selected--;
7773 break;
7775 ref_scroll_up(s, 1);
7776 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7777 view->count = 0;
7778 break;
7779 case CTRL('u'):
7780 case 'u':
7781 nscroll /= 2;
7782 /* FALL THROUGH */
7783 case KEY_PPAGE:
7784 case CTRL('b'):
7785 case 'b':
7786 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7787 s->selected -= MIN(nscroll, s->selected);
7788 ref_scroll_up(s, MAX(0, nscroll));
7789 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7790 view->count = 0;
7791 break;
7792 case 'j':
7793 case KEY_DOWN:
7794 case CTRL('n'):
7795 if (s->selected < s->ndisplayed - 1) {
7796 s->selected++;
7797 break;
7799 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7800 /* can't scroll any further */
7801 view->count = 0;
7802 break;
7804 ref_scroll_down(view, 1);
7805 break;
7806 case CTRL('d'):
7807 case 'd':
7808 nscroll /= 2;
7809 /* FALL THROUGH */
7810 case KEY_NPAGE:
7811 case CTRL('f'):
7812 case 'f':
7813 case ' ':
7814 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7815 /* can't scroll any further; move cursor down */
7816 if (s->selected < s->ndisplayed - 1)
7817 s->selected += MIN(nscroll,
7818 s->ndisplayed - s->selected - 1);
7819 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7820 s->selected += s->ndisplayed - s->selected - 1;
7821 view->count = 0;
7822 break;
7824 ref_scroll_down(view, nscroll);
7825 break;
7826 case CTRL('l'):
7827 view->count = 0;
7828 tog_free_refs();
7829 err = tog_load_refs(s->repo, s->sort_by_date);
7830 if (err)
7831 break;
7832 ref_view_free_refs(s);
7833 err = ref_view_load_refs(s);
7834 break;
7835 case KEY_RESIZE:
7836 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7837 s->selected = view->nlines - 2;
7838 break;
7839 default:
7840 view->count = 0;
7841 break;
7844 return err;
7847 __dead static void
7848 usage_ref(void)
7850 endwin();
7851 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7852 getprogname());
7853 exit(1);
7856 static const struct got_error *
7857 cmd_ref(int argc, char *argv[])
7859 const struct got_error *error;
7860 struct got_repository *repo = NULL;
7861 struct got_worktree *worktree = NULL;
7862 char *cwd = NULL, *repo_path = NULL;
7863 int ch;
7864 struct tog_view *view;
7865 int *pack_fds = NULL;
7867 while ((ch = getopt(argc, argv, "r:")) != -1) {
7868 switch (ch) {
7869 case 'r':
7870 repo_path = realpath(optarg, NULL);
7871 if (repo_path == NULL)
7872 return got_error_from_errno2("realpath",
7873 optarg);
7874 break;
7875 default:
7876 usage_ref();
7877 /* NOTREACHED */
7881 argc -= optind;
7882 argv += optind;
7884 if (argc > 1)
7885 usage_ref();
7887 error = got_repo_pack_fds_open(&pack_fds);
7888 if (error != NULL)
7889 goto done;
7891 if (repo_path == NULL) {
7892 cwd = getcwd(NULL, 0);
7893 if (cwd == NULL)
7894 return got_error_from_errno("getcwd");
7895 error = got_worktree_open(&worktree, cwd);
7896 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7897 goto done;
7898 if (worktree)
7899 repo_path =
7900 strdup(got_worktree_get_repo_path(worktree));
7901 else
7902 repo_path = strdup(cwd);
7903 if (repo_path == NULL) {
7904 error = got_error_from_errno("strdup");
7905 goto done;
7909 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7910 if (error != NULL)
7911 goto done;
7913 init_curses();
7915 error = apply_unveil(got_repo_get_path(repo), NULL);
7916 if (error)
7917 goto done;
7919 error = tog_load_refs(repo, 0);
7920 if (error)
7921 goto done;
7923 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7924 if (view == NULL) {
7925 error = got_error_from_errno("view_open");
7926 goto done;
7929 error = open_ref_view(view, repo);
7930 if (error)
7931 goto done;
7933 if (worktree) {
7934 /* Release work tree lock. */
7935 got_worktree_close(worktree);
7936 worktree = NULL;
7938 error = view_loop(view);
7939 done:
7940 free(repo_path);
7941 free(cwd);
7942 if (repo) {
7943 const struct got_error *close_err = got_repo_close(repo);
7944 if (close_err)
7945 error = close_err;
7947 if (pack_fds) {
7948 const struct got_error *pack_err =
7949 got_repo_pack_fds_close(pack_fds);
7950 if (error == NULL)
7951 error = pack_err;
7953 tog_free_refs();
7954 return error;
7958 * If view was scrolled down to move the selected line into view when opening a
7959 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7961 static void
7962 offset_selection_up(struct tog_view *view)
7964 switch (view->type) {
7965 case TOG_VIEW_BLAME: {
7966 struct tog_blame_view_state *s = &view->state.blame;
7967 if (s->first_displayed_line == 1) {
7968 s->selected_line = MAX(s->selected_line - view->offset,
7969 1);
7970 break;
7972 if (s->first_displayed_line > view->offset)
7973 s->first_displayed_line -= view->offset;
7974 else
7975 s->first_displayed_line = 1;
7976 s->selected_line += view->offset;
7977 break;
7979 case TOG_VIEW_LOG:
7980 log_scroll_up(&view->state.log, view->offset);
7981 view->state.log.selected += view->offset;
7982 break;
7983 case TOG_VIEW_REF:
7984 ref_scroll_up(&view->state.ref, view->offset);
7985 view->state.ref.selected += view->offset;
7986 break;
7987 case TOG_VIEW_TREE:
7988 tree_scroll_up(&view->state.tree, view->offset);
7989 view->state.tree.selected += view->offset;
7990 break;
7991 default:
7992 break;
7995 view->offset = 0;
7999 * If the selected line is in the section of screen covered by the bottom split,
8000 * scroll down offset lines to move it into view and index its new position.
8002 static const struct got_error *
8003 offset_selection_down(struct tog_view *view)
8005 const struct got_error *err = NULL;
8006 const struct got_error *(*scrolld)(struct tog_view *, int);
8007 int *selected = NULL;
8008 int header, offset;
8010 switch (view->type) {
8011 case TOG_VIEW_BLAME: {
8012 struct tog_blame_view_state *s = &view->state.blame;
8013 header = 3;
8014 scrolld = NULL;
8015 if (s->selected_line > view->nlines - header) {
8016 offset = abs(view->nlines - s->selected_line - header);
8017 s->first_displayed_line += offset;
8018 s->selected_line -= offset;
8019 view->offset = offset;
8021 break;
8023 case TOG_VIEW_LOG: {
8024 struct tog_log_view_state *s = &view->state.log;
8025 scrolld = &log_scroll_down;
8026 header = view_is_parent_view(view) ? 3 : 2;
8027 selected = &s->selected;
8028 break;
8030 case TOG_VIEW_REF: {
8031 struct tog_ref_view_state *s = &view->state.ref;
8032 scrolld = &ref_scroll_down;
8033 header = 3;
8034 selected = &s->selected;
8035 break;
8037 case TOG_VIEW_TREE: {
8038 struct tog_tree_view_state *s = &view->state.tree;
8039 scrolld = &tree_scroll_down;
8040 header = 5;
8041 selected = &s->selected;
8042 break;
8044 default:
8045 selected = NULL;
8046 scrolld = NULL;
8047 header = 0;
8048 break;
8051 if (selected && *selected > view->nlines - header) {
8052 offset = abs(view->nlines - *selected - header);
8053 view->offset = offset;
8054 if (scrolld && offset) {
8055 err = scrolld(view, offset);
8056 *selected -= offset;
8060 return err;
8063 static void
8064 list_commands(FILE *fp)
8066 size_t i;
8068 fprintf(fp, "commands:");
8069 for (i = 0; i < nitems(tog_commands); i++) {
8070 const struct tog_cmd *cmd = &tog_commands[i];
8071 fprintf(fp, " %s", cmd->name);
8073 fputc('\n', fp);
8076 __dead static void
8077 usage(int hflag, int status)
8079 FILE *fp = (status == 0) ? stdout : stderr;
8081 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8082 getprogname());
8083 if (hflag) {
8084 fprintf(fp, "lazy usage: %s path\n", getprogname());
8085 list_commands(fp);
8087 exit(status);
8090 static char **
8091 make_argv(int argc, ...)
8093 va_list ap;
8094 char **argv;
8095 int i;
8097 va_start(ap, argc);
8099 argv = calloc(argc, sizeof(char *));
8100 if (argv == NULL)
8101 err(1, "calloc");
8102 for (i = 0; i < argc; i++) {
8103 argv[i] = strdup(va_arg(ap, char *));
8104 if (argv[i] == NULL)
8105 err(1, "strdup");
8108 va_end(ap);
8109 return argv;
8113 * Try to convert 'tog path' into a 'tog log path' command.
8114 * The user could simply have mistyped the command rather than knowingly
8115 * provided a path. So check whether argv[0] can in fact be resolved
8116 * to a path in the HEAD commit and print a special error if not.
8117 * This hack is for mpi@ <3
8119 static const struct got_error *
8120 tog_log_with_path(int argc, char *argv[])
8122 const struct got_error *error = NULL, *close_err;
8123 const struct tog_cmd *cmd = NULL;
8124 struct got_repository *repo = NULL;
8125 struct got_worktree *worktree = NULL;
8126 struct got_object_id *commit_id = NULL, *id = NULL;
8127 struct got_commit_object *commit = NULL;
8128 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8129 char *commit_id_str = NULL, **cmd_argv = NULL;
8130 int *pack_fds = NULL;
8132 cwd = getcwd(NULL, 0);
8133 if (cwd == NULL)
8134 return got_error_from_errno("getcwd");
8136 error = got_repo_pack_fds_open(&pack_fds);
8137 if (error != NULL)
8138 goto done;
8140 error = got_worktree_open(&worktree, cwd);
8141 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8142 goto done;
8144 if (worktree)
8145 repo_path = strdup(got_worktree_get_repo_path(worktree));
8146 else
8147 repo_path = strdup(cwd);
8148 if (repo_path == NULL) {
8149 error = got_error_from_errno("strdup");
8150 goto done;
8153 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8154 if (error != NULL)
8155 goto done;
8157 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8158 repo, worktree);
8159 if (error)
8160 goto done;
8162 error = tog_load_refs(repo, 0);
8163 if (error)
8164 goto done;
8165 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8166 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8167 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8168 if (error)
8169 goto done;
8171 if (worktree) {
8172 got_worktree_close(worktree);
8173 worktree = NULL;
8176 error = got_object_open_as_commit(&commit, repo, commit_id);
8177 if (error)
8178 goto done;
8180 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8181 if (error) {
8182 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8183 goto done;
8184 fprintf(stderr, "%s: '%s' is no known command or path\n",
8185 getprogname(), argv[0]);
8186 usage(1, 1);
8187 /* not reached */
8190 close_err = got_repo_close(repo);
8191 if (error == NULL)
8192 error = close_err;
8193 repo = NULL;
8195 error = got_object_id_str(&commit_id_str, commit_id);
8196 if (error)
8197 goto done;
8199 cmd = &tog_commands[0]; /* log */
8200 argc = 4;
8201 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8202 error = cmd->cmd_main(argc, cmd_argv);
8203 done:
8204 if (repo) {
8205 close_err = got_repo_close(repo);
8206 if (error == NULL)
8207 error = close_err;
8209 if (commit)
8210 got_object_commit_close(commit);
8211 if (worktree)
8212 got_worktree_close(worktree);
8213 if (pack_fds) {
8214 const struct got_error *pack_err =
8215 got_repo_pack_fds_close(pack_fds);
8216 if (error == NULL)
8217 error = pack_err;
8219 free(id);
8220 free(commit_id_str);
8221 free(commit_id);
8222 free(cwd);
8223 free(repo_path);
8224 free(in_repo_path);
8225 if (cmd_argv) {
8226 int i;
8227 for (i = 0; i < argc; i++)
8228 free(cmd_argv[i]);
8229 free(cmd_argv);
8231 tog_free_refs();
8232 return error;
8235 int
8236 main(int argc, char *argv[])
8238 const struct got_error *error = NULL;
8239 const struct tog_cmd *cmd = NULL;
8240 int ch, hflag = 0, Vflag = 0;
8241 char **cmd_argv = NULL;
8242 static const struct option longopts[] = {
8243 { "version", no_argument, NULL, 'V' },
8244 { NULL, 0, NULL, 0}
8246 char *diff_algo_str = NULL;
8248 setlocale(LC_CTYPE, "");
8250 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8251 switch (ch) {
8252 case 'h':
8253 hflag = 1;
8254 break;
8255 case 'V':
8256 Vflag = 1;
8257 break;
8258 default:
8259 usage(hflag, 1);
8260 /* NOTREACHED */
8264 argc -= optind;
8265 argv += optind;
8266 optind = 1;
8267 optreset = 1;
8269 if (Vflag) {
8270 got_version_print_str();
8271 return 0;
8274 #ifndef PROFILE
8275 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8276 NULL) == -1)
8277 err(1, "pledge");
8278 #endif
8280 if (argc == 0) {
8281 if (hflag)
8282 usage(hflag, 0);
8283 /* Build an argument vector which runs a default command. */
8284 cmd = &tog_commands[0];
8285 argc = 1;
8286 cmd_argv = make_argv(argc, cmd->name);
8287 } else {
8288 size_t i;
8290 /* Did the user specify a command? */
8291 for (i = 0; i < nitems(tog_commands); i++) {
8292 if (strncmp(tog_commands[i].name, argv[0],
8293 strlen(argv[0])) == 0) {
8294 cmd = &tog_commands[i];
8295 break;
8300 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8301 if (diff_algo_str) {
8302 if (strcasecmp(diff_algo_str, "patience") == 0)
8303 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8304 if (strcasecmp(diff_algo_str, "myers") == 0)
8305 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8308 if (cmd == NULL) {
8309 if (argc != 1)
8310 usage(0, 1);
8311 /* No command specified; try log with a path */
8312 error = tog_log_with_path(argc, argv);
8313 } else {
8314 if (hflag)
8315 cmd->cmd_usage();
8316 else
8317 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8320 endwin();
8321 putchar('\n');
8322 if (cmd_argv) {
8323 int i;
8324 for (i = 0; i < argc; i++)
8325 free(cmd_argv[i]);
8326 free(cmd_argv);
8329 if (error && error->code != GOT_ERR_CANCELLED)
8330 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8331 return 0;