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 const struct got_error *
937 view_resize_split(struct tog_view *view, int resize)
939 const struct got_error *err = NULL;
940 struct tog_view *v = NULL;
942 if (view->parent)
943 v = view->parent;
944 else
945 v = view;
947 if (!v->child || !view_is_splitscreen(v->child))
948 return NULL;
950 v->resize = v->child->resize = resize; /* lock for resize event */
952 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
953 if (v->child->resized_y)
954 v->child->begin_y = v->child->resized_y;
955 if (view->parent)
956 v->child->begin_y -= resize;
957 else
958 v->child->begin_y += resize;
959 if (v->child->begin_y < 3) {
960 view->count = 0;
961 v->child->begin_y = 3;
962 } else if (v->child->begin_y > LINES - 1) {
963 view->count = 0;
964 v->child->begin_y = LINES - 1;
966 v->ncols = COLS;
967 v->child->ncols = COLS;
968 err = view_init_hsplit(v, v->child->begin_y);
969 if (err)
970 return err;
971 v->child->resized_y = v->child->begin_y;
972 } else {
973 if (v->child->resized_x)
974 v->child->begin_x = v->child->resized_x;
975 if (view->parent)
976 v->child->begin_x -= resize;
977 else
978 v->child->begin_x += resize;
979 if (v->child->begin_x < 11) {
980 view->count = 0;
981 v->child->begin_x = 11;
982 } else if (v->child->begin_x > COLS - 1) {
983 view->count = 0;
984 v->child->begin_x = COLS - 1;
986 v->child->resized_x = v->child->begin_x;
989 v->child->mode = v->mode;
990 v->child->nlines = v->lines - v->child->begin_y;
991 v->child->ncols = v->cols - v->child->begin_x;
992 v->focus_child = 1;
994 err = view_fullscreen(v);
995 if (err)
996 return err;
997 err = view_splitscreen(v->child);
998 if (err)
999 return err;
1001 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1002 err = offset_selection_down(v->child);
1003 if (err)
1004 return err;
1007 if (v->type == TOG_VIEW_LOG)
1008 err = request_log_commits(v);
1009 else if (v->child->type == TOG_VIEW_LOG)
1010 err = request_log_commits(v->child);
1012 v->resize = v->child->resize = 0;
1014 return err;
1017 static void
1018 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1020 struct tog_view *v = src->child ? src->child : src;
1022 dst->resized_x = v->resized_x;
1023 dst->resized_y = v->resized_y;
1026 static const struct got_error *
1027 view_close_child(struct tog_view *view)
1029 const struct got_error *err = NULL;
1031 if (view->child == NULL)
1032 return NULL;
1034 err = view_close(view->child);
1035 view->child = NULL;
1036 return err;
1039 static const struct got_error *
1040 view_set_child(struct tog_view *view, struct tog_view *child)
1042 const struct got_error *err = NULL;
1044 view->child = child;
1045 child->parent = view;
1047 err = view_resize(view);
1048 if (err)
1049 return err;
1051 if (view->child->resized_x || view->child->resized_y)
1052 err = view_resize_split(view, 0);
1054 return err;
1057 static void
1058 tog_resizeterm(void)
1060 int cols, lines;
1061 struct winsize size;
1063 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1064 cols = 80; /* Default */
1065 lines = 24;
1066 } else {
1067 cols = size.ws_col;
1068 lines = size.ws_row;
1070 resize_term(lines, cols);
1073 static const struct got_error *
1074 view_search_start(struct tog_view *view)
1076 const struct got_error *err = NULL;
1077 struct tog_view *v = view;
1078 char pattern[1024];
1079 int ret;
1081 if (view->search_started) {
1082 regfree(&view->regex);
1083 view->searching = 0;
1084 memset(&view->regmatch, 0, sizeof(view->regmatch));
1086 view->search_started = 0;
1088 if (view->nlines < 1)
1089 return NULL;
1091 if (view_is_hsplit_top(view))
1092 v = view->child;
1094 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1095 wclrtoeol(v->window);
1097 nodelay(view->window, FALSE); /* block for search term input */
1098 nocbreak();
1099 echo();
1100 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1101 wrefresh(v->window);
1102 cbreak();
1103 noecho();
1104 nodelay(view->window, TRUE);
1105 if (ret == ERR)
1106 return NULL;
1108 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1109 err = view->search_start(view);
1110 if (err) {
1111 regfree(&view->regex);
1112 return err;
1114 view->search_started = 1;
1115 view->searching = TOG_SEARCH_FORWARD;
1116 view->search_next_done = 0;
1117 view->search_next(view);
1120 return NULL;
1123 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1124 static const struct got_error *
1125 switch_split(struct tog_view *view)
1127 const struct got_error *err = NULL;
1128 struct tog_view *v = NULL;
1130 if (view->parent)
1131 v = view->parent;
1132 else
1133 v = view;
1135 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1136 v->mode = TOG_VIEW_SPLIT_VERT;
1137 else
1138 v->mode = TOG_VIEW_SPLIT_HRZN;
1140 if (!v->child)
1141 return NULL;
1142 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1143 v->mode = TOG_VIEW_SPLIT_NONE;
1145 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1146 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1147 v->child->begin_y = v->child->resized_y;
1148 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1149 v->child->begin_x = v->child->resized_x;
1152 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1153 v->ncols = COLS;
1154 v->child->ncols = COLS;
1155 v->child->nscrolled = LINES - v->child->nlines;
1157 err = view_init_hsplit(v, v->child->begin_y);
1158 if (err)
1159 return err;
1161 v->child->mode = v->mode;
1162 v->child->nlines = v->lines - v->child->begin_y;
1163 v->focus_child = 1;
1165 err = view_fullscreen(v);
1166 if (err)
1167 return err;
1168 err = view_splitscreen(v->child);
1169 if (err)
1170 return err;
1172 if (v->mode == TOG_VIEW_SPLIT_NONE)
1173 v->mode = TOG_VIEW_SPLIT_VERT;
1174 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1175 err = offset_selection_down(v);
1176 err = offset_selection_down(v->child);
1177 } else {
1178 offset_selection_up(v);
1179 offset_selection_up(v->child);
1181 if (v->type == TOG_VIEW_LOG)
1182 err = request_log_commits(v);
1183 else if (v->child->type == TOG_VIEW_LOG)
1184 err = request_log_commits(v->child);
1186 return err;
1190 * Compute view->count from numeric input. Assign total to view->count and
1191 * return first non-numeric key entered.
1193 static int
1194 get_compound_key(struct tog_view *view, int c)
1196 struct tog_view *v = view;
1197 int x, n = 0;
1199 if (view_is_hsplit_top(view))
1200 v = view->child;
1201 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1202 v = view->parent;
1204 view->count = 0;
1205 cbreak(); /* block for input */
1206 wmove(v->window, v->nlines - 1, 0);
1207 wclrtoeol(v->window);
1208 waddch(v->window, ':');
1210 do {
1211 x = getcurx(v->window);
1212 if (x != ERR && x < view->ncols) {
1213 waddch(v->window, c);
1214 wrefresh(v->window);
1218 * Don't overflow. Max valid request should be the greatest
1219 * between the longest and total lines; cap at 10 million.
1221 if (n >= 9999999)
1222 n = 9999999;
1223 else
1224 n = n * 10 + (c - '0');
1225 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1227 /* Massage excessive or inapplicable values at the input handler. */
1228 view->count = n;
1230 return c;
1233 static const struct got_error *
1234 view_input(struct tog_view **new, int *done, struct tog_view *view,
1235 struct tog_view_list_head *views)
1237 const struct got_error *err = NULL;
1238 struct tog_view *v;
1239 int ch, errcode;
1241 *new = NULL;
1243 /* Clear "no matches" indicator. */
1244 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1245 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1246 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1247 view->count = 0;
1250 if (view->searching && !view->search_next_done) {
1251 errcode = pthread_mutex_unlock(&tog_mutex);
1252 if (errcode)
1253 return got_error_set_errno(errcode,
1254 "pthread_mutex_unlock");
1255 sched_yield();
1256 errcode = pthread_mutex_lock(&tog_mutex);
1257 if (errcode)
1258 return got_error_set_errno(errcode,
1259 "pthread_mutex_lock");
1260 view->search_next(view);
1261 return NULL;
1264 nodelay(view->window, FALSE);
1265 /* Allow threads to make progress while we are waiting for input. */
1266 errcode = pthread_mutex_unlock(&tog_mutex);
1267 if (errcode)
1268 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1269 /* If we have an unfinished count, let C-g or backspace abort. */
1270 if (view->count && --view->count) {
1271 cbreak();
1272 nodelay(view->window, TRUE);
1273 ch = wgetch(view->window);
1274 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1275 view->count = 0;
1276 else
1277 ch = view->ch;
1278 } else {
1279 ch = wgetch(view->window);
1280 if (ch >= '1' && ch <= '9')
1281 view->ch = ch = get_compound_key(view, ch);
1283 errcode = pthread_mutex_lock(&tog_mutex);
1284 if (errcode)
1285 return got_error_set_errno(errcode, "pthread_mutex_lock");
1286 nodelay(view->window, TRUE);
1288 if (tog_sigwinch_received || tog_sigcont_received) {
1289 tog_resizeterm();
1290 tog_sigwinch_received = 0;
1291 tog_sigcont_received = 0;
1292 TAILQ_FOREACH(v, views, entry) {
1293 err = view_resize(v);
1294 if (err)
1295 return err;
1296 err = v->input(new, v, KEY_RESIZE);
1297 if (err)
1298 return err;
1299 if (v->child) {
1300 err = view_resize(v->child);
1301 if (err)
1302 return err;
1303 err = v->child->input(new, v->child,
1304 KEY_RESIZE);
1305 if (err)
1306 return err;
1307 if (v->child->resized_x || v->child->resized_y) {
1308 err = view_resize_split(v, 0);
1309 if (err)
1310 return err;
1316 switch (ch) {
1317 case '\t':
1318 view->count = 0;
1319 if (view->child) {
1320 view->focussed = 0;
1321 view->child->focussed = 1;
1322 view->focus_child = 1;
1323 } else if (view->parent) {
1324 view->focussed = 0;
1325 view->parent->focussed = 1;
1326 view->parent->focus_child = 0;
1327 if (!view_is_splitscreen(view)) {
1328 if (view->mode == TOG_VIEW_SPLIT_HRZN &&
1329 view->parent->type == TOG_VIEW_LOG) {
1330 err = request_log_commits(view->parent);
1331 if (err)
1332 return err;
1334 offset_selection_up(view->parent);
1335 err = view_fullscreen(view->parent);
1336 if (err)
1337 return err;
1340 break;
1341 case 'q':
1342 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1343 if (view->parent->type == TOG_VIEW_LOG) {
1344 /* might need more commits to fill fullscreen */
1345 err = request_log_commits(view->parent);
1346 if (err)
1347 break;
1349 offset_selection_up(view->parent);
1351 err = view->input(new, view, ch);
1352 view->dying = 1;
1353 break;
1354 case 'Q':
1355 *done = 1;
1356 break;
1357 case 'F':
1358 view->count = 0;
1359 if (view_is_parent_view(view)) {
1360 if (view->child == NULL)
1361 break;
1362 if (view_is_splitscreen(view->child)) {
1363 view->focussed = 0;
1364 view->child->focussed = 1;
1365 err = view_fullscreen(view->child);
1366 } else {
1367 err = view_splitscreen(view->child);
1368 if (!err)
1369 err = view_resize_split(view, 0);
1371 if (err)
1372 break;
1373 err = view->child->input(new, view->child,
1374 KEY_RESIZE);
1375 } else {
1376 if (view_is_splitscreen(view)) {
1377 view->parent->focussed = 0;
1378 view->focussed = 1;
1379 err = view_fullscreen(view);
1380 } else {
1381 err = view_splitscreen(view);
1382 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1383 err = view_resize(view->parent);
1384 if (!err)
1385 err = view_resize_split(view, 0);
1387 if (err)
1388 break;
1389 err = view->input(new, view, KEY_RESIZE);
1391 if (err)
1392 break;
1393 if (view->type == TOG_VIEW_LOG) {
1394 err = request_log_commits(view);
1395 if (err)
1396 break;
1398 if (view->parent)
1399 err = offset_selection_down(view->parent);
1400 if (!err)
1401 err = offset_selection_down(view);
1402 break;
1403 case 'S':
1404 view->count = 0;
1405 err = switch_split(view);
1406 break;
1407 case '-':
1408 err = view_resize_split(view, -1);
1409 break;
1410 case '+':
1411 err = view_resize_split(view, 1);
1412 break;
1413 case KEY_RESIZE:
1414 break;
1415 case '/':
1416 view->count = 0;
1417 if (view->search_start)
1418 view_search_start(view);
1419 else
1420 err = view->input(new, view, ch);
1421 break;
1422 case 'N':
1423 case 'n':
1424 if (view->search_started && view->search_next) {
1425 view->searching = (ch == 'n' ?
1426 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1427 view->search_next_done = 0;
1428 view->search_next(view);
1429 } else
1430 err = view->input(new, view, ch);
1431 break;
1432 case 'A':
1433 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1434 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1435 else
1436 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1437 TAILQ_FOREACH(v, views, entry) {
1438 if (v->reset) {
1439 err = v->reset(v);
1440 if (err)
1441 return err;
1443 if (v->child && v->child->reset) {
1444 err = v->child->reset(v->child);
1445 if (err)
1446 return err;
1449 break;
1450 default:
1451 err = view->input(new, view, ch);
1452 break;
1455 return err;
1458 static int
1459 view_needs_focus_indication(struct tog_view *view)
1461 if (view_is_parent_view(view)) {
1462 if (view->child == NULL || view->child->focussed)
1463 return 0;
1464 if (!view_is_splitscreen(view->child))
1465 return 0;
1466 } else if (!view_is_splitscreen(view))
1467 return 0;
1469 return view->focussed;
1472 static const struct got_error *
1473 view_loop(struct tog_view *view)
1475 const struct got_error *err = NULL;
1476 struct tog_view_list_head views;
1477 struct tog_view *new_view;
1478 char *mode;
1479 int fast_refresh = 10;
1480 int done = 0, errcode;
1482 mode = getenv("TOG_VIEW_SPLIT_MODE");
1483 if (!mode || !(*mode == 'h' || *mode == 'H'))
1484 view->mode = TOG_VIEW_SPLIT_VERT;
1485 else
1486 view->mode = TOG_VIEW_SPLIT_HRZN;
1488 errcode = pthread_mutex_lock(&tog_mutex);
1489 if (errcode)
1490 return got_error_set_errno(errcode, "pthread_mutex_lock");
1492 TAILQ_INIT(&views);
1493 TAILQ_INSERT_HEAD(&views, view, entry);
1495 view->focussed = 1;
1496 err = view->show(view);
1497 if (err)
1498 return err;
1499 update_panels();
1500 doupdate();
1501 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1502 !tog_fatal_signal_received()) {
1503 /* Refresh fast during initialization, then become slower. */
1504 if (fast_refresh && fast_refresh-- == 0)
1505 halfdelay(10); /* switch to once per second */
1507 err = view_input(&new_view, &done, view, &views);
1508 if (err)
1509 break;
1510 if (view->dying) {
1511 struct tog_view *v, *prev = NULL;
1513 if (view_is_parent_view(view))
1514 prev = TAILQ_PREV(view, tog_view_list_head,
1515 entry);
1516 else if (view->parent)
1517 prev = view->parent;
1519 if (view->parent) {
1520 view->parent->child = NULL;
1521 view->parent->focus_child = 0;
1522 /* Restore fullscreen line height. */
1523 view->parent->nlines = view->parent->lines;
1524 err = view_resize(view->parent);
1525 if (err)
1526 break;
1527 /* Make resized splits persist. */
1528 view_transfer_size(view->parent, view);
1529 } else
1530 TAILQ_REMOVE(&views, view, entry);
1532 err = view_close(view);
1533 if (err)
1534 goto done;
1536 view = NULL;
1537 TAILQ_FOREACH(v, &views, entry) {
1538 if (v->focussed)
1539 break;
1541 if (view == NULL && new_view == NULL) {
1542 /* No view has focus. Try to pick one. */
1543 if (prev)
1544 view = prev;
1545 else if (!TAILQ_EMPTY(&views)) {
1546 view = TAILQ_LAST(&views,
1547 tog_view_list_head);
1549 if (view) {
1550 if (view->focus_child) {
1551 view->child->focussed = 1;
1552 view = view->child;
1553 } else
1554 view->focussed = 1;
1558 if (new_view) {
1559 struct tog_view *v, *t;
1560 /* Only allow one parent view per type. */
1561 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1562 if (v->type != new_view->type)
1563 continue;
1564 TAILQ_REMOVE(&views, v, entry);
1565 err = view_close(v);
1566 if (err)
1567 goto done;
1568 break;
1570 TAILQ_INSERT_TAIL(&views, new_view, entry);
1571 view = new_view;
1573 if (view) {
1574 if (view_is_parent_view(view)) {
1575 if (view->child && view->child->focussed)
1576 view = view->child;
1577 } else {
1578 if (view->parent && view->parent->focussed)
1579 view = view->parent;
1581 show_panel(view->panel);
1582 if (view->child && view_is_splitscreen(view->child))
1583 show_panel(view->child->panel);
1584 if (view->parent && view_is_splitscreen(view)) {
1585 err = view->parent->show(view->parent);
1586 if (err)
1587 goto done;
1589 err = view->show(view);
1590 if (err)
1591 goto done;
1592 if (view->child) {
1593 err = view->child->show(view->child);
1594 if (err)
1595 goto done;
1597 update_panels();
1598 doupdate();
1601 done:
1602 while (!TAILQ_EMPTY(&views)) {
1603 const struct got_error *close_err;
1604 view = TAILQ_FIRST(&views);
1605 TAILQ_REMOVE(&views, view, entry);
1606 close_err = view_close(view);
1607 if (close_err && err == NULL)
1608 err = close_err;
1611 errcode = pthread_mutex_unlock(&tog_mutex);
1612 if (errcode && err == NULL)
1613 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1615 return err;
1618 __dead static void
1619 usage_log(void)
1621 endwin();
1622 fprintf(stderr,
1623 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1624 getprogname());
1625 exit(1);
1628 /* Create newly allocated wide-character string equivalent to a byte string. */
1629 static const struct got_error *
1630 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1632 char *vis = NULL;
1633 const struct got_error *err = NULL;
1635 *ws = NULL;
1636 *wlen = mbstowcs(NULL, s, 0);
1637 if (*wlen == (size_t)-1) {
1638 int vislen;
1639 if (errno != EILSEQ)
1640 return got_error_from_errno("mbstowcs");
1642 /* byte string invalid in current encoding; try to "fix" it */
1643 err = got_mbsavis(&vis, &vislen, s);
1644 if (err)
1645 return err;
1646 *wlen = mbstowcs(NULL, vis, 0);
1647 if (*wlen == (size_t)-1) {
1648 err = got_error_from_errno("mbstowcs"); /* give up */
1649 goto done;
1653 *ws = calloc(*wlen + 1, sizeof(**ws));
1654 if (*ws == NULL) {
1655 err = got_error_from_errno("calloc");
1656 goto done;
1659 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1660 err = got_error_from_errno("mbstowcs");
1661 done:
1662 free(vis);
1663 if (err) {
1664 free(*ws);
1665 *ws = NULL;
1666 *wlen = 0;
1668 return err;
1671 static const struct got_error *
1672 expand_tab(char **ptr, const char *src)
1674 char *dst;
1675 size_t len, n, idx = 0, sz = 0;
1677 *ptr = NULL;
1678 n = len = strlen(src);
1679 dst = malloc(n + 1);
1680 if (dst == NULL)
1681 return got_error_from_errno("malloc");
1683 while (idx < len && src[idx]) {
1684 const char c = src[idx];
1686 if (c == '\t') {
1687 size_t nb = TABSIZE - sz % TABSIZE;
1688 char *p;
1690 p = realloc(dst, n + nb);
1691 if (p == NULL) {
1692 free(dst);
1693 return got_error_from_errno("realloc");
1696 dst = p;
1697 n += nb;
1698 memset(dst + sz, ' ', nb);
1699 sz += nb;
1700 } else
1701 dst[sz++] = src[idx];
1702 ++idx;
1705 dst[sz] = '\0';
1706 *ptr = dst;
1707 return NULL;
1711 * Advance at most n columns from wline starting at offset off.
1712 * Return the index to the first character after the span operation.
1713 * Return the combined column width of all spanned wide character in
1714 * *rcol.
1716 static int
1717 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1719 int width, i, cols = 0;
1721 if (n == 0) {
1722 *rcol = cols;
1723 return off;
1726 for (i = off; wline[i] != L'\0'; ++i) {
1727 if (wline[i] == L'\t')
1728 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1729 else
1730 width = wcwidth(wline[i]);
1732 if (width == -1) {
1733 width = 1;
1734 wline[i] = L'.';
1737 if (cols + width > n)
1738 break;
1739 cols += width;
1742 *rcol = cols;
1743 return i;
1747 * Format a line for display, ensuring that it won't overflow a width limit.
1748 * With scrolling, the width returned refers to the scrolled version of the
1749 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1751 static const struct got_error *
1752 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1753 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1755 const struct got_error *err = NULL;
1756 int cols;
1757 wchar_t *wline = NULL;
1758 char *exstr = NULL;
1759 size_t wlen;
1760 int i, scrollx;
1762 *wlinep = NULL;
1763 *widthp = 0;
1765 if (expand) {
1766 err = expand_tab(&exstr, line);
1767 if (err)
1768 return err;
1771 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1772 free(exstr);
1773 if (err)
1774 return err;
1776 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1778 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1779 wline[wlen - 1] = L'\0';
1780 wlen--;
1782 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1783 wline[wlen - 1] = L'\0';
1784 wlen--;
1787 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1788 wline[i] = L'\0';
1790 if (widthp)
1791 *widthp = cols;
1792 if (scrollxp)
1793 *scrollxp = scrollx;
1794 if (err)
1795 free(wline);
1796 else
1797 *wlinep = wline;
1798 return err;
1801 static const struct got_error*
1802 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1803 struct got_object_id *id, struct got_repository *repo)
1805 static const struct got_error *err = NULL;
1806 struct got_reflist_entry *re;
1807 char *s;
1808 const char *name;
1810 *refs_str = NULL;
1812 TAILQ_FOREACH(re, refs, entry) {
1813 struct got_tag_object *tag = NULL;
1814 struct got_object_id *ref_id;
1815 int cmp;
1817 name = got_ref_get_name(re->ref);
1818 if (strcmp(name, GOT_REF_HEAD) == 0)
1819 continue;
1820 if (strncmp(name, "refs/", 5) == 0)
1821 name += 5;
1822 if (strncmp(name, "got/", 4) == 0 &&
1823 strncmp(name, "got/backup/", 11) != 0)
1824 continue;
1825 if (strncmp(name, "heads/", 6) == 0)
1826 name += 6;
1827 if (strncmp(name, "remotes/", 8) == 0) {
1828 name += 8;
1829 s = strstr(name, "/" GOT_REF_HEAD);
1830 if (s != NULL && s[strlen(s)] == '\0')
1831 continue;
1833 err = got_ref_resolve(&ref_id, repo, re->ref);
1834 if (err)
1835 break;
1836 if (strncmp(name, "tags/", 5) == 0) {
1837 err = got_object_open_as_tag(&tag, repo, ref_id);
1838 if (err) {
1839 if (err->code != GOT_ERR_OBJ_TYPE) {
1840 free(ref_id);
1841 break;
1843 /* Ref points at something other than a tag. */
1844 err = NULL;
1845 tag = NULL;
1848 cmp = got_object_id_cmp(tag ?
1849 got_object_tag_get_object_id(tag) : ref_id, id);
1850 free(ref_id);
1851 if (tag)
1852 got_object_tag_close(tag);
1853 if (cmp != 0)
1854 continue;
1855 s = *refs_str;
1856 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1857 s ? ", " : "", name) == -1) {
1858 err = got_error_from_errno("asprintf");
1859 free(s);
1860 *refs_str = NULL;
1861 break;
1863 free(s);
1866 return err;
1869 static const struct got_error *
1870 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1871 int col_tab_align)
1873 char *smallerthan;
1875 smallerthan = strchr(author, '<');
1876 if (smallerthan && smallerthan[1] != '\0')
1877 author = smallerthan + 1;
1878 author[strcspn(author, "@>")] = '\0';
1879 return format_line(wauthor, author_width, NULL, author, 0, limit,
1880 col_tab_align, 0);
1883 static const struct got_error *
1884 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1885 struct got_object_id *id, const size_t date_display_cols,
1886 int author_display_cols)
1888 struct tog_log_view_state *s = &view->state.log;
1889 const struct got_error *err = NULL;
1890 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1891 char *logmsg0 = NULL, *logmsg = NULL;
1892 char *author = NULL;
1893 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1894 int author_width, logmsg_width;
1895 char *newline, *line = NULL;
1896 int col, limit, scrollx;
1897 const int avail = view->ncols;
1898 struct tm tm;
1899 time_t committer_time;
1900 struct tog_color *tc;
1902 committer_time = got_object_commit_get_committer_time(commit);
1903 if (gmtime_r(&committer_time, &tm) == NULL)
1904 return got_error_from_errno("gmtime_r");
1905 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1906 return got_error(GOT_ERR_NO_SPACE);
1908 if (avail <= date_display_cols)
1909 limit = MIN(sizeof(datebuf) - 1, avail);
1910 else
1911 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1912 tc = get_color(&s->colors, TOG_COLOR_DATE);
1913 if (tc)
1914 wattr_on(view->window,
1915 COLOR_PAIR(tc->colorpair), NULL);
1916 waddnstr(view->window, datebuf, limit);
1917 if (tc)
1918 wattr_off(view->window,
1919 COLOR_PAIR(tc->colorpair), NULL);
1920 col = limit;
1921 if (col > avail)
1922 goto done;
1924 if (avail >= 120) {
1925 char *id_str;
1926 err = got_object_id_str(&id_str, id);
1927 if (err)
1928 goto done;
1929 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1930 if (tc)
1931 wattr_on(view->window,
1932 COLOR_PAIR(tc->colorpair), NULL);
1933 wprintw(view->window, "%.8s ", id_str);
1934 if (tc)
1935 wattr_off(view->window,
1936 COLOR_PAIR(tc->colorpair), NULL);
1937 free(id_str);
1938 col += 9;
1939 if (col > avail)
1940 goto done;
1943 author = strdup(got_object_commit_get_author(commit));
1944 if (author == NULL) {
1945 err = got_error_from_errno("strdup");
1946 goto done;
1948 err = format_author(&wauthor, &author_width, author, avail - col, col);
1949 if (err)
1950 goto done;
1951 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1952 if (tc)
1953 wattr_on(view->window,
1954 COLOR_PAIR(tc->colorpair), NULL);
1955 waddwstr(view->window, wauthor);
1956 if (tc)
1957 wattr_off(view->window,
1958 COLOR_PAIR(tc->colorpair), NULL);
1959 col += author_width;
1960 while (col < avail && author_width < author_display_cols + 2) {
1961 waddch(view->window, ' ');
1962 col++;
1963 author_width++;
1965 if (col > avail)
1966 goto done;
1968 err = got_object_commit_get_logmsg(&logmsg0, commit);
1969 if (err)
1970 goto done;
1971 logmsg = logmsg0;
1972 while (*logmsg == '\n')
1973 logmsg++;
1974 newline = strchr(logmsg, '\n');
1975 if (newline)
1976 *newline = '\0';
1977 limit = avail - col;
1978 if (view->child && !view_is_hsplit_top(view) && limit > 0)
1979 limit--; /* for the border */
1980 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1981 limit, col, 1);
1982 if (err)
1983 goto done;
1984 waddwstr(view->window, &wlogmsg[scrollx]);
1985 col += MAX(logmsg_width, 0);
1986 while (col < avail) {
1987 waddch(view->window, ' ');
1988 col++;
1990 done:
1991 free(logmsg0);
1992 free(wlogmsg);
1993 free(author);
1994 free(wauthor);
1995 free(line);
1996 return err;
1999 static struct commit_queue_entry *
2000 alloc_commit_queue_entry(struct got_commit_object *commit,
2001 struct got_object_id *id)
2003 struct commit_queue_entry *entry;
2005 entry = calloc(1, sizeof(*entry));
2006 if (entry == NULL)
2007 return NULL;
2009 entry->id = id;
2010 entry->commit = commit;
2011 return entry;
2014 static void
2015 pop_commit(struct commit_queue *commits)
2017 struct commit_queue_entry *entry;
2019 entry = TAILQ_FIRST(&commits->head);
2020 TAILQ_REMOVE(&commits->head, entry, entry);
2021 got_object_commit_close(entry->commit);
2022 commits->ncommits--;
2023 /* Don't free entry->id! It is owned by the commit graph. */
2024 free(entry);
2027 static void
2028 free_commits(struct commit_queue *commits)
2030 while (!TAILQ_EMPTY(&commits->head))
2031 pop_commit(commits);
2034 static const struct got_error *
2035 match_commit(int *have_match, struct got_object_id *id,
2036 struct got_commit_object *commit, regex_t *regex)
2038 const struct got_error *err = NULL;
2039 regmatch_t regmatch;
2040 char *id_str = NULL, *logmsg = NULL;
2042 *have_match = 0;
2044 err = got_object_id_str(&id_str, id);
2045 if (err)
2046 return err;
2048 err = got_object_commit_get_logmsg(&logmsg, commit);
2049 if (err)
2050 goto done;
2052 if (regexec(regex, got_object_commit_get_author(commit), 1,
2053 &regmatch, 0) == 0 ||
2054 regexec(regex, got_object_commit_get_committer(commit), 1,
2055 &regmatch, 0) == 0 ||
2056 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2057 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2058 *have_match = 1;
2059 done:
2060 free(id_str);
2061 free(logmsg);
2062 return err;
2065 static const struct got_error *
2066 queue_commits(struct tog_log_thread_args *a)
2068 const struct got_error *err = NULL;
2071 * We keep all commits open throughout the lifetime of the log
2072 * view in order to avoid having to re-fetch commits from disk
2073 * while updating the display.
2075 do {
2076 struct got_object_id *id;
2077 struct got_commit_object *commit;
2078 struct commit_queue_entry *entry;
2079 int errcode;
2081 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2082 NULL, NULL);
2083 if (err || id == NULL)
2084 break;
2086 err = got_object_open_as_commit(&commit, a->repo, id);
2087 if (err)
2088 break;
2089 entry = alloc_commit_queue_entry(commit, id);
2090 if (entry == NULL) {
2091 err = got_error_from_errno("alloc_commit_queue_entry");
2092 break;
2095 errcode = pthread_mutex_lock(&tog_mutex);
2096 if (errcode) {
2097 err = got_error_set_errno(errcode,
2098 "pthread_mutex_lock");
2099 break;
2102 entry->idx = a->commits->ncommits;
2103 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2104 a->commits->ncommits++;
2106 if (*a->searching == TOG_SEARCH_FORWARD &&
2107 !*a->search_next_done) {
2108 int have_match;
2109 err = match_commit(&have_match, id, commit, a->regex);
2110 if (err)
2111 break;
2112 if (have_match)
2113 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2116 errcode = pthread_mutex_unlock(&tog_mutex);
2117 if (errcode && err == NULL)
2118 err = got_error_set_errno(errcode,
2119 "pthread_mutex_unlock");
2120 if (err)
2121 break;
2122 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2124 return err;
2127 static void
2128 select_commit(struct tog_log_view_state *s)
2130 struct commit_queue_entry *entry;
2131 int ncommits = 0;
2133 entry = s->first_displayed_entry;
2134 while (entry) {
2135 if (ncommits == s->selected) {
2136 s->selected_entry = entry;
2137 break;
2139 entry = TAILQ_NEXT(entry, entry);
2140 ncommits++;
2144 static const struct got_error *
2145 draw_commits(struct tog_view *view)
2147 const struct got_error *err = NULL;
2148 struct tog_log_view_state *s = &view->state.log;
2149 struct commit_queue_entry *entry = s->selected_entry;
2150 const int limit = view->nlines;
2151 int width;
2152 int ncommits, author_cols = 4;
2153 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2154 char *refs_str = NULL;
2155 wchar_t *wline;
2156 struct tog_color *tc;
2157 static const size_t date_display_cols = 12;
2159 if (s->selected_entry &&
2160 !(view->searching && view->search_next_done == 0)) {
2161 struct got_reflist_head *refs;
2162 err = got_object_id_str(&id_str, s->selected_entry->id);
2163 if (err)
2164 return err;
2165 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2166 s->selected_entry->id);
2167 if (refs) {
2168 err = build_refs_str(&refs_str, refs,
2169 s->selected_entry->id, s->repo);
2170 if (err)
2171 goto done;
2175 if (s->thread_args.commits_needed == 0)
2176 halfdelay(10); /* disable fast refresh */
2178 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2179 if (asprintf(&ncommits_str, " [%d/%d] %s",
2180 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2181 (view->searching && !view->search_next_done) ?
2182 "searching..." : "loading...") == -1) {
2183 err = got_error_from_errno("asprintf");
2184 goto done;
2186 } else {
2187 const char *search_str = NULL;
2189 if (view->searching) {
2190 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2191 search_str = "no more matches";
2192 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2193 search_str = "no matches found";
2194 else if (!view->search_next_done)
2195 search_str = "searching...";
2198 if (asprintf(&ncommits_str, " [%d/%d] %s",
2199 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2200 search_str ? search_str :
2201 (refs_str ? refs_str : "")) == -1) {
2202 err = got_error_from_errno("asprintf");
2203 goto done;
2207 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2208 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2209 "........................................",
2210 s->in_repo_path, ncommits_str) == -1) {
2211 err = got_error_from_errno("asprintf");
2212 header = NULL;
2213 goto done;
2215 } else if (asprintf(&header, "commit %s%s",
2216 id_str ? id_str : "........................................",
2217 ncommits_str) == -1) {
2218 err = got_error_from_errno("asprintf");
2219 header = NULL;
2220 goto done;
2222 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2223 if (err)
2224 goto done;
2226 werase(view->window);
2228 if (view_needs_focus_indication(view))
2229 wstandout(view->window);
2230 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2231 if (tc)
2232 wattr_on(view->window,
2233 COLOR_PAIR(tc->colorpair), NULL);
2234 waddwstr(view->window, wline);
2235 if (tc)
2236 wattr_off(view->window,
2237 COLOR_PAIR(tc->colorpair), NULL);
2238 while (width < view->ncols) {
2239 waddch(view->window, ' ');
2240 width++;
2242 if (view_needs_focus_indication(view))
2243 wstandend(view->window);
2244 free(wline);
2245 if (limit <= 1)
2246 goto done;
2248 /* Grow author column size if necessary, and set view->maxx. */
2249 entry = s->first_displayed_entry;
2250 ncommits = 0;
2251 view->maxx = 0;
2252 while (entry) {
2253 char *author, *eol, *msg, *msg0;
2254 wchar_t *wauthor, *wmsg;
2255 int width;
2256 if (ncommits >= limit - 1)
2257 break;
2258 author = strdup(got_object_commit_get_author(entry->commit));
2259 if (author == NULL) {
2260 err = got_error_from_errno("strdup");
2261 goto done;
2263 err = format_author(&wauthor, &width, author, COLS,
2264 date_display_cols);
2265 if (author_cols < width)
2266 author_cols = width;
2267 free(wauthor);
2268 free(author);
2269 err = got_object_commit_get_logmsg(&msg0, entry->commit);
2270 if (err)
2271 goto done;
2272 msg = msg0;
2273 while (*msg == '\n')
2274 ++msg;
2275 if ((eol = strchr(msg, '\n')))
2276 *eol = '\0';
2277 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2278 date_display_cols + author_cols, 0);
2279 if (err)
2280 goto done;
2281 view->maxx = MAX(view->maxx, width);
2282 free(msg0);
2283 free(wmsg);
2284 ncommits++;
2285 entry = TAILQ_NEXT(entry, entry);
2288 entry = s->first_displayed_entry;
2289 s->last_displayed_entry = s->first_displayed_entry;
2290 ncommits = 0;
2291 while (entry) {
2292 if (ncommits >= limit - 1)
2293 break;
2294 if (ncommits == s->selected)
2295 wstandout(view->window);
2296 err = draw_commit(view, entry->commit, entry->id,
2297 date_display_cols, author_cols);
2298 if (ncommits == s->selected)
2299 wstandend(view->window);
2300 if (err)
2301 goto done;
2302 ncommits++;
2303 s->last_displayed_entry = entry;
2304 entry = TAILQ_NEXT(entry, entry);
2307 view_border(view);
2308 done:
2309 free(id_str);
2310 free(refs_str);
2311 free(ncommits_str);
2312 free(header);
2313 return err;
2316 static void
2317 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2319 struct commit_queue_entry *entry;
2320 int nscrolled = 0;
2322 entry = TAILQ_FIRST(&s->commits.head);
2323 if (s->first_displayed_entry == entry)
2324 return;
2326 entry = s->first_displayed_entry;
2327 while (entry && nscrolled < maxscroll) {
2328 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2329 if (entry) {
2330 s->first_displayed_entry = entry;
2331 nscrolled++;
2336 static const struct got_error *
2337 trigger_log_thread(struct tog_view *view, int wait)
2339 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2340 int errcode;
2342 halfdelay(1); /* fast refresh while loading commits */
2344 while (!ta->log_complete && !tog_thread_error &&
2345 (ta->commits_needed > 0 || ta->load_all)) {
2346 /* Wake the log thread. */
2347 errcode = pthread_cond_signal(&ta->need_commits);
2348 if (errcode)
2349 return got_error_set_errno(errcode,
2350 "pthread_cond_signal");
2353 * The mutex will be released while the view loop waits
2354 * in wgetch(), at which time the log thread will run.
2356 if (!wait)
2357 break;
2359 /* Display progress update in log view. */
2360 show_log_view(view);
2361 update_panels();
2362 doupdate();
2364 /* Wait right here while next commit is being loaded. */
2365 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2366 if (errcode)
2367 return got_error_set_errno(errcode,
2368 "pthread_cond_wait");
2370 /* Display progress update in log view. */
2371 show_log_view(view);
2372 update_panels();
2373 doupdate();
2376 return NULL;
2379 static const struct got_error *
2380 request_log_commits(struct tog_view *view)
2382 struct tog_log_view_state *state = &view->state.log;
2383 const struct got_error *err = NULL;
2385 state->thread_args.commits_needed = view->nscrolled;
2386 err = trigger_log_thread(view, 1);
2387 view->nscrolled = 0;
2389 return err;
2392 static const struct got_error *
2393 log_scroll_down(struct tog_view *view, int maxscroll)
2395 struct tog_log_view_state *s = &view->state.log;
2396 const struct got_error *err = NULL;
2397 struct commit_queue_entry *pentry;
2398 int nscrolled = 0, ncommits_needed;
2400 if (s->last_displayed_entry == NULL)
2401 return NULL;
2403 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2404 if (s->commits.ncommits < ncommits_needed &&
2405 !s->thread_args.log_complete) {
2407 * Ask the log thread for required amount of commits.
2409 s->thread_args.commits_needed += maxscroll;
2410 err = trigger_log_thread(view, 1);
2411 if (err)
2412 return err;
2415 do {
2416 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2417 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2418 break;
2420 s->last_displayed_entry = pentry ?
2421 pentry : s->last_displayed_entry;;
2423 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2424 if (pentry == NULL)
2425 break;
2426 s->first_displayed_entry = pentry;
2427 } while (++nscrolled < maxscroll);
2429 if (view->mode == TOG_VIEW_SPLIT_HRZN)
2430 view->nscrolled += nscrolled;
2431 else
2432 view->nscrolled = 0;
2434 return err;
2437 static const struct got_error *
2438 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2439 struct got_commit_object *commit, struct got_object_id *commit_id,
2440 struct tog_view *log_view, struct got_repository *repo)
2442 const struct got_error *err;
2443 struct got_object_qid *parent_id;
2444 struct tog_view *diff_view;
2446 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2447 if (diff_view == NULL)
2448 return got_error_from_errno("view_open");
2450 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2451 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2452 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2453 if (err == NULL)
2454 *new_view = diff_view;
2455 return err;
2458 static const struct got_error *
2459 tree_view_visit_subtree(struct tog_tree_view_state *s,
2460 struct got_tree_object *subtree)
2462 struct tog_parent_tree *parent;
2464 parent = calloc(1, sizeof(*parent));
2465 if (parent == NULL)
2466 return got_error_from_errno("calloc");
2468 parent->tree = s->tree;
2469 parent->first_displayed_entry = s->first_displayed_entry;
2470 parent->selected_entry = s->selected_entry;
2471 parent->selected = s->selected;
2472 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2473 s->tree = subtree;
2474 s->selected = 0;
2475 s->first_displayed_entry = NULL;
2476 return NULL;
2479 static const struct got_error *
2480 tree_view_walk_path(struct tog_tree_view_state *s,
2481 struct got_commit_object *commit, const char *path)
2483 const struct got_error *err = NULL;
2484 struct got_tree_object *tree = NULL;
2485 const char *p;
2486 char *slash, *subpath = NULL;
2488 /* Walk the path and open corresponding tree objects. */
2489 p = path;
2490 while (*p) {
2491 struct got_tree_entry *te;
2492 struct got_object_id *tree_id;
2493 char *te_name;
2495 while (p[0] == '/')
2496 p++;
2498 /* Ensure the correct subtree entry is selected. */
2499 slash = strchr(p, '/');
2500 if (slash == NULL)
2501 te_name = strdup(p);
2502 else
2503 te_name = strndup(p, slash - p);
2504 if (te_name == NULL) {
2505 err = got_error_from_errno("strndup");
2506 break;
2508 te = got_object_tree_find_entry(s->tree, te_name);
2509 if (te == NULL) {
2510 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2511 free(te_name);
2512 break;
2514 free(te_name);
2515 s->first_displayed_entry = s->selected_entry = te;
2517 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2518 break; /* jump to this file's entry */
2520 slash = strchr(p, '/');
2521 if (slash)
2522 subpath = strndup(path, slash - path);
2523 else
2524 subpath = strdup(path);
2525 if (subpath == NULL) {
2526 err = got_error_from_errno("strdup");
2527 break;
2530 err = got_object_id_by_path(&tree_id, s->repo, commit,
2531 subpath);
2532 if (err)
2533 break;
2535 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2536 free(tree_id);
2537 if (err)
2538 break;
2540 err = tree_view_visit_subtree(s, tree);
2541 if (err) {
2542 got_object_tree_close(tree);
2543 break;
2545 if (slash == NULL)
2546 break;
2547 free(subpath);
2548 subpath = NULL;
2549 p = slash;
2552 free(subpath);
2553 return err;
2556 static const struct got_error *
2557 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2558 struct commit_queue_entry *entry, const char *path,
2559 const char *head_ref_name, struct got_repository *repo)
2561 const struct got_error *err = NULL;
2562 struct tog_tree_view_state *s;
2563 struct tog_view *tree_view;
2565 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2566 if (tree_view == NULL)
2567 return got_error_from_errno("view_open");
2569 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2570 if (err)
2571 return err;
2572 s = &tree_view->state.tree;
2574 *new_view = tree_view;
2576 if (got_path_is_root_dir(path))
2577 return NULL;
2579 return tree_view_walk_path(s, entry->commit, path);
2582 static const struct got_error *
2583 block_signals_used_by_main_thread(void)
2585 sigset_t sigset;
2586 int errcode;
2588 if (sigemptyset(&sigset) == -1)
2589 return got_error_from_errno("sigemptyset");
2591 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2592 if (sigaddset(&sigset, SIGWINCH) == -1)
2593 return got_error_from_errno("sigaddset");
2594 if (sigaddset(&sigset, SIGCONT) == -1)
2595 return got_error_from_errno("sigaddset");
2596 if (sigaddset(&sigset, SIGINT) == -1)
2597 return got_error_from_errno("sigaddset");
2598 if (sigaddset(&sigset, SIGTERM) == -1)
2599 return got_error_from_errno("sigaddset");
2601 /* ncurses handles SIGTSTP */
2602 if (sigaddset(&sigset, SIGTSTP) == -1)
2603 return got_error_from_errno("sigaddset");
2605 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2606 if (errcode)
2607 return got_error_set_errno(errcode, "pthread_sigmask");
2609 return NULL;
2612 static void *
2613 log_thread(void *arg)
2615 const struct got_error *err = NULL;
2616 int errcode = 0;
2617 struct tog_log_thread_args *a = arg;
2618 int done = 0;
2621 * Sync startup with main thread such that we begin our
2622 * work once view_input() has released the mutex.
2624 errcode = pthread_mutex_lock(&tog_mutex);
2625 if (errcode) {
2626 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2627 return (void *)err;
2630 err = block_signals_used_by_main_thread();
2631 if (err) {
2632 pthread_mutex_unlock(&tog_mutex);
2633 goto done;
2636 while (!done && !err && !tog_fatal_signal_received()) {
2637 errcode = pthread_mutex_unlock(&tog_mutex);
2638 if (errcode) {
2639 err = got_error_set_errno(errcode,
2640 "pthread_mutex_unlock");
2641 goto done;
2643 err = queue_commits(a);
2644 if (err) {
2645 if (err->code != GOT_ERR_ITER_COMPLETED)
2646 goto done;
2647 err = NULL;
2648 done = 1;
2649 } else if (a->commits_needed > 0 && !a->load_all)
2650 a->commits_needed--;
2652 errcode = pthread_mutex_lock(&tog_mutex);
2653 if (errcode) {
2654 err = got_error_set_errno(errcode,
2655 "pthread_mutex_lock");
2656 goto done;
2657 } else if (*a->quit)
2658 done = 1;
2659 else if (*a->first_displayed_entry == NULL) {
2660 *a->first_displayed_entry =
2661 TAILQ_FIRST(&a->commits->head);
2662 *a->selected_entry = *a->first_displayed_entry;
2665 errcode = pthread_cond_signal(&a->commit_loaded);
2666 if (errcode) {
2667 err = got_error_set_errno(errcode,
2668 "pthread_cond_signal");
2669 pthread_mutex_unlock(&tog_mutex);
2670 goto done;
2673 if (done)
2674 a->commits_needed = 0;
2675 else {
2676 if (a->commits_needed == 0 && !a->load_all) {
2677 errcode = pthread_cond_wait(&a->need_commits,
2678 &tog_mutex);
2679 if (errcode) {
2680 err = got_error_set_errno(errcode,
2681 "pthread_cond_wait");
2682 pthread_mutex_unlock(&tog_mutex);
2683 goto done;
2685 if (*a->quit)
2686 done = 1;
2690 a->log_complete = 1;
2691 errcode = pthread_mutex_unlock(&tog_mutex);
2692 if (errcode)
2693 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2694 done:
2695 if (err) {
2696 tog_thread_error = 1;
2697 pthread_cond_signal(&a->commit_loaded);
2699 return (void *)err;
2702 static const struct got_error *
2703 stop_log_thread(struct tog_log_view_state *s)
2705 const struct got_error *err = NULL, *thread_err = NULL;
2706 int errcode;
2708 if (s->thread) {
2709 s->quit = 1;
2710 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2711 if (errcode)
2712 return got_error_set_errno(errcode,
2713 "pthread_cond_signal");
2714 errcode = pthread_mutex_unlock(&tog_mutex);
2715 if (errcode)
2716 return got_error_set_errno(errcode,
2717 "pthread_mutex_unlock");
2718 errcode = pthread_join(s->thread, (void **)&thread_err);
2719 if (errcode)
2720 return got_error_set_errno(errcode, "pthread_join");
2721 errcode = pthread_mutex_lock(&tog_mutex);
2722 if (errcode)
2723 return got_error_set_errno(errcode,
2724 "pthread_mutex_lock");
2725 s->thread = 0; //NULL;
2728 if (s->thread_args.repo) {
2729 err = got_repo_close(s->thread_args.repo);
2730 s->thread_args.repo = NULL;
2733 if (s->thread_args.pack_fds) {
2734 const struct got_error *pack_err =
2735 got_repo_pack_fds_close(s->thread_args.pack_fds);
2736 if (err == NULL)
2737 err = pack_err;
2738 s->thread_args.pack_fds = NULL;
2741 if (s->thread_args.graph) {
2742 got_commit_graph_close(s->thread_args.graph);
2743 s->thread_args.graph = NULL;
2746 return err ? err : thread_err;
2749 static const struct got_error *
2750 close_log_view(struct tog_view *view)
2752 const struct got_error *err = NULL;
2753 struct tog_log_view_state *s = &view->state.log;
2754 int errcode;
2756 err = stop_log_thread(s);
2758 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2759 if (errcode && err == NULL)
2760 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2762 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2763 if (errcode && err == NULL)
2764 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2766 free_commits(&s->commits);
2767 free(s->in_repo_path);
2768 s->in_repo_path = NULL;
2769 free(s->start_id);
2770 s->start_id = NULL;
2771 free(s->head_ref_name);
2772 s->head_ref_name = NULL;
2773 return err;
2776 static const struct got_error *
2777 search_start_log_view(struct tog_view *view)
2779 struct tog_log_view_state *s = &view->state.log;
2781 s->matched_entry = NULL;
2782 s->search_entry = NULL;
2783 return NULL;
2786 static const struct got_error *
2787 search_next_log_view(struct tog_view *view)
2789 const struct got_error *err = NULL;
2790 struct tog_log_view_state *s = &view->state.log;
2791 struct commit_queue_entry *entry;
2793 /* Display progress update in log view. */
2794 show_log_view(view);
2795 update_panels();
2796 doupdate();
2798 if (s->search_entry) {
2799 int errcode, ch;
2800 errcode = pthread_mutex_unlock(&tog_mutex);
2801 if (errcode)
2802 return got_error_set_errno(errcode,
2803 "pthread_mutex_unlock");
2804 ch = wgetch(view->window);
2805 errcode = pthread_mutex_lock(&tog_mutex);
2806 if (errcode)
2807 return got_error_set_errno(errcode,
2808 "pthread_mutex_lock");
2809 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2810 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2811 return NULL;
2813 if (view->searching == TOG_SEARCH_FORWARD)
2814 entry = TAILQ_NEXT(s->search_entry, entry);
2815 else
2816 entry = TAILQ_PREV(s->search_entry,
2817 commit_queue_head, entry);
2818 } else if (s->matched_entry) {
2819 int matched_idx = s->matched_entry->idx;
2820 int selected_idx = s->selected_entry->idx;
2823 * If the user has moved the cursor after we hit a match,
2824 * the position from where we should continue searching
2825 * might have changed.
2827 if (view->searching == TOG_SEARCH_FORWARD) {
2828 if (matched_idx > selected_idx)
2829 entry = TAILQ_NEXT(s->selected_entry, entry);
2830 else
2831 entry = TAILQ_NEXT(s->matched_entry, entry);
2832 } else {
2833 if (matched_idx < selected_idx)
2834 entry = TAILQ_PREV(s->selected_entry,
2835 commit_queue_head, entry);
2836 else
2837 entry = TAILQ_PREV(s->matched_entry,
2838 commit_queue_head, entry);
2840 } else {
2841 entry = s->selected_entry;
2844 while (1) {
2845 int have_match = 0;
2847 if (entry == NULL) {
2848 if (s->thread_args.log_complete ||
2849 view->searching == TOG_SEARCH_BACKWARD) {
2850 view->search_next_done =
2851 (s->matched_entry == NULL ?
2852 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2853 s->search_entry = NULL;
2854 return NULL;
2857 * Poke the log thread for more commits and return,
2858 * allowing the main loop to make progress. Search
2859 * will resume at s->search_entry once we come back.
2861 s->thread_args.commits_needed++;
2862 return trigger_log_thread(view, 0);
2865 err = match_commit(&have_match, entry->id, entry->commit,
2866 &view->regex);
2867 if (err)
2868 break;
2869 if (have_match) {
2870 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2871 s->matched_entry = entry;
2872 break;
2875 s->search_entry = entry;
2876 if (view->searching == TOG_SEARCH_FORWARD)
2877 entry = TAILQ_NEXT(entry, entry);
2878 else
2879 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2882 if (s->matched_entry) {
2883 int cur = s->selected_entry->idx;
2884 while (cur < s->matched_entry->idx) {
2885 err = input_log_view(NULL, view, KEY_DOWN);
2886 if (err)
2887 return err;
2888 cur++;
2890 while (cur > s->matched_entry->idx) {
2891 err = input_log_view(NULL, view, KEY_UP);
2892 if (err)
2893 return err;
2894 cur--;
2898 s->search_entry = NULL;
2900 return NULL;
2903 static const struct got_error *
2904 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2905 struct got_repository *repo, const char *head_ref_name,
2906 const char *in_repo_path, int log_branches)
2908 const struct got_error *err = NULL;
2909 struct tog_log_view_state *s = &view->state.log;
2910 struct got_repository *thread_repo = NULL;
2911 struct got_commit_graph *thread_graph = NULL;
2912 int errcode;
2914 if (in_repo_path != s->in_repo_path) {
2915 free(s->in_repo_path);
2916 s->in_repo_path = strdup(in_repo_path);
2917 if (s->in_repo_path == NULL)
2918 return got_error_from_errno("strdup");
2921 /* The commit queue only contains commits being displayed. */
2922 TAILQ_INIT(&s->commits.head);
2923 s->commits.ncommits = 0;
2925 s->repo = repo;
2926 if (head_ref_name) {
2927 s->head_ref_name = strdup(head_ref_name);
2928 if (s->head_ref_name == NULL) {
2929 err = got_error_from_errno("strdup");
2930 goto done;
2933 s->start_id = got_object_id_dup(start_id);
2934 if (s->start_id == NULL) {
2935 err = got_error_from_errno("got_object_id_dup");
2936 goto done;
2938 s->log_branches = log_branches;
2940 STAILQ_INIT(&s->colors);
2941 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2942 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2943 get_color_value("TOG_COLOR_COMMIT"));
2944 if (err)
2945 goto done;
2946 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2947 get_color_value("TOG_COLOR_AUTHOR"));
2948 if (err) {
2949 free_colors(&s->colors);
2950 goto done;
2952 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2953 get_color_value("TOG_COLOR_DATE"));
2954 if (err) {
2955 free_colors(&s->colors);
2956 goto done;
2960 view->show = show_log_view;
2961 view->input = input_log_view;
2962 view->close = close_log_view;
2963 view->search_start = search_start_log_view;
2964 view->search_next = search_next_log_view;
2966 if (s->thread_args.pack_fds == NULL) {
2967 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2968 if (err)
2969 goto done;
2971 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2972 s->thread_args.pack_fds);
2973 if (err)
2974 goto done;
2975 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2976 !s->log_branches);
2977 if (err)
2978 goto done;
2979 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2980 s->repo, NULL, NULL);
2981 if (err)
2982 goto done;
2984 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2985 if (errcode) {
2986 err = got_error_set_errno(errcode, "pthread_cond_init");
2987 goto done;
2989 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2990 if (errcode) {
2991 err = got_error_set_errno(errcode, "pthread_cond_init");
2992 goto done;
2995 s->thread_args.commits_needed = view->nlines;
2996 s->thread_args.graph = thread_graph;
2997 s->thread_args.commits = &s->commits;
2998 s->thread_args.in_repo_path = s->in_repo_path;
2999 s->thread_args.start_id = s->start_id;
3000 s->thread_args.repo = thread_repo;
3001 s->thread_args.log_complete = 0;
3002 s->thread_args.quit = &s->quit;
3003 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3004 s->thread_args.selected_entry = &s->selected_entry;
3005 s->thread_args.searching = &view->searching;
3006 s->thread_args.search_next_done = &view->search_next_done;
3007 s->thread_args.regex = &view->regex;
3008 done:
3009 if (err)
3010 close_log_view(view);
3011 return err;
3014 static const struct got_error *
3015 show_log_view(struct tog_view *view)
3017 const struct got_error *err;
3018 struct tog_log_view_state *s = &view->state.log;
3020 if (s->thread == 0) { //NULL) {
3021 int errcode = pthread_create(&s->thread, NULL, log_thread,
3022 &s->thread_args);
3023 if (errcode)
3024 return got_error_set_errno(errcode, "pthread_create");
3025 if (s->thread_args.commits_needed > 0) {
3026 err = trigger_log_thread(view, 1);
3027 if (err)
3028 return err;
3032 return draw_commits(view);
3035 static void
3036 log_move_cursor_up(struct tog_view *view, int page, int home)
3038 struct tog_log_view_state *s = &view->state.log;
3040 if (s->selected_entry->idx == 0)
3041 view->count = 0;
3042 if (s->first_displayed_entry == NULL)
3043 return;
3045 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3046 || home)
3047 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3049 if (!page && !home && s->selected > 0)
3050 --s->selected;
3051 else
3052 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3054 select_commit(s);
3055 return;
3058 static const struct got_error *
3059 log_move_cursor_down(struct tog_view *view, int page)
3061 struct tog_log_view_state *s = &view->state.log;
3062 struct commit_queue_entry *first;
3063 const struct got_error *err = NULL;
3065 first = s->first_displayed_entry;
3066 if (first == NULL) {
3067 view->count = 0;
3068 return NULL;
3071 if (s->thread_args.log_complete &&
3072 s->selected_entry->idx >= s->commits.ncommits - 1)
3073 return NULL;
3075 if (!page) {
3076 int eos = view->nlines - 2;
3078 if (view_is_hsplit_top(view))
3079 --eos; /* border consumes the last line */
3080 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3081 ++s->selected;
3082 else
3083 err = log_scroll_down(view, 1);
3084 } else if (s->thread_args.load_all) {
3085 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3086 s->selected += MIN(s->last_displayed_entry->idx -
3087 s->selected_entry->idx, page + 1);
3088 else
3089 err = log_scroll_down(view, MIN(page,
3090 s->commits.ncommits - s->selected_entry->idx - 1));
3091 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3092 } else {
3093 err = log_scroll_down(view, page);
3094 if (err)
3095 return err;
3096 if (first == s->first_displayed_entry && s->selected <
3097 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
3098 s->selected = MIN(s->commits.ncommits - 1, page);
3101 if (err)
3102 return err;
3105 * We might necessarily overshoot in horizontal
3106 * splits; if so, select the last displayed commit.
3108 s->selected = MIN(s->selected,
3109 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3111 select_commit(s);
3113 if (s->thread_args.log_complete &&
3114 s->selected_entry->idx == s->commits.ncommits - 1)
3115 view->count = 0;
3117 return NULL;
3120 static void
3121 view_get_split(struct tog_view *view, int *y, int *x)
3123 *x = 0;
3124 *y = 0;
3126 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3127 if (view->child && view->child->resized_y)
3128 *y = view->child->resized_y;
3129 else if (view->resized_y)
3130 *y = view->resized_y;
3131 else
3132 *y = view_split_begin_y(view->lines);
3133 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3134 if (view->child && view->child->resized_x)
3135 *x = view->child->resized_x;
3136 else if (view->resized_x)
3137 *x = view->resized_x;
3138 else
3139 *x = view_split_begin_x(view->begin_x);
3143 /* Split view horizontally at y and offset view->state->selected line. */
3144 static const struct got_error *
3145 view_init_hsplit(struct tog_view *view, int y)
3147 const struct got_error *err = NULL;
3149 view->nlines = y;
3150 view->ncols = COLS;
3151 err = view_resize(view);
3152 if (err)
3153 return err;
3155 err = offset_selection_down(view);
3157 return err;
3160 static const struct got_error *
3161 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3163 const struct got_error *err = NULL;
3164 struct tog_log_view_state *s = &view->state.log;
3165 struct tog_view *diff_view = NULL, *tree_view = NULL;
3166 struct tog_view *ref_view = NULL;
3167 struct commit_queue_entry *entry;
3168 int begin_x = 0, begin_y = 0, eos, n, nscroll;
3170 if (s->thread_args.load_all) {
3171 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3172 s->thread_args.load_all = 0;
3173 else if (s->thread_args.log_complete) {
3174 err = log_move_cursor_down(view, s->commits.ncommits);
3175 s->thread_args.load_all = 0;
3177 return err;
3180 eos = nscroll = view->nlines - 1;
3181 if (view_is_hsplit_top(view))
3182 --eos; /* border */
3184 switch (ch) {
3185 case 'q':
3186 s->quit = 1;
3187 break;
3188 case '0':
3189 view->x = 0;
3190 break;
3191 case '$':
3192 view->x = MAX(view->maxx - view->ncols / 2, 0);
3193 view->count = 0;
3194 break;
3195 case KEY_RIGHT:
3196 case 'l':
3197 if (view->x + view->ncols / 2 < view->maxx)
3198 view->x += 2; /* move two columns right */
3199 else
3200 view->count = 0;
3201 break;
3202 case KEY_LEFT:
3203 case 'h':
3204 view->x -= MIN(view->x, 2); /* move two columns back */
3205 if (view->x <= 0)
3206 view->count = 0;
3207 break;
3208 case 'k':
3209 case KEY_UP:
3210 case '<':
3211 case ',':
3212 case CTRL('p'):
3213 log_move_cursor_up(view, 0, 0);
3214 break;
3215 case 'g':
3216 case KEY_HOME:
3217 log_move_cursor_up(view, 0, 1);
3218 view->count = 0;
3219 break;
3220 case CTRL('u'):
3221 case 'u':
3222 nscroll /= 2;
3223 /* FALL THROUGH */
3224 case KEY_PPAGE:
3225 case CTRL('b'):
3226 case 'b':
3227 log_move_cursor_up(view, nscroll, 0);
3228 break;
3229 case 'j':
3230 case KEY_DOWN:
3231 case '>':
3232 case '.':
3233 case CTRL('n'):
3234 err = log_move_cursor_down(view, 0);
3235 break;
3236 case 'G':
3237 case KEY_END: {
3238 /* We don't know yet how many commits, so we're forced to
3239 * traverse them all. */
3240 view->count = 0;
3241 if (!s->thread_args.log_complete) {
3242 s->thread_args.load_all = 1;
3243 return trigger_log_thread(view, 0);
3246 s->selected = 0;
3247 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3248 for (n = 0; n < eos; n++) {
3249 if (entry == NULL)
3250 break;
3251 s->first_displayed_entry = entry;
3252 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3254 if (n > 0)
3255 s->selected = n - 1;
3256 select_commit(s);
3257 break;
3259 case CTRL('d'):
3260 case 'd':
3261 nscroll /= 2;
3262 /* FALL THROUGH */
3263 case KEY_NPAGE:
3264 case CTRL('f'):
3265 case 'f':
3266 case ' ':
3267 err = log_move_cursor_down(view, nscroll);
3268 break;
3269 case KEY_RESIZE:
3270 if (s->selected > view->nlines - 2)
3271 s->selected = view->nlines - 2;
3272 if (s->selected > s->commits.ncommits - 1)
3273 s->selected = s->commits.ncommits - 1;
3274 select_commit(s);
3275 if (s->commits.ncommits < view->nlines - 1 &&
3276 !s->thread_args.log_complete) {
3277 s->thread_args.commits_needed += (view->nlines - 1) -
3278 s->commits.ncommits;
3279 err = trigger_log_thread(view, 1);
3281 break;
3282 case KEY_ENTER:
3283 case '\r':
3284 view->count = 0;
3285 if (s->selected_entry == NULL)
3286 break;
3288 /* get dimensions--don't split till initialisation succeeds */
3289 if (view_is_parent_view(view))
3290 view_get_split(view, &begin_y, &begin_x);
3292 err = open_diff_view_for_commit(&diff_view, begin_y, begin_x,
3293 s->selected_entry->commit, s->selected_entry->id,
3294 view, s->repo);
3295 if (err)
3296 break;
3298 if (view_is_parent_view(view) &&
3299 view->mode == TOG_VIEW_SPLIT_HRZN) { /* safe to split */
3300 err = view_init_hsplit(view, begin_y);
3301 if (err)
3302 break;
3305 view->focussed = 0;
3306 diff_view->focussed = 1;
3307 diff_view->mode = view->mode;
3308 diff_view->nlines = view->lines - begin_y;
3310 if (view_is_parent_view(view)) {
3311 view_transfer_size(diff_view, view);
3312 err = view_close_child(view);
3313 if (err)
3314 return err;
3315 err = view_set_child(view, diff_view);
3316 if (err)
3317 return err;
3318 view->focus_child = 1;
3319 } else
3320 *new_view = diff_view;
3321 break;
3322 case 't':
3323 view->count = 0;
3324 if (s->selected_entry == NULL)
3325 break;
3326 if (view_is_parent_view(view))
3327 view_get_split(view, &begin_y, &begin_x);
3328 err = browse_commit_tree(&tree_view, begin_y, begin_x,
3329 s->selected_entry, s->in_repo_path, s->head_ref_name,
3330 s->repo);
3331 if (err)
3332 break;
3333 if (view_is_parent_view(view) &&
3334 view->mode == TOG_VIEW_SPLIT_HRZN) {
3335 err = view_init_hsplit(view, begin_y);
3336 if (err)
3337 break;
3339 view->focussed = 0;
3340 tree_view->focussed = 1;
3341 tree_view->mode = view->mode;
3342 tree_view->nlines = view->lines - begin_y;
3343 if (view_is_parent_view(view)) {
3344 view_transfer_size(tree_view, view);
3345 err = view_close_child(view);
3346 if (err)
3347 return err;
3348 err = view_set_child(view, tree_view);
3349 if (err)
3350 return err;
3351 view->focus_child = 1;
3352 } else
3353 *new_view = tree_view;
3354 break;
3355 case KEY_BACKSPACE:
3356 case CTRL('l'):
3357 case 'B':
3358 view->count = 0;
3359 if (ch == KEY_BACKSPACE &&
3360 got_path_is_root_dir(s->in_repo_path))
3361 break;
3362 err = stop_log_thread(s);
3363 if (err)
3364 return err;
3365 if (ch == KEY_BACKSPACE) {
3366 char *parent_path;
3367 err = got_path_dirname(&parent_path, s->in_repo_path);
3368 if (err)
3369 return err;
3370 free(s->in_repo_path);
3371 s->in_repo_path = parent_path;
3372 s->thread_args.in_repo_path = s->in_repo_path;
3373 } else if (ch == CTRL('l')) {
3374 struct got_object_id *start_id;
3375 err = got_repo_match_object_id(&start_id, NULL,
3376 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3377 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3378 if (err)
3379 return err;
3380 free(s->start_id);
3381 s->start_id = start_id;
3382 s->thread_args.start_id = s->start_id;
3383 } else /* 'B' */
3384 s->log_branches = !s->log_branches;
3386 if (s->thread_args.pack_fds == NULL) {
3387 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3388 if (err)
3389 return err;
3391 err = got_repo_open(&s->thread_args.repo,
3392 got_repo_get_path(s->repo), NULL,
3393 s->thread_args.pack_fds);
3394 if (err)
3395 return err;
3396 tog_free_refs();
3397 err = tog_load_refs(s->repo, 0);
3398 if (err)
3399 return err;
3400 err = got_commit_graph_open(&s->thread_args.graph,
3401 s->in_repo_path, !s->log_branches);
3402 if (err)
3403 return err;
3404 err = got_commit_graph_iter_start(s->thread_args.graph,
3405 s->start_id, s->repo, NULL, NULL);
3406 if (err)
3407 return err;
3408 free_commits(&s->commits);
3409 s->first_displayed_entry = NULL;
3410 s->last_displayed_entry = NULL;
3411 s->selected_entry = NULL;
3412 s->selected = 0;
3413 s->thread_args.log_complete = 0;
3414 s->quit = 0;
3415 s->thread_args.commits_needed = view->lines;
3416 s->matched_entry = NULL;
3417 s->search_entry = NULL;
3418 break;
3419 case 'r':
3420 view->count = 0;
3421 if (view_is_parent_view(view))
3422 view_get_split(view, &begin_y, &begin_x);
3423 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
3424 if (ref_view == NULL)
3425 return got_error_from_errno("view_open");
3426 err = open_ref_view(ref_view, s->repo);
3427 if (err) {
3428 view_close(ref_view);
3429 return err;
3431 if (view_is_parent_view(view) &&
3432 view->mode == TOG_VIEW_SPLIT_HRZN) {
3433 err = view_init_hsplit(view, begin_y);
3434 if (err)
3435 break;
3437 view->focussed = 0;
3438 ref_view->focussed = 1;
3439 ref_view->mode = view->mode;
3440 ref_view->nlines = view->lines - begin_y;
3441 if (view_is_parent_view(view)) {
3442 view_transfer_size(ref_view, view);
3443 err = view_close_child(view);
3444 if (err)
3445 return err;
3446 err = view_set_child(view, ref_view);
3447 if (err)
3448 return err;
3449 view->focus_child = 1;
3450 } else
3451 *new_view = ref_view;
3452 break;
3453 default:
3454 view->count = 0;
3455 break;
3458 return err;
3461 static const struct got_error *
3462 apply_unveil(const char *repo_path, const char *worktree_path)
3464 const struct got_error *error;
3466 #ifdef PROFILE
3467 if (unveil("gmon.out", "rwc") != 0)
3468 return got_error_from_errno2("unveil", "gmon.out");
3469 #endif
3470 if (repo_path && unveil(repo_path, "r") != 0)
3471 return got_error_from_errno2("unveil", repo_path);
3473 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3474 return got_error_from_errno2("unveil", worktree_path);
3476 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3477 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3479 error = got_privsep_unveil_exec_helpers();
3480 if (error != NULL)
3481 return error;
3483 if (unveil(NULL, NULL) != 0)
3484 return got_error_from_errno("unveil");
3486 return NULL;
3489 static void
3490 init_curses(void)
3493 * Override default signal handlers before starting ncurses.
3494 * This should prevent ncurses from installing its own
3495 * broken cleanup() signal handler.
3497 signal(SIGWINCH, tog_sigwinch);
3498 signal(SIGPIPE, tog_sigpipe);
3499 signal(SIGCONT, tog_sigcont);
3500 signal(SIGINT, tog_sigint);
3501 signal(SIGTERM, tog_sigterm);
3503 initscr();
3504 cbreak();
3505 halfdelay(1); /* Do fast refresh while initial view is loading. */
3506 noecho();
3507 nonl();
3508 intrflush(stdscr, FALSE);
3509 keypad(stdscr, TRUE);
3510 curs_set(0);
3511 if (getenv("TOG_COLORS") != NULL) {
3512 start_color();
3513 use_default_colors();
3517 static const struct got_error *
3518 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3519 struct got_repository *repo, struct got_worktree *worktree)
3521 const struct got_error *err = NULL;
3523 if (argc == 0) {
3524 *in_repo_path = strdup("/");
3525 if (*in_repo_path == NULL)
3526 return got_error_from_errno("strdup");
3527 return NULL;
3530 if (worktree) {
3531 const char *prefix = got_worktree_get_path_prefix(worktree);
3532 char *p;
3534 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3535 if (err)
3536 return err;
3537 if (asprintf(in_repo_path, "%s%s%s", prefix,
3538 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3539 p) == -1) {
3540 err = got_error_from_errno("asprintf");
3541 *in_repo_path = NULL;
3543 free(p);
3544 } else
3545 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3547 return err;
3550 static const struct got_error *
3551 cmd_log(int argc, char *argv[])
3553 const struct got_error *error;
3554 struct got_repository *repo = NULL;
3555 struct got_worktree *worktree = NULL;
3556 struct got_object_id *start_id = NULL;
3557 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3558 char *start_commit = NULL, *label = NULL;
3559 struct got_reference *ref = NULL;
3560 const char *head_ref_name = NULL;
3561 int ch, log_branches = 0;
3562 struct tog_view *view;
3563 int *pack_fds = NULL;
3565 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3566 switch (ch) {
3567 case 'b':
3568 log_branches = 1;
3569 break;
3570 case 'c':
3571 start_commit = optarg;
3572 break;
3573 case 'r':
3574 repo_path = realpath(optarg, NULL);
3575 if (repo_path == NULL)
3576 return got_error_from_errno2("realpath",
3577 optarg);
3578 break;
3579 default:
3580 usage_log();
3581 /* NOTREACHED */
3585 argc -= optind;
3586 argv += optind;
3588 if (argc > 1)
3589 usage_log();
3591 error = got_repo_pack_fds_open(&pack_fds);
3592 if (error != NULL)
3593 goto done;
3595 if (repo_path == NULL) {
3596 cwd = getcwd(NULL, 0);
3597 if (cwd == NULL)
3598 return got_error_from_errno("getcwd");
3599 error = got_worktree_open(&worktree, cwd);
3600 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3601 goto done;
3602 if (worktree)
3603 repo_path =
3604 strdup(got_worktree_get_repo_path(worktree));
3605 else
3606 repo_path = strdup(cwd);
3607 if (repo_path == NULL) {
3608 error = got_error_from_errno("strdup");
3609 goto done;
3613 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3614 if (error != NULL)
3615 goto done;
3617 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3618 repo, worktree);
3619 if (error)
3620 goto done;
3622 init_curses();
3624 error = apply_unveil(got_repo_get_path(repo),
3625 worktree ? got_worktree_get_root_path(worktree) : NULL);
3626 if (error)
3627 goto done;
3629 /* already loaded by tog_log_with_path()? */
3630 if (TAILQ_EMPTY(&tog_refs)) {
3631 error = tog_load_refs(repo, 0);
3632 if (error)
3633 goto done;
3636 if (start_commit == NULL) {
3637 error = got_repo_match_object_id(&start_id, &label,
3638 worktree ? got_worktree_get_head_ref_name(worktree) :
3639 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3640 if (error)
3641 goto done;
3642 head_ref_name = label;
3643 } else {
3644 error = got_ref_open(&ref, repo, start_commit, 0);
3645 if (error == NULL)
3646 head_ref_name = got_ref_get_name(ref);
3647 else if (error->code != GOT_ERR_NOT_REF)
3648 goto done;
3649 error = got_repo_match_object_id(&start_id, NULL,
3650 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3651 if (error)
3652 goto done;
3655 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3656 if (view == NULL) {
3657 error = got_error_from_errno("view_open");
3658 goto done;
3660 error = open_log_view(view, start_id, repo, head_ref_name,
3661 in_repo_path, log_branches);
3662 if (error)
3663 goto done;
3664 if (worktree) {
3665 /* Release work tree lock. */
3666 got_worktree_close(worktree);
3667 worktree = NULL;
3669 error = view_loop(view);
3670 done:
3671 free(in_repo_path);
3672 free(repo_path);
3673 free(cwd);
3674 free(start_id);
3675 free(label);
3676 if (ref)
3677 got_ref_close(ref);
3678 if (repo) {
3679 const struct got_error *close_err = got_repo_close(repo);
3680 if (error == NULL)
3681 error = close_err;
3683 if (worktree)
3684 got_worktree_close(worktree);
3685 if (pack_fds) {
3686 const struct got_error *pack_err =
3687 got_repo_pack_fds_close(pack_fds);
3688 if (error == NULL)
3689 error = pack_err;
3691 tog_free_refs();
3692 return error;
3695 __dead static void
3696 usage_diff(void)
3698 endwin();
3699 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3700 "[-w] object1 object2\n", getprogname());
3701 exit(1);
3704 static int
3705 match_line(const char *line, regex_t *regex, size_t nmatch,
3706 regmatch_t *regmatch)
3708 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3711 static struct tog_color *
3712 match_color(struct tog_colors *colors, const char *line)
3714 struct tog_color *tc = NULL;
3716 STAILQ_FOREACH(tc, colors, entry) {
3717 if (match_line(line, &tc->regex, 0, NULL))
3718 return tc;
3721 return NULL;
3724 static const struct got_error *
3725 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3726 WINDOW *window, int skipcol, regmatch_t *regmatch)
3728 const struct got_error *err = NULL;
3729 char *exstr = NULL;
3730 wchar_t *wline = NULL;
3731 int rme, rms, n, width, scrollx;
3732 int width0 = 0, width1 = 0, width2 = 0;
3733 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3735 *wtotal = 0;
3737 rms = regmatch->rm_so;
3738 rme = regmatch->rm_eo;
3740 err = expand_tab(&exstr, line);
3741 if (err)
3742 return err;
3744 /* Split the line into 3 segments, according to match offsets. */
3745 seg0 = strndup(exstr, rms);
3746 if (seg0 == NULL) {
3747 err = got_error_from_errno("strndup");
3748 goto done;
3750 seg1 = strndup(exstr + rms, rme - rms);
3751 if (seg1 == NULL) {
3752 err = got_error_from_errno("strndup");
3753 goto done;
3755 seg2 = strdup(exstr + rme);
3756 if (seg2 == NULL) {
3757 err = got_error_from_errno("strndup");
3758 goto done;
3761 /* draw up to matched token if we haven't scrolled past it */
3762 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3763 col_tab_align, 1);
3764 if (err)
3765 goto done;
3766 n = MAX(width0 - skipcol, 0);
3767 if (n) {
3768 free(wline);
3769 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3770 wlimit, col_tab_align, 1);
3771 if (err)
3772 goto done;
3773 waddwstr(window, &wline[scrollx]);
3774 wlimit -= width;
3775 *wtotal += width;
3778 if (wlimit > 0) {
3779 int i = 0, w = 0;
3780 size_t wlen;
3782 free(wline);
3783 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3784 col_tab_align, 1);
3785 if (err)
3786 goto done;
3787 wlen = wcslen(wline);
3788 while (i < wlen) {
3789 width = wcwidth(wline[i]);
3790 if (width == -1) {
3791 /* should not happen, tabs are expanded */
3792 err = got_error(GOT_ERR_RANGE);
3793 goto done;
3795 if (width0 + w + width > skipcol)
3796 break;
3797 w += width;
3798 i++;
3800 /* draw (visible part of) matched token (if scrolled into it) */
3801 if (width1 - w > 0) {
3802 wattron(window, A_STANDOUT);
3803 waddwstr(window, &wline[i]);
3804 wattroff(window, A_STANDOUT);
3805 wlimit -= (width1 - w);
3806 *wtotal += (width1 - w);
3810 if (wlimit > 0) { /* draw rest of line */
3811 free(wline);
3812 if (skipcol > width0 + width1) {
3813 err = format_line(&wline, &width2, &scrollx, seg2,
3814 skipcol - (width0 + width1), wlimit,
3815 col_tab_align, 1);
3816 if (err)
3817 goto done;
3818 waddwstr(window, &wline[scrollx]);
3819 } else {
3820 err = format_line(&wline, &width2, NULL, seg2, 0,
3821 wlimit, col_tab_align, 1);
3822 if (err)
3823 goto done;
3824 waddwstr(window, wline);
3826 *wtotal += width2;
3828 done:
3829 free(wline);
3830 free(exstr);
3831 free(seg0);
3832 free(seg1);
3833 free(seg2);
3834 return err;
3837 static const struct got_error *
3838 draw_file(struct tog_view *view, const char *header)
3840 struct tog_diff_view_state *s = &view->state.diff;
3841 regmatch_t *regmatch = &view->regmatch;
3842 const struct got_error *err;
3843 int nprinted = 0;
3844 char *line;
3845 size_t linesize = 0;
3846 ssize_t linelen;
3847 struct tog_color *tc;
3848 wchar_t *wline;
3849 int width;
3850 int max_lines = view->nlines;
3851 int nlines = s->nlines;
3852 off_t line_offset;
3854 line_offset = s->line_offsets[s->first_displayed_line - 1];
3855 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3856 return got_error_from_errno("fseek");
3858 werase(view->window);
3860 if (header) {
3861 if (asprintf(&line, "[%d/%d] %s",
3862 s->first_displayed_line - 1 + s->selected_line, nlines,
3863 header) == -1)
3864 return got_error_from_errno("asprintf");
3865 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3866 0, 0);
3867 free(line);
3868 if (err)
3869 return err;
3871 if (view_needs_focus_indication(view))
3872 wstandout(view->window);
3873 waddwstr(view->window, wline);
3874 free(wline);
3875 wline = NULL;
3876 if (view_needs_focus_indication(view))
3877 wstandend(view->window);
3878 if (width <= view->ncols - 1)
3879 waddch(view->window, '\n');
3881 if (max_lines <= 1)
3882 return NULL;
3883 max_lines--;
3886 s->eof = 0;
3887 view->maxx = 0;
3888 line = NULL;
3889 while (max_lines > 0 && nprinted < max_lines) {
3890 linelen = getline(&line, &linesize, s->f);
3891 if (linelen == -1) {
3892 if (feof(s->f)) {
3893 s->eof = 1;
3894 break;
3896 free(line);
3897 return got_ferror(s->f, GOT_ERR_IO);
3900 /* Set view->maxx based on full line length. */
3901 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3902 view->x ? 1 : 0);
3903 if (err) {
3904 free(line);
3905 return err;
3907 view->maxx = MAX(view->maxx, width);
3908 free(wline);
3909 wline = NULL;
3911 tc = match_color(&s->colors, line);
3912 if (tc)
3913 wattr_on(view->window,
3914 COLOR_PAIR(tc->colorpair), NULL);
3915 if (s->first_displayed_line + nprinted == s->matched_line &&
3916 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3917 err = add_matched_line(&width, line, view->ncols, 0,
3918 view->window, view->x, regmatch);
3919 if (err) {
3920 free(line);
3921 return err;
3923 } else {
3924 int skip;
3925 err = format_line(&wline, &width, &skip, line,
3926 view->x, view->ncols, 0, view->x ? 1 : 0);
3927 if (err) {
3928 free(line);
3929 return err;
3931 waddwstr(view->window, &wline[skip]);
3932 free(wline);
3933 wline = NULL;
3935 if (tc)
3936 wattr_off(view->window,
3937 COLOR_PAIR(tc->colorpair), NULL);
3938 if (width <= view->ncols - 1)
3939 waddch(view->window, '\n');
3940 nprinted++;
3942 free(line);
3943 if (nprinted >= 1)
3944 s->last_displayed_line = s->first_displayed_line +
3945 (nprinted - 1);
3946 else
3947 s->last_displayed_line = s->first_displayed_line;
3949 view_border(view);
3951 if (s->eof) {
3952 while (nprinted < view->nlines) {
3953 waddch(view->window, '\n');
3954 nprinted++;
3957 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3958 view->ncols, 0, 0);
3959 if (err) {
3960 return err;
3963 wstandout(view->window);
3964 waddwstr(view->window, wline);
3965 free(wline);
3966 wline = NULL;
3967 wstandend(view->window);
3970 return NULL;
3973 static char *
3974 get_datestr(time_t *time, char *datebuf)
3976 struct tm mytm, *tm;
3977 char *p, *s;
3979 tm = gmtime_r(time, &mytm);
3980 if (tm == NULL)
3981 return NULL;
3982 s = asctime_r(tm, datebuf);
3983 if (s == NULL)
3984 return NULL;
3985 p = strchr(s, '\n');
3986 if (p)
3987 *p = '\0';
3988 return s;
3991 static const struct got_error *
3992 get_changed_paths(struct got_pathlist_head *paths,
3993 struct got_commit_object *commit, struct got_repository *repo)
3995 const struct got_error *err = NULL;
3996 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3997 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3998 struct got_object_qid *qid;
4000 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4001 if (qid != NULL) {
4002 struct got_commit_object *pcommit;
4003 err = got_object_open_as_commit(&pcommit, repo,
4004 &qid->id);
4005 if (err)
4006 return err;
4008 tree_id1 = got_object_id_dup(
4009 got_object_commit_get_tree_id(pcommit));
4010 if (tree_id1 == NULL) {
4011 got_object_commit_close(pcommit);
4012 return got_error_from_errno("got_object_id_dup");
4014 got_object_commit_close(pcommit);
4018 if (tree_id1) {
4019 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4020 if (err)
4021 goto done;
4024 tree_id2 = got_object_commit_get_tree_id(commit);
4025 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4026 if (err)
4027 goto done;
4029 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4030 got_diff_tree_collect_changed_paths, paths, 0);
4031 done:
4032 if (tree1)
4033 got_object_tree_close(tree1);
4034 if (tree2)
4035 got_object_tree_close(tree2);
4036 free(tree_id1);
4037 return err;
4040 static const struct got_error *
4041 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
4043 off_t *p;
4045 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
4046 if (p == NULL)
4047 return got_error_from_errno("reallocarray");
4048 *line_offsets = p;
4049 (*line_offsets)[*nlines] = off;
4050 (*nlines)++;
4051 return NULL;
4054 static const struct got_error *
4055 write_commit_info(off_t **line_offsets, size_t *nlines,
4056 struct got_object_id *commit_id, struct got_reflist_head *refs,
4057 struct got_repository *repo, FILE *outfile)
4059 const struct got_error *err = NULL;
4060 char datebuf[26], *datestr;
4061 struct got_commit_object *commit;
4062 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4063 time_t committer_time;
4064 const char *author, *committer;
4065 char *refs_str = NULL;
4066 struct got_pathlist_head changed_paths;
4067 struct got_pathlist_entry *pe;
4068 off_t outoff = 0;
4069 int n;
4071 TAILQ_INIT(&changed_paths);
4073 if (refs) {
4074 err = build_refs_str(&refs_str, refs, commit_id, repo);
4075 if (err)
4076 return err;
4079 err = got_object_open_as_commit(&commit, repo, commit_id);
4080 if (err)
4081 return err;
4083 err = got_object_id_str(&id_str, commit_id);
4084 if (err) {
4085 err = got_error_from_errno("got_object_id_str");
4086 goto done;
4089 err = add_line_offset(line_offsets, nlines, 0);
4090 if (err)
4091 goto done;
4093 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4094 refs_str ? refs_str : "", refs_str ? ")" : "");
4095 if (n < 0) {
4096 err = got_error_from_errno("fprintf");
4097 goto done;
4099 outoff += n;
4100 err = add_line_offset(line_offsets, nlines, outoff);
4101 if (err)
4102 goto done;
4104 n = fprintf(outfile, "from: %s\n",
4105 got_object_commit_get_author(commit));
4106 if (n < 0) {
4107 err = got_error_from_errno("fprintf");
4108 goto done;
4110 outoff += n;
4111 err = add_line_offset(line_offsets, nlines, outoff);
4112 if (err)
4113 goto done;
4115 committer_time = got_object_commit_get_committer_time(commit);
4116 datestr = get_datestr(&committer_time, datebuf);
4117 if (datestr) {
4118 n = fprintf(outfile, "date: %s UTC\n", datestr);
4119 if (n < 0) {
4120 err = got_error_from_errno("fprintf");
4121 goto done;
4123 outoff += n;
4124 err = add_line_offset(line_offsets, nlines, outoff);
4125 if (err)
4126 goto done;
4128 author = got_object_commit_get_author(commit);
4129 committer = got_object_commit_get_committer(commit);
4130 if (strcmp(author, committer) != 0) {
4131 n = fprintf(outfile, "via: %s\n", committer);
4132 if (n < 0) {
4133 err = got_error_from_errno("fprintf");
4134 goto done;
4136 outoff += n;
4137 err = add_line_offset(line_offsets, nlines, outoff);
4138 if (err)
4139 goto done;
4141 if (got_object_commit_get_nparents(commit) > 1) {
4142 const struct got_object_id_queue *parent_ids;
4143 struct got_object_qid *qid;
4144 int pn = 1;
4145 parent_ids = got_object_commit_get_parent_ids(commit);
4146 STAILQ_FOREACH(qid, parent_ids, entry) {
4147 err = got_object_id_str(&id_str, &qid->id);
4148 if (err)
4149 goto done;
4150 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4151 if (n < 0) {
4152 err = got_error_from_errno("fprintf");
4153 goto done;
4155 outoff += n;
4156 err = add_line_offset(line_offsets, nlines, outoff);
4157 if (err)
4158 goto done;
4159 free(id_str);
4160 id_str = NULL;
4164 err = got_object_commit_get_logmsg(&logmsg, commit);
4165 if (err)
4166 goto done;
4167 s = logmsg;
4168 while ((line = strsep(&s, "\n")) != NULL) {
4169 n = fprintf(outfile, "%s\n", line);
4170 if (n < 0) {
4171 err = got_error_from_errno("fprintf");
4172 goto done;
4174 outoff += n;
4175 err = add_line_offset(line_offsets, nlines, outoff);
4176 if (err)
4177 goto done;
4180 err = get_changed_paths(&changed_paths, commit, repo);
4181 if (err)
4182 goto done;
4183 TAILQ_FOREACH(pe, &changed_paths, entry) {
4184 struct got_diff_changed_path *cp = pe->data;
4185 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4186 if (n < 0) {
4187 err = got_error_from_errno("fprintf");
4188 goto done;
4190 outoff += n;
4191 err = add_line_offset(line_offsets, nlines, outoff);
4192 if (err)
4193 goto done;
4194 free((char *)pe->path);
4195 free(pe->data);
4198 fputc('\n', outfile);
4199 outoff++;
4200 err = add_line_offset(line_offsets, nlines, outoff);
4201 done:
4202 got_pathlist_free(&changed_paths);
4203 free(id_str);
4204 free(logmsg);
4205 free(refs_str);
4206 got_object_commit_close(commit);
4207 if (err) {
4208 free(*line_offsets);
4209 *line_offsets = NULL;
4210 *nlines = 0;
4212 return err;
4215 static const struct got_error *
4216 create_diff(struct tog_diff_view_state *s)
4218 const struct got_error *err = NULL;
4219 FILE *f = NULL;
4220 int obj_type;
4222 free(s->line_offsets);
4223 s->line_offsets = malloc(sizeof(off_t));
4224 if (s->line_offsets == NULL)
4225 return got_error_from_errno("malloc");
4226 s->nlines = 0;
4228 f = got_opentemp();
4229 if (f == NULL) {
4230 err = got_error_from_errno("got_opentemp");
4231 goto done;
4233 if (s->f && fclose(s->f) == EOF) {
4234 err = got_error_from_errno("fclose");
4235 goto done;
4237 s->f = f;
4239 if (s->id1)
4240 err = got_object_get_type(&obj_type, s->repo, s->id1);
4241 else
4242 err = got_object_get_type(&obj_type, s->repo, s->id2);
4243 if (err)
4244 goto done;
4246 switch (obj_type) {
4247 case GOT_OBJ_TYPE_BLOB:
4248 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
4249 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4250 s->label1, s->label2, tog_diff_algo, s->diff_context,
4251 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4252 break;
4253 case GOT_OBJ_TYPE_TREE:
4254 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
4255 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4256 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4257 s->force_text_diff, s->repo, s->f);
4258 break;
4259 case GOT_OBJ_TYPE_COMMIT: {
4260 const struct got_object_id_queue *parent_ids;
4261 struct got_object_qid *pid;
4262 struct got_commit_object *commit2;
4263 struct got_reflist_head *refs;
4265 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4266 if (err)
4267 goto done;
4268 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4269 /* Show commit info if we're diffing to a parent/root commit. */
4270 if (s->id1 == NULL) {
4271 err = write_commit_info(&s->line_offsets, &s->nlines,
4272 s->id2, refs, s->repo, s->f);
4273 if (err)
4274 goto done;
4275 } else {
4276 parent_ids = got_object_commit_get_parent_ids(commit2);
4277 STAILQ_FOREACH(pid, parent_ids, entry) {
4278 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4279 err = write_commit_info(
4280 &s->line_offsets, &s->nlines,
4281 s->id2, refs, s->repo, s->f);
4282 if (err)
4283 goto done;
4284 break;
4288 got_object_commit_close(commit2);
4290 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4291 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4292 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4293 s->force_text_diff, s->repo, s->f);
4294 break;
4296 default:
4297 err = got_error(GOT_ERR_OBJ_TYPE);
4298 break;
4300 if (err)
4301 goto done;
4302 done:
4303 if (s->f && fflush(s->f) != 0 && err == NULL)
4304 err = got_error_from_errno("fflush");
4305 return err;
4308 static void
4309 diff_view_indicate_progress(struct tog_view *view)
4311 mvwaddstr(view->window, 0, 0, "diffing...");
4312 update_panels();
4313 doupdate();
4316 static const struct got_error *
4317 search_start_diff_view(struct tog_view *view)
4319 struct tog_diff_view_state *s = &view->state.diff;
4321 s->matched_line = 0;
4322 return NULL;
4325 static const struct got_error *
4326 search_next_diff_view(struct tog_view *view)
4328 struct tog_diff_view_state *s = &view->state.diff;
4329 const struct got_error *err = NULL;
4330 int lineno;
4331 char *line = NULL;
4332 size_t linesize = 0;
4333 ssize_t linelen;
4335 if (!view->searching) {
4336 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4337 return NULL;
4340 if (s->matched_line) {
4341 if (view->searching == TOG_SEARCH_FORWARD)
4342 lineno = s->matched_line + 1;
4343 else
4344 lineno = s->matched_line - 1;
4345 } else
4346 lineno = s->first_displayed_line;
4348 while (1) {
4349 off_t offset;
4351 if (lineno <= 0 || lineno > s->nlines) {
4352 if (s->matched_line == 0) {
4353 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4354 break;
4357 if (view->searching == TOG_SEARCH_FORWARD)
4358 lineno = 1;
4359 else
4360 lineno = s->nlines;
4363 offset = s->line_offsets[lineno - 1];
4364 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4365 free(line);
4366 return got_error_from_errno("fseeko");
4368 linelen = getline(&line, &linesize, s->f);
4369 if (linelen != -1) {
4370 char *exstr;
4371 err = expand_tab(&exstr, line);
4372 if (err)
4373 break;
4374 if (match_line(exstr, &view->regex, 1,
4375 &view->regmatch)) {
4376 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4377 s->matched_line = lineno;
4378 free(exstr);
4379 break;
4381 free(exstr);
4383 if (view->searching == TOG_SEARCH_FORWARD)
4384 lineno++;
4385 else
4386 lineno--;
4388 free(line);
4390 if (s->matched_line) {
4391 s->first_displayed_line = s->matched_line;
4392 s->selected_line = 1;
4395 return err;
4398 static const struct got_error *
4399 close_diff_view(struct tog_view *view)
4401 const struct got_error *err = NULL;
4402 struct tog_diff_view_state *s = &view->state.diff;
4404 free(s->id1);
4405 s->id1 = NULL;
4406 free(s->id2);
4407 s->id2 = NULL;
4408 if (s->f && fclose(s->f) == EOF)
4409 err = got_error_from_errno("fclose");
4410 s->f = NULL;
4411 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4412 err = got_error_from_errno("fclose");
4413 s->f1 = NULL;
4414 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4415 err = got_error_from_errno("fclose");
4416 s->f2 = NULL;
4417 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4418 err = got_error_from_errno("close");
4419 s->fd1 = -1;
4420 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4421 err = got_error_from_errno("close");
4422 s->fd2 = -1;
4423 free_colors(&s->colors);
4424 free(s->line_offsets);
4425 s->line_offsets = NULL;
4426 s->nlines = 0;
4427 return err;
4430 static const struct got_error *
4431 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4432 struct got_object_id *id2, const char *label1, const char *label2,
4433 int diff_context, int ignore_whitespace, int force_text_diff,
4434 struct tog_view *parent_view, struct got_repository *repo)
4436 const struct got_error *err;
4437 struct tog_diff_view_state *s = &view->state.diff;
4439 memset(s, 0, sizeof(*s));
4440 s->fd1 = -1;
4441 s->fd2 = -1;
4443 if (id1 != NULL && id2 != NULL) {
4444 int type1, type2;
4445 err = got_object_get_type(&type1, repo, id1);
4446 if (err)
4447 return err;
4448 err = got_object_get_type(&type2, repo, id2);
4449 if (err)
4450 return err;
4452 if (type1 != type2)
4453 return got_error(GOT_ERR_OBJ_TYPE);
4455 s->first_displayed_line = 1;
4456 s->last_displayed_line = view->nlines;
4457 s->selected_line = 1;
4458 s->repo = repo;
4459 s->id1 = id1;
4460 s->id2 = id2;
4461 s->label1 = label1;
4462 s->label2 = label2;
4464 if (id1) {
4465 s->id1 = got_object_id_dup(id1);
4466 if (s->id1 == NULL)
4467 return got_error_from_errno("got_object_id_dup");
4468 } else
4469 s->id1 = NULL;
4471 s->id2 = got_object_id_dup(id2);
4472 if (s->id2 == NULL) {
4473 err = got_error_from_errno("got_object_id_dup");
4474 goto done;
4477 s->f1 = got_opentemp();
4478 if (s->f1 == NULL) {
4479 err = got_error_from_errno("got_opentemp");
4480 goto done;
4483 s->f2 = got_opentemp();
4484 if (s->f2 == NULL) {
4485 err = got_error_from_errno("got_opentemp");
4486 goto done;
4489 s->fd1 = got_opentempfd();
4490 if (s->fd1 == -1) {
4491 err = got_error_from_errno("got_opentempfd");
4492 goto done;
4495 s->fd2 = got_opentempfd();
4496 if (s->fd2 == -1) {
4497 err = got_error_from_errno("got_opentempfd");
4498 goto done;
4501 s->first_displayed_line = 1;
4502 s->last_displayed_line = view->nlines;
4503 s->diff_context = diff_context;
4504 s->ignore_whitespace = ignore_whitespace;
4505 s->force_text_diff = force_text_diff;
4506 s->parent_view = parent_view;
4507 s->repo = repo;
4509 STAILQ_INIT(&s->colors);
4510 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4511 err = add_color(&s->colors,
4512 "^-", TOG_COLOR_DIFF_MINUS,
4513 get_color_value("TOG_COLOR_DIFF_MINUS"));
4514 if (err)
4515 goto done;
4516 err = add_color(&s->colors, "^\\+",
4517 TOG_COLOR_DIFF_PLUS,
4518 get_color_value("TOG_COLOR_DIFF_PLUS"));
4519 if (err)
4520 goto done;
4521 err = add_color(&s->colors,
4522 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4523 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4524 if (err)
4525 goto done;
4527 err = add_color(&s->colors,
4528 "^(commit [0-9a-f]|parent [0-9]|"
4529 "(blob|file|tree|commit) [-+] |"
4530 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4531 get_color_value("TOG_COLOR_DIFF_META"));
4532 if (err)
4533 goto done;
4535 err = add_color(&s->colors,
4536 "^(from|via): ", TOG_COLOR_AUTHOR,
4537 get_color_value("TOG_COLOR_AUTHOR"));
4538 if (err)
4539 goto done;
4541 err = add_color(&s->colors,
4542 "^date: ", TOG_COLOR_DATE,
4543 get_color_value("TOG_COLOR_DATE"));
4544 if (err)
4545 goto done;
4548 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4549 view_is_splitscreen(view))
4550 show_log_view(parent_view); /* draw border */
4551 diff_view_indicate_progress(view);
4553 err = create_diff(s);
4555 view->show = show_diff_view;
4556 view->input = input_diff_view;
4557 view->reset = reset_diff_view;
4558 view->close = close_diff_view;
4559 view->search_start = search_start_diff_view;
4560 view->search_next = search_next_diff_view;
4561 done:
4562 if (err)
4563 close_diff_view(view);
4564 return err;
4567 static const struct got_error *
4568 show_diff_view(struct tog_view *view)
4570 const struct got_error *err;
4571 struct tog_diff_view_state *s = &view->state.diff;
4572 char *id_str1 = NULL, *id_str2, *header;
4573 const char *label1, *label2;
4575 if (s->id1) {
4576 err = got_object_id_str(&id_str1, s->id1);
4577 if (err)
4578 return err;
4579 label1 = s->label1 ? : id_str1;
4580 } else
4581 label1 = "/dev/null";
4583 err = got_object_id_str(&id_str2, s->id2);
4584 if (err)
4585 return err;
4586 label2 = s->label2 ? : id_str2;
4588 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4589 err = got_error_from_errno("asprintf");
4590 free(id_str1);
4591 free(id_str2);
4592 return err;
4594 free(id_str1);
4595 free(id_str2);
4597 err = draw_file(view, header);
4598 free(header);
4599 return err;
4602 static const struct got_error *
4603 set_selected_commit(struct tog_diff_view_state *s,
4604 struct commit_queue_entry *entry)
4606 const struct got_error *err;
4607 const struct got_object_id_queue *parent_ids;
4608 struct got_commit_object *selected_commit;
4609 struct got_object_qid *pid;
4611 free(s->id2);
4612 s->id2 = got_object_id_dup(entry->id);
4613 if (s->id2 == NULL)
4614 return got_error_from_errno("got_object_id_dup");
4616 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4617 if (err)
4618 return err;
4619 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4620 free(s->id1);
4621 pid = STAILQ_FIRST(parent_ids);
4622 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4623 got_object_commit_close(selected_commit);
4624 return NULL;
4627 static const struct got_error *
4628 reset_diff_view(struct tog_view *view)
4630 struct tog_diff_view_state *s = &view->state.diff;
4632 view->count = 0;
4633 wclear(view->window);
4634 s->first_displayed_line = 1;
4635 s->last_displayed_line = view->nlines;
4636 s->matched_line = 0;
4637 diff_view_indicate_progress(view);
4638 return create_diff(s);
4641 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4642 int, int, int);
4643 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4644 int, int);
4646 static const struct got_error *
4647 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4649 const struct got_error *err = NULL;
4650 struct tog_diff_view_state *s = &view->state.diff;
4651 struct tog_log_view_state *ls;
4652 struct commit_queue_entry *old_selected_entry;
4653 char *line = NULL;
4654 size_t linesize = 0;
4655 ssize_t linelen;
4656 int i, nscroll = view->nlines - 1, up = 0;
4658 switch (ch) {
4659 case '0':
4660 view->x = 0;
4661 break;
4662 case '$':
4663 view->x = MAX(view->maxx - view->ncols / 3, 0);
4664 view->count = 0;
4665 break;
4666 case KEY_RIGHT:
4667 case 'l':
4668 if (view->x + view->ncols / 3 < view->maxx)
4669 view->x += 2; /* move two columns right */
4670 else
4671 view->count = 0;
4672 break;
4673 case KEY_LEFT:
4674 case 'h':
4675 view->x -= MIN(view->x, 2); /* move two columns back */
4676 if (view->x <= 0)
4677 view->count = 0;
4678 break;
4679 case 'a':
4680 case 'w':
4681 if (ch == 'a')
4682 s->force_text_diff = !s->force_text_diff;
4683 if (ch == 'w')
4684 s->ignore_whitespace = !s->ignore_whitespace;
4685 err = reset_diff_view(view);
4686 break;
4687 case 'g':
4688 case KEY_HOME:
4689 s->first_displayed_line = 1;
4690 view->count = 0;
4691 break;
4692 case 'G':
4693 case KEY_END:
4694 view->count = 0;
4695 if (s->eof)
4696 break;
4698 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4699 s->eof = 1;
4700 break;
4701 case 'k':
4702 case KEY_UP:
4703 case CTRL('p'):
4704 if (s->first_displayed_line > 1)
4705 s->first_displayed_line--;
4706 else
4707 view->count = 0;
4708 break;
4709 case CTRL('u'):
4710 case 'u':
4711 nscroll /= 2;
4712 /* FALL THROUGH */
4713 case KEY_PPAGE:
4714 case CTRL('b'):
4715 case 'b':
4716 if (s->first_displayed_line == 1) {
4717 view->count = 0;
4718 break;
4720 i = 0;
4721 while (i++ < nscroll && s->first_displayed_line > 1)
4722 s->first_displayed_line--;
4723 break;
4724 case 'j':
4725 case KEY_DOWN:
4726 case CTRL('n'):
4727 if (!s->eof)
4728 s->first_displayed_line++;
4729 else
4730 view->count = 0;
4731 break;
4732 case CTRL('d'):
4733 case 'd':
4734 nscroll /= 2;
4735 /* FALL THROUGH */
4736 case KEY_NPAGE:
4737 case CTRL('f'):
4738 case 'f':
4739 case ' ':
4740 if (s->eof) {
4741 view->count = 0;
4742 break;
4744 i = 0;
4745 while (!s->eof && i++ < nscroll) {
4746 linelen = getline(&line, &linesize, s->f);
4747 s->first_displayed_line++;
4748 if (linelen == -1) {
4749 if (feof(s->f)) {
4750 s->eof = 1;
4751 } else
4752 err = got_ferror(s->f, GOT_ERR_IO);
4753 break;
4756 free(line);
4757 break;
4758 case '[':
4759 if (s->diff_context > 0) {
4760 s->diff_context--;
4761 s->matched_line = 0;
4762 diff_view_indicate_progress(view);
4763 err = create_diff(s);
4764 if (s->first_displayed_line + view->nlines - 1 >
4765 s->nlines) {
4766 s->first_displayed_line = 1;
4767 s->last_displayed_line = view->nlines;
4769 } else
4770 view->count = 0;
4771 break;
4772 case ']':
4773 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4774 s->diff_context++;
4775 s->matched_line = 0;
4776 diff_view_indicate_progress(view);
4777 err = create_diff(s);
4778 } else
4779 view->count = 0;
4780 break;
4781 case '<':
4782 case ',':
4783 up = 1;
4784 /* FALL THROUGH */
4785 case '>':
4786 case '.':
4787 if (s->parent_view == NULL) {
4788 view->count = 0;
4789 break;
4791 s->parent_view->count = view->count;
4793 if (s->parent_view->type == TOG_VIEW_LOG) {
4794 ls = &s->parent_view->state.log;
4795 old_selected_entry = ls->selected_entry;
4797 err = input_log_view(NULL, s->parent_view,
4798 up ? KEY_UP : KEY_DOWN);
4799 if (err)
4800 break;
4801 view->count = s->parent_view->count;
4803 if (old_selected_entry == ls->selected_entry)
4804 break;
4806 err = set_selected_commit(s, ls->selected_entry);
4807 if (err)
4808 break;
4809 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4810 struct tog_blame_view_state *bs;
4811 struct got_object_id *id, *prev_id;
4813 bs = &s->parent_view->state.blame;
4814 prev_id = get_annotation_for_line(bs->blame.lines,
4815 bs->blame.nlines, bs->last_diffed_line);
4817 err = input_blame_view(&view, s->parent_view,
4818 up ? KEY_UP : KEY_DOWN);
4819 if (err)
4820 break;
4821 view->count = s->parent_view->count;
4823 if (prev_id == NULL)
4824 break;
4825 id = get_selected_commit_id(bs->blame.lines,
4826 bs->blame.nlines, bs->first_displayed_line,
4827 bs->selected_line);
4828 if (id == NULL)
4829 break;
4831 if (!got_object_id_cmp(prev_id, id))
4832 break;
4834 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
4835 if (err)
4836 break;
4838 s->first_displayed_line = 1;
4839 s->last_displayed_line = view->nlines;
4840 s->matched_line = 0;
4841 view->x = 0;
4843 diff_view_indicate_progress(view);
4844 err = create_diff(s);
4845 break;
4846 default:
4847 view->count = 0;
4848 break;
4851 return err;
4854 static const struct got_error *
4855 cmd_diff(int argc, char *argv[])
4857 const struct got_error *error = NULL;
4858 struct got_repository *repo = NULL;
4859 struct got_worktree *worktree = NULL;
4860 struct got_object_id *id1 = NULL, *id2 = NULL;
4861 char *repo_path = NULL, *cwd = NULL;
4862 char *id_str1 = NULL, *id_str2 = NULL;
4863 char *label1 = NULL, *label2 = NULL;
4864 int diff_context = 3, ignore_whitespace = 0;
4865 int ch, force_text_diff = 0;
4866 const char *errstr;
4867 struct tog_view *view;
4868 int *pack_fds = NULL;
4870 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4871 switch (ch) {
4872 case 'a':
4873 force_text_diff = 1;
4874 break;
4875 case 'C':
4876 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4877 &errstr);
4878 if (errstr != NULL)
4879 errx(1, "number of context lines is %s: %s",
4880 errstr, errstr);
4881 break;
4882 case 'r':
4883 repo_path = realpath(optarg, NULL);
4884 if (repo_path == NULL)
4885 return got_error_from_errno2("realpath",
4886 optarg);
4887 got_path_strip_trailing_slashes(repo_path);
4888 break;
4889 case 'w':
4890 ignore_whitespace = 1;
4891 break;
4892 default:
4893 usage_diff();
4894 /* NOTREACHED */
4898 argc -= optind;
4899 argv += optind;
4901 if (argc == 0) {
4902 usage_diff(); /* TODO show local worktree changes */
4903 } else if (argc == 2) {
4904 id_str1 = argv[0];
4905 id_str2 = argv[1];
4906 } else
4907 usage_diff();
4909 error = got_repo_pack_fds_open(&pack_fds);
4910 if (error)
4911 goto done;
4913 if (repo_path == NULL) {
4914 cwd = getcwd(NULL, 0);
4915 if (cwd == NULL)
4916 return got_error_from_errno("getcwd");
4917 error = got_worktree_open(&worktree, cwd);
4918 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4919 goto done;
4920 if (worktree)
4921 repo_path =
4922 strdup(got_worktree_get_repo_path(worktree));
4923 else
4924 repo_path = strdup(cwd);
4925 if (repo_path == NULL) {
4926 error = got_error_from_errno("strdup");
4927 goto done;
4931 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4932 if (error)
4933 goto done;
4935 init_curses();
4937 error = apply_unveil(got_repo_get_path(repo), NULL);
4938 if (error)
4939 goto done;
4941 error = tog_load_refs(repo, 0);
4942 if (error)
4943 goto done;
4945 error = got_repo_match_object_id(&id1, &label1, id_str1,
4946 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4947 if (error)
4948 goto done;
4950 error = got_repo_match_object_id(&id2, &label2, id_str2,
4951 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4952 if (error)
4953 goto done;
4955 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4956 if (view == NULL) {
4957 error = got_error_from_errno("view_open");
4958 goto done;
4960 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4961 ignore_whitespace, force_text_diff, NULL, repo);
4962 if (error)
4963 goto done;
4964 error = view_loop(view);
4965 done:
4966 free(label1);
4967 free(label2);
4968 free(repo_path);
4969 free(cwd);
4970 if (repo) {
4971 const struct got_error *close_err = got_repo_close(repo);
4972 if (error == NULL)
4973 error = close_err;
4975 if (worktree)
4976 got_worktree_close(worktree);
4977 if (pack_fds) {
4978 const struct got_error *pack_err =
4979 got_repo_pack_fds_close(pack_fds);
4980 if (error == NULL)
4981 error = pack_err;
4983 tog_free_refs();
4984 return error;
4987 __dead static void
4988 usage_blame(void)
4990 endwin();
4991 fprintf(stderr,
4992 "usage: %s blame [-c commit] [-r repository-path] path\n",
4993 getprogname());
4994 exit(1);
4997 struct tog_blame_line {
4998 int annotated;
4999 struct got_object_id *id;
5002 static const struct got_error *
5003 draw_blame(struct tog_view *view)
5005 struct tog_blame_view_state *s = &view->state.blame;
5006 struct tog_blame *blame = &s->blame;
5007 regmatch_t *regmatch = &view->regmatch;
5008 const struct got_error *err;
5009 int lineno = 0, nprinted = 0;
5010 char *line = NULL;
5011 size_t linesize = 0;
5012 ssize_t linelen;
5013 wchar_t *wline;
5014 int width;
5015 struct tog_blame_line *blame_line;
5016 struct got_object_id *prev_id = NULL;
5017 char *id_str;
5018 struct tog_color *tc;
5020 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5021 if (err)
5022 return err;
5024 rewind(blame->f);
5025 werase(view->window);
5027 if (asprintf(&line, "commit %s", id_str) == -1) {
5028 err = got_error_from_errno("asprintf");
5029 free(id_str);
5030 return err;
5033 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5034 free(line);
5035 line = NULL;
5036 if (err)
5037 return err;
5038 if (view_needs_focus_indication(view))
5039 wstandout(view->window);
5040 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5041 if (tc)
5042 wattr_on(view->window,
5043 COLOR_PAIR(tc->colorpair), NULL);
5044 waddwstr(view->window, wline);
5045 if (tc)
5046 wattr_off(view->window,
5047 COLOR_PAIR(tc->colorpair), NULL);
5048 if (view_needs_focus_indication(view))
5049 wstandend(view->window);
5050 free(wline);
5051 wline = NULL;
5052 if (width < view->ncols - 1)
5053 waddch(view->window, '\n');
5055 if (asprintf(&line, "[%d/%d] %s%s",
5056 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5057 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5058 free(id_str);
5059 return got_error_from_errno("asprintf");
5061 free(id_str);
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 waddwstr(view->window, wline);
5068 free(wline);
5069 wline = NULL;
5070 if (width < view->ncols - 1)
5071 waddch(view->window, '\n');
5073 s->eof = 0;
5074 view->maxx = 0;
5075 while (nprinted < view->nlines - 2) {
5076 linelen = getline(&line, &linesize, blame->f);
5077 if (linelen == -1) {
5078 if (feof(blame->f)) {
5079 s->eof = 1;
5080 break;
5082 free(line);
5083 return got_ferror(blame->f, GOT_ERR_IO);
5085 if (++lineno < s->first_displayed_line)
5086 continue;
5088 /* Set view->maxx based on full line length. */
5089 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5090 if (err) {
5091 free(line);
5092 return err;
5094 free(wline);
5095 wline = NULL;
5096 view->maxx = MAX(view->maxx, width);
5098 if (nprinted == s->selected_line - 1)
5099 wstandout(view->window);
5101 if (blame->nlines > 0) {
5102 blame_line = &blame->lines[lineno - 1];
5103 if (blame_line->annotated && prev_id &&
5104 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5105 !(nprinted == s->selected_line - 1)) {
5106 waddstr(view->window, " ");
5107 } else if (blame_line->annotated) {
5108 char *id_str;
5109 err = got_object_id_str(&id_str,
5110 blame_line->id);
5111 if (err) {
5112 free(line);
5113 return err;
5115 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5116 if (tc)
5117 wattr_on(view->window,
5118 COLOR_PAIR(tc->colorpair), NULL);
5119 wprintw(view->window, "%.8s", id_str);
5120 if (tc)
5121 wattr_off(view->window,
5122 COLOR_PAIR(tc->colorpair), NULL);
5123 free(id_str);
5124 prev_id = blame_line->id;
5125 } else {
5126 waddstr(view->window, "........");
5127 prev_id = NULL;
5129 } else {
5130 waddstr(view->window, "........");
5131 prev_id = NULL;
5134 if (nprinted == s->selected_line - 1)
5135 wstandend(view->window);
5136 waddstr(view->window, " ");
5138 if (view->ncols <= 9) {
5139 width = 9;
5140 } else if (s->first_displayed_line + nprinted ==
5141 s->matched_line &&
5142 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5143 err = add_matched_line(&width, line, view->ncols - 9, 9,
5144 view->window, view->x, regmatch);
5145 if (err) {
5146 free(line);
5147 return err;
5149 width += 9;
5150 } else {
5151 int skip;
5152 err = format_line(&wline, &width, &skip, line,
5153 view->x, view->ncols - 9, 9, 1);
5154 if (err) {
5155 free(line);
5156 return err;
5158 waddwstr(view->window, &wline[skip]);
5159 width += 9;
5160 free(wline);
5161 wline = NULL;
5164 if (width <= view->ncols - 1)
5165 waddch(view->window, '\n');
5166 if (++nprinted == 1)
5167 s->first_displayed_line = lineno;
5169 free(line);
5170 s->last_displayed_line = lineno;
5172 view_border(view);
5174 return NULL;
5177 static const struct got_error *
5178 blame_cb(void *arg, int nlines, int lineno,
5179 struct got_commit_object *commit, struct got_object_id *id)
5181 const struct got_error *err = NULL;
5182 struct tog_blame_cb_args *a = arg;
5183 struct tog_blame_line *line;
5184 int errcode;
5186 if (nlines != a->nlines ||
5187 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5188 return got_error(GOT_ERR_RANGE);
5190 errcode = pthread_mutex_lock(&tog_mutex);
5191 if (errcode)
5192 return got_error_set_errno(errcode, "pthread_mutex_lock");
5194 if (*a->quit) { /* user has quit the blame view */
5195 err = got_error(GOT_ERR_ITER_COMPLETED);
5196 goto done;
5199 if (lineno == -1)
5200 goto done; /* no change in this commit */
5202 line = &a->lines[lineno - 1];
5203 if (line->annotated)
5204 goto done;
5206 line->id = got_object_id_dup(id);
5207 if (line->id == NULL) {
5208 err = got_error_from_errno("got_object_id_dup");
5209 goto done;
5211 line->annotated = 1;
5212 done:
5213 errcode = pthread_mutex_unlock(&tog_mutex);
5214 if (errcode)
5215 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5216 return err;
5219 static void *
5220 blame_thread(void *arg)
5222 const struct got_error *err, *close_err;
5223 struct tog_blame_thread_args *ta = arg;
5224 struct tog_blame_cb_args *a = ta->cb_args;
5225 int errcode, fd1 = -1, fd2 = -1;
5226 FILE *f1 = NULL, *f2 = NULL;
5228 fd1 = got_opentempfd();
5229 if (fd1 == -1)
5230 return (void *)got_error_from_errno("got_opentempfd");
5232 fd2 = got_opentempfd();
5233 if (fd2 == -1) {
5234 err = got_error_from_errno("got_opentempfd");
5235 goto done;
5238 f1 = got_opentemp();
5239 if (f1 == NULL) {
5240 err = (void *)got_error_from_errno("got_opentemp");
5241 goto done;
5243 f2 = got_opentemp();
5244 if (f2 == NULL) {
5245 err = (void *)got_error_from_errno("got_opentemp");
5246 goto done;
5249 err = block_signals_used_by_main_thread();
5250 if (err)
5251 goto done;
5253 err = got_blame(ta->path, a->commit_id, ta->repo,
5254 tog_diff_algo, blame_cb, ta->cb_args,
5255 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5256 if (err && err->code == GOT_ERR_CANCELLED)
5257 err = NULL;
5259 errcode = pthread_mutex_lock(&tog_mutex);
5260 if (errcode) {
5261 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5262 goto done;
5265 close_err = got_repo_close(ta->repo);
5266 if (err == NULL)
5267 err = close_err;
5268 ta->repo = NULL;
5269 *ta->complete = 1;
5271 errcode = pthread_mutex_unlock(&tog_mutex);
5272 if (errcode && err == NULL)
5273 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5275 done:
5276 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5277 err = got_error_from_errno("close");
5278 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5279 err = got_error_from_errno("close");
5280 if (f1 && fclose(f1) == EOF && err == NULL)
5281 err = got_error_from_errno("fclose");
5282 if (f2 && fclose(f2) == EOF && err == NULL)
5283 err = got_error_from_errno("fclose");
5285 return (void *)err;
5288 static struct got_object_id *
5289 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5290 int first_displayed_line, int selected_line)
5292 struct tog_blame_line *line;
5294 if (nlines <= 0)
5295 return NULL;
5297 line = &lines[first_displayed_line - 1 + selected_line - 1];
5298 if (!line->annotated)
5299 return NULL;
5301 return line->id;
5304 static struct got_object_id *
5305 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5306 int lineno)
5308 struct tog_blame_line *line;
5310 if (nlines <= 0 || lineno >= nlines)
5311 return NULL;
5313 line = &lines[lineno - 1];
5314 if (!line->annotated)
5315 return NULL;
5317 return line->id;
5320 static const struct got_error *
5321 stop_blame(struct tog_blame *blame)
5323 const struct got_error *err = NULL;
5324 int i;
5326 if (blame->thread) {
5327 int errcode;
5328 errcode = pthread_mutex_unlock(&tog_mutex);
5329 if (errcode)
5330 return got_error_set_errno(errcode,
5331 "pthread_mutex_unlock");
5332 errcode = pthread_join(blame->thread, (void **)&err);
5333 if (errcode)
5334 return got_error_set_errno(errcode, "pthread_join");
5335 errcode = pthread_mutex_lock(&tog_mutex);
5336 if (errcode)
5337 return got_error_set_errno(errcode,
5338 "pthread_mutex_lock");
5339 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5340 err = NULL;
5341 blame->thread = 0; //NULL;
5343 if (blame->thread_args.repo) {
5344 const struct got_error *close_err;
5345 close_err = got_repo_close(blame->thread_args.repo);
5346 if (err == NULL)
5347 err = close_err;
5348 blame->thread_args.repo = NULL;
5350 if (blame->f) {
5351 if (fclose(blame->f) == EOF && err == NULL)
5352 err = got_error_from_errno("fclose");
5353 blame->f = NULL;
5355 if (blame->lines) {
5356 for (i = 0; i < blame->nlines; i++)
5357 free(blame->lines[i].id);
5358 free(blame->lines);
5359 blame->lines = NULL;
5361 free(blame->cb_args.commit_id);
5362 blame->cb_args.commit_id = NULL;
5363 if (blame->pack_fds) {
5364 const struct got_error *pack_err =
5365 got_repo_pack_fds_close(blame->pack_fds);
5366 if (err == NULL)
5367 err = pack_err;
5368 blame->pack_fds = NULL;
5370 return err;
5373 static const struct got_error *
5374 cancel_blame_view(void *arg)
5376 const struct got_error *err = NULL;
5377 int *done = arg;
5378 int errcode;
5380 errcode = pthread_mutex_lock(&tog_mutex);
5381 if (errcode)
5382 return got_error_set_errno(errcode,
5383 "pthread_mutex_unlock");
5385 if (*done)
5386 err = got_error(GOT_ERR_CANCELLED);
5388 errcode = pthread_mutex_unlock(&tog_mutex);
5389 if (errcode)
5390 return got_error_set_errno(errcode,
5391 "pthread_mutex_lock");
5393 return err;
5396 static const struct got_error *
5397 run_blame(struct tog_view *view)
5399 struct tog_blame_view_state *s = &view->state.blame;
5400 struct tog_blame *blame = &s->blame;
5401 const struct got_error *err = NULL;
5402 struct got_commit_object *commit = NULL;
5403 struct got_blob_object *blob = NULL;
5404 struct got_repository *thread_repo = NULL;
5405 struct got_object_id *obj_id = NULL;
5406 int obj_type, fd = -1;
5407 int *pack_fds = NULL;
5409 err = got_object_open_as_commit(&commit, s->repo,
5410 &s->blamed_commit->id);
5411 if (err)
5412 return err;
5414 fd = got_opentempfd();
5415 if (fd == -1) {
5416 err = got_error_from_errno("got_opentempfd");
5417 goto done;
5420 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5421 if (err)
5422 goto done;
5424 err = got_object_get_type(&obj_type, s->repo, obj_id);
5425 if (err)
5426 goto done;
5428 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5429 err = got_error(GOT_ERR_OBJ_TYPE);
5430 goto done;
5433 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5434 if (err)
5435 goto done;
5436 blame->f = got_opentemp();
5437 if (blame->f == NULL) {
5438 err = got_error_from_errno("got_opentemp");
5439 goto done;
5441 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5442 &blame->line_offsets, blame->f, blob);
5443 if (err)
5444 goto done;
5445 if (blame->nlines == 0) {
5446 s->blame_complete = 1;
5447 goto done;
5450 /* Don't include \n at EOF in the blame line count. */
5451 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5452 blame->nlines--;
5454 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5455 if (blame->lines == NULL) {
5456 err = got_error_from_errno("calloc");
5457 goto done;
5460 err = got_repo_pack_fds_open(&pack_fds);
5461 if (err)
5462 goto done;
5463 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5464 pack_fds);
5465 if (err)
5466 goto done;
5468 blame->pack_fds = pack_fds;
5469 blame->cb_args.view = view;
5470 blame->cb_args.lines = blame->lines;
5471 blame->cb_args.nlines = blame->nlines;
5472 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5473 if (blame->cb_args.commit_id == NULL) {
5474 err = got_error_from_errno("got_object_id_dup");
5475 goto done;
5477 blame->cb_args.quit = &s->done;
5479 blame->thread_args.path = s->path;
5480 blame->thread_args.repo = thread_repo;
5481 blame->thread_args.cb_args = &blame->cb_args;
5482 blame->thread_args.complete = &s->blame_complete;
5483 blame->thread_args.cancel_cb = cancel_blame_view;
5484 blame->thread_args.cancel_arg = &s->done;
5485 s->blame_complete = 0;
5487 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5488 s->first_displayed_line = 1;
5489 s->last_displayed_line = view->nlines;
5490 s->selected_line = 1;
5492 s->matched_line = 0;
5494 done:
5495 if (commit)
5496 got_object_commit_close(commit);
5497 if (fd != -1 && close(fd) == -1 && err == NULL)
5498 err = got_error_from_errno("close");
5499 if (blob)
5500 got_object_blob_close(blob);
5501 free(obj_id);
5502 if (err)
5503 stop_blame(blame);
5504 return err;
5507 static const struct got_error *
5508 open_blame_view(struct tog_view *view, char *path,
5509 struct got_object_id *commit_id, struct got_repository *repo)
5511 const struct got_error *err = NULL;
5512 struct tog_blame_view_state *s = &view->state.blame;
5514 STAILQ_INIT(&s->blamed_commits);
5516 s->path = strdup(path);
5517 if (s->path == NULL)
5518 return got_error_from_errno("strdup");
5520 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5521 if (err) {
5522 free(s->path);
5523 return err;
5526 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5527 s->first_displayed_line = 1;
5528 s->last_displayed_line = view->nlines;
5529 s->selected_line = 1;
5530 s->blame_complete = 0;
5531 s->repo = repo;
5532 s->commit_id = commit_id;
5533 memset(&s->blame, 0, sizeof(s->blame));
5535 STAILQ_INIT(&s->colors);
5536 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5537 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5538 get_color_value("TOG_COLOR_COMMIT"));
5539 if (err)
5540 return err;
5543 view->show = show_blame_view;
5544 view->input = input_blame_view;
5545 view->reset = reset_blame_view;
5546 view->close = close_blame_view;
5547 view->search_start = search_start_blame_view;
5548 view->search_next = search_next_blame_view;
5550 return run_blame(view);
5553 static const struct got_error *
5554 close_blame_view(struct tog_view *view)
5556 const struct got_error *err = NULL;
5557 struct tog_blame_view_state *s = &view->state.blame;
5559 if (s->blame.thread)
5560 err = stop_blame(&s->blame);
5562 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5563 struct got_object_qid *blamed_commit;
5564 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5565 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5566 got_object_qid_free(blamed_commit);
5569 free(s->path);
5570 free_colors(&s->colors);
5571 return err;
5574 static const struct got_error *
5575 search_start_blame_view(struct tog_view *view)
5577 struct tog_blame_view_state *s = &view->state.blame;
5579 s->matched_line = 0;
5580 return NULL;
5583 static const struct got_error *
5584 search_next_blame_view(struct tog_view *view)
5586 struct tog_blame_view_state *s = &view->state.blame;
5587 const struct got_error *err = NULL;
5588 int lineno;
5589 char *line = NULL;
5590 size_t linesize = 0;
5591 ssize_t linelen;
5593 if (!view->searching) {
5594 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5595 return NULL;
5598 if (s->matched_line) {
5599 if (view->searching == TOG_SEARCH_FORWARD)
5600 lineno = s->matched_line + 1;
5601 else
5602 lineno = s->matched_line - 1;
5603 } else
5604 lineno = s->first_displayed_line - 1 + s->selected_line;
5606 while (1) {
5607 off_t offset;
5609 if (lineno <= 0 || lineno > s->blame.nlines) {
5610 if (s->matched_line == 0) {
5611 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5612 break;
5615 if (view->searching == TOG_SEARCH_FORWARD)
5616 lineno = 1;
5617 else
5618 lineno = s->blame.nlines;
5621 offset = s->blame.line_offsets[lineno - 1];
5622 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5623 free(line);
5624 return got_error_from_errno("fseeko");
5626 linelen = getline(&line, &linesize, s->blame.f);
5627 if (linelen != -1) {
5628 char *exstr;
5629 err = expand_tab(&exstr, line);
5630 if (err)
5631 break;
5632 if (match_line(exstr, &view->regex, 1,
5633 &view->regmatch)) {
5634 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5635 s->matched_line = lineno;
5636 free(exstr);
5637 break;
5639 free(exstr);
5641 if (view->searching == TOG_SEARCH_FORWARD)
5642 lineno++;
5643 else
5644 lineno--;
5646 free(line);
5648 if (s->matched_line) {
5649 s->first_displayed_line = s->matched_line;
5650 s->selected_line = 1;
5653 return err;
5656 static const struct got_error *
5657 show_blame_view(struct tog_view *view)
5659 const struct got_error *err = NULL;
5660 struct tog_blame_view_state *s = &view->state.blame;
5661 int errcode;
5663 if (s->blame.thread == 0 && !s->blame_complete) {
5664 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5665 &s->blame.thread_args);
5666 if (errcode)
5667 return got_error_set_errno(errcode, "pthread_create");
5669 halfdelay(1); /* fast refresh while annotating */
5672 if (s->blame_complete)
5673 halfdelay(10); /* disable fast refresh */
5675 err = draw_blame(view);
5677 view_border(view);
5678 return err;
5681 static const struct got_error *
5682 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5684 const struct got_error *err = NULL, *thread_err = NULL;
5685 struct tog_view *diff_view;
5686 struct tog_blame_view_state *s = &view->state.blame;
5687 int eos, nscroll, begin_y = 0, begin_x = 0;
5689 eos = nscroll = view->nlines - 2;
5690 if (view_is_hsplit_top(view))
5691 --eos; /* border */
5693 switch (ch) {
5694 case '0':
5695 view->x = 0;
5696 break;
5697 case '$':
5698 view->x = MAX(view->maxx - view->ncols / 3, 0);
5699 view->count = 0;
5700 break;
5701 case KEY_RIGHT:
5702 case 'l':
5703 if (view->x + view->ncols / 3 < view->maxx)
5704 view->x += 2; /* move two columns right */
5705 else
5706 view->count = 0;
5707 break;
5708 case KEY_LEFT:
5709 case 'h':
5710 view->x -= MIN(view->x, 2); /* move two columns back */
5711 if (view->x <= 0)
5712 view->count = 0;
5713 break;
5714 case 'q':
5715 s->done = 1;
5716 break;
5717 case 'g':
5718 case KEY_HOME:
5719 s->selected_line = 1;
5720 s->first_displayed_line = 1;
5721 view->count = 0;
5722 break;
5723 case 'G':
5724 case KEY_END:
5725 if (s->blame.nlines < eos) {
5726 s->selected_line = s->blame.nlines;
5727 s->first_displayed_line = 1;
5728 } else {
5729 s->selected_line = eos;
5730 s->first_displayed_line = s->blame.nlines - (eos - 1);
5732 view->count = 0;
5733 break;
5734 case 'k':
5735 case KEY_UP:
5736 case CTRL('p'):
5737 if (s->selected_line > 1)
5738 s->selected_line--;
5739 else if (s->selected_line == 1 &&
5740 s->first_displayed_line > 1)
5741 s->first_displayed_line--;
5742 else
5743 view->count = 0;
5744 break;
5745 case CTRL('u'):
5746 case 'u':
5747 nscroll /= 2;
5748 /* FALL THROUGH */
5749 case KEY_PPAGE:
5750 case CTRL('b'):
5751 case 'b':
5752 if (s->first_displayed_line == 1) {
5753 if (view->count > 1)
5754 nscroll += nscroll;
5755 s->selected_line = MAX(1, s->selected_line - nscroll);
5756 view->count = 0;
5757 break;
5759 if (s->first_displayed_line > nscroll)
5760 s->first_displayed_line -= nscroll;
5761 else
5762 s->first_displayed_line = 1;
5763 break;
5764 case 'j':
5765 case KEY_DOWN:
5766 case CTRL('n'):
5767 if (s->selected_line < eos && s->first_displayed_line +
5768 s->selected_line <= s->blame.nlines)
5769 s->selected_line++;
5770 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5771 s->first_displayed_line++;
5772 else
5773 view->count = 0;
5774 break;
5775 case 'c':
5776 case 'p': {
5777 struct got_object_id *id = NULL;
5779 view->count = 0;
5780 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5781 s->first_displayed_line, s->selected_line);
5782 if (id == NULL)
5783 break;
5784 if (ch == 'p') {
5785 struct got_commit_object *commit, *pcommit;
5786 struct got_object_qid *pid;
5787 struct got_object_id *blob_id = NULL;
5788 int obj_type;
5789 err = got_object_open_as_commit(&commit,
5790 s->repo, id);
5791 if (err)
5792 break;
5793 pid = STAILQ_FIRST(
5794 got_object_commit_get_parent_ids(commit));
5795 if (pid == NULL) {
5796 got_object_commit_close(commit);
5797 break;
5799 /* Check if path history ends here. */
5800 err = got_object_open_as_commit(&pcommit,
5801 s->repo, &pid->id);
5802 if (err)
5803 break;
5804 err = got_object_id_by_path(&blob_id, s->repo,
5805 pcommit, s->path);
5806 got_object_commit_close(pcommit);
5807 if (err) {
5808 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5809 err = NULL;
5810 got_object_commit_close(commit);
5811 break;
5813 err = got_object_get_type(&obj_type, s->repo,
5814 blob_id);
5815 free(blob_id);
5816 /* Can't blame non-blob type objects. */
5817 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5818 got_object_commit_close(commit);
5819 break;
5821 err = got_object_qid_alloc(&s->blamed_commit,
5822 &pid->id);
5823 got_object_commit_close(commit);
5824 } else {
5825 if (got_object_id_cmp(id,
5826 &s->blamed_commit->id) == 0)
5827 break;
5828 err = got_object_qid_alloc(&s->blamed_commit,
5829 id);
5831 if (err)
5832 break;
5833 s->done = 1;
5834 thread_err = stop_blame(&s->blame);
5835 s->done = 0;
5836 if (thread_err)
5837 break;
5838 STAILQ_INSERT_HEAD(&s->blamed_commits,
5839 s->blamed_commit, entry);
5840 err = run_blame(view);
5841 if (err)
5842 break;
5843 break;
5845 case 'C': {
5846 struct got_object_qid *first;
5848 view->count = 0;
5849 first = STAILQ_FIRST(&s->blamed_commits);
5850 if (!got_object_id_cmp(&first->id, s->commit_id))
5851 break;
5852 s->done = 1;
5853 thread_err = stop_blame(&s->blame);
5854 s->done = 0;
5855 if (thread_err)
5856 break;
5857 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5858 got_object_qid_free(s->blamed_commit);
5859 s->blamed_commit =
5860 STAILQ_FIRST(&s->blamed_commits);
5861 err = run_blame(view);
5862 if (err)
5863 break;
5864 break;
5866 case KEY_ENTER:
5867 case '\r': {
5868 struct got_object_id *id = NULL;
5869 struct got_object_qid *pid;
5870 struct got_commit_object *commit = NULL;
5872 view->count = 0;
5873 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5874 s->first_displayed_line, s->selected_line);
5875 if (id == NULL)
5876 break;
5877 err = got_object_open_as_commit(&commit, s->repo, id);
5878 if (err)
5879 break;
5880 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5881 if (*new_view) {
5882 /* traversed from diff view, release diff resources */
5883 err = close_diff_view(*new_view);
5884 if (err)
5885 break;
5886 diff_view = *new_view;
5887 } else {
5888 if (view_is_parent_view(view))
5889 view_get_split(view, &begin_y, &begin_x);
5891 diff_view = view_open(0, 0, begin_y, begin_x,
5892 TOG_VIEW_DIFF);
5893 if (diff_view == NULL) {
5894 got_object_commit_close(commit);
5895 err = got_error_from_errno("view_open");
5896 break;
5899 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5900 id, NULL, NULL, 3, 0, 0, view, s->repo);
5901 got_object_commit_close(commit);
5902 if (err) {
5903 view_close(diff_view);
5904 break;
5906 s->last_diffed_line = s->first_displayed_line - 1 +
5907 s->selected_line;
5908 if (*new_view)
5909 break; /* still open from active diff view */
5910 if (view_is_parent_view(view) &&
5911 view->mode == TOG_VIEW_SPLIT_HRZN) {
5912 err = view_init_hsplit(view, begin_y);
5913 if (err)
5914 break;
5917 view->focussed = 0;
5918 diff_view->focussed = 1;
5919 diff_view->mode = view->mode;
5920 diff_view->nlines = view->lines - begin_y;
5921 if (view_is_parent_view(view)) {
5922 view_transfer_size(diff_view, view);
5923 err = view_close_child(view);
5924 if (err)
5925 break;
5926 err = view_set_child(view, diff_view);
5927 if (err)
5928 break;
5929 view->focus_child = 1;
5930 } else
5931 *new_view = diff_view;
5932 if (err)
5933 break;
5934 break;
5936 case CTRL('d'):
5937 case 'd':
5938 nscroll /= 2;
5939 /* FALL THROUGH */
5940 case KEY_NPAGE:
5941 case CTRL('f'):
5942 case 'f':
5943 case ' ':
5944 if (s->last_displayed_line >= s->blame.nlines &&
5945 s->selected_line >= MIN(s->blame.nlines,
5946 view->nlines - 2)) {
5947 view->count = 0;
5948 break;
5950 if (s->last_displayed_line >= s->blame.nlines &&
5951 s->selected_line < view->nlines - 2) {
5952 s->selected_line +=
5953 MIN(nscroll, s->last_displayed_line -
5954 s->first_displayed_line - s->selected_line + 1);
5956 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5957 s->first_displayed_line += nscroll;
5958 else
5959 s->first_displayed_line =
5960 s->blame.nlines - (view->nlines - 3);
5961 break;
5962 case KEY_RESIZE:
5963 if (s->selected_line > view->nlines - 2) {
5964 s->selected_line = MIN(s->blame.nlines,
5965 view->nlines - 2);
5967 break;
5968 default:
5969 view->count = 0;
5970 break;
5972 return thread_err ? thread_err : err;
5975 static const struct got_error *
5976 reset_blame_view(struct tog_view *view)
5978 const struct got_error *err;
5979 struct tog_blame_view_state *s = &view->state.blame;
5981 view->count = 0;
5982 s->done = 1;
5983 err = stop_blame(&s->blame);
5984 s->done = 0;
5985 if (err)
5986 return err;
5987 return run_blame(view);
5990 static const struct got_error *
5991 cmd_blame(int argc, char *argv[])
5993 const struct got_error *error;
5994 struct got_repository *repo = NULL;
5995 struct got_worktree *worktree = NULL;
5996 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5997 char *link_target = NULL;
5998 struct got_object_id *commit_id = NULL;
5999 struct got_commit_object *commit = NULL;
6000 char *commit_id_str = NULL;
6001 int ch;
6002 struct tog_view *view;
6003 int *pack_fds = NULL;
6005 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6006 switch (ch) {
6007 case 'c':
6008 commit_id_str = optarg;
6009 break;
6010 case 'r':
6011 repo_path = realpath(optarg, NULL);
6012 if (repo_path == NULL)
6013 return got_error_from_errno2("realpath",
6014 optarg);
6015 break;
6016 default:
6017 usage_blame();
6018 /* NOTREACHED */
6022 argc -= optind;
6023 argv += optind;
6025 if (argc != 1)
6026 usage_blame();
6028 error = got_repo_pack_fds_open(&pack_fds);
6029 if (error != NULL)
6030 goto done;
6032 if (repo_path == NULL) {
6033 cwd = getcwd(NULL, 0);
6034 if (cwd == NULL)
6035 return got_error_from_errno("getcwd");
6036 error = got_worktree_open(&worktree, cwd);
6037 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6038 goto done;
6039 if (worktree)
6040 repo_path =
6041 strdup(got_worktree_get_repo_path(worktree));
6042 else
6043 repo_path = strdup(cwd);
6044 if (repo_path == NULL) {
6045 error = got_error_from_errno("strdup");
6046 goto done;
6050 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6051 if (error != NULL)
6052 goto done;
6054 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6055 worktree);
6056 if (error)
6057 goto done;
6059 init_curses();
6061 error = apply_unveil(got_repo_get_path(repo), NULL);
6062 if (error)
6063 goto done;
6065 error = tog_load_refs(repo, 0);
6066 if (error)
6067 goto done;
6069 if (commit_id_str == NULL) {
6070 struct got_reference *head_ref;
6071 error = got_ref_open(&head_ref, repo, worktree ?
6072 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6073 if (error != NULL)
6074 goto done;
6075 error = got_ref_resolve(&commit_id, repo, head_ref);
6076 got_ref_close(head_ref);
6077 } else {
6078 error = got_repo_match_object_id(&commit_id, NULL,
6079 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6081 if (error != NULL)
6082 goto done;
6084 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6085 if (view == NULL) {
6086 error = got_error_from_errno("view_open");
6087 goto done;
6090 error = got_object_open_as_commit(&commit, repo, commit_id);
6091 if (error)
6092 goto done;
6094 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6095 commit, repo);
6096 if (error)
6097 goto done;
6099 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6100 commit_id, repo);
6101 if (error)
6102 goto done;
6103 if (worktree) {
6104 /* Release work tree lock. */
6105 got_worktree_close(worktree);
6106 worktree = NULL;
6108 error = view_loop(view);
6109 done:
6110 free(repo_path);
6111 free(in_repo_path);
6112 free(link_target);
6113 free(cwd);
6114 free(commit_id);
6115 if (commit)
6116 got_object_commit_close(commit);
6117 if (worktree)
6118 got_worktree_close(worktree);
6119 if (repo) {
6120 const struct got_error *close_err = got_repo_close(repo);
6121 if (error == NULL)
6122 error = close_err;
6124 if (pack_fds) {
6125 const struct got_error *pack_err =
6126 got_repo_pack_fds_close(pack_fds);
6127 if (error == NULL)
6128 error = pack_err;
6130 tog_free_refs();
6131 return error;
6134 static const struct got_error *
6135 draw_tree_entries(struct tog_view *view, const char *parent_path)
6137 struct tog_tree_view_state *s = &view->state.tree;
6138 const struct got_error *err = NULL;
6139 struct got_tree_entry *te;
6140 wchar_t *wline;
6141 struct tog_color *tc;
6142 int width, n, i, nentries;
6143 int limit = view->nlines;
6145 s->ndisplayed = 0;
6146 if (view_is_hsplit_top(view))
6147 --limit; /* border */
6149 werase(view->window);
6151 if (limit == 0)
6152 return NULL;
6154 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6155 0, 0);
6156 if (err)
6157 return err;
6158 if (view_needs_focus_indication(view))
6159 wstandout(view->window);
6160 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6161 if (tc)
6162 wattr_on(view->window,
6163 COLOR_PAIR(tc->colorpair), NULL);
6164 waddwstr(view->window, wline);
6165 if (tc)
6166 wattr_off(view->window,
6167 COLOR_PAIR(tc->colorpair), NULL);
6168 if (view_needs_focus_indication(view))
6169 wstandend(view->window);
6170 free(wline);
6171 wline = NULL;
6172 if (width < view->ncols - 1)
6173 waddch(view->window, '\n');
6174 if (--limit <= 0)
6175 return NULL;
6176 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6177 0, 0);
6178 if (err)
6179 return err;
6180 waddwstr(view->window, wline);
6181 free(wline);
6182 wline = NULL;
6183 if (width < view->ncols - 1)
6184 waddch(view->window, '\n');
6185 if (--limit <= 0)
6186 return NULL;
6187 waddch(view->window, '\n');
6188 if (--limit <= 0)
6189 return NULL;
6191 if (s->first_displayed_entry == NULL) {
6192 te = got_object_tree_get_first_entry(s->tree);
6193 if (s->selected == 0) {
6194 if (view->focussed)
6195 wstandout(view->window);
6196 s->selected_entry = NULL;
6198 waddstr(view->window, " ..\n"); /* parent directory */
6199 if (s->selected == 0 && view->focussed)
6200 wstandend(view->window);
6201 s->ndisplayed++;
6202 if (--limit <= 0)
6203 return NULL;
6204 n = 1;
6205 } else {
6206 n = 0;
6207 te = s->first_displayed_entry;
6210 nentries = got_object_tree_get_nentries(s->tree);
6211 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6212 char *line = NULL, *id_str = NULL, *link_target = NULL;
6213 const char *modestr = "";
6214 mode_t mode;
6216 te = got_object_tree_get_entry(s->tree, i);
6217 mode = got_tree_entry_get_mode(te);
6219 if (s->show_ids) {
6220 err = got_object_id_str(&id_str,
6221 got_tree_entry_get_id(te));
6222 if (err)
6223 return got_error_from_errno(
6224 "got_object_id_str");
6226 if (got_object_tree_entry_is_submodule(te))
6227 modestr = "$";
6228 else if (S_ISLNK(mode)) {
6229 int i;
6231 err = got_tree_entry_get_symlink_target(&link_target,
6232 te, s->repo);
6233 if (err) {
6234 free(id_str);
6235 return err;
6237 for (i = 0; i < strlen(link_target); i++) {
6238 if (!isprint((unsigned char)link_target[i]))
6239 link_target[i] = '?';
6241 modestr = "@";
6243 else if (S_ISDIR(mode))
6244 modestr = "/";
6245 else if (mode & S_IXUSR)
6246 modestr = "*";
6247 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6248 got_tree_entry_get_name(te), modestr,
6249 link_target ? " -> ": "",
6250 link_target ? link_target : "") == -1) {
6251 free(id_str);
6252 free(link_target);
6253 return got_error_from_errno("asprintf");
6255 free(id_str);
6256 free(link_target);
6257 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6258 0, 0);
6259 if (err) {
6260 free(line);
6261 break;
6263 if (n == s->selected) {
6264 if (view->focussed)
6265 wstandout(view->window);
6266 s->selected_entry = te;
6268 tc = match_color(&s->colors, line);
6269 if (tc)
6270 wattr_on(view->window,
6271 COLOR_PAIR(tc->colorpair), NULL);
6272 waddwstr(view->window, wline);
6273 if (tc)
6274 wattr_off(view->window,
6275 COLOR_PAIR(tc->colorpair), NULL);
6276 if (width < view->ncols - 1)
6277 waddch(view->window, '\n');
6278 if (n == s->selected && view->focussed)
6279 wstandend(view->window);
6280 free(line);
6281 free(wline);
6282 wline = NULL;
6283 n++;
6284 s->ndisplayed++;
6285 s->last_displayed_entry = te;
6286 if (--limit <= 0)
6287 break;
6290 return err;
6293 static void
6294 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6296 struct got_tree_entry *te;
6297 int isroot = s->tree == s->root;
6298 int i = 0;
6300 if (s->first_displayed_entry == NULL)
6301 return;
6303 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6304 while (i++ < maxscroll) {
6305 if (te == NULL) {
6306 if (!isroot)
6307 s->first_displayed_entry = NULL;
6308 break;
6310 s->first_displayed_entry = te;
6311 te = got_tree_entry_get_prev(s->tree, te);
6315 static const struct got_error *
6316 tree_scroll_down(struct tog_view *view, int maxscroll)
6318 struct tog_tree_view_state *s = &view->state.tree;
6319 struct got_tree_entry *next, *last;
6320 int n = 0;
6322 if (s->first_displayed_entry)
6323 next = got_tree_entry_get_next(s->tree,
6324 s->first_displayed_entry);
6325 else
6326 next = got_object_tree_get_first_entry(s->tree);
6328 last = s->last_displayed_entry;
6329 while (next && n++ < maxscroll) {
6330 if (last)
6331 last = got_tree_entry_get_next(s->tree, last);
6332 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6333 s->first_displayed_entry = next;
6334 next = got_tree_entry_get_next(s->tree, next);
6338 return NULL;
6341 static const struct got_error *
6342 tree_entry_path(char **path, struct tog_parent_trees *parents,
6343 struct got_tree_entry *te)
6345 const struct got_error *err = NULL;
6346 struct tog_parent_tree *pt;
6347 size_t len = 2; /* for leading slash and NUL */
6349 TAILQ_FOREACH(pt, parents, entry)
6350 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6351 + 1 /* slash */;
6352 if (te)
6353 len += strlen(got_tree_entry_get_name(te));
6355 *path = calloc(1, len);
6356 if (path == NULL)
6357 return got_error_from_errno("calloc");
6359 (*path)[0] = '/';
6360 pt = TAILQ_LAST(parents, tog_parent_trees);
6361 while (pt) {
6362 const char *name = got_tree_entry_get_name(pt->selected_entry);
6363 if (strlcat(*path, name, len) >= len) {
6364 err = got_error(GOT_ERR_NO_SPACE);
6365 goto done;
6367 if (strlcat(*path, "/", len) >= len) {
6368 err = got_error(GOT_ERR_NO_SPACE);
6369 goto done;
6371 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6373 if (te) {
6374 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6375 err = got_error(GOT_ERR_NO_SPACE);
6376 goto done;
6379 done:
6380 if (err) {
6381 free(*path);
6382 *path = NULL;
6384 return err;
6387 static const struct got_error *
6388 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6389 struct got_tree_entry *te, struct tog_parent_trees *parents,
6390 struct got_object_id *commit_id, struct got_repository *repo)
6392 const struct got_error *err = NULL;
6393 char *path;
6394 struct tog_view *blame_view;
6396 *new_view = NULL;
6398 err = tree_entry_path(&path, parents, te);
6399 if (err)
6400 return err;
6402 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6403 if (blame_view == NULL) {
6404 err = got_error_from_errno("view_open");
6405 goto done;
6408 err = open_blame_view(blame_view, path, commit_id, repo);
6409 if (err) {
6410 if (err->code == GOT_ERR_CANCELLED)
6411 err = NULL;
6412 view_close(blame_view);
6413 } else
6414 *new_view = blame_view;
6415 done:
6416 free(path);
6417 return err;
6420 static const struct got_error *
6421 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6422 struct tog_tree_view_state *s)
6424 struct tog_view *log_view;
6425 const struct got_error *err = NULL;
6426 char *path;
6428 *new_view = NULL;
6430 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6431 if (log_view == NULL)
6432 return got_error_from_errno("view_open");
6434 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6435 if (err)
6436 return err;
6438 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6439 path, 0);
6440 if (err)
6441 view_close(log_view);
6442 else
6443 *new_view = log_view;
6444 free(path);
6445 return err;
6448 static const struct got_error *
6449 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6450 const char *head_ref_name, struct got_repository *repo)
6452 const struct got_error *err = NULL;
6453 char *commit_id_str = NULL;
6454 struct tog_tree_view_state *s = &view->state.tree;
6455 struct got_commit_object *commit = NULL;
6457 TAILQ_INIT(&s->parents);
6458 STAILQ_INIT(&s->colors);
6460 s->commit_id = got_object_id_dup(commit_id);
6461 if (s->commit_id == NULL)
6462 return got_error_from_errno("got_object_id_dup");
6464 err = got_object_open_as_commit(&commit, repo, commit_id);
6465 if (err)
6466 goto done;
6469 * The root is opened here and will be closed when the view is closed.
6470 * Any visited subtrees and their path-wise parents are opened and
6471 * closed on demand.
6473 err = got_object_open_as_tree(&s->root, repo,
6474 got_object_commit_get_tree_id(commit));
6475 if (err)
6476 goto done;
6477 s->tree = s->root;
6479 err = got_object_id_str(&commit_id_str, commit_id);
6480 if (err != NULL)
6481 goto done;
6483 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6484 err = got_error_from_errno("asprintf");
6485 goto done;
6488 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6489 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6490 if (head_ref_name) {
6491 s->head_ref_name = strdup(head_ref_name);
6492 if (s->head_ref_name == NULL) {
6493 err = got_error_from_errno("strdup");
6494 goto done;
6497 s->repo = repo;
6499 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6500 err = add_color(&s->colors, "\\$$",
6501 TOG_COLOR_TREE_SUBMODULE,
6502 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6503 if (err)
6504 goto done;
6505 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6506 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6507 if (err)
6508 goto done;
6509 err = add_color(&s->colors, "/$",
6510 TOG_COLOR_TREE_DIRECTORY,
6511 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6512 if (err)
6513 goto done;
6515 err = add_color(&s->colors, "\\*$",
6516 TOG_COLOR_TREE_EXECUTABLE,
6517 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6518 if (err)
6519 goto done;
6521 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6522 get_color_value("TOG_COLOR_COMMIT"));
6523 if (err)
6524 goto done;
6527 view->show = show_tree_view;
6528 view->input = input_tree_view;
6529 view->close = close_tree_view;
6530 view->search_start = search_start_tree_view;
6531 view->search_next = search_next_tree_view;
6532 done:
6533 free(commit_id_str);
6534 if (commit)
6535 got_object_commit_close(commit);
6536 if (err)
6537 close_tree_view(view);
6538 return err;
6541 static const struct got_error *
6542 close_tree_view(struct tog_view *view)
6544 struct tog_tree_view_state *s = &view->state.tree;
6546 free_colors(&s->colors);
6547 free(s->tree_label);
6548 s->tree_label = NULL;
6549 free(s->commit_id);
6550 s->commit_id = NULL;
6551 free(s->head_ref_name);
6552 s->head_ref_name = NULL;
6553 while (!TAILQ_EMPTY(&s->parents)) {
6554 struct tog_parent_tree *parent;
6555 parent = TAILQ_FIRST(&s->parents);
6556 TAILQ_REMOVE(&s->parents, parent, entry);
6557 if (parent->tree != s->root)
6558 got_object_tree_close(parent->tree);
6559 free(parent);
6562 if (s->tree != NULL && s->tree != s->root)
6563 got_object_tree_close(s->tree);
6564 if (s->root)
6565 got_object_tree_close(s->root);
6566 return NULL;
6569 static const struct got_error *
6570 search_start_tree_view(struct tog_view *view)
6572 struct tog_tree_view_state *s = &view->state.tree;
6574 s->matched_entry = NULL;
6575 return NULL;
6578 static int
6579 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6581 regmatch_t regmatch;
6583 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6584 0) == 0;
6587 static const struct got_error *
6588 search_next_tree_view(struct tog_view *view)
6590 struct tog_tree_view_state *s = &view->state.tree;
6591 struct got_tree_entry *te = NULL;
6593 if (!view->searching) {
6594 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6595 return NULL;
6598 if (s->matched_entry) {
6599 if (view->searching == TOG_SEARCH_FORWARD) {
6600 if (s->selected_entry)
6601 te = got_tree_entry_get_next(s->tree,
6602 s->selected_entry);
6603 else
6604 te = got_object_tree_get_first_entry(s->tree);
6605 } else {
6606 if (s->selected_entry == NULL)
6607 te = got_object_tree_get_last_entry(s->tree);
6608 else
6609 te = got_tree_entry_get_prev(s->tree,
6610 s->selected_entry);
6612 } else {
6613 if (s->selected_entry)
6614 te = s->selected_entry;
6615 else if (view->searching == TOG_SEARCH_FORWARD)
6616 te = got_object_tree_get_first_entry(s->tree);
6617 else
6618 te = got_object_tree_get_last_entry(s->tree);
6621 while (1) {
6622 if (te == NULL) {
6623 if (s->matched_entry == NULL) {
6624 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6625 return NULL;
6627 if (view->searching == TOG_SEARCH_FORWARD)
6628 te = got_object_tree_get_first_entry(s->tree);
6629 else
6630 te = got_object_tree_get_last_entry(s->tree);
6633 if (match_tree_entry(te, &view->regex)) {
6634 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6635 s->matched_entry = te;
6636 break;
6639 if (view->searching == TOG_SEARCH_FORWARD)
6640 te = got_tree_entry_get_next(s->tree, te);
6641 else
6642 te = got_tree_entry_get_prev(s->tree, te);
6645 if (s->matched_entry) {
6646 s->first_displayed_entry = s->matched_entry;
6647 s->selected = 0;
6650 return NULL;
6653 static const struct got_error *
6654 show_tree_view(struct tog_view *view)
6656 const struct got_error *err = NULL;
6657 struct tog_tree_view_state *s = &view->state.tree;
6658 char *parent_path;
6660 err = tree_entry_path(&parent_path, &s->parents, NULL);
6661 if (err)
6662 return err;
6664 err = draw_tree_entries(view, parent_path);
6665 free(parent_path);
6667 view_border(view);
6668 return err;
6671 static const struct got_error *
6672 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6674 const struct got_error *err = NULL;
6675 struct tog_tree_view_state *s = &view->state.tree;
6676 struct tog_view *log_view, *ref_view;
6677 struct got_tree_entry *te;
6678 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 3;
6680 switch (ch) {
6681 case 'i':
6682 s->show_ids = !s->show_ids;
6683 view->count = 0;
6684 break;
6685 case 'l':
6686 view->count = 0;
6687 if (!s->selected_entry)
6688 break;
6689 if (view_is_parent_view(view))
6690 view_get_split(view, &begin_y, &begin_x);
6691 err = log_selected_tree_entry(&log_view, begin_y, begin_x, s);
6692 if (view_is_parent_view(view) &&
6693 view->mode == TOG_VIEW_SPLIT_HRZN) {
6694 err = view_init_hsplit(view, begin_y);
6695 if (err)
6696 break;
6698 view->focussed = 0;
6699 log_view->focussed = 1;
6700 log_view->mode = view->mode;
6701 log_view->nlines = view->lines - begin_y;
6702 if (view_is_parent_view(view)) {
6703 view_transfer_size(log_view, view);
6704 err = view_close_child(view);
6705 if (err)
6706 return err;
6707 err = view_set_child(view, log_view);
6708 if (err)
6709 return err;
6710 view->focus_child = 1;
6711 } else
6712 *new_view = log_view;
6713 break;
6714 case 'r':
6715 view->count = 0;
6716 if (view_is_parent_view(view))
6717 view_get_split(view, &begin_y, &begin_x);
6718 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
6719 if (ref_view == NULL)
6720 return got_error_from_errno("view_open");
6721 err = open_ref_view(ref_view, s->repo);
6722 if (err) {
6723 view_close(ref_view);
6724 return err;
6726 if (view_is_parent_view(view) &&
6727 view->mode == TOG_VIEW_SPLIT_HRZN) {
6728 err = view_init_hsplit(view, begin_y);
6729 if (err)
6730 break;
6732 view->focussed = 0;
6733 ref_view->focussed = 1;
6734 ref_view->mode = view->mode;
6735 ref_view->nlines = view->lines - begin_y;
6736 if (view_is_parent_view(view)) {
6737 view_transfer_size(ref_view, view);
6738 err = view_close_child(view);
6739 if (err)
6740 return err;
6741 err = view_set_child(view, ref_view);
6742 if (err)
6743 return err;
6744 view->focus_child = 1;
6745 } else
6746 *new_view = ref_view;
6747 break;
6748 case 'g':
6749 case KEY_HOME:
6750 s->selected = 0;
6751 view->count = 0;
6752 if (s->tree == s->root)
6753 s->first_displayed_entry =
6754 got_object_tree_get_first_entry(s->tree);
6755 else
6756 s->first_displayed_entry = NULL;
6757 break;
6758 case 'G':
6759 case KEY_END: {
6760 int eos = view->nlines - 3;
6762 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6763 --eos; /* border */
6764 s->selected = 0;
6765 view->count = 0;
6766 te = got_object_tree_get_last_entry(s->tree);
6767 for (n = 0; n < eos; n++) {
6768 if (te == NULL) {
6769 if(s->tree != s->root) {
6770 s->first_displayed_entry = NULL;
6771 n++;
6773 break;
6775 s->first_displayed_entry = te;
6776 te = got_tree_entry_get_prev(s->tree, te);
6778 if (n > 0)
6779 s->selected = n - 1;
6780 break;
6782 case 'k':
6783 case KEY_UP:
6784 case CTRL('p'):
6785 if (s->selected > 0) {
6786 s->selected--;
6787 break;
6789 tree_scroll_up(s, 1);
6790 if (s->selected_entry == NULL ||
6791 (s->tree == s->root && s->selected_entry ==
6792 got_object_tree_get_first_entry(s->tree)))
6793 view->count = 0;
6794 break;
6795 case CTRL('u'):
6796 case 'u':
6797 nscroll /= 2;
6798 /* FALL THROUGH */
6799 case KEY_PPAGE:
6800 case CTRL('b'):
6801 case 'b':
6802 if (s->tree == s->root) {
6803 if (got_object_tree_get_first_entry(s->tree) ==
6804 s->first_displayed_entry)
6805 s->selected -= MIN(s->selected, nscroll);
6806 } else {
6807 if (s->first_displayed_entry == NULL)
6808 s->selected -= MIN(s->selected, nscroll);
6810 tree_scroll_up(s, MAX(0, nscroll));
6811 if (s->selected_entry == NULL ||
6812 (s->tree == s->root && s->selected_entry ==
6813 got_object_tree_get_first_entry(s->tree)))
6814 view->count = 0;
6815 break;
6816 case 'j':
6817 case KEY_DOWN:
6818 case CTRL('n'):
6819 if (s->selected < s->ndisplayed - 1) {
6820 s->selected++;
6821 break;
6823 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6824 == NULL) {
6825 /* can't scroll any further */
6826 view->count = 0;
6827 break;
6829 tree_scroll_down(view, 1);
6830 break;
6831 case CTRL('d'):
6832 case 'd':
6833 nscroll /= 2;
6834 /* FALL THROUGH */
6835 case KEY_NPAGE:
6836 case CTRL('f'):
6837 case 'f':
6838 case ' ':
6839 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6840 == NULL) {
6841 /* can't scroll any further; move cursor down */
6842 if (s->selected < s->ndisplayed - 1)
6843 s->selected += MIN(nscroll,
6844 s->ndisplayed - s->selected - 1);
6845 else
6846 view->count = 0;
6847 break;
6849 tree_scroll_down(view, nscroll);
6850 break;
6851 case KEY_ENTER:
6852 case '\r':
6853 case KEY_BACKSPACE:
6854 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6855 struct tog_parent_tree *parent;
6856 /* user selected '..' */
6857 if (s->tree == s->root) {
6858 view->count = 0;
6859 break;
6861 parent = TAILQ_FIRST(&s->parents);
6862 TAILQ_REMOVE(&s->parents, parent,
6863 entry);
6864 got_object_tree_close(s->tree);
6865 s->tree = parent->tree;
6866 s->first_displayed_entry =
6867 parent->first_displayed_entry;
6868 s->selected_entry =
6869 parent->selected_entry;
6870 s->selected = parent->selected;
6871 if (s->selected > view->nlines - 3) {
6872 err = offset_selection_down(view);
6873 if (err)
6874 break;
6876 free(parent);
6877 } else if (S_ISDIR(got_tree_entry_get_mode(
6878 s->selected_entry))) {
6879 struct got_tree_object *subtree;
6880 view->count = 0;
6881 err = got_object_open_as_tree(&subtree, s->repo,
6882 got_tree_entry_get_id(s->selected_entry));
6883 if (err)
6884 break;
6885 err = tree_view_visit_subtree(s, subtree);
6886 if (err) {
6887 got_object_tree_close(subtree);
6888 break;
6890 } else if (S_ISREG(got_tree_entry_get_mode(
6891 s->selected_entry))) {
6892 struct tog_view *blame_view;
6893 int begin_x = 0, begin_y = 0;
6895 if (view_is_parent_view(view))
6896 view_get_split(view, &begin_y, &begin_x);
6898 err = blame_tree_entry(&blame_view, begin_y, begin_x,
6899 s->selected_entry, &s->parents,
6900 s->commit_id, s->repo);
6901 if (err)
6902 break;
6904 if (view_is_parent_view(view) &&
6905 view->mode == TOG_VIEW_SPLIT_HRZN) {
6906 err = view_init_hsplit(view, begin_y);
6907 if (err)
6908 break;
6911 view->count = 0;
6912 view->focussed = 0;
6913 blame_view->focussed = 1;
6914 blame_view->mode = view->mode;
6915 blame_view->nlines = view->lines - begin_y;
6916 if (view_is_parent_view(view)) {
6917 view_transfer_size(blame_view, view);
6918 err = view_close_child(view);
6919 if (err)
6920 return err;
6921 err = view_set_child(view, blame_view);
6922 if (err)
6923 return err;
6924 view->focus_child = 1;
6925 } else
6926 *new_view = blame_view;
6928 break;
6929 case KEY_RESIZE:
6930 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6931 s->selected = view->nlines - 4;
6932 view->count = 0;
6933 break;
6934 default:
6935 view->count = 0;
6936 break;
6939 return err;
6942 __dead static void
6943 usage_tree(void)
6945 endwin();
6946 fprintf(stderr,
6947 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6948 getprogname());
6949 exit(1);
6952 static const struct got_error *
6953 cmd_tree(int argc, char *argv[])
6955 const struct got_error *error;
6956 struct got_repository *repo = NULL;
6957 struct got_worktree *worktree = NULL;
6958 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6959 struct got_object_id *commit_id = NULL;
6960 struct got_commit_object *commit = NULL;
6961 const char *commit_id_arg = NULL;
6962 char *label = NULL;
6963 struct got_reference *ref = NULL;
6964 const char *head_ref_name = NULL;
6965 int ch;
6966 struct tog_view *view;
6967 int *pack_fds = NULL;
6969 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6970 switch (ch) {
6971 case 'c':
6972 commit_id_arg = optarg;
6973 break;
6974 case 'r':
6975 repo_path = realpath(optarg, NULL);
6976 if (repo_path == NULL)
6977 return got_error_from_errno2("realpath",
6978 optarg);
6979 break;
6980 default:
6981 usage_tree();
6982 /* NOTREACHED */
6986 argc -= optind;
6987 argv += optind;
6989 if (argc > 1)
6990 usage_tree();
6992 error = got_repo_pack_fds_open(&pack_fds);
6993 if (error != NULL)
6994 goto done;
6996 if (repo_path == NULL) {
6997 cwd = getcwd(NULL, 0);
6998 if (cwd == NULL)
6999 return got_error_from_errno("getcwd");
7000 error = got_worktree_open(&worktree, cwd);
7001 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7002 goto done;
7003 if (worktree)
7004 repo_path =
7005 strdup(got_worktree_get_repo_path(worktree));
7006 else
7007 repo_path = strdup(cwd);
7008 if (repo_path == NULL) {
7009 error = got_error_from_errno("strdup");
7010 goto done;
7014 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7015 if (error != NULL)
7016 goto done;
7018 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7019 repo, worktree);
7020 if (error)
7021 goto done;
7023 init_curses();
7025 error = apply_unveil(got_repo_get_path(repo), NULL);
7026 if (error)
7027 goto done;
7029 error = tog_load_refs(repo, 0);
7030 if (error)
7031 goto done;
7033 if (commit_id_arg == NULL) {
7034 error = got_repo_match_object_id(&commit_id, &label,
7035 worktree ? got_worktree_get_head_ref_name(worktree) :
7036 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7037 if (error)
7038 goto done;
7039 head_ref_name = label;
7040 } else {
7041 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7042 if (error == NULL)
7043 head_ref_name = got_ref_get_name(ref);
7044 else if (error->code != GOT_ERR_NOT_REF)
7045 goto done;
7046 error = got_repo_match_object_id(&commit_id, NULL,
7047 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7048 if (error)
7049 goto done;
7052 error = got_object_open_as_commit(&commit, repo, commit_id);
7053 if (error)
7054 goto done;
7056 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7057 if (view == NULL) {
7058 error = got_error_from_errno("view_open");
7059 goto done;
7061 error = open_tree_view(view, commit_id, head_ref_name, repo);
7062 if (error)
7063 goto done;
7064 if (!got_path_is_root_dir(in_repo_path)) {
7065 error = tree_view_walk_path(&view->state.tree, commit,
7066 in_repo_path);
7067 if (error)
7068 goto done;
7071 if (worktree) {
7072 /* Release work tree lock. */
7073 got_worktree_close(worktree);
7074 worktree = NULL;
7076 error = view_loop(view);
7077 done:
7078 free(repo_path);
7079 free(cwd);
7080 free(commit_id);
7081 free(label);
7082 if (ref)
7083 got_ref_close(ref);
7084 if (repo) {
7085 const struct got_error *close_err = got_repo_close(repo);
7086 if (error == NULL)
7087 error = close_err;
7089 if (pack_fds) {
7090 const struct got_error *pack_err =
7091 got_repo_pack_fds_close(pack_fds);
7092 if (error == NULL)
7093 error = pack_err;
7095 tog_free_refs();
7096 return error;
7099 static const struct got_error *
7100 ref_view_load_refs(struct tog_ref_view_state *s)
7102 struct got_reflist_entry *sre;
7103 struct tog_reflist_entry *re;
7105 s->nrefs = 0;
7106 TAILQ_FOREACH(sre, &tog_refs, entry) {
7107 if (strncmp(got_ref_get_name(sre->ref),
7108 "refs/got/", 9) == 0 &&
7109 strncmp(got_ref_get_name(sre->ref),
7110 "refs/got/backup/", 16) != 0)
7111 continue;
7113 re = malloc(sizeof(*re));
7114 if (re == NULL)
7115 return got_error_from_errno("malloc");
7117 re->ref = got_ref_dup(sre->ref);
7118 if (re->ref == NULL)
7119 return got_error_from_errno("got_ref_dup");
7120 re->idx = s->nrefs++;
7121 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7124 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7125 return NULL;
7128 static void
7129 ref_view_free_refs(struct tog_ref_view_state *s)
7131 struct tog_reflist_entry *re;
7133 while (!TAILQ_EMPTY(&s->refs)) {
7134 re = TAILQ_FIRST(&s->refs);
7135 TAILQ_REMOVE(&s->refs, re, entry);
7136 got_ref_close(re->ref);
7137 free(re);
7141 static const struct got_error *
7142 open_ref_view(struct tog_view *view, struct got_repository *repo)
7144 const struct got_error *err = NULL;
7145 struct tog_ref_view_state *s = &view->state.ref;
7147 s->selected_entry = 0;
7148 s->repo = repo;
7150 TAILQ_INIT(&s->refs);
7151 STAILQ_INIT(&s->colors);
7153 err = ref_view_load_refs(s);
7154 if (err)
7155 return err;
7157 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7158 err = add_color(&s->colors, "^refs/heads/",
7159 TOG_COLOR_REFS_HEADS,
7160 get_color_value("TOG_COLOR_REFS_HEADS"));
7161 if (err)
7162 goto done;
7164 err = add_color(&s->colors, "^refs/tags/",
7165 TOG_COLOR_REFS_TAGS,
7166 get_color_value("TOG_COLOR_REFS_TAGS"));
7167 if (err)
7168 goto done;
7170 err = add_color(&s->colors, "^refs/remotes/",
7171 TOG_COLOR_REFS_REMOTES,
7172 get_color_value("TOG_COLOR_REFS_REMOTES"));
7173 if (err)
7174 goto done;
7176 err = add_color(&s->colors, "^refs/got/backup/",
7177 TOG_COLOR_REFS_BACKUP,
7178 get_color_value("TOG_COLOR_REFS_BACKUP"));
7179 if (err)
7180 goto done;
7183 view->show = show_ref_view;
7184 view->input = input_ref_view;
7185 view->close = close_ref_view;
7186 view->search_start = search_start_ref_view;
7187 view->search_next = search_next_ref_view;
7188 done:
7189 if (err)
7190 free_colors(&s->colors);
7191 return err;
7194 static const struct got_error *
7195 close_ref_view(struct tog_view *view)
7197 struct tog_ref_view_state *s = &view->state.ref;
7199 ref_view_free_refs(s);
7200 free_colors(&s->colors);
7202 return NULL;
7205 static const struct got_error *
7206 resolve_reflist_entry(struct got_object_id **commit_id,
7207 struct tog_reflist_entry *re, struct got_repository *repo)
7209 const struct got_error *err = NULL;
7210 struct got_object_id *obj_id;
7211 struct got_tag_object *tag = NULL;
7212 int obj_type;
7214 *commit_id = NULL;
7216 err = got_ref_resolve(&obj_id, repo, re->ref);
7217 if (err)
7218 return err;
7220 err = got_object_get_type(&obj_type, repo, obj_id);
7221 if (err)
7222 goto done;
7224 switch (obj_type) {
7225 case GOT_OBJ_TYPE_COMMIT:
7226 *commit_id = obj_id;
7227 break;
7228 case GOT_OBJ_TYPE_TAG:
7229 err = got_object_open_as_tag(&tag, repo, obj_id);
7230 if (err)
7231 goto done;
7232 free(obj_id);
7233 err = got_object_get_type(&obj_type, repo,
7234 got_object_tag_get_object_id(tag));
7235 if (err)
7236 goto done;
7237 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7238 err = got_error(GOT_ERR_OBJ_TYPE);
7239 goto done;
7241 *commit_id = got_object_id_dup(
7242 got_object_tag_get_object_id(tag));
7243 if (*commit_id == NULL) {
7244 err = got_error_from_errno("got_object_id_dup");
7245 goto done;
7247 break;
7248 default:
7249 err = got_error(GOT_ERR_OBJ_TYPE);
7250 break;
7253 done:
7254 if (tag)
7255 got_object_tag_close(tag);
7256 if (err) {
7257 free(*commit_id);
7258 *commit_id = NULL;
7260 return err;
7263 static const struct got_error *
7264 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7265 struct tog_reflist_entry *re, struct got_repository *repo)
7267 struct tog_view *log_view;
7268 const struct got_error *err = NULL;
7269 struct got_object_id *commit_id = NULL;
7271 *new_view = NULL;
7273 err = resolve_reflist_entry(&commit_id, re, repo);
7274 if (err) {
7275 if (err->code != GOT_ERR_OBJ_TYPE)
7276 return err;
7277 else
7278 return NULL;
7281 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7282 if (log_view == NULL) {
7283 err = got_error_from_errno("view_open");
7284 goto done;
7287 err = open_log_view(log_view, commit_id, repo,
7288 got_ref_get_name(re->ref), "", 0);
7289 done:
7290 if (err)
7291 view_close(log_view);
7292 else
7293 *new_view = log_view;
7294 free(commit_id);
7295 return err;
7298 static void
7299 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7301 struct tog_reflist_entry *re;
7302 int i = 0;
7304 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7305 return;
7307 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7308 while (i++ < maxscroll) {
7309 if (re == NULL)
7310 break;
7311 s->first_displayed_entry = re;
7312 re = TAILQ_PREV(re, tog_reflist_head, entry);
7316 static const struct got_error *
7317 ref_scroll_down(struct tog_view *view, int maxscroll)
7319 struct tog_ref_view_state *s = &view->state.ref;
7320 struct tog_reflist_entry *next, *last;
7321 int n = 0;
7323 if (s->first_displayed_entry)
7324 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7325 else
7326 next = TAILQ_FIRST(&s->refs);
7328 last = s->last_displayed_entry;
7329 while (next && n++ < maxscroll) {
7330 if (last)
7331 last = TAILQ_NEXT(last, entry);
7332 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7333 s->first_displayed_entry = next;
7334 next = TAILQ_NEXT(next, entry);
7338 return NULL;
7341 static const struct got_error *
7342 search_start_ref_view(struct tog_view *view)
7344 struct tog_ref_view_state *s = &view->state.ref;
7346 s->matched_entry = NULL;
7347 return NULL;
7350 static int
7351 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7353 regmatch_t regmatch;
7355 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7356 0) == 0;
7359 static const struct got_error *
7360 search_next_ref_view(struct tog_view *view)
7362 struct tog_ref_view_state *s = &view->state.ref;
7363 struct tog_reflist_entry *re = NULL;
7365 if (!view->searching) {
7366 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7367 return NULL;
7370 if (s->matched_entry) {
7371 if (view->searching == TOG_SEARCH_FORWARD) {
7372 if (s->selected_entry)
7373 re = TAILQ_NEXT(s->selected_entry, entry);
7374 else
7375 re = TAILQ_PREV(s->selected_entry,
7376 tog_reflist_head, entry);
7377 } else {
7378 if (s->selected_entry == NULL)
7379 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7380 else
7381 re = TAILQ_PREV(s->selected_entry,
7382 tog_reflist_head, entry);
7384 } else {
7385 if (s->selected_entry)
7386 re = s->selected_entry;
7387 else if (view->searching == TOG_SEARCH_FORWARD)
7388 re = TAILQ_FIRST(&s->refs);
7389 else
7390 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7393 while (1) {
7394 if (re == NULL) {
7395 if (s->matched_entry == NULL) {
7396 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7397 return NULL;
7399 if (view->searching == TOG_SEARCH_FORWARD)
7400 re = TAILQ_FIRST(&s->refs);
7401 else
7402 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7405 if (match_reflist_entry(re, &view->regex)) {
7406 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7407 s->matched_entry = re;
7408 break;
7411 if (view->searching == TOG_SEARCH_FORWARD)
7412 re = TAILQ_NEXT(re, entry);
7413 else
7414 re = TAILQ_PREV(re, tog_reflist_head, entry);
7417 if (s->matched_entry) {
7418 s->first_displayed_entry = s->matched_entry;
7419 s->selected = 0;
7422 return NULL;
7425 static const struct got_error *
7426 show_ref_view(struct tog_view *view)
7428 const struct got_error *err = NULL;
7429 struct tog_ref_view_state *s = &view->state.ref;
7430 struct tog_reflist_entry *re;
7431 char *line = NULL;
7432 wchar_t *wline;
7433 struct tog_color *tc;
7434 int width, n;
7435 int limit = view->nlines;
7437 werase(view->window);
7439 s->ndisplayed = 0;
7440 if (view_is_hsplit_top(view))
7441 --limit; /* border */
7443 if (limit == 0)
7444 return NULL;
7446 re = s->first_displayed_entry;
7448 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7449 s->nrefs) == -1)
7450 return got_error_from_errno("asprintf");
7452 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7453 if (err) {
7454 free(line);
7455 return err;
7457 if (view_needs_focus_indication(view))
7458 wstandout(view->window);
7459 waddwstr(view->window, wline);
7460 if (view_needs_focus_indication(view))
7461 wstandend(view->window);
7462 free(wline);
7463 wline = NULL;
7464 free(line);
7465 line = NULL;
7466 if (width < view->ncols - 1)
7467 waddch(view->window, '\n');
7468 if (--limit <= 0)
7469 return NULL;
7471 n = 0;
7472 while (re && limit > 0) {
7473 char *line = NULL;
7474 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7476 if (s->show_date) {
7477 struct got_commit_object *ci;
7478 struct got_tag_object *tag;
7479 struct got_object_id *id;
7480 struct tm tm;
7481 time_t t;
7483 err = got_ref_resolve(&id, s->repo, re->ref);
7484 if (err)
7485 return err;
7486 err = got_object_open_as_tag(&tag, s->repo, id);
7487 if (err) {
7488 if (err->code != GOT_ERR_OBJ_TYPE) {
7489 free(id);
7490 return err;
7492 err = got_object_open_as_commit(&ci, s->repo,
7493 id);
7494 if (err) {
7495 free(id);
7496 return err;
7498 t = got_object_commit_get_committer_time(ci);
7499 got_object_commit_close(ci);
7500 } else {
7501 t = got_object_tag_get_tagger_time(tag);
7502 got_object_tag_close(tag);
7504 free(id);
7505 if (gmtime_r(&t, &tm) == NULL)
7506 return got_error_from_errno("gmtime_r");
7507 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7508 return got_error(GOT_ERR_NO_SPACE);
7510 if (got_ref_is_symbolic(re->ref)) {
7511 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7512 ymd : "", got_ref_get_name(re->ref),
7513 got_ref_get_symref_target(re->ref)) == -1)
7514 return got_error_from_errno("asprintf");
7515 } else if (s->show_ids) {
7516 struct got_object_id *id;
7517 char *id_str;
7518 err = got_ref_resolve(&id, s->repo, re->ref);
7519 if (err)
7520 return err;
7521 err = got_object_id_str(&id_str, id);
7522 if (err) {
7523 free(id);
7524 return err;
7526 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7527 got_ref_get_name(re->ref), id_str) == -1) {
7528 err = got_error_from_errno("asprintf");
7529 free(id);
7530 free(id_str);
7531 return err;
7533 free(id);
7534 free(id_str);
7535 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7536 got_ref_get_name(re->ref)) == -1)
7537 return got_error_from_errno("asprintf");
7539 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7540 0, 0);
7541 if (err) {
7542 free(line);
7543 return err;
7545 if (n == s->selected) {
7546 if (view->focussed)
7547 wstandout(view->window);
7548 s->selected_entry = re;
7550 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7551 if (tc)
7552 wattr_on(view->window,
7553 COLOR_PAIR(tc->colorpair), NULL);
7554 waddwstr(view->window, wline);
7555 if (tc)
7556 wattr_off(view->window,
7557 COLOR_PAIR(tc->colorpair), NULL);
7558 if (width < view->ncols - 1)
7559 waddch(view->window, '\n');
7560 if (n == s->selected && view->focussed)
7561 wstandend(view->window);
7562 free(line);
7563 free(wline);
7564 wline = NULL;
7565 n++;
7566 s->ndisplayed++;
7567 s->last_displayed_entry = re;
7569 limit--;
7570 re = TAILQ_NEXT(re, entry);
7573 view_border(view);
7574 return err;
7577 static const struct got_error *
7578 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7579 struct tog_reflist_entry *re, struct got_repository *repo)
7581 const struct got_error *err = NULL;
7582 struct got_object_id *commit_id = NULL;
7583 struct tog_view *tree_view;
7585 *new_view = NULL;
7587 err = resolve_reflist_entry(&commit_id, re, repo);
7588 if (err) {
7589 if (err->code != GOT_ERR_OBJ_TYPE)
7590 return err;
7591 else
7592 return NULL;
7596 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7597 if (tree_view == NULL) {
7598 err = got_error_from_errno("view_open");
7599 goto done;
7602 err = open_tree_view(tree_view, commit_id,
7603 got_ref_get_name(re->ref), repo);
7604 if (err)
7605 goto done;
7607 *new_view = tree_view;
7608 done:
7609 free(commit_id);
7610 return err;
7612 static const struct got_error *
7613 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7615 const struct got_error *err = NULL;
7616 struct tog_ref_view_state *s = &view->state.ref;
7617 struct tog_view *log_view, *tree_view;
7618 struct tog_reflist_entry *re;
7619 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 1;
7621 switch (ch) {
7622 case 'i':
7623 s->show_ids = !s->show_ids;
7624 view->count = 0;
7625 break;
7626 case 'm':
7627 s->show_date = !s->show_date;
7628 view->count = 0;
7629 break;
7630 case 'o':
7631 s->sort_by_date = !s->sort_by_date;
7632 view->count = 0;
7633 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7634 got_ref_cmp_by_commit_timestamp_descending :
7635 tog_ref_cmp_by_name, s->repo);
7636 if (err)
7637 break;
7638 got_reflist_object_id_map_free(tog_refs_idmap);
7639 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7640 &tog_refs, s->repo);
7641 if (err)
7642 break;
7643 ref_view_free_refs(s);
7644 err = ref_view_load_refs(s);
7645 break;
7646 case KEY_ENTER:
7647 case '\r':
7648 view->count = 0;
7649 if (!s->selected_entry)
7650 break;
7651 if (view_is_parent_view(view))
7652 view_get_split(view, &begin_y, &begin_x);
7654 err = log_ref_entry(&log_view, begin_y, begin_x,
7655 s->selected_entry, s->repo);
7656 if (err)
7657 break;
7659 if (view_is_parent_view(view) &&
7660 view->mode == TOG_VIEW_SPLIT_HRZN) {
7661 err = view_init_hsplit(view, begin_y);
7662 if (err)
7663 break;
7666 view->focussed = 0;
7667 log_view->focussed = 1;
7668 log_view->mode = view->mode;
7669 log_view->nlines = view->lines - begin_y;
7670 if (view_is_parent_view(view)) {
7671 view_transfer_size(log_view, view);
7672 err = view_close_child(view);
7673 if (err)
7674 return err;
7675 err = view_set_child(view, log_view);
7676 if (err)
7677 return err;
7678 view->focus_child = 1;
7679 } else
7680 *new_view = log_view;
7681 break;
7682 case 't':
7683 view->count = 0;
7684 if (!s->selected_entry)
7685 break;
7686 if (view_is_parent_view(view))
7687 view_get_split(view, &begin_y, &begin_x);
7688 err = browse_ref_tree(&tree_view, begin_y, begin_x,
7689 s->selected_entry, s->repo);
7690 if (err || tree_view == NULL)
7691 break;
7692 if (view_is_parent_view(view) &&
7693 view->mode == TOG_VIEW_SPLIT_HRZN) {
7694 err = view_init_hsplit(view, begin_y);
7695 if (err)
7696 break;
7698 view->focussed = 0;
7699 tree_view->focussed = 1;
7700 tree_view->mode = view->mode;
7701 tree_view->nlines = view->lines - begin_y;
7702 if (view_is_parent_view(view)) {
7703 view_transfer_size(tree_view, view);
7704 err = view_close_child(view);
7705 if (err)
7706 return err;
7707 err = view_set_child(view, tree_view);
7708 if (err)
7709 return err;
7710 view->focus_child = 1;
7711 } else
7712 *new_view = tree_view;
7713 break;
7714 case 'g':
7715 case KEY_HOME:
7716 s->selected = 0;
7717 view->count = 0;
7718 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7719 break;
7720 case 'G':
7721 case KEY_END: {
7722 int eos = view->nlines - 1;
7724 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7725 --eos; /* border */
7726 s->selected = 0;
7727 view->count = 0;
7728 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7729 for (n = 0; n < eos; n++) {
7730 if (re == NULL)
7731 break;
7732 s->first_displayed_entry = re;
7733 re = TAILQ_PREV(re, tog_reflist_head, entry);
7735 if (n > 0)
7736 s->selected = n - 1;
7737 break;
7739 case 'k':
7740 case KEY_UP:
7741 case CTRL('p'):
7742 if (s->selected > 0) {
7743 s->selected--;
7744 break;
7746 ref_scroll_up(s, 1);
7747 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7748 view->count = 0;
7749 break;
7750 case CTRL('u'):
7751 case 'u':
7752 nscroll /= 2;
7753 /* FALL THROUGH */
7754 case KEY_PPAGE:
7755 case CTRL('b'):
7756 case 'b':
7757 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7758 s->selected -= MIN(nscroll, s->selected);
7759 ref_scroll_up(s, MAX(0, nscroll));
7760 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7761 view->count = 0;
7762 break;
7763 case 'j':
7764 case KEY_DOWN:
7765 case CTRL('n'):
7766 if (s->selected < s->ndisplayed - 1) {
7767 s->selected++;
7768 break;
7770 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7771 /* can't scroll any further */
7772 view->count = 0;
7773 break;
7775 ref_scroll_down(view, 1);
7776 break;
7777 case CTRL('d'):
7778 case 'd':
7779 nscroll /= 2;
7780 /* FALL THROUGH */
7781 case KEY_NPAGE:
7782 case CTRL('f'):
7783 case 'f':
7784 case ' ':
7785 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7786 /* can't scroll any further; move cursor down */
7787 if (s->selected < s->ndisplayed - 1)
7788 s->selected += MIN(nscroll,
7789 s->ndisplayed - s->selected - 1);
7790 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7791 s->selected += s->ndisplayed - s->selected - 1;
7792 view->count = 0;
7793 break;
7795 ref_scroll_down(view, nscroll);
7796 break;
7797 case CTRL('l'):
7798 view->count = 0;
7799 tog_free_refs();
7800 err = tog_load_refs(s->repo, s->sort_by_date);
7801 if (err)
7802 break;
7803 ref_view_free_refs(s);
7804 err = ref_view_load_refs(s);
7805 break;
7806 case KEY_RESIZE:
7807 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7808 s->selected = view->nlines - 2;
7809 break;
7810 default:
7811 view->count = 0;
7812 break;
7815 return err;
7818 __dead static void
7819 usage_ref(void)
7821 endwin();
7822 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7823 getprogname());
7824 exit(1);
7827 static const struct got_error *
7828 cmd_ref(int argc, char *argv[])
7830 const struct got_error *error;
7831 struct got_repository *repo = NULL;
7832 struct got_worktree *worktree = NULL;
7833 char *cwd = NULL, *repo_path = NULL;
7834 int ch;
7835 struct tog_view *view;
7836 int *pack_fds = NULL;
7838 while ((ch = getopt(argc, argv, "r:")) != -1) {
7839 switch (ch) {
7840 case 'r':
7841 repo_path = realpath(optarg, NULL);
7842 if (repo_path == NULL)
7843 return got_error_from_errno2("realpath",
7844 optarg);
7845 break;
7846 default:
7847 usage_ref();
7848 /* NOTREACHED */
7852 argc -= optind;
7853 argv += optind;
7855 if (argc > 1)
7856 usage_ref();
7858 error = got_repo_pack_fds_open(&pack_fds);
7859 if (error != NULL)
7860 goto done;
7862 if (repo_path == NULL) {
7863 cwd = getcwd(NULL, 0);
7864 if (cwd == NULL)
7865 return got_error_from_errno("getcwd");
7866 error = got_worktree_open(&worktree, cwd);
7867 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7868 goto done;
7869 if (worktree)
7870 repo_path =
7871 strdup(got_worktree_get_repo_path(worktree));
7872 else
7873 repo_path = strdup(cwd);
7874 if (repo_path == NULL) {
7875 error = got_error_from_errno("strdup");
7876 goto done;
7880 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7881 if (error != NULL)
7882 goto done;
7884 init_curses();
7886 error = apply_unveil(got_repo_get_path(repo), NULL);
7887 if (error)
7888 goto done;
7890 error = tog_load_refs(repo, 0);
7891 if (error)
7892 goto done;
7894 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7895 if (view == NULL) {
7896 error = got_error_from_errno("view_open");
7897 goto done;
7900 error = open_ref_view(view, repo);
7901 if (error)
7902 goto done;
7904 if (worktree) {
7905 /* Release work tree lock. */
7906 got_worktree_close(worktree);
7907 worktree = NULL;
7909 error = view_loop(view);
7910 done:
7911 free(repo_path);
7912 free(cwd);
7913 if (repo) {
7914 const struct got_error *close_err = got_repo_close(repo);
7915 if (close_err)
7916 error = close_err;
7918 if (pack_fds) {
7919 const struct got_error *pack_err =
7920 got_repo_pack_fds_close(pack_fds);
7921 if (error == NULL)
7922 error = pack_err;
7924 tog_free_refs();
7925 return error;
7929 * If view was scrolled down to move the selected line into view when opening a
7930 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7932 static void
7933 offset_selection_up(struct tog_view *view)
7935 switch (view->type) {
7936 case TOG_VIEW_BLAME: {
7937 struct tog_blame_view_state *s = &view->state.blame;
7938 if (s->first_displayed_line == 1) {
7939 s->selected_line = MAX(s->selected_line - view->offset,
7940 1);
7941 break;
7943 if (s->first_displayed_line > view->offset)
7944 s->first_displayed_line -= view->offset;
7945 else
7946 s->first_displayed_line = 1;
7947 s->selected_line += view->offset;
7948 break;
7950 case TOG_VIEW_LOG:
7951 log_scroll_up(&view->state.log, view->offset);
7952 view->state.log.selected += view->offset;
7953 break;
7954 case TOG_VIEW_REF:
7955 ref_scroll_up(&view->state.ref, view->offset);
7956 view->state.ref.selected += view->offset;
7957 break;
7958 case TOG_VIEW_TREE:
7959 tree_scroll_up(&view->state.tree, view->offset);
7960 view->state.tree.selected += view->offset;
7961 break;
7962 default:
7963 break;
7966 view->offset = 0;
7970 * If the selected line is in the section of screen covered by the bottom split,
7971 * scroll down offset lines to move it into view and index its new position.
7973 static const struct got_error *
7974 offset_selection_down(struct tog_view *view)
7976 const struct got_error *err = NULL;
7977 const struct got_error *(*scrolld)(struct tog_view *, int);
7978 int *selected = NULL;
7979 int header, offset;
7981 switch (view->type) {
7982 case TOG_VIEW_BLAME: {
7983 struct tog_blame_view_state *s = &view->state.blame;
7984 header = 3;
7985 scrolld = NULL;
7986 if (s->selected_line > view->nlines - header) {
7987 offset = abs(view->nlines - s->selected_line - header);
7988 s->first_displayed_line += offset;
7989 s->selected_line -= offset;
7990 view->offset = offset;
7992 break;
7994 case TOG_VIEW_LOG: {
7995 struct tog_log_view_state *s = &view->state.log;
7996 scrolld = &log_scroll_down;
7997 header = view_is_parent_view(view) ? 3 : 2;
7998 selected = &s->selected;
7999 break;
8001 case TOG_VIEW_REF: {
8002 struct tog_ref_view_state *s = &view->state.ref;
8003 scrolld = &ref_scroll_down;
8004 header = 3;
8005 selected = &s->selected;
8006 break;
8008 case TOG_VIEW_TREE: {
8009 struct tog_tree_view_state *s = &view->state.tree;
8010 scrolld = &tree_scroll_down;
8011 header = 5;
8012 selected = &s->selected;
8013 break;
8015 default:
8016 selected = NULL;
8017 scrolld = NULL;
8018 header = 0;
8019 break;
8022 if (selected && *selected > view->nlines - header) {
8023 offset = abs(view->nlines - *selected - header);
8024 view->offset = offset;
8025 if (scrolld && offset) {
8026 err = scrolld(view, offset);
8027 *selected -= offset;
8031 return err;
8034 static void
8035 list_commands(FILE *fp)
8037 size_t i;
8039 fprintf(fp, "commands:");
8040 for (i = 0; i < nitems(tog_commands); i++) {
8041 const struct tog_cmd *cmd = &tog_commands[i];
8042 fprintf(fp, " %s", cmd->name);
8044 fputc('\n', fp);
8047 __dead static void
8048 usage(int hflag, int status)
8050 FILE *fp = (status == 0) ? stdout : stderr;
8052 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8053 getprogname());
8054 if (hflag) {
8055 fprintf(fp, "lazy usage: %s path\n", getprogname());
8056 list_commands(fp);
8058 exit(status);
8061 static char **
8062 make_argv(int argc, ...)
8064 va_list ap;
8065 char **argv;
8066 int i;
8068 va_start(ap, argc);
8070 argv = calloc(argc, sizeof(char *));
8071 if (argv == NULL)
8072 err(1, "calloc");
8073 for (i = 0; i < argc; i++) {
8074 argv[i] = strdup(va_arg(ap, char *));
8075 if (argv[i] == NULL)
8076 err(1, "strdup");
8079 va_end(ap);
8080 return argv;
8084 * Try to convert 'tog path' into a 'tog log path' command.
8085 * The user could simply have mistyped the command rather than knowingly
8086 * provided a path. So check whether argv[0] can in fact be resolved
8087 * to a path in the HEAD commit and print a special error if not.
8088 * This hack is for mpi@ <3
8090 static const struct got_error *
8091 tog_log_with_path(int argc, char *argv[])
8093 const struct got_error *error = NULL, *close_err;
8094 const struct tog_cmd *cmd = NULL;
8095 struct got_repository *repo = NULL;
8096 struct got_worktree *worktree = NULL;
8097 struct got_object_id *commit_id = NULL, *id = NULL;
8098 struct got_commit_object *commit = NULL;
8099 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8100 char *commit_id_str = NULL, **cmd_argv = NULL;
8101 int *pack_fds = NULL;
8103 cwd = getcwd(NULL, 0);
8104 if (cwd == NULL)
8105 return got_error_from_errno("getcwd");
8107 error = got_repo_pack_fds_open(&pack_fds);
8108 if (error != NULL)
8109 goto done;
8111 error = got_worktree_open(&worktree, cwd);
8112 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8113 goto done;
8115 if (worktree)
8116 repo_path = strdup(got_worktree_get_repo_path(worktree));
8117 else
8118 repo_path = strdup(cwd);
8119 if (repo_path == NULL) {
8120 error = got_error_from_errno("strdup");
8121 goto done;
8124 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8125 if (error != NULL)
8126 goto done;
8128 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8129 repo, worktree);
8130 if (error)
8131 goto done;
8133 error = tog_load_refs(repo, 0);
8134 if (error)
8135 goto done;
8136 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8137 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8138 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8139 if (error)
8140 goto done;
8142 if (worktree) {
8143 got_worktree_close(worktree);
8144 worktree = NULL;
8147 error = got_object_open_as_commit(&commit, repo, commit_id);
8148 if (error)
8149 goto done;
8151 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8152 if (error) {
8153 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8154 goto done;
8155 fprintf(stderr, "%s: '%s' is no known command or path\n",
8156 getprogname(), argv[0]);
8157 usage(1, 1);
8158 /* not reached */
8161 close_err = got_repo_close(repo);
8162 if (error == NULL)
8163 error = close_err;
8164 repo = NULL;
8166 error = got_object_id_str(&commit_id_str, commit_id);
8167 if (error)
8168 goto done;
8170 cmd = &tog_commands[0]; /* log */
8171 argc = 4;
8172 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8173 error = cmd->cmd_main(argc, cmd_argv);
8174 done:
8175 if (repo) {
8176 close_err = got_repo_close(repo);
8177 if (error == NULL)
8178 error = close_err;
8180 if (commit)
8181 got_object_commit_close(commit);
8182 if (worktree)
8183 got_worktree_close(worktree);
8184 if (pack_fds) {
8185 const struct got_error *pack_err =
8186 got_repo_pack_fds_close(pack_fds);
8187 if (error == NULL)
8188 error = pack_err;
8190 free(id);
8191 free(commit_id_str);
8192 free(commit_id);
8193 free(cwd);
8194 free(repo_path);
8195 free(in_repo_path);
8196 if (cmd_argv) {
8197 int i;
8198 for (i = 0; i < argc; i++)
8199 free(cmd_argv[i]);
8200 free(cmd_argv);
8202 tog_free_refs();
8203 return error;
8206 int
8207 main(int argc, char *argv[])
8209 const struct got_error *error = NULL;
8210 const struct tog_cmd *cmd = NULL;
8211 int ch, hflag = 0, Vflag = 0;
8212 char **cmd_argv = NULL;
8213 static const struct option longopts[] = {
8214 { "version", no_argument, NULL, 'V' },
8215 { NULL, 0, NULL, 0}
8217 char *diff_algo_str = NULL;
8219 setlocale(LC_CTYPE, "");
8221 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8222 switch (ch) {
8223 case 'h':
8224 hflag = 1;
8225 break;
8226 case 'V':
8227 Vflag = 1;
8228 break;
8229 default:
8230 usage(hflag, 1);
8231 /* NOTREACHED */
8235 argc -= optind;
8236 argv += optind;
8237 optind = 1;
8238 optreset = 1;
8240 if (Vflag) {
8241 got_version_print_str();
8242 return 0;
8245 #ifndef PROFILE
8246 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8247 NULL) == -1)
8248 err(1, "pledge");
8249 #endif
8251 if (argc == 0) {
8252 if (hflag)
8253 usage(hflag, 0);
8254 /* Build an argument vector which runs a default command. */
8255 cmd = &tog_commands[0];
8256 argc = 1;
8257 cmd_argv = make_argv(argc, cmd->name);
8258 } else {
8259 size_t i;
8261 /* Did the user specify a command? */
8262 for (i = 0; i < nitems(tog_commands); i++) {
8263 if (strncmp(tog_commands[i].name, argv[0],
8264 strlen(argv[0])) == 0) {
8265 cmd = &tog_commands[i];
8266 break;
8271 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8272 if (diff_algo_str) {
8273 if (strcasecmp(diff_algo_str, "patience") == 0)
8274 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8275 if (strcasecmp(diff_algo_str, "myers") == 0)
8276 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8279 if (cmd == NULL) {
8280 if (argc != 1)
8281 usage(0, 1);
8282 /* No command specified; try log with a path */
8283 error = tog_log_with_path(argc, argv);
8284 } else {
8285 if (hflag)
8286 cmd->cmd_usage();
8287 else
8288 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8291 endwin();
8292 putchar('\n');
8293 if (cmd_argv) {
8294 int i;
8295 for (i = 0; i < argc; i++)
8296 free(cmd_argv[i]);
8297 free(cmd_argv);
8300 if (error && error->code != GOT_ERR_CANCELLED)
8301 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8302 return 0;