Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #if defined(__FreeBSD__) || defined(__APPLE__)
24 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
25 #endif
26 #include <curses.h>
27 #include <panel.h>
28 #include <locale.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_compat.h"
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 };
113 enum tog_view_mode {
114 TOG_VIEW_SPLIT_NONE,
115 TOG_VIEW_SPLIT_VERT,
116 TOG_VIEW_SPLIT_HRZN
117 };
119 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
121 #define TOG_EOF_STRING "(END)"
123 struct commit_queue_entry {
124 TAILQ_ENTRY(commit_queue_entry) entry;
125 struct got_object_id *id;
126 struct got_commit_object *commit;
127 int idx;
128 };
129 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
130 struct commit_queue {
131 int ncommits;
132 struct commit_queue_head head;
133 };
135 struct tog_color {
136 STAILQ_ENTRY(tog_color) entry;
137 regex_t regex;
138 short colorpair;
139 };
140 STAILQ_HEAD(tog_colors, tog_color);
142 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
143 static struct got_reflist_object_id_map *tog_refs_idmap;
144 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
146 static const struct got_error *
147 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
148 struct got_reference* re2)
150 const char *name1 = got_ref_get_name(re1);
151 const char *name2 = got_ref_get_name(re2);
152 int isbackup1, isbackup2;
154 /* Sort backup refs towards the bottom of the list. */
155 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
156 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
157 if (!isbackup1 && isbackup2) {
158 *cmp = -1;
159 return NULL;
160 } else if (isbackup1 && !isbackup2) {
161 *cmp = 1;
162 return NULL;
165 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
166 return NULL;
169 static const struct got_error *
170 tog_load_refs(struct got_repository *repo, int sort_by_date)
172 const struct got_error *err;
174 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
175 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
176 repo);
177 if (err)
178 return err;
180 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
181 repo);
184 static void
185 tog_free_refs(void)
187 if (tog_refs_idmap) {
188 got_reflist_object_id_map_free(tog_refs_idmap);
189 tog_refs_idmap = NULL;
191 got_ref_list_free(&tog_refs);
194 static const struct got_error *
195 add_color(struct tog_colors *colors, const char *pattern,
196 int idx, short color)
198 const struct got_error *err = NULL;
199 struct tog_color *tc;
200 int regerr = 0;
202 if (idx < 1 || idx > COLOR_PAIRS - 1)
203 return NULL;
205 init_pair(idx, color, -1);
207 tc = calloc(1, sizeof(*tc));
208 if (tc == NULL)
209 return got_error_from_errno("calloc");
210 regerr = regcomp(&tc->regex, pattern,
211 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
212 if (regerr) {
213 static char regerr_msg[512];
214 static char err_msg[512];
215 regerror(regerr, &tc->regex, regerr_msg,
216 sizeof(regerr_msg));
217 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
218 regerr_msg);
219 err = got_error_msg(GOT_ERR_REGEX, err_msg);
220 free(tc);
221 return err;
223 tc->colorpair = idx;
224 STAILQ_INSERT_HEAD(colors, tc, entry);
225 return NULL;
228 static void
229 free_colors(struct tog_colors *colors)
231 struct tog_color *tc;
233 while (!STAILQ_EMPTY(colors)) {
234 tc = STAILQ_FIRST(colors);
235 STAILQ_REMOVE_HEAD(colors, entry);
236 regfree(&tc->regex);
237 free(tc);
241 static struct tog_color *
242 get_color(struct tog_colors *colors, int colorpair)
244 struct tog_color *tc = NULL;
246 STAILQ_FOREACH(tc, colors, entry) {
247 if (tc->colorpair == colorpair)
248 return tc;
251 return NULL;
254 static int
255 default_color_value(const char *envvar)
257 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
258 return COLOR_MAGENTA;
259 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
260 return COLOR_CYAN;
261 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
262 return COLOR_YELLOW;
263 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
264 return COLOR_GREEN;
265 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
266 return COLOR_MAGENTA;
267 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
268 return COLOR_MAGENTA;
269 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
270 return COLOR_CYAN;
271 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
272 return COLOR_GREEN;
273 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
274 return COLOR_GREEN;
275 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
276 return COLOR_CYAN;
277 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
278 return COLOR_YELLOW;
279 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
280 return COLOR_GREEN;
281 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
282 return COLOR_MAGENTA;
283 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
284 return COLOR_YELLOW;
285 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
286 return COLOR_CYAN;
288 return -1;
291 static int
292 get_color_value(const char *envvar)
294 const char *val = getenv(envvar);
296 if (val == NULL)
297 return default_color_value(envvar);
299 if (strcasecmp(val, "black") == 0)
300 return COLOR_BLACK;
301 if (strcasecmp(val, "red") == 0)
302 return COLOR_RED;
303 if (strcasecmp(val, "green") == 0)
304 return COLOR_GREEN;
305 if (strcasecmp(val, "yellow") == 0)
306 return COLOR_YELLOW;
307 if (strcasecmp(val, "blue") == 0)
308 return COLOR_BLUE;
309 if (strcasecmp(val, "magenta") == 0)
310 return COLOR_MAGENTA;
311 if (strcasecmp(val, "cyan") == 0)
312 return COLOR_CYAN;
313 if (strcasecmp(val, "white") == 0)
314 return COLOR_WHITE;
315 if (strcasecmp(val, "default") == 0)
316 return -1;
318 return default_color_value(envvar);
322 struct tog_diff_view_state {
323 struct got_object_id *id1, *id2;
324 const char *label1, *label2;
325 FILE *f, *f1, *f2;
326 int fd1, fd2;
327 int first_displayed_line;
328 int last_displayed_line;
329 int eof;
330 int diff_context;
331 int ignore_whitespace;
332 int force_text_diff;
333 struct got_repository *repo;
334 struct tog_colors colors;
335 size_t nlines;
336 off_t *line_offsets;
337 int matched_line;
338 int selected_line;
340 /* passed from log or blame view; may be NULL */
341 struct tog_view *parent_view;
342 };
344 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
345 static volatile sig_atomic_t tog_thread_error;
347 struct tog_log_thread_args {
348 pthread_cond_t need_commits;
349 pthread_cond_t commit_loaded;
350 int commits_needed;
351 int load_all;
352 struct got_commit_graph *graph;
353 struct commit_queue *commits;
354 const char *in_repo_path;
355 struct got_object_id *start_id;
356 struct got_repository *repo;
357 int *pack_fds;
358 int log_complete;
359 sig_atomic_t *quit;
360 struct commit_queue_entry **first_displayed_entry;
361 struct commit_queue_entry **selected_entry;
362 int *searching;
363 int *search_next_done;
364 regex_t *regex;
365 };
367 struct tog_log_view_state {
368 struct commit_queue commits;
369 struct commit_queue_entry *first_displayed_entry;
370 struct commit_queue_entry *last_displayed_entry;
371 struct commit_queue_entry *selected_entry;
372 int selected;
373 char *in_repo_path;
374 char *head_ref_name;
375 int log_branches;
376 struct got_repository *repo;
377 struct got_object_id *start_id;
378 sig_atomic_t quit;
379 pthread_t thread;
380 struct tog_log_thread_args thread_args;
381 struct commit_queue_entry *matched_entry;
382 struct commit_queue_entry *search_entry;
383 struct tog_colors colors;
384 };
386 #define TOG_COLOR_DIFF_MINUS 1
387 #define TOG_COLOR_DIFF_PLUS 2
388 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
389 #define TOG_COLOR_DIFF_META 4
390 #define TOG_COLOR_TREE_SUBMODULE 5
391 #define TOG_COLOR_TREE_SYMLINK 6
392 #define TOG_COLOR_TREE_DIRECTORY 7
393 #define TOG_COLOR_TREE_EXECUTABLE 8
394 #define TOG_COLOR_COMMIT 9
395 #define TOG_COLOR_AUTHOR 10
396 #define TOG_COLOR_DATE 11
397 #define TOG_COLOR_REFS_HEADS 12
398 #define TOG_COLOR_REFS_TAGS 13
399 #define TOG_COLOR_REFS_REMOTES 14
400 #define TOG_COLOR_REFS_BACKUP 15
402 struct tog_blame_cb_args {
403 struct tog_blame_line *lines; /* one per line */
404 int nlines;
406 struct tog_view *view;
407 struct got_object_id *commit_id;
408 int *quit;
409 };
411 struct tog_blame_thread_args {
412 const char *path;
413 struct got_repository *repo;
414 struct tog_blame_cb_args *cb_args;
415 int *complete;
416 got_cancel_cb cancel_cb;
417 void *cancel_arg;
418 };
420 struct tog_blame {
421 FILE *f;
422 off_t filesize;
423 struct tog_blame_line *lines;
424 int nlines;
425 off_t *line_offsets;
426 pthread_t thread;
427 struct tog_blame_thread_args thread_args;
428 struct tog_blame_cb_args cb_args;
429 const char *path;
430 int *pack_fds;
431 };
433 struct tog_blame_view_state {
434 int first_displayed_line;
435 int last_displayed_line;
436 int selected_line;
437 int last_diffed_line;
438 int blame_complete;
439 int eof;
440 int done;
441 struct got_object_id_queue blamed_commits;
442 struct got_object_qid *blamed_commit;
443 char *path;
444 struct got_repository *repo;
445 struct got_object_id *commit_id;
446 struct tog_blame blame;
447 int matched_line;
448 struct tog_colors colors;
449 };
451 struct tog_parent_tree {
452 TAILQ_ENTRY(tog_parent_tree) entry;
453 struct got_tree_object *tree;
454 struct got_tree_entry *first_displayed_entry;
455 struct got_tree_entry *selected_entry;
456 int selected;
457 };
459 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
461 struct tog_tree_view_state {
462 char *tree_label;
463 struct got_object_id *commit_id;/* commit which this tree belongs to */
464 struct got_tree_object *root; /* the commit's root tree entry */
465 struct got_tree_object *tree; /* currently displayed (sub-)tree */
466 struct got_tree_entry *first_displayed_entry;
467 struct got_tree_entry *last_displayed_entry;
468 struct got_tree_entry *selected_entry;
469 int ndisplayed, selected, show_ids;
470 struct tog_parent_trees parents; /* parent trees of current sub-tree */
471 char *head_ref_name;
472 struct got_repository *repo;
473 struct got_tree_entry *matched_entry;
474 struct tog_colors colors;
475 };
477 struct tog_reflist_entry {
478 TAILQ_ENTRY(tog_reflist_entry) entry;
479 struct got_reference *ref;
480 int idx;
481 };
483 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
485 struct tog_ref_view_state {
486 struct tog_reflist_head refs;
487 struct tog_reflist_entry *first_displayed_entry;
488 struct tog_reflist_entry *last_displayed_entry;
489 struct tog_reflist_entry *selected_entry;
490 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
491 struct got_repository *repo;
492 struct tog_reflist_entry *matched_entry;
493 struct tog_colors colors;
494 };
496 /*
497 * We implement two types of views: parent views and child views.
499 * The 'Tab' key switches focus between a parent view and its child view.
500 * Child views are shown side-by-side to their parent view, provided
501 * there is enough screen estate.
503 * When a new view is opened from within a parent view, this new view
504 * becomes a child view of the parent view, replacing any existing child.
506 * When a new view is opened from within a child view, this new view
507 * becomes a parent view which will obscure the views below until the
508 * user quits the new parent view by typing 'q'.
510 * This list of views contains parent views only.
511 * Child views are only pointed to by their parent view.
512 */
513 TAILQ_HEAD(tog_view_list_head, tog_view);
515 struct tog_view {
516 TAILQ_ENTRY(tog_view) entry;
517 WINDOW *window;
518 PANEL *panel;
519 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
520 int resized_y, resized_x; /* begin_y/x based on user resizing */
521 int maxx, x; /* max column and current start column */
522 int lines, cols; /* copies of LINES and COLS */
523 int nscrolled, offset; /* lines scrolled and hsplit line offset */
524 int ch, count; /* current keymap and count prefix */
525 int resized; /* set when in a resize event */
526 int focussed; /* Only set on one parent or child view at a time. */
527 int dying;
528 struct tog_view *parent;
529 struct tog_view *child;
531 /*
532 * This flag is initially set on parent views when a new child view
533 * is created. It gets toggled when the 'Tab' key switches focus
534 * between parent and child.
535 * The flag indicates whether focus should be passed on to our child
536 * view if this parent view gets picked for focus after another parent
537 * view was closed. This prevents child views from losing focus in such
538 * situations.
539 */
540 int focus_child;
542 enum tog_view_mode mode;
543 /* type-specific state */
544 enum tog_view_type type;
545 union {
546 struct tog_diff_view_state diff;
547 struct tog_log_view_state log;
548 struct tog_blame_view_state blame;
549 struct tog_tree_view_state tree;
550 struct tog_ref_view_state ref;
551 } state;
553 const struct got_error *(*show)(struct tog_view *);
554 const struct got_error *(*input)(struct tog_view **,
555 struct tog_view *, int);
556 const struct got_error *(*reset)(struct tog_view *);
557 const struct got_error *(*resize)(struct tog_view *, int);
558 const struct got_error *(*close)(struct tog_view *);
560 const struct got_error *(*search_start)(struct tog_view *);
561 const struct got_error *(*search_next)(struct tog_view *);
562 int search_started;
563 int searching;
564 #define TOG_SEARCH_FORWARD 1
565 #define TOG_SEARCH_BACKWARD 2
566 int search_next_done;
567 #define TOG_SEARCH_HAVE_MORE 1
568 #define TOG_SEARCH_NO_MORE 2
569 #define TOG_SEARCH_HAVE_NONE 3
570 regex_t regex;
571 regmatch_t regmatch;
572 };
574 static const struct got_error *open_diff_view(struct tog_view *,
575 struct got_object_id *, struct got_object_id *,
576 const char *, const char *, int, int, int, struct tog_view *,
577 struct got_repository *);
578 static const struct got_error *show_diff_view(struct tog_view *);
579 static const struct got_error *input_diff_view(struct tog_view **,
580 struct tog_view *, int);
581 static const struct got_error *reset_diff_view(struct tog_view *);
582 static const struct got_error* close_diff_view(struct tog_view *);
583 static const struct got_error *search_start_diff_view(struct tog_view *);
584 static const struct got_error *search_next_diff_view(struct tog_view *);
586 static const struct got_error *open_log_view(struct tog_view *,
587 struct got_object_id *, struct got_repository *,
588 const char *, const char *, int);
589 static const struct got_error * show_log_view(struct tog_view *);
590 static const struct got_error *input_log_view(struct tog_view **,
591 struct tog_view *, int);
592 static const struct got_error *resize_log_view(struct tog_view *, int);
593 static const struct got_error *close_log_view(struct tog_view *);
594 static const struct got_error *search_start_log_view(struct tog_view *);
595 static const struct got_error *search_next_log_view(struct tog_view *);
597 static const struct got_error *open_blame_view(struct tog_view *, char *,
598 struct got_object_id *, struct got_repository *);
599 static const struct got_error *show_blame_view(struct tog_view *);
600 static const struct got_error *input_blame_view(struct tog_view **,
601 struct tog_view *, int);
602 static const struct got_error *reset_blame_view(struct tog_view *);
603 static const struct got_error *close_blame_view(struct tog_view *);
604 static const struct got_error *search_start_blame_view(struct tog_view *);
605 static const struct got_error *search_next_blame_view(struct tog_view *);
607 static const struct got_error *open_tree_view(struct tog_view *,
608 struct got_object_id *, const char *, struct got_repository *);
609 static const struct got_error *show_tree_view(struct tog_view *);
610 static const struct got_error *input_tree_view(struct tog_view **,
611 struct tog_view *, int);
612 static const struct got_error *close_tree_view(struct tog_view *);
613 static const struct got_error *search_start_tree_view(struct tog_view *);
614 static const struct got_error *search_next_tree_view(struct tog_view *);
616 static const struct got_error *open_ref_view(struct tog_view *,
617 struct got_repository *);
618 static const struct got_error *show_ref_view(struct tog_view *);
619 static const struct got_error *input_ref_view(struct tog_view **,
620 struct tog_view *, int);
621 static const struct got_error *close_ref_view(struct tog_view *);
622 static const struct got_error *search_start_ref_view(struct tog_view *);
623 static const struct got_error *search_next_ref_view(struct tog_view *);
625 static volatile sig_atomic_t tog_sigwinch_received;
626 static volatile sig_atomic_t tog_sigpipe_received;
627 static volatile sig_atomic_t tog_sigcont_received;
628 static volatile sig_atomic_t tog_sigint_received;
629 static volatile sig_atomic_t tog_sigterm_received;
631 static void
632 tog_sigwinch(int signo)
634 tog_sigwinch_received = 1;
637 static void
638 tog_sigpipe(int signo)
640 tog_sigpipe_received = 1;
643 static void
644 tog_sigcont(int signo)
646 tog_sigcont_received = 1;
649 static void
650 tog_sigint(int signo)
652 tog_sigint_received = 1;
655 static void
656 tog_sigterm(int signo)
658 tog_sigterm_received = 1;
661 static int
662 tog_fatal_signal_received(void)
664 return (tog_sigpipe_received ||
665 tog_sigint_received || tog_sigint_received);
668 static const struct got_error *
669 view_close(struct tog_view *view)
671 const struct got_error *err = NULL, *child_err = NULL;
673 if (view->child) {
674 child_err = view_close(view->child);
675 view->child = NULL;
677 if (view->close)
678 err = view->close(view);
679 if (view->panel)
680 del_panel(view->panel);
681 if (view->window)
682 delwin(view->window);
683 free(view);
684 return err ? err : child_err;
687 static struct tog_view *
688 view_open(int nlines, int ncols, int begin_y, int begin_x,
689 enum tog_view_type type)
691 struct tog_view *view = calloc(1, sizeof(*view));
693 if (view == NULL)
694 return NULL;
696 view->type = type;
697 view->lines = LINES;
698 view->cols = COLS;
699 view->nlines = nlines ? nlines : LINES - begin_y;
700 view->ncols = ncols ? ncols : COLS - begin_x;
701 view->begin_y = begin_y;
702 view->begin_x = begin_x;
703 view->window = newwin(nlines, ncols, begin_y, begin_x);
704 if (view->window == NULL) {
705 view_close(view);
706 return NULL;
708 view->panel = new_panel(view->window);
709 if (view->panel == NULL ||
710 set_panel_userptr(view->panel, view) != OK) {
711 view_close(view);
712 return NULL;
715 keypad(view->window, TRUE);
716 return view;
719 static int
720 view_split_begin_x(int begin_x)
722 if (begin_x > 0 || COLS < 120)
723 return 0;
724 return (COLS - MAX(COLS / 2, 80));
727 /* XXX Stub till we decide what to do. */
728 static int
729 view_split_begin_y(int lines)
731 return lines * HSPLIT_SCALE;
734 static const struct got_error *view_resize(struct tog_view *);
736 static const struct got_error *
737 view_splitscreen(struct tog_view *view)
739 const struct got_error *err = NULL;
741 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
742 if (view->resized_y && view->resized_y < view->lines)
743 view->begin_y = view->resized_y;
744 else
745 view->begin_y = view_split_begin_y(view->nlines);
746 view->begin_x = 0;
747 } else if (!view->resized) {
748 if (view->resized_x && view->resized_x < view->cols - 1 &&
749 view->cols > 119)
750 view->begin_x = view->resized_x;
751 else
752 view->begin_x = view_split_begin_x(0);
753 view->begin_y = 0;
755 view->nlines = LINES - view->begin_y;
756 view->ncols = COLS - view->begin_x;
757 view->lines = LINES;
758 view->cols = COLS;
759 err = view_resize(view);
760 if (err)
761 return err;
763 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
764 view->parent->nlines = view->begin_y;
766 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
767 return got_error_from_errno("mvwin");
769 return NULL;
772 static const struct got_error *
773 view_fullscreen(struct tog_view *view)
775 const struct got_error *err = NULL;
777 view->begin_x = 0;
778 view->begin_y = view->resized ? view->begin_y : 0;
779 view->nlines = view->resized ? view->nlines : LINES;
780 view->ncols = COLS;
781 view->lines = LINES;
782 view->cols = COLS;
783 err = view_resize(view);
784 if (err)
785 return err;
787 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
788 return got_error_from_errno("mvwin");
790 return NULL;
793 static int
794 view_is_parent_view(struct tog_view *view)
796 return view->parent == NULL;
799 static int
800 view_is_splitscreen(struct tog_view *view)
802 return view->begin_x > 0 || view->begin_y > 0;
805 static int
806 view_is_fullscreen(struct tog_view *view)
808 return view->nlines == LINES && view->ncols == COLS;
811 static int
812 view_is_hsplit_top(struct tog_view *view)
814 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
815 view_is_splitscreen(view->child);
818 static void
819 view_border(struct tog_view *view)
821 PANEL *panel;
822 const struct tog_view *view_above;
824 if (view->parent)
825 return view_border(view->parent);
827 panel = panel_above(view->panel);
828 if (panel == NULL)
829 return;
831 view_above = panel_userptr(panel);
832 if (view->mode == TOG_VIEW_SPLIT_HRZN)
833 mvwhline(view->window, view_above->begin_y - 1,
834 view->begin_x, got_locale_is_utf8() ?
835 ACS_HLINE : '-', view->ncols);
836 else
837 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
838 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
841 static const struct got_error *view_init_hsplit(struct tog_view *, int);
842 static const struct got_error *request_log_commits(struct tog_view *);
843 static const struct got_error *offset_selection_down(struct tog_view *);
844 static void offset_selection_up(struct tog_view *);
845 static void view_get_split(struct tog_view *, int *, int *);
847 static const struct got_error *
848 view_resize(struct tog_view *view)
850 const struct got_error *err = NULL;
851 int dif, nlines, ncols;
853 dif = LINES - view->lines; /* line difference */
855 if (view->lines > LINES)
856 nlines = view->nlines - (view->lines - LINES);
857 else
858 nlines = view->nlines + (LINES - view->lines);
859 if (view->cols > COLS)
860 ncols = view->ncols - (view->cols - COLS);
861 else
862 ncols = view->ncols + (COLS - view->cols);
864 if (view->child) {
865 int hs = view->child->begin_y;
867 if (!view_is_fullscreen(view))
868 view->child->begin_x = view_split_begin_x(view->begin_x);
869 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
870 view->child->begin_x == 0) {
871 ncols = COLS;
873 view_fullscreen(view->child);
874 if (view->child->focussed)
875 show_panel(view->child->panel);
876 else
877 show_panel(view->panel);
878 } else {
879 ncols = view->child->begin_x;
881 view_splitscreen(view->child);
882 show_panel(view->child->panel);
884 /*
885 * XXX This is ugly and needs to be moved into the above
886 * logic but "works" for now and my attempts at moving it
887 * break either 'tab' or 'F' key maps in horizontal splits.
888 */
889 if (hs) {
890 err = view_splitscreen(view->child);
891 if (err)
892 return err;
893 if (dif < 0) { /* top split decreased */
894 err = offset_selection_down(view);
895 if (err)
896 return err;
898 view_border(view);
899 update_panels();
900 doupdate();
901 show_panel(view->child->panel);
902 nlines = view->nlines;
904 } else if (view->parent == NULL)
905 ncols = COLS;
907 if (view->resize && dif > 0) {
908 err = view->resize(view, dif);
909 if (err)
910 return err;
913 if (wresize(view->window, nlines, ncols) == ERR)
914 return got_error_from_errno("wresize");
915 if (replace_panel(view->panel, view->window) == ERR)
916 return got_error_from_errno("replace_panel");
917 wclear(view->window);
919 view->nlines = nlines;
920 view->ncols = ncols;
921 view->lines = LINES;
922 view->cols = COLS;
924 return NULL;
927 static const struct got_error *
928 resize_log_view(struct tog_view *view, int increase)
930 struct tog_log_view_state *s = &view->state.log;
931 const struct got_error *err = NULL;
932 int n = s->selected_entry->idx + view->lines - s->selected;
934 /*
935 * Request commits to account for the increased
936 * height so we have enough to populate the view.
937 */
938 if (s->commits.ncommits < n) {
939 view->nscrolled = n - s->commits.ncommits + increase + 1;
940 err = request_log_commits(view);
943 return err;
946 static void
947 view_adjust_offset(struct tog_view *view, int n)
949 if (n == 0)
950 return;
952 if (view->parent && view->parent->offset) {
953 if (view->parent->offset + n >= 0)
954 view->parent->offset += n;
955 else
956 view->parent->offset = 0;
957 } else if (view->offset) {
958 if (view->offset - n >= 0)
959 view->offset -= n;
960 else
961 view->offset = 0;
965 static const struct got_error *
966 view_resize_split(struct tog_view *view, int resize)
968 const struct got_error *err = NULL;
969 struct tog_view *v = NULL;
971 if (view->parent)
972 v = view->parent;
973 else
974 v = view;
976 if (!v->child || !view_is_splitscreen(v->child))
977 return NULL;
979 v->resized = v->child->resized = resize; /* lock for resize event */
981 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
982 int y = v->child->begin_y;
984 if (v->child->resized_y)
985 v->child->begin_y = v->child->resized_y;
986 if (view->parent)
987 v->child->begin_y -= resize;
988 else
989 v->child->begin_y += resize;
990 if (v->child->begin_y < 3) {
991 view->count = 0;
992 v->child->begin_y = 3;
993 } else if (v->child->begin_y > LINES - 1) {
994 view->count = 0;
995 v->child->begin_y = LINES - 1;
997 v->ncols = COLS;
998 v->child->ncols = COLS;
999 view_adjust_offset(view, resize);
1000 err = view_init_hsplit(v, v->child->begin_y);
1001 if (err)
1002 return err;
1003 v->child->resized_y = v->child->begin_y;
1004 if (y > v->child->begin_y && v->child->type == TOG_VIEW_LOG)
1005 v->child->nscrolled = y - v->child->begin_y;
1006 else if (y < v->child->begin_y && v->type == TOG_VIEW_LOG)
1007 v->nscrolled = v->child->begin_y - y;
1008 } else {
1009 if (v->child->resized_x)
1010 v->child->begin_x = v->child->resized_x;
1011 if (view->parent)
1012 v->child->begin_x -= resize;
1013 else
1014 v->child->begin_x += resize;
1015 if (v->child->begin_x < 11) {
1016 view->count = 0;
1017 v->child->begin_x = 11;
1018 } else if (v->child->begin_x > COLS - 1) {
1019 view->count = 0;
1020 v->child->begin_x = COLS - 1;
1022 v->child->resized_x = v->child->begin_x;
1025 v->child->mode = v->mode;
1026 v->child->nlines = v->lines - v->child->begin_y;
1027 v->child->ncols = v->cols - v->child->begin_x;
1028 v->focus_child = 1;
1030 err = view_fullscreen(v);
1031 if (err)
1032 return err;
1033 err = view_splitscreen(v->child);
1034 if (err)
1035 return err;
1037 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1038 err = offset_selection_down(v->child);
1039 if (err)
1040 return err;
1043 if (v->nscrolled)
1044 err = request_log_commits(v);
1045 else if (v->child->nscrolled)
1046 err = request_log_commits(v->child);
1048 v->resized = v->child->resized = 0;
1050 return err;
1053 static void
1054 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1056 struct tog_view *v = src->child ? src->child : src;
1058 dst->resized_x = v->resized_x;
1059 dst->resized_y = v->resized_y;
1062 static const struct got_error *
1063 view_close_child(struct tog_view *view)
1065 const struct got_error *err = NULL;
1067 if (view->child == NULL)
1068 return NULL;
1070 err = view_close(view->child);
1071 view->child = NULL;
1072 return err;
1075 static const struct got_error *
1076 view_set_child(struct tog_view *view, struct tog_view *child)
1078 const struct got_error *err = NULL;
1080 view->child = child;
1081 child->parent = view;
1083 err = view_resize(view);
1084 if (err)
1085 return err;
1087 if (view->child->resized_x || view->child->resized_y)
1088 err = view_resize_split(view, 0);
1090 return err;
1093 static void
1094 tog_resizeterm(void)
1096 int cols, lines;
1097 struct winsize size;
1099 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1100 cols = 80; /* Default */
1101 lines = 24;
1102 } else {
1103 cols = size.ws_col;
1104 lines = size.ws_row;
1106 resize_term(lines, cols);
1109 static const struct got_error *
1110 view_search_start(struct tog_view *view)
1112 const struct got_error *err = NULL;
1113 struct tog_view *v = view;
1114 char pattern[1024];
1115 int ret;
1117 if (view->search_started) {
1118 regfree(&view->regex);
1119 view->searching = 0;
1120 memset(&view->regmatch, 0, sizeof(view->regmatch));
1122 view->search_started = 0;
1124 if (view->nlines < 1)
1125 return NULL;
1127 if (view_is_hsplit_top(view))
1128 v = view->child;
1130 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1131 wclrtoeol(v->window);
1133 nodelay(view->window, FALSE); /* block for search term input */
1134 nocbreak();
1135 echo();
1136 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1137 wrefresh(v->window);
1138 cbreak();
1139 noecho();
1140 nodelay(view->window, TRUE);
1141 if (ret == ERR)
1142 return NULL;
1144 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1145 err = view->search_start(view);
1146 if (err) {
1147 regfree(&view->regex);
1148 return err;
1150 view->search_started = 1;
1151 view->searching = TOG_SEARCH_FORWARD;
1152 view->search_next_done = 0;
1153 view->search_next(view);
1156 return NULL;
1159 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1160 static const struct got_error *
1161 switch_split(struct tog_view *view)
1163 const struct got_error *err = NULL;
1164 struct tog_view *v = NULL;
1166 if (view->parent)
1167 v = view->parent;
1168 else
1169 v = view;
1171 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1172 v->mode = TOG_VIEW_SPLIT_VERT;
1173 else
1174 v->mode = TOG_VIEW_SPLIT_HRZN;
1176 if (!v->child)
1177 return NULL;
1178 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1179 v->mode = TOG_VIEW_SPLIT_NONE;
1181 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1182 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1183 v->child->begin_y = v->child->resized_y;
1184 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1185 v->child->begin_x = v->child->resized_x;
1188 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1189 v->ncols = COLS;
1190 v->child->ncols = COLS;
1191 v->child->nscrolled = LINES - v->child->nlines;
1193 err = view_init_hsplit(v, v->child->begin_y);
1194 if (err)
1195 return err;
1197 v->child->mode = v->mode;
1198 v->child->nlines = v->lines - v->child->begin_y;
1199 v->focus_child = 1;
1201 err = view_fullscreen(v);
1202 if (err)
1203 return err;
1204 err = view_splitscreen(v->child);
1205 if (err)
1206 return err;
1208 if (v->mode == TOG_VIEW_SPLIT_NONE)
1209 v->mode = TOG_VIEW_SPLIT_VERT;
1210 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1211 err = offset_selection_down(v);
1212 err = offset_selection_down(v->child);
1213 } else {
1214 offset_selection_up(v);
1215 offset_selection_up(v->child);
1217 if (v->type == TOG_VIEW_LOG && v->nscrolled)
1218 err = request_log_commits(v);
1219 else if (v->child->type == TOG_VIEW_LOG && v->child->nscrolled)
1220 err = request_log_commits(v->child);
1222 return err;
1226 * Compute view->count from numeric input. Assign total to view->count and
1227 * return first non-numeric key entered.
1229 static int
1230 get_compound_key(struct tog_view *view, int c)
1232 struct tog_view *v = view;
1233 int x, n = 0;
1235 if (view_is_hsplit_top(view))
1236 v = view->child;
1237 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1238 v = view->parent;
1240 view->count = 0;
1241 cbreak(); /* block for input */
1242 wmove(v->window, v->nlines - 1, 0);
1243 wclrtoeol(v->window);
1244 waddch(v->window, ':');
1246 do {
1247 x = getcurx(v->window);
1248 if (x != ERR && x < view->ncols) {
1249 waddch(v->window, c);
1250 wrefresh(v->window);
1254 * Don't overflow. Max valid request should be the greatest
1255 * between the longest and total lines; cap at 10 million.
1257 if (n >= 9999999)
1258 n = 9999999;
1259 else
1260 n = n * 10 + (c - '0');
1261 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1263 /* Massage excessive or inapplicable values at the input handler. */
1264 view->count = n;
1266 return c;
1269 static const struct got_error *
1270 view_input(struct tog_view **new, int *done, struct tog_view *view,
1271 struct tog_view_list_head *views)
1273 const struct got_error *err = NULL;
1274 struct tog_view *v;
1275 int ch, errcode;
1277 *new = NULL;
1279 /* Clear "no matches" indicator. */
1280 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1281 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1282 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1283 view->count = 0;
1286 if (view->searching && !view->search_next_done) {
1287 errcode = pthread_mutex_unlock(&tog_mutex);
1288 if (errcode)
1289 return got_error_set_errno(errcode,
1290 "pthread_mutex_unlock");
1291 sched_yield();
1292 errcode = pthread_mutex_lock(&tog_mutex);
1293 if (errcode)
1294 return got_error_set_errno(errcode,
1295 "pthread_mutex_lock");
1296 view->search_next(view);
1297 return NULL;
1300 nodelay(view->window, FALSE);
1301 /* Allow threads to make progress while we are waiting for input. */
1302 errcode = pthread_mutex_unlock(&tog_mutex);
1303 if (errcode)
1304 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1305 /* If we have an unfinished count, let C-g or backspace abort. */
1306 if (view->count && --view->count) {
1307 cbreak();
1308 nodelay(view->window, TRUE);
1309 ch = wgetch(view->window);
1310 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1311 view->count = 0;
1312 else
1313 ch = view->ch;
1314 } else {
1315 ch = wgetch(view->window);
1316 if (ch >= '1' && ch <= '9')
1317 view->ch = ch = get_compound_key(view, ch);
1319 errcode = pthread_mutex_lock(&tog_mutex);
1320 if (errcode)
1321 return got_error_set_errno(errcode, "pthread_mutex_lock");
1322 nodelay(view->window, TRUE);
1324 if (tog_sigwinch_received || tog_sigcont_received) {
1325 tog_resizeterm();
1326 tog_sigwinch_received = 0;
1327 tog_sigcont_received = 0;
1328 TAILQ_FOREACH(v, views, entry) {
1329 err = view_resize(v);
1330 if (err)
1331 return err;
1332 err = v->input(new, v, KEY_RESIZE);
1333 if (err)
1334 return err;
1335 if (v->child) {
1336 err = view_resize(v->child);
1337 if (err)
1338 return err;
1339 err = v->child->input(new, v->child,
1340 KEY_RESIZE);
1341 if (err)
1342 return err;
1343 if (v->child->resized_x || v->child->resized_y) {
1344 err = view_resize_split(v, 0);
1345 if (err)
1346 return err;
1352 switch (ch) {
1353 case '\t':
1354 view->count = 0;
1355 if (view->child) {
1356 view->focussed = 0;
1357 view->child->focussed = 1;
1358 view->focus_child = 1;
1359 } else if (view->parent) {
1360 view->focussed = 0;
1361 view->parent->focussed = 1;
1362 view->parent->focus_child = 0;
1363 if (!view_is_splitscreen(view)) {
1364 if (view->mode == TOG_VIEW_SPLIT_HRZN &&
1365 view->parent->type == TOG_VIEW_LOG) {
1366 err = request_log_commits(view->parent);
1367 if (err)
1368 return err;
1370 offset_selection_up(view->parent);
1371 err = view_fullscreen(view->parent);
1372 if (err)
1373 return err;
1376 break;
1377 case 'q':
1378 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1379 if (view->parent->type == TOG_VIEW_LOG) {
1380 /* might need more commits to fill fullscreen */
1381 err = request_log_commits(view->parent);
1382 if (err)
1383 break;
1385 offset_selection_up(view->parent);
1387 err = view->input(new, view, ch);
1388 view->dying = 1;
1389 break;
1390 case 'Q':
1391 *done = 1;
1392 break;
1393 case 'F':
1394 view->count = 0;
1395 if (view_is_parent_view(view)) {
1396 if (view->child == NULL)
1397 break;
1398 if (view_is_splitscreen(view->child)) {
1399 view->focussed = 0;
1400 view->child->focussed = 1;
1401 err = view_fullscreen(view->child);
1402 } else {
1403 err = view_splitscreen(view->child);
1404 if (!err)
1405 err = view_resize_split(view, 0);
1407 if (err)
1408 break;
1409 err = view->child->input(new, view->child,
1410 KEY_RESIZE);
1411 } else {
1412 if (view_is_splitscreen(view)) {
1413 view->parent->focussed = 0;
1414 view->focussed = 1;
1415 err = view_fullscreen(view);
1416 } else {
1417 err = view_splitscreen(view);
1418 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1419 err = view_resize(view->parent);
1420 if (!err)
1421 err = view_resize_split(view, 0);
1423 if (err)
1424 break;
1425 err = view->input(new, view, KEY_RESIZE);
1427 if (err)
1428 break;
1429 if (view->type == TOG_VIEW_LOG) {
1430 err = request_log_commits(view);
1431 if (err)
1432 break;
1434 if (view->parent)
1435 err = offset_selection_down(view->parent);
1436 if (!err)
1437 err = offset_selection_down(view);
1438 break;
1439 case 'S':
1440 view->count = 0;
1441 err = switch_split(view);
1442 break;
1443 case '-':
1444 err = view_resize_split(view, -1);
1445 break;
1446 case '+':
1447 err = view_resize_split(view, 1);
1448 break;
1449 case KEY_RESIZE:
1450 break;
1451 case '/':
1452 view->count = 0;
1453 if (view->search_start)
1454 view_search_start(view);
1455 else
1456 err = view->input(new, view, ch);
1457 break;
1458 case 'N':
1459 case 'n':
1460 if (view->search_started && view->search_next) {
1461 view->searching = (ch == 'n' ?
1462 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1463 view->search_next_done = 0;
1464 view->search_next(view);
1465 } else
1466 err = view->input(new, view, ch);
1467 break;
1468 case 'A':
1469 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1470 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1471 else
1472 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1473 TAILQ_FOREACH(v, views, entry) {
1474 if (v->reset) {
1475 err = v->reset(v);
1476 if (err)
1477 return err;
1479 if (v->child && v->child->reset) {
1480 err = v->child->reset(v->child);
1481 if (err)
1482 return err;
1485 break;
1486 default:
1487 err = view->input(new, view, ch);
1488 break;
1491 return err;
1494 static int
1495 view_needs_focus_indication(struct tog_view *view)
1497 if (view_is_parent_view(view)) {
1498 if (view->child == NULL || view->child->focussed)
1499 return 0;
1500 if (!view_is_splitscreen(view->child))
1501 return 0;
1502 } else if (!view_is_splitscreen(view))
1503 return 0;
1505 return view->focussed;
1508 static const struct got_error *
1509 view_loop(struct tog_view *view)
1511 const struct got_error *err = NULL;
1512 struct tog_view_list_head views;
1513 struct tog_view *new_view;
1514 char *mode;
1515 int fast_refresh = 10;
1516 int done = 0, errcode;
1518 mode = getenv("TOG_VIEW_SPLIT_MODE");
1519 if (!mode || !(*mode == 'h' || *mode == 'H'))
1520 view->mode = TOG_VIEW_SPLIT_VERT;
1521 else
1522 view->mode = TOG_VIEW_SPLIT_HRZN;
1524 errcode = pthread_mutex_lock(&tog_mutex);
1525 if (errcode)
1526 return got_error_set_errno(errcode, "pthread_mutex_lock");
1528 TAILQ_INIT(&views);
1529 TAILQ_INSERT_HEAD(&views, view, entry);
1531 view->focussed = 1;
1532 err = view->show(view);
1533 if (err)
1534 return err;
1535 update_panels();
1536 doupdate();
1537 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1538 !tog_fatal_signal_received()) {
1539 /* Refresh fast during initialization, then become slower. */
1540 if (fast_refresh && fast_refresh-- == 0)
1541 halfdelay(10); /* switch to once per second */
1543 err = view_input(&new_view, &done, view, &views);
1544 if (err)
1545 break;
1546 if (view->dying) {
1547 struct tog_view *v, *prev = NULL;
1549 if (view_is_parent_view(view))
1550 prev = TAILQ_PREV(view, tog_view_list_head,
1551 entry);
1552 else if (view->parent)
1553 prev = view->parent;
1555 if (view->parent) {
1556 view->parent->child = NULL;
1557 view->parent->focus_child = 0;
1558 /* Restore fullscreen line height. */
1559 view->parent->nlines = view->parent->lines;
1560 err = view_resize(view->parent);
1561 if (err)
1562 break;
1563 /* Make resized splits persist. */
1564 view_transfer_size(view->parent, view);
1565 } else
1566 TAILQ_REMOVE(&views, view, entry);
1568 err = view_close(view);
1569 if (err)
1570 goto done;
1572 view = NULL;
1573 TAILQ_FOREACH(v, &views, entry) {
1574 if (v->focussed)
1575 break;
1577 if (view == NULL && new_view == NULL) {
1578 /* No view has focus. Try to pick one. */
1579 if (prev)
1580 view = prev;
1581 else if (!TAILQ_EMPTY(&views)) {
1582 view = TAILQ_LAST(&views,
1583 tog_view_list_head);
1585 if (view) {
1586 if (view->focus_child) {
1587 view->child->focussed = 1;
1588 view = view->child;
1589 } else
1590 view->focussed = 1;
1594 if (new_view) {
1595 struct tog_view *v, *t;
1596 /* Only allow one parent view per type. */
1597 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1598 if (v->type != new_view->type)
1599 continue;
1600 TAILQ_REMOVE(&views, v, entry);
1601 err = view_close(v);
1602 if (err)
1603 goto done;
1604 break;
1606 TAILQ_INSERT_TAIL(&views, new_view, entry);
1607 view = new_view;
1609 if (view) {
1610 if (view_is_parent_view(view)) {
1611 if (view->child && view->child->focussed)
1612 view = view->child;
1613 } else {
1614 if (view->parent && view->parent->focussed)
1615 view = view->parent;
1617 show_panel(view->panel);
1618 if (view->child && view_is_splitscreen(view->child))
1619 show_panel(view->child->panel);
1620 if (view->parent && view_is_splitscreen(view)) {
1621 err = view->parent->show(view->parent);
1622 if (err)
1623 goto done;
1625 err = view->show(view);
1626 if (err)
1627 goto done;
1628 if (view->child) {
1629 err = view->child->show(view->child);
1630 if (err)
1631 goto done;
1633 update_panels();
1634 doupdate();
1637 done:
1638 while (!TAILQ_EMPTY(&views)) {
1639 const struct got_error *close_err;
1640 view = TAILQ_FIRST(&views);
1641 TAILQ_REMOVE(&views, view, entry);
1642 close_err = view_close(view);
1643 if (close_err && err == NULL)
1644 err = close_err;
1647 errcode = pthread_mutex_unlock(&tog_mutex);
1648 if (errcode && err == NULL)
1649 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1651 return err;
1654 __dead static void
1655 usage_log(void)
1657 endwin();
1658 fprintf(stderr,
1659 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1660 getprogname());
1661 exit(1);
1664 /* Create newly allocated wide-character string equivalent to a byte string. */
1665 static const struct got_error *
1666 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1668 char *vis = NULL;
1669 const struct got_error *err = NULL;
1671 *ws = NULL;
1672 *wlen = mbstowcs(NULL, s, 0);
1673 if (*wlen == (size_t)-1) {
1674 int vislen;
1675 if (errno != EILSEQ)
1676 return got_error_from_errno("mbstowcs");
1678 /* byte string invalid in current encoding; try to "fix" it */
1679 err = got_mbsavis(&vis, &vislen, s);
1680 if (err)
1681 return err;
1682 *wlen = mbstowcs(NULL, vis, 0);
1683 if (*wlen == (size_t)-1) {
1684 err = got_error_from_errno("mbstowcs"); /* give up */
1685 goto done;
1689 *ws = calloc(*wlen + 1, sizeof(**ws));
1690 if (*ws == NULL) {
1691 err = got_error_from_errno("calloc");
1692 goto done;
1695 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1696 err = got_error_from_errno("mbstowcs");
1697 done:
1698 free(vis);
1699 if (err) {
1700 free(*ws);
1701 *ws = NULL;
1702 *wlen = 0;
1704 return err;
1707 static const struct got_error *
1708 expand_tab(char **ptr, const char *src)
1710 char *dst;
1711 size_t len, n, idx = 0, sz = 0;
1713 *ptr = NULL;
1714 n = len = strlen(src);
1715 dst = malloc(n + 1);
1716 if (dst == NULL)
1717 return got_error_from_errno("malloc");
1719 while (idx < len && src[idx]) {
1720 const char c = src[idx];
1722 if (c == '\t') {
1723 size_t nb = TABSIZE - sz % TABSIZE;
1724 char *p;
1726 p = realloc(dst, n + nb);
1727 if (p == NULL) {
1728 free(dst);
1729 return got_error_from_errno("realloc");
1732 dst = p;
1733 n += nb;
1734 memset(dst + sz, ' ', nb);
1735 sz += nb;
1736 } else
1737 dst[sz++] = src[idx];
1738 ++idx;
1741 dst[sz] = '\0';
1742 *ptr = dst;
1743 return NULL;
1747 * Advance at most n columns from wline starting at offset off.
1748 * Return the index to the first character after the span operation.
1749 * Return the combined column width of all spanned wide character in
1750 * *rcol.
1752 static int
1753 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1755 int width, i, cols = 0;
1757 if (n == 0) {
1758 *rcol = cols;
1759 return off;
1762 for (i = off; wline[i] != L'\0'; ++i) {
1763 if (wline[i] == L'\t')
1764 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1765 else
1766 width = wcwidth(wline[i]);
1768 if (width == -1) {
1769 width = 1;
1770 wline[i] = L'.';
1773 if (cols + width > n)
1774 break;
1775 cols += width;
1778 *rcol = cols;
1779 return i;
1783 * Format a line for display, ensuring that it won't overflow a width limit.
1784 * With scrolling, the width returned refers to the scrolled version of the
1785 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1787 static const struct got_error *
1788 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1789 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1791 const struct got_error *err = NULL;
1792 int cols;
1793 wchar_t *wline = NULL;
1794 char *exstr = NULL;
1795 size_t wlen;
1796 int i, scrollx;
1798 *wlinep = NULL;
1799 *widthp = 0;
1801 if (expand) {
1802 err = expand_tab(&exstr, line);
1803 if (err)
1804 return err;
1807 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1808 free(exstr);
1809 if (err)
1810 return err;
1812 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1814 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1815 wline[wlen - 1] = L'\0';
1816 wlen--;
1818 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1819 wline[wlen - 1] = L'\0';
1820 wlen--;
1823 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1824 wline[i] = L'\0';
1826 if (widthp)
1827 *widthp = cols;
1828 if (scrollxp)
1829 *scrollxp = scrollx;
1830 if (err)
1831 free(wline);
1832 else
1833 *wlinep = wline;
1834 return err;
1837 static const struct got_error*
1838 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1839 struct got_object_id *id, struct got_repository *repo)
1841 static const struct got_error *err = NULL;
1842 struct got_reflist_entry *re;
1843 char *s;
1844 const char *name;
1846 *refs_str = NULL;
1848 TAILQ_FOREACH(re, refs, entry) {
1849 struct got_tag_object *tag = NULL;
1850 struct got_object_id *ref_id;
1851 int cmp;
1853 name = got_ref_get_name(re->ref);
1854 if (strcmp(name, GOT_REF_HEAD) == 0)
1855 continue;
1856 if (strncmp(name, "refs/", 5) == 0)
1857 name += 5;
1858 if (strncmp(name, "got/", 4) == 0 &&
1859 strncmp(name, "got/backup/", 11) != 0)
1860 continue;
1861 if (strncmp(name, "heads/", 6) == 0)
1862 name += 6;
1863 if (strncmp(name, "remotes/", 8) == 0) {
1864 name += 8;
1865 s = strstr(name, "/" GOT_REF_HEAD);
1866 if (s != NULL && s[strlen(s)] == '\0')
1867 continue;
1869 err = got_ref_resolve(&ref_id, repo, re->ref);
1870 if (err)
1871 break;
1872 if (strncmp(name, "tags/", 5) == 0) {
1873 err = got_object_open_as_tag(&tag, repo, ref_id);
1874 if (err) {
1875 if (err->code != GOT_ERR_OBJ_TYPE) {
1876 free(ref_id);
1877 break;
1879 /* Ref points at something other than a tag. */
1880 err = NULL;
1881 tag = NULL;
1884 cmp = got_object_id_cmp(tag ?
1885 got_object_tag_get_object_id(tag) : ref_id, id);
1886 free(ref_id);
1887 if (tag)
1888 got_object_tag_close(tag);
1889 if (cmp != 0)
1890 continue;
1891 s = *refs_str;
1892 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1893 s ? ", " : "", name) == -1) {
1894 err = got_error_from_errno("asprintf");
1895 free(s);
1896 *refs_str = NULL;
1897 break;
1899 free(s);
1902 return err;
1905 static const struct got_error *
1906 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1907 int col_tab_align)
1909 char *smallerthan;
1911 smallerthan = strchr(author, '<');
1912 if (smallerthan && smallerthan[1] != '\0')
1913 author = smallerthan + 1;
1914 author[strcspn(author, "@>")] = '\0';
1915 return format_line(wauthor, author_width, NULL, author, 0, limit,
1916 col_tab_align, 0);
1919 static const struct got_error *
1920 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1921 struct got_object_id *id, const size_t date_display_cols,
1922 int author_display_cols)
1924 struct tog_log_view_state *s = &view->state.log;
1925 const struct got_error *err = NULL;
1926 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1927 char *logmsg0 = NULL, *logmsg = NULL;
1928 char *author = NULL;
1929 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1930 int author_width, logmsg_width;
1931 char *newline, *line = NULL;
1932 int col, limit, scrollx;
1933 const int avail = view->ncols;
1934 struct tm tm;
1935 time_t committer_time;
1936 struct tog_color *tc;
1938 committer_time = got_object_commit_get_committer_time(commit);
1939 if (gmtime_r(&committer_time, &tm) == NULL)
1940 return got_error_from_errno("gmtime_r");
1941 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1942 return got_error(GOT_ERR_NO_SPACE);
1944 if (avail <= date_display_cols)
1945 limit = MIN(sizeof(datebuf) - 1, avail);
1946 else
1947 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1948 tc = get_color(&s->colors, TOG_COLOR_DATE);
1949 if (tc)
1950 wattr_on(view->window,
1951 COLOR_PAIR(tc->colorpair), NULL);
1952 waddnstr(view->window, datebuf, limit);
1953 if (tc)
1954 wattr_off(view->window,
1955 COLOR_PAIR(tc->colorpair), NULL);
1956 col = limit;
1957 if (col > avail)
1958 goto done;
1960 if (avail >= 120) {
1961 char *id_str;
1962 err = got_object_id_str(&id_str, id);
1963 if (err)
1964 goto done;
1965 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1966 if (tc)
1967 wattr_on(view->window,
1968 COLOR_PAIR(tc->colorpair), NULL);
1969 wprintw(view->window, "%.8s ", id_str);
1970 if (tc)
1971 wattr_off(view->window,
1972 COLOR_PAIR(tc->colorpair), NULL);
1973 free(id_str);
1974 col += 9;
1975 if (col > avail)
1976 goto done;
1979 author = strdup(got_object_commit_get_author(commit));
1980 if (author == NULL) {
1981 err = got_error_from_errno("strdup");
1982 goto done;
1984 err = format_author(&wauthor, &author_width, author, avail - col, col);
1985 if (err)
1986 goto done;
1987 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1988 if (tc)
1989 wattr_on(view->window,
1990 COLOR_PAIR(tc->colorpair), NULL);
1991 waddwstr(view->window, wauthor);
1992 if (tc)
1993 wattr_off(view->window,
1994 COLOR_PAIR(tc->colorpair), NULL);
1995 col += author_width;
1996 while (col < avail && author_width < author_display_cols + 2) {
1997 waddch(view->window, ' ');
1998 col++;
1999 author_width++;
2001 if (col > avail)
2002 goto done;
2004 err = got_object_commit_get_logmsg(&logmsg0, commit);
2005 if (err)
2006 goto done;
2007 logmsg = logmsg0;
2008 while (*logmsg == '\n')
2009 logmsg++;
2010 newline = strchr(logmsg, '\n');
2011 if (newline)
2012 *newline = '\0';
2013 limit = avail - col;
2014 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2015 limit--; /* for the border */
2016 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2017 limit, col, 1);
2018 if (err)
2019 goto done;
2020 waddwstr(view->window, &wlogmsg[scrollx]);
2021 col += MAX(logmsg_width, 0);
2022 while (col < avail) {
2023 waddch(view->window, ' ');
2024 col++;
2026 done:
2027 free(logmsg0);
2028 free(wlogmsg);
2029 free(author);
2030 free(wauthor);
2031 free(line);
2032 return err;
2035 static struct commit_queue_entry *
2036 alloc_commit_queue_entry(struct got_commit_object *commit,
2037 struct got_object_id *id)
2039 struct commit_queue_entry *entry;
2041 entry = calloc(1, sizeof(*entry));
2042 if (entry == NULL)
2043 return NULL;
2045 entry->id = id;
2046 entry->commit = commit;
2047 return entry;
2050 static void
2051 pop_commit(struct commit_queue *commits)
2053 struct commit_queue_entry *entry;
2055 entry = TAILQ_FIRST(&commits->head);
2056 TAILQ_REMOVE(&commits->head, entry, entry);
2057 got_object_commit_close(entry->commit);
2058 commits->ncommits--;
2059 /* Don't free entry->id! It is owned by the commit graph. */
2060 free(entry);
2063 static void
2064 free_commits(struct commit_queue *commits)
2066 while (!TAILQ_EMPTY(&commits->head))
2067 pop_commit(commits);
2070 static const struct got_error *
2071 match_commit(int *have_match, struct got_object_id *id,
2072 struct got_commit_object *commit, regex_t *regex)
2074 const struct got_error *err = NULL;
2075 regmatch_t regmatch;
2076 char *id_str = NULL, *logmsg = NULL;
2078 *have_match = 0;
2080 err = got_object_id_str(&id_str, id);
2081 if (err)
2082 return err;
2084 err = got_object_commit_get_logmsg(&logmsg, commit);
2085 if (err)
2086 goto done;
2088 if (regexec(regex, got_object_commit_get_author(commit), 1,
2089 &regmatch, 0) == 0 ||
2090 regexec(regex, got_object_commit_get_committer(commit), 1,
2091 &regmatch, 0) == 0 ||
2092 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2093 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2094 *have_match = 1;
2095 done:
2096 free(id_str);
2097 free(logmsg);
2098 return err;
2101 static const struct got_error *
2102 queue_commits(struct tog_log_thread_args *a)
2104 const struct got_error *err = NULL;
2107 * We keep all commits open throughout the lifetime of the log
2108 * view in order to avoid having to re-fetch commits from disk
2109 * while updating the display.
2111 do {
2112 struct got_object_id *id;
2113 struct got_commit_object *commit;
2114 struct commit_queue_entry *entry;
2115 int errcode;
2117 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2118 NULL, NULL);
2119 if (err || id == NULL)
2120 break;
2122 err = got_object_open_as_commit(&commit, a->repo, id);
2123 if (err)
2124 break;
2125 entry = alloc_commit_queue_entry(commit, id);
2126 if (entry == NULL) {
2127 err = got_error_from_errno("alloc_commit_queue_entry");
2128 break;
2131 errcode = pthread_mutex_lock(&tog_mutex);
2132 if (errcode) {
2133 err = got_error_set_errno(errcode,
2134 "pthread_mutex_lock");
2135 break;
2138 entry->idx = a->commits->ncommits;
2139 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2140 a->commits->ncommits++;
2142 if (*a->searching == TOG_SEARCH_FORWARD &&
2143 !*a->search_next_done) {
2144 int have_match;
2145 err = match_commit(&have_match, id, commit, a->regex);
2146 if (err)
2147 break;
2148 if (have_match)
2149 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2152 errcode = pthread_mutex_unlock(&tog_mutex);
2153 if (errcode && err == NULL)
2154 err = got_error_set_errno(errcode,
2155 "pthread_mutex_unlock");
2156 if (err)
2157 break;
2158 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2160 return err;
2163 static void
2164 select_commit(struct tog_log_view_state *s)
2166 struct commit_queue_entry *entry;
2167 int ncommits = 0;
2169 entry = s->first_displayed_entry;
2170 while (entry) {
2171 if (ncommits == s->selected) {
2172 s->selected_entry = entry;
2173 break;
2175 entry = TAILQ_NEXT(entry, entry);
2176 ncommits++;
2180 static const struct got_error *
2181 draw_commits(struct tog_view *view)
2183 const struct got_error *err = NULL;
2184 struct tog_log_view_state *s = &view->state.log;
2185 struct commit_queue_entry *entry = s->selected_entry;
2186 const int limit = view->nlines;
2187 int width;
2188 int ncommits, author_cols = 4;
2189 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2190 char *refs_str = NULL;
2191 wchar_t *wline;
2192 struct tog_color *tc;
2193 static const size_t date_display_cols = 12;
2195 if (s->selected_entry &&
2196 !(view->searching && view->search_next_done == 0)) {
2197 struct got_reflist_head *refs;
2198 err = got_object_id_str(&id_str, s->selected_entry->id);
2199 if (err)
2200 return err;
2201 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2202 s->selected_entry->id);
2203 if (refs) {
2204 err = build_refs_str(&refs_str, refs,
2205 s->selected_entry->id, s->repo);
2206 if (err)
2207 goto done;
2211 if (s->thread_args.commits_needed == 0)
2212 halfdelay(10); /* disable fast refresh */
2214 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2215 if (asprintf(&ncommits_str, " [%d/%d] %s",
2216 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2217 (view->searching && !view->search_next_done) ?
2218 "searching..." : "loading...") == -1) {
2219 err = got_error_from_errno("asprintf");
2220 goto done;
2222 } else {
2223 const char *search_str = NULL;
2225 if (view->searching) {
2226 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2227 search_str = "no more matches";
2228 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2229 search_str = "no matches found";
2230 else if (!view->search_next_done)
2231 search_str = "searching...";
2234 if (asprintf(&ncommits_str, " [%d/%d] %s",
2235 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2236 search_str ? search_str :
2237 (refs_str ? refs_str : "")) == -1) {
2238 err = got_error_from_errno("asprintf");
2239 goto done;
2243 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2244 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2245 "........................................",
2246 s->in_repo_path, ncommits_str) == -1) {
2247 err = got_error_from_errno("asprintf");
2248 header = NULL;
2249 goto done;
2251 } else if (asprintf(&header, "commit %s%s",
2252 id_str ? id_str : "........................................",
2253 ncommits_str) == -1) {
2254 err = got_error_from_errno("asprintf");
2255 header = NULL;
2256 goto done;
2258 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2259 if (err)
2260 goto done;
2262 werase(view->window);
2264 if (view_needs_focus_indication(view))
2265 wstandout(view->window);
2266 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2267 if (tc)
2268 wattr_on(view->window,
2269 COLOR_PAIR(tc->colorpair), NULL);
2270 waddwstr(view->window, wline);
2271 if (tc)
2272 wattr_off(view->window,
2273 COLOR_PAIR(tc->colorpair), NULL);
2274 while (width < view->ncols) {
2275 waddch(view->window, ' ');
2276 width++;
2278 if (view_needs_focus_indication(view))
2279 wstandend(view->window);
2280 free(wline);
2281 if (limit <= 1)
2282 goto done;
2284 /* Grow author column size if necessary, and set view->maxx. */
2285 entry = s->first_displayed_entry;
2286 ncommits = 0;
2287 view->maxx = 0;
2288 while (entry) {
2289 char *author, *eol, *msg, *msg0;
2290 wchar_t *wauthor, *wmsg;
2291 int width;
2292 if (ncommits >= limit - 1)
2293 break;
2294 author = strdup(got_object_commit_get_author(entry->commit));
2295 if (author == NULL) {
2296 err = got_error_from_errno("strdup");
2297 goto done;
2299 err = format_author(&wauthor, &width, author, COLS,
2300 date_display_cols);
2301 if (author_cols < width)
2302 author_cols = width;
2303 free(wauthor);
2304 free(author);
2305 err = got_object_commit_get_logmsg(&msg0, entry->commit);
2306 if (err)
2307 goto done;
2308 msg = msg0;
2309 while (*msg == '\n')
2310 ++msg;
2311 if ((eol = strchr(msg, '\n')))
2312 *eol = '\0';
2313 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2314 date_display_cols + author_cols, 0);
2315 if (err)
2316 goto done;
2317 view->maxx = MAX(view->maxx, width);
2318 free(msg0);
2319 free(wmsg);
2320 ncommits++;
2321 entry = TAILQ_NEXT(entry, entry);
2324 entry = s->first_displayed_entry;
2325 s->last_displayed_entry = s->first_displayed_entry;
2326 ncommits = 0;
2327 while (entry) {
2328 if (ncommits >= limit - 1)
2329 break;
2330 if (ncommits == s->selected)
2331 wstandout(view->window);
2332 err = draw_commit(view, entry->commit, entry->id,
2333 date_display_cols, author_cols);
2334 if (ncommits == s->selected)
2335 wstandend(view->window);
2336 if (err)
2337 goto done;
2338 ncommits++;
2339 s->last_displayed_entry = entry;
2340 entry = TAILQ_NEXT(entry, entry);
2343 view_border(view);
2344 done:
2345 free(id_str);
2346 free(refs_str);
2347 free(ncommits_str);
2348 free(header);
2349 return err;
2352 static void
2353 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2355 struct commit_queue_entry *entry;
2356 int nscrolled = 0;
2358 entry = TAILQ_FIRST(&s->commits.head);
2359 if (s->first_displayed_entry == entry)
2360 return;
2362 entry = s->first_displayed_entry;
2363 while (entry && nscrolled < maxscroll) {
2364 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2365 if (entry) {
2366 s->first_displayed_entry = entry;
2367 nscrolled++;
2372 static const struct got_error *
2373 trigger_log_thread(struct tog_view *view, int wait)
2375 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2376 int errcode;
2378 halfdelay(1); /* fast refresh while loading commits */
2380 while (!ta->log_complete && !tog_thread_error &&
2381 (ta->commits_needed > 0 || ta->load_all)) {
2382 /* Wake the log thread. */
2383 errcode = pthread_cond_signal(&ta->need_commits);
2384 if (errcode)
2385 return got_error_set_errno(errcode,
2386 "pthread_cond_signal");
2389 * The mutex will be released while the view loop waits
2390 * in wgetch(), at which time the log thread will run.
2392 if (!wait)
2393 break;
2395 /* Display progress update in log view. */
2396 show_log_view(view);
2397 update_panels();
2398 doupdate();
2400 /* Wait right here while next commit is being loaded. */
2401 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2402 if (errcode)
2403 return got_error_set_errno(errcode,
2404 "pthread_cond_wait");
2406 /* Display progress update in log view. */
2407 show_log_view(view);
2408 update_panels();
2409 doupdate();
2412 return NULL;
2415 static const struct got_error *
2416 request_log_commits(struct tog_view *view)
2418 struct tog_log_view_state *state = &view->state.log;
2419 const struct got_error *err = NULL;
2421 if (state->thread_args.log_complete)
2422 return NULL;
2424 state->thread_args.commits_needed += view->nscrolled;
2425 err = trigger_log_thread(view, 1);
2426 view->nscrolled = 0;
2428 return err;
2431 static const struct got_error *
2432 log_scroll_down(struct tog_view *view, int maxscroll)
2434 struct tog_log_view_state *s = &view->state.log;
2435 const struct got_error *err = NULL;
2436 struct commit_queue_entry *pentry;
2437 int nscrolled = 0, ncommits_needed;
2439 if (s->last_displayed_entry == NULL)
2440 return NULL;
2442 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2443 if (s->commits.ncommits < ncommits_needed &&
2444 !s->thread_args.log_complete) {
2446 * Ask the log thread for required amount of commits.
2448 s->thread_args.commits_needed += maxscroll;
2449 err = trigger_log_thread(view, 1);
2450 if (err)
2451 return err;
2454 do {
2455 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2456 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2457 break;
2459 s->last_displayed_entry = pentry ?
2460 pentry : s->last_displayed_entry;;
2462 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2463 if (pentry == NULL)
2464 break;
2465 s->first_displayed_entry = pentry;
2466 } while (++nscrolled < maxscroll);
2468 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2469 view->nscrolled += nscrolled;
2470 else
2471 view->nscrolled = 0;
2473 return err;
2476 static const struct got_error *
2477 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2478 struct got_commit_object *commit, struct got_object_id *commit_id,
2479 struct tog_view *log_view, struct got_repository *repo)
2481 const struct got_error *err;
2482 struct got_object_qid *parent_id;
2483 struct tog_view *diff_view;
2485 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2486 if (diff_view == NULL)
2487 return got_error_from_errno("view_open");
2489 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2490 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2491 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2492 if (err == NULL)
2493 *new_view = diff_view;
2494 return err;
2497 static const struct got_error *
2498 tree_view_visit_subtree(struct tog_tree_view_state *s,
2499 struct got_tree_object *subtree)
2501 struct tog_parent_tree *parent;
2503 parent = calloc(1, sizeof(*parent));
2504 if (parent == NULL)
2505 return got_error_from_errno("calloc");
2507 parent->tree = s->tree;
2508 parent->first_displayed_entry = s->first_displayed_entry;
2509 parent->selected_entry = s->selected_entry;
2510 parent->selected = s->selected;
2511 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2512 s->tree = subtree;
2513 s->selected = 0;
2514 s->first_displayed_entry = NULL;
2515 return NULL;
2518 static const struct got_error *
2519 tree_view_walk_path(struct tog_tree_view_state *s,
2520 struct got_commit_object *commit, const char *path)
2522 const struct got_error *err = NULL;
2523 struct got_tree_object *tree = NULL;
2524 const char *p;
2525 char *slash, *subpath = NULL;
2527 /* Walk the path and open corresponding tree objects. */
2528 p = path;
2529 while (*p) {
2530 struct got_tree_entry *te;
2531 struct got_object_id *tree_id;
2532 char *te_name;
2534 while (p[0] == '/')
2535 p++;
2537 /* Ensure the correct subtree entry is selected. */
2538 slash = strchr(p, '/');
2539 if (slash == NULL)
2540 te_name = strdup(p);
2541 else
2542 te_name = strndup(p, slash - p);
2543 if (te_name == NULL) {
2544 err = got_error_from_errno("strndup");
2545 break;
2547 te = got_object_tree_find_entry(s->tree, te_name);
2548 if (te == NULL) {
2549 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2550 free(te_name);
2551 break;
2553 free(te_name);
2554 s->first_displayed_entry = s->selected_entry = te;
2556 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2557 break; /* jump to this file's entry */
2559 slash = strchr(p, '/');
2560 if (slash)
2561 subpath = strndup(path, slash - path);
2562 else
2563 subpath = strdup(path);
2564 if (subpath == NULL) {
2565 err = got_error_from_errno("strdup");
2566 break;
2569 err = got_object_id_by_path(&tree_id, s->repo, commit,
2570 subpath);
2571 if (err)
2572 break;
2574 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2575 free(tree_id);
2576 if (err)
2577 break;
2579 err = tree_view_visit_subtree(s, tree);
2580 if (err) {
2581 got_object_tree_close(tree);
2582 break;
2584 if (slash == NULL)
2585 break;
2586 free(subpath);
2587 subpath = NULL;
2588 p = slash;
2591 free(subpath);
2592 return err;
2595 static const struct got_error *
2596 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2597 struct commit_queue_entry *entry, const char *path,
2598 const char *head_ref_name, struct got_repository *repo)
2600 const struct got_error *err = NULL;
2601 struct tog_tree_view_state *s;
2602 struct tog_view *tree_view;
2604 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2605 if (tree_view == NULL)
2606 return got_error_from_errno("view_open");
2608 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2609 if (err)
2610 return err;
2611 s = &tree_view->state.tree;
2613 *new_view = tree_view;
2615 if (got_path_is_root_dir(path))
2616 return NULL;
2618 return tree_view_walk_path(s, entry->commit, path);
2621 static const struct got_error *
2622 block_signals_used_by_main_thread(void)
2624 sigset_t sigset;
2625 int errcode;
2627 if (sigemptyset(&sigset) == -1)
2628 return got_error_from_errno("sigemptyset");
2630 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2631 if (sigaddset(&sigset, SIGWINCH) == -1)
2632 return got_error_from_errno("sigaddset");
2633 if (sigaddset(&sigset, SIGCONT) == -1)
2634 return got_error_from_errno("sigaddset");
2635 if (sigaddset(&sigset, SIGINT) == -1)
2636 return got_error_from_errno("sigaddset");
2637 if (sigaddset(&sigset, SIGTERM) == -1)
2638 return got_error_from_errno("sigaddset");
2640 /* ncurses handles SIGTSTP */
2641 if (sigaddset(&sigset, SIGTSTP) == -1)
2642 return got_error_from_errno("sigaddset");
2644 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2645 if (errcode)
2646 return got_error_set_errno(errcode, "pthread_sigmask");
2648 return NULL;
2651 static void *
2652 log_thread(void *arg)
2654 const struct got_error *err = NULL;
2655 int errcode = 0;
2656 struct tog_log_thread_args *a = arg;
2657 int done = 0;
2660 * Sync startup with main thread such that we begin our
2661 * work once view_input() has released the mutex.
2663 errcode = pthread_mutex_lock(&tog_mutex);
2664 if (errcode) {
2665 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2666 return (void *)err;
2669 err = block_signals_used_by_main_thread();
2670 if (err) {
2671 pthread_mutex_unlock(&tog_mutex);
2672 goto done;
2675 while (!done && !err && !tog_fatal_signal_received()) {
2676 errcode = pthread_mutex_unlock(&tog_mutex);
2677 if (errcode) {
2678 err = got_error_set_errno(errcode,
2679 "pthread_mutex_unlock");
2680 goto done;
2682 err = queue_commits(a);
2683 if (err) {
2684 if (err->code != GOT_ERR_ITER_COMPLETED)
2685 goto done;
2686 err = NULL;
2687 done = 1;
2688 } else if (a->commits_needed > 0 && !a->load_all)
2689 a->commits_needed--;
2691 errcode = pthread_mutex_lock(&tog_mutex);
2692 if (errcode) {
2693 err = got_error_set_errno(errcode,
2694 "pthread_mutex_lock");
2695 goto done;
2696 } else if (*a->quit)
2697 done = 1;
2698 else if (*a->first_displayed_entry == NULL) {
2699 *a->first_displayed_entry =
2700 TAILQ_FIRST(&a->commits->head);
2701 *a->selected_entry = *a->first_displayed_entry;
2704 errcode = pthread_cond_signal(&a->commit_loaded);
2705 if (errcode) {
2706 err = got_error_set_errno(errcode,
2707 "pthread_cond_signal");
2708 pthread_mutex_unlock(&tog_mutex);
2709 goto done;
2712 if (done)
2713 a->commits_needed = 0;
2714 else {
2715 if (a->commits_needed == 0 && !a->load_all) {
2716 errcode = pthread_cond_wait(&a->need_commits,
2717 &tog_mutex);
2718 if (errcode) {
2719 err = got_error_set_errno(errcode,
2720 "pthread_cond_wait");
2721 pthread_mutex_unlock(&tog_mutex);
2722 goto done;
2724 if (*a->quit)
2725 done = 1;
2729 a->log_complete = 1;
2730 errcode = pthread_mutex_unlock(&tog_mutex);
2731 if (errcode)
2732 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2733 done:
2734 if (err) {
2735 tog_thread_error = 1;
2736 pthread_cond_signal(&a->commit_loaded);
2738 return (void *)err;
2741 static const struct got_error *
2742 stop_log_thread(struct tog_log_view_state *s)
2744 const struct got_error *err = NULL, *thread_err = NULL;
2745 int errcode;
2747 if (s->thread) {
2748 s->quit = 1;
2749 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2750 if (errcode)
2751 return got_error_set_errno(errcode,
2752 "pthread_cond_signal");
2753 errcode = pthread_mutex_unlock(&tog_mutex);
2754 if (errcode)
2755 return got_error_set_errno(errcode,
2756 "pthread_mutex_unlock");
2757 errcode = pthread_join(s->thread, (void **)&thread_err);
2758 if (errcode)
2759 return got_error_set_errno(errcode, "pthread_join");
2760 errcode = pthread_mutex_lock(&tog_mutex);
2761 if (errcode)
2762 return got_error_set_errno(errcode,
2763 "pthread_mutex_lock");
2764 s->thread = 0; //NULL;
2767 if (s->thread_args.repo) {
2768 err = got_repo_close(s->thread_args.repo);
2769 s->thread_args.repo = NULL;
2772 if (s->thread_args.pack_fds) {
2773 const struct got_error *pack_err =
2774 got_repo_pack_fds_close(s->thread_args.pack_fds);
2775 if (err == NULL)
2776 err = pack_err;
2777 s->thread_args.pack_fds = NULL;
2780 if (s->thread_args.graph) {
2781 got_commit_graph_close(s->thread_args.graph);
2782 s->thread_args.graph = NULL;
2785 return err ? err : thread_err;
2788 static const struct got_error *
2789 close_log_view(struct tog_view *view)
2791 const struct got_error *err = NULL;
2792 struct tog_log_view_state *s = &view->state.log;
2793 int errcode;
2795 err = stop_log_thread(s);
2797 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2798 if (errcode && err == NULL)
2799 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2801 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2802 if (errcode && err == NULL)
2803 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2805 free_commits(&s->commits);
2806 free(s->in_repo_path);
2807 s->in_repo_path = NULL;
2808 free(s->start_id);
2809 s->start_id = NULL;
2810 free(s->head_ref_name);
2811 s->head_ref_name = NULL;
2812 return err;
2815 static const struct got_error *
2816 search_start_log_view(struct tog_view *view)
2818 struct tog_log_view_state *s = &view->state.log;
2820 s->matched_entry = NULL;
2821 s->search_entry = NULL;
2822 return NULL;
2825 static const struct got_error *
2826 search_next_log_view(struct tog_view *view)
2828 const struct got_error *err = NULL;
2829 struct tog_log_view_state *s = &view->state.log;
2830 struct commit_queue_entry *entry;
2832 /* Display progress update in log view. */
2833 show_log_view(view);
2834 update_panels();
2835 doupdate();
2837 if (s->search_entry) {
2838 int errcode, ch;
2839 errcode = pthread_mutex_unlock(&tog_mutex);
2840 if (errcode)
2841 return got_error_set_errno(errcode,
2842 "pthread_mutex_unlock");
2843 ch = wgetch(view->window);
2844 errcode = pthread_mutex_lock(&tog_mutex);
2845 if (errcode)
2846 return got_error_set_errno(errcode,
2847 "pthread_mutex_lock");
2848 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2849 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2850 return NULL;
2852 if (view->searching == TOG_SEARCH_FORWARD)
2853 entry = TAILQ_NEXT(s->search_entry, entry);
2854 else
2855 entry = TAILQ_PREV(s->search_entry,
2856 commit_queue_head, entry);
2857 } else if (s->matched_entry) {
2858 int matched_idx = s->matched_entry->idx;
2859 int selected_idx = s->selected_entry->idx;
2862 * If the user has moved the cursor after we hit a match,
2863 * the position from where we should continue searching
2864 * might have changed.
2866 if (view->searching == TOG_SEARCH_FORWARD) {
2867 if (matched_idx > selected_idx)
2868 entry = TAILQ_NEXT(s->selected_entry, entry);
2869 else
2870 entry = TAILQ_NEXT(s->matched_entry, entry);
2871 } else {
2872 if (matched_idx < selected_idx)
2873 entry = TAILQ_PREV(s->selected_entry,
2874 commit_queue_head, entry);
2875 else
2876 entry = TAILQ_PREV(s->matched_entry,
2877 commit_queue_head, entry);
2879 } else {
2880 entry = s->selected_entry;
2883 while (1) {
2884 int have_match = 0;
2886 if (entry == NULL) {
2887 if (s->thread_args.log_complete ||
2888 view->searching == TOG_SEARCH_BACKWARD) {
2889 view->search_next_done =
2890 (s->matched_entry == NULL ?
2891 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2892 s->search_entry = NULL;
2893 return NULL;
2896 * Poke the log thread for more commits and return,
2897 * allowing the main loop to make progress. Search
2898 * will resume at s->search_entry once we come back.
2900 s->thread_args.commits_needed++;
2901 return trigger_log_thread(view, 0);
2904 err = match_commit(&have_match, entry->id, entry->commit,
2905 &view->regex);
2906 if (err)
2907 break;
2908 if (have_match) {
2909 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2910 s->matched_entry = entry;
2911 break;
2914 s->search_entry = entry;
2915 if (view->searching == TOG_SEARCH_FORWARD)
2916 entry = TAILQ_NEXT(entry, entry);
2917 else
2918 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2921 if (s->matched_entry) {
2922 int cur = s->selected_entry->idx;
2923 while (cur < s->matched_entry->idx) {
2924 err = input_log_view(NULL, view, KEY_DOWN);
2925 if (err)
2926 return err;
2927 cur++;
2929 while (cur > s->matched_entry->idx) {
2930 err = input_log_view(NULL, view, KEY_UP);
2931 if (err)
2932 return err;
2933 cur--;
2937 s->search_entry = NULL;
2939 return NULL;
2942 static const struct got_error *
2943 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2944 struct got_repository *repo, const char *head_ref_name,
2945 const char *in_repo_path, int log_branches)
2947 const struct got_error *err = NULL;
2948 struct tog_log_view_state *s = &view->state.log;
2949 struct got_repository *thread_repo = NULL;
2950 struct got_commit_graph *thread_graph = NULL;
2951 int errcode;
2953 if (in_repo_path != s->in_repo_path) {
2954 free(s->in_repo_path);
2955 s->in_repo_path = strdup(in_repo_path);
2956 if (s->in_repo_path == NULL)
2957 return got_error_from_errno("strdup");
2960 /* The commit queue only contains commits being displayed. */
2961 TAILQ_INIT(&s->commits.head);
2962 s->commits.ncommits = 0;
2964 s->repo = repo;
2965 if (head_ref_name) {
2966 s->head_ref_name = strdup(head_ref_name);
2967 if (s->head_ref_name == NULL) {
2968 err = got_error_from_errno("strdup");
2969 goto done;
2972 s->start_id = got_object_id_dup(start_id);
2973 if (s->start_id == NULL) {
2974 err = got_error_from_errno("got_object_id_dup");
2975 goto done;
2977 s->log_branches = log_branches;
2979 STAILQ_INIT(&s->colors);
2980 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2981 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2982 get_color_value("TOG_COLOR_COMMIT"));
2983 if (err)
2984 goto done;
2985 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2986 get_color_value("TOG_COLOR_AUTHOR"));
2987 if (err) {
2988 free_colors(&s->colors);
2989 goto done;
2991 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2992 get_color_value("TOG_COLOR_DATE"));
2993 if (err) {
2994 free_colors(&s->colors);
2995 goto done;
2999 view->show = show_log_view;
3000 view->input = input_log_view;
3001 view->resize = resize_log_view;
3002 view->close = close_log_view;
3003 view->search_start = search_start_log_view;
3004 view->search_next = search_next_log_view;
3006 if (s->thread_args.pack_fds == NULL) {
3007 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3008 if (err)
3009 goto done;
3011 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3012 s->thread_args.pack_fds);
3013 if (err)
3014 goto done;
3015 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3016 !s->log_branches);
3017 if (err)
3018 goto done;
3019 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3020 s->repo, NULL, NULL);
3021 if (err)
3022 goto done;
3024 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3025 if (errcode) {
3026 err = got_error_set_errno(errcode, "pthread_cond_init");
3027 goto done;
3029 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3030 if (errcode) {
3031 err = got_error_set_errno(errcode, "pthread_cond_init");
3032 goto done;
3035 s->thread_args.commits_needed = view->nlines;
3036 s->thread_args.graph = thread_graph;
3037 s->thread_args.commits = &s->commits;
3038 s->thread_args.in_repo_path = s->in_repo_path;
3039 s->thread_args.start_id = s->start_id;
3040 s->thread_args.repo = thread_repo;
3041 s->thread_args.log_complete = 0;
3042 s->thread_args.quit = &s->quit;
3043 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3044 s->thread_args.selected_entry = &s->selected_entry;
3045 s->thread_args.searching = &view->searching;
3046 s->thread_args.search_next_done = &view->search_next_done;
3047 s->thread_args.regex = &view->regex;
3048 done:
3049 if (err)
3050 close_log_view(view);
3051 return err;
3054 static const struct got_error *
3055 show_log_view(struct tog_view *view)
3057 const struct got_error *err;
3058 struct tog_log_view_state *s = &view->state.log;
3060 if (s->thread == 0) { //NULL) {
3061 int errcode = pthread_create(&s->thread, NULL, log_thread,
3062 &s->thread_args);
3063 if (errcode)
3064 return got_error_set_errno(errcode, "pthread_create");
3065 if (s->thread_args.commits_needed > 0) {
3066 err = trigger_log_thread(view, 1);
3067 if (err)
3068 return err;
3072 return draw_commits(view);
3075 static void
3076 log_move_cursor_up(struct tog_view *view, int page, int home)
3078 struct tog_log_view_state *s = &view->state.log;
3080 if (s->selected_entry->idx == 0)
3081 view->count = 0;
3082 if (s->first_displayed_entry == NULL)
3083 return;
3085 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3086 || home)
3087 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3089 if (!page && !home && s->selected > 0)
3090 --s->selected;
3091 else
3092 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3094 select_commit(s);
3095 return;
3098 static const struct got_error *
3099 log_move_cursor_down(struct tog_view *view, int page)
3101 struct tog_log_view_state *s = &view->state.log;
3102 struct commit_queue_entry *first;
3103 const struct got_error *err = NULL;
3105 first = s->first_displayed_entry;
3106 if (first == NULL) {
3107 view->count = 0;
3108 return NULL;
3111 if (s->thread_args.log_complete &&
3112 s->selected_entry->idx >= s->commits.ncommits - 1)
3113 return NULL;
3115 if (!page) {
3116 int eos = view->nlines - 2;
3118 if (view_is_hsplit_top(view))
3119 --eos; /* border consumes the last line */
3120 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3121 ++s->selected;
3122 else
3123 err = log_scroll_down(view, 1);
3124 } else if (s->thread_args.load_all) {
3125 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3126 s->selected += MIN(s->last_displayed_entry->idx -
3127 s->selected_entry->idx, page + 1);
3128 else
3129 err = log_scroll_down(view, MIN(page,
3130 s->commits.ncommits - s->selected_entry->idx - 1));
3131 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3132 } else {
3133 err = log_scroll_down(view, page);
3134 if (err)
3135 return err;
3136 if (first == s->first_displayed_entry && s->selected <
3137 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
3138 s->selected = MIN(s->commits.ncommits - 1, page);
3141 if (err)
3142 return err;
3145 * We might necessarily overshoot in horizontal
3146 * splits; if so, select the last displayed commit.
3148 s->selected = MIN(s->selected,
3149 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3151 select_commit(s);
3153 if (s->thread_args.log_complete &&
3154 s->selected_entry->idx == s->commits.ncommits - 1)
3155 view->count = 0;
3157 return NULL;
3160 static void
3161 view_get_split(struct tog_view *view, int *y, int *x)
3163 *x = 0;
3164 *y = 0;
3166 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3167 if (view->child && view->child->resized_y)
3168 *y = view->child->resized_y;
3169 else if (view->resized_y)
3170 *y = view->resized_y;
3171 else
3172 *y = view_split_begin_y(view->lines);
3173 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3174 if (view->child && view->child->resized_x)
3175 *x = view->child->resized_x;
3176 else if (view->resized_x)
3177 *x = view->resized_x;
3178 else
3179 *x = view_split_begin_x(view->begin_x);
3183 /* Split view horizontally at y and offset view->state->selected line. */
3184 static const struct got_error *
3185 view_init_hsplit(struct tog_view *view, int y)
3187 const struct got_error *err = NULL;
3189 view->nlines = y;
3190 view->ncols = COLS;
3191 err = view_resize(view);
3192 if (err)
3193 return err;
3195 err = offset_selection_down(view);
3197 return err;
3200 static const struct got_error *
3201 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3203 const struct got_error *err = NULL;
3204 struct tog_log_view_state *s = &view->state.log;
3205 struct tog_view *diff_view = NULL, *tree_view = NULL;
3206 struct tog_view *ref_view = NULL;
3207 struct commit_queue_entry *entry;
3208 int begin_x = 0, begin_y = 0, eos, n, nscroll;
3210 if (s->thread_args.load_all) {
3211 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3212 s->thread_args.load_all = 0;
3213 else if (s->thread_args.log_complete) {
3214 err = log_move_cursor_down(view, s->commits.ncommits);
3215 s->thread_args.load_all = 0;
3217 return err;
3220 eos = nscroll = view->nlines - 1;
3221 if (view_is_hsplit_top(view))
3222 --eos; /* border */
3224 switch (ch) {
3225 case 'q':
3226 s->quit = 1;
3227 break;
3228 case '0':
3229 view->x = 0;
3230 break;
3231 case '$':
3232 view->x = MAX(view->maxx - view->ncols / 2, 0);
3233 view->count = 0;
3234 break;
3235 case KEY_RIGHT:
3236 case 'l':
3237 if (view->x + view->ncols / 2 < view->maxx)
3238 view->x += 2; /* move two columns right */
3239 else
3240 view->count = 0;
3241 break;
3242 case KEY_LEFT:
3243 case 'h':
3244 view->x -= MIN(view->x, 2); /* move two columns back */
3245 if (view->x <= 0)
3246 view->count = 0;
3247 break;
3248 case 'k':
3249 case KEY_UP:
3250 case '<':
3251 case ',':
3252 case CTRL('p'):
3253 log_move_cursor_up(view, 0, 0);
3254 break;
3255 case 'g':
3256 case KEY_HOME:
3257 log_move_cursor_up(view, 0, 1);
3258 view->count = 0;
3259 break;
3260 case CTRL('u'):
3261 case 'u':
3262 nscroll /= 2;
3263 /* FALL THROUGH */
3264 case KEY_PPAGE:
3265 case CTRL('b'):
3266 case 'b':
3267 log_move_cursor_up(view, nscroll, 0);
3268 break;
3269 case 'j':
3270 case KEY_DOWN:
3271 case '>':
3272 case '.':
3273 case CTRL('n'):
3274 err = log_move_cursor_down(view, 0);
3275 break;
3276 case 'G':
3277 case KEY_END: {
3278 /* We don't know yet how many commits, so we're forced to
3279 * traverse them all. */
3280 view->count = 0;
3281 if (!s->thread_args.log_complete) {
3282 s->thread_args.load_all = 1;
3283 return trigger_log_thread(view, 0);
3286 s->selected = 0;
3287 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3288 for (n = 0; n < eos; n++) {
3289 if (entry == NULL)
3290 break;
3291 s->first_displayed_entry = entry;
3292 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3294 if (n > 0)
3295 s->selected = n - 1;
3296 select_commit(s);
3297 break;
3299 case CTRL('d'):
3300 case 'd':
3301 nscroll /= 2;
3302 /* FALL THROUGH */
3303 case KEY_NPAGE:
3304 case CTRL('f'):
3305 case 'f':
3306 case ' ':
3307 err = log_move_cursor_down(view, nscroll);
3308 break;
3309 case KEY_RESIZE:
3310 if (s->selected > view->nlines - 2)
3311 s->selected = view->nlines - 2;
3312 if (s->selected > s->commits.ncommits - 1)
3313 s->selected = s->commits.ncommits - 1;
3314 select_commit(s);
3315 if (s->commits.ncommits < view->nlines - 1 &&
3316 !s->thread_args.log_complete) {
3317 s->thread_args.commits_needed += (view->nlines - 1) -
3318 s->commits.ncommits;
3319 err = trigger_log_thread(view, 1);
3321 break;
3322 case KEY_ENTER:
3323 case '\r':
3324 view->count = 0;
3325 if (s->selected_entry == NULL)
3326 break;
3328 /* get dimensions--don't split till initialisation succeeds */
3329 if (view_is_parent_view(view))
3330 view_get_split(view, &begin_y, &begin_x);
3332 err = open_diff_view_for_commit(&diff_view, begin_y, begin_x,
3333 s->selected_entry->commit, s->selected_entry->id,
3334 view, s->repo);
3335 if (err)
3336 break;
3338 if (view_is_parent_view(view) &&
3339 view->mode == TOG_VIEW_SPLIT_HRZN) { /* safe to split */
3340 err = view_init_hsplit(view, begin_y);
3341 if (err)
3342 break;
3345 view->focussed = 0;
3346 diff_view->focussed = 1;
3347 diff_view->mode = view->mode;
3348 diff_view->nlines = view->lines - begin_y;
3350 if (view_is_parent_view(view)) {
3351 view_transfer_size(diff_view, view);
3352 err = view_close_child(view);
3353 if (err)
3354 return err;
3355 err = view_set_child(view, diff_view);
3356 if (err)
3357 return err;
3358 view->focus_child = 1;
3359 } else
3360 *new_view = diff_view;
3361 break;
3362 case 't':
3363 view->count = 0;
3364 if (s->selected_entry == NULL)
3365 break;
3366 if (view_is_parent_view(view))
3367 view_get_split(view, &begin_y, &begin_x);
3368 err = browse_commit_tree(&tree_view, begin_y, begin_x,
3369 s->selected_entry, s->in_repo_path, s->head_ref_name,
3370 s->repo);
3371 if (err)
3372 break;
3373 if (view_is_parent_view(view) &&
3374 view->mode == TOG_VIEW_SPLIT_HRZN) {
3375 err = view_init_hsplit(view, begin_y);
3376 if (err)
3377 break;
3379 view->focussed = 0;
3380 tree_view->focussed = 1;
3381 tree_view->mode = view->mode;
3382 tree_view->nlines = view->lines - begin_y;
3383 if (view_is_parent_view(view)) {
3384 view_transfer_size(tree_view, view);
3385 err = view_close_child(view);
3386 if (err)
3387 return err;
3388 err = view_set_child(view, tree_view);
3389 if (err)
3390 return err;
3391 view->focus_child = 1;
3392 } else
3393 *new_view = tree_view;
3394 break;
3395 case KEY_BACKSPACE:
3396 case CTRL('l'):
3397 case 'B':
3398 view->count = 0;
3399 if (ch == KEY_BACKSPACE &&
3400 got_path_is_root_dir(s->in_repo_path))
3401 break;
3402 err = stop_log_thread(s);
3403 if (err)
3404 return err;
3405 if (ch == KEY_BACKSPACE) {
3406 char *parent_path;
3407 err = got_path_dirname(&parent_path, s->in_repo_path);
3408 if (err)
3409 return err;
3410 free(s->in_repo_path);
3411 s->in_repo_path = parent_path;
3412 s->thread_args.in_repo_path = s->in_repo_path;
3413 } else if (ch == CTRL('l')) {
3414 struct got_object_id *start_id;
3415 err = got_repo_match_object_id(&start_id, NULL,
3416 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3417 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3418 if (err)
3419 return err;
3420 free(s->start_id);
3421 s->start_id = start_id;
3422 s->thread_args.start_id = s->start_id;
3423 } else /* 'B' */
3424 s->log_branches = !s->log_branches;
3426 if (s->thread_args.pack_fds == NULL) {
3427 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3428 if (err)
3429 return err;
3431 err = got_repo_open(&s->thread_args.repo,
3432 got_repo_get_path(s->repo), NULL,
3433 s->thread_args.pack_fds);
3434 if (err)
3435 return err;
3436 tog_free_refs();
3437 err = tog_load_refs(s->repo, 0);
3438 if (err)
3439 return err;
3440 err = got_commit_graph_open(&s->thread_args.graph,
3441 s->in_repo_path, !s->log_branches);
3442 if (err)
3443 return err;
3444 err = got_commit_graph_iter_start(s->thread_args.graph,
3445 s->start_id, s->repo, NULL, NULL);
3446 if (err)
3447 return err;
3448 free_commits(&s->commits);
3449 s->first_displayed_entry = NULL;
3450 s->last_displayed_entry = NULL;
3451 s->selected_entry = NULL;
3452 s->selected = 0;
3453 s->thread_args.log_complete = 0;
3454 s->quit = 0;
3455 s->thread_args.commits_needed = view->lines;
3456 s->matched_entry = NULL;
3457 s->search_entry = NULL;
3458 break;
3459 case 'r':
3460 view->count = 0;
3461 if (view_is_parent_view(view))
3462 view_get_split(view, &begin_y, &begin_x);
3463 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
3464 if (ref_view == NULL)
3465 return got_error_from_errno("view_open");
3466 err = open_ref_view(ref_view, s->repo);
3467 if (err) {
3468 view_close(ref_view);
3469 return err;
3471 if (view_is_parent_view(view) &&
3472 view->mode == TOG_VIEW_SPLIT_HRZN) {
3473 err = view_init_hsplit(view, begin_y);
3474 if (err)
3475 break;
3477 view->focussed = 0;
3478 ref_view->focussed = 1;
3479 ref_view->mode = view->mode;
3480 ref_view->nlines = view->lines - begin_y;
3481 if (view_is_parent_view(view)) {
3482 view_transfer_size(ref_view, view);
3483 err = view_close_child(view);
3484 if (err)
3485 return err;
3486 err = view_set_child(view, ref_view);
3487 if (err)
3488 return err;
3489 view->focus_child = 1;
3490 } else
3491 *new_view = ref_view;
3492 break;
3493 default:
3494 view->count = 0;
3495 break;
3498 return err;
3501 static const struct got_error *
3502 apply_unveil(const char *repo_path, const char *worktree_path)
3504 const struct got_error *error;
3506 #ifdef PROFILE
3507 if (unveil("gmon.out", "rwc") != 0)
3508 return got_error_from_errno2("unveil", "gmon.out");
3509 #endif
3510 if (repo_path && unveil(repo_path, "r") != 0)
3511 return got_error_from_errno2("unveil", repo_path);
3513 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3514 return got_error_from_errno2("unveil", worktree_path);
3516 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3517 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3519 error = got_privsep_unveil_exec_helpers();
3520 if (error != NULL)
3521 return error;
3523 if (unveil(NULL, NULL) != 0)
3524 return got_error_from_errno("unveil");
3526 return NULL;
3529 static void
3530 init_curses(void)
3533 * Override default signal handlers before starting ncurses.
3534 * This should prevent ncurses from installing its own
3535 * broken cleanup() signal handler.
3537 signal(SIGWINCH, tog_sigwinch);
3538 signal(SIGPIPE, tog_sigpipe);
3539 signal(SIGCONT, tog_sigcont);
3540 signal(SIGINT, tog_sigint);
3541 signal(SIGTERM, tog_sigterm);
3543 initscr();
3544 cbreak();
3545 halfdelay(1); /* Do fast refresh while initial view is loading. */
3546 noecho();
3547 nonl();
3548 intrflush(stdscr, FALSE);
3549 keypad(stdscr, TRUE);
3550 curs_set(0);
3551 if (getenv("TOG_COLORS") != NULL) {
3552 start_color();
3553 use_default_colors();
3557 static const struct got_error *
3558 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3559 struct got_repository *repo, struct got_worktree *worktree)
3561 const struct got_error *err = NULL;
3563 if (argc == 0) {
3564 *in_repo_path = strdup("/");
3565 if (*in_repo_path == NULL)
3566 return got_error_from_errno("strdup");
3567 return NULL;
3570 if (worktree) {
3571 const char *prefix = got_worktree_get_path_prefix(worktree);
3572 char *p;
3574 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3575 if (err)
3576 return err;
3577 if (asprintf(in_repo_path, "%s%s%s", prefix,
3578 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3579 p) == -1) {
3580 err = got_error_from_errno("asprintf");
3581 *in_repo_path = NULL;
3583 free(p);
3584 } else
3585 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3587 return err;
3590 static const struct got_error *
3591 cmd_log(int argc, char *argv[])
3593 const struct got_error *error;
3594 struct got_repository *repo = NULL;
3595 struct got_worktree *worktree = NULL;
3596 struct got_object_id *start_id = NULL;
3597 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3598 char *start_commit = NULL, *label = NULL;
3599 struct got_reference *ref = NULL;
3600 const char *head_ref_name = NULL;
3601 int ch, log_branches = 0;
3602 struct tog_view *view;
3603 int *pack_fds = NULL;
3605 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3606 switch (ch) {
3607 case 'b':
3608 log_branches = 1;
3609 break;
3610 case 'c':
3611 start_commit = optarg;
3612 break;
3613 case 'r':
3614 repo_path = realpath(optarg, NULL);
3615 if (repo_path == NULL)
3616 return got_error_from_errno2("realpath",
3617 optarg);
3618 break;
3619 default:
3620 usage_log();
3621 /* NOTREACHED */
3625 argc -= optind;
3626 argv += optind;
3628 if (argc > 1)
3629 usage_log();
3631 error = got_repo_pack_fds_open(&pack_fds);
3632 if (error != NULL)
3633 goto done;
3635 if (repo_path == NULL) {
3636 cwd = getcwd(NULL, 0);
3637 if (cwd == NULL)
3638 return got_error_from_errno("getcwd");
3639 error = got_worktree_open(&worktree, cwd);
3640 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3641 goto done;
3642 if (worktree)
3643 repo_path =
3644 strdup(got_worktree_get_repo_path(worktree));
3645 else
3646 repo_path = strdup(cwd);
3647 if (repo_path == NULL) {
3648 error = got_error_from_errno("strdup");
3649 goto done;
3653 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3654 if (error != NULL)
3655 goto done;
3657 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3658 repo, worktree);
3659 if (error)
3660 goto done;
3662 init_curses();
3664 error = apply_unveil(got_repo_get_path(repo),
3665 worktree ? got_worktree_get_root_path(worktree) : NULL);
3666 if (error)
3667 goto done;
3669 /* already loaded by tog_log_with_path()? */
3670 if (TAILQ_EMPTY(&tog_refs)) {
3671 error = tog_load_refs(repo, 0);
3672 if (error)
3673 goto done;
3676 if (start_commit == NULL) {
3677 error = got_repo_match_object_id(&start_id, &label,
3678 worktree ? got_worktree_get_head_ref_name(worktree) :
3679 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3680 if (error)
3681 goto done;
3682 head_ref_name = label;
3683 } else {
3684 error = got_ref_open(&ref, repo, start_commit, 0);
3685 if (error == NULL)
3686 head_ref_name = got_ref_get_name(ref);
3687 else if (error->code != GOT_ERR_NOT_REF)
3688 goto done;
3689 error = got_repo_match_object_id(&start_id, NULL,
3690 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3691 if (error)
3692 goto done;
3695 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3696 if (view == NULL) {
3697 error = got_error_from_errno("view_open");
3698 goto done;
3700 error = open_log_view(view, start_id, repo, head_ref_name,
3701 in_repo_path, log_branches);
3702 if (error)
3703 goto done;
3704 if (worktree) {
3705 /* Release work tree lock. */
3706 got_worktree_close(worktree);
3707 worktree = NULL;
3709 error = view_loop(view);
3710 done:
3711 free(in_repo_path);
3712 free(repo_path);
3713 free(cwd);
3714 free(start_id);
3715 free(label);
3716 if (ref)
3717 got_ref_close(ref);
3718 if (repo) {
3719 const struct got_error *close_err = got_repo_close(repo);
3720 if (error == NULL)
3721 error = close_err;
3723 if (worktree)
3724 got_worktree_close(worktree);
3725 if (pack_fds) {
3726 const struct got_error *pack_err =
3727 got_repo_pack_fds_close(pack_fds);
3728 if (error == NULL)
3729 error = pack_err;
3731 tog_free_refs();
3732 return error;
3735 __dead static void
3736 usage_diff(void)
3738 endwin();
3739 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3740 "[-w] object1 object2\n", getprogname());
3741 exit(1);
3744 static int
3745 match_line(const char *line, regex_t *regex, size_t nmatch,
3746 regmatch_t *regmatch)
3748 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3751 static struct tog_color *
3752 match_color(struct tog_colors *colors, const char *line)
3754 struct tog_color *tc = NULL;
3756 STAILQ_FOREACH(tc, colors, entry) {
3757 if (match_line(line, &tc->regex, 0, NULL))
3758 return tc;
3761 return NULL;
3764 static const struct got_error *
3765 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3766 WINDOW *window, int skipcol, regmatch_t *regmatch)
3768 const struct got_error *err = NULL;
3769 char *exstr = NULL;
3770 wchar_t *wline = NULL;
3771 int rme, rms, n, width, scrollx;
3772 int width0 = 0, width1 = 0, width2 = 0;
3773 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3775 *wtotal = 0;
3777 rms = regmatch->rm_so;
3778 rme = regmatch->rm_eo;
3780 err = expand_tab(&exstr, line);
3781 if (err)
3782 return err;
3784 /* Split the line into 3 segments, according to match offsets. */
3785 seg0 = strndup(exstr, rms);
3786 if (seg0 == NULL) {
3787 err = got_error_from_errno("strndup");
3788 goto done;
3790 seg1 = strndup(exstr + rms, rme - rms);
3791 if (seg1 == NULL) {
3792 err = got_error_from_errno("strndup");
3793 goto done;
3795 seg2 = strdup(exstr + rme);
3796 if (seg2 == NULL) {
3797 err = got_error_from_errno("strndup");
3798 goto done;
3801 /* draw up to matched token if we haven't scrolled past it */
3802 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3803 col_tab_align, 1);
3804 if (err)
3805 goto done;
3806 n = MAX(width0 - skipcol, 0);
3807 if (n) {
3808 free(wline);
3809 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3810 wlimit, col_tab_align, 1);
3811 if (err)
3812 goto done;
3813 waddwstr(window, &wline[scrollx]);
3814 wlimit -= width;
3815 *wtotal += width;
3818 if (wlimit > 0) {
3819 int i = 0, w = 0;
3820 size_t wlen;
3822 free(wline);
3823 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3824 col_tab_align, 1);
3825 if (err)
3826 goto done;
3827 wlen = wcslen(wline);
3828 while (i < wlen) {
3829 width = wcwidth(wline[i]);
3830 if (width == -1) {
3831 /* should not happen, tabs are expanded */
3832 err = got_error(GOT_ERR_RANGE);
3833 goto done;
3835 if (width0 + w + width > skipcol)
3836 break;
3837 w += width;
3838 i++;
3840 /* draw (visible part of) matched token (if scrolled into it) */
3841 if (width1 - w > 0) {
3842 wattron(window, A_STANDOUT);
3843 waddwstr(window, &wline[i]);
3844 wattroff(window, A_STANDOUT);
3845 wlimit -= (width1 - w);
3846 *wtotal += (width1 - w);
3850 if (wlimit > 0) { /* draw rest of line */
3851 free(wline);
3852 if (skipcol > width0 + width1) {
3853 err = format_line(&wline, &width2, &scrollx, seg2,
3854 skipcol - (width0 + width1), wlimit,
3855 col_tab_align, 1);
3856 if (err)
3857 goto done;
3858 waddwstr(window, &wline[scrollx]);
3859 } else {
3860 err = format_line(&wline, &width2, NULL, seg2, 0,
3861 wlimit, col_tab_align, 1);
3862 if (err)
3863 goto done;
3864 waddwstr(window, wline);
3866 *wtotal += width2;
3868 done:
3869 free(wline);
3870 free(exstr);
3871 free(seg0);
3872 free(seg1);
3873 free(seg2);
3874 return err;
3877 static const struct got_error *
3878 draw_file(struct tog_view *view, const char *header)
3880 struct tog_diff_view_state *s = &view->state.diff;
3881 regmatch_t *regmatch = &view->regmatch;
3882 const struct got_error *err;
3883 int nprinted = 0;
3884 char *line;
3885 size_t linesize = 0;
3886 ssize_t linelen;
3887 struct tog_color *tc;
3888 wchar_t *wline;
3889 int width;
3890 int max_lines = view->nlines;
3891 int nlines = s->nlines;
3892 off_t line_offset;
3894 line_offset = s->line_offsets[s->first_displayed_line - 1];
3895 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3896 return got_error_from_errno("fseek");
3898 werase(view->window);
3900 if (header) {
3901 if (asprintf(&line, "[%d/%d] %s",
3902 s->first_displayed_line - 1 + s->selected_line, nlines,
3903 header) == -1)
3904 return got_error_from_errno("asprintf");
3905 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3906 0, 0);
3907 free(line);
3908 if (err)
3909 return err;
3911 if (view_needs_focus_indication(view))
3912 wstandout(view->window);
3913 waddwstr(view->window, wline);
3914 free(wline);
3915 wline = NULL;
3916 if (view_needs_focus_indication(view))
3917 wstandend(view->window);
3918 if (width <= view->ncols - 1)
3919 waddch(view->window, '\n');
3921 if (max_lines <= 1)
3922 return NULL;
3923 max_lines--;
3926 s->eof = 0;
3927 view->maxx = 0;
3928 line = NULL;
3929 while (max_lines > 0 && nprinted < max_lines) {
3930 linelen = getline(&line, &linesize, s->f);
3931 if (linelen == -1) {
3932 if (feof(s->f)) {
3933 s->eof = 1;
3934 break;
3936 free(line);
3937 return got_ferror(s->f, GOT_ERR_IO);
3940 /* Set view->maxx based on full line length. */
3941 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3942 view->x ? 1 : 0);
3943 if (err) {
3944 free(line);
3945 return err;
3947 view->maxx = MAX(view->maxx, width);
3948 free(wline);
3949 wline = NULL;
3951 tc = match_color(&s->colors, line);
3952 if (tc)
3953 wattr_on(view->window,
3954 COLOR_PAIR(tc->colorpair), NULL);
3955 if (s->first_displayed_line + nprinted == s->matched_line &&
3956 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3957 err = add_matched_line(&width, line, view->ncols, 0,
3958 view->window, view->x, regmatch);
3959 if (err) {
3960 free(line);
3961 return err;
3963 } else {
3964 int skip;
3965 err = format_line(&wline, &width, &skip, line,
3966 view->x, view->ncols, 0, view->x ? 1 : 0);
3967 if (err) {
3968 free(line);
3969 return err;
3971 waddwstr(view->window, &wline[skip]);
3972 free(wline);
3973 wline = NULL;
3975 if (tc)
3976 wattr_off(view->window,
3977 COLOR_PAIR(tc->colorpair), NULL);
3978 if (width <= view->ncols - 1)
3979 waddch(view->window, '\n');
3980 nprinted++;
3982 free(line);
3983 if (nprinted >= 1)
3984 s->last_displayed_line = s->first_displayed_line +
3985 (nprinted - 1);
3986 else
3987 s->last_displayed_line = s->first_displayed_line;
3989 view_border(view);
3991 if (s->eof) {
3992 while (nprinted < view->nlines) {
3993 waddch(view->window, '\n');
3994 nprinted++;
3997 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3998 view->ncols, 0, 0);
3999 if (err) {
4000 return err;
4003 wstandout(view->window);
4004 waddwstr(view->window, wline);
4005 free(wline);
4006 wline = NULL;
4007 wstandend(view->window);
4010 return NULL;
4013 static char *
4014 get_datestr(time_t *time, char *datebuf)
4016 struct tm mytm, *tm;
4017 char *p, *s;
4019 tm = gmtime_r(time, &mytm);
4020 if (tm == NULL)
4021 return NULL;
4022 s = asctime_r(tm, datebuf);
4023 if (s == NULL)
4024 return NULL;
4025 p = strchr(s, '\n');
4026 if (p)
4027 *p = '\0';
4028 return s;
4031 static const struct got_error *
4032 get_changed_paths(struct got_pathlist_head *paths,
4033 struct got_commit_object *commit, struct got_repository *repo)
4035 const struct got_error *err = NULL;
4036 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4037 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4038 struct got_object_qid *qid;
4040 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4041 if (qid != NULL) {
4042 struct got_commit_object *pcommit;
4043 err = got_object_open_as_commit(&pcommit, repo,
4044 &qid->id);
4045 if (err)
4046 return err;
4048 tree_id1 = got_object_id_dup(
4049 got_object_commit_get_tree_id(pcommit));
4050 if (tree_id1 == NULL) {
4051 got_object_commit_close(pcommit);
4052 return got_error_from_errno("got_object_id_dup");
4054 got_object_commit_close(pcommit);
4058 if (tree_id1) {
4059 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4060 if (err)
4061 goto done;
4064 tree_id2 = got_object_commit_get_tree_id(commit);
4065 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4066 if (err)
4067 goto done;
4069 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4070 got_diff_tree_collect_changed_paths, paths, 0);
4071 done:
4072 if (tree1)
4073 got_object_tree_close(tree1);
4074 if (tree2)
4075 got_object_tree_close(tree2);
4076 free(tree_id1);
4077 return err;
4080 static const struct got_error *
4081 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
4083 off_t *p;
4085 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
4086 if (p == NULL)
4087 return got_error_from_errno("reallocarray");
4088 *line_offsets = p;
4089 (*line_offsets)[*nlines] = off;
4090 (*nlines)++;
4091 return NULL;
4094 static const struct got_error *
4095 write_commit_info(off_t **line_offsets, size_t *nlines,
4096 struct got_object_id *commit_id, struct got_reflist_head *refs,
4097 struct got_repository *repo, FILE *outfile)
4099 const struct got_error *err = NULL;
4100 char datebuf[26], *datestr;
4101 struct got_commit_object *commit;
4102 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4103 time_t committer_time;
4104 const char *author, *committer;
4105 char *refs_str = NULL;
4106 struct got_pathlist_head changed_paths;
4107 struct got_pathlist_entry *pe;
4108 off_t outoff = 0;
4109 int n;
4111 TAILQ_INIT(&changed_paths);
4113 if (refs) {
4114 err = build_refs_str(&refs_str, refs, commit_id, repo);
4115 if (err)
4116 return err;
4119 err = got_object_open_as_commit(&commit, repo, commit_id);
4120 if (err)
4121 return err;
4123 err = got_object_id_str(&id_str, commit_id);
4124 if (err) {
4125 err = got_error_from_errno("got_object_id_str");
4126 goto done;
4129 err = add_line_offset(line_offsets, nlines, 0);
4130 if (err)
4131 goto done;
4133 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4134 refs_str ? refs_str : "", refs_str ? ")" : "");
4135 if (n < 0) {
4136 err = got_error_from_errno("fprintf");
4137 goto done;
4139 outoff += n;
4140 err = add_line_offset(line_offsets, nlines, outoff);
4141 if (err)
4142 goto done;
4144 n = fprintf(outfile, "from: %s\n",
4145 got_object_commit_get_author(commit));
4146 if (n < 0) {
4147 err = got_error_from_errno("fprintf");
4148 goto done;
4150 outoff += n;
4151 err = add_line_offset(line_offsets, nlines, outoff);
4152 if (err)
4153 goto done;
4155 committer_time = got_object_commit_get_committer_time(commit);
4156 datestr = get_datestr(&committer_time, datebuf);
4157 if (datestr) {
4158 n = fprintf(outfile, "date: %s UTC\n", datestr);
4159 if (n < 0) {
4160 err = got_error_from_errno("fprintf");
4161 goto done;
4163 outoff += n;
4164 err = add_line_offset(line_offsets, nlines, outoff);
4165 if (err)
4166 goto done;
4168 author = got_object_commit_get_author(commit);
4169 committer = got_object_commit_get_committer(commit);
4170 if (strcmp(author, committer) != 0) {
4171 n = fprintf(outfile, "via: %s\n", committer);
4172 if (n < 0) {
4173 err = got_error_from_errno("fprintf");
4174 goto done;
4176 outoff += n;
4177 err = add_line_offset(line_offsets, nlines, outoff);
4178 if (err)
4179 goto done;
4181 if (got_object_commit_get_nparents(commit) > 1) {
4182 const struct got_object_id_queue *parent_ids;
4183 struct got_object_qid *qid;
4184 int pn = 1;
4185 parent_ids = got_object_commit_get_parent_ids(commit);
4186 STAILQ_FOREACH(qid, parent_ids, entry) {
4187 err = got_object_id_str(&id_str, &qid->id);
4188 if (err)
4189 goto done;
4190 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4191 if (n < 0) {
4192 err = got_error_from_errno("fprintf");
4193 goto done;
4195 outoff += n;
4196 err = add_line_offset(line_offsets, nlines, outoff);
4197 if (err)
4198 goto done;
4199 free(id_str);
4200 id_str = NULL;
4204 err = got_object_commit_get_logmsg(&logmsg, commit);
4205 if (err)
4206 goto done;
4207 s = logmsg;
4208 while ((line = strsep(&s, "\n")) != NULL) {
4209 n = fprintf(outfile, "%s\n", line);
4210 if (n < 0) {
4211 err = got_error_from_errno("fprintf");
4212 goto done;
4214 outoff += n;
4215 err = add_line_offset(line_offsets, nlines, outoff);
4216 if (err)
4217 goto done;
4220 err = get_changed_paths(&changed_paths, commit, repo);
4221 if (err)
4222 goto done;
4223 TAILQ_FOREACH(pe, &changed_paths, entry) {
4224 struct got_diff_changed_path *cp = pe->data;
4225 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4226 if (n < 0) {
4227 err = got_error_from_errno("fprintf");
4228 goto done;
4230 outoff += n;
4231 err = add_line_offset(line_offsets, nlines, outoff);
4232 if (err)
4233 goto done;
4234 free((char *)pe->path);
4235 free(pe->data);
4238 fputc('\n', outfile);
4239 outoff++;
4240 err = add_line_offset(line_offsets, nlines, outoff);
4241 done:
4242 got_pathlist_free(&changed_paths);
4243 free(id_str);
4244 free(logmsg);
4245 free(refs_str);
4246 got_object_commit_close(commit);
4247 if (err) {
4248 free(*line_offsets);
4249 *line_offsets = NULL;
4250 *nlines = 0;
4252 return err;
4255 static const struct got_error *
4256 create_diff(struct tog_diff_view_state *s)
4258 const struct got_error *err = NULL;
4259 FILE *f = NULL;
4260 int obj_type;
4262 free(s->line_offsets);
4263 s->line_offsets = malloc(sizeof(off_t));
4264 if (s->line_offsets == NULL)
4265 return got_error_from_errno("malloc");
4266 s->nlines = 0;
4268 f = got_opentemp();
4269 if (f == NULL) {
4270 err = got_error_from_errno("got_opentemp");
4271 goto done;
4273 if (s->f && fclose(s->f) == EOF) {
4274 err = got_error_from_errno("fclose");
4275 goto done;
4277 s->f = f;
4279 if (s->id1)
4280 err = got_object_get_type(&obj_type, s->repo, s->id1);
4281 else
4282 err = got_object_get_type(&obj_type, s->repo, s->id2);
4283 if (err)
4284 goto done;
4286 switch (obj_type) {
4287 case GOT_OBJ_TYPE_BLOB:
4288 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
4289 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4290 s->label1, s->label2, tog_diff_algo, s->diff_context,
4291 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4292 break;
4293 case GOT_OBJ_TYPE_TREE:
4294 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
4295 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4296 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4297 s->force_text_diff, s->repo, s->f);
4298 break;
4299 case GOT_OBJ_TYPE_COMMIT: {
4300 const struct got_object_id_queue *parent_ids;
4301 struct got_object_qid *pid;
4302 struct got_commit_object *commit2;
4303 struct got_reflist_head *refs;
4305 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4306 if (err)
4307 goto done;
4308 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4309 /* Show commit info if we're diffing to a parent/root commit. */
4310 if (s->id1 == NULL) {
4311 err = write_commit_info(&s->line_offsets, &s->nlines,
4312 s->id2, refs, s->repo, s->f);
4313 if (err)
4314 goto done;
4315 } else {
4316 parent_ids = got_object_commit_get_parent_ids(commit2);
4317 STAILQ_FOREACH(pid, parent_ids, entry) {
4318 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4319 err = write_commit_info(
4320 &s->line_offsets, &s->nlines,
4321 s->id2, refs, s->repo, s->f);
4322 if (err)
4323 goto done;
4324 break;
4328 got_object_commit_close(commit2);
4330 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4331 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4332 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4333 s->force_text_diff, s->repo, s->f);
4334 break;
4336 default:
4337 err = got_error(GOT_ERR_OBJ_TYPE);
4338 break;
4340 if (err)
4341 goto done;
4342 done:
4343 if (s->f && fflush(s->f) != 0 && err == NULL)
4344 err = got_error_from_errno("fflush");
4345 return err;
4348 static void
4349 diff_view_indicate_progress(struct tog_view *view)
4351 mvwaddstr(view->window, 0, 0, "diffing...");
4352 update_panels();
4353 doupdate();
4356 static const struct got_error *
4357 search_start_diff_view(struct tog_view *view)
4359 struct tog_diff_view_state *s = &view->state.diff;
4361 s->matched_line = 0;
4362 return NULL;
4365 static const struct got_error *
4366 search_next_diff_view(struct tog_view *view)
4368 struct tog_diff_view_state *s = &view->state.diff;
4369 const struct got_error *err = NULL;
4370 int lineno;
4371 char *line = NULL;
4372 size_t linesize = 0;
4373 ssize_t linelen;
4375 if (!view->searching) {
4376 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4377 return NULL;
4380 if (s->matched_line) {
4381 if (view->searching == TOG_SEARCH_FORWARD)
4382 lineno = s->matched_line + 1;
4383 else
4384 lineno = s->matched_line - 1;
4385 } else
4386 lineno = s->first_displayed_line;
4388 while (1) {
4389 off_t offset;
4391 if (lineno <= 0 || lineno > s->nlines) {
4392 if (s->matched_line == 0) {
4393 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4394 break;
4397 if (view->searching == TOG_SEARCH_FORWARD)
4398 lineno = 1;
4399 else
4400 lineno = s->nlines;
4403 offset = s->line_offsets[lineno - 1];
4404 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4405 free(line);
4406 return got_error_from_errno("fseeko");
4408 linelen = getline(&line, &linesize, s->f);
4409 if (linelen != -1) {
4410 char *exstr;
4411 err = expand_tab(&exstr, line);
4412 if (err)
4413 break;
4414 if (match_line(exstr, &view->regex, 1,
4415 &view->regmatch)) {
4416 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4417 s->matched_line = lineno;
4418 free(exstr);
4419 break;
4421 free(exstr);
4423 if (view->searching == TOG_SEARCH_FORWARD)
4424 lineno++;
4425 else
4426 lineno--;
4428 free(line);
4430 if (s->matched_line) {
4431 s->first_displayed_line = s->matched_line;
4432 s->selected_line = 1;
4435 return err;
4438 static const struct got_error *
4439 close_diff_view(struct tog_view *view)
4441 const struct got_error *err = NULL;
4442 struct tog_diff_view_state *s = &view->state.diff;
4444 free(s->id1);
4445 s->id1 = NULL;
4446 free(s->id2);
4447 s->id2 = NULL;
4448 if (s->f && fclose(s->f) == EOF)
4449 err = got_error_from_errno("fclose");
4450 s->f = NULL;
4451 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4452 err = got_error_from_errno("fclose");
4453 s->f1 = NULL;
4454 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4455 err = got_error_from_errno("fclose");
4456 s->f2 = NULL;
4457 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4458 err = got_error_from_errno("close");
4459 s->fd1 = -1;
4460 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4461 err = got_error_from_errno("close");
4462 s->fd2 = -1;
4463 free_colors(&s->colors);
4464 free(s->line_offsets);
4465 s->line_offsets = NULL;
4466 s->nlines = 0;
4467 return err;
4470 static const struct got_error *
4471 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4472 struct got_object_id *id2, const char *label1, const char *label2,
4473 int diff_context, int ignore_whitespace, int force_text_diff,
4474 struct tog_view *parent_view, struct got_repository *repo)
4476 const struct got_error *err;
4477 struct tog_diff_view_state *s = &view->state.diff;
4479 memset(s, 0, sizeof(*s));
4480 s->fd1 = -1;
4481 s->fd2 = -1;
4483 if (id1 != NULL && id2 != NULL) {
4484 int type1, type2;
4485 err = got_object_get_type(&type1, repo, id1);
4486 if (err)
4487 return err;
4488 err = got_object_get_type(&type2, repo, id2);
4489 if (err)
4490 return err;
4492 if (type1 != type2)
4493 return got_error(GOT_ERR_OBJ_TYPE);
4495 s->first_displayed_line = 1;
4496 s->last_displayed_line = view->nlines;
4497 s->selected_line = 1;
4498 s->repo = repo;
4499 s->id1 = id1;
4500 s->id2 = id2;
4501 s->label1 = label1;
4502 s->label2 = label2;
4504 if (id1) {
4505 s->id1 = got_object_id_dup(id1);
4506 if (s->id1 == NULL)
4507 return got_error_from_errno("got_object_id_dup");
4508 } else
4509 s->id1 = NULL;
4511 s->id2 = got_object_id_dup(id2);
4512 if (s->id2 == NULL) {
4513 err = got_error_from_errno("got_object_id_dup");
4514 goto done;
4517 s->f1 = got_opentemp();
4518 if (s->f1 == NULL) {
4519 err = got_error_from_errno("got_opentemp");
4520 goto done;
4523 s->f2 = got_opentemp();
4524 if (s->f2 == NULL) {
4525 err = got_error_from_errno("got_opentemp");
4526 goto done;
4529 s->fd1 = got_opentempfd();
4530 if (s->fd1 == -1) {
4531 err = got_error_from_errno("got_opentempfd");
4532 goto done;
4535 s->fd2 = got_opentempfd();
4536 if (s->fd2 == -1) {
4537 err = got_error_from_errno("got_opentempfd");
4538 goto done;
4541 s->first_displayed_line = 1;
4542 s->last_displayed_line = view->nlines;
4543 s->diff_context = diff_context;
4544 s->ignore_whitespace = ignore_whitespace;
4545 s->force_text_diff = force_text_diff;
4546 s->parent_view = parent_view;
4547 s->repo = repo;
4549 STAILQ_INIT(&s->colors);
4550 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4551 err = add_color(&s->colors,
4552 "^-", TOG_COLOR_DIFF_MINUS,
4553 get_color_value("TOG_COLOR_DIFF_MINUS"));
4554 if (err)
4555 goto done;
4556 err = add_color(&s->colors, "^\\+",
4557 TOG_COLOR_DIFF_PLUS,
4558 get_color_value("TOG_COLOR_DIFF_PLUS"));
4559 if (err)
4560 goto done;
4561 err = add_color(&s->colors,
4562 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4563 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4564 if (err)
4565 goto done;
4567 err = add_color(&s->colors,
4568 "^(commit [0-9a-f]|parent [0-9]|"
4569 "(blob|file|tree|commit) [-+] |"
4570 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4571 get_color_value("TOG_COLOR_DIFF_META"));
4572 if (err)
4573 goto done;
4575 err = add_color(&s->colors,
4576 "^(from|via): ", TOG_COLOR_AUTHOR,
4577 get_color_value("TOG_COLOR_AUTHOR"));
4578 if (err)
4579 goto done;
4581 err = add_color(&s->colors,
4582 "^date: ", TOG_COLOR_DATE,
4583 get_color_value("TOG_COLOR_DATE"));
4584 if (err)
4585 goto done;
4588 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4589 view_is_splitscreen(view))
4590 show_log_view(parent_view); /* draw border */
4591 diff_view_indicate_progress(view);
4593 err = create_diff(s);
4595 view->show = show_diff_view;
4596 view->input = input_diff_view;
4597 view->reset = reset_diff_view;
4598 view->close = close_diff_view;
4599 view->search_start = search_start_diff_view;
4600 view->search_next = search_next_diff_view;
4601 done:
4602 if (err)
4603 close_diff_view(view);
4604 return err;
4607 static const struct got_error *
4608 show_diff_view(struct tog_view *view)
4610 const struct got_error *err;
4611 struct tog_diff_view_state *s = &view->state.diff;
4612 char *id_str1 = NULL, *id_str2, *header;
4613 const char *label1, *label2;
4615 if (s->id1) {
4616 err = got_object_id_str(&id_str1, s->id1);
4617 if (err)
4618 return err;
4619 label1 = s->label1 ? : id_str1;
4620 } else
4621 label1 = "/dev/null";
4623 err = got_object_id_str(&id_str2, s->id2);
4624 if (err)
4625 return err;
4626 label2 = s->label2 ? : id_str2;
4628 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4629 err = got_error_from_errno("asprintf");
4630 free(id_str1);
4631 free(id_str2);
4632 return err;
4634 free(id_str1);
4635 free(id_str2);
4637 err = draw_file(view, header);
4638 free(header);
4639 return err;
4642 static const struct got_error *
4643 set_selected_commit(struct tog_diff_view_state *s,
4644 struct commit_queue_entry *entry)
4646 const struct got_error *err;
4647 const struct got_object_id_queue *parent_ids;
4648 struct got_commit_object *selected_commit;
4649 struct got_object_qid *pid;
4651 free(s->id2);
4652 s->id2 = got_object_id_dup(entry->id);
4653 if (s->id2 == NULL)
4654 return got_error_from_errno("got_object_id_dup");
4656 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4657 if (err)
4658 return err;
4659 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4660 free(s->id1);
4661 pid = STAILQ_FIRST(parent_ids);
4662 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4663 got_object_commit_close(selected_commit);
4664 return NULL;
4667 static const struct got_error *
4668 reset_diff_view(struct tog_view *view)
4670 struct tog_diff_view_state *s = &view->state.diff;
4672 view->count = 0;
4673 wclear(view->window);
4674 s->first_displayed_line = 1;
4675 s->last_displayed_line = view->nlines;
4676 s->matched_line = 0;
4677 diff_view_indicate_progress(view);
4678 return create_diff(s);
4681 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4682 int, int, int);
4683 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4684 int, int);
4686 static const struct got_error *
4687 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4689 const struct got_error *err = NULL;
4690 struct tog_diff_view_state *s = &view->state.diff;
4691 struct tog_log_view_state *ls;
4692 struct commit_queue_entry *old_selected_entry;
4693 char *line = NULL;
4694 size_t linesize = 0;
4695 ssize_t linelen;
4696 int i, nscroll = view->nlines - 1, up = 0;
4698 switch (ch) {
4699 case '0':
4700 view->x = 0;
4701 break;
4702 case '$':
4703 view->x = MAX(view->maxx - view->ncols / 3, 0);
4704 view->count = 0;
4705 break;
4706 case KEY_RIGHT:
4707 case 'l':
4708 if (view->x + view->ncols / 3 < view->maxx)
4709 view->x += 2; /* move two columns right */
4710 else
4711 view->count = 0;
4712 break;
4713 case KEY_LEFT:
4714 case 'h':
4715 view->x -= MIN(view->x, 2); /* move two columns back */
4716 if (view->x <= 0)
4717 view->count = 0;
4718 break;
4719 case 'a':
4720 case 'w':
4721 if (ch == 'a')
4722 s->force_text_diff = !s->force_text_diff;
4723 if (ch == 'w')
4724 s->ignore_whitespace = !s->ignore_whitespace;
4725 err = reset_diff_view(view);
4726 break;
4727 case 'g':
4728 case KEY_HOME:
4729 s->first_displayed_line = 1;
4730 view->count = 0;
4731 break;
4732 case 'G':
4733 case KEY_END:
4734 view->count = 0;
4735 if (s->eof)
4736 break;
4738 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4739 s->eof = 1;
4740 break;
4741 case 'k':
4742 case KEY_UP:
4743 case CTRL('p'):
4744 if (s->first_displayed_line > 1)
4745 s->first_displayed_line--;
4746 else
4747 view->count = 0;
4748 break;
4749 case CTRL('u'):
4750 case 'u':
4751 nscroll /= 2;
4752 /* FALL THROUGH */
4753 case KEY_PPAGE:
4754 case CTRL('b'):
4755 case 'b':
4756 if (s->first_displayed_line == 1) {
4757 view->count = 0;
4758 break;
4760 i = 0;
4761 while (i++ < nscroll && s->first_displayed_line > 1)
4762 s->first_displayed_line--;
4763 break;
4764 case 'j':
4765 case KEY_DOWN:
4766 case CTRL('n'):
4767 if (!s->eof)
4768 s->first_displayed_line++;
4769 else
4770 view->count = 0;
4771 break;
4772 case CTRL('d'):
4773 case 'd':
4774 nscroll /= 2;
4775 /* FALL THROUGH */
4776 case KEY_NPAGE:
4777 case CTRL('f'):
4778 case 'f':
4779 case ' ':
4780 if (s->eof) {
4781 view->count = 0;
4782 break;
4784 i = 0;
4785 while (!s->eof && i++ < nscroll) {
4786 linelen = getline(&line, &linesize, s->f);
4787 s->first_displayed_line++;
4788 if (linelen == -1) {
4789 if (feof(s->f)) {
4790 s->eof = 1;
4791 } else
4792 err = got_ferror(s->f, GOT_ERR_IO);
4793 break;
4796 free(line);
4797 break;
4798 case '[':
4799 if (s->diff_context > 0) {
4800 s->diff_context--;
4801 s->matched_line = 0;
4802 diff_view_indicate_progress(view);
4803 err = create_diff(s);
4804 if (s->first_displayed_line + view->nlines - 1 >
4805 s->nlines) {
4806 s->first_displayed_line = 1;
4807 s->last_displayed_line = view->nlines;
4809 } else
4810 view->count = 0;
4811 break;
4812 case ']':
4813 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4814 s->diff_context++;
4815 s->matched_line = 0;
4816 diff_view_indicate_progress(view);
4817 err = create_diff(s);
4818 } else
4819 view->count = 0;
4820 break;
4821 case '<':
4822 case ',':
4823 up = 1;
4824 /* FALL THROUGH */
4825 case '>':
4826 case '.':
4827 if (s->parent_view == NULL) {
4828 view->count = 0;
4829 break;
4831 s->parent_view->count = view->count;
4833 if (s->parent_view->type == TOG_VIEW_LOG) {
4834 ls = &s->parent_view->state.log;
4835 old_selected_entry = ls->selected_entry;
4837 err = input_log_view(NULL, s->parent_view,
4838 up ? KEY_UP : KEY_DOWN);
4839 if (err)
4840 break;
4841 view->count = s->parent_view->count;
4843 if (old_selected_entry == ls->selected_entry)
4844 break;
4846 err = set_selected_commit(s, ls->selected_entry);
4847 if (err)
4848 break;
4849 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4850 struct tog_blame_view_state *bs;
4851 struct got_object_id *id, *prev_id;
4853 bs = &s->parent_view->state.blame;
4854 prev_id = get_annotation_for_line(bs->blame.lines,
4855 bs->blame.nlines, bs->last_diffed_line);
4857 err = input_blame_view(&view, s->parent_view,
4858 up ? KEY_UP : KEY_DOWN);
4859 if (err)
4860 break;
4861 view->count = s->parent_view->count;
4863 if (prev_id == NULL)
4864 break;
4865 id = get_selected_commit_id(bs->blame.lines,
4866 bs->blame.nlines, bs->first_displayed_line,
4867 bs->selected_line);
4868 if (id == NULL)
4869 break;
4871 if (!got_object_id_cmp(prev_id, id))
4872 break;
4874 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
4875 if (err)
4876 break;
4878 s->first_displayed_line = 1;
4879 s->last_displayed_line = view->nlines;
4880 s->matched_line = 0;
4881 view->x = 0;
4883 diff_view_indicate_progress(view);
4884 err = create_diff(s);
4885 break;
4886 default:
4887 view->count = 0;
4888 break;
4891 return err;
4894 static const struct got_error *
4895 cmd_diff(int argc, char *argv[])
4897 const struct got_error *error = NULL;
4898 struct got_repository *repo = NULL;
4899 struct got_worktree *worktree = NULL;
4900 struct got_object_id *id1 = NULL, *id2 = NULL;
4901 char *repo_path = NULL, *cwd = NULL;
4902 char *id_str1 = NULL, *id_str2 = NULL;
4903 char *label1 = NULL, *label2 = NULL;
4904 int diff_context = 3, ignore_whitespace = 0;
4905 int ch, force_text_diff = 0;
4906 const char *errstr;
4907 struct tog_view *view;
4908 int *pack_fds = NULL;
4910 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4911 switch (ch) {
4912 case 'a':
4913 force_text_diff = 1;
4914 break;
4915 case 'C':
4916 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4917 &errstr);
4918 if (errstr != NULL)
4919 errx(1, "number of context lines is %s: %s",
4920 errstr, errstr);
4921 break;
4922 case 'r':
4923 repo_path = realpath(optarg, NULL);
4924 if (repo_path == NULL)
4925 return got_error_from_errno2("realpath",
4926 optarg);
4927 got_path_strip_trailing_slashes(repo_path);
4928 break;
4929 case 'w':
4930 ignore_whitespace = 1;
4931 break;
4932 default:
4933 usage_diff();
4934 /* NOTREACHED */
4938 argc -= optind;
4939 argv += optind;
4941 if (argc == 0) {
4942 usage_diff(); /* TODO show local worktree changes */
4943 } else if (argc == 2) {
4944 id_str1 = argv[0];
4945 id_str2 = argv[1];
4946 } else
4947 usage_diff();
4949 error = got_repo_pack_fds_open(&pack_fds);
4950 if (error)
4951 goto done;
4953 if (repo_path == NULL) {
4954 cwd = getcwd(NULL, 0);
4955 if (cwd == NULL)
4956 return got_error_from_errno("getcwd");
4957 error = got_worktree_open(&worktree, cwd);
4958 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4959 goto done;
4960 if (worktree)
4961 repo_path =
4962 strdup(got_worktree_get_repo_path(worktree));
4963 else
4964 repo_path = strdup(cwd);
4965 if (repo_path == NULL) {
4966 error = got_error_from_errno("strdup");
4967 goto done;
4971 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4972 if (error)
4973 goto done;
4975 init_curses();
4977 error = apply_unveil(got_repo_get_path(repo), NULL);
4978 if (error)
4979 goto done;
4981 error = tog_load_refs(repo, 0);
4982 if (error)
4983 goto done;
4985 error = got_repo_match_object_id(&id1, &label1, id_str1,
4986 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4987 if (error)
4988 goto done;
4990 error = got_repo_match_object_id(&id2, &label2, id_str2,
4991 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4992 if (error)
4993 goto done;
4995 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4996 if (view == NULL) {
4997 error = got_error_from_errno("view_open");
4998 goto done;
5000 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5001 ignore_whitespace, force_text_diff, NULL, repo);
5002 if (error)
5003 goto done;
5004 error = view_loop(view);
5005 done:
5006 free(label1);
5007 free(label2);
5008 free(repo_path);
5009 free(cwd);
5010 if (repo) {
5011 const struct got_error *close_err = got_repo_close(repo);
5012 if (error == NULL)
5013 error = close_err;
5015 if (worktree)
5016 got_worktree_close(worktree);
5017 if (pack_fds) {
5018 const struct got_error *pack_err =
5019 got_repo_pack_fds_close(pack_fds);
5020 if (error == NULL)
5021 error = pack_err;
5023 tog_free_refs();
5024 return error;
5027 __dead static void
5028 usage_blame(void)
5030 endwin();
5031 fprintf(stderr,
5032 "usage: %s blame [-c commit] [-r repository-path] path\n",
5033 getprogname());
5034 exit(1);
5037 struct tog_blame_line {
5038 int annotated;
5039 struct got_object_id *id;
5042 static const struct got_error *
5043 draw_blame(struct tog_view *view)
5045 struct tog_blame_view_state *s = &view->state.blame;
5046 struct tog_blame *blame = &s->blame;
5047 regmatch_t *regmatch = &view->regmatch;
5048 const struct got_error *err;
5049 int lineno = 0, nprinted = 0;
5050 char *line = NULL;
5051 size_t linesize = 0;
5052 ssize_t linelen;
5053 wchar_t *wline;
5054 int width;
5055 struct tog_blame_line *blame_line;
5056 struct got_object_id *prev_id = NULL;
5057 char *id_str;
5058 struct tog_color *tc;
5060 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5061 if (err)
5062 return err;
5064 rewind(blame->f);
5065 werase(view->window);
5067 if (asprintf(&line, "commit %s", id_str) == -1) {
5068 err = got_error_from_errno("asprintf");
5069 free(id_str);
5070 return err;
5073 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5074 free(line);
5075 line = NULL;
5076 if (err)
5077 return err;
5078 if (view_needs_focus_indication(view))
5079 wstandout(view->window);
5080 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5081 if (tc)
5082 wattr_on(view->window,
5083 COLOR_PAIR(tc->colorpair), NULL);
5084 waddwstr(view->window, wline);
5085 if (tc)
5086 wattr_off(view->window,
5087 COLOR_PAIR(tc->colorpair), NULL);
5088 if (view_needs_focus_indication(view))
5089 wstandend(view->window);
5090 free(wline);
5091 wline = NULL;
5092 if (width < view->ncols - 1)
5093 waddch(view->window, '\n');
5095 if (asprintf(&line, "[%d/%d] %s%s",
5096 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5097 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5098 free(id_str);
5099 return got_error_from_errno("asprintf");
5101 free(id_str);
5102 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5103 free(line);
5104 line = NULL;
5105 if (err)
5106 return err;
5107 waddwstr(view->window, wline);
5108 free(wline);
5109 wline = NULL;
5110 if (width < view->ncols - 1)
5111 waddch(view->window, '\n');
5113 s->eof = 0;
5114 view->maxx = 0;
5115 while (nprinted < view->nlines - 2) {
5116 linelen = getline(&line, &linesize, blame->f);
5117 if (linelen == -1) {
5118 if (feof(blame->f)) {
5119 s->eof = 1;
5120 break;
5122 free(line);
5123 return got_ferror(blame->f, GOT_ERR_IO);
5125 if (++lineno < s->first_displayed_line)
5126 continue;
5128 /* Set view->maxx based on full line length. */
5129 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5130 if (err) {
5131 free(line);
5132 return err;
5134 free(wline);
5135 wline = NULL;
5136 view->maxx = MAX(view->maxx, width);
5138 if (nprinted == s->selected_line - 1)
5139 wstandout(view->window);
5141 if (blame->nlines > 0) {
5142 blame_line = &blame->lines[lineno - 1];
5143 if (blame_line->annotated && prev_id &&
5144 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5145 !(nprinted == s->selected_line - 1)) {
5146 waddstr(view->window, " ");
5147 } else if (blame_line->annotated) {
5148 char *id_str;
5149 err = got_object_id_str(&id_str,
5150 blame_line->id);
5151 if (err) {
5152 free(line);
5153 return err;
5155 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5156 if (tc)
5157 wattr_on(view->window,
5158 COLOR_PAIR(tc->colorpair), NULL);
5159 wprintw(view->window, "%.8s", id_str);
5160 if (tc)
5161 wattr_off(view->window,
5162 COLOR_PAIR(tc->colorpair), NULL);
5163 free(id_str);
5164 prev_id = blame_line->id;
5165 } else {
5166 waddstr(view->window, "........");
5167 prev_id = NULL;
5169 } else {
5170 waddstr(view->window, "........");
5171 prev_id = NULL;
5174 if (nprinted == s->selected_line - 1)
5175 wstandend(view->window);
5176 waddstr(view->window, " ");
5178 if (view->ncols <= 9) {
5179 width = 9;
5180 } else if (s->first_displayed_line + nprinted ==
5181 s->matched_line &&
5182 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5183 err = add_matched_line(&width, line, view->ncols - 9, 9,
5184 view->window, view->x, regmatch);
5185 if (err) {
5186 free(line);
5187 return err;
5189 width += 9;
5190 } else {
5191 int skip;
5192 err = format_line(&wline, &width, &skip, line,
5193 view->x, view->ncols - 9, 9, 1);
5194 if (err) {
5195 free(line);
5196 return err;
5198 waddwstr(view->window, &wline[skip]);
5199 width += 9;
5200 free(wline);
5201 wline = NULL;
5204 if (width <= view->ncols - 1)
5205 waddch(view->window, '\n');
5206 if (++nprinted == 1)
5207 s->first_displayed_line = lineno;
5209 free(line);
5210 s->last_displayed_line = lineno;
5212 view_border(view);
5214 return NULL;
5217 static const struct got_error *
5218 blame_cb(void *arg, int nlines, int lineno,
5219 struct got_commit_object *commit, struct got_object_id *id)
5221 const struct got_error *err = NULL;
5222 struct tog_blame_cb_args *a = arg;
5223 struct tog_blame_line *line;
5224 int errcode;
5226 if (nlines != a->nlines ||
5227 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5228 return got_error(GOT_ERR_RANGE);
5230 errcode = pthread_mutex_lock(&tog_mutex);
5231 if (errcode)
5232 return got_error_set_errno(errcode, "pthread_mutex_lock");
5234 if (*a->quit) { /* user has quit the blame view */
5235 err = got_error(GOT_ERR_ITER_COMPLETED);
5236 goto done;
5239 if (lineno == -1)
5240 goto done; /* no change in this commit */
5242 line = &a->lines[lineno - 1];
5243 if (line->annotated)
5244 goto done;
5246 line->id = got_object_id_dup(id);
5247 if (line->id == NULL) {
5248 err = got_error_from_errno("got_object_id_dup");
5249 goto done;
5251 line->annotated = 1;
5252 done:
5253 errcode = pthread_mutex_unlock(&tog_mutex);
5254 if (errcode)
5255 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5256 return err;
5259 static void *
5260 blame_thread(void *arg)
5262 const struct got_error *err, *close_err;
5263 struct tog_blame_thread_args *ta = arg;
5264 struct tog_blame_cb_args *a = ta->cb_args;
5265 int errcode, fd1 = -1, fd2 = -1;
5266 FILE *f1 = NULL, *f2 = NULL;
5268 fd1 = got_opentempfd();
5269 if (fd1 == -1)
5270 return (void *)got_error_from_errno("got_opentempfd");
5272 fd2 = got_opentempfd();
5273 if (fd2 == -1) {
5274 err = got_error_from_errno("got_opentempfd");
5275 goto done;
5278 f1 = got_opentemp();
5279 if (f1 == NULL) {
5280 err = (void *)got_error_from_errno("got_opentemp");
5281 goto done;
5283 f2 = got_opentemp();
5284 if (f2 == NULL) {
5285 err = (void *)got_error_from_errno("got_opentemp");
5286 goto done;
5289 err = block_signals_used_by_main_thread();
5290 if (err)
5291 goto done;
5293 err = got_blame(ta->path, a->commit_id, ta->repo,
5294 tog_diff_algo, blame_cb, ta->cb_args,
5295 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5296 if (err && err->code == GOT_ERR_CANCELLED)
5297 err = NULL;
5299 errcode = pthread_mutex_lock(&tog_mutex);
5300 if (errcode) {
5301 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5302 goto done;
5305 close_err = got_repo_close(ta->repo);
5306 if (err == NULL)
5307 err = close_err;
5308 ta->repo = NULL;
5309 *ta->complete = 1;
5311 errcode = pthread_mutex_unlock(&tog_mutex);
5312 if (errcode && err == NULL)
5313 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5315 done:
5316 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5317 err = got_error_from_errno("close");
5318 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5319 err = got_error_from_errno("close");
5320 if (f1 && fclose(f1) == EOF && err == NULL)
5321 err = got_error_from_errno("fclose");
5322 if (f2 && fclose(f2) == EOF && err == NULL)
5323 err = got_error_from_errno("fclose");
5325 return (void *)err;
5328 static struct got_object_id *
5329 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5330 int first_displayed_line, int selected_line)
5332 struct tog_blame_line *line;
5334 if (nlines <= 0)
5335 return NULL;
5337 line = &lines[first_displayed_line - 1 + selected_line - 1];
5338 if (!line->annotated)
5339 return NULL;
5341 return line->id;
5344 static struct got_object_id *
5345 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5346 int lineno)
5348 struct tog_blame_line *line;
5350 if (nlines <= 0 || lineno >= nlines)
5351 return NULL;
5353 line = &lines[lineno - 1];
5354 if (!line->annotated)
5355 return NULL;
5357 return line->id;
5360 static const struct got_error *
5361 stop_blame(struct tog_blame *blame)
5363 const struct got_error *err = NULL;
5364 int i;
5366 if (blame->thread) {
5367 int errcode;
5368 errcode = pthread_mutex_unlock(&tog_mutex);
5369 if (errcode)
5370 return got_error_set_errno(errcode,
5371 "pthread_mutex_unlock");
5372 errcode = pthread_join(blame->thread, (void **)&err);
5373 if (errcode)
5374 return got_error_set_errno(errcode, "pthread_join");
5375 errcode = pthread_mutex_lock(&tog_mutex);
5376 if (errcode)
5377 return got_error_set_errno(errcode,
5378 "pthread_mutex_lock");
5379 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5380 err = NULL;
5381 blame->thread = 0; //NULL;
5383 if (blame->thread_args.repo) {
5384 const struct got_error *close_err;
5385 close_err = got_repo_close(blame->thread_args.repo);
5386 if (err == NULL)
5387 err = close_err;
5388 blame->thread_args.repo = NULL;
5390 if (blame->f) {
5391 if (fclose(blame->f) == EOF && err == NULL)
5392 err = got_error_from_errno("fclose");
5393 blame->f = NULL;
5395 if (blame->lines) {
5396 for (i = 0; i < blame->nlines; i++)
5397 free(blame->lines[i].id);
5398 free(blame->lines);
5399 blame->lines = NULL;
5401 free(blame->cb_args.commit_id);
5402 blame->cb_args.commit_id = NULL;
5403 if (blame->pack_fds) {
5404 const struct got_error *pack_err =
5405 got_repo_pack_fds_close(blame->pack_fds);
5406 if (err == NULL)
5407 err = pack_err;
5408 blame->pack_fds = NULL;
5410 return err;
5413 static const struct got_error *
5414 cancel_blame_view(void *arg)
5416 const struct got_error *err = NULL;
5417 int *done = arg;
5418 int errcode;
5420 errcode = pthread_mutex_lock(&tog_mutex);
5421 if (errcode)
5422 return got_error_set_errno(errcode,
5423 "pthread_mutex_unlock");
5425 if (*done)
5426 err = got_error(GOT_ERR_CANCELLED);
5428 errcode = pthread_mutex_unlock(&tog_mutex);
5429 if (errcode)
5430 return got_error_set_errno(errcode,
5431 "pthread_mutex_lock");
5433 return err;
5436 static const struct got_error *
5437 run_blame(struct tog_view *view)
5439 struct tog_blame_view_state *s = &view->state.blame;
5440 struct tog_blame *blame = &s->blame;
5441 const struct got_error *err = NULL;
5442 struct got_commit_object *commit = NULL;
5443 struct got_blob_object *blob = NULL;
5444 struct got_repository *thread_repo = NULL;
5445 struct got_object_id *obj_id = NULL;
5446 int obj_type, fd = -1;
5447 int *pack_fds = NULL;
5449 err = got_object_open_as_commit(&commit, s->repo,
5450 &s->blamed_commit->id);
5451 if (err)
5452 return err;
5454 fd = got_opentempfd();
5455 if (fd == -1) {
5456 err = got_error_from_errno("got_opentempfd");
5457 goto done;
5460 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5461 if (err)
5462 goto done;
5464 err = got_object_get_type(&obj_type, s->repo, obj_id);
5465 if (err)
5466 goto done;
5468 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5469 err = got_error(GOT_ERR_OBJ_TYPE);
5470 goto done;
5473 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5474 if (err)
5475 goto done;
5476 blame->f = got_opentemp();
5477 if (blame->f == NULL) {
5478 err = got_error_from_errno("got_opentemp");
5479 goto done;
5481 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5482 &blame->line_offsets, blame->f, blob);
5483 if (err)
5484 goto done;
5485 if (blame->nlines == 0) {
5486 s->blame_complete = 1;
5487 goto done;
5490 /* Don't include \n at EOF in the blame line count. */
5491 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5492 blame->nlines--;
5494 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5495 if (blame->lines == NULL) {
5496 err = got_error_from_errno("calloc");
5497 goto done;
5500 err = got_repo_pack_fds_open(&pack_fds);
5501 if (err)
5502 goto done;
5503 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5504 pack_fds);
5505 if (err)
5506 goto done;
5508 blame->pack_fds = pack_fds;
5509 blame->cb_args.view = view;
5510 blame->cb_args.lines = blame->lines;
5511 blame->cb_args.nlines = blame->nlines;
5512 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5513 if (blame->cb_args.commit_id == NULL) {
5514 err = got_error_from_errno("got_object_id_dup");
5515 goto done;
5517 blame->cb_args.quit = &s->done;
5519 blame->thread_args.path = s->path;
5520 blame->thread_args.repo = thread_repo;
5521 blame->thread_args.cb_args = &blame->cb_args;
5522 blame->thread_args.complete = &s->blame_complete;
5523 blame->thread_args.cancel_cb = cancel_blame_view;
5524 blame->thread_args.cancel_arg = &s->done;
5525 s->blame_complete = 0;
5527 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5528 s->first_displayed_line = 1;
5529 s->last_displayed_line = view->nlines;
5530 s->selected_line = 1;
5532 s->matched_line = 0;
5534 done:
5535 if (commit)
5536 got_object_commit_close(commit);
5537 if (fd != -1 && close(fd) == -1 && err == NULL)
5538 err = got_error_from_errno("close");
5539 if (blob)
5540 got_object_blob_close(blob);
5541 free(obj_id);
5542 if (err)
5543 stop_blame(blame);
5544 return err;
5547 static const struct got_error *
5548 open_blame_view(struct tog_view *view, char *path,
5549 struct got_object_id *commit_id, struct got_repository *repo)
5551 const struct got_error *err = NULL;
5552 struct tog_blame_view_state *s = &view->state.blame;
5554 STAILQ_INIT(&s->blamed_commits);
5556 s->path = strdup(path);
5557 if (s->path == NULL)
5558 return got_error_from_errno("strdup");
5560 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5561 if (err) {
5562 free(s->path);
5563 return err;
5566 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5567 s->first_displayed_line = 1;
5568 s->last_displayed_line = view->nlines;
5569 s->selected_line = 1;
5570 s->blame_complete = 0;
5571 s->repo = repo;
5572 s->commit_id = commit_id;
5573 memset(&s->blame, 0, sizeof(s->blame));
5575 STAILQ_INIT(&s->colors);
5576 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5577 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5578 get_color_value("TOG_COLOR_COMMIT"));
5579 if (err)
5580 return err;
5583 view->show = show_blame_view;
5584 view->input = input_blame_view;
5585 view->reset = reset_blame_view;
5586 view->close = close_blame_view;
5587 view->search_start = search_start_blame_view;
5588 view->search_next = search_next_blame_view;
5590 return run_blame(view);
5593 static const struct got_error *
5594 close_blame_view(struct tog_view *view)
5596 const struct got_error *err = NULL;
5597 struct tog_blame_view_state *s = &view->state.blame;
5599 if (s->blame.thread)
5600 err = stop_blame(&s->blame);
5602 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5603 struct got_object_qid *blamed_commit;
5604 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5605 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5606 got_object_qid_free(blamed_commit);
5609 free(s->path);
5610 free_colors(&s->colors);
5611 return err;
5614 static const struct got_error *
5615 search_start_blame_view(struct tog_view *view)
5617 struct tog_blame_view_state *s = &view->state.blame;
5619 s->matched_line = 0;
5620 return NULL;
5623 static const struct got_error *
5624 search_next_blame_view(struct tog_view *view)
5626 struct tog_blame_view_state *s = &view->state.blame;
5627 const struct got_error *err = NULL;
5628 int lineno;
5629 char *line = NULL;
5630 size_t linesize = 0;
5631 ssize_t linelen;
5633 if (!view->searching) {
5634 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5635 return NULL;
5638 if (s->matched_line) {
5639 if (view->searching == TOG_SEARCH_FORWARD)
5640 lineno = s->matched_line + 1;
5641 else
5642 lineno = s->matched_line - 1;
5643 } else
5644 lineno = s->first_displayed_line - 1 + s->selected_line;
5646 while (1) {
5647 off_t offset;
5649 if (lineno <= 0 || lineno > s->blame.nlines) {
5650 if (s->matched_line == 0) {
5651 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5652 break;
5655 if (view->searching == TOG_SEARCH_FORWARD)
5656 lineno = 1;
5657 else
5658 lineno = s->blame.nlines;
5661 offset = s->blame.line_offsets[lineno - 1];
5662 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5663 free(line);
5664 return got_error_from_errno("fseeko");
5666 linelen = getline(&line, &linesize, s->blame.f);
5667 if (linelen != -1) {
5668 char *exstr;
5669 err = expand_tab(&exstr, line);
5670 if (err)
5671 break;
5672 if (match_line(exstr, &view->regex, 1,
5673 &view->regmatch)) {
5674 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5675 s->matched_line = lineno;
5676 free(exstr);
5677 break;
5679 free(exstr);
5681 if (view->searching == TOG_SEARCH_FORWARD)
5682 lineno++;
5683 else
5684 lineno--;
5686 free(line);
5688 if (s->matched_line) {
5689 s->first_displayed_line = s->matched_line;
5690 s->selected_line = 1;
5693 return err;
5696 static const struct got_error *
5697 show_blame_view(struct tog_view *view)
5699 const struct got_error *err = NULL;
5700 struct tog_blame_view_state *s = &view->state.blame;
5701 int errcode;
5703 if (s->blame.thread == 0 && !s->blame_complete) {
5704 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5705 &s->blame.thread_args);
5706 if (errcode)
5707 return got_error_set_errno(errcode, "pthread_create");
5709 halfdelay(1); /* fast refresh while annotating */
5712 if (s->blame_complete)
5713 halfdelay(10); /* disable fast refresh */
5715 err = draw_blame(view);
5717 view_border(view);
5718 return err;
5721 static const struct got_error *
5722 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5724 const struct got_error *err = NULL, *thread_err = NULL;
5725 struct tog_view *diff_view;
5726 struct tog_blame_view_state *s = &view->state.blame;
5727 int eos, nscroll, begin_y = 0, begin_x = 0;
5729 eos = nscroll = view->nlines - 2;
5730 if (view_is_hsplit_top(view))
5731 --eos; /* border */
5733 switch (ch) {
5734 case '0':
5735 view->x = 0;
5736 break;
5737 case '$':
5738 view->x = MAX(view->maxx - view->ncols / 3, 0);
5739 view->count = 0;
5740 break;
5741 case KEY_RIGHT:
5742 case 'l':
5743 if (view->x + view->ncols / 3 < view->maxx)
5744 view->x += 2; /* move two columns right */
5745 else
5746 view->count = 0;
5747 break;
5748 case KEY_LEFT:
5749 case 'h':
5750 view->x -= MIN(view->x, 2); /* move two columns back */
5751 if (view->x <= 0)
5752 view->count = 0;
5753 break;
5754 case 'q':
5755 s->done = 1;
5756 break;
5757 case 'g':
5758 case KEY_HOME:
5759 s->selected_line = 1;
5760 s->first_displayed_line = 1;
5761 view->count = 0;
5762 break;
5763 case 'G':
5764 case KEY_END:
5765 if (s->blame.nlines < eos) {
5766 s->selected_line = s->blame.nlines;
5767 s->first_displayed_line = 1;
5768 } else {
5769 s->selected_line = eos;
5770 s->first_displayed_line = s->blame.nlines - (eos - 1);
5772 view->count = 0;
5773 break;
5774 case 'k':
5775 case KEY_UP:
5776 case CTRL('p'):
5777 if (s->selected_line > 1)
5778 s->selected_line--;
5779 else if (s->selected_line == 1 &&
5780 s->first_displayed_line > 1)
5781 s->first_displayed_line--;
5782 else
5783 view->count = 0;
5784 break;
5785 case CTRL('u'):
5786 case 'u':
5787 nscroll /= 2;
5788 /* FALL THROUGH */
5789 case KEY_PPAGE:
5790 case CTRL('b'):
5791 case 'b':
5792 if (s->first_displayed_line == 1) {
5793 if (view->count > 1)
5794 nscroll += nscroll;
5795 s->selected_line = MAX(1, s->selected_line - nscroll);
5796 view->count = 0;
5797 break;
5799 if (s->first_displayed_line > nscroll)
5800 s->first_displayed_line -= nscroll;
5801 else
5802 s->first_displayed_line = 1;
5803 break;
5804 case 'j':
5805 case KEY_DOWN:
5806 case CTRL('n'):
5807 if (s->selected_line < eos && s->first_displayed_line +
5808 s->selected_line <= s->blame.nlines)
5809 s->selected_line++;
5810 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5811 s->first_displayed_line++;
5812 else
5813 view->count = 0;
5814 break;
5815 case 'c':
5816 case 'p': {
5817 struct got_object_id *id = NULL;
5819 view->count = 0;
5820 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5821 s->first_displayed_line, s->selected_line);
5822 if (id == NULL)
5823 break;
5824 if (ch == 'p') {
5825 struct got_commit_object *commit, *pcommit;
5826 struct got_object_qid *pid;
5827 struct got_object_id *blob_id = NULL;
5828 int obj_type;
5829 err = got_object_open_as_commit(&commit,
5830 s->repo, id);
5831 if (err)
5832 break;
5833 pid = STAILQ_FIRST(
5834 got_object_commit_get_parent_ids(commit));
5835 if (pid == NULL) {
5836 got_object_commit_close(commit);
5837 break;
5839 /* Check if path history ends here. */
5840 err = got_object_open_as_commit(&pcommit,
5841 s->repo, &pid->id);
5842 if (err)
5843 break;
5844 err = got_object_id_by_path(&blob_id, s->repo,
5845 pcommit, s->path);
5846 got_object_commit_close(pcommit);
5847 if (err) {
5848 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5849 err = NULL;
5850 got_object_commit_close(commit);
5851 break;
5853 err = got_object_get_type(&obj_type, s->repo,
5854 blob_id);
5855 free(blob_id);
5856 /* Can't blame non-blob type objects. */
5857 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5858 got_object_commit_close(commit);
5859 break;
5861 err = got_object_qid_alloc(&s->blamed_commit,
5862 &pid->id);
5863 got_object_commit_close(commit);
5864 } else {
5865 if (got_object_id_cmp(id,
5866 &s->blamed_commit->id) == 0)
5867 break;
5868 err = got_object_qid_alloc(&s->blamed_commit,
5869 id);
5871 if (err)
5872 break;
5873 s->done = 1;
5874 thread_err = stop_blame(&s->blame);
5875 s->done = 0;
5876 if (thread_err)
5877 break;
5878 STAILQ_INSERT_HEAD(&s->blamed_commits,
5879 s->blamed_commit, entry);
5880 err = run_blame(view);
5881 if (err)
5882 break;
5883 break;
5885 case 'C': {
5886 struct got_object_qid *first;
5888 view->count = 0;
5889 first = STAILQ_FIRST(&s->blamed_commits);
5890 if (!got_object_id_cmp(&first->id, s->commit_id))
5891 break;
5892 s->done = 1;
5893 thread_err = stop_blame(&s->blame);
5894 s->done = 0;
5895 if (thread_err)
5896 break;
5897 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5898 got_object_qid_free(s->blamed_commit);
5899 s->blamed_commit =
5900 STAILQ_FIRST(&s->blamed_commits);
5901 err = run_blame(view);
5902 if (err)
5903 break;
5904 break;
5906 case KEY_ENTER:
5907 case '\r': {
5908 struct got_object_id *id = NULL;
5909 struct got_object_qid *pid;
5910 struct got_commit_object *commit = NULL;
5912 view->count = 0;
5913 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5914 s->first_displayed_line, s->selected_line);
5915 if (id == NULL)
5916 break;
5917 err = got_object_open_as_commit(&commit, s->repo, id);
5918 if (err)
5919 break;
5920 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5921 if (*new_view) {
5922 /* traversed from diff view, release diff resources */
5923 err = close_diff_view(*new_view);
5924 if (err)
5925 break;
5926 diff_view = *new_view;
5927 } else {
5928 if (view_is_parent_view(view))
5929 view_get_split(view, &begin_y, &begin_x);
5931 diff_view = view_open(0, 0, begin_y, begin_x,
5932 TOG_VIEW_DIFF);
5933 if (diff_view == NULL) {
5934 got_object_commit_close(commit);
5935 err = got_error_from_errno("view_open");
5936 break;
5939 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5940 id, NULL, NULL, 3, 0, 0, view, s->repo);
5941 got_object_commit_close(commit);
5942 if (err) {
5943 view_close(diff_view);
5944 break;
5946 s->last_diffed_line = s->first_displayed_line - 1 +
5947 s->selected_line;
5948 if (*new_view)
5949 break; /* still open from active diff view */
5950 if (view_is_parent_view(view) &&
5951 view->mode == TOG_VIEW_SPLIT_HRZN) {
5952 err = view_init_hsplit(view, begin_y);
5953 if (err)
5954 break;
5957 view->focussed = 0;
5958 diff_view->focussed = 1;
5959 diff_view->mode = view->mode;
5960 diff_view->nlines = view->lines - begin_y;
5961 if (view_is_parent_view(view)) {
5962 view_transfer_size(diff_view, view);
5963 err = view_close_child(view);
5964 if (err)
5965 break;
5966 err = view_set_child(view, diff_view);
5967 if (err)
5968 break;
5969 view->focus_child = 1;
5970 } else
5971 *new_view = diff_view;
5972 if (err)
5973 break;
5974 break;
5976 case CTRL('d'):
5977 case 'd':
5978 nscroll /= 2;
5979 /* FALL THROUGH */
5980 case KEY_NPAGE:
5981 case CTRL('f'):
5982 case 'f':
5983 case ' ':
5984 if (s->last_displayed_line >= s->blame.nlines &&
5985 s->selected_line >= MIN(s->blame.nlines,
5986 view->nlines - 2)) {
5987 view->count = 0;
5988 break;
5990 if (s->last_displayed_line >= s->blame.nlines &&
5991 s->selected_line < view->nlines - 2) {
5992 s->selected_line +=
5993 MIN(nscroll, s->last_displayed_line -
5994 s->first_displayed_line - s->selected_line + 1);
5996 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5997 s->first_displayed_line += nscroll;
5998 else
5999 s->first_displayed_line =
6000 s->blame.nlines - (view->nlines - 3);
6001 break;
6002 case KEY_RESIZE:
6003 if (s->selected_line > view->nlines - 2) {
6004 s->selected_line = MIN(s->blame.nlines,
6005 view->nlines - 2);
6007 break;
6008 default:
6009 view->count = 0;
6010 break;
6012 return thread_err ? thread_err : err;
6015 static const struct got_error *
6016 reset_blame_view(struct tog_view *view)
6018 const struct got_error *err;
6019 struct tog_blame_view_state *s = &view->state.blame;
6021 view->count = 0;
6022 s->done = 1;
6023 err = stop_blame(&s->blame);
6024 s->done = 0;
6025 if (err)
6026 return err;
6027 return run_blame(view);
6030 static const struct got_error *
6031 cmd_blame(int argc, char *argv[])
6033 const struct got_error *error;
6034 struct got_repository *repo = NULL;
6035 struct got_worktree *worktree = NULL;
6036 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6037 char *link_target = NULL;
6038 struct got_object_id *commit_id = NULL;
6039 struct got_commit_object *commit = NULL;
6040 char *commit_id_str = NULL;
6041 int ch;
6042 struct tog_view *view;
6043 int *pack_fds = NULL;
6045 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6046 switch (ch) {
6047 case 'c':
6048 commit_id_str = optarg;
6049 break;
6050 case 'r':
6051 repo_path = realpath(optarg, NULL);
6052 if (repo_path == NULL)
6053 return got_error_from_errno2("realpath",
6054 optarg);
6055 break;
6056 default:
6057 usage_blame();
6058 /* NOTREACHED */
6062 argc -= optind;
6063 argv += optind;
6065 if (argc != 1)
6066 usage_blame();
6068 error = got_repo_pack_fds_open(&pack_fds);
6069 if (error != NULL)
6070 goto done;
6072 if (repo_path == NULL) {
6073 cwd = getcwd(NULL, 0);
6074 if (cwd == NULL)
6075 return got_error_from_errno("getcwd");
6076 error = got_worktree_open(&worktree, cwd);
6077 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6078 goto done;
6079 if (worktree)
6080 repo_path =
6081 strdup(got_worktree_get_repo_path(worktree));
6082 else
6083 repo_path = strdup(cwd);
6084 if (repo_path == NULL) {
6085 error = got_error_from_errno("strdup");
6086 goto done;
6090 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6091 if (error != NULL)
6092 goto done;
6094 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6095 worktree);
6096 if (error)
6097 goto done;
6099 init_curses();
6101 error = apply_unveil(got_repo_get_path(repo), NULL);
6102 if (error)
6103 goto done;
6105 error = tog_load_refs(repo, 0);
6106 if (error)
6107 goto done;
6109 if (commit_id_str == NULL) {
6110 struct got_reference *head_ref;
6111 error = got_ref_open(&head_ref, repo, worktree ?
6112 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6113 if (error != NULL)
6114 goto done;
6115 error = got_ref_resolve(&commit_id, repo, head_ref);
6116 got_ref_close(head_ref);
6117 } else {
6118 error = got_repo_match_object_id(&commit_id, NULL,
6119 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6121 if (error != NULL)
6122 goto done;
6124 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6125 if (view == NULL) {
6126 error = got_error_from_errno("view_open");
6127 goto done;
6130 error = got_object_open_as_commit(&commit, repo, commit_id);
6131 if (error)
6132 goto done;
6134 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6135 commit, repo);
6136 if (error)
6137 goto done;
6139 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6140 commit_id, repo);
6141 if (error)
6142 goto done;
6143 if (worktree) {
6144 /* Release work tree lock. */
6145 got_worktree_close(worktree);
6146 worktree = NULL;
6148 error = view_loop(view);
6149 done:
6150 free(repo_path);
6151 free(in_repo_path);
6152 free(link_target);
6153 free(cwd);
6154 free(commit_id);
6155 if (commit)
6156 got_object_commit_close(commit);
6157 if (worktree)
6158 got_worktree_close(worktree);
6159 if (repo) {
6160 const struct got_error *close_err = got_repo_close(repo);
6161 if (error == NULL)
6162 error = close_err;
6164 if (pack_fds) {
6165 const struct got_error *pack_err =
6166 got_repo_pack_fds_close(pack_fds);
6167 if (error == NULL)
6168 error = pack_err;
6170 tog_free_refs();
6171 return error;
6174 static const struct got_error *
6175 draw_tree_entries(struct tog_view *view, const char *parent_path)
6177 struct tog_tree_view_state *s = &view->state.tree;
6178 const struct got_error *err = NULL;
6179 struct got_tree_entry *te;
6180 wchar_t *wline;
6181 struct tog_color *tc;
6182 int width, n, i, nentries;
6183 int limit = view->nlines;
6185 s->ndisplayed = 0;
6186 if (view_is_hsplit_top(view))
6187 --limit; /* border */
6189 werase(view->window);
6191 if (limit == 0)
6192 return NULL;
6194 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6195 0, 0);
6196 if (err)
6197 return err;
6198 if (view_needs_focus_indication(view))
6199 wstandout(view->window);
6200 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6201 if (tc)
6202 wattr_on(view->window,
6203 COLOR_PAIR(tc->colorpair), NULL);
6204 waddwstr(view->window, wline);
6205 if (tc)
6206 wattr_off(view->window,
6207 COLOR_PAIR(tc->colorpair), NULL);
6208 if (view_needs_focus_indication(view))
6209 wstandend(view->window);
6210 free(wline);
6211 wline = NULL;
6212 if (width < view->ncols - 1)
6213 waddch(view->window, '\n');
6214 if (--limit <= 0)
6215 return NULL;
6216 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6217 0, 0);
6218 if (err)
6219 return err;
6220 waddwstr(view->window, wline);
6221 free(wline);
6222 wline = NULL;
6223 if (width < view->ncols - 1)
6224 waddch(view->window, '\n');
6225 if (--limit <= 0)
6226 return NULL;
6227 waddch(view->window, '\n');
6228 if (--limit <= 0)
6229 return NULL;
6231 if (s->first_displayed_entry == NULL) {
6232 te = got_object_tree_get_first_entry(s->tree);
6233 if (s->selected == 0) {
6234 if (view->focussed)
6235 wstandout(view->window);
6236 s->selected_entry = NULL;
6238 waddstr(view->window, " ..\n"); /* parent directory */
6239 if (s->selected == 0 && view->focussed)
6240 wstandend(view->window);
6241 s->ndisplayed++;
6242 if (--limit <= 0)
6243 return NULL;
6244 n = 1;
6245 } else {
6246 n = 0;
6247 te = s->first_displayed_entry;
6250 nentries = got_object_tree_get_nentries(s->tree);
6251 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6252 char *line = NULL, *id_str = NULL, *link_target = NULL;
6253 const char *modestr = "";
6254 mode_t mode;
6256 te = got_object_tree_get_entry(s->tree, i);
6257 mode = got_tree_entry_get_mode(te);
6259 if (s->show_ids) {
6260 err = got_object_id_str(&id_str,
6261 got_tree_entry_get_id(te));
6262 if (err)
6263 return got_error_from_errno(
6264 "got_object_id_str");
6266 if (got_object_tree_entry_is_submodule(te))
6267 modestr = "$";
6268 else if (S_ISLNK(mode)) {
6269 int i;
6271 err = got_tree_entry_get_symlink_target(&link_target,
6272 te, s->repo);
6273 if (err) {
6274 free(id_str);
6275 return err;
6277 for (i = 0; i < strlen(link_target); i++) {
6278 if (!isprint((unsigned char)link_target[i]))
6279 link_target[i] = '?';
6281 modestr = "@";
6283 else if (S_ISDIR(mode))
6284 modestr = "/";
6285 else if (mode & S_IXUSR)
6286 modestr = "*";
6287 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6288 got_tree_entry_get_name(te), modestr,
6289 link_target ? " -> ": "",
6290 link_target ? link_target : "") == -1) {
6291 free(id_str);
6292 free(link_target);
6293 return got_error_from_errno("asprintf");
6295 free(id_str);
6296 free(link_target);
6297 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6298 0, 0);
6299 if (err) {
6300 free(line);
6301 break;
6303 if (n == s->selected) {
6304 if (view->focussed)
6305 wstandout(view->window);
6306 s->selected_entry = te;
6308 tc = match_color(&s->colors, line);
6309 if (tc)
6310 wattr_on(view->window,
6311 COLOR_PAIR(tc->colorpair), NULL);
6312 waddwstr(view->window, wline);
6313 if (tc)
6314 wattr_off(view->window,
6315 COLOR_PAIR(tc->colorpair), NULL);
6316 if (width < view->ncols - 1)
6317 waddch(view->window, '\n');
6318 if (n == s->selected && view->focussed)
6319 wstandend(view->window);
6320 free(line);
6321 free(wline);
6322 wline = NULL;
6323 n++;
6324 s->ndisplayed++;
6325 s->last_displayed_entry = te;
6326 if (--limit <= 0)
6327 break;
6330 return err;
6333 static void
6334 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6336 struct got_tree_entry *te;
6337 int isroot = s->tree == s->root;
6338 int i = 0;
6340 if (s->first_displayed_entry == NULL)
6341 return;
6343 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6344 while (i++ < maxscroll) {
6345 if (te == NULL) {
6346 if (!isroot)
6347 s->first_displayed_entry = NULL;
6348 break;
6350 s->first_displayed_entry = te;
6351 te = got_tree_entry_get_prev(s->tree, te);
6355 static const struct got_error *
6356 tree_scroll_down(struct tog_view *view, int maxscroll)
6358 struct tog_tree_view_state *s = &view->state.tree;
6359 struct got_tree_entry *next, *last;
6360 int n = 0;
6362 if (s->first_displayed_entry)
6363 next = got_tree_entry_get_next(s->tree,
6364 s->first_displayed_entry);
6365 else
6366 next = got_object_tree_get_first_entry(s->tree);
6368 last = s->last_displayed_entry;
6369 while (next && n++ < maxscroll) {
6370 if (last)
6371 last = got_tree_entry_get_next(s->tree, last);
6372 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6373 s->first_displayed_entry = next;
6374 next = got_tree_entry_get_next(s->tree, next);
6378 return NULL;
6381 static const struct got_error *
6382 tree_entry_path(char **path, struct tog_parent_trees *parents,
6383 struct got_tree_entry *te)
6385 const struct got_error *err = NULL;
6386 struct tog_parent_tree *pt;
6387 size_t len = 2; /* for leading slash and NUL */
6389 TAILQ_FOREACH(pt, parents, entry)
6390 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6391 + 1 /* slash */;
6392 if (te)
6393 len += strlen(got_tree_entry_get_name(te));
6395 *path = calloc(1, len);
6396 if (path == NULL)
6397 return got_error_from_errno("calloc");
6399 (*path)[0] = '/';
6400 pt = TAILQ_LAST(parents, tog_parent_trees);
6401 while (pt) {
6402 const char *name = got_tree_entry_get_name(pt->selected_entry);
6403 if (strlcat(*path, name, len) >= len) {
6404 err = got_error(GOT_ERR_NO_SPACE);
6405 goto done;
6407 if (strlcat(*path, "/", len) >= len) {
6408 err = got_error(GOT_ERR_NO_SPACE);
6409 goto done;
6411 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6413 if (te) {
6414 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6415 err = got_error(GOT_ERR_NO_SPACE);
6416 goto done;
6419 done:
6420 if (err) {
6421 free(*path);
6422 *path = NULL;
6424 return err;
6427 static const struct got_error *
6428 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6429 struct got_tree_entry *te, struct tog_parent_trees *parents,
6430 struct got_object_id *commit_id, struct got_repository *repo)
6432 const struct got_error *err = NULL;
6433 char *path;
6434 struct tog_view *blame_view;
6436 *new_view = NULL;
6438 err = tree_entry_path(&path, parents, te);
6439 if (err)
6440 return err;
6442 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6443 if (blame_view == NULL) {
6444 err = got_error_from_errno("view_open");
6445 goto done;
6448 err = open_blame_view(blame_view, path, commit_id, repo);
6449 if (err) {
6450 if (err->code == GOT_ERR_CANCELLED)
6451 err = NULL;
6452 view_close(blame_view);
6453 } else
6454 *new_view = blame_view;
6455 done:
6456 free(path);
6457 return err;
6460 static const struct got_error *
6461 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6462 struct tog_tree_view_state *s)
6464 struct tog_view *log_view;
6465 const struct got_error *err = NULL;
6466 char *path;
6468 *new_view = NULL;
6470 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6471 if (log_view == NULL)
6472 return got_error_from_errno("view_open");
6474 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6475 if (err)
6476 return err;
6478 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6479 path, 0);
6480 if (err)
6481 view_close(log_view);
6482 else
6483 *new_view = log_view;
6484 free(path);
6485 return err;
6488 static const struct got_error *
6489 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6490 const char *head_ref_name, struct got_repository *repo)
6492 const struct got_error *err = NULL;
6493 char *commit_id_str = NULL;
6494 struct tog_tree_view_state *s = &view->state.tree;
6495 struct got_commit_object *commit = NULL;
6497 TAILQ_INIT(&s->parents);
6498 STAILQ_INIT(&s->colors);
6500 s->commit_id = got_object_id_dup(commit_id);
6501 if (s->commit_id == NULL)
6502 return got_error_from_errno("got_object_id_dup");
6504 err = got_object_open_as_commit(&commit, repo, commit_id);
6505 if (err)
6506 goto done;
6509 * The root is opened here and will be closed when the view is closed.
6510 * Any visited subtrees and their path-wise parents are opened and
6511 * closed on demand.
6513 err = got_object_open_as_tree(&s->root, repo,
6514 got_object_commit_get_tree_id(commit));
6515 if (err)
6516 goto done;
6517 s->tree = s->root;
6519 err = got_object_id_str(&commit_id_str, commit_id);
6520 if (err != NULL)
6521 goto done;
6523 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6524 err = got_error_from_errno("asprintf");
6525 goto done;
6528 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6529 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6530 if (head_ref_name) {
6531 s->head_ref_name = strdup(head_ref_name);
6532 if (s->head_ref_name == NULL) {
6533 err = got_error_from_errno("strdup");
6534 goto done;
6537 s->repo = repo;
6539 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6540 err = add_color(&s->colors, "\\$$",
6541 TOG_COLOR_TREE_SUBMODULE,
6542 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6543 if (err)
6544 goto done;
6545 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6546 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6547 if (err)
6548 goto done;
6549 err = add_color(&s->colors, "/$",
6550 TOG_COLOR_TREE_DIRECTORY,
6551 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6552 if (err)
6553 goto done;
6555 err = add_color(&s->colors, "\\*$",
6556 TOG_COLOR_TREE_EXECUTABLE,
6557 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6558 if (err)
6559 goto done;
6561 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6562 get_color_value("TOG_COLOR_COMMIT"));
6563 if (err)
6564 goto done;
6567 view->show = show_tree_view;
6568 view->input = input_tree_view;
6569 view->close = close_tree_view;
6570 view->search_start = search_start_tree_view;
6571 view->search_next = search_next_tree_view;
6572 done:
6573 free(commit_id_str);
6574 if (commit)
6575 got_object_commit_close(commit);
6576 if (err)
6577 close_tree_view(view);
6578 return err;
6581 static const struct got_error *
6582 close_tree_view(struct tog_view *view)
6584 struct tog_tree_view_state *s = &view->state.tree;
6586 free_colors(&s->colors);
6587 free(s->tree_label);
6588 s->tree_label = NULL;
6589 free(s->commit_id);
6590 s->commit_id = NULL;
6591 free(s->head_ref_name);
6592 s->head_ref_name = NULL;
6593 while (!TAILQ_EMPTY(&s->parents)) {
6594 struct tog_parent_tree *parent;
6595 parent = TAILQ_FIRST(&s->parents);
6596 TAILQ_REMOVE(&s->parents, parent, entry);
6597 if (parent->tree != s->root)
6598 got_object_tree_close(parent->tree);
6599 free(parent);
6602 if (s->tree != NULL && s->tree != s->root)
6603 got_object_tree_close(s->tree);
6604 if (s->root)
6605 got_object_tree_close(s->root);
6606 return NULL;
6609 static const struct got_error *
6610 search_start_tree_view(struct tog_view *view)
6612 struct tog_tree_view_state *s = &view->state.tree;
6614 s->matched_entry = NULL;
6615 return NULL;
6618 static int
6619 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6621 regmatch_t regmatch;
6623 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6624 0) == 0;
6627 static const struct got_error *
6628 search_next_tree_view(struct tog_view *view)
6630 struct tog_tree_view_state *s = &view->state.tree;
6631 struct got_tree_entry *te = NULL;
6633 if (!view->searching) {
6634 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6635 return NULL;
6638 if (s->matched_entry) {
6639 if (view->searching == TOG_SEARCH_FORWARD) {
6640 if (s->selected_entry)
6641 te = got_tree_entry_get_next(s->tree,
6642 s->selected_entry);
6643 else
6644 te = got_object_tree_get_first_entry(s->tree);
6645 } else {
6646 if (s->selected_entry == NULL)
6647 te = got_object_tree_get_last_entry(s->tree);
6648 else
6649 te = got_tree_entry_get_prev(s->tree,
6650 s->selected_entry);
6652 } else {
6653 if (s->selected_entry)
6654 te = s->selected_entry;
6655 else if (view->searching == TOG_SEARCH_FORWARD)
6656 te = got_object_tree_get_first_entry(s->tree);
6657 else
6658 te = got_object_tree_get_last_entry(s->tree);
6661 while (1) {
6662 if (te == NULL) {
6663 if (s->matched_entry == NULL) {
6664 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6665 return NULL;
6667 if (view->searching == TOG_SEARCH_FORWARD)
6668 te = got_object_tree_get_first_entry(s->tree);
6669 else
6670 te = got_object_tree_get_last_entry(s->tree);
6673 if (match_tree_entry(te, &view->regex)) {
6674 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6675 s->matched_entry = te;
6676 break;
6679 if (view->searching == TOG_SEARCH_FORWARD)
6680 te = got_tree_entry_get_next(s->tree, te);
6681 else
6682 te = got_tree_entry_get_prev(s->tree, te);
6685 if (s->matched_entry) {
6686 s->first_displayed_entry = s->matched_entry;
6687 s->selected = 0;
6690 return NULL;
6693 static const struct got_error *
6694 show_tree_view(struct tog_view *view)
6696 const struct got_error *err = NULL;
6697 struct tog_tree_view_state *s = &view->state.tree;
6698 char *parent_path;
6700 err = tree_entry_path(&parent_path, &s->parents, NULL);
6701 if (err)
6702 return err;
6704 err = draw_tree_entries(view, parent_path);
6705 free(parent_path);
6707 view_border(view);
6708 return err;
6711 static const struct got_error *
6712 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6714 const struct got_error *err = NULL;
6715 struct tog_tree_view_state *s = &view->state.tree;
6716 struct tog_view *log_view, *ref_view;
6717 struct got_tree_entry *te;
6718 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 3;
6720 switch (ch) {
6721 case 'i':
6722 s->show_ids = !s->show_ids;
6723 view->count = 0;
6724 break;
6725 case 'l':
6726 view->count = 0;
6727 if (!s->selected_entry)
6728 break;
6729 if (view_is_parent_view(view))
6730 view_get_split(view, &begin_y, &begin_x);
6731 err = log_selected_tree_entry(&log_view, begin_y, begin_x, s);
6732 if (view_is_parent_view(view) &&
6733 view->mode == TOG_VIEW_SPLIT_HRZN) {
6734 err = view_init_hsplit(view, begin_y);
6735 if (err)
6736 break;
6738 view->focussed = 0;
6739 log_view->focussed = 1;
6740 log_view->mode = view->mode;
6741 log_view->nlines = view->lines - begin_y;
6742 if (view_is_parent_view(view)) {
6743 view_transfer_size(log_view, view);
6744 err = view_close_child(view);
6745 if (err)
6746 return err;
6747 err = view_set_child(view, log_view);
6748 if (err)
6749 return err;
6750 view->focus_child = 1;
6751 } else
6752 *new_view = log_view;
6753 break;
6754 case 'r':
6755 view->count = 0;
6756 if (view_is_parent_view(view))
6757 view_get_split(view, &begin_y, &begin_x);
6758 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
6759 if (ref_view == NULL)
6760 return got_error_from_errno("view_open");
6761 err = open_ref_view(ref_view, s->repo);
6762 if (err) {
6763 view_close(ref_view);
6764 return err;
6766 if (view_is_parent_view(view) &&
6767 view->mode == TOG_VIEW_SPLIT_HRZN) {
6768 err = view_init_hsplit(view, begin_y);
6769 if (err)
6770 break;
6772 view->focussed = 0;
6773 ref_view->focussed = 1;
6774 ref_view->mode = view->mode;
6775 ref_view->nlines = view->lines - begin_y;
6776 if (view_is_parent_view(view)) {
6777 view_transfer_size(ref_view, view);
6778 err = view_close_child(view);
6779 if (err)
6780 return err;
6781 err = view_set_child(view, ref_view);
6782 if (err)
6783 return err;
6784 view->focus_child = 1;
6785 } else
6786 *new_view = ref_view;
6787 break;
6788 case 'g':
6789 case KEY_HOME:
6790 s->selected = 0;
6791 view->count = 0;
6792 if (s->tree == s->root)
6793 s->first_displayed_entry =
6794 got_object_tree_get_first_entry(s->tree);
6795 else
6796 s->first_displayed_entry = NULL;
6797 break;
6798 case 'G':
6799 case KEY_END: {
6800 int eos = view->nlines - 3;
6802 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6803 --eos; /* border */
6804 s->selected = 0;
6805 view->count = 0;
6806 te = got_object_tree_get_last_entry(s->tree);
6807 for (n = 0; n < eos; n++) {
6808 if (te == NULL) {
6809 if (s->tree != s->root) {
6810 s->first_displayed_entry = NULL;
6811 n++;
6813 break;
6815 s->first_displayed_entry = te;
6816 te = got_tree_entry_get_prev(s->tree, te);
6818 if (n > 0)
6819 s->selected = n - 1;
6820 break;
6822 case 'k':
6823 case KEY_UP:
6824 case CTRL('p'):
6825 if (s->selected > 0) {
6826 s->selected--;
6827 break;
6829 tree_scroll_up(s, 1);
6830 if (s->selected_entry == NULL ||
6831 (s->tree == s->root && s->selected_entry ==
6832 got_object_tree_get_first_entry(s->tree)))
6833 view->count = 0;
6834 break;
6835 case CTRL('u'):
6836 case 'u':
6837 nscroll /= 2;
6838 /* FALL THROUGH */
6839 case KEY_PPAGE:
6840 case CTRL('b'):
6841 case 'b':
6842 if (s->tree == s->root) {
6843 if (got_object_tree_get_first_entry(s->tree) ==
6844 s->first_displayed_entry)
6845 s->selected -= MIN(s->selected, nscroll);
6846 } else {
6847 if (s->first_displayed_entry == NULL)
6848 s->selected -= MIN(s->selected, nscroll);
6850 tree_scroll_up(s, MAX(0, nscroll));
6851 if (s->selected_entry == NULL ||
6852 (s->tree == s->root && s->selected_entry ==
6853 got_object_tree_get_first_entry(s->tree)))
6854 view->count = 0;
6855 break;
6856 case 'j':
6857 case KEY_DOWN:
6858 case CTRL('n'):
6859 if (s->selected < s->ndisplayed - 1) {
6860 s->selected++;
6861 break;
6863 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6864 == NULL) {
6865 /* can't scroll any further */
6866 view->count = 0;
6867 break;
6869 tree_scroll_down(view, 1);
6870 break;
6871 case CTRL('d'):
6872 case 'd':
6873 nscroll /= 2;
6874 /* FALL THROUGH */
6875 case KEY_NPAGE:
6876 case CTRL('f'):
6877 case 'f':
6878 case ' ':
6879 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6880 == NULL) {
6881 /* can't scroll any further; move cursor down */
6882 if (s->selected < s->ndisplayed - 1)
6883 s->selected += MIN(nscroll,
6884 s->ndisplayed - s->selected - 1);
6885 else
6886 view->count = 0;
6887 break;
6889 tree_scroll_down(view, nscroll);
6890 break;
6891 case KEY_ENTER:
6892 case '\r':
6893 case KEY_BACKSPACE:
6894 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6895 struct tog_parent_tree *parent;
6896 /* user selected '..' */
6897 if (s->tree == s->root) {
6898 view->count = 0;
6899 break;
6901 parent = TAILQ_FIRST(&s->parents);
6902 TAILQ_REMOVE(&s->parents, parent,
6903 entry);
6904 got_object_tree_close(s->tree);
6905 s->tree = parent->tree;
6906 s->first_displayed_entry =
6907 parent->first_displayed_entry;
6908 s->selected_entry =
6909 parent->selected_entry;
6910 s->selected = parent->selected;
6911 if (s->selected > view->nlines - 3) {
6912 err = offset_selection_down(view);
6913 if (err)
6914 break;
6916 free(parent);
6917 } else if (S_ISDIR(got_tree_entry_get_mode(
6918 s->selected_entry))) {
6919 struct got_tree_object *subtree;
6920 view->count = 0;
6921 err = got_object_open_as_tree(&subtree, s->repo,
6922 got_tree_entry_get_id(s->selected_entry));
6923 if (err)
6924 break;
6925 err = tree_view_visit_subtree(s, subtree);
6926 if (err) {
6927 got_object_tree_close(subtree);
6928 break;
6930 } else if (S_ISREG(got_tree_entry_get_mode(
6931 s->selected_entry))) {
6932 struct tog_view *blame_view;
6933 int begin_x = 0, begin_y = 0;
6935 if (view_is_parent_view(view))
6936 view_get_split(view, &begin_y, &begin_x);
6938 err = blame_tree_entry(&blame_view, begin_y, begin_x,
6939 s->selected_entry, &s->parents,
6940 s->commit_id, s->repo);
6941 if (err)
6942 break;
6944 if (view_is_parent_view(view) &&
6945 view->mode == TOG_VIEW_SPLIT_HRZN) {
6946 err = view_init_hsplit(view, begin_y);
6947 if (err)
6948 break;
6951 view->count = 0;
6952 view->focussed = 0;
6953 blame_view->focussed = 1;
6954 blame_view->mode = view->mode;
6955 blame_view->nlines = view->lines - begin_y;
6956 if (view_is_parent_view(view)) {
6957 view_transfer_size(blame_view, view);
6958 err = view_close_child(view);
6959 if (err)
6960 return err;
6961 err = view_set_child(view, blame_view);
6962 if (err)
6963 return err;
6964 view->focus_child = 1;
6965 } else
6966 *new_view = blame_view;
6968 break;
6969 case KEY_RESIZE:
6970 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6971 s->selected = view->nlines - 4;
6972 view->count = 0;
6973 break;
6974 default:
6975 view->count = 0;
6976 break;
6979 return err;
6982 __dead static void
6983 usage_tree(void)
6985 endwin();
6986 fprintf(stderr,
6987 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6988 getprogname());
6989 exit(1);
6992 static const struct got_error *
6993 cmd_tree(int argc, char *argv[])
6995 const struct got_error *error;
6996 struct got_repository *repo = NULL;
6997 struct got_worktree *worktree = NULL;
6998 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6999 struct got_object_id *commit_id = NULL;
7000 struct got_commit_object *commit = NULL;
7001 const char *commit_id_arg = NULL;
7002 char *label = NULL;
7003 struct got_reference *ref = NULL;
7004 const char *head_ref_name = NULL;
7005 int ch;
7006 struct tog_view *view;
7007 int *pack_fds = NULL;
7009 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7010 switch (ch) {
7011 case 'c':
7012 commit_id_arg = optarg;
7013 break;
7014 case 'r':
7015 repo_path = realpath(optarg, NULL);
7016 if (repo_path == NULL)
7017 return got_error_from_errno2("realpath",
7018 optarg);
7019 break;
7020 default:
7021 usage_tree();
7022 /* NOTREACHED */
7026 argc -= optind;
7027 argv += optind;
7029 if (argc > 1)
7030 usage_tree();
7032 error = got_repo_pack_fds_open(&pack_fds);
7033 if (error != NULL)
7034 goto done;
7036 if (repo_path == NULL) {
7037 cwd = getcwd(NULL, 0);
7038 if (cwd == NULL)
7039 return got_error_from_errno("getcwd");
7040 error = got_worktree_open(&worktree, cwd);
7041 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7042 goto done;
7043 if (worktree)
7044 repo_path =
7045 strdup(got_worktree_get_repo_path(worktree));
7046 else
7047 repo_path = strdup(cwd);
7048 if (repo_path == NULL) {
7049 error = got_error_from_errno("strdup");
7050 goto done;
7054 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7055 if (error != NULL)
7056 goto done;
7058 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7059 repo, worktree);
7060 if (error)
7061 goto done;
7063 init_curses();
7065 error = apply_unveil(got_repo_get_path(repo), NULL);
7066 if (error)
7067 goto done;
7069 error = tog_load_refs(repo, 0);
7070 if (error)
7071 goto done;
7073 if (commit_id_arg == NULL) {
7074 error = got_repo_match_object_id(&commit_id, &label,
7075 worktree ? got_worktree_get_head_ref_name(worktree) :
7076 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7077 if (error)
7078 goto done;
7079 head_ref_name = label;
7080 } else {
7081 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7082 if (error == NULL)
7083 head_ref_name = got_ref_get_name(ref);
7084 else if (error->code != GOT_ERR_NOT_REF)
7085 goto done;
7086 error = got_repo_match_object_id(&commit_id, NULL,
7087 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7088 if (error)
7089 goto done;
7092 error = got_object_open_as_commit(&commit, repo, commit_id);
7093 if (error)
7094 goto done;
7096 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7097 if (view == NULL) {
7098 error = got_error_from_errno("view_open");
7099 goto done;
7101 error = open_tree_view(view, commit_id, head_ref_name, repo);
7102 if (error)
7103 goto done;
7104 if (!got_path_is_root_dir(in_repo_path)) {
7105 error = tree_view_walk_path(&view->state.tree, commit,
7106 in_repo_path);
7107 if (error)
7108 goto done;
7111 if (worktree) {
7112 /* Release work tree lock. */
7113 got_worktree_close(worktree);
7114 worktree = NULL;
7116 error = view_loop(view);
7117 done:
7118 free(repo_path);
7119 free(cwd);
7120 free(commit_id);
7121 free(label);
7122 if (ref)
7123 got_ref_close(ref);
7124 if (repo) {
7125 const struct got_error *close_err = got_repo_close(repo);
7126 if (error == NULL)
7127 error = close_err;
7129 if (pack_fds) {
7130 const struct got_error *pack_err =
7131 got_repo_pack_fds_close(pack_fds);
7132 if (error == NULL)
7133 error = pack_err;
7135 tog_free_refs();
7136 return error;
7139 static const struct got_error *
7140 ref_view_load_refs(struct tog_ref_view_state *s)
7142 struct got_reflist_entry *sre;
7143 struct tog_reflist_entry *re;
7145 s->nrefs = 0;
7146 TAILQ_FOREACH(sre, &tog_refs, entry) {
7147 if (strncmp(got_ref_get_name(sre->ref),
7148 "refs/got/", 9) == 0 &&
7149 strncmp(got_ref_get_name(sre->ref),
7150 "refs/got/backup/", 16) != 0)
7151 continue;
7153 re = malloc(sizeof(*re));
7154 if (re == NULL)
7155 return got_error_from_errno("malloc");
7157 re->ref = got_ref_dup(sre->ref);
7158 if (re->ref == NULL)
7159 return got_error_from_errno("got_ref_dup");
7160 re->idx = s->nrefs++;
7161 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7164 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7165 return NULL;
7168 static void
7169 ref_view_free_refs(struct tog_ref_view_state *s)
7171 struct tog_reflist_entry *re;
7173 while (!TAILQ_EMPTY(&s->refs)) {
7174 re = TAILQ_FIRST(&s->refs);
7175 TAILQ_REMOVE(&s->refs, re, entry);
7176 got_ref_close(re->ref);
7177 free(re);
7181 static const struct got_error *
7182 open_ref_view(struct tog_view *view, struct got_repository *repo)
7184 const struct got_error *err = NULL;
7185 struct tog_ref_view_state *s = &view->state.ref;
7187 s->selected_entry = 0;
7188 s->repo = repo;
7190 TAILQ_INIT(&s->refs);
7191 STAILQ_INIT(&s->colors);
7193 err = ref_view_load_refs(s);
7194 if (err)
7195 return err;
7197 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7198 err = add_color(&s->colors, "^refs/heads/",
7199 TOG_COLOR_REFS_HEADS,
7200 get_color_value("TOG_COLOR_REFS_HEADS"));
7201 if (err)
7202 goto done;
7204 err = add_color(&s->colors, "^refs/tags/",
7205 TOG_COLOR_REFS_TAGS,
7206 get_color_value("TOG_COLOR_REFS_TAGS"));
7207 if (err)
7208 goto done;
7210 err = add_color(&s->colors, "^refs/remotes/",
7211 TOG_COLOR_REFS_REMOTES,
7212 get_color_value("TOG_COLOR_REFS_REMOTES"));
7213 if (err)
7214 goto done;
7216 err = add_color(&s->colors, "^refs/got/backup/",
7217 TOG_COLOR_REFS_BACKUP,
7218 get_color_value("TOG_COLOR_REFS_BACKUP"));
7219 if (err)
7220 goto done;
7223 view->show = show_ref_view;
7224 view->input = input_ref_view;
7225 view->close = close_ref_view;
7226 view->search_start = search_start_ref_view;
7227 view->search_next = search_next_ref_view;
7228 done:
7229 if (err)
7230 free_colors(&s->colors);
7231 return err;
7234 static const struct got_error *
7235 close_ref_view(struct tog_view *view)
7237 struct tog_ref_view_state *s = &view->state.ref;
7239 ref_view_free_refs(s);
7240 free_colors(&s->colors);
7242 return NULL;
7245 static const struct got_error *
7246 resolve_reflist_entry(struct got_object_id **commit_id,
7247 struct tog_reflist_entry *re, struct got_repository *repo)
7249 const struct got_error *err = NULL;
7250 struct got_object_id *obj_id;
7251 struct got_tag_object *tag = NULL;
7252 int obj_type;
7254 *commit_id = NULL;
7256 err = got_ref_resolve(&obj_id, repo, re->ref);
7257 if (err)
7258 return err;
7260 err = got_object_get_type(&obj_type, repo, obj_id);
7261 if (err)
7262 goto done;
7264 switch (obj_type) {
7265 case GOT_OBJ_TYPE_COMMIT:
7266 *commit_id = obj_id;
7267 break;
7268 case GOT_OBJ_TYPE_TAG:
7269 err = got_object_open_as_tag(&tag, repo, obj_id);
7270 if (err)
7271 goto done;
7272 free(obj_id);
7273 err = got_object_get_type(&obj_type, repo,
7274 got_object_tag_get_object_id(tag));
7275 if (err)
7276 goto done;
7277 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7278 err = got_error(GOT_ERR_OBJ_TYPE);
7279 goto done;
7281 *commit_id = got_object_id_dup(
7282 got_object_tag_get_object_id(tag));
7283 if (*commit_id == NULL) {
7284 err = got_error_from_errno("got_object_id_dup");
7285 goto done;
7287 break;
7288 default:
7289 err = got_error(GOT_ERR_OBJ_TYPE);
7290 break;
7293 done:
7294 if (tag)
7295 got_object_tag_close(tag);
7296 if (err) {
7297 free(*commit_id);
7298 *commit_id = NULL;
7300 return err;
7303 static const struct got_error *
7304 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7305 struct tog_reflist_entry *re, struct got_repository *repo)
7307 struct tog_view *log_view;
7308 const struct got_error *err = NULL;
7309 struct got_object_id *commit_id = NULL;
7311 *new_view = NULL;
7313 err = resolve_reflist_entry(&commit_id, re, repo);
7314 if (err) {
7315 if (err->code != GOT_ERR_OBJ_TYPE)
7316 return err;
7317 else
7318 return NULL;
7321 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7322 if (log_view == NULL) {
7323 err = got_error_from_errno("view_open");
7324 goto done;
7327 err = open_log_view(log_view, commit_id, repo,
7328 got_ref_get_name(re->ref), "", 0);
7329 done:
7330 if (err)
7331 view_close(log_view);
7332 else
7333 *new_view = log_view;
7334 free(commit_id);
7335 return err;
7338 static void
7339 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7341 struct tog_reflist_entry *re;
7342 int i = 0;
7344 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7345 return;
7347 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7348 while (i++ < maxscroll) {
7349 if (re == NULL)
7350 break;
7351 s->first_displayed_entry = re;
7352 re = TAILQ_PREV(re, tog_reflist_head, entry);
7356 static const struct got_error *
7357 ref_scroll_down(struct tog_view *view, int maxscroll)
7359 struct tog_ref_view_state *s = &view->state.ref;
7360 struct tog_reflist_entry *next, *last;
7361 int n = 0;
7363 if (s->first_displayed_entry)
7364 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7365 else
7366 next = TAILQ_FIRST(&s->refs);
7368 last = s->last_displayed_entry;
7369 while (next && n++ < maxscroll) {
7370 if (last)
7371 last = TAILQ_NEXT(last, entry);
7372 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7373 s->first_displayed_entry = next;
7374 next = TAILQ_NEXT(next, entry);
7378 return NULL;
7381 static const struct got_error *
7382 search_start_ref_view(struct tog_view *view)
7384 struct tog_ref_view_state *s = &view->state.ref;
7386 s->matched_entry = NULL;
7387 return NULL;
7390 static int
7391 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7393 regmatch_t regmatch;
7395 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7396 0) == 0;
7399 static const struct got_error *
7400 search_next_ref_view(struct tog_view *view)
7402 struct tog_ref_view_state *s = &view->state.ref;
7403 struct tog_reflist_entry *re = NULL;
7405 if (!view->searching) {
7406 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7407 return NULL;
7410 if (s->matched_entry) {
7411 if (view->searching == TOG_SEARCH_FORWARD) {
7412 if (s->selected_entry)
7413 re = TAILQ_NEXT(s->selected_entry, entry);
7414 else
7415 re = TAILQ_PREV(s->selected_entry,
7416 tog_reflist_head, entry);
7417 } else {
7418 if (s->selected_entry == NULL)
7419 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7420 else
7421 re = TAILQ_PREV(s->selected_entry,
7422 tog_reflist_head, entry);
7424 } else {
7425 if (s->selected_entry)
7426 re = s->selected_entry;
7427 else if (view->searching == TOG_SEARCH_FORWARD)
7428 re = TAILQ_FIRST(&s->refs);
7429 else
7430 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7433 while (1) {
7434 if (re == NULL) {
7435 if (s->matched_entry == NULL) {
7436 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7437 return NULL;
7439 if (view->searching == TOG_SEARCH_FORWARD)
7440 re = TAILQ_FIRST(&s->refs);
7441 else
7442 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7445 if (match_reflist_entry(re, &view->regex)) {
7446 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7447 s->matched_entry = re;
7448 break;
7451 if (view->searching == TOG_SEARCH_FORWARD)
7452 re = TAILQ_NEXT(re, entry);
7453 else
7454 re = TAILQ_PREV(re, tog_reflist_head, entry);
7457 if (s->matched_entry) {
7458 s->first_displayed_entry = s->matched_entry;
7459 s->selected = 0;
7462 return NULL;
7465 static const struct got_error *
7466 show_ref_view(struct tog_view *view)
7468 const struct got_error *err = NULL;
7469 struct tog_ref_view_state *s = &view->state.ref;
7470 struct tog_reflist_entry *re;
7471 char *line = NULL;
7472 wchar_t *wline;
7473 struct tog_color *tc;
7474 int width, n;
7475 int limit = view->nlines;
7477 werase(view->window);
7479 s->ndisplayed = 0;
7480 if (view_is_hsplit_top(view))
7481 --limit; /* border */
7483 if (limit == 0)
7484 return NULL;
7486 re = s->first_displayed_entry;
7488 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7489 s->nrefs) == -1)
7490 return got_error_from_errno("asprintf");
7492 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7493 if (err) {
7494 free(line);
7495 return err;
7497 if (view_needs_focus_indication(view))
7498 wstandout(view->window);
7499 waddwstr(view->window, wline);
7500 if (view_needs_focus_indication(view))
7501 wstandend(view->window);
7502 free(wline);
7503 wline = NULL;
7504 free(line);
7505 line = NULL;
7506 if (width < view->ncols - 1)
7507 waddch(view->window, '\n');
7508 if (--limit <= 0)
7509 return NULL;
7511 n = 0;
7512 while (re && limit > 0) {
7513 char *line = NULL;
7514 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7516 if (s->show_date) {
7517 struct got_commit_object *ci;
7518 struct got_tag_object *tag;
7519 struct got_object_id *id;
7520 struct tm tm;
7521 time_t t;
7523 err = got_ref_resolve(&id, s->repo, re->ref);
7524 if (err)
7525 return err;
7526 err = got_object_open_as_tag(&tag, s->repo, id);
7527 if (err) {
7528 if (err->code != GOT_ERR_OBJ_TYPE) {
7529 free(id);
7530 return err;
7532 err = got_object_open_as_commit(&ci, s->repo,
7533 id);
7534 if (err) {
7535 free(id);
7536 return err;
7538 t = got_object_commit_get_committer_time(ci);
7539 got_object_commit_close(ci);
7540 } else {
7541 t = got_object_tag_get_tagger_time(tag);
7542 got_object_tag_close(tag);
7544 free(id);
7545 if (gmtime_r(&t, &tm) == NULL)
7546 return got_error_from_errno("gmtime_r");
7547 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7548 return got_error(GOT_ERR_NO_SPACE);
7550 if (got_ref_is_symbolic(re->ref)) {
7551 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7552 ymd : "", got_ref_get_name(re->ref),
7553 got_ref_get_symref_target(re->ref)) == -1)
7554 return got_error_from_errno("asprintf");
7555 } else if (s->show_ids) {
7556 struct got_object_id *id;
7557 char *id_str;
7558 err = got_ref_resolve(&id, s->repo, re->ref);
7559 if (err)
7560 return err;
7561 err = got_object_id_str(&id_str, id);
7562 if (err) {
7563 free(id);
7564 return err;
7566 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7567 got_ref_get_name(re->ref), id_str) == -1) {
7568 err = got_error_from_errno("asprintf");
7569 free(id);
7570 free(id_str);
7571 return err;
7573 free(id);
7574 free(id_str);
7575 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7576 got_ref_get_name(re->ref)) == -1)
7577 return got_error_from_errno("asprintf");
7579 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7580 0, 0);
7581 if (err) {
7582 free(line);
7583 return err;
7585 if (n == s->selected) {
7586 if (view->focussed)
7587 wstandout(view->window);
7588 s->selected_entry = re;
7590 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7591 if (tc)
7592 wattr_on(view->window,
7593 COLOR_PAIR(tc->colorpair), NULL);
7594 waddwstr(view->window, wline);
7595 if (tc)
7596 wattr_off(view->window,
7597 COLOR_PAIR(tc->colorpair), NULL);
7598 if (width < view->ncols - 1)
7599 waddch(view->window, '\n');
7600 if (n == s->selected && view->focussed)
7601 wstandend(view->window);
7602 free(line);
7603 free(wline);
7604 wline = NULL;
7605 n++;
7606 s->ndisplayed++;
7607 s->last_displayed_entry = re;
7609 limit--;
7610 re = TAILQ_NEXT(re, entry);
7613 view_border(view);
7614 return err;
7617 static const struct got_error *
7618 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7619 struct tog_reflist_entry *re, struct got_repository *repo)
7621 const struct got_error *err = NULL;
7622 struct got_object_id *commit_id = NULL;
7623 struct tog_view *tree_view;
7625 *new_view = NULL;
7627 err = resolve_reflist_entry(&commit_id, re, repo);
7628 if (err) {
7629 if (err->code != GOT_ERR_OBJ_TYPE)
7630 return err;
7631 else
7632 return NULL;
7636 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7637 if (tree_view == NULL) {
7638 err = got_error_from_errno("view_open");
7639 goto done;
7642 err = open_tree_view(tree_view, commit_id,
7643 got_ref_get_name(re->ref), repo);
7644 if (err)
7645 goto done;
7647 *new_view = tree_view;
7648 done:
7649 free(commit_id);
7650 return err;
7652 static const struct got_error *
7653 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7655 const struct got_error *err = NULL;
7656 struct tog_ref_view_state *s = &view->state.ref;
7657 struct tog_view *log_view, *tree_view;
7658 struct tog_reflist_entry *re;
7659 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 1;
7661 switch (ch) {
7662 case 'i':
7663 s->show_ids = !s->show_ids;
7664 view->count = 0;
7665 break;
7666 case 'm':
7667 s->show_date = !s->show_date;
7668 view->count = 0;
7669 break;
7670 case 'o':
7671 s->sort_by_date = !s->sort_by_date;
7672 view->count = 0;
7673 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7674 got_ref_cmp_by_commit_timestamp_descending :
7675 tog_ref_cmp_by_name, s->repo);
7676 if (err)
7677 break;
7678 got_reflist_object_id_map_free(tog_refs_idmap);
7679 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7680 &tog_refs, s->repo);
7681 if (err)
7682 break;
7683 ref_view_free_refs(s);
7684 err = ref_view_load_refs(s);
7685 break;
7686 case KEY_ENTER:
7687 case '\r':
7688 view->count = 0;
7689 if (!s->selected_entry)
7690 break;
7691 if (view_is_parent_view(view))
7692 view_get_split(view, &begin_y, &begin_x);
7694 err = log_ref_entry(&log_view, begin_y, begin_x,
7695 s->selected_entry, s->repo);
7696 if (err)
7697 break;
7699 if (view_is_parent_view(view) &&
7700 view->mode == TOG_VIEW_SPLIT_HRZN) {
7701 err = view_init_hsplit(view, begin_y);
7702 if (err)
7703 break;
7706 view->focussed = 0;
7707 log_view->focussed = 1;
7708 log_view->mode = view->mode;
7709 log_view->nlines = view->lines - begin_y;
7710 if (view_is_parent_view(view)) {
7711 view_transfer_size(log_view, view);
7712 err = view_close_child(view);
7713 if (err)
7714 return err;
7715 err = view_set_child(view, log_view);
7716 if (err)
7717 return err;
7718 view->focus_child = 1;
7719 } else
7720 *new_view = log_view;
7721 break;
7722 case 't':
7723 view->count = 0;
7724 if (!s->selected_entry)
7725 break;
7726 if (view_is_parent_view(view))
7727 view_get_split(view, &begin_y, &begin_x);
7728 err = browse_ref_tree(&tree_view, begin_y, begin_x,
7729 s->selected_entry, s->repo);
7730 if (err || tree_view == NULL)
7731 break;
7732 if (view_is_parent_view(view) &&
7733 view->mode == TOG_VIEW_SPLIT_HRZN) {
7734 err = view_init_hsplit(view, begin_y);
7735 if (err)
7736 break;
7738 view->focussed = 0;
7739 tree_view->focussed = 1;
7740 tree_view->mode = view->mode;
7741 tree_view->nlines = view->lines - begin_y;
7742 if (view_is_parent_view(view)) {
7743 view_transfer_size(tree_view, view);
7744 err = view_close_child(view);
7745 if (err)
7746 return err;
7747 err = view_set_child(view, tree_view);
7748 if (err)
7749 return err;
7750 view->focus_child = 1;
7751 } else
7752 *new_view = tree_view;
7753 break;
7754 case 'g':
7755 case KEY_HOME:
7756 s->selected = 0;
7757 view->count = 0;
7758 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7759 break;
7760 case 'G':
7761 case KEY_END: {
7762 int eos = view->nlines - 1;
7764 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7765 --eos; /* border */
7766 s->selected = 0;
7767 view->count = 0;
7768 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7769 for (n = 0; n < eos; n++) {
7770 if (re == NULL)
7771 break;
7772 s->first_displayed_entry = re;
7773 re = TAILQ_PREV(re, tog_reflist_head, entry);
7775 if (n > 0)
7776 s->selected = n - 1;
7777 break;
7779 case 'k':
7780 case KEY_UP:
7781 case CTRL('p'):
7782 if (s->selected > 0) {
7783 s->selected--;
7784 break;
7786 ref_scroll_up(s, 1);
7787 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7788 view->count = 0;
7789 break;
7790 case CTRL('u'):
7791 case 'u':
7792 nscroll /= 2;
7793 /* FALL THROUGH */
7794 case KEY_PPAGE:
7795 case CTRL('b'):
7796 case 'b':
7797 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7798 s->selected -= MIN(nscroll, s->selected);
7799 ref_scroll_up(s, MAX(0, nscroll));
7800 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7801 view->count = 0;
7802 break;
7803 case 'j':
7804 case KEY_DOWN:
7805 case CTRL('n'):
7806 if (s->selected < s->ndisplayed - 1) {
7807 s->selected++;
7808 break;
7810 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7811 /* can't scroll any further */
7812 view->count = 0;
7813 break;
7815 ref_scroll_down(view, 1);
7816 break;
7817 case CTRL('d'):
7818 case 'd':
7819 nscroll /= 2;
7820 /* FALL THROUGH */
7821 case KEY_NPAGE:
7822 case CTRL('f'):
7823 case 'f':
7824 case ' ':
7825 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7826 /* can't scroll any further; move cursor down */
7827 if (s->selected < s->ndisplayed - 1)
7828 s->selected += MIN(nscroll,
7829 s->ndisplayed - s->selected - 1);
7830 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7831 s->selected += s->ndisplayed - s->selected - 1;
7832 view->count = 0;
7833 break;
7835 ref_scroll_down(view, nscroll);
7836 break;
7837 case CTRL('l'):
7838 view->count = 0;
7839 tog_free_refs();
7840 err = tog_load_refs(s->repo, s->sort_by_date);
7841 if (err)
7842 break;
7843 ref_view_free_refs(s);
7844 err = ref_view_load_refs(s);
7845 break;
7846 case KEY_RESIZE:
7847 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7848 s->selected = view->nlines - 2;
7849 break;
7850 default:
7851 view->count = 0;
7852 break;
7855 return err;
7858 __dead static void
7859 usage_ref(void)
7861 endwin();
7862 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7863 getprogname());
7864 exit(1);
7867 static const struct got_error *
7868 cmd_ref(int argc, char *argv[])
7870 const struct got_error *error;
7871 struct got_repository *repo = NULL;
7872 struct got_worktree *worktree = NULL;
7873 char *cwd = NULL, *repo_path = NULL;
7874 int ch;
7875 struct tog_view *view;
7876 int *pack_fds = NULL;
7878 while ((ch = getopt(argc, argv, "r:")) != -1) {
7879 switch (ch) {
7880 case 'r':
7881 repo_path = realpath(optarg, NULL);
7882 if (repo_path == NULL)
7883 return got_error_from_errno2("realpath",
7884 optarg);
7885 break;
7886 default:
7887 usage_ref();
7888 /* NOTREACHED */
7892 argc -= optind;
7893 argv += optind;
7895 if (argc > 1)
7896 usage_ref();
7898 error = got_repo_pack_fds_open(&pack_fds);
7899 if (error != NULL)
7900 goto done;
7902 if (repo_path == NULL) {
7903 cwd = getcwd(NULL, 0);
7904 if (cwd == NULL)
7905 return got_error_from_errno("getcwd");
7906 error = got_worktree_open(&worktree, cwd);
7907 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7908 goto done;
7909 if (worktree)
7910 repo_path =
7911 strdup(got_worktree_get_repo_path(worktree));
7912 else
7913 repo_path = strdup(cwd);
7914 if (repo_path == NULL) {
7915 error = got_error_from_errno("strdup");
7916 goto done;
7920 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7921 if (error != NULL)
7922 goto done;
7924 init_curses();
7926 error = apply_unveil(got_repo_get_path(repo), NULL);
7927 if (error)
7928 goto done;
7930 error = tog_load_refs(repo, 0);
7931 if (error)
7932 goto done;
7934 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7935 if (view == NULL) {
7936 error = got_error_from_errno("view_open");
7937 goto done;
7940 error = open_ref_view(view, repo);
7941 if (error)
7942 goto done;
7944 if (worktree) {
7945 /* Release work tree lock. */
7946 got_worktree_close(worktree);
7947 worktree = NULL;
7949 error = view_loop(view);
7950 done:
7951 free(repo_path);
7952 free(cwd);
7953 if (repo) {
7954 const struct got_error *close_err = got_repo_close(repo);
7955 if (close_err)
7956 error = close_err;
7958 if (pack_fds) {
7959 const struct got_error *pack_err =
7960 got_repo_pack_fds_close(pack_fds);
7961 if (error == NULL)
7962 error = pack_err;
7964 tog_free_refs();
7965 return error;
7969 * If view was scrolled down to move the selected line into view when opening a
7970 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7972 static void
7973 offset_selection_up(struct tog_view *view)
7975 switch (view->type) {
7976 case TOG_VIEW_BLAME: {
7977 struct tog_blame_view_state *s = &view->state.blame;
7978 if (s->first_displayed_line == 1) {
7979 s->selected_line = MAX(s->selected_line - view->offset,
7980 1);
7981 break;
7983 if (s->first_displayed_line > view->offset)
7984 s->first_displayed_line -= view->offset;
7985 else
7986 s->first_displayed_line = 1;
7987 s->selected_line += view->offset;
7988 break;
7990 case TOG_VIEW_LOG:
7991 log_scroll_up(&view->state.log, view->offset);
7992 view->state.log.selected += view->offset;
7993 break;
7994 case TOG_VIEW_REF:
7995 ref_scroll_up(&view->state.ref, view->offset);
7996 view->state.ref.selected += view->offset;
7997 break;
7998 case TOG_VIEW_TREE:
7999 tree_scroll_up(&view->state.tree, view->offset);
8000 view->state.tree.selected += view->offset;
8001 break;
8002 default:
8003 break;
8006 view->offset = 0;
8010 * If the selected line is in the section of screen covered by the bottom split,
8011 * scroll down offset lines to move it into view and index its new position.
8013 static const struct got_error *
8014 offset_selection_down(struct tog_view *view)
8016 const struct got_error *err = NULL;
8017 const struct got_error *(*scrolld)(struct tog_view *, int);
8018 int *selected = NULL;
8019 int header, offset;
8021 switch (view->type) {
8022 case TOG_VIEW_BLAME: {
8023 struct tog_blame_view_state *s = &view->state.blame;
8024 header = 3;
8025 scrolld = NULL;
8026 if (s->selected_line > view->nlines - header) {
8027 offset = abs(view->nlines - s->selected_line - header);
8028 s->first_displayed_line += offset;
8029 s->selected_line -= offset;
8030 view->offset = offset;
8032 break;
8034 case TOG_VIEW_LOG: {
8035 struct tog_log_view_state *s = &view->state.log;
8036 scrolld = &log_scroll_down;
8037 header = view_is_parent_view(view) ? 3 : 2;
8038 selected = &s->selected;
8039 break;
8041 case TOG_VIEW_REF: {
8042 struct tog_ref_view_state *s = &view->state.ref;
8043 scrolld = &ref_scroll_down;
8044 header = 3;
8045 selected = &s->selected;
8046 break;
8048 case TOG_VIEW_TREE: {
8049 struct tog_tree_view_state *s = &view->state.tree;
8050 scrolld = &tree_scroll_down;
8051 header = 5;
8052 selected = &s->selected;
8053 break;
8055 default:
8056 selected = NULL;
8057 scrolld = NULL;
8058 header = 0;
8059 break;
8062 if (selected && *selected > view->nlines - header) {
8063 offset = abs(view->nlines - *selected - header);
8064 view->offset = offset;
8065 if (scrolld && offset) {
8066 err = scrolld(view, offset);
8067 *selected -= offset;
8071 return err;
8074 static void
8075 list_commands(FILE *fp)
8077 size_t i;
8079 fprintf(fp, "commands:");
8080 for (i = 0; i < nitems(tog_commands); i++) {
8081 const struct tog_cmd *cmd = &tog_commands[i];
8082 fprintf(fp, " %s", cmd->name);
8084 fputc('\n', fp);
8087 __dead static void
8088 usage(int hflag, int status)
8090 FILE *fp = (status == 0) ? stdout : stderr;
8092 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8093 getprogname());
8094 if (hflag) {
8095 fprintf(fp, "lazy usage: %s path\n", getprogname());
8096 list_commands(fp);
8098 exit(status);
8101 static char **
8102 make_argv(int argc, ...)
8104 va_list ap;
8105 char **argv;
8106 int i;
8108 va_start(ap, argc);
8110 argv = calloc(argc, sizeof(char *));
8111 if (argv == NULL)
8112 err(1, "calloc");
8113 for (i = 0; i < argc; i++) {
8114 argv[i] = strdup(va_arg(ap, char *));
8115 if (argv[i] == NULL)
8116 err(1, "strdup");
8119 va_end(ap);
8120 return argv;
8124 * Try to convert 'tog path' into a 'tog log path' command.
8125 * The user could simply have mistyped the command rather than knowingly
8126 * provided a path. So check whether argv[0] can in fact be resolved
8127 * to a path in the HEAD commit and print a special error if not.
8128 * This hack is for mpi@ <3
8130 static const struct got_error *
8131 tog_log_with_path(int argc, char *argv[])
8133 const struct got_error *error = NULL, *close_err;
8134 const struct tog_cmd *cmd = NULL;
8135 struct got_repository *repo = NULL;
8136 struct got_worktree *worktree = NULL;
8137 struct got_object_id *commit_id = NULL, *id = NULL;
8138 struct got_commit_object *commit = NULL;
8139 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8140 char *commit_id_str = NULL, **cmd_argv = NULL;
8141 int *pack_fds = NULL;
8143 cwd = getcwd(NULL, 0);
8144 if (cwd == NULL)
8145 return got_error_from_errno("getcwd");
8147 error = got_repo_pack_fds_open(&pack_fds);
8148 if (error != NULL)
8149 goto done;
8151 error = got_worktree_open(&worktree, cwd);
8152 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8153 goto done;
8155 if (worktree)
8156 repo_path = strdup(got_worktree_get_repo_path(worktree));
8157 else
8158 repo_path = strdup(cwd);
8159 if (repo_path == NULL) {
8160 error = got_error_from_errno("strdup");
8161 goto done;
8164 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8165 if (error != NULL)
8166 goto done;
8168 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8169 repo, worktree);
8170 if (error)
8171 goto done;
8173 error = tog_load_refs(repo, 0);
8174 if (error)
8175 goto done;
8176 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8177 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8178 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8179 if (error)
8180 goto done;
8182 if (worktree) {
8183 got_worktree_close(worktree);
8184 worktree = NULL;
8187 error = got_object_open_as_commit(&commit, repo, commit_id);
8188 if (error)
8189 goto done;
8191 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8192 if (error) {
8193 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8194 goto done;
8195 fprintf(stderr, "%s: '%s' is no known command or path\n",
8196 getprogname(), argv[0]);
8197 usage(1, 1);
8198 /* not reached */
8201 close_err = got_repo_close(repo);
8202 if (error == NULL)
8203 error = close_err;
8204 repo = NULL;
8206 error = got_object_id_str(&commit_id_str, commit_id);
8207 if (error)
8208 goto done;
8210 cmd = &tog_commands[0]; /* log */
8211 argc = 4;
8212 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8213 error = cmd->cmd_main(argc, cmd_argv);
8214 done:
8215 if (repo) {
8216 close_err = got_repo_close(repo);
8217 if (error == NULL)
8218 error = close_err;
8220 if (commit)
8221 got_object_commit_close(commit);
8222 if (worktree)
8223 got_worktree_close(worktree);
8224 if (pack_fds) {
8225 const struct got_error *pack_err =
8226 got_repo_pack_fds_close(pack_fds);
8227 if (error == NULL)
8228 error = pack_err;
8230 free(id);
8231 free(commit_id_str);
8232 free(commit_id);
8233 free(cwd);
8234 free(repo_path);
8235 free(in_repo_path);
8236 if (cmd_argv) {
8237 int i;
8238 for (i = 0; i < argc; i++)
8239 free(cmd_argv[i]);
8240 free(cmd_argv);
8242 tog_free_refs();
8243 return error;
8246 int
8247 main(int argc, char *argv[])
8249 const struct got_error *error = NULL;
8250 const struct tog_cmd *cmd = NULL;
8251 int ch, hflag = 0, Vflag = 0;
8252 char **cmd_argv = NULL;
8253 static const struct option longopts[] = {
8254 { "version", no_argument, NULL, 'V' },
8255 { NULL, 0, NULL, 0}
8257 char *diff_algo_str = NULL;
8259 setlocale(LC_CTYPE, "");
8261 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8262 switch (ch) {
8263 case 'h':
8264 hflag = 1;
8265 break;
8266 case 'V':
8267 Vflag = 1;
8268 break;
8269 default:
8270 usage(hflag, 1);
8271 /* NOTREACHED */
8275 argc -= optind;
8276 argv += optind;
8277 optind = 1;
8278 optreset = 1;
8280 if (Vflag) {
8281 got_version_print_str();
8282 return 0;
8285 #ifndef PROFILE
8286 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8287 NULL) == -1)
8288 err(1, "pledge");
8289 #endif
8291 if (argc == 0) {
8292 if (hflag)
8293 usage(hflag, 0);
8294 /* Build an argument vector which runs a default command. */
8295 cmd = &tog_commands[0];
8296 argc = 1;
8297 cmd_argv = make_argv(argc, cmd->name);
8298 } else {
8299 size_t i;
8301 /* Did the user specify a command? */
8302 for (i = 0; i < nitems(tog_commands); i++) {
8303 if (strncmp(tog_commands[i].name, argv[0],
8304 strlen(argv[0])) == 0) {
8305 cmd = &tog_commands[i];
8306 break;
8311 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8312 if (diff_algo_str) {
8313 if (strcasecmp(diff_algo_str, "patience") == 0)
8314 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8315 if (strcasecmp(diff_algo_str, "myers") == 0)
8316 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8319 if (cmd == NULL) {
8320 if (argc != 1)
8321 usage(0, 1);
8322 /* No command specified; try log with a path */
8323 error = tog_log_with_path(argc, argv);
8324 } else {
8325 if (hflag)
8326 cmd->cmd_usage();
8327 else
8328 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8331 endwin();
8332 putchar('\n');
8333 if (cmd_argv) {
8334 int i;
8335 for (i = 0; i < argc; i++)
8336 free(cmd_argv[i]);
8337 free(cmd_argv);
8340 if (error && error->code != GOT_ERR_CANCELLED)
8341 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8342 return 0;