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 int use_committer;
385 };
387 #define TOG_COLOR_DIFF_MINUS 1
388 #define TOG_COLOR_DIFF_PLUS 2
389 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
390 #define TOG_COLOR_DIFF_META 4
391 #define TOG_COLOR_TREE_SUBMODULE 5
392 #define TOG_COLOR_TREE_SYMLINK 6
393 #define TOG_COLOR_TREE_DIRECTORY 7
394 #define TOG_COLOR_TREE_EXECUTABLE 8
395 #define TOG_COLOR_COMMIT 9
396 #define TOG_COLOR_AUTHOR 10
397 #define TOG_COLOR_DATE 11
398 #define TOG_COLOR_REFS_HEADS 12
399 #define TOG_COLOR_REFS_TAGS 13
400 #define TOG_COLOR_REFS_REMOTES 14
401 #define TOG_COLOR_REFS_BACKUP 15
403 struct tog_blame_cb_args {
404 struct tog_blame_line *lines; /* one per line */
405 int nlines;
407 struct tog_view *view;
408 struct got_object_id *commit_id;
409 int *quit;
410 };
412 struct tog_blame_thread_args {
413 const char *path;
414 struct got_repository *repo;
415 struct tog_blame_cb_args *cb_args;
416 int *complete;
417 got_cancel_cb cancel_cb;
418 void *cancel_arg;
419 };
421 struct tog_blame {
422 FILE *f;
423 off_t filesize;
424 struct tog_blame_line *lines;
425 int nlines;
426 off_t *line_offsets;
427 pthread_t thread;
428 struct tog_blame_thread_args thread_args;
429 struct tog_blame_cb_args cb_args;
430 const char *path;
431 int *pack_fds;
432 };
434 struct tog_blame_view_state {
435 int first_displayed_line;
436 int last_displayed_line;
437 int selected_line;
438 int last_diffed_line;
439 int blame_complete;
440 int eof;
441 int done;
442 struct got_object_id_queue blamed_commits;
443 struct got_object_qid *blamed_commit;
444 char *path;
445 struct got_repository *repo;
446 struct got_object_id *commit_id;
447 struct tog_blame blame;
448 int matched_line;
449 struct tog_colors colors;
450 };
452 struct tog_parent_tree {
453 TAILQ_ENTRY(tog_parent_tree) entry;
454 struct got_tree_object *tree;
455 struct got_tree_entry *first_displayed_entry;
456 struct got_tree_entry *selected_entry;
457 int selected;
458 };
460 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
462 struct tog_tree_view_state {
463 char *tree_label;
464 struct got_object_id *commit_id;/* commit which this tree belongs to */
465 struct got_tree_object *root; /* the commit's root tree entry */
466 struct got_tree_object *tree; /* currently displayed (sub-)tree */
467 struct got_tree_entry *first_displayed_entry;
468 struct got_tree_entry *last_displayed_entry;
469 struct got_tree_entry *selected_entry;
470 int ndisplayed, selected, show_ids;
471 struct tog_parent_trees parents; /* parent trees of current sub-tree */
472 char *head_ref_name;
473 struct got_repository *repo;
474 struct got_tree_entry *matched_entry;
475 struct tog_colors colors;
476 };
478 struct tog_reflist_entry {
479 TAILQ_ENTRY(tog_reflist_entry) entry;
480 struct got_reference *ref;
481 int idx;
482 };
484 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
486 struct tog_ref_view_state {
487 struct tog_reflist_head refs;
488 struct tog_reflist_entry *first_displayed_entry;
489 struct tog_reflist_entry *last_displayed_entry;
490 struct tog_reflist_entry *selected_entry;
491 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
492 struct got_repository *repo;
493 struct tog_reflist_entry *matched_entry;
494 struct tog_colors colors;
495 };
497 /*
498 * We implement two types of views: parent views and child views.
500 * The 'Tab' key switches focus between a parent view and its child view.
501 * Child views are shown side-by-side to their parent view, provided
502 * there is enough screen estate.
504 * When a new view is opened from within a parent view, this new view
505 * becomes a child view of the parent view, replacing any existing child.
507 * When a new view is opened from within a child view, this new view
508 * becomes a parent view which will obscure the views below until the
509 * user quits the new parent view by typing 'q'.
511 * This list of views contains parent views only.
512 * Child views are only pointed to by their parent view.
513 */
514 TAILQ_HEAD(tog_view_list_head, tog_view);
516 struct tog_view {
517 TAILQ_ENTRY(tog_view) entry;
518 WINDOW *window;
519 PANEL *panel;
520 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
521 int resized_y, resized_x; /* begin_y/x based on user resizing */
522 int maxx, x; /* max column and current start column */
523 int lines, cols; /* copies of LINES and COLS */
524 int nscrolled, offset; /* lines scrolled and hsplit line offset */
525 int ch, count; /* current keymap and count prefix */
526 int resized; /* set when in a resize event */
527 int focussed; /* Only set on one parent or child view at a time. */
528 int dying;
529 struct tog_view *parent;
530 struct tog_view *child;
532 /*
533 * This flag is initially set on parent views when a new child view
534 * is created. It gets toggled when the 'Tab' key switches focus
535 * between parent and child.
536 * The flag indicates whether focus should be passed on to our child
537 * view if this parent view gets picked for focus after another parent
538 * view was closed. This prevents child views from losing focus in such
539 * situations.
540 */
541 int focus_child;
543 enum tog_view_mode mode;
544 /* type-specific state */
545 enum tog_view_type type;
546 union {
547 struct tog_diff_view_state diff;
548 struct tog_log_view_state log;
549 struct tog_blame_view_state blame;
550 struct tog_tree_view_state tree;
551 struct tog_ref_view_state ref;
552 } state;
554 const struct got_error *(*show)(struct tog_view *);
555 const struct got_error *(*input)(struct tog_view **,
556 struct tog_view *, int);
557 const struct got_error *(*reset)(struct tog_view *);
558 const struct got_error *(*resize)(struct tog_view *, int);
559 const struct got_error *(*close)(struct tog_view *);
561 const struct got_error *(*search_start)(struct tog_view *);
562 const struct got_error *(*search_next)(struct tog_view *);
563 int search_started;
564 int searching;
565 #define TOG_SEARCH_FORWARD 1
566 #define TOG_SEARCH_BACKWARD 2
567 int search_next_done;
568 #define TOG_SEARCH_HAVE_MORE 1
569 #define TOG_SEARCH_NO_MORE 2
570 #define TOG_SEARCH_HAVE_NONE 3
571 regex_t regex;
572 regmatch_t regmatch;
573 };
575 static const struct got_error *open_diff_view(struct tog_view *,
576 struct got_object_id *, struct got_object_id *,
577 const char *, const char *, int, int, int, struct tog_view *,
578 struct got_repository *);
579 static const struct got_error *show_diff_view(struct tog_view *);
580 static const struct got_error *input_diff_view(struct tog_view **,
581 struct tog_view *, int);
582 static const struct got_error *reset_diff_view(struct tog_view *);
583 static const struct got_error* close_diff_view(struct tog_view *);
584 static const struct got_error *search_start_diff_view(struct tog_view *);
585 static const struct got_error *search_next_diff_view(struct tog_view *);
587 static const struct got_error *open_log_view(struct tog_view *,
588 struct got_object_id *, struct got_repository *,
589 const char *, const char *, int);
590 static const struct got_error * show_log_view(struct tog_view *);
591 static const struct got_error *input_log_view(struct tog_view **,
592 struct tog_view *, int);
593 static const struct got_error *resize_log_view(struct tog_view *, int);
594 static const struct got_error *close_log_view(struct tog_view *);
595 static const struct got_error *search_start_log_view(struct tog_view *);
596 static const struct got_error *search_next_log_view(struct tog_view *);
598 static const struct got_error *open_blame_view(struct tog_view *, char *,
599 struct got_object_id *, struct got_repository *);
600 static const struct got_error *show_blame_view(struct tog_view *);
601 static const struct got_error *input_blame_view(struct tog_view **,
602 struct tog_view *, int);
603 static const struct got_error *reset_blame_view(struct tog_view *);
604 static const struct got_error *close_blame_view(struct tog_view *);
605 static const struct got_error *search_start_blame_view(struct tog_view *);
606 static const struct got_error *search_next_blame_view(struct tog_view *);
608 static const struct got_error *open_tree_view(struct tog_view *,
609 struct got_object_id *, const char *, struct got_repository *);
610 static const struct got_error *show_tree_view(struct tog_view *);
611 static const struct got_error *input_tree_view(struct tog_view **,
612 struct tog_view *, int);
613 static const struct got_error *close_tree_view(struct tog_view *);
614 static const struct got_error *search_start_tree_view(struct tog_view *);
615 static const struct got_error *search_next_tree_view(struct tog_view *);
617 static const struct got_error *open_ref_view(struct tog_view *,
618 struct got_repository *);
619 static const struct got_error *show_ref_view(struct tog_view *);
620 static const struct got_error *input_ref_view(struct tog_view **,
621 struct tog_view *, int);
622 static const struct got_error *close_ref_view(struct tog_view *);
623 static const struct got_error *search_start_ref_view(struct tog_view *);
624 static const struct got_error *search_next_ref_view(struct tog_view *);
626 static volatile sig_atomic_t tog_sigwinch_received;
627 static volatile sig_atomic_t tog_sigpipe_received;
628 static volatile sig_atomic_t tog_sigcont_received;
629 static volatile sig_atomic_t tog_sigint_received;
630 static volatile sig_atomic_t tog_sigterm_received;
632 static void
633 tog_sigwinch(int signo)
635 tog_sigwinch_received = 1;
638 static void
639 tog_sigpipe(int signo)
641 tog_sigpipe_received = 1;
644 static void
645 tog_sigcont(int signo)
647 tog_sigcont_received = 1;
650 static void
651 tog_sigint(int signo)
653 tog_sigint_received = 1;
656 static void
657 tog_sigterm(int signo)
659 tog_sigterm_received = 1;
662 static int
663 tog_fatal_signal_received(void)
665 return (tog_sigpipe_received ||
666 tog_sigint_received || tog_sigint_received);
669 static const struct got_error *
670 view_close(struct tog_view *view)
672 const struct got_error *err = NULL, *child_err = NULL;
674 if (view->child) {
675 child_err = view_close(view->child);
676 view->child = NULL;
678 if (view->close)
679 err = view->close(view);
680 if (view->panel)
681 del_panel(view->panel);
682 if (view->window)
683 delwin(view->window);
684 free(view);
685 return err ? err : child_err;
688 static struct tog_view *
689 view_open(int nlines, int ncols, int begin_y, int begin_x,
690 enum tog_view_type type)
692 struct tog_view *view = calloc(1, sizeof(*view));
694 if (view == NULL)
695 return NULL;
697 view->type = type;
698 view->lines = LINES;
699 view->cols = COLS;
700 view->nlines = nlines ? nlines : LINES - begin_y;
701 view->ncols = ncols ? ncols : COLS - begin_x;
702 view->begin_y = begin_y;
703 view->begin_x = begin_x;
704 view->window = newwin(nlines, ncols, begin_y, begin_x);
705 if (view->window == NULL) {
706 view_close(view);
707 return NULL;
709 view->panel = new_panel(view->window);
710 if (view->panel == NULL ||
711 set_panel_userptr(view->panel, view) != OK) {
712 view_close(view);
713 return NULL;
716 keypad(view->window, TRUE);
717 return view;
720 static int
721 view_split_begin_x(int begin_x)
723 if (begin_x > 0 || COLS < 120)
724 return 0;
725 return (COLS - MAX(COLS / 2, 80));
728 /* XXX Stub till we decide what to do. */
729 static int
730 view_split_begin_y(int lines)
732 return lines * HSPLIT_SCALE;
735 static const struct got_error *view_resize(struct tog_view *);
737 static const struct got_error *
738 view_splitscreen(struct tog_view *view)
740 const struct got_error *err = NULL;
742 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
743 if (view->resized_y && view->resized_y < view->lines)
744 view->begin_y = view->resized_y;
745 else
746 view->begin_y = view_split_begin_y(view->nlines);
747 view->begin_x = 0;
748 } else if (!view->resized) {
749 if (view->resized_x && view->resized_x < view->cols - 1 &&
750 view->cols > 119)
751 view->begin_x = view->resized_x;
752 else
753 view->begin_x = view_split_begin_x(0);
754 view->begin_y = 0;
756 view->nlines = LINES - view->begin_y;
757 view->ncols = COLS - view->begin_x;
758 view->lines = LINES;
759 view->cols = COLS;
760 err = view_resize(view);
761 if (err)
762 return err;
764 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
765 view->parent->nlines = view->begin_y;
767 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
768 return got_error_from_errno("mvwin");
770 return NULL;
773 static const struct got_error *
774 view_fullscreen(struct tog_view *view)
776 const struct got_error *err = NULL;
778 view->begin_x = 0;
779 view->begin_y = view->resized ? view->begin_y : 0;
780 view->nlines = view->resized ? view->nlines : LINES;
781 view->ncols = COLS;
782 view->lines = LINES;
783 view->cols = COLS;
784 err = view_resize(view);
785 if (err)
786 return err;
788 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
789 return got_error_from_errno("mvwin");
791 return NULL;
794 static int
795 view_is_parent_view(struct tog_view *view)
797 return view->parent == NULL;
800 static int
801 view_is_splitscreen(struct tog_view *view)
803 return view->begin_x > 0 || view->begin_y > 0;
806 static int
807 view_is_fullscreen(struct tog_view *view)
809 return view->nlines == LINES && view->ncols == COLS;
812 static int
813 view_is_hsplit_top(struct tog_view *view)
815 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
816 view_is_splitscreen(view->child);
819 static void
820 view_border(struct tog_view *view)
822 PANEL *panel;
823 const struct tog_view *view_above;
825 if (view->parent)
826 return view_border(view->parent);
828 panel = panel_above(view->panel);
829 if (panel == NULL)
830 return;
832 view_above = panel_userptr(panel);
833 if (view->mode == TOG_VIEW_SPLIT_HRZN)
834 mvwhline(view->window, view_above->begin_y - 1,
835 view->begin_x, got_locale_is_utf8() ?
836 ACS_HLINE : '-', view->ncols);
837 else
838 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
839 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
842 static const struct got_error *view_init_hsplit(struct tog_view *, int);
843 static const struct got_error *request_log_commits(struct tog_view *);
844 static const struct got_error *offset_selection_down(struct tog_view *);
845 static void offset_selection_up(struct tog_view *);
846 static void view_get_split(struct tog_view *, int *, int *);
848 static const struct got_error *
849 view_resize(struct tog_view *view)
851 const struct got_error *err = NULL;
852 int dif, nlines, ncols;
854 dif = LINES - view->lines; /* line difference */
856 if (view->lines > LINES)
857 nlines = view->nlines - (view->lines - LINES);
858 else
859 nlines = view->nlines + (LINES - view->lines);
860 if (view->cols > COLS)
861 ncols = view->ncols - (view->cols - COLS);
862 else
863 ncols = view->ncols + (COLS - view->cols);
865 if (view->child) {
866 int hs = view->child->begin_y;
868 if (!view_is_fullscreen(view))
869 view->child->begin_x = view_split_begin_x(view->begin_x);
870 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
871 view->child->begin_x == 0) {
872 ncols = COLS;
874 view_fullscreen(view->child);
875 if (view->child->focussed)
876 show_panel(view->child->panel);
877 else
878 show_panel(view->panel);
879 } else {
880 ncols = view->child->begin_x;
882 view_splitscreen(view->child);
883 show_panel(view->child->panel);
885 /*
886 * XXX This is ugly and needs to be moved into the above
887 * logic but "works" for now and my attempts at moving it
888 * break either 'tab' or 'F' key maps in horizontal splits.
889 */
890 if (hs) {
891 err = view_splitscreen(view->child);
892 if (err)
893 return err;
894 if (dif < 0) { /* top split decreased */
895 err = offset_selection_down(view);
896 if (err)
897 return err;
899 view_border(view);
900 update_panels();
901 doupdate();
902 show_panel(view->child->panel);
903 nlines = view->nlines;
905 } else if (view->parent == NULL)
906 ncols = COLS;
908 if (view->resize && dif > 0) {
909 err = view->resize(view, dif);
910 if (err)
911 return err;
914 if (wresize(view->window, nlines, ncols) == ERR)
915 return got_error_from_errno("wresize");
916 if (replace_panel(view->panel, view->window) == ERR)
917 return got_error_from_errno("replace_panel");
918 wclear(view->window);
920 view->nlines = nlines;
921 view->ncols = ncols;
922 view->lines = LINES;
923 view->cols = COLS;
925 return NULL;
928 static const struct got_error *
929 resize_log_view(struct tog_view *view, int increase)
931 struct tog_log_view_state *s = &view->state.log;
932 const struct got_error *err = NULL;
933 int n = s->selected_entry->idx + view->lines - s->selected;
935 /*
936 * Request commits to account for the increased
937 * height so we have enough to populate the view.
938 */
939 if (s->commits.ncommits < n) {
940 view->nscrolled = n - s->commits.ncommits + increase + 1;
941 err = request_log_commits(view);
944 return err;
947 static void
948 view_adjust_offset(struct tog_view *view, int n)
950 if (n == 0)
951 return;
953 if (view->parent && view->parent->offset) {
954 if (view->parent->offset + n >= 0)
955 view->parent->offset += n;
956 else
957 view->parent->offset = 0;
958 } else if (view->offset) {
959 if (view->offset - n >= 0)
960 view->offset -= n;
961 else
962 view->offset = 0;
966 static const struct got_error *
967 view_resize_split(struct tog_view *view, int resize)
969 const struct got_error *err = NULL;
970 struct tog_view *v = NULL;
972 if (view->parent)
973 v = view->parent;
974 else
975 v = view;
977 if (!v->child || !view_is_splitscreen(v->child))
978 return NULL;
980 v->resized = v->child->resized = resize; /* lock for resize event */
982 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
983 int y = v->child->begin_y;
985 if (v->child->resized_y)
986 v->child->begin_y = v->child->resized_y;
987 if (view->parent)
988 v->child->begin_y -= resize;
989 else
990 v->child->begin_y += resize;
991 if (v->child->begin_y < 3) {
992 view->count = 0;
993 v->child->begin_y = 3;
994 } else if (v->child->begin_y > LINES - 1) {
995 view->count = 0;
996 v->child->begin_y = LINES - 1;
998 v->ncols = COLS;
999 v->child->ncols = COLS;
1000 view_adjust_offset(view, resize);
1001 err = view_init_hsplit(v, v->child->begin_y);
1002 if (err)
1003 return err;
1004 v->child->resized_y = v->child->begin_y;
1005 if (y > v->child->begin_y && v->child->type == TOG_VIEW_LOG)
1006 v->child->nscrolled = y - v->child->begin_y;
1007 else if (y < v->child->begin_y && v->type == TOG_VIEW_LOG)
1008 v->nscrolled = v->child->begin_y - y;
1009 } else {
1010 if (v->child->resized_x)
1011 v->child->begin_x = v->child->resized_x;
1012 if (view->parent)
1013 v->child->begin_x -= resize;
1014 else
1015 v->child->begin_x += resize;
1016 if (v->child->begin_x < 11) {
1017 view->count = 0;
1018 v->child->begin_x = 11;
1019 } else if (v->child->begin_x > COLS - 1) {
1020 view->count = 0;
1021 v->child->begin_x = COLS - 1;
1023 v->child->resized_x = v->child->begin_x;
1026 v->child->mode = v->mode;
1027 v->child->nlines = v->lines - v->child->begin_y;
1028 v->child->ncols = v->cols - v->child->begin_x;
1029 v->focus_child = 1;
1031 err = view_fullscreen(v);
1032 if (err)
1033 return err;
1034 err = view_splitscreen(v->child);
1035 if (err)
1036 return err;
1038 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1039 err = offset_selection_down(v->child);
1040 if (err)
1041 return err;
1044 if (v->nscrolled)
1045 err = request_log_commits(v);
1046 else if (v->child->nscrolled)
1047 err = request_log_commits(v->child);
1049 v->resized = v->child->resized = 0;
1051 return err;
1054 static void
1055 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1057 struct tog_view *v = src->child ? src->child : src;
1059 dst->resized_x = v->resized_x;
1060 dst->resized_y = v->resized_y;
1063 static const struct got_error *
1064 view_close_child(struct tog_view *view)
1066 const struct got_error *err = NULL;
1068 if (view->child == NULL)
1069 return NULL;
1071 err = view_close(view->child);
1072 view->child = NULL;
1073 return err;
1076 static const struct got_error *
1077 view_set_child(struct tog_view *view, struct tog_view *child)
1079 const struct got_error *err = NULL;
1081 view->child = child;
1082 child->parent = view;
1084 err = view_resize(view);
1085 if (err)
1086 return err;
1088 if (view->child->resized_x || view->child->resized_y)
1089 err = view_resize_split(view, 0);
1091 return err;
1094 static void
1095 tog_resizeterm(void)
1097 int cols, lines;
1098 struct winsize size;
1100 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1101 cols = 80; /* Default */
1102 lines = 24;
1103 } else {
1104 cols = size.ws_col;
1105 lines = size.ws_row;
1107 resize_term(lines, cols);
1110 static const struct got_error *
1111 view_search_start(struct tog_view *view)
1113 const struct got_error *err = NULL;
1114 struct tog_view *v = view;
1115 char pattern[1024];
1116 int ret;
1118 if (view->search_started) {
1119 regfree(&view->regex);
1120 view->searching = 0;
1121 memset(&view->regmatch, 0, sizeof(view->regmatch));
1123 view->search_started = 0;
1125 if (view->nlines < 1)
1126 return NULL;
1128 if (view_is_hsplit_top(view))
1129 v = view->child;
1131 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1132 wclrtoeol(v->window);
1134 nodelay(view->window, FALSE); /* block for search term input */
1135 nocbreak();
1136 echo();
1137 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1138 wrefresh(v->window);
1139 cbreak();
1140 noecho();
1141 nodelay(view->window, TRUE);
1142 if (ret == ERR)
1143 return NULL;
1145 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1146 err = view->search_start(view);
1147 if (err) {
1148 regfree(&view->regex);
1149 return err;
1151 view->search_started = 1;
1152 view->searching = TOG_SEARCH_FORWARD;
1153 view->search_next_done = 0;
1154 view->search_next(view);
1157 return NULL;
1160 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1161 static const struct got_error *
1162 switch_split(struct tog_view *view)
1164 const struct got_error *err = NULL;
1165 struct tog_view *v = NULL;
1167 if (view->parent)
1168 v = view->parent;
1169 else
1170 v = view;
1172 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1173 v->mode = TOG_VIEW_SPLIT_VERT;
1174 else
1175 v->mode = TOG_VIEW_SPLIT_HRZN;
1177 if (!v->child)
1178 return NULL;
1179 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1180 v->mode = TOG_VIEW_SPLIT_NONE;
1182 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1183 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1184 v->child->begin_y = v->child->resized_y;
1185 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1186 v->child->begin_x = v->child->resized_x;
1189 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1190 v->ncols = COLS;
1191 v->child->ncols = COLS;
1192 v->child->nscrolled = LINES - v->child->nlines;
1194 err = view_init_hsplit(v, v->child->begin_y);
1195 if (err)
1196 return err;
1198 v->child->mode = v->mode;
1199 v->child->nlines = v->lines - v->child->begin_y;
1200 v->focus_child = 1;
1202 err = view_fullscreen(v);
1203 if (err)
1204 return err;
1205 err = view_splitscreen(v->child);
1206 if (err)
1207 return err;
1209 if (v->mode == TOG_VIEW_SPLIT_NONE)
1210 v->mode = TOG_VIEW_SPLIT_VERT;
1211 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1212 err = offset_selection_down(v);
1213 err = offset_selection_down(v->child);
1214 } else {
1215 offset_selection_up(v);
1216 offset_selection_up(v->child);
1218 if (v->type == TOG_VIEW_LOG && v->nscrolled)
1219 err = request_log_commits(v);
1220 else if (v->child->type == TOG_VIEW_LOG && v->child->nscrolled)
1221 err = request_log_commits(v->child);
1223 return err;
1227 * Compute view->count from numeric input. Assign total to view->count and
1228 * return first non-numeric key entered.
1230 static int
1231 get_compound_key(struct tog_view *view, int c)
1233 struct tog_view *v = view;
1234 int x, n = 0;
1236 if (view_is_hsplit_top(view))
1237 v = view->child;
1238 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1239 v = view->parent;
1241 view->count = 0;
1242 cbreak(); /* block for input */
1243 wmove(v->window, v->nlines - 1, 0);
1244 wclrtoeol(v->window);
1245 waddch(v->window, ':');
1247 do {
1248 x = getcurx(v->window);
1249 if (x != ERR && x < view->ncols) {
1250 waddch(v->window, c);
1251 wrefresh(v->window);
1255 * Don't overflow. Max valid request should be the greatest
1256 * between the longest and total lines; cap at 10 million.
1258 if (n >= 9999999)
1259 n = 9999999;
1260 else
1261 n = n * 10 + (c - '0');
1262 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1264 /* Massage excessive or inapplicable values at the input handler. */
1265 view->count = n;
1267 return c;
1270 static const struct got_error *
1271 view_input(struct tog_view **new, int *done, struct tog_view *view,
1272 struct tog_view_list_head *views)
1274 const struct got_error *err = NULL;
1275 struct tog_view *v;
1276 int ch, errcode;
1278 *new = NULL;
1280 /* Clear "no matches" indicator. */
1281 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1282 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1283 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1284 view->count = 0;
1287 if (view->searching && !view->search_next_done) {
1288 errcode = pthread_mutex_unlock(&tog_mutex);
1289 if (errcode)
1290 return got_error_set_errno(errcode,
1291 "pthread_mutex_unlock");
1292 sched_yield();
1293 errcode = pthread_mutex_lock(&tog_mutex);
1294 if (errcode)
1295 return got_error_set_errno(errcode,
1296 "pthread_mutex_lock");
1297 view->search_next(view);
1298 return NULL;
1301 nodelay(view->window, FALSE);
1302 /* Allow threads to make progress while we are waiting for input. */
1303 errcode = pthread_mutex_unlock(&tog_mutex);
1304 if (errcode)
1305 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1306 /* If we have an unfinished count, let C-g or backspace abort. */
1307 if (view->count && --view->count) {
1308 cbreak();
1309 nodelay(view->window, TRUE);
1310 ch = wgetch(view->window);
1311 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1312 view->count = 0;
1313 else
1314 ch = view->ch;
1315 } else {
1316 ch = wgetch(view->window);
1317 if (ch >= '1' && ch <= '9')
1318 view->ch = ch = get_compound_key(view, ch);
1320 errcode = pthread_mutex_lock(&tog_mutex);
1321 if (errcode)
1322 return got_error_set_errno(errcode, "pthread_mutex_lock");
1323 nodelay(view->window, TRUE);
1325 if (tog_sigwinch_received || tog_sigcont_received) {
1326 tog_resizeterm();
1327 tog_sigwinch_received = 0;
1328 tog_sigcont_received = 0;
1329 TAILQ_FOREACH(v, views, entry) {
1330 err = view_resize(v);
1331 if (err)
1332 return err;
1333 err = v->input(new, v, KEY_RESIZE);
1334 if (err)
1335 return err;
1336 if (v->child) {
1337 err = view_resize(v->child);
1338 if (err)
1339 return err;
1340 err = v->child->input(new, v->child,
1341 KEY_RESIZE);
1342 if (err)
1343 return err;
1344 if (v->child->resized_x || v->child->resized_y) {
1345 err = view_resize_split(v, 0);
1346 if (err)
1347 return err;
1353 switch (ch) {
1354 case '\t':
1355 view->count = 0;
1356 if (view->child) {
1357 view->focussed = 0;
1358 view->child->focussed = 1;
1359 view->focus_child = 1;
1360 } else if (view->parent) {
1361 view->focussed = 0;
1362 view->parent->focussed = 1;
1363 view->parent->focus_child = 0;
1364 if (!view_is_splitscreen(view)) {
1365 if (view->mode == TOG_VIEW_SPLIT_HRZN &&
1366 view->parent->type == TOG_VIEW_LOG) {
1367 err = request_log_commits(view->parent);
1368 if (err)
1369 return err;
1371 offset_selection_up(view->parent);
1372 err = view_fullscreen(view->parent);
1373 if (err)
1374 return err;
1377 break;
1378 case 'q':
1379 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1380 if (view->parent->type == TOG_VIEW_LOG) {
1381 /* might need more commits to fill fullscreen */
1382 err = request_log_commits(view->parent);
1383 if (err)
1384 break;
1386 offset_selection_up(view->parent);
1388 err = view->input(new, view, ch);
1389 view->dying = 1;
1390 break;
1391 case 'Q':
1392 *done = 1;
1393 break;
1394 case 'F':
1395 view->count = 0;
1396 if (view_is_parent_view(view)) {
1397 if (view->child == NULL)
1398 break;
1399 if (view_is_splitscreen(view->child)) {
1400 view->focussed = 0;
1401 view->child->focussed = 1;
1402 err = view_fullscreen(view->child);
1403 } else {
1404 err = view_splitscreen(view->child);
1405 if (!err)
1406 err = view_resize_split(view, 0);
1408 if (err)
1409 break;
1410 err = view->child->input(new, view->child,
1411 KEY_RESIZE);
1412 } else {
1413 if (view_is_splitscreen(view)) {
1414 view->parent->focussed = 0;
1415 view->focussed = 1;
1416 err = view_fullscreen(view);
1417 } else {
1418 err = view_splitscreen(view);
1419 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1420 err = view_resize(view->parent);
1421 if (!err)
1422 err = view_resize_split(view, 0);
1424 if (err)
1425 break;
1426 err = view->input(new, view, KEY_RESIZE);
1428 if (err)
1429 break;
1430 if (view->type == TOG_VIEW_LOG) {
1431 err = request_log_commits(view);
1432 if (err)
1433 break;
1435 if (view->parent)
1436 err = offset_selection_down(view->parent);
1437 if (!err)
1438 err = offset_selection_down(view);
1439 break;
1440 case 'S':
1441 view->count = 0;
1442 err = switch_split(view);
1443 break;
1444 case '-':
1445 err = view_resize_split(view, -1);
1446 break;
1447 case '+':
1448 err = view_resize_split(view, 1);
1449 break;
1450 case KEY_RESIZE:
1451 break;
1452 case '/':
1453 view->count = 0;
1454 if (view->search_start)
1455 view_search_start(view);
1456 else
1457 err = view->input(new, view, ch);
1458 break;
1459 case 'N':
1460 case 'n':
1461 if (view->search_started && view->search_next) {
1462 view->searching = (ch == 'n' ?
1463 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1464 view->search_next_done = 0;
1465 view->search_next(view);
1466 } else
1467 err = view->input(new, view, ch);
1468 break;
1469 case 'A':
1470 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1471 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1472 else
1473 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1474 TAILQ_FOREACH(v, views, entry) {
1475 if (v->reset) {
1476 err = v->reset(v);
1477 if (err)
1478 return err;
1480 if (v->child && v->child->reset) {
1481 err = v->child->reset(v->child);
1482 if (err)
1483 return err;
1486 break;
1487 default:
1488 err = view->input(new, view, ch);
1489 break;
1492 return err;
1495 static int
1496 view_needs_focus_indication(struct tog_view *view)
1498 if (view_is_parent_view(view)) {
1499 if (view->child == NULL || view->child->focussed)
1500 return 0;
1501 if (!view_is_splitscreen(view->child))
1502 return 0;
1503 } else if (!view_is_splitscreen(view))
1504 return 0;
1506 return view->focussed;
1509 static const struct got_error *
1510 view_loop(struct tog_view *view)
1512 const struct got_error *err = NULL;
1513 struct tog_view_list_head views;
1514 struct tog_view *new_view;
1515 char *mode;
1516 int fast_refresh = 10;
1517 int done = 0, errcode;
1519 mode = getenv("TOG_VIEW_SPLIT_MODE");
1520 if (!mode || !(*mode == 'h' || *mode == 'H'))
1521 view->mode = TOG_VIEW_SPLIT_VERT;
1522 else
1523 view->mode = TOG_VIEW_SPLIT_HRZN;
1525 errcode = pthread_mutex_lock(&tog_mutex);
1526 if (errcode)
1527 return got_error_set_errno(errcode, "pthread_mutex_lock");
1529 TAILQ_INIT(&views);
1530 TAILQ_INSERT_HEAD(&views, view, entry);
1532 view->focussed = 1;
1533 err = view->show(view);
1534 if (err)
1535 return err;
1536 update_panels();
1537 doupdate();
1538 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1539 !tog_fatal_signal_received()) {
1540 /* Refresh fast during initialization, then become slower. */
1541 if (fast_refresh && fast_refresh-- == 0)
1542 halfdelay(10); /* switch to once per second */
1544 err = view_input(&new_view, &done, view, &views);
1545 if (err)
1546 break;
1547 if (view->dying) {
1548 struct tog_view *v, *prev = NULL;
1550 if (view_is_parent_view(view))
1551 prev = TAILQ_PREV(view, tog_view_list_head,
1552 entry);
1553 else if (view->parent)
1554 prev = view->parent;
1556 if (view->parent) {
1557 view->parent->child = NULL;
1558 view->parent->focus_child = 0;
1559 /* Restore fullscreen line height. */
1560 view->parent->nlines = view->parent->lines;
1561 err = view_resize(view->parent);
1562 if (err)
1563 break;
1564 /* Make resized splits persist. */
1565 view_transfer_size(view->parent, view);
1566 } else
1567 TAILQ_REMOVE(&views, view, entry);
1569 err = view_close(view);
1570 if (err)
1571 goto done;
1573 view = NULL;
1574 TAILQ_FOREACH(v, &views, entry) {
1575 if (v->focussed)
1576 break;
1578 if (view == NULL && new_view == NULL) {
1579 /* No view has focus. Try to pick one. */
1580 if (prev)
1581 view = prev;
1582 else if (!TAILQ_EMPTY(&views)) {
1583 view = TAILQ_LAST(&views,
1584 tog_view_list_head);
1586 if (view) {
1587 if (view->focus_child) {
1588 view->child->focussed = 1;
1589 view = view->child;
1590 } else
1591 view->focussed = 1;
1595 if (new_view) {
1596 struct tog_view *v, *t;
1597 /* Only allow one parent view per type. */
1598 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1599 if (v->type != new_view->type)
1600 continue;
1601 TAILQ_REMOVE(&views, v, entry);
1602 err = view_close(v);
1603 if (err)
1604 goto done;
1605 break;
1607 TAILQ_INSERT_TAIL(&views, new_view, entry);
1608 view = new_view;
1610 if (view) {
1611 if (view_is_parent_view(view)) {
1612 if (view->child && view->child->focussed)
1613 view = view->child;
1614 } else {
1615 if (view->parent && view->parent->focussed)
1616 view = view->parent;
1618 show_panel(view->panel);
1619 if (view->child && view_is_splitscreen(view->child))
1620 show_panel(view->child->panel);
1621 if (view->parent && view_is_splitscreen(view)) {
1622 err = view->parent->show(view->parent);
1623 if (err)
1624 goto done;
1626 err = view->show(view);
1627 if (err)
1628 goto done;
1629 if (view->child) {
1630 err = view->child->show(view->child);
1631 if (err)
1632 goto done;
1634 update_panels();
1635 doupdate();
1638 done:
1639 while (!TAILQ_EMPTY(&views)) {
1640 const struct got_error *close_err;
1641 view = TAILQ_FIRST(&views);
1642 TAILQ_REMOVE(&views, view, entry);
1643 close_err = view_close(view);
1644 if (close_err && err == NULL)
1645 err = close_err;
1648 errcode = pthread_mutex_unlock(&tog_mutex);
1649 if (errcode && err == NULL)
1650 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1652 return err;
1655 __dead static void
1656 usage_log(void)
1658 endwin();
1659 fprintf(stderr,
1660 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1661 getprogname());
1662 exit(1);
1665 /* Create newly allocated wide-character string equivalent to a byte string. */
1666 static const struct got_error *
1667 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1669 char *vis = NULL;
1670 const struct got_error *err = NULL;
1672 *ws = NULL;
1673 *wlen = mbstowcs(NULL, s, 0);
1674 if (*wlen == (size_t)-1) {
1675 int vislen;
1676 if (errno != EILSEQ)
1677 return got_error_from_errno("mbstowcs");
1679 /* byte string invalid in current encoding; try to "fix" it */
1680 err = got_mbsavis(&vis, &vislen, s);
1681 if (err)
1682 return err;
1683 *wlen = mbstowcs(NULL, vis, 0);
1684 if (*wlen == (size_t)-1) {
1685 err = got_error_from_errno("mbstowcs"); /* give up */
1686 goto done;
1690 *ws = calloc(*wlen + 1, sizeof(**ws));
1691 if (*ws == NULL) {
1692 err = got_error_from_errno("calloc");
1693 goto done;
1696 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1697 err = got_error_from_errno("mbstowcs");
1698 done:
1699 free(vis);
1700 if (err) {
1701 free(*ws);
1702 *ws = NULL;
1703 *wlen = 0;
1705 return err;
1708 static const struct got_error *
1709 expand_tab(char **ptr, const char *src)
1711 char *dst;
1712 size_t len, n, idx = 0, sz = 0;
1714 *ptr = NULL;
1715 n = len = strlen(src);
1716 dst = malloc(n + 1);
1717 if (dst == NULL)
1718 return got_error_from_errno("malloc");
1720 while (idx < len && src[idx]) {
1721 const char c = src[idx];
1723 if (c == '\t') {
1724 size_t nb = TABSIZE - sz % TABSIZE;
1725 char *p;
1727 p = realloc(dst, n + nb);
1728 if (p == NULL) {
1729 free(dst);
1730 return got_error_from_errno("realloc");
1733 dst = p;
1734 n += nb;
1735 memset(dst + sz, ' ', nb);
1736 sz += nb;
1737 } else
1738 dst[sz++] = src[idx];
1739 ++idx;
1742 dst[sz] = '\0';
1743 *ptr = dst;
1744 return NULL;
1748 * Advance at most n columns from wline starting at offset off.
1749 * Return the index to the first character after the span operation.
1750 * Return the combined column width of all spanned wide character in
1751 * *rcol.
1753 static int
1754 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1756 int width, i, cols = 0;
1758 if (n == 0) {
1759 *rcol = cols;
1760 return off;
1763 for (i = off; wline[i] != L'\0'; ++i) {
1764 if (wline[i] == L'\t')
1765 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1766 else
1767 width = wcwidth(wline[i]);
1769 if (width == -1) {
1770 width = 1;
1771 wline[i] = L'.';
1774 if (cols + width > n)
1775 break;
1776 cols += width;
1779 *rcol = cols;
1780 return i;
1784 * Format a line for display, ensuring that it won't overflow a width limit.
1785 * With scrolling, the width returned refers to the scrolled version of the
1786 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1788 static const struct got_error *
1789 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1790 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1792 const struct got_error *err = NULL;
1793 int cols;
1794 wchar_t *wline = NULL;
1795 char *exstr = NULL;
1796 size_t wlen;
1797 int i, scrollx;
1799 *wlinep = NULL;
1800 *widthp = 0;
1802 if (expand) {
1803 err = expand_tab(&exstr, line);
1804 if (err)
1805 return err;
1808 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1809 free(exstr);
1810 if (err)
1811 return err;
1813 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1815 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1816 wline[wlen - 1] = L'\0';
1817 wlen--;
1819 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1820 wline[wlen - 1] = L'\0';
1821 wlen--;
1824 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1825 wline[i] = L'\0';
1827 if (widthp)
1828 *widthp = cols;
1829 if (scrollxp)
1830 *scrollxp = scrollx;
1831 if (err)
1832 free(wline);
1833 else
1834 *wlinep = wline;
1835 return err;
1838 static const struct got_error*
1839 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1840 struct got_object_id *id, struct got_repository *repo)
1842 static const struct got_error *err = NULL;
1843 struct got_reflist_entry *re;
1844 char *s;
1845 const char *name;
1847 *refs_str = NULL;
1849 TAILQ_FOREACH(re, refs, entry) {
1850 struct got_tag_object *tag = NULL;
1851 struct got_object_id *ref_id;
1852 int cmp;
1854 name = got_ref_get_name(re->ref);
1855 if (strcmp(name, GOT_REF_HEAD) == 0)
1856 continue;
1857 if (strncmp(name, "refs/", 5) == 0)
1858 name += 5;
1859 if (strncmp(name, "got/", 4) == 0 &&
1860 strncmp(name, "got/backup/", 11) != 0)
1861 continue;
1862 if (strncmp(name, "heads/", 6) == 0)
1863 name += 6;
1864 if (strncmp(name, "remotes/", 8) == 0) {
1865 name += 8;
1866 s = strstr(name, "/" GOT_REF_HEAD);
1867 if (s != NULL && s[strlen(s)] == '\0')
1868 continue;
1870 err = got_ref_resolve(&ref_id, repo, re->ref);
1871 if (err)
1872 break;
1873 if (strncmp(name, "tags/", 5) == 0) {
1874 err = got_object_open_as_tag(&tag, repo, ref_id);
1875 if (err) {
1876 if (err->code != GOT_ERR_OBJ_TYPE) {
1877 free(ref_id);
1878 break;
1880 /* Ref points at something other than a tag. */
1881 err = NULL;
1882 tag = NULL;
1885 cmp = got_object_id_cmp(tag ?
1886 got_object_tag_get_object_id(tag) : ref_id, id);
1887 free(ref_id);
1888 if (tag)
1889 got_object_tag_close(tag);
1890 if (cmp != 0)
1891 continue;
1892 s = *refs_str;
1893 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1894 s ? ", " : "", name) == -1) {
1895 err = got_error_from_errno("asprintf");
1896 free(s);
1897 *refs_str = NULL;
1898 break;
1900 free(s);
1903 return err;
1906 static const struct got_error *
1907 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1908 int col_tab_align)
1910 char *smallerthan;
1912 smallerthan = strchr(author, '<');
1913 if (smallerthan && smallerthan[1] != '\0')
1914 author = smallerthan + 1;
1915 author[strcspn(author, "@>")] = '\0';
1916 return format_line(wauthor, author_width, NULL, author, 0, limit,
1917 col_tab_align, 0);
1920 static const struct got_error *
1921 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1922 struct got_object_id *id, const size_t date_display_cols,
1923 int author_display_cols)
1925 struct tog_log_view_state *s = &view->state.log;
1926 const struct got_error *err = NULL;
1927 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1928 char *logmsg0 = NULL, *logmsg = NULL;
1929 char *author = NULL;
1930 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1931 int author_width, logmsg_width;
1932 char *newline, *line = NULL;
1933 int col, limit, scrollx;
1934 const int avail = view->ncols;
1935 struct tm tm;
1936 time_t committer_time;
1937 struct tog_color *tc;
1939 committer_time = got_object_commit_get_committer_time(commit);
1940 if (gmtime_r(&committer_time, &tm) == NULL)
1941 return got_error_from_errno("gmtime_r");
1942 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1943 return got_error(GOT_ERR_NO_SPACE);
1945 if (avail <= date_display_cols)
1946 limit = MIN(sizeof(datebuf) - 1, avail);
1947 else
1948 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1949 tc = get_color(&s->colors, TOG_COLOR_DATE);
1950 if (tc)
1951 wattr_on(view->window,
1952 COLOR_PAIR(tc->colorpair), NULL);
1953 waddnstr(view->window, datebuf, limit);
1954 if (tc)
1955 wattr_off(view->window,
1956 COLOR_PAIR(tc->colorpair), NULL);
1957 col = limit;
1958 if (col > avail)
1959 goto done;
1961 if (avail >= 120) {
1962 char *id_str;
1963 err = got_object_id_str(&id_str, id);
1964 if (err)
1965 goto done;
1966 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1967 if (tc)
1968 wattr_on(view->window,
1969 COLOR_PAIR(tc->colorpair), NULL);
1970 wprintw(view->window, "%.8s ", id_str);
1971 if (tc)
1972 wattr_off(view->window,
1973 COLOR_PAIR(tc->colorpair), NULL);
1974 free(id_str);
1975 col += 9;
1976 if (col > avail)
1977 goto done;
1980 if (s->use_committer)
1981 author = strdup(got_object_commit_get_committer(commit));
1982 else
1983 author = strdup(got_object_commit_get_author(commit));
1984 if (author == NULL) {
1985 err = got_error_from_errno("strdup");
1986 goto done;
1988 err = format_author(&wauthor, &author_width, author, avail - col, col);
1989 if (err)
1990 goto done;
1991 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1992 if (tc)
1993 wattr_on(view->window,
1994 COLOR_PAIR(tc->colorpair), NULL);
1995 waddwstr(view->window, wauthor);
1996 if (tc)
1997 wattr_off(view->window,
1998 COLOR_PAIR(tc->colorpair), NULL);
1999 col += author_width;
2000 while (col < avail && author_width < author_display_cols + 2) {
2001 waddch(view->window, ' ');
2002 col++;
2003 author_width++;
2005 if (col > avail)
2006 goto done;
2008 err = got_object_commit_get_logmsg(&logmsg0, commit);
2009 if (err)
2010 goto done;
2011 logmsg = logmsg0;
2012 while (*logmsg == '\n')
2013 logmsg++;
2014 newline = strchr(logmsg, '\n');
2015 if (newline)
2016 *newline = '\0';
2017 limit = avail - col;
2018 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2019 limit--; /* for the border */
2020 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2021 limit, col, 1);
2022 if (err)
2023 goto done;
2024 waddwstr(view->window, &wlogmsg[scrollx]);
2025 col += MAX(logmsg_width, 0);
2026 while (col < avail) {
2027 waddch(view->window, ' ');
2028 col++;
2030 done:
2031 free(logmsg0);
2032 free(wlogmsg);
2033 free(author);
2034 free(wauthor);
2035 free(line);
2036 return err;
2039 static struct commit_queue_entry *
2040 alloc_commit_queue_entry(struct got_commit_object *commit,
2041 struct got_object_id *id)
2043 struct commit_queue_entry *entry;
2045 entry = calloc(1, sizeof(*entry));
2046 if (entry == NULL)
2047 return NULL;
2049 entry->id = id;
2050 entry->commit = commit;
2051 return entry;
2054 static void
2055 pop_commit(struct commit_queue *commits)
2057 struct commit_queue_entry *entry;
2059 entry = TAILQ_FIRST(&commits->head);
2060 TAILQ_REMOVE(&commits->head, entry, entry);
2061 got_object_commit_close(entry->commit);
2062 commits->ncommits--;
2063 /* Don't free entry->id! It is owned by the commit graph. */
2064 free(entry);
2067 static void
2068 free_commits(struct commit_queue *commits)
2070 while (!TAILQ_EMPTY(&commits->head))
2071 pop_commit(commits);
2074 static const struct got_error *
2075 match_commit(int *have_match, struct got_object_id *id,
2076 struct got_commit_object *commit, regex_t *regex)
2078 const struct got_error *err = NULL;
2079 regmatch_t regmatch;
2080 char *id_str = NULL, *logmsg = NULL;
2082 *have_match = 0;
2084 err = got_object_id_str(&id_str, id);
2085 if (err)
2086 return err;
2088 err = got_object_commit_get_logmsg(&logmsg, commit);
2089 if (err)
2090 goto done;
2092 if (regexec(regex, got_object_commit_get_author(commit), 1,
2093 &regmatch, 0) == 0 ||
2094 regexec(regex, got_object_commit_get_committer(commit), 1,
2095 &regmatch, 0) == 0 ||
2096 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2097 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2098 *have_match = 1;
2099 done:
2100 free(id_str);
2101 free(logmsg);
2102 return err;
2105 static const struct got_error *
2106 queue_commits(struct tog_log_thread_args *a)
2108 const struct got_error *err = NULL;
2111 * We keep all commits open throughout the lifetime of the log
2112 * view in order to avoid having to re-fetch commits from disk
2113 * while updating the display.
2115 do {
2116 struct got_object_id *id;
2117 struct got_commit_object *commit;
2118 struct commit_queue_entry *entry;
2119 int errcode;
2121 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2122 NULL, NULL);
2123 if (err || id == NULL)
2124 break;
2126 err = got_object_open_as_commit(&commit, a->repo, id);
2127 if (err)
2128 break;
2129 entry = alloc_commit_queue_entry(commit, id);
2130 if (entry == NULL) {
2131 err = got_error_from_errno("alloc_commit_queue_entry");
2132 break;
2135 errcode = pthread_mutex_lock(&tog_mutex);
2136 if (errcode) {
2137 err = got_error_set_errno(errcode,
2138 "pthread_mutex_lock");
2139 break;
2142 entry->idx = a->commits->ncommits;
2143 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2144 a->commits->ncommits++;
2146 if (*a->searching == TOG_SEARCH_FORWARD &&
2147 !*a->search_next_done) {
2148 int have_match;
2149 err = match_commit(&have_match, id, commit, a->regex);
2150 if (err)
2151 break;
2152 if (have_match)
2153 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2156 errcode = pthread_mutex_unlock(&tog_mutex);
2157 if (errcode && err == NULL)
2158 err = got_error_set_errno(errcode,
2159 "pthread_mutex_unlock");
2160 if (err)
2161 break;
2162 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2164 return err;
2167 static void
2168 select_commit(struct tog_log_view_state *s)
2170 struct commit_queue_entry *entry;
2171 int ncommits = 0;
2173 entry = s->first_displayed_entry;
2174 while (entry) {
2175 if (ncommits == s->selected) {
2176 s->selected_entry = entry;
2177 break;
2179 entry = TAILQ_NEXT(entry, entry);
2180 ncommits++;
2184 static const struct got_error *
2185 draw_commits(struct tog_view *view)
2187 const struct got_error *err = NULL;
2188 struct tog_log_view_state *s = &view->state.log;
2189 struct commit_queue_entry *entry = s->selected_entry;
2190 const int limit = view->nlines;
2191 int width;
2192 int ncommits, author_cols = 4;
2193 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2194 char *refs_str = NULL;
2195 wchar_t *wline;
2196 struct tog_color *tc;
2197 static const size_t date_display_cols = 12;
2199 if (s->selected_entry &&
2200 !(view->searching && view->search_next_done == 0)) {
2201 struct got_reflist_head *refs;
2202 err = got_object_id_str(&id_str, s->selected_entry->id);
2203 if (err)
2204 return err;
2205 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2206 s->selected_entry->id);
2207 if (refs) {
2208 err = build_refs_str(&refs_str, refs,
2209 s->selected_entry->id, s->repo);
2210 if (err)
2211 goto done;
2215 if (s->thread_args.commits_needed == 0)
2216 halfdelay(10); /* disable fast refresh */
2218 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2219 if (asprintf(&ncommits_str, " [%d/%d] %s",
2220 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2221 (view->searching && !view->search_next_done) ?
2222 "searching..." : "loading...") == -1) {
2223 err = got_error_from_errno("asprintf");
2224 goto done;
2226 } else {
2227 const char *search_str = NULL;
2229 if (view->searching) {
2230 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2231 search_str = "no more matches";
2232 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2233 search_str = "no matches found";
2234 else if (!view->search_next_done)
2235 search_str = "searching...";
2238 if (asprintf(&ncommits_str, " [%d/%d] %s",
2239 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2240 search_str ? search_str :
2241 (refs_str ? refs_str : "")) == -1) {
2242 err = got_error_from_errno("asprintf");
2243 goto done;
2247 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2248 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2249 "........................................",
2250 s->in_repo_path, ncommits_str) == -1) {
2251 err = got_error_from_errno("asprintf");
2252 header = NULL;
2253 goto done;
2255 } else if (asprintf(&header, "commit %s%s",
2256 id_str ? id_str : "........................................",
2257 ncommits_str) == -1) {
2258 err = got_error_from_errno("asprintf");
2259 header = NULL;
2260 goto done;
2262 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2263 if (err)
2264 goto done;
2266 werase(view->window);
2268 if (view_needs_focus_indication(view))
2269 wstandout(view->window);
2270 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2271 if (tc)
2272 wattr_on(view->window,
2273 COLOR_PAIR(tc->colorpair), NULL);
2274 waddwstr(view->window, wline);
2275 if (tc)
2276 wattr_off(view->window,
2277 COLOR_PAIR(tc->colorpair), NULL);
2278 while (width < view->ncols) {
2279 waddch(view->window, ' ');
2280 width++;
2282 if (view_needs_focus_indication(view))
2283 wstandend(view->window);
2284 free(wline);
2285 if (limit <= 1)
2286 goto done;
2288 /* Grow author column size if necessary, and set view->maxx. */
2289 entry = s->first_displayed_entry;
2290 ncommits = 0;
2291 view->maxx = 0;
2292 while (entry) {
2293 struct got_commit_object *c = entry->commit;
2294 char *author, *eol, *msg, *msg0;
2295 wchar_t *wauthor, *wmsg;
2296 int width;
2297 if (ncommits >= limit - 1)
2298 break;
2299 if (s->use_committer)
2300 author = strdup(got_object_commit_get_committer(c));
2301 else
2302 author = strdup(got_object_commit_get_author(c));
2303 if (author == NULL) {
2304 err = got_error_from_errno("strdup");
2305 goto done;
2307 err = format_author(&wauthor, &width, author, COLS,
2308 date_display_cols);
2309 if (author_cols < width)
2310 author_cols = width;
2311 free(wauthor);
2312 free(author);
2313 err = got_object_commit_get_logmsg(&msg0, c);
2314 if (err)
2315 goto done;
2316 msg = msg0;
2317 while (*msg == '\n')
2318 ++msg;
2319 if ((eol = strchr(msg, '\n')))
2320 *eol = '\0';
2321 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2322 date_display_cols + author_cols, 0);
2323 if (err)
2324 goto done;
2325 view->maxx = MAX(view->maxx, width);
2326 free(msg0);
2327 free(wmsg);
2328 ncommits++;
2329 entry = TAILQ_NEXT(entry, entry);
2332 entry = s->first_displayed_entry;
2333 s->last_displayed_entry = s->first_displayed_entry;
2334 ncommits = 0;
2335 while (entry) {
2336 if (ncommits >= limit - 1)
2337 break;
2338 if (ncommits == s->selected)
2339 wstandout(view->window);
2340 err = draw_commit(view, entry->commit, entry->id,
2341 date_display_cols, author_cols);
2342 if (ncommits == s->selected)
2343 wstandend(view->window);
2344 if (err)
2345 goto done;
2346 ncommits++;
2347 s->last_displayed_entry = entry;
2348 entry = TAILQ_NEXT(entry, entry);
2351 view_border(view);
2352 done:
2353 free(id_str);
2354 free(refs_str);
2355 free(ncommits_str);
2356 free(header);
2357 return err;
2360 static void
2361 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2363 struct commit_queue_entry *entry;
2364 int nscrolled = 0;
2366 entry = TAILQ_FIRST(&s->commits.head);
2367 if (s->first_displayed_entry == entry)
2368 return;
2370 entry = s->first_displayed_entry;
2371 while (entry && nscrolled < maxscroll) {
2372 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2373 if (entry) {
2374 s->first_displayed_entry = entry;
2375 nscrolled++;
2380 static const struct got_error *
2381 trigger_log_thread(struct tog_view *view, int wait)
2383 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2384 int errcode;
2386 halfdelay(1); /* fast refresh while loading commits */
2388 while (!ta->log_complete && !tog_thread_error &&
2389 (ta->commits_needed > 0 || ta->load_all)) {
2390 /* Wake the log thread. */
2391 errcode = pthread_cond_signal(&ta->need_commits);
2392 if (errcode)
2393 return got_error_set_errno(errcode,
2394 "pthread_cond_signal");
2397 * The mutex will be released while the view loop waits
2398 * in wgetch(), at which time the log thread will run.
2400 if (!wait)
2401 break;
2403 /* Display progress update in log view. */
2404 show_log_view(view);
2405 update_panels();
2406 doupdate();
2408 /* Wait right here while next commit is being loaded. */
2409 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2410 if (errcode)
2411 return got_error_set_errno(errcode,
2412 "pthread_cond_wait");
2414 /* Display progress update in log view. */
2415 show_log_view(view);
2416 update_panels();
2417 doupdate();
2420 return NULL;
2423 static const struct got_error *
2424 request_log_commits(struct tog_view *view)
2426 struct tog_log_view_state *state = &view->state.log;
2427 const struct got_error *err = NULL;
2429 if (state->thread_args.log_complete)
2430 return NULL;
2432 state->thread_args.commits_needed += view->nscrolled;
2433 err = trigger_log_thread(view, 1);
2434 view->nscrolled = 0;
2436 return err;
2439 static const struct got_error *
2440 log_scroll_down(struct tog_view *view, int maxscroll)
2442 struct tog_log_view_state *s = &view->state.log;
2443 const struct got_error *err = NULL;
2444 struct commit_queue_entry *pentry;
2445 int nscrolled = 0, ncommits_needed;
2447 if (s->last_displayed_entry == NULL)
2448 return NULL;
2450 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2451 if (s->commits.ncommits < ncommits_needed &&
2452 !s->thread_args.log_complete) {
2454 * Ask the log thread for required amount of commits.
2456 s->thread_args.commits_needed += maxscroll;
2457 err = trigger_log_thread(view, 1);
2458 if (err)
2459 return err;
2462 do {
2463 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2464 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2465 break;
2467 s->last_displayed_entry = pentry ?
2468 pentry : s->last_displayed_entry;;
2470 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2471 if (pentry == NULL)
2472 break;
2473 s->first_displayed_entry = pentry;
2474 } while (++nscrolled < maxscroll);
2476 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2477 view->nscrolled += nscrolled;
2478 else
2479 view->nscrolled = 0;
2481 return err;
2484 static const struct got_error *
2485 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2486 struct got_commit_object *commit, struct got_object_id *commit_id,
2487 struct tog_view *log_view, struct got_repository *repo)
2489 const struct got_error *err;
2490 struct got_object_qid *parent_id;
2491 struct tog_view *diff_view;
2493 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2494 if (diff_view == NULL)
2495 return got_error_from_errno("view_open");
2497 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2498 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2499 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2500 if (err == NULL)
2501 *new_view = diff_view;
2502 return err;
2505 static const struct got_error *
2506 tree_view_visit_subtree(struct tog_tree_view_state *s,
2507 struct got_tree_object *subtree)
2509 struct tog_parent_tree *parent;
2511 parent = calloc(1, sizeof(*parent));
2512 if (parent == NULL)
2513 return got_error_from_errno("calloc");
2515 parent->tree = s->tree;
2516 parent->first_displayed_entry = s->first_displayed_entry;
2517 parent->selected_entry = s->selected_entry;
2518 parent->selected = s->selected;
2519 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2520 s->tree = subtree;
2521 s->selected = 0;
2522 s->first_displayed_entry = NULL;
2523 return NULL;
2526 static const struct got_error *
2527 tree_view_walk_path(struct tog_tree_view_state *s,
2528 struct got_commit_object *commit, const char *path)
2530 const struct got_error *err = NULL;
2531 struct got_tree_object *tree = NULL;
2532 const char *p;
2533 char *slash, *subpath = NULL;
2535 /* Walk the path and open corresponding tree objects. */
2536 p = path;
2537 while (*p) {
2538 struct got_tree_entry *te;
2539 struct got_object_id *tree_id;
2540 char *te_name;
2542 while (p[0] == '/')
2543 p++;
2545 /* Ensure the correct subtree entry is selected. */
2546 slash = strchr(p, '/');
2547 if (slash == NULL)
2548 te_name = strdup(p);
2549 else
2550 te_name = strndup(p, slash - p);
2551 if (te_name == NULL) {
2552 err = got_error_from_errno("strndup");
2553 break;
2555 te = got_object_tree_find_entry(s->tree, te_name);
2556 if (te == NULL) {
2557 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2558 free(te_name);
2559 break;
2561 free(te_name);
2562 s->first_displayed_entry = s->selected_entry = te;
2564 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2565 break; /* jump to this file's entry */
2567 slash = strchr(p, '/');
2568 if (slash)
2569 subpath = strndup(path, slash - path);
2570 else
2571 subpath = strdup(path);
2572 if (subpath == NULL) {
2573 err = got_error_from_errno("strdup");
2574 break;
2577 err = got_object_id_by_path(&tree_id, s->repo, commit,
2578 subpath);
2579 if (err)
2580 break;
2582 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2583 free(tree_id);
2584 if (err)
2585 break;
2587 err = tree_view_visit_subtree(s, tree);
2588 if (err) {
2589 got_object_tree_close(tree);
2590 break;
2592 if (slash == NULL)
2593 break;
2594 free(subpath);
2595 subpath = NULL;
2596 p = slash;
2599 free(subpath);
2600 return err;
2603 static const struct got_error *
2604 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2605 struct commit_queue_entry *entry, const char *path,
2606 const char *head_ref_name, struct got_repository *repo)
2608 const struct got_error *err = NULL;
2609 struct tog_tree_view_state *s;
2610 struct tog_view *tree_view;
2612 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2613 if (tree_view == NULL)
2614 return got_error_from_errno("view_open");
2616 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2617 if (err)
2618 return err;
2619 s = &tree_view->state.tree;
2621 *new_view = tree_view;
2623 if (got_path_is_root_dir(path))
2624 return NULL;
2626 return tree_view_walk_path(s, entry->commit, path);
2629 static const struct got_error *
2630 block_signals_used_by_main_thread(void)
2632 sigset_t sigset;
2633 int errcode;
2635 if (sigemptyset(&sigset) == -1)
2636 return got_error_from_errno("sigemptyset");
2638 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2639 if (sigaddset(&sigset, SIGWINCH) == -1)
2640 return got_error_from_errno("sigaddset");
2641 if (sigaddset(&sigset, SIGCONT) == -1)
2642 return got_error_from_errno("sigaddset");
2643 if (sigaddset(&sigset, SIGINT) == -1)
2644 return got_error_from_errno("sigaddset");
2645 if (sigaddset(&sigset, SIGTERM) == -1)
2646 return got_error_from_errno("sigaddset");
2648 /* ncurses handles SIGTSTP */
2649 if (sigaddset(&sigset, SIGTSTP) == -1)
2650 return got_error_from_errno("sigaddset");
2652 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2653 if (errcode)
2654 return got_error_set_errno(errcode, "pthread_sigmask");
2656 return NULL;
2659 static void *
2660 log_thread(void *arg)
2662 const struct got_error *err = NULL;
2663 int errcode = 0;
2664 struct tog_log_thread_args *a = arg;
2665 int done = 0;
2668 * Sync startup with main thread such that we begin our
2669 * work once view_input() has released the mutex.
2671 errcode = pthread_mutex_lock(&tog_mutex);
2672 if (errcode) {
2673 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2674 return (void *)err;
2677 err = block_signals_used_by_main_thread();
2678 if (err) {
2679 pthread_mutex_unlock(&tog_mutex);
2680 goto done;
2683 while (!done && !err && !tog_fatal_signal_received()) {
2684 errcode = pthread_mutex_unlock(&tog_mutex);
2685 if (errcode) {
2686 err = got_error_set_errno(errcode,
2687 "pthread_mutex_unlock");
2688 goto done;
2690 err = queue_commits(a);
2691 if (err) {
2692 if (err->code != GOT_ERR_ITER_COMPLETED)
2693 goto done;
2694 err = NULL;
2695 done = 1;
2696 } else if (a->commits_needed > 0 && !a->load_all)
2697 a->commits_needed--;
2699 errcode = pthread_mutex_lock(&tog_mutex);
2700 if (errcode) {
2701 err = got_error_set_errno(errcode,
2702 "pthread_mutex_lock");
2703 goto done;
2704 } else if (*a->quit)
2705 done = 1;
2706 else if (*a->first_displayed_entry == NULL) {
2707 *a->first_displayed_entry =
2708 TAILQ_FIRST(&a->commits->head);
2709 *a->selected_entry = *a->first_displayed_entry;
2712 errcode = pthread_cond_signal(&a->commit_loaded);
2713 if (errcode) {
2714 err = got_error_set_errno(errcode,
2715 "pthread_cond_signal");
2716 pthread_mutex_unlock(&tog_mutex);
2717 goto done;
2720 if (done)
2721 a->commits_needed = 0;
2722 else {
2723 if (a->commits_needed == 0 && !a->load_all) {
2724 errcode = pthread_cond_wait(&a->need_commits,
2725 &tog_mutex);
2726 if (errcode) {
2727 err = got_error_set_errno(errcode,
2728 "pthread_cond_wait");
2729 pthread_mutex_unlock(&tog_mutex);
2730 goto done;
2732 if (*a->quit)
2733 done = 1;
2737 a->log_complete = 1;
2738 errcode = pthread_mutex_unlock(&tog_mutex);
2739 if (errcode)
2740 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2741 done:
2742 if (err) {
2743 tog_thread_error = 1;
2744 pthread_cond_signal(&a->commit_loaded);
2746 return (void *)err;
2749 static const struct got_error *
2750 stop_log_thread(struct tog_log_view_state *s)
2752 const struct got_error *err = NULL, *thread_err = NULL;
2753 int errcode;
2755 if (s->thread) {
2756 s->quit = 1;
2757 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2758 if (errcode)
2759 return got_error_set_errno(errcode,
2760 "pthread_cond_signal");
2761 errcode = pthread_mutex_unlock(&tog_mutex);
2762 if (errcode)
2763 return got_error_set_errno(errcode,
2764 "pthread_mutex_unlock");
2765 errcode = pthread_join(s->thread, (void **)&thread_err);
2766 if (errcode)
2767 return got_error_set_errno(errcode, "pthread_join");
2768 errcode = pthread_mutex_lock(&tog_mutex);
2769 if (errcode)
2770 return got_error_set_errno(errcode,
2771 "pthread_mutex_lock");
2772 s->thread = 0; //NULL;
2775 if (s->thread_args.repo) {
2776 err = got_repo_close(s->thread_args.repo);
2777 s->thread_args.repo = NULL;
2780 if (s->thread_args.pack_fds) {
2781 const struct got_error *pack_err =
2782 got_repo_pack_fds_close(s->thread_args.pack_fds);
2783 if (err == NULL)
2784 err = pack_err;
2785 s->thread_args.pack_fds = NULL;
2788 if (s->thread_args.graph) {
2789 got_commit_graph_close(s->thread_args.graph);
2790 s->thread_args.graph = NULL;
2793 return err ? err : thread_err;
2796 static const struct got_error *
2797 close_log_view(struct tog_view *view)
2799 const struct got_error *err = NULL;
2800 struct tog_log_view_state *s = &view->state.log;
2801 int errcode;
2803 err = stop_log_thread(s);
2805 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2806 if (errcode && err == NULL)
2807 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2809 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2810 if (errcode && err == NULL)
2811 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2813 free_commits(&s->commits);
2814 free(s->in_repo_path);
2815 s->in_repo_path = NULL;
2816 free(s->start_id);
2817 s->start_id = NULL;
2818 free(s->head_ref_name);
2819 s->head_ref_name = NULL;
2820 return err;
2823 static const struct got_error *
2824 search_start_log_view(struct tog_view *view)
2826 struct tog_log_view_state *s = &view->state.log;
2828 s->matched_entry = NULL;
2829 s->search_entry = NULL;
2830 return NULL;
2833 static const struct got_error *
2834 search_next_log_view(struct tog_view *view)
2836 const struct got_error *err = NULL;
2837 struct tog_log_view_state *s = &view->state.log;
2838 struct commit_queue_entry *entry;
2840 /* Display progress update in log view. */
2841 show_log_view(view);
2842 update_panels();
2843 doupdate();
2845 if (s->search_entry) {
2846 int errcode, ch;
2847 errcode = pthread_mutex_unlock(&tog_mutex);
2848 if (errcode)
2849 return got_error_set_errno(errcode,
2850 "pthread_mutex_unlock");
2851 ch = wgetch(view->window);
2852 errcode = pthread_mutex_lock(&tog_mutex);
2853 if (errcode)
2854 return got_error_set_errno(errcode,
2855 "pthread_mutex_lock");
2856 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2857 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2858 return NULL;
2860 if (view->searching == TOG_SEARCH_FORWARD)
2861 entry = TAILQ_NEXT(s->search_entry, entry);
2862 else
2863 entry = TAILQ_PREV(s->search_entry,
2864 commit_queue_head, entry);
2865 } else if (s->matched_entry) {
2866 int matched_idx = s->matched_entry->idx;
2867 int selected_idx = s->selected_entry->idx;
2870 * If the user has moved the cursor after we hit a match,
2871 * the position from where we should continue searching
2872 * might have changed.
2874 if (view->searching == TOG_SEARCH_FORWARD) {
2875 if (matched_idx > selected_idx)
2876 entry = TAILQ_NEXT(s->selected_entry, entry);
2877 else
2878 entry = TAILQ_NEXT(s->matched_entry, entry);
2879 } else {
2880 if (matched_idx < selected_idx)
2881 entry = TAILQ_PREV(s->selected_entry,
2882 commit_queue_head, entry);
2883 else
2884 entry = TAILQ_PREV(s->matched_entry,
2885 commit_queue_head, entry);
2887 } else {
2888 entry = s->selected_entry;
2891 while (1) {
2892 int have_match = 0;
2894 if (entry == NULL) {
2895 if (s->thread_args.log_complete ||
2896 view->searching == TOG_SEARCH_BACKWARD) {
2897 view->search_next_done =
2898 (s->matched_entry == NULL ?
2899 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2900 s->search_entry = NULL;
2901 return NULL;
2904 * Poke the log thread for more commits and return,
2905 * allowing the main loop to make progress. Search
2906 * will resume at s->search_entry once we come back.
2908 s->thread_args.commits_needed++;
2909 return trigger_log_thread(view, 0);
2912 err = match_commit(&have_match, entry->id, entry->commit,
2913 &view->regex);
2914 if (err)
2915 break;
2916 if (have_match) {
2917 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2918 s->matched_entry = entry;
2919 break;
2922 s->search_entry = entry;
2923 if (view->searching == TOG_SEARCH_FORWARD)
2924 entry = TAILQ_NEXT(entry, entry);
2925 else
2926 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2929 if (s->matched_entry) {
2930 int cur = s->selected_entry->idx;
2931 while (cur < s->matched_entry->idx) {
2932 err = input_log_view(NULL, view, KEY_DOWN);
2933 if (err)
2934 return err;
2935 cur++;
2937 while (cur > s->matched_entry->idx) {
2938 err = input_log_view(NULL, view, KEY_UP);
2939 if (err)
2940 return err;
2941 cur--;
2945 s->search_entry = NULL;
2947 return NULL;
2950 static const struct got_error *
2951 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2952 struct got_repository *repo, const char *head_ref_name,
2953 const char *in_repo_path, int log_branches)
2955 const struct got_error *err = NULL;
2956 struct tog_log_view_state *s = &view->state.log;
2957 struct got_repository *thread_repo = NULL;
2958 struct got_commit_graph *thread_graph = NULL;
2959 int errcode;
2961 if (in_repo_path != s->in_repo_path) {
2962 free(s->in_repo_path);
2963 s->in_repo_path = strdup(in_repo_path);
2964 if (s->in_repo_path == NULL)
2965 return got_error_from_errno("strdup");
2968 /* The commit queue only contains commits being displayed. */
2969 TAILQ_INIT(&s->commits.head);
2970 s->commits.ncommits = 0;
2972 s->repo = repo;
2973 if (head_ref_name) {
2974 s->head_ref_name = strdup(head_ref_name);
2975 if (s->head_ref_name == NULL) {
2976 err = got_error_from_errno("strdup");
2977 goto done;
2980 s->start_id = got_object_id_dup(start_id);
2981 if (s->start_id == NULL) {
2982 err = got_error_from_errno("got_object_id_dup");
2983 goto done;
2985 s->log_branches = log_branches;
2987 STAILQ_INIT(&s->colors);
2988 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2989 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2990 get_color_value("TOG_COLOR_COMMIT"));
2991 if (err)
2992 goto done;
2993 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2994 get_color_value("TOG_COLOR_AUTHOR"));
2995 if (err) {
2996 free_colors(&s->colors);
2997 goto done;
2999 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3000 get_color_value("TOG_COLOR_DATE"));
3001 if (err) {
3002 free_colors(&s->colors);
3003 goto done;
3007 view->show = show_log_view;
3008 view->input = input_log_view;
3009 view->resize = resize_log_view;
3010 view->close = close_log_view;
3011 view->search_start = search_start_log_view;
3012 view->search_next = search_next_log_view;
3014 if (s->thread_args.pack_fds == NULL) {
3015 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3016 if (err)
3017 goto done;
3019 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3020 s->thread_args.pack_fds);
3021 if (err)
3022 goto done;
3023 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3024 !s->log_branches);
3025 if (err)
3026 goto done;
3027 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3028 s->repo, NULL, NULL);
3029 if (err)
3030 goto done;
3032 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3033 if (errcode) {
3034 err = got_error_set_errno(errcode, "pthread_cond_init");
3035 goto done;
3037 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3038 if (errcode) {
3039 err = got_error_set_errno(errcode, "pthread_cond_init");
3040 goto done;
3043 s->thread_args.commits_needed = view->nlines;
3044 s->thread_args.graph = thread_graph;
3045 s->thread_args.commits = &s->commits;
3046 s->thread_args.in_repo_path = s->in_repo_path;
3047 s->thread_args.start_id = s->start_id;
3048 s->thread_args.repo = thread_repo;
3049 s->thread_args.log_complete = 0;
3050 s->thread_args.quit = &s->quit;
3051 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3052 s->thread_args.selected_entry = &s->selected_entry;
3053 s->thread_args.searching = &view->searching;
3054 s->thread_args.search_next_done = &view->search_next_done;
3055 s->thread_args.regex = &view->regex;
3056 done:
3057 if (err)
3058 close_log_view(view);
3059 return err;
3062 static const struct got_error *
3063 show_log_view(struct tog_view *view)
3065 const struct got_error *err;
3066 struct tog_log_view_state *s = &view->state.log;
3068 if (s->thread == 0) { //NULL) {
3069 int errcode = pthread_create(&s->thread, NULL, log_thread,
3070 &s->thread_args);
3071 if (errcode)
3072 return got_error_set_errno(errcode, "pthread_create");
3073 if (s->thread_args.commits_needed > 0) {
3074 err = trigger_log_thread(view, 1);
3075 if (err)
3076 return err;
3080 return draw_commits(view);
3083 static void
3084 log_move_cursor_up(struct tog_view *view, int page, int home)
3086 struct tog_log_view_state *s = &view->state.log;
3088 if (s->selected_entry->idx == 0)
3089 view->count = 0;
3090 if (s->first_displayed_entry == NULL)
3091 return;
3093 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3094 || home)
3095 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3097 if (!page && !home && s->selected > 0)
3098 --s->selected;
3099 else
3100 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3102 select_commit(s);
3103 return;
3106 static const struct got_error *
3107 log_move_cursor_down(struct tog_view *view, int page)
3109 struct tog_log_view_state *s = &view->state.log;
3110 struct commit_queue_entry *first;
3111 const struct got_error *err = NULL;
3113 first = s->first_displayed_entry;
3114 if (first == NULL) {
3115 view->count = 0;
3116 return NULL;
3119 if (s->thread_args.log_complete &&
3120 s->selected_entry->idx >= s->commits.ncommits - 1)
3121 return NULL;
3123 if (!page) {
3124 int eos = view->nlines - 2;
3126 if (view_is_hsplit_top(view))
3127 --eos; /* border consumes the last line */
3128 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3129 ++s->selected;
3130 else
3131 err = log_scroll_down(view, 1);
3132 } else if (s->thread_args.load_all) {
3133 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3134 s->selected += MIN(s->last_displayed_entry->idx -
3135 s->selected_entry->idx, page + 1);
3136 else
3137 err = log_scroll_down(view, MIN(page,
3138 s->commits.ncommits - s->selected_entry->idx - 1));
3139 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3140 } else {
3141 err = log_scroll_down(view, page);
3142 if (err)
3143 return err;
3144 if (first == s->first_displayed_entry && s->selected <
3145 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
3146 s->selected = MIN(s->commits.ncommits - 1, page);
3149 if (err)
3150 return err;
3153 * We might necessarily overshoot in horizontal
3154 * splits; if so, select the last displayed commit.
3156 s->selected = MIN(s->selected,
3157 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3159 select_commit(s);
3161 if (s->thread_args.log_complete &&
3162 s->selected_entry->idx == s->commits.ncommits - 1)
3163 view->count = 0;
3165 return NULL;
3168 static void
3169 view_get_split(struct tog_view *view, int *y, int *x)
3171 *x = 0;
3172 *y = 0;
3174 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3175 if (view->child && view->child->resized_y)
3176 *y = view->child->resized_y;
3177 else if (view->resized_y)
3178 *y = view->resized_y;
3179 else
3180 *y = view_split_begin_y(view->lines);
3181 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3182 if (view->child && view->child->resized_x)
3183 *x = view->child->resized_x;
3184 else if (view->resized_x)
3185 *x = view->resized_x;
3186 else
3187 *x = view_split_begin_x(view->begin_x);
3191 /* Split view horizontally at y and offset view->state->selected line. */
3192 static const struct got_error *
3193 view_init_hsplit(struct tog_view *view, int y)
3195 const struct got_error *err = NULL;
3197 view->nlines = y;
3198 view->ncols = COLS;
3199 err = view_resize(view);
3200 if (err)
3201 return err;
3203 err = offset_selection_down(view);
3205 return err;
3208 static const struct got_error *
3209 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3211 const struct got_error *err = NULL;
3212 struct tog_log_view_state *s = &view->state.log;
3213 struct tog_view *diff_view = NULL, *tree_view = NULL;
3214 struct tog_view *ref_view = NULL;
3215 struct commit_queue_entry *entry;
3216 int begin_x = 0, begin_y = 0, eos, n, nscroll;
3218 if (s->thread_args.load_all) {
3219 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3220 s->thread_args.load_all = 0;
3221 else if (s->thread_args.log_complete) {
3222 err = log_move_cursor_down(view, s->commits.ncommits);
3223 s->thread_args.load_all = 0;
3225 return err;
3228 eos = nscroll = view->nlines - 1;
3229 if (view_is_hsplit_top(view))
3230 --eos; /* border */
3232 switch (ch) {
3233 case 'q':
3234 s->quit = 1;
3235 break;
3236 case '0':
3237 view->x = 0;
3238 break;
3239 case '$':
3240 view->x = MAX(view->maxx - view->ncols / 2, 0);
3241 view->count = 0;
3242 break;
3243 case KEY_RIGHT:
3244 case 'l':
3245 if (view->x + view->ncols / 2 < view->maxx)
3246 view->x += 2; /* move two columns right */
3247 else
3248 view->count = 0;
3249 break;
3250 case KEY_LEFT:
3251 case 'h':
3252 view->x -= MIN(view->x, 2); /* move two columns back */
3253 if (view->x <= 0)
3254 view->count = 0;
3255 break;
3256 case 'k':
3257 case KEY_UP:
3258 case '<':
3259 case ',':
3260 case CTRL('p'):
3261 log_move_cursor_up(view, 0, 0);
3262 break;
3263 case 'g':
3264 case KEY_HOME:
3265 log_move_cursor_up(view, 0, 1);
3266 view->count = 0;
3267 break;
3268 case CTRL('u'):
3269 case 'u':
3270 nscroll /= 2;
3271 /* FALL THROUGH */
3272 case KEY_PPAGE:
3273 case CTRL('b'):
3274 case 'b':
3275 log_move_cursor_up(view, nscroll, 0);
3276 break;
3277 case 'j':
3278 case KEY_DOWN:
3279 case '>':
3280 case '.':
3281 case CTRL('n'):
3282 err = log_move_cursor_down(view, 0);
3283 break;
3284 case '@':
3285 s->use_committer = !s->use_committer;
3286 break;
3287 case 'G':
3288 case KEY_END: {
3289 /* We don't know yet how many commits, so we're forced to
3290 * traverse them all. */
3291 view->count = 0;
3292 if (!s->thread_args.log_complete) {
3293 s->thread_args.load_all = 1;
3294 return trigger_log_thread(view, 0);
3297 s->selected = 0;
3298 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3299 for (n = 0; n < eos; n++) {
3300 if (entry == NULL)
3301 break;
3302 s->first_displayed_entry = entry;
3303 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3305 if (n > 0)
3306 s->selected = n - 1;
3307 select_commit(s);
3308 break;
3310 case CTRL('d'):
3311 case 'd':
3312 nscroll /= 2;
3313 /* FALL THROUGH */
3314 case KEY_NPAGE:
3315 case CTRL('f'):
3316 case 'f':
3317 case ' ':
3318 err = log_move_cursor_down(view, nscroll);
3319 break;
3320 case KEY_RESIZE:
3321 if (s->selected > view->nlines - 2)
3322 s->selected = view->nlines - 2;
3323 if (s->selected > s->commits.ncommits - 1)
3324 s->selected = s->commits.ncommits - 1;
3325 select_commit(s);
3326 if (s->commits.ncommits < view->nlines - 1 &&
3327 !s->thread_args.log_complete) {
3328 s->thread_args.commits_needed += (view->nlines - 1) -
3329 s->commits.ncommits;
3330 err = trigger_log_thread(view, 1);
3332 break;
3333 case KEY_ENTER:
3334 case '\r':
3335 view->count = 0;
3336 if (s->selected_entry == NULL)
3337 break;
3339 /* get dimensions--don't split till initialisation succeeds */
3340 if (view_is_parent_view(view))
3341 view_get_split(view, &begin_y, &begin_x);
3343 err = open_diff_view_for_commit(&diff_view, begin_y, begin_x,
3344 s->selected_entry->commit, s->selected_entry->id,
3345 view, s->repo);
3346 if (err)
3347 break;
3349 if (view_is_parent_view(view) &&
3350 view->mode == TOG_VIEW_SPLIT_HRZN) { /* safe to split */
3351 err = view_init_hsplit(view, begin_y);
3352 if (err)
3353 break;
3356 view->focussed = 0;
3357 diff_view->focussed = 1;
3358 diff_view->mode = view->mode;
3359 diff_view->nlines = view->lines - begin_y;
3361 if (view_is_parent_view(view)) {
3362 view_transfer_size(diff_view, view);
3363 err = view_close_child(view);
3364 if (err)
3365 return err;
3366 err = view_set_child(view, diff_view);
3367 if (err)
3368 return err;
3369 view->focus_child = 1;
3370 } else
3371 *new_view = diff_view;
3372 break;
3373 case 't':
3374 view->count = 0;
3375 if (s->selected_entry == NULL)
3376 break;
3377 if (view_is_parent_view(view))
3378 view_get_split(view, &begin_y, &begin_x);
3379 err = browse_commit_tree(&tree_view, begin_y, begin_x,
3380 s->selected_entry, s->in_repo_path, s->head_ref_name,
3381 s->repo);
3382 if (err)
3383 break;
3384 if (view_is_parent_view(view) &&
3385 view->mode == TOG_VIEW_SPLIT_HRZN) {
3386 err = view_init_hsplit(view, begin_y);
3387 if (err)
3388 break;
3390 view->focussed = 0;
3391 tree_view->focussed = 1;
3392 tree_view->mode = view->mode;
3393 tree_view->nlines = view->lines - begin_y;
3394 if (view_is_parent_view(view)) {
3395 view_transfer_size(tree_view, view);
3396 err = view_close_child(view);
3397 if (err)
3398 return err;
3399 err = view_set_child(view, tree_view);
3400 if (err)
3401 return err;
3402 view->focus_child = 1;
3403 } else
3404 *new_view = tree_view;
3405 break;
3406 case KEY_BACKSPACE:
3407 case CTRL('l'):
3408 case 'B':
3409 view->count = 0;
3410 if (ch == KEY_BACKSPACE &&
3411 got_path_is_root_dir(s->in_repo_path))
3412 break;
3413 err = stop_log_thread(s);
3414 if (err)
3415 return err;
3416 if (ch == KEY_BACKSPACE) {
3417 char *parent_path;
3418 err = got_path_dirname(&parent_path, s->in_repo_path);
3419 if (err)
3420 return err;
3421 free(s->in_repo_path);
3422 s->in_repo_path = parent_path;
3423 s->thread_args.in_repo_path = s->in_repo_path;
3424 } else if (ch == CTRL('l')) {
3425 struct got_object_id *start_id;
3426 err = got_repo_match_object_id(&start_id, NULL,
3427 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3428 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3429 if (err)
3430 return err;
3431 free(s->start_id);
3432 s->start_id = start_id;
3433 s->thread_args.start_id = s->start_id;
3434 } else /* 'B' */
3435 s->log_branches = !s->log_branches;
3437 if (s->thread_args.pack_fds == NULL) {
3438 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3439 if (err)
3440 return err;
3442 err = got_repo_open(&s->thread_args.repo,
3443 got_repo_get_path(s->repo), NULL,
3444 s->thread_args.pack_fds);
3445 if (err)
3446 return err;
3447 tog_free_refs();
3448 err = tog_load_refs(s->repo, 0);
3449 if (err)
3450 return err;
3451 err = got_commit_graph_open(&s->thread_args.graph,
3452 s->in_repo_path, !s->log_branches);
3453 if (err)
3454 return err;
3455 err = got_commit_graph_iter_start(s->thread_args.graph,
3456 s->start_id, s->repo, NULL, NULL);
3457 if (err)
3458 return err;
3459 free_commits(&s->commits);
3460 s->first_displayed_entry = NULL;
3461 s->last_displayed_entry = NULL;
3462 s->selected_entry = NULL;
3463 s->selected = 0;
3464 s->thread_args.log_complete = 0;
3465 s->quit = 0;
3466 s->thread_args.commits_needed = view->lines;
3467 s->matched_entry = NULL;
3468 s->search_entry = NULL;
3469 break;
3470 case 'r':
3471 view->count = 0;
3472 if (view_is_parent_view(view))
3473 view_get_split(view, &begin_y, &begin_x);
3474 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
3475 if (ref_view == NULL)
3476 return got_error_from_errno("view_open");
3477 err = open_ref_view(ref_view, s->repo);
3478 if (err) {
3479 view_close(ref_view);
3480 return err;
3482 if (view_is_parent_view(view) &&
3483 view->mode == TOG_VIEW_SPLIT_HRZN) {
3484 err = view_init_hsplit(view, begin_y);
3485 if (err)
3486 break;
3488 view->focussed = 0;
3489 ref_view->focussed = 1;
3490 ref_view->mode = view->mode;
3491 ref_view->nlines = view->lines - begin_y;
3492 if (view_is_parent_view(view)) {
3493 view_transfer_size(ref_view, view);
3494 err = view_close_child(view);
3495 if (err)
3496 return err;
3497 err = view_set_child(view, ref_view);
3498 if (err)
3499 return err;
3500 view->focus_child = 1;
3501 } else
3502 *new_view = ref_view;
3503 break;
3504 default:
3505 view->count = 0;
3506 break;
3509 return err;
3512 static const struct got_error *
3513 apply_unveil(const char *repo_path, const char *worktree_path)
3515 const struct got_error *error;
3517 #ifdef PROFILE
3518 if (unveil("gmon.out", "rwc") != 0)
3519 return got_error_from_errno2("unveil", "gmon.out");
3520 #endif
3521 if (repo_path && unveil(repo_path, "r") != 0)
3522 return got_error_from_errno2("unveil", repo_path);
3524 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3525 return got_error_from_errno2("unveil", worktree_path);
3527 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3528 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3530 error = got_privsep_unveil_exec_helpers();
3531 if (error != NULL)
3532 return error;
3534 if (unveil(NULL, NULL) != 0)
3535 return got_error_from_errno("unveil");
3537 return NULL;
3540 static void
3541 init_curses(void)
3544 * Override default signal handlers before starting ncurses.
3545 * This should prevent ncurses from installing its own
3546 * broken cleanup() signal handler.
3548 signal(SIGWINCH, tog_sigwinch);
3549 signal(SIGPIPE, tog_sigpipe);
3550 signal(SIGCONT, tog_sigcont);
3551 signal(SIGINT, tog_sigint);
3552 signal(SIGTERM, tog_sigterm);
3554 initscr();
3555 cbreak();
3556 halfdelay(1); /* Do fast refresh while initial view is loading. */
3557 noecho();
3558 nonl();
3559 intrflush(stdscr, FALSE);
3560 keypad(stdscr, TRUE);
3561 curs_set(0);
3562 if (getenv("TOG_COLORS") != NULL) {
3563 start_color();
3564 use_default_colors();
3568 static const struct got_error *
3569 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3570 struct got_repository *repo, struct got_worktree *worktree)
3572 const struct got_error *err = NULL;
3574 if (argc == 0) {
3575 *in_repo_path = strdup("/");
3576 if (*in_repo_path == NULL)
3577 return got_error_from_errno("strdup");
3578 return NULL;
3581 if (worktree) {
3582 const char *prefix = got_worktree_get_path_prefix(worktree);
3583 char *p;
3585 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3586 if (err)
3587 return err;
3588 if (asprintf(in_repo_path, "%s%s%s", prefix,
3589 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3590 p) == -1) {
3591 err = got_error_from_errno("asprintf");
3592 *in_repo_path = NULL;
3594 free(p);
3595 } else
3596 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3598 return err;
3601 static const struct got_error *
3602 cmd_log(int argc, char *argv[])
3604 const struct got_error *error;
3605 struct got_repository *repo = NULL;
3606 struct got_worktree *worktree = NULL;
3607 struct got_object_id *start_id = NULL;
3608 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3609 char *start_commit = NULL, *label = NULL;
3610 struct got_reference *ref = NULL;
3611 const char *head_ref_name = NULL;
3612 int ch, log_branches = 0;
3613 struct tog_view *view;
3614 int *pack_fds = NULL;
3616 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3617 switch (ch) {
3618 case 'b':
3619 log_branches = 1;
3620 break;
3621 case 'c':
3622 start_commit = optarg;
3623 break;
3624 case 'r':
3625 repo_path = realpath(optarg, NULL);
3626 if (repo_path == NULL)
3627 return got_error_from_errno2("realpath",
3628 optarg);
3629 break;
3630 default:
3631 usage_log();
3632 /* NOTREACHED */
3636 argc -= optind;
3637 argv += optind;
3639 if (argc > 1)
3640 usage_log();
3642 error = got_repo_pack_fds_open(&pack_fds);
3643 if (error != NULL)
3644 goto done;
3646 if (repo_path == NULL) {
3647 cwd = getcwd(NULL, 0);
3648 if (cwd == NULL)
3649 return got_error_from_errno("getcwd");
3650 error = got_worktree_open(&worktree, cwd);
3651 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3652 goto done;
3653 if (worktree)
3654 repo_path =
3655 strdup(got_worktree_get_repo_path(worktree));
3656 else
3657 repo_path = strdup(cwd);
3658 if (repo_path == NULL) {
3659 error = got_error_from_errno("strdup");
3660 goto done;
3664 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3665 if (error != NULL)
3666 goto done;
3668 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3669 repo, worktree);
3670 if (error)
3671 goto done;
3673 init_curses();
3675 error = apply_unveil(got_repo_get_path(repo),
3676 worktree ? got_worktree_get_root_path(worktree) : NULL);
3677 if (error)
3678 goto done;
3680 /* already loaded by tog_log_with_path()? */
3681 if (TAILQ_EMPTY(&tog_refs)) {
3682 error = tog_load_refs(repo, 0);
3683 if (error)
3684 goto done;
3687 if (start_commit == NULL) {
3688 error = got_repo_match_object_id(&start_id, &label,
3689 worktree ? got_worktree_get_head_ref_name(worktree) :
3690 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3691 if (error)
3692 goto done;
3693 head_ref_name = label;
3694 } else {
3695 error = got_ref_open(&ref, repo, start_commit, 0);
3696 if (error == NULL)
3697 head_ref_name = got_ref_get_name(ref);
3698 else if (error->code != GOT_ERR_NOT_REF)
3699 goto done;
3700 error = got_repo_match_object_id(&start_id, NULL,
3701 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3702 if (error)
3703 goto done;
3706 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3707 if (view == NULL) {
3708 error = got_error_from_errno("view_open");
3709 goto done;
3711 error = open_log_view(view, start_id, repo, head_ref_name,
3712 in_repo_path, log_branches);
3713 if (error)
3714 goto done;
3715 if (worktree) {
3716 /* Release work tree lock. */
3717 got_worktree_close(worktree);
3718 worktree = NULL;
3720 error = view_loop(view);
3721 done:
3722 free(in_repo_path);
3723 free(repo_path);
3724 free(cwd);
3725 free(start_id);
3726 free(label);
3727 if (ref)
3728 got_ref_close(ref);
3729 if (repo) {
3730 const struct got_error *close_err = got_repo_close(repo);
3731 if (error == NULL)
3732 error = close_err;
3734 if (worktree)
3735 got_worktree_close(worktree);
3736 if (pack_fds) {
3737 const struct got_error *pack_err =
3738 got_repo_pack_fds_close(pack_fds);
3739 if (error == NULL)
3740 error = pack_err;
3742 tog_free_refs();
3743 return error;
3746 __dead static void
3747 usage_diff(void)
3749 endwin();
3750 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3751 "[-w] object1 object2\n", getprogname());
3752 exit(1);
3755 static int
3756 match_line(const char *line, regex_t *regex, size_t nmatch,
3757 regmatch_t *regmatch)
3759 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3762 static struct tog_color *
3763 match_color(struct tog_colors *colors, const char *line)
3765 struct tog_color *tc = NULL;
3767 STAILQ_FOREACH(tc, colors, entry) {
3768 if (match_line(line, &tc->regex, 0, NULL))
3769 return tc;
3772 return NULL;
3775 static const struct got_error *
3776 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3777 WINDOW *window, int skipcol, regmatch_t *regmatch)
3779 const struct got_error *err = NULL;
3780 char *exstr = NULL;
3781 wchar_t *wline = NULL;
3782 int rme, rms, n, width, scrollx;
3783 int width0 = 0, width1 = 0, width2 = 0;
3784 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3786 *wtotal = 0;
3788 rms = regmatch->rm_so;
3789 rme = regmatch->rm_eo;
3791 err = expand_tab(&exstr, line);
3792 if (err)
3793 return err;
3795 /* Split the line into 3 segments, according to match offsets. */
3796 seg0 = strndup(exstr, rms);
3797 if (seg0 == NULL) {
3798 err = got_error_from_errno("strndup");
3799 goto done;
3801 seg1 = strndup(exstr + rms, rme - rms);
3802 if (seg1 == NULL) {
3803 err = got_error_from_errno("strndup");
3804 goto done;
3806 seg2 = strdup(exstr + rme);
3807 if (seg2 == NULL) {
3808 err = got_error_from_errno("strndup");
3809 goto done;
3812 /* draw up to matched token if we haven't scrolled past it */
3813 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3814 col_tab_align, 1);
3815 if (err)
3816 goto done;
3817 n = MAX(width0 - skipcol, 0);
3818 if (n) {
3819 free(wline);
3820 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3821 wlimit, col_tab_align, 1);
3822 if (err)
3823 goto done;
3824 waddwstr(window, &wline[scrollx]);
3825 wlimit -= width;
3826 *wtotal += width;
3829 if (wlimit > 0) {
3830 int i = 0, w = 0;
3831 size_t wlen;
3833 free(wline);
3834 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3835 col_tab_align, 1);
3836 if (err)
3837 goto done;
3838 wlen = wcslen(wline);
3839 while (i < wlen) {
3840 width = wcwidth(wline[i]);
3841 if (width == -1) {
3842 /* should not happen, tabs are expanded */
3843 err = got_error(GOT_ERR_RANGE);
3844 goto done;
3846 if (width0 + w + width > skipcol)
3847 break;
3848 w += width;
3849 i++;
3851 /* draw (visible part of) matched token (if scrolled into it) */
3852 if (width1 - w > 0) {
3853 wattron(window, A_STANDOUT);
3854 waddwstr(window, &wline[i]);
3855 wattroff(window, A_STANDOUT);
3856 wlimit -= (width1 - w);
3857 *wtotal += (width1 - w);
3861 if (wlimit > 0) { /* draw rest of line */
3862 free(wline);
3863 if (skipcol > width0 + width1) {
3864 err = format_line(&wline, &width2, &scrollx, seg2,
3865 skipcol - (width0 + width1), wlimit,
3866 col_tab_align, 1);
3867 if (err)
3868 goto done;
3869 waddwstr(window, &wline[scrollx]);
3870 } else {
3871 err = format_line(&wline, &width2, NULL, seg2, 0,
3872 wlimit, col_tab_align, 1);
3873 if (err)
3874 goto done;
3875 waddwstr(window, wline);
3877 *wtotal += width2;
3879 done:
3880 free(wline);
3881 free(exstr);
3882 free(seg0);
3883 free(seg1);
3884 free(seg2);
3885 return err;
3888 static const struct got_error *
3889 draw_file(struct tog_view *view, const char *header)
3891 struct tog_diff_view_state *s = &view->state.diff;
3892 regmatch_t *regmatch = &view->regmatch;
3893 const struct got_error *err;
3894 int nprinted = 0;
3895 char *line;
3896 size_t linesize = 0;
3897 ssize_t linelen;
3898 struct tog_color *tc;
3899 wchar_t *wline;
3900 int width;
3901 int max_lines = view->nlines;
3902 int nlines = s->nlines;
3903 off_t line_offset;
3905 line_offset = s->line_offsets[s->first_displayed_line - 1];
3906 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3907 return got_error_from_errno("fseek");
3909 werase(view->window);
3911 if (header) {
3912 if (asprintf(&line, "[%d/%d] %s",
3913 s->first_displayed_line - 1 + s->selected_line, nlines,
3914 header) == -1)
3915 return got_error_from_errno("asprintf");
3916 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3917 0, 0);
3918 free(line);
3919 if (err)
3920 return err;
3922 if (view_needs_focus_indication(view))
3923 wstandout(view->window);
3924 waddwstr(view->window, wline);
3925 free(wline);
3926 wline = NULL;
3927 if (view_needs_focus_indication(view))
3928 wstandend(view->window);
3929 if (width <= view->ncols - 1)
3930 waddch(view->window, '\n');
3932 if (max_lines <= 1)
3933 return NULL;
3934 max_lines--;
3937 s->eof = 0;
3938 view->maxx = 0;
3939 line = NULL;
3940 while (max_lines > 0 && nprinted < max_lines) {
3941 linelen = getline(&line, &linesize, s->f);
3942 if (linelen == -1) {
3943 if (feof(s->f)) {
3944 s->eof = 1;
3945 break;
3947 free(line);
3948 return got_ferror(s->f, GOT_ERR_IO);
3951 /* Set view->maxx based on full line length. */
3952 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3953 view->x ? 1 : 0);
3954 if (err) {
3955 free(line);
3956 return err;
3958 view->maxx = MAX(view->maxx, width);
3959 free(wline);
3960 wline = NULL;
3962 tc = match_color(&s->colors, line);
3963 if (tc)
3964 wattr_on(view->window,
3965 COLOR_PAIR(tc->colorpair), NULL);
3966 if (s->first_displayed_line + nprinted == s->matched_line &&
3967 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3968 err = add_matched_line(&width, line, view->ncols, 0,
3969 view->window, view->x, regmatch);
3970 if (err) {
3971 free(line);
3972 return err;
3974 } else {
3975 int skip;
3976 err = format_line(&wline, &width, &skip, line,
3977 view->x, view->ncols, 0, view->x ? 1 : 0);
3978 if (err) {
3979 free(line);
3980 return err;
3982 waddwstr(view->window, &wline[skip]);
3983 free(wline);
3984 wline = NULL;
3986 if (tc)
3987 wattr_off(view->window,
3988 COLOR_PAIR(tc->colorpair), NULL);
3989 if (width <= view->ncols - 1)
3990 waddch(view->window, '\n');
3991 nprinted++;
3993 free(line);
3994 if (nprinted >= 1)
3995 s->last_displayed_line = s->first_displayed_line +
3996 (nprinted - 1);
3997 else
3998 s->last_displayed_line = s->first_displayed_line;
4000 view_border(view);
4002 if (s->eof) {
4003 while (nprinted < view->nlines) {
4004 waddch(view->window, '\n');
4005 nprinted++;
4008 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4009 view->ncols, 0, 0);
4010 if (err) {
4011 return err;
4014 wstandout(view->window);
4015 waddwstr(view->window, wline);
4016 free(wline);
4017 wline = NULL;
4018 wstandend(view->window);
4021 return NULL;
4024 static char *
4025 get_datestr(time_t *time, char *datebuf)
4027 struct tm mytm, *tm;
4028 char *p, *s;
4030 tm = gmtime_r(time, &mytm);
4031 if (tm == NULL)
4032 return NULL;
4033 s = asctime_r(tm, datebuf);
4034 if (s == NULL)
4035 return NULL;
4036 p = strchr(s, '\n');
4037 if (p)
4038 *p = '\0';
4039 return s;
4042 static const struct got_error *
4043 get_changed_paths(struct got_pathlist_head *paths,
4044 struct got_commit_object *commit, struct got_repository *repo)
4046 const struct got_error *err = NULL;
4047 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4048 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4049 struct got_object_qid *qid;
4051 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4052 if (qid != NULL) {
4053 struct got_commit_object *pcommit;
4054 err = got_object_open_as_commit(&pcommit, repo,
4055 &qid->id);
4056 if (err)
4057 return err;
4059 tree_id1 = got_object_id_dup(
4060 got_object_commit_get_tree_id(pcommit));
4061 if (tree_id1 == NULL) {
4062 got_object_commit_close(pcommit);
4063 return got_error_from_errno("got_object_id_dup");
4065 got_object_commit_close(pcommit);
4069 if (tree_id1) {
4070 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4071 if (err)
4072 goto done;
4075 tree_id2 = got_object_commit_get_tree_id(commit);
4076 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4077 if (err)
4078 goto done;
4080 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4081 got_diff_tree_collect_changed_paths, paths, 0);
4082 done:
4083 if (tree1)
4084 got_object_tree_close(tree1);
4085 if (tree2)
4086 got_object_tree_close(tree2);
4087 free(tree_id1);
4088 return err;
4091 static const struct got_error *
4092 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
4094 off_t *p;
4096 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
4097 if (p == NULL)
4098 return got_error_from_errno("reallocarray");
4099 *line_offsets = p;
4100 (*line_offsets)[*nlines] = off;
4101 (*nlines)++;
4102 return NULL;
4105 static const struct got_error *
4106 write_commit_info(off_t **line_offsets, size_t *nlines,
4107 struct got_object_id *commit_id, struct got_reflist_head *refs,
4108 struct got_repository *repo, FILE *outfile)
4110 const struct got_error *err = NULL;
4111 char datebuf[26], *datestr;
4112 struct got_commit_object *commit;
4113 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4114 time_t committer_time;
4115 const char *author, *committer;
4116 char *refs_str = NULL;
4117 struct got_pathlist_head changed_paths;
4118 struct got_pathlist_entry *pe;
4119 off_t outoff = 0;
4120 int n;
4122 TAILQ_INIT(&changed_paths);
4124 if (refs) {
4125 err = build_refs_str(&refs_str, refs, commit_id, repo);
4126 if (err)
4127 return err;
4130 err = got_object_open_as_commit(&commit, repo, commit_id);
4131 if (err)
4132 return err;
4134 err = got_object_id_str(&id_str, commit_id);
4135 if (err) {
4136 err = got_error_from_errno("got_object_id_str");
4137 goto done;
4140 err = add_line_offset(line_offsets, nlines, 0);
4141 if (err)
4142 goto done;
4144 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4145 refs_str ? refs_str : "", refs_str ? ")" : "");
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 n = fprintf(outfile, "from: %s\n",
4156 got_object_commit_get_author(commit));
4157 if (n < 0) {
4158 err = got_error_from_errno("fprintf");
4159 goto done;
4161 outoff += n;
4162 err = add_line_offset(line_offsets, nlines, outoff);
4163 if (err)
4164 goto done;
4166 committer_time = got_object_commit_get_committer_time(commit);
4167 datestr = get_datestr(&committer_time, datebuf);
4168 if (datestr) {
4169 n = fprintf(outfile, "date: %s UTC\n", datestr);
4170 if (n < 0) {
4171 err = got_error_from_errno("fprintf");
4172 goto done;
4174 outoff += n;
4175 err = add_line_offset(line_offsets, nlines, outoff);
4176 if (err)
4177 goto done;
4179 author = got_object_commit_get_author(commit);
4180 committer = got_object_commit_get_committer(commit);
4181 if (strcmp(author, committer) != 0) {
4182 n = fprintf(outfile, "via: %s\n", committer);
4183 if (n < 0) {
4184 err = got_error_from_errno("fprintf");
4185 goto done;
4187 outoff += n;
4188 err = add_line_offset(line_offsets, nlines, outoff);
4189 if (err)
4190 goto done;
4192 if (got_object_commit_get_nparents(commit) > 1) {
4193 const struct got_object_id_queue *parent_ids;
4194 struct got_object_qid *qid;
4195 int pn = 1;
4196 parent_ids = got_object_commit_get_parent_ids(commit);
4197 STAILQ_FOREACH(qid, parent_ids, entry) {
4198 err = got_object_id_str(&id_str, &qid->id);
4199 if (err)
4200 goto done;
4201 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4202 if (n < 0) {
4203 err = got_error_from_errno("fprintf");
4204 goto done;
4206 outoff += n;
4207 err = add_line_offset(line_offsets, nlines, outoff);
4208 if (err)
4209 goto done;
4210 free(id_str);
4211 id_str = NULL;
4215 err = got_object_commit_get_logmsg(&logmsg, commit);
4216 if (err)
4217 goto done;
4218 s = logmsg;
4219 while ((line = strsep(&s, "\n")) != NULL) {
4220 n = fprintf(outfile, "%s\n", line);
4221 if (n < 0) {
4222 err = got_error_from_errno("fprintf");
4223 goto done;
4225 outoff += n;
4226 err = add_line_offset(line_offsets, nlines, outoff);
4227 if (err)
4228 goto done;
4231 err = get_changed_paths(&changed_paths, commit, repo);
4232 if (err)
4233 goto done;
4234 TAILQ_FOREACH(pe, &changed_paths, entry) {
4235 struct got_diff_changed_path *cp = pe->data;
4236 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4237 if (n < 0) {
4238 err = got_error_from_errno("fprintf");
4239 goto done;
4241 outoff += n;
4242 err = add_line_offset(line_offsets, nlines, outoff);
4243 if (err)
4244 goto done;
4245 free((char *)pe->path);
4246 free(pe->data);
4249 fputc('\n', outfile);
4250 outoff++;
4251 err = add_line_offset(line_offsets, nlines, outoff);
4252 done:
4253 got_pathlist_free(&changed_paths);
4254 free(id_str);
4255 free(logmsg);
4256 free(refs_str);
4257 got_object_commit_close(commit);
4258 if (err) {
4259 free(*line_offsets);
4260 *line_offsets = NULL;
4261 *nlines = 0;
4263 return err;
4266 static const struct got_error *
4267 create_diff(struct tog_diff_view_state *s)
4269 const struct got_error *err = NULL;
4270 FILE *f = NULL;
4271 int obj_type;
4273 free(s->line_offsets);
4274 s->line_offsets = malloc(sizeof(off_t));
4275 if (s->line_offsets == NULL)
4276 return got_error_from_errno("malloc");
4277 s->nlines = 0;
4279 f = got_opentemp();
4280 if (f == NULL) {
4281 err = got_error_from_errno("got_opentemp");
4282 goto done;
4284 if (s->f && fclose(s->f) == EOF) {
4285 err = got_error_from_errno("fclose");
4286 goto done;
4288 s->f = f;
4290 if (s->id1)
4291 err = got_object_get_type(&obj_type, s->repo, s->id1);
4292 else
4293 err = got_object_get_type(&obj_type, s->repo, s->id2);
4294 if (err)
4295 goto done;
4297 switch (obj_type) {
4298 case GOT_OBJ_TYPE_BLOB:
4299 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
4300 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4301 s->label1, s->label2, tog_diff_algo, s->diff_context,
4302 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4303 break;
4304 case GOT_OBJ_TYPE_TREE:
4305 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
4306 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4307 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4308 s->force_text_diff, s->repo, s->f);
4309 break;
4310 case GOT_OBJ_TYPE_COMMIT: {
4311 const struct got_object_id_queue *parent_ids;
4312 struct got_object_qid *pid;
4313 struct got_commit_object *commit2;
4314 struct got_reflist_head *refs;
4316 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4317 if (err)
4318 goto done;
4319 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4320 /* Show commit info if we're diffing to a parent/root commit. */
4321 if (s->id1 == NULL) {
4322 err = write_commit_info(&s->line_offsets, &s->nlines,
4323 s->id2, refs, s->repo, s->f);
4324 if (err)
4325 goto done;
4326 } else {
4327 parent_ids = got_object_commit_get_parent_ids(commit2);
4328 STAILQ_FOREACH(pid, parent_ids, entry) {
4329 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4330 err = write_commit_info(
4331 &s->line_offsets, &s->nlines,
4332 s->id2, refs, s->repo, s->f);
4333 if (err)
4334 goto done;
4335 break;
4339 got_object_commit_close(commit2);
4341 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4342 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4343 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4344 s->force_text_diff, s->repo, s->f);
4345 break;
4347 default:
4348 err = got_error(GOT_ERR_OBJ_TYPE);
4349 break;
4351 if (err)
4352 goto done;
4353 done:
4354 if (s->f && fflush(s->f) != 0 && err == NULL)
4355 err = got_error_from_errno("fflush");
4356 return err;
4359 static void
4360 diff_view_indicate_progress(struct tog_view *view)
4362 mvwaddstr(view->window, 0, 0, "diffing...");
4363 update_panels();
4364 doupdate();
4367 static const struct got_error *
4368 search_start_diff_view(struct tog_view *view)
4370 struct tog_diff_view_state *s = &view->state.diff;
4372 s->matched_line = 0;
4373 return NULL;
4376 static const struct got_error *
4377 search_next_diff_view(struct tog_view *view)
4379 struct tog_diff_view_state *s = &view->state.diff;
4380 const struct got_error *err = NULL;
4381 int lineno;
4382 char *line = NULL;
4383 size_t linesize = 0;
4384 ssize_t linelen;
4386 if (!view->searching) {
4387 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4388 return NULL;
4391 if (s->matched_line) {
4392 if (view->searching == TOG_SEARCH_FORWARD)
4393 lineno = s->matched_line + 1;
4394 else
4395 lineno = s->matched_line - 1;
4396 } else
4397 lineno = s->first_displayed_line;
4399 while (1) {
4400 off_t offset;
4402 if (lineno <= 0 || lineno > s->nlines) {
4403 if (s->matched_line == 0) {
4404 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4405 break;
4408 if (view->searching == TOG_SEARCH_FORWARD)
4409 lineno = 1;
4410 else
4411 lineno = s->nlines;
4414 offset = s->line_offsets[lineno - 1];
4415 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4416 free(line);
4417 return got_error_from_errno("fseeko");
4419 linelen = getline(&line, &linesize, s->f);
4420 if (linelen != -1) {
4421 char *exstr;
4422 err = expand_tab(&exstr, line);
4423 if (err)
4424 break;
4425 if (match_line(exstr, &view->regex, 1,
4426 &view->regmatch)) {
4427 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4428 s->matched_line = lineno;
4429 free(exstr);
4430 break;
4432 free(exstr);
4434 if (view->searching == TOG_SEARCH_FORWARD)
4435 lineno++;
4436 else
4437 lineno--;
4439 free(line);
4441 if (s->matched_line) {
4442 s->first_displayed_line = s->matched_line;
4443 s->selected_line = 1;
4446 return err;
4449 static const struct got_error *
4450 close_diff_view(struct tog_view *view)
4452 const struct got_error *err = NULL;
4453 struct tog_diff_view_state *s = &view->state.diff;
4455 free(s->id1);
4456 s->id1 = NULL;
4457 free(s->id2);
4458 s->id2 = NULL;
4459 if (s->f && fclose(s->f) == EOF)
4460 err = got_error_from_errno("fclose");
4461 s->f = NULL;
4462 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4463 err = got_error_from_errno("fclose");
4464 s->f1 = NULL;
4465 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4466 err = got_error_from_errno("fclose");
4467 s->f2 = NULL;
4468 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4469 err = got_error_from_errno("close");
4470 s->fd1 = -1;
4471 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4472 err = got_error_from_errno("close");
4473 s->fd2 = -1;
4474 free_colors(&s->colors);
4475 free(s->line_offsets);
4476 s->line_offsets = NULL;
4477 s->nlines = 0;
4478 return err;
4481 static const struct got_error *
4482 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4483 struct got_object_id *id2, const char *label1, const char *label2,
4484 int diff_context, int ignore_whitespace, int force_text_diff,
4485 struct tog_view *parent_view, struct got_repository *repo)
4487 const struct got_error *err;
4488 struct tog_diff_view_state *s = &view->state.diff;
4490 memset(s, 0, sizeof(*s));
4491 s->fd1 = -1;
4492 s->fd2 = -1;
4494 if (id1 != NULL && id2 != NULL) {
4495 int type1, type2;
4496 err = got_object_get_type(&type1, repo, id1);
4497 if (err)
4498 return err;
4499 err = got_object_get_type(&type2, repo, id2);
4500 if (err)
4501 return err;
4503 if (type1 != type2)
4504 return got_error(GOT_ERR_OBJ_TYPE);
4506 s->first_displayed_line = 1;
4507 s->last_displayed_line = view->nlines;
4508 s->selected_line = 1;
4509 s->repo = repo;
4510 s->id1 = id1;
4511 s->id2 = id2;
4512 s->label1 = label1;
4513 s->label2 = label2;
4515 if (id1) {
4516 s->id1 = got_object_id_dup(id1);
4517 if (s->id1 == NULL)
4518 return got_error_from_errno("got_object_id_dup");
4519 } else
4520 s->id1 = NULL;
4522 s->id2 = got_object_id_dup(id2);
4523 if (s->id2 == NULL) {
4524 err = got_error_from_errno("got_object_id_dup");
4525 goto done;
4528 s->f1 = got_opentemp();
4529 if (s->f1 == NULL) {
4530 err = got_error_from_errno("got_opentemp");
4531 goto done;
4534 s->f2 = got_opentemp();
4535 if (s->f2 == NULL) {
4536 err = got_error_from_errno("got_opentemp");
4537 goto done;
4540 s->fd1 = got_opentempfd();
4541 if (s->fd1 == -1) {
4542 err = got_error_from_errno("got_opentempfd");
4543 goto done;
4546 s->fd2 = got_opentempfd();
4547 if (s->fd2 == -1) {
4548 err = got_error_from_errno("got_opentempfd");
4549 goto done;
4552 s->first_displayed_line = 1;
4553 s->last_displayed_line = view->nlines;
4554 s->diff_context = diff_context;
4555 s->ignore_whitespace = ignore_whitespace;
4556 s->force_text_diff = force_text_diff;
4557 s->parent_view = parent_view;
4558 s->repo = repo;
4560 STAILQ_INIT(&s->colors);
4561 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4562 err = add_color(&s->colors,
4563 "^-", TOG_COLOR_DIFF_MINUS,
4564 get_color_value("TOG_COLOR_DIFF_MINUS"));
4565 if (err)
4566 goto done;
4567 err = add_color(&s->colors, "^\\+",
4568 TOG_COLOR_DIFF_PLUS,
4569 get_color_value("TOG_COLOR_DIFF_PLUS"));
4570 if (err)
4571 goto done;
4572 err = add_color(&s->colors,
4573 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4574 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4575 if (err)
4576 goto done;
4578 err = add_color(&s->colors,
4579 "^(commit [0-9a-f]|parent [0-9]|"
4580 "(blob|file|tree|commit) [-+] |"
4581 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4582 get_color_value("TOG_COLOR_DIFF_META"));
4583 if (err)
4584 goto done;
4586 err = add_color(&s->colors,
4587 "^(from|via): ", TOG_COLOR_AUTHOR,
4588 get_color_value("TOG_COLOR_AUTHOR"));
4589 if (err)
4590 goto done;
4592 err = add_color(&s->colors,
4593 "^date: ", TOG_COLOR_DATE,
4594 get_color_value("TOG_COLOR_DATE"));
4595 if (err)
4596 goto done;
4599 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4600 view_is_splitscreen(view))
4601 show_log_view(parent_view); /* draw border */
4602 diff_view_indicate_progress(view);
4604 err = create_diff(s);
4606 view->show = show_diff_view;
4607 view->input = input_diff_view;
4608 view->reset = reset_diff_view;
4609 view->close = close_diff_view;
4610 view->search_start = search_start_diff_view;
4611 view->search_next = search_next_diff_view;
4612 done:
4613 if (err)
4614 close_diff_view(view);
4615 return err;
4618 static const struct got_error *
4619 show_diff_view(struct tog_view *view)
4621 const struct got_error *err;
4622 struct tog_diff_view_state *s = &view->state.diff;
4623 char *id_str1 = NULL, *id_str2, *header;
4624 const char *label1, *label2;
4626 if (s->id1) {
4627 err = got_object_id_str(&id_str1, s->id1);
4628 if (err)
4629 return err;
4630 label1 = s->label1 ? : id_str1;
4631 } else
4632 label1 = "/dev/null";
4634 err = got_object_id_str(&id_str2, s->id2);
4635 if (err)
4636 return err;
4637 label2 = s->label2 ? : id_str2;
4639 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4640 err = got_error_from_errno("asprintf");
4641 free(id_str1);
4642 free(id_str2);
4643 return err;
4645 free(id_str1);
4646 free(id_str2);
4648 err = draw_file(view, header);
4649 free(header);
4650 return err;
4653 static const struct got_error *
4654 set_selected_commit(struct tog_diff_view_state *s,
4655 struct commit_queue_entry *entry)
4657 const struct got_error *err;
4658 const struct got_object_id_queue *parent_ids;
4659 struct got_commit_object *selected_commit;
4660 struct got_object_qid *pid;
4662 free(s->id2);
4663 s->id2 = got_object_id_dup(entry->id);
4664 if (s->id2 == NULL)
4665 return got_error_from_errno("got_object_id_dup");
4667 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4668 if (err)
4669 return err;
4670 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4671 free(s->id1);
4672 pid = STAILQ_FIRST(parent_ids);
4673 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4674 got_object_commit_close(selected_commit);
4675 return NULL;
4678 static const struct got_error *
4679 reset_diff_view(struct tog_view *view)
4681 struct tog_diff_view_state *s = &view->state.diff;
4683 view->count = 0;
4684 wclear(view->window);
4685 s->first_displayed_line = 1;
4686 s->last_displayed_line = view->nlines;
4687 s->matched_line = 0;
4688 diff_view_indicate_progress(view);
4689 return create_diff(s);
4692 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4693 int, int, int);
4694 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4695 int, int);
4697 static const struct got_error *
4698 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4700 const struct got_error *err = NULL;
4701 struct tog_diff_view_state *s = &view->state.diff;
4702 struct tog_log_view_state *ls;
4703 struct commit_queue_entry *old_selected_entry;
4704 char *line = NULL;
4705 size_t linesize = 0;
4706 ssize_t linelen;
4707 int i, nscroll = view->nlines - 1, up = 0;
4709 switch (ch) {
4710 case '0':
4711 view->x = 0;
4712 break;
4713 case '$':
4714 view->x = MAX(view->maxx - view->ncols / 3, 0);
4715 view->count = 0;
4716 break;
4717 case KEY_RIGHT:
4718 case 'l':
4719 if (view->x + view->ncols / 3 < view->maxx)
4720 view->x += 2; /* move two columns right */
4721 else
4722 view->count = 0;
4723 break;
4724 case KEY_LEFT:
4725 case 'h':
4726 view->x -= MIN(view->x, 2); /* move two columns back */
4727 if (view->x <= 0)
4728 view->count = 0;
4729 break;
4730 case 'a':
4731 case 'w':
4732 if (ch == 'a')
4733 s->force_text_diff = !s->force_text_diff;
4734 if (ch == 'w')
4735 s->ignore_whitespace = !s->ignore_whitespace;
4736 err = reset_diff_view(view);
4737 break;
4738 case 'g':
4739 case KEY_HOME:
4740 s->first_displayed_line = 1;
4741 view->count = 0;
4742 break;
4743 case 'G':
4744 case KEY_END:
4745 view->count = 0;
4746 if (s->eof)
4747 break;
4749 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4750 s->eof = 1;
4751 break;
4752 case 'k':
4753 case KEY_UP:
4754 case CTRL('p'):
4755 if (s->first_displayed_line > 1)
4756 s->first_displayed_line--;
4757 else
4758 view->count = 0;
4759 break;
4760 case CTRL('u'):
4761 case 'u':
4762 nscroll /= 2;
4763 /* FALL THROUGH */
4764 case KEY_PPAGE:
4765 case CTRL('b'):
4766 case 'b':
4767 if (s->first_displayed_line == 1) {
4768 view->count = 0;
4769 break;
4771 i = 0;
4772 while (i++ < nscroll && s->first_displayed_line > 1)
4773 s->first_displayed_line--;
4774 break;
4775 case 'j':
4776 case KEY_DOWN:
4777 case CTRL('n'):
4778 if (!s->eof)
4779 s->first_displayed_line++;
4780 else
4781 view->count = 0;
4782 break;
4783 case CTRL('d'):
4784 case 'd':
4785 nscroll /= 2;
4786 /* FALL THROUGH */
4787 case KEY_NPAGE:
4788 case CTRL('f'):
4789 case 'f':
4790 case ' ':
4791 if (s->eof) {
4792 view->count = 0;
4793 break;
4795 i = 0;
4796 while (!s->eof && i++ < nscroll) {
4797 linelen = getline(&line, &linesize, s->f);
4798 s->first_displayed_line++;
4799 if (linelen == -1) {
4800 if (feof(s->f)) {
4801 s->eof = 1;
4802 } else
4803 err = got_ferror(s->f, GOT_ERR_IO);
4804 break;
4807 free(line);
4808 break;
4809 case '[':
4810 if (s->diff_context > 0) {
4811 s->diff_context--;
4812 s->matched_line = 0;
4813 diff_view_indicate_progress(view);
4814 err = create_diff(s);
4815 if (s->first_displayed_line + view->nlines - 1 >
4816 s->nlines) {
4817 s->first_displayed_line = 1;
4818 s->last_displayed_line = view->nlines;
4820 } else
4821 view->count = 0;
4822 break;
4823 case ']':
4824 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4825 s->diff_context++;
4826 s->matched_line = 0;
4827 diff_view_indicate_progress(view);
4828 err = create_diff(s);
4829 } else
4830 view->count = 0;
4831 break;
4832 case '<':
4833 case ',':
4834 up = 1;
4835 /* FALL THROUGH */
4836 case '>':
4837 case '.':
4838 if (s->parent_view == NULL) {
4839 view->count = 0;
4840 break;
4842 s->parent_view->count = view->count;
4844 if (s->parent_view->type == TOG_VIEW_LOG) {
4845 ls = &s->parent_view->state.log;
4846 old_selected_entry = ls->selected_entry;
4848 err = input_log_view(NULL, s->parent_view,
4849 up ? KEY_UP : KEY_DOWN);
4850 if (err)
4851 break;
4852 view->count = s->parent_view->count;
4854 if (old_selected_entry == ls->selected_entry)
4855 break;
4857 err = set_selected_commit(s, ls->selected_entry);
4858 if (err)
4859 break;
4860 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4861 struct tog_blame_view_state *bs;
4862 struct got_object_id *id, *prev_id;
4864 bs = &s->parent_view->state.blame;
4865 prev_id = get_annotation_for_line(bs->blame.lines,
4866 bs->blame.nlines, bs->last_diffed_line);
4868 err = input_blame_view(&view, s->parent_view,
4869 up ? KEY_UP : KEY_DOWN);
4870 if (err)
4871 break;
4872 view->count = s->parent_view->count;
4874 if (prev_id == NULL)
4875 break;
4876 id = get_selected_commit_id(bs->blame.lines,
4877 bs->blame.nlines, bs->first_displayed_line,
4878 bs->selected_line);
4879 if (id == NULL)
4880 break;
4882 if (!got_object_id_cmp(prev_id, id))
4883 break;
4885 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
4886 if (err)
4887 break;
4889 s->first_displayed_line = 1;
4890 s->last_displayed_line = view->nlines;
4891 s->matched_line = 0;
4892 view->x = 0;
4894 diff_view_indicate_progress(view);
4895 err = create_diff(s);
4896 break;
4897 default:
4898 view->count = 0;
4899 break;
4902 return err;
4905 static const struct got_error *
4906 cmd_diff(int argc, char *argv[])
4908 const struct got_error *error = NULL;
4909 struct got_repository *repo = NULL;
4910 struct got_worktree *worktree = NULL;
4911 struct got_object_id *id1 = NULL, *id2 = NULL;
4912 char *repo_path = NULL, *cwd = NULL;
4913 char *id_str1 = NULL, *id_str2 = NULL;
4914 char *label1 = NULL, *label2 = NULL;
4915 int diff_context = 3, ignore_whitespace = 0;
4916 int ch, force_text_diff = 0;
4917 const char *errstr;
4918 struct tog_view *view;
4919 int *pack_fds = NULL;
4921 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4922 switch (ch) {
4923 case 'a':
4924 force_text_diff = 1;
4925 break;
4926 case 'C':
4927 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4928 &errstr);
4929 if (errstr != NULL)
4930 errx(1, "number of context lines is %s: %s",
4931 errstr, errstr);
4932 break;
4933 case 'r':
4934 repo_path = realpath(optarg, NULL);
4935 if (repo_path == NULL)
4936 return got_error_from_errno2("realpath",
4937 optarg);
4938 got_path_strip_trailing_slashes(repo_path);
4939 break;
4940 case 'w':
4941 ignore_whitespace = 1;
4942 break;
4943 default:
4944 usage_diff();
4945 /* NOTREACHED */
4949 argc -= optind;
4950 argv += optind;
4952 if (argc == 0) {
4953 usage_diff(); /* TODO show local worktree changes */
4954 } else if (argc == 2) {
4955 id_str1 = argv[0];
4956 id_str2 = argv[1];
4957 } else
4958 usage_diff();
4960 error = got_repo_pack_fds_open(&pack_fds);
4961 if (error)
4962 goto done;
4964 if (repo_path == NULL) {
4965 cwd = getcwd(NULL, 0);
4966 if (cwd == NULL)
4967 return got_error_from_errno("getcwd");
4968 error = got_worktree_open(&worktree, cwd);
4969 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4970 goto done;
4971 if (worktree)
4972 repo_path =
4973 strdup(got_worktree_get_repo_path(worktree));
4974 else
4975 repo_path = strdup(cwd);
4976 if (repo_path == NULL) {
4977 error = got_error_from_errno("strdup");
4978 goto done;
4982 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4983 if (error)
4984 goto done;
4986 init_curses();
4988 error = apply_unveil(got_repo_get_path(repo), NULL);
4989 if (error)
4990 goto done;
4992 error = tog_load_refs(repo, 0);
4993 if (error)
4994 goto done;
4996 error = got_repo_match_object_id(&id1, &label1, id_str1,
4997 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4998 if (error)
4999 goto done;
5001 error = got_repo_match_object_id(&id2, &label2, id_str2,
5002 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5003 if (error)
5004 goto done;
5006 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5007 if (view == NULL) {
5008 error = got_error_from_errno("view_open");
5009 goto done;
5011 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5012 ignore_whitespace, force_text_diff, NULL, repo);
5013 if (error)
5014 goto done;
5015 error = view_loop(view);
5016 done:
5017 free(label1);
5018 free(label2);
5019 free(repo_path);
5020 free(cwd);
5021 if (repo) {
5022 const struct got_error *close_err = got_repo_close(repo);
5023 if (error == NULL)
5024 error = close_err;
5026 if (worktree)
5027 got_worktree_close(worktree);
5028 if (pack_fds) {
5029 const struct got_error *pack_err =
5030 got_repo_pack_fds_close(pack_fds);
5031 if (error == NULL)
5032 error = pack_err;
5034 tog_free_refs();
5035 return error;
5038 __dead static void
5039 usage_blame(void)
5041 endwin();
5042 fprintf(stderr,
5043 "usage: %s blame [-c commit] [-r repository-path] path\n",
5044 getprogname());
5045 exit(1);
5048 struct tog_blame_line {
5049 int annotated;
5050 struct got_object_id *id;
5053 static const struct got_error *
5054 draw_blame(struct tog_view *view)
5056 struct tog_blame_view_state *s = &view->state.blame;
5057 struct tog_blame *blame = &s->blame;
5058 regmatch_t *regmatch = &view->regmatch;
5059 const struct got_error *err;
5060 int lineno = 0, nprinted = 0;
5061 char *line = NULL;
5062 size_t linesize = 0;
5063 ssize_t linelen;
5064 wchar_t *wline;
5065 int width;
5066 struct tog_blame_line *blame_line;
5067 struct got_object_id *prev_id = NULL;
5068 char *id_str;
5069 struct tog_color *tc;
5071 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5072 if (err)
5073 return err;
5075 rewind(blame->f);
5076 werase(view->window);
5078 if (asprintf(&line, "commit %s", id_str) == -1) {
5079 err = got_error_from_errno("asprintf");
5080 free(id_str);
5081 return err;
5084 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5085 free(line);
5086 line = NULL;
5087 if (err)
5088 return err;
5089 if (view_needs_focus_indication(view))
5090 wstandout(view->window);
5091 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5092 if (tc)
5093 wattr_on(view->window,
5094 COLOR_PAIR(tc->colorpair), NULL);
5095 waddwstr(view->window, wline);
5096 if (tc)
5097 wattr_off(view->window,
5098 COLOR_PAIR(tc->colorpair), NULL);
5099 if (view_needs_focus_indication(view))
5100 wstandend(view->window);
5101 free(wline);
5102 wline = NULL;
5103 if (width < view->ncols - 1)
5104 waddch(view->window, '\n');
5106 if (asprintf(&line, "[%d/%d] %s%s",
5107 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5108 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5109 free(id_str);
5110 return got_error_from_errno("asprintf");
5112 free(id_str);
5113 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5114 free(line);
5115 line = NULL;
5116 if (err)
5117 return err;
5118 waddwstr(view->window, wline);
5119 free(wline);
5120 wline = NULL;
5121 if (width < view->ncols - 1)
5122 waddch(view->window, '\n');
5124 s->eof = 0;
5125 view->maxx = 0;
5126 while (nprinted < view->nlines - 2) {
5127 linelen = getline(&line, &linesize, blame->f);
5128 if (linelen == -1) {
5129 if (feof(blame->f)) {
5130 s->eof = 1;
5131 break;
5133 free(line);
5134 return got_ferror(blame->f, GOT_ERR_IO);
5136 if (++lineno < s->first_displayed_line)
5137 continue;
5139 /* Set view->maxx based on full line length. */
5140 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5141 if (err) {
5142 free(line);
5143 return err;
5145 free(wline);
5146 wline = NULL;
5147 view->maxx = MAX(view->maxx, width);
5149 if (nprinted == s->selected_line - 1)
5150 wstandout(view->window);
5152 if (blame->nlines > 0) {
5153 blame_line = &blame->lines[lineno - 1];
5154 if (blame_line->annotated && prev_id &&
5155 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5156 !(nprinted == s->selected_line - 1)) {
5157 waddstr(view->window, " ");
5158 } else if (blame_line->annotated) {
5159 char *id_str;
5160 err = got_object_id_str(&id_str,
5161 blame_line->id);
5162 if (err) {
5163 free(line);
5164 return err;
5166 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5167 if (tc)
5168 wattr_on(view->window,
5169 COLOR_PAIR(tc->colorpair), NULL);
5170 wprintw(view->window, "%.8s", id_str);
5171 if (tc)
5172 wattr_off(view->window,
5173 COLOR_PAIR(tc->colorpair), NULL);
5174 free(id_str);
5175 prev_id = blame_line->id;
5176 } else {
5177 waddstr(view->window, "........");
5178 prev_id = NULL;
5180 } else {
5181 waddstr(view->window, "........");
5182 prev_id = NULL;
5185 if (nprinted == s->selected_line - 1)
5186 wstandend(view->window);
5187 waddstr(view->window, " ");
5189 if (view->ncols <= 9) {
5190 width = 9;
5191 } else if (s->first_displayed_line + nprinted ==
5192 s->matched_line &&
5193 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5194 err = add_matched_line(&width, line, view->ncols - 9, 9,
5195 view->window, view->x, regmatch);
5196 if (err) {
5197 free(line);
5198 return err;
5200 width += 9;
5201 } else {
5202 int skip;
5203 err = format_line(&wline, &width, &skip, line,
5204 view->x, view->ncols - 9, 9, 1);
5205 if (err) {
5206 free(line);
5207 return err;
5209 waddwstr(view->window, &wline[skip]);
5210 width += 9;
5211 free(wline);
5212 wline = NULL;
5215 if (width <= view->ncols - 1)
5216 waddch(view->window, '\n');
5217 if (++nprinted == 1)
5218 s->first_displayed_line = lineno;
5220 free(line);
5221 s->last_displayed_line = lineno;
5223 view_border(view);
5225 return NULL;
5228 static const struct got_error *
5229 blame_cb(void *arg, int nlines, int lineno,
5230 struct got_commit_object *commit, struct got_object_id *id)
5232 const struct got_error *err = NULL;
5233 struct tog_blame_cb_args *a = arg;
5234 struct tog_blame_line *line;
5235 int errcode;
5237 if (nlines != a->nlines ||
5238 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5239 return got_error(GOT_ERR_RANGE);
5241 errcode = pthread_mutex_lock(&tog_mutex);
5242 if (errcode)
5243 return got_error_set_errno(errcode, "pthread_mutex_lock");
5245 if (*a->quit) { /* user has quit the blame view */
5246 err = got_error(GOT_ERR_ITER_COMPLETED);
5247 goto done;
5250 if (lineno == -1)
5251 goto done; /* no change in this commit */
5253 line = &a->lines[lineno - 1];
5254 if (line->annotated)
5255 goto done;
5257 line->id = got_object_id_dup(id);
5258 if (line->id == NULL) {
5259 err = got_error_from_errno("got_object_id_dup");
5260 goto done;
5262 line->annotated = 1;
5263 done:
5264 errcode = pthread_mutex_unlock(&tog_mutex);
5265 if (errcode)
5266 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5267 return err;
5270 static void *
5271 blame_thread(void *arg)
5273 const struct got_error *err, *close_err;
5274 struct tog_blame_thread_args *ta = arg;
5275 struct tog_blame_cb_args *a = ta->cb_args;
5276 int errcode, fd1 = -1, fd2 = -1;
5277 FILE *f1 = NULL, *f2 = NULL;
5279 fd1 = got_opentempfd();
5280 if (fd1 == -1)
5281 return (void *)got_error_from_errno("got_opentempfd");
5283 fd2 = got_opentempfd();
5284 if (fd2 == -1) {
5285 err = got_error_from_errno("got_opentempfd");
5286 goto done;
5289 f1 = got_opentemp();
5290 if (f1 == NULL) {
5291 err = (void *)got_error_from_errno("got_opentemp");
5292 goto done;
5294 f2 = got_opentemp();
5295 if (f2 == NULL) {
5296 err = (void *)got_error_from_errno("got_opentemp");
5297 goto done;
5300 err = block_signals_used_by_main_thread();
5301 if (err)
5302 goto done;
5304 err = got_blame(ta->path, a->commit_id, ta->repo,
5305 tog_diff_algo, blame_cb, ta->cb_args,
5306 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5307 if (err && err->code == GOT_ERR_CANCELLED)
5308 err = NULL;
5310 errcode = pthread_mutex_lock(&tog_mutex);
5311 if (errcode) {
5312 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5313 goto done;
5316 close_err = got_repo_close(ta->repo);
5317 if (err == NULL)
5318 err = close_err;
5319 ta->repo = NULL;
5320 *ta->complete = 1;
5322 errcode = pthread_mutex_unlock(&tog_mutex);
5323 if (errcode && err == NULL)
5324 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5326 done:
5327 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5328 err = got_error_from_errno("close");
5329 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5330 err = got_error_from_errno("close");
5331 if (f1 && fclose(f1) == EOF && err == NULL)
5332 err = got_error_from_errno("fclose");
5333 if (f2 && fclose(f2) == EOF && err == NULL)
5334 err = got_error_from_errno("fclose");
5336 return (void *)err;
5339 static struct got_object_id *
5340 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5341 int first_displayed_line, int selected_line)
5343 struct tog_blame_line *line;
5345 if (nlines <= 0)
5346 return NULL;
5348 line = &lines[first_displayed_line - 1 + selected_line - 1];
5349 if (!line->annotated)
5350 return NULL;
5352 return line->id;
5355 static struct got_object_id *
5356 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5357 int lineno)
5359 struct tog_blame_line *line;
5361 if (nlines <= 0 || lineno >= nlines)
5362 return NULL;
5364 line = &lines[lineno - 1];
5365 if (!line->annotated)
5366 return NULL;
5368 return line->id;
5371 static const struct got_error *
5372 stop_blame(struct tog_blame *blame)
5374 const struct got_error *err = NULL;
5375 int i;
5377 if (blame->thread) {
5378 int errcode;
5379 errcode = pthread_mutex_unlock(&tog_mutex);
5380 if (errcode)
5381 return got_error_set_errno(errcode,
5382 "pthread_mutex_unlock");
5383 errcode = pthread_join(blame->thread, (void **)&err);
5384 if (errcode)
5385 return got_error_set_errno(errcode, "pthread_join");
5386 errcode = pthread_mutex_lock(&tog_mutex);
5387 if (errcode)
5388 return got_error_set_errno(errcode,
5389 "pthread_mutex_lock");
5390 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5391 err = NULL;
5392 blame->thread = 0; //NULL;
5394 if (blame->thread_args.repo) {
5395 const struct got_error *close_err;
5396 close_err = got_repo_close(blame->thread_args.repo);
5397 if (err == NULL)
5398 err = close_err;
5399 blame->thread_args.repo = NULL;
5401 if (blame->f) {
5402 if (fclose(blame->f) == EOF && err == NULL)
5403 err = got_error_from_errno("fclose");
5404 blame->f = NULL;
5406 if (blame->lines) {
5407 for (i = 0; i < blame->nlines; i++)
5408 free(blame->lines[i].id);
5409 free(blame->lines);
5410 blame->lines = NULL;
5412 free(blame->cb_args.commit_id);
5413 blame->cb_args.commit_id = NULL;
5414 if (blame->pack_fds) {
5415 const struct got_error *pack_err =
5416 got_repo_pack_fds_close(blame->pack_fds);
5417 if (err == NULL)
5418 err = pack_err;
5419 blame->pack_fds = NULL;
5421 return err;
5424 static const struct got_error *
5425 cancel_blame_view(void *arg)
5427 const struct got_error *err = NULL;
5428 int *done = arg;
5429 int errcode;
5431 errcode = pthread_mutex_lock(&tog_mutex);
5432 if (errcode)
5433 return got_error_set_errno(errcode,
5434 "pthread_mutex_unlock");
5436 if (*done)
5437 err = got_error(GOT_ERR_CANCELLED);
5439 errcode = pthread_mutex_unlock(&tog_mutex);
5440 if (errcode)
5441 return got_error_set_errno(errcode,
5442 "pthread_mutex_lock");
5444 return err;
5447 static const struct got_error *
5448 run_blame(struct tog_view *view)
5450 struct tog_blame_view_state *s = &view->state.blame;
5451 struct tog_blame *blame = &s->blame;
5452 const struct got_error *err = NULL;
5453 struct got_commit_object *commit = NULL;
5454 struct got_blob_object *blob = NULL;
5455 struct got_repository *thread_repo = NULL;
5456 struct got_object_id *obj_id = NULL;
5457 int obj_type, fd = -1;
5458 int *pack_fds = NULL;
5460 err = got_object_open_as_commit(&commit, s->repo,
5461 &s->blamed_commit->id);
5462 if (err)
5463 return err;
5465 fd = got_opentempfd();
5466 if (fd == -1) {
5467 err = got_error_from_errno("got_opentempfd");
5468 goto done;
5471 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5472 if (err)
5473 goto done;
5475 err = got_object_get_type(&obj_type, s->repo, obj_id);
5476 if (err)
5477 goto done;
5479 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5480 err = got_error(GOT_ERR_OBJ_TYPE);
5481 goto done;
5484 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5485 if (err)
5486 goto done;
5487 blame->f = got_opentemp();
5488 if (blame->f == NULL) {
5489 err = got_error_from_errno("got_opentemp");
5490 goto done;
5492 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5493 &blame->line_offsets, blame->f, blob);
5494 if (err)
5495 goto done;
5496 if (blame->nlines == 0) {
5497 s->blame_complete = 1;
5498 goto done;
5501 /* Don't include \n at EOF in the blame line count. */
5502 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5503 blame->nlines--;
5505 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5506 if (blame->lines == NULL) {
5507 err = got_error_from_errno("calloc");
5508 goto done;
5511 err = got_repo_pack_fds_open(&pack_fds);
5512 if (err)
5513 goto done;
5514 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5515 pack_fds);
5516 if (err)
5517 goto done;
5519 blame->pack_fds = pack_fds;
5520 blame->cb_args.view = view;
5521 blame->cb_args.lines = blame->lines;
5522 blame->cb_args.nlines = blame->nlines;
5523 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5524 if (blame->cb_args.commit_id == NULL) {
5525 err = got_error_from_errno("got_object_id_dup");
5526 goto done;
5528 blame->cb_args.quit = &s->done;
5530 blame->thread_args.path = s->path;
5531 blame->thread_args.repo = thread_repo;
5532 blame->thread_args.cb_args = &blame->cb_args;
5533 blame->thread_args.complete = &s->blame_complete;
5534 blame->thread_args.cancel_cb = cancel_blame_view;
5535 blame->thread_args.cancel_arg = &s->done;
5536 s->blame_complete = 0;
5538 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5539 s->first_displayed_line = 1;
5540 s->last_displayed_line = view->nlines;
5541 s->selected_line = 1;
5543 s->matched_line = 0;
5545 done:
5546 if (commit)
5547 got_object_commit_close(commit);
5548 if (fd != -1 && close(fd) == -1 && err == NULL)
5549 err = got_error_from_errno("close");
5550 if (blob)
5551 got_object_blob_close(blob);
5552 free(obj_id);
5553 if (err)
5554 stop_blame(blame);
5555 return err;
5558 static const struct got_error *
5559 open_blame_view(struct tog_view *view, char *path,
5560 struct got_object_id *commit_id, struct got_repository *repo)
5562 const struct got_error *err = NULL;
5563 struct tog_blame_view_state *s = &view->state.blame;
5565 STAILQ_INIT(&s->blamed_commits);
5567 s->path = strdup(path);
5568 if (s->path == NULL)
5569 return got_error_from_errno("strdup");
5571 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5572 if (err) {
5573 free(s->path);
5574 return err;
5577 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5578 s->first_displayed_line = 1;
5579 s->last_displayed_line = view->nlines;
5580 s->selected_line = 1;
5581 s->blame_complete = 0;
5582 s->repo = repo;
5583 s->commit_id = commit_id;
5584 memset(&s->blame, 0, sizeof(s->blame));
5586 STAILQ_INIT(&s->colors);
5587 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5588 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5589 get_color_value("TOG_COLOR_COMMIT"));
5590 if (err)
5591 return err;
5594 view->show = show_blame_view;
5595 view->input = input_blame_view;
5596 view->reset = reset_blame_view;
5597 view->close = close_blame_view;
5598 view->search_start = search_start_blame_view;
5599 view->search_next = search_next_blame_view;
5601 return run_blame(view);
5604 static const struct got_error *
5605 close_blame_view(struct tog_view *view)
5607 const struct got_error *err = NULL;
5608 struct tog_blame_view_state *s = &view->state.blame;
5610 if (s->blame.thread)
5611 err = stop_blame(&s->blame);
5613 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5614 struct got_object_qid *blamed_commit;
5615 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5616 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5617 got_object_qid_free(blamed_commit);
5620 free(s->path);
5621 free_colors(&s->colors);
5622 return err;
5625 static const struct got_error *
5626 search_start_blame_view(struct tog_view *view)
5628 struct tog_blame_view_state *s = &view->state.blame;
5630 s->matched_line = 0;
5631 return NULL;
5634 static const struct got_error *
5635 search_next_blame_view(struct tog_view *view)
5637 struct tog_blame_view_state *s = &view->state.blame;
5638 const struct got_error *err = NULL;
5639 int lineno;
5640 char *line = NULL;
5641 size_t linesize = 0;
5642 ssize_t linelen;
5644 if (!view->searching) {
5645 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5646 return NULL;
5649 if (s->matched_line) {
5650 if (view->searching == TOG_SEARCH_FORWARD)
5651 lineno = s->matched_line + 1;
5652 else
5653 lineno = s->matched_line - 1;
5654 } else
5655 lineno = s->first_displayed_line - 1 + s->selected_line;
5657 while (1) {
5658 off_t offset;
5660 if (lineno <= 0 || lineno > s->blame.nlines) {
5661 if (s->matched_line == 0) {
5662 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5663 break;
5666 if (view->searching == TOG_SEARCH_FORWARD)
5667 lineno = 1;
5668 else
5669 lineno = s->blame.nlines;
5672 offset = s->blame.line_offsets[lineno - 1];
5673 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5674 free(line);
5675 return got_error_from_errno("fseeko");
5677 linelen = getline(&line, &linesize, s->blame.f);
5678 if (linelen != -1) {
5679 char *exstr;
5680 err = expand_tab(&exstr, line);
5681 if (err)
5682 break;
5683 if (match_line(exstr, &view->regex, 1,
5684 &view->regmatch)) {
5685 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5686 s->matched_line = lineno;
5687 free(exstr);
5688 break;
5690 free(exstr);
5692 if (view->searching == TOG_SEARCH_FORWARD)
5693 lineno++;
5694 else
5695 lineno--;
5697 free(line);
5699 if (s->matched_line) {
5700 s->first_displayed_line = s->matched_line;
5701 s->selected_line = 1;
5704 return err;
5707 static const struct got_error *
5708 show_blame_view(struct tog_view *view)
5710 const struct got_error *err = NULL;
5711 struct tog_blame_view_state *s = &view->state.blame;
5712 int errcode;
5714 if (s->blame.thread == 0 && !s->blame_complete) {
5715 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5716 &s->blame.thread_args);
5717 if (errcode)
5718 return got_error_set_errno(errcode, "pthread_create");
5720 halfdelay(1); /* fast refresh while annotating */
5723 if (s->blame_complete)
5724 halfdelay(10); /* disable fast refresh */
5726 err = draw_blame(view);
5728 view_border(view);
5729 return err;
5732 static const struct got_error *
5733 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5735 const struct got_error *err = NULL, *thread_err = NULL;
5736 struct tog_view *diff_view;
5737 struct tog_blame_view_state *s = &view->state.blame;
5738 int eos, nscroll, begin_y = 0, begin_x = 0;
5740 eos = nscroll = view->nlines - 2;
5741 if (view_is_hsplit_top(view))
5742 --eos; /* border */
5744 switch (ch) {
5745 case '0':
5746 view->x = 0;
5747 break;
5748 case '$':
5749 view->x = MAX(view->maxx - view->ncols / 3, 0);
5750 view->count = 0;
5751 break;
5752 case KEY_RIGHT:
5753 case 'l':
5754 if (view->x + view->ncols / 3 < view->maxx)
5755 view->x += 2; /* move two columns right */
5756 else
5757 view->count = 0;
5758 break;
5759 case KEY_LEFT:
5760 case 'h':
5761 view->x -= MIN(view->x, 2); /* move two columns back */
5762 if (view->x <= 0)
5763 view->count = 0;
5764 break;
5765 case 'q':
5766 s->done = 1;
5767 break;
5768 case 'g':
5769 case KEY_HOME:
5770 s->selected_line = 1;
5771 s->first_displayed_line = 1;
5772 view->count = 0;
5773 break;
5774 case 'G':
5775 case KEY_END:
5776 if (s->blame.nlines < eos) {
5777 s->selected_line = s->blame.nlines;
5778 s->first_displayed_line = 1;
5779 } else {
5780 s->selected_line = eos;
5781 s->first_displayed_line = s->blame.nlines - (eos - 1);
5783 view->count = 0;
5784 break;
5785 case 'k':
5786 case KEY_UP:
5787 case CTRL('p'):
5788 if (s->selected_line > 1)
5789 s->selected_line--;
5790 else if (s->selected_line == 1 &&
5791 s->first_displayed_line > 1)
5792 s->first_displayed_line--;
5793 else
5794 view->count = 0;
5795 break;
5796 case CTRL('u'):
5797 case 'u':
5798 nscroll /= 2;
5799 /* FALL THROUGH */
5800 case KEY_PPAGE:
5801 case CTRL('b'):
5802 case 'b':
5803 if (s->first_displayed_line == 1) {
5804 if (view->count > 1)
5805 nscroll += nscroll;
5806 s->selected_line = MAX(1, s->selected_line - nscroll);
5807 view->count = 0;
5808 break;
5810 if (s->first_displayed_line > nscroll)
5811 s->first_displayed_line -= nscroll;
5812 else
5813 s->first_displayed_line = 1;
5814 break;
5815 case 'j':
5816 case KEY_DOWN:
5817 case CTRL('n'):
5818 if (s->selected_line < eos && s->first_displayed_line +
5819 s->selected_line <= s->blame.nlines)
5820 s->selected_line++;
5821 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5822 s->first_displayed_line++;
5823 else
5824 view->count = 0;
5825 break;
5826 case 'c':
5827 case 'p': {
5828 struct got_object_id *id = NULL;
5830 view->count = 0;
5831 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5832 s->first_displayed_line, s->selected_line);
5833 if (id == NULL)
5834 break;
5835 if (ch == 'p') {
5836 struct got_commit_object *commit, *pcommit;
5837 struct got_object_qid *pid;
5838 struct got_object_id *blob_id = NULL;
5839 int obj_type;
5840 err = got_object_open_as_commit(&commit,
5841 s->repo, id);
5842 if (err)
5843 break;
5844 pid = STAILQ_FIRST(
5845 got_object_commit_get_parent_ids(commit));
5846 if (pid == NULL) {
5847 got_object_commit_close(commit);
5848 break;
5850 /* Check if path history ends here. */
5851 err = got_object_open_as_commit(&pcommit,
5852 s->repo, &pid->id);
5853 if (err)
5854 break;
5855 err = got_object_id_by_path(&blob_id, s->repo,
5856 pcommit, s->path);
5857 got_object_commit_close(pcommit);
5858 if (err) {
5859 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5860 err = NULL;
5861 got_object_commit_close(commit);
5862 break;
5864 err = got_object_get_type(&obj_type, s->repo,
5865 blob_id);
5866 free(blob_id);
5867 /* Can't blame non-blob type objects. */
5868 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5869 got_object_commit_close(commit);
5870 break;
5872 err = got_object_qid_alloc(&s->blamed_commit,
5873 &pid->id);
5874 got_object_commit_close(commit);
5875 } else {
5876 if (got_object_id_cmp(id,
5877 &s->blamed_commit->id) == 0)
5878 break;
5879 err = got_object_qid_alloc(&s->blamed_commit,
5880 id);
5882 if (err)
5883 break;
5884 s->done = 1;
5885 thread_err = stop_blame(&s->blame);
5886 s->done = 0;
5887 if (thread_err)
5888 break;
5889 STAILQ_INSERT_HEAD(&s->blamed_commits,
5890 s->blamed_commit, entry);
5891 err = run_blame(view);
5892 if (err)
5893 break;
5894 break;
5896 case 'C': {
5897 struct got_object_qid *first;
5899 view->count = 0;
5900 first = STAILQ_FIRST(&s->blamed_commits);
5901 if (!got_object_id_cmp(&first->id, s->commit_id))
5902 break;
5903 s->done = 1;
5904 thread_err = stop_blame(&s->blame);
5905 s->done = 0;
5906 if (thread_err)
5907 break;
5908 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5909 got_object_qid_free(s->blamed_commit);
5910 s->blamed_commit =
5911 STAILQ_FIRST(&s->blamed_commits);
5912 err = run_blame(view);
5913 if (err)
5914 break;
5915 break;
5917 case KEY_ENTER:
5918 case '\r': {
5919 struct got_object_id *id = NULL;
5920 struct got_object_qid *pid;
5921 struct got_commit_object *commit = NULL;
5923 view->count = 0;
5924 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5925 s->first_displayed_line, s->selected_line);
5926 if (id == NULL)
5927 break;
5928 err = got_object_open_as_commit(&commit, s->repo, id);
5929 if (err)
5930 break;
5931 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5932 if (*new_view) {
5933 /* traversed from diff view, release diff resources */
5934 err = close_diff_view(*new_view);
5935 if (err)
5936 break;
5937 diff_view = *new_view;
5938 } else {
5939 if (view_is_parent_view(view))
5940 view_get_split(view, &begin_y, &begin_x);
5942 diff_view = view_open(0, 0, begin_y, begin_x,
5943 TOG_VIEW_DIFF);
5944 if (diff_view == NULL) {
5945 got_object_commit_close(commit);
5946 err = got_error_from_errno("view_open");
5947 break;
5950 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5951 id, NULL, NULL, 3, 0, 0, view, s->repo);
5952 got_object_commit_close(commit);
5953 if (err) {
5954 view_close(diff_view);
5955 break;
5957 s->last_diffed_line = s->first_displayed_line - 1 +
5958 s->selected_line;
5959 if (*new_view)
5960 break; /* still open from active diff view */
5961 if (view_is_parent_view(view) &&
5962 view->mode == TOG_VIEW_SPLIT_HRZN) {
5963 err = view_init_hsplit(view, begin_y);
5964 if (err)
5965 break;
5968 view->focussed = 0;
5969 diff_view->focussed = 1;
5970 diff_view->mode = view->mode;
5971 diff_view->nlines = view->lines - begin_y;
5972 if (view_is_parent_view(view)) {
5973 view_transfer_size(diff_view, view);
5974 err = view_close_child(view);
5975 if (err)
5976 break;
5977 err = view_set_child(view, diff_view);
5978 if (err)
5979 break;
5980 view->focus_child = 1;
5981 } else
5982 *new_view = diff_view;
5983 if (err)
5984 break;
5985 break;
5987 case CTRL('d'):
5988 case 'd':
5989 nscroll /= 2;
5990 /* FALL THROUGH */
5991 case KEY_NPAGE:
5992 case CTRL('f'):
5993 case 'f':
5994 case ' ':
5995 if (s->last_displayed_line >= s->blame.nlines &&
5996 s->selected_line >= MIN(s->blame.nlines,
5997 view->nlines - 2)) {
5998 view->count = 0;
5999 break;
6001 if (s->last_displayed_line >= s->blame.nlines &&
6002 s->selected_line < view->nlines - 2) {
6003 s->selected_line +=
6004 MIN(nscroll, s->last_displayed_line -
6005 s->first_displayed_line - s->selected_line + 1);
6007 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6008 s->first_displayed_line += nscroll;
6009 else
6010 s->first_displayed_line =
6011 s->blame.nlines - (view->nlines - 3);
6012 break;
6013 case KEY_RESIZE:
6014 if (s->selected_line > view->nlines - 2) {
6015 s->selected_line = MIN(s->blame.nlines,
6016 view->nlines - 2);
6018 break;
6019 default:
6020 view->count = 0;
6021 break;
6023 return thread_err ? thread_err : err;
6026 static const struct got_error *
6027 reset_blame_view(struct tog_view *view)
6029 const struct got_error *err;
6030 struct tog_blame_view_state *s = &view->state.blame;
6032 view->count = 0;
6033 s->done = 1;
6034 err = stop_blame(&s->blame);
6035 s->done = 0;
6036 if (err)
6037 return err;
6038 return run_blame(view);
6041 static const struct got_error *
6042 cmd_blame(int argc, char *argv[])
6044 const struct got_error *error;
6045 struct got_repository *repo = NULL;
6046 struct got_worktree *worktree = NULL;
6047 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6048 char *link_target = NULL;
6049 struct got_object_id *commit_id = NULL;
6050 struct got_commit_object *commit = NULL;
6051 char *commit_id_str = NULL;
6052 int ch;
6053 struct tog_view *view;
6054 int *pack_fds = NULL;
6056 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6057 switch (ch) {
6058 case 'c':
6059 commit_id_str = optarg;
6060 break;
6061 case 'r':
6062 repo_path = realpath(optarg, NULL);
6063 if (repo_path == NULL)
6064 return got_error_from_errno2("realpath",
6065 optarg);
6066 break;
6067 default:
6068 usage_blame();
6069 /* NOTREACHED */
6073 argc -= optind;
6074 argv += optind;
6076 if (argc != 1)
6077 usage_blame();
6079 error = got_repo_pack_fds_open(&pack_fds);
6080 if (error != NULL)
6081 goto done;
6083 if (repo_path == NULL) {
6084 cwd = getcwd(NULL, 0);
6085 if (cwd == NULL)
6086 return got_error_from_errno("getcwd");
6087 error = got_worktree_open(&worktree, cwd);
6088 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6089 goto done;
6090 if (worktree)
6091 repo_path =
6092 strdup(got_worktree_get_repo_path(worktree));
6093 else
6094 repo_path = strdup(cwd);
6095 if (repo_path == NULL) {
6096 error = got_error_from_errno("strdup");
6097 goto done;
6101 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6102 if (error != NULL)
6103 goto done;
6105 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6106 worktree);
6107 if (error)
6108 goto done;
6110 init_curses();
6112 error = apply_unveil(got_repo_get_path(repo), NULL);
6113 if (error)
6114 goto done;
6116 error = tog_load_refs(repo, 0);
6117 if (error)
6118 goto done;
6120 if (commit_id_str == NULL) {
6121 struct got_reference *head_ref;
6122 error = got_ref_open(&head_ref, repo, worktree ?
6123 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6124 if (error != NULL)
6125 goto done;
6126 error = got_ref_resolve(&commit_id, repo, head_ref);
6127 got_ref_close(head_ref);
6128 } else {
6129 error = got_repo_match_object_id(&commit_id, NULL,
6130 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6132 if (error != NULL)
6133 goto done;
6135 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6136 if (view == NULL) {
6137 error = got_error_from_errno("view_open");
6138 goto done;
6141 error = got_object_open_as_commit(&commit, repo, commit_id);
6142 if (error)
6143 goto done;
6145 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6146 commit, repo);
6147 if (error)
6148 goto done;
6150 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6151 commit_id, repo);
6152 if (error)
6153 goto done;
6154 if (worktree) {
6155 /* Release work tree lock. */
6156 got_worktree_close(worktree);
6157 worktree = NULL;
6159 error = view_loop(view);
6160 done:
6161 free(repo_path);
6162 free(in_repo_path);
6163 free(link_target);
6164 free(cwd);
6165 free(commit_id);
6166 if (commit)
6167 got_object_commit_close(commit);
6168 if (worktree)
6169 got_worktree_close(worktree);
6170 if (repo) {
6171 const struct got_error *close_err = got_repo_close(repo);
6172 if (error == NULL)
6173 error = close_err;
6175 if (pack_fds) {
6176 const struct got_error *pack_err =
6177 got_repo_pack_fds_close(pack_fds);
6178 if (error == NULL)
6179 error = pack_err;
6181 tog_free_refs();
6182 return error;
6185 static const struct got_error *
6186 draw_tree_entries(struct tog_view *view, const char *parent_path)
6188 struct tog_tree_view_state *s = &view->state.tree;
6189 const struct got_error *err = NULL;
6190 struct got_tree_entry *te;
6191 wchar_t *wline;
6192 struct tog_color *tc;
6193 int width, n, i, nentries;
6194 int limit = view->nlines;
6196 s->ndisplayed = 0;
6197 if (view_is_hsplit_top(view))
6198 --limit; /* border */
6200 werase(view->window);
6202 if (limit == 0)
6203 return NULL;
6205 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6206 0, 0);
6207 if (err)
6208 return err;
6209 if (view_needs_focus_indication(view))
6210 wstandout(view->window);
6211 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6212 if (tc)
6213 wattr_on(view->window,
6214 COLOR_PAIR(tc->colorpair), NULL);
6215 waddwstr(view->window, wline);
6216 if (tc)
6217 wattr_off(view->window,
6218 COLOR_PAIR(tc->colorpair), NULL);
6219 if (view_needs_focus_indication(view))
6220 wstandend(view->window);
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 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6228 0, 0);
6229 if (err)
6230 return err;
6231 waddwstr(view->window, wline);
6232 free(wline);
6233 wline = NULL;
6234 if (width < view->ncols - 1)
6235 waddch(view->window, '\n');
6236 if (--limit <= 0)
6237 return NULL;
6238 waddch(view->window, '\n');
6239 if (--limit <= 0)
6240 return NULL;
6242 if (s->first_displayed_entry == NULL) {
6243 te = got_object_tree_get_first_entry(s->tree);
6244 if (s->selected == 0) {
6245 if (view->focussed)
6246 wstandout(view->window);
6247 s->selected_entry = NULL;
6249 waddstr(view->window, " ..\n"); /* parent directory */
6250 if (s->selected == 0 && view->focussed)
6251 wstandend(view->window);
6252 s->ndisplayed++;
6253 if (--limit <= 0)
6254 return NULL;
6255 n = 1;
6256 } else {
6257 n = 0;
6258 te = s->first_displayed_entry;
6261 nentries = got_object_tree_get_nentries(s->tree);
6262 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6263 char *line = NULL, *id_str = NULL, *link_target = NULL;
6264 const char *modestr = "";
6265 mode_t mode;
6267 te = got_object_tree_get_entry(s->tree, i);
6268 mode = got_tree_entry_get_mode(te);
6270 if (s->show_ids) {
6271 err = got_object_id_str(&id_str,
6272 got_tree_entry_get_id(te));
6273 if (err)
6274 return got_error_from_errno(
6275 "got_object_id_str");
6277 if (got_object_tree_entry_is_submodule(te))
6278 modestr = "$";
6279 else if (S_ISLNK(mode)) {
6280 int i;
6282 err = got_tree_entry_get_symlink_target(&link_target,
6283 te, s->repo);
6284 if (err) {
6285 free(id_str);
6286 return err;
6288 for (i = 0; i < strlen(link_target); i++) {
6289 if (!isprint((unsigned char)link_target[i]))
6290 link_target[i] = '?';
6292 modestr = "@";
6294 else if (S_ISDIR(mode))
6295 modestr = "/";
6296 else if (mode & S_IXUSR)
6297 modestr = "*";
6298 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6299 got_tree_entry_get_name(te), modestr,
6300 link_target ? " -> ": "",
6301 link_target ? link_target : "") == -1) {
6302 free(id_str);
6303 free(link_target);
6304 return got_error_from_errno("asprintf");
6306 free(id_str);
6307 free(link_target);
6308 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6309 0, 0);
6310 if (err) {
6311 free(line);
6312 break;
6314 if (n == s->selected) {
6315 if (view->focussed)
6316 wstandout(view->window);
6317 s->selected_entry = te;
6319 tc = match_color(&s->colors, line);
6320 if (tc)
6321 wattr_on(view->window,
6322 COLOR_PAIR(tc->colorpair), NULL);
6323 waddwstr(view->window, wline);
6324 if (tc)
6325 wattr_off(view->window,
6326 COLOR_PAIR(tc->colorpair), NULL);
6327 if (width < view->ncols - 1)
6328 waddch(view->window, '\n');
6329 if (n == s->selected && view->focussed)
6330 wstandend(view->window);
6331 free(line);
6332 free(wline);
6333 wline = NULL;
6334 n++;
6335 s->ndisplayed++;
6336 s->last_displayed_entry = te;
6337 if (--limit <= 0)
6338 break;
6341 return err;
6344 static void
6345 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6347 struct got_tree_entry *te;
6348 int isroot = s->tree == s->root;
6349 int i = 0;
6351 if (s->first_displayed_entry == NULL)
6352 return;
6354 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6355 while (i++ < maxscroll) {
6356 if (te == NULL) {
6357 if (!isroot)
6358 s->first_displayed_entry = NULL;
6359 break;
6361 s->first_displayed_entry = te;
6362 te = got_tree_entry_get_prev(s->tree, te);
6366 static const struct got_error *
6367 tree_scroll_down(struct tog_view *view, int maxscroll)
6369 struct tog_tree_view_state *s = &view->state.tree;
6370 struct got_tree_entry *next, *last;
6371 int n = 0;
6373 if (s->first_displayed_entry)
6374 next = got_tree_entry_get_next(s->tree,
6375 s->first_displayed_entry);
6376 else
6377 next = got_object_tree_get_first_entry(s->tree);
6379 last = s->last_displayed_entry;
6380 while (next && n++ < maxscroll) {
6381 if (last)
6382 last = got_tree_entry_get_next(s->tree, last);
6383 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6384 s->first_displayed_entry = next;
6385 next = got_tree_entry_get_next(s->tree, next);
6389 return NULL;
6392 static const struct got_error *
6393 tree_entry_path(char **path, struct tog_parent_trees *parents,
6394 struct got_tree_entry *te)
6396 const struct got_error *err = NULL;
6397 struct tog_parent_tree *pt;
6398 size_t len = 2; /* for leading slash and NUL */
6400 TAILQ_FOREACH(pt, parents, entry)
6401 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6402 + 1 /* slash */;
6403 if (te)
6404 len += strlen(got_tree_entry_get_name(te));
6406 *path = calloc(1, len);
6407 if (path == NULL)
6408 return got_error_from_errno("calloc");
6410 (*path)[0] = '/';
6411 pt = TAILQ_LAST(parents, tog_parent_trees);
6412 while (pt) {
6413 const char *name = got_tree_entry_get_name(pt->selected_entry);
6414 if (strlcat(*path, name, len) >= len) {
6415 err = got_error(GOT_ERR_NO_SPACE);
6416 goto done;
6418 if (strlcat(*path, "/", len) >= len) {
6419 err = got_error(GOT_ERR_NO_SPACE);
6420 goto done;
6422 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6424 if (te) {
6425 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6426 err = got_error(GOT_ERR_NO_SPACE);
6427 goto done;
6430 done:
6431 if (err) {
6432 free(*path);
6433 *path = NULL;
6435 return err;
6438 static const struct got_error *
6439 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6440 struct got_tree_entry *te, struct tog_parent_trees *parents,
6441 struct got_object_id *commit_id, struct got_repository *repo)
6443 const struct got_error *err = NULL;
6444 char *path;
6445 struct tog_view *blame_view;
6447 *new_view = NULL;
6449 err = tree_entry_path(&path, parents, te);
6450 if (err)
6451 return err;
6453 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6454 if (blame_view == NULL) {
6455 err = got_error_from_errno("view_open");
6456 goto done;
6459 err = open_blame_view(blame_view, path, commit_id, repo);
6460 if (err) {
6461 if (err->code == GOT_ERR_CANCELLED)
6462 err = NULL;
6463 view_close(blame_view);
6464 } else
6465 *new_view = blame_view;
6466 done:
6467 free(path);
6468 return err;
6471 static const struct got_error *
6472 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6473 struct tog_tree_view_state *s)
6475 struct tog_view *log_view;
6476 const struct got_error *err = NULL;
6477 char *path;
6479 *new_view = NULL;
6481 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6482 if (log_view == NULL)
6483 return got_error_from_errno("view_open");
6485 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6486 if (err)
6487 return err;
6489 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6490 path, 0);
6491 if (err)
6492 view_close(log_view);
6493 else
6494 *new_view = log_view;
6495 free(path);
6496 return err;
6499 static const struct got_error *
6500 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6501 const char *head_ref_name, struct got_repository *repo)
6503 const struct got_error *err = NULL;
6504 char *commit_id_str = NULL;
6505 struct tog_tree_view_state *s = &view->state.tree;
6506 struct got_commit_object *commit = NULL;
6508 TAILQ_INIT(&s->parents);
6509 STAILQ_INIT(&s->colors);
6511 s->commit_id = got_object_id_dup(commit_id);
6512 if (s->commit_id == NULL)
6513 return got_error_from_errno("got_object_id_dup");
6515 err = got_object_open_as_commit(&commit, repo, commit_id);
6516 if (err)
6517 goto done;
6520 * The root is opened here and will be closed when the view is closed.
6521 * Any visited subtrees and their path-wise parents are opened and
6522 * closed on demand.
6524 err = got_object_open_as_tree(&s->root, repo,
6525 got_object_commit_get_tree_id(commit));
6526 if (err)
6527 goto done;
6528 s->tree = s->root;
6530 err = got_object_id_str(&commit_id_str, commit_id);
6531 if (err != NULL)
6532 goto done;
6534 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6535 err = got_error_from_errno("asprintf");
6536 goto done;
6539 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6540 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6541 if (head_ref_name) {
6542 s->head_ref_name = strdup(head_ref_name);
6543 if (s->head_ref_name == NULL) {
6544 err = got_error_from_errno("strdup");
6545 goto done;
6548 s->repo = repo;
6550 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6551 err = add_color(&s->colors, "\\$$",
6552 TOG_COLOR_TREE_SUBMODULE,
6553 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6554 if (err)
6555 goto done;
6556 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6557 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6558 if (err)
6559 goto done;
6560 err = add_color(&s->colors, "/$",
6561 TOG_COLOR_TREE_DIRECTORY,
6562 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6563 if (err)
6564 goto done;
6566 err = add_color(&s->colors, "\\*$",
6567 TOG_COLOR_TREE_EXECUTABLE,
6568 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6569 if (err)
6570 goto done;
6572 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6573 get_color_value("TOG_COLOR_COMMIT"));
6574 if (err)
6575 goto done;
6578 view->show = show_tree_view;
6579 view->input = input_tree_view;
6580 view->close = close_tree_view;
6581 view->search_start = search_start_tree_view;
6582 view->search_next = search_next_tree_view;
6583 done:
6584 free(commit_id_str);
6585 if (commit)
6586 got_object_commit_close(commit);
6587 if (err)
6588 close_tree_view(view);
6589 return err;
6592 static const struct got_error *
6593 close_tree_view(struct tog_view *view)
6595 struct tog_tree_view_state *s = &view->state.tree;
6597 free_colors(&s->colors);
6598 free(s->tree_label);
6599 s->tree_label = NULL;
6600 free(s->commit_id);
6601 s->commit_id = NULL;
6602 free(s->head_ref_name);
6603 s->head_ref_name = NULL;
6604 while (!TAILQ_EMPTY(&s->parents)) {
6605 struct tog_parent_tree *parent;
6606 parent = TAILQ_FIRST(&s->parents);
6607 TAILQ_REMOVE(&s->parents, parent, entry);
6608 if (parent->tree != s->root)
6609 got_object_tree_close(parent->tree);
6610 free(parent);
6613 if (s->tree != NULL && s->tree != s->root)
6614 got_object_tree_close(s->tree);
6615 if (s->root)
6616 got_object_tree_close(s->root);
6617 return NULL;
6620 static const struct got_error *
6621 search_start_tree_view(struct tog_view *view)
6623 struct tog_tree_view_state *s = &view->state.tree;
6625 s->matched_entry = NULL;
6626 return NULL;
6629 static int
6630 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6632 regmatch_t regmatch;
6634 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6635 0) == 0;
6638 static const struct got_error *
6639 search_next_tree_view(struct tog_view *view)
6641 struct tog_tree_view_state *s = &view->state.tree;
6642 struct got_tree_entry *te = NULL;
6644 if (!view->searching) {
6645 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6646 return NULL;
6649 if (s->matched_entry) {
6650 if (view->searching == TOG_SEARCH_FORWARD) {
6651 if (s->selected_entry)
6652 te = got_tree_entry_get_next(s->tree,
6653 s->selected_entry);
6654 else
6655 te = got_object_tree_get_first_entry(s->tree);
6656 } else {
6657 if (s->selected_entry == NULL)
6658 te = got_object_tree_get_last_entry(s->tree);
6659 else
6660 te = got_tree_entry_get_prev(s->tree,
6661 s->selected_entry);
6663 } else {
6664 if (s->selected_entry)
6665 te = s->selected_entry;
6666 else if (view->searching == TOG_SEARCH_FORWARD)
6667 te = got_object_tree_get_first_entry(s->tree);
6668 else
6669 te = got_object_tree_get_last_entry(s->tree);
6672 while (1) {
6673 if (te == NULL) {
6674 if (s->matched_entry == NULL) {
6675 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6676 return NULL;
6678 if (view->searching == TOG_SEARCH_FORWARD)
6679 te = got_object_tree_get_first_entry(s->tree);
6680 else
6681 te = got_object_tree_get_last_entry(s->tree);
6684 if (match_tree_entry(te, &view->regex)) {
6685 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6686 s->matched_entry = te;
6687 break;
6690 if (view->searching == TOG_SEARCH_FORWARD)
6691 te = got_tree_entry_get_next(s->tree, te);
6692 else
6693 te = got_tree_entry_get_prev(s->tree, te);
6696 if (s->matched_entry) {
6697 s->first_displayed_entry = s->matched_entry;
6698 s->selected = 0;
6701 return NULL;
6704 static const struct got_error *
6705 show_tree_view(struct tog_view *view)
6707 const struct got_error *err = NULL;
6708 struct tog_tree_view_state *s = &view->state.tree;
6709 char *parent_path;
6711 err = tree_entry_path(&parent_path, &s->parents, NULL);
6712 if (err)
6713 return err;
6715 err = draw_tree_entries(view, parent_path);
6716 free(parent_path);
6718 view_border(view);
6719 return err;
6722 static const struct got_error *
6723 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6725 const struct got_error *err = NULL;
6726 struct tog_tree_view_state *s = &view->state.tree;
6727 struct tog_view *log_view, *ref_view;
6728 struct got_tree_entry *te;
6729 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 3;
6731 switch (ch) {
6732 case 'i':
6733 s->show_ids = !s->show_ids;
6734 view->count = 0;
6735 break;
6736 case 'l':
6737 view->count = 0;
6738 if (!s->selected_entry)
6739 break;
6740 if (view_is_parent_view(view))
6741 view_get_split(view, &begin_y, &begin_x);
6742 err = log_selected_tree_entry(&log_view, begin_y, begin_x, s);
6743 if (view_is_parent_view(view) &&
6744 view->mode == TOG_VIEW_SPLIT_HRZN) {
6745 err = view_init_hsplit(view, begin_y);
6746 if (err)
6747 break;
6749 view->focussed = 0;
6750 log_view->focussed = 1;
6751 log_view->mode = view->mode;
6752 log_view->nlines = view->lines - begin_y;
6753 if (view_is_parent_view(view)) {
6754 view_transfer_size(log_view, view);
6755 err = view_close_child(view);
6756 if (err)
6757 return err;
6758 err = view_set_child(view, log_view);
6759 if (err)
6760 return err;
6761 view->focus_child = 1;
6762 } else
6763 *new_view = log_view;
6764 break;
6765 case 'r':
6766 view->count = 0;
6767 if (view_is_parent_view(view))
6768 view_get_split(view, &begin_y, &begin_x);
6769 ref_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_REF);
6770 if (ref_view == NULL)
6771 return got_error_from_errno("view_open");
6772 err = open_ref_view(ref_view, s->repo);
6773 if (err) {
6774 view_close(ref_view);
6775 return err;
6777 if (view_is_parent_view(view) &&
6778 view->mode == TOG_VIEW_SPLIT_HRZN) {
6779 err = view_init_hsplit(view, begin_y);
6780 if (err)
6781 break;
6783 view->focussed = 0;
6784 ref_view->focussed = 1;
6785 ref_view->mode = view->mode;
6786 ref_view->nlines = view->lines - begin_y;
6787 if (view_is_parent_view(view)) {
6788 view_transfer_size(ref_view, view);
6789 err = view_close_child(view);
6790 if (err)
6791 return err;
6792 err = view_set_child(view, ref_view);
6793 if (err)
6794 return err;
6795 view->focus_child = 1;
6796 } else
6797 *new_view = ref_view;
6798 break;
6799 case 'g':
6800 case KEY_HOME:
6801 s->selected = 0;
6802 view->count = 0;
6803 if (s->tree == s->root)
6804 s->first_displayed_entry =
6805 got_object_tree_get_first_entry(s->tree);
6806 else
6807 s->first_displayed_entry = NULL;
6808 break;
6809 case 'G':
6810 case KEY_END: {
6811 int eos = view->nlines - 3;
6813 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6814 --eos; /* border */
6815 s->selected = 0;
6816 view->count = 0;
6817 te = got_object_tree_get_last_entry(s->tree);
6818 for (n = 0; n < eos; n++) {
6819 if (te == NULL) {
6820 if (s->tree != s->root) {
6821 s->first_displayed_entry = NULL;
6822 n++;
6824 break;
6826 s->first_displayed_entry = te;
6827 te = got_tree_entry_get_prev(s->tree, te);
6829 if (n > 0)
6830 s->selected = n - 1;
6831 break;
6833 case 'k':
6834 case KEY_UP:
6835 case CTRL('p'):
6836 if (s->selected > 0) {
6837 s->selected--;
6838 break;
6840 tree_scroll_up(s, 1);
6841 if (s->selected_entry == NULL ||
6842 (s->tree == s->root && s->selected_entry ==
6843 got_object_tree_get_first_entry(s->tree)))
6844 view->count = 0;
6845 break;
6846 case CTRL('u'):
6847 case 'u':
6848 nscroll /= 2;
6849 /* FALL THROUGH */
6850 case KEY_PPAGE:
6851 case CTRL('b'):
6852 case 'b':
6853 if (s->tree == s->root) {
6854 if (got_object_tree_get_first_entry(s->tree) ==
6855 s->first_displayed_entry)
6856 s->selected -= MIN(s->selected, nscroll);
6857 } else {
6858 if (s->first_displayed_entry == NULL)
6859 s->selected -= MIN(s->selected, nscroll);
6861 tree_scroll_up(s, MAX(0, nscroll));
6862 if (s->selected_entry == NULL ||
6863 (s->tree == s->root && s->selected_entry ==
6864 got_object_tree_get_first_entry(s->tree)))
6865 view->count = 0;
6866 break;
6867 case 'j':
6868 case KEY_DOWN:
6869 case CTRL('n'):
6870 if (s->selected < s->ndisplayed - 1) {
6871 s->selected++;
6872 break;
6874 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6875 == NULL) {
6876 /* can't scroll any further */
6877 view->count = 0;
6878 break;
6880 tree_scroll_down(view, 1);
6881 break;
6882 case CTRL('d'):
6883 case 'd':
6884 nscroll /= 2;
6885 /* FALL THROUGH */
6886 case KEY_NPAGE:
6887 case CTRL('f'):
6888 case 'f':
6889 case ' ':
6890 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6891 == NULL) {
6892 /* can't scroll any further; move cursor down */
6893 if (s->selected < s->ndisplayed - 1)
6894 s->selected += MIN(nscroll,
6895 s->ndisplayed - s->selected - 1);
6896 else
6897 view->count = 0;
6898 break;
6900 tree_scroll_down(view, nscroll);
6901 break;
6902 case KEY_ENTER:
6903 case '\r':
6904 case KEY_BACKSPACE:
6905 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6906 struct tog_parent_tree *parent;
6907 /* user selected '..' */
6908 if (s->tree == s->root) {
6909 view->count = 0;
6910 break;
6912 parent = TAILQ_FIRST(&s->parents);
6913 TAILQ_REMOVE(&s->parents, parent,
6914 entry);
6915 got_object_tree_close(s->tree);
6916 s->tree = parent->tree;
6917 s->first_displayed_entry =
6918 parent->first_displayed_entry;
6919 s->selected_entry =
6920 parent->selected_entry;
6921 s->selected = parent->selected;
6922 if (s->selected > view->nlines - 3) {
6923 err = offset_selection_down(view);
6924 if (err)
6925 break;
6927 free(parent);
6928 } else if (S_ISDIR(got_tree_entry_get_mode(
6929 s->selected_entry))) {
6930 struct got_tree_object *subtree;
6931 view->count = 0;
6932 err = got_object_open_as_tree(&subtree, s->repo,
6933 got_tree_entry_get_id(s->selected_entry));
6934 if (err)
6935 break;
6936 err = tree_view_visit_subtree(s, subtree);
6937 if (err) {
6938 got_object_tree_close(subtree);
6939 break;
6941 } else if (S_ISREG(got_tree_entry_get_mode(
6942 s->selected_entry))) {
6943 struct tog_view *blame_view;
6944 int begin_x = 0, begin_y = 0;
6946 if (view_is_parent_view(view))
6947 view_get_split(view, &begin_y, &begin_x);
6949 err = blame_tree_entry(&blame_view, begin_y, begin_x,
6950 s->selected_entry, &s->parents,
6951 s->commit_id, s->repo);
6952 if (err)
6953 break;
6955 if (view_is_parent_view(view) &&
6956 view->mode == TOG_VIEW_SPLIT_HRZN) {
6957 err = view_init_hsplit(view, begin_y);
6958 if (err)
6959 break;
6962 view->count = 0;
6963 view->focussed = 0;
6964 blame_view->focussed = 1;
6965 blame_view->mode = view->mode;
6966 blame_view->nlines = view->lines - begin_y;
6967 if (view_is_parent_view(view)) {
6968 view_transfer_size(blame_view, view);
6969 err = view_close_child(view);
6970 if (err)
6971 return err;
6972 err = view_set_child(view, blame_view);
6973 if (err)
6974 return err;
6975 view->focus_child = 1;
6976 } else
6977 *new_view = blame_view;
6979 break;
6980 case KEY_RESIZE:
6981 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6982 s->selected = view->nlines - 4;
6983 view->count = 0;
6984 break;
6985 default:
6986 view->count = 0;
6987 break;
6990 return err;
6993 __dead static void
6994 usage_tree(void)
6996 endwin();
6997 fprintf(stderr,
6998 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6999 getprogname());
7000 exit(1);
7003 static const struct got_error *
7004 cmd_tree(int argc, char *argv[])
7006 const struct got_error *error;
7007 struct got_repository *repo = NULL;
7008 struct got_worktree *worktree = NULL;
7009 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7010 struct got_object_id *commit_id = NULL;
7011 struct got_commit_object *commit = NULL;
7012 const char *commit_id_arg = NULL;
7013 char *label = NULL;
7014 struct got_reference *ref = NULL;
7015 const char *head_ref_name = NULL;
7016 int ch;
7017 struct tog_view *view;
7018 int *pack_fds = NULL;
7020 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7021 switch (ch) {
7022 case 'c':
7023 commit_id_arg = optarg;
7024 break;
7025 case 'r':
7026 repo_path = realpath(optarg, NULL);
7027 if (repo_path == NULL)
7028 return got_error_from_errno2("realpath",
7029 optarg);
7030 break;
7031 default:
7032 usage_tree();
7033 /* NOTREACHED */
7037 argc -= optind;
7038 argv += optind;
7040 if (argc > 1)
7041 usage_tree();
7043 error = got_repo_pack_fds_open(&pack_fds);
7044 if (error != NULL)
7045 goto done;
7047 if (repo_path == NULL) {
7048 cwd = getcwd(NULL, 0);
7049 if (cwd == NULL)
7050 return got_error_from_errno("getcwd");
7051 error = got_worktree_open(&worktree, cwd);
7052 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7053 goto done;
7054 if (worktree)
7055 repo_path =
7056 strdup(got_worktree_get_repo_path(worktree));
7057 else
7058 repo_path = strdup(cwd);
7059 if (repo_path == NULL) {
7060 error = got_error_from_errno("strdup");
7061 goto done;
7065 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7066 if (error != NULL)
7067 goto done;
7069 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7070 repo, worktree);
7071 if (error)
7072 goto done;
7074 init_curses();
7076 error = apply_unveil(got_repo_get_path(repo), NULL);
7077 if (error)
7078 goto done;
7080 error = tog_load_refs(repo, 0);
7081 if (error)
7082 goto done;
7084 if (commit_id_arg == NULL) {
7085 error = got_repo_match_object_id(&commit_id, &label,
7086 worktree ? got_worktree_get_head_ref_name(worktree) :
7087 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7088 if (error)
7089 goto done;
7090 head_ref_name = label;
7091 } else {
7092 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7093 if (error == NULL)
7094 head_ref_name = got_ref_get_name(ref);
7095 else if (error->code != GOT_ERR_NOT_REF)
7096 goto done;
7097 error = got_repo_match_object_id(&commit_id, NULL,
7098 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7099 if (error)
7100 goto done;
7103 error = got_object_open_as_commit(&commit, repo, commit_id);
7104 if (error)
7105 goto done;
7107 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7108 if (view == NULL) {
7109 error = got_error_from_errno("view_open");
7110 goto done;
7112 error = open_tree_view(view, commit_id, head_ref_name, repo);
7113 if (error)
7114 goto done;
7115 if (!got_path_is_root_dir(in_repo_path)) {
7116 error = tree_view_walk_path(&view->state.tree, commit,
7117 in_repo_path);
7118 if (error)
7119 goto done;
7122 if (worktree) {
7123 /* Release work tree lock. */
7124 got_worktree_close(worktree);
7125 worktree = NULL;
7127 error = view_loop(view);
7128 done:
7129 free(repo_path);
7130 free(cwd);
7131 free(commit_id);
7132 free(label);
7133 if (ref)
7134 got_ref_close(ref);
7135 if (repo) {
7136 const struct got_error *close_err = got_repo_close(repo);
7137 if (error == NULL)
7138 error = close_err;
7140 if (pack_fds) {
7141 const struct got_error *pack_err =
7142 got_repo_pack_fds_close(pack_fds);
7143 if (error == NULL)
7144 error = pack_err;
7146 tog_free_refs();
7147 return error;
7150 static const struct got_error *
7151 ref_view_load_refs(struct tog_ref_view_state *s)
7153 struct got_reflist_entry *sre;
7154 struct tog_reflist_entry *re;
7156 s->nrefs = 0;
7157 TAILQ_FOREACH(sre, &tog_refs, entry) {
7158 if (strncmp(got_ref_get_name(sre->ref),
7159 "refs/got/", 9) == 0 &&
7160 strncmp(got_ref_get_name(sre->ref),
7161 "refs/got/backup/", 16) != 0)
7162 continue;
7164 re = malloc(sizeof(*re));
7165 if (re == NULL)
7166 return got_error_from_errno("malloc");
7168 re->ref = got_ref_dup(sre->ref);
7169 if (re->ref == NULL)
7170 return got_error_from_errno("got_ref_dup");
7171 re->idx = s->nrefs++;
7172 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7175 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7176 return NULL;
7179 static void
7180 ref_view_free_refs(struct tog_ref_view_state *s)
7182 struct tog_reflist_entry *re;
7184 while (!TAILQ_EMPTY(&s->refs)) {
7185 re = TAILQ_FIRST(&s->refs);
7186 TAILQ_REMOVE(&s->refs, re, entry);
7187 got_ref_close(re->ref);
7188 free(re);
7192 static const struct got_error *
7193 open_ref_view(struct tog_view *view, struct got_repository *repo)
7195 const struct got_error *err = NULL;
7196 struct tog_ref_view_state *s = &view->state.ref;
7198 s->selected_entry = 0;
7199 s->repo = repo;
7201 TAILQ_INIT(&s->refs);
7202 STAILQ_INIT(&s->colors);
7204 err = ref_view_load_refs(s);
7205 if (err)
7206 return err;
7208 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7209 err = add_color(&s->colors, "^refs/heads/",
7210 TOG_COLOR_REFS_HEADS,
7211 get_color_value("TOG_COLOR_REFS_HEADS"));
7212 if (err)
7213 goto done;
7215 err = add_color(&s->colors, "^refs/tags/",
7216 TOG_COLOR_REFS_TAGS,
7217 get_color_value("TOG_COLOR_REFS_TAGS"));
7218 if (err)
7219 goto done;
7221 err = add_color(&s->colors, "^refs/remotes/",
7222 TOG_COLOR_REFS_REMOTES,
7223 get_color_value("TOG_COLOR_REFS_REMOTES"));
7224 if (err)
7225 goto done;
7227 err = add_color(&s->colors, "^refs/got/backup/",
7228 TOG_COLOR_REFS_BACKUP,
7229 get_color_value("TOG_COLOR_REFS_BACKUP"));
7230 if (err)
7231 goto done;
7234 view->show = show_ref_view;
7235 view->input = input_ref_view;
7236 view->close = close_ref_view;
7237 view->search_start = search_start_ref_view;
7238 view->search_next = search_next_ref_view;
7239 done:
7240 if (err)
7241 free_colors(&s->colors);
7242 return err;
7245 static const struct got_error *
7246 close_ref_view(struct tog_view *view)
7248 struct tog_ref_view_state *s = &view->state.ref;
7250 ref_view_free_refs(s);
7251 free_colors(&s->colors);
7253 return NULL;
7256 static const struct got_error *
7257 resolve_reflist_entry(struct got_object_id **commit_id,
7258 struct tog_reflist_entry *re, struct got_repository *repo)
7260 const struct got_error *err = NULL;
7261 struct got_object_id *obj_id;
7262 struct got_tag_object *tag = NULL;
7263 int obj_type;
7265 *commit_id = NULL;
7267 err = got_ref_resolve(&obj_id, repo, re->ref);
7268 if (err)
7269 return err;
7271 err = got_object_get_type(&obj_type, repo, obj_id);
7272 if (err)
7273 goto done;
7275 switch (obj_type) {
7276 case GOT_OBJ_TYPE_COMMIT:
7277 *commit_id = obj_id;
7278 break;
7279 case GOT_OBJ_TYPE_TAG:
7280 err = got_object_open_as_tag(&tag, repo, obj_id);
7281 if (err)
7282 goto done;
7283 free(obj_id);
7284 err = got_object_get_type(&obj_type, repo,
7285 got_object_tag_get_object_id(tag));
7286 if (err)
7287 goto done;
7288 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7289 err = got_error(GOT_ERR_OBJ_TYPE);
7290 goto done;
7292 *commit_id = got_object_id_dup(
7293 got_object_tag_get_object_id(tag));
7294 if (*commit_id == NULL) {
7295 err = got_error_from_errno("got_object_id_dup");
7296 goto done;
7298 break;
7299 default:
7300 err = got_error(GOT_ERR_OBJ_TYPE);
7301 break;
7304 done:
7305 if (tag)
7306 got_object_tag_close(tag);
7307 if (err) {
7308 free(*commit_id);
7309 *commit_id = NULL;
7311 return err;
7314 static const struct got_error *
7315 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7316 struct tog_reflist_entry *re, struct got_repository *repo)
7318 struct tog_view *log_view;
7319 const struct got_error *err = NULL;
7320 struct got_object_id *commit_id = NULL;
7322 *new_view = NULL;
7324 err = resolve_reflist_entry(&commit_id, re, repo);
7325 if (err) {
7326 if (err->code != GOT_ERR_OBJ_TYPE)
7327 return err;
7328 else
7329 return NULL;
7332 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7333 if (log_view == NULL) {
7334 err = got_error_from_errno("view_open");
7335 goto done;
7338 err = open_log_view(log_view, commit_id, repo,
7339 got_ref_get_name(re->ref), "", 0);
7340 done:
7341 if (err)
7342 view_close(log_view);
7343 else
7344 *new_view = log_view;
7345 free(commit_id);
7346 return err;
7349 static void
7350 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7352 struct tog_reflist_entry *re;
7353 int i = 0;
7355 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7356 return;
7358 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7359 while (i++ < maxscroll) {
7360 if (re == NULL)
7361 break;
7362 s->first_displayed_entry = re;
7363 re = TAILQ_PREV(re, tog_reflist_head, entry);
7367 static const struct got_error *
7368 ref_scroll_down(struct tog_view *view, int maxscroll)
7370 struct tog_ref_view_state *s = &view->state.ref;
7371 struct tog_reflist_entry *next, *last;
7372 int n = 0;
7374 if (s->first_displayed_entry)
7375 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7376 else
7377 next = TAILQ_FIRST(&s->refs);
7379 last = s->last_displayed_entry;
7380 while (next && n++ < maxscroll) {
7381 if (last)
7382 last = TAILQ_NEXT(last, entry);
7383 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7384 s->first_displayed_entry = next;
7385 next = TAILQ_NEXT(next, entry);
7389 return NULL;
7392 static const struct got_error *
7393 search_start_ref_view(struct tog_view *view)
7395 struct tog_ref_view_state *s = &view->state.ref;
7397 s->matched_entry = NULL;
7398 return NULL;
7401 static int
7402 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7404 regmatch_t regmatch;
7406 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7407 0) == 0;
7410 static const struct got_error *
7411 search_next_ref_view(struct tog_view *view)
7413 struct tog_ref_view_state *s = &view->state.ref;
7414 struct tog_reflist_entry *re = NULL;
7416 if (!view->searching) {
7417 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7418 return NULL;
7421 if (s->matched_entry) {
7422 if (view->searching == TOG_SEARCH_FORWARD) {
7423 if (s->selected_entry)
7424 re = TAILQ_NEXT(s->selected_entry, entry);
7425 else
7426 re = TAILQ_PREV(s->selected_entry,
7427 tog_reflist_head, entry);
7428 } else {
7429 if (s->selected_entry == NULL)
7430 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7431 else
7432 re = TAILQ_PREV(s->selected_entry,
7433 tog_reflist_head, entry);
7435 } else {
7436 if (s->selected_entry)
7437 re = s->selected_entry;
7438 else if (view->searching == TOG_SEARCH_FORWARD)
7439 re = TAILQ_FIRST(&s->refs);
7440 else
7441 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7444 while (1) {
7445 if (re == NULL) {
7446 if (s->matched_entry == NULL) {
7447 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7448 return NULL;
7450 if (view->searching == TOG_SEARCH_FORWARD)
7451 re = TAILQ_FIRST(&s->refs);
7452 else
7453 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7456 if (match_reflist_entry(re, &view->regex)) {
7457 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7458 s->matched_entry = re;
7459 break;
7462 if (view->searching == TOG_SEARCH_FORWARD)
7463 re = TAILQ_NEXT(re, entry);
7464 else
7465 re = TAILQ_PREV(re, tog_reflist_head, entry);
7468 if (s->matched_entry) {
7469 s->first_displayed_entry = s->matched_entry;
7470 s->selected = 0;
7473 return NULL;
7476 static const struct got_error *
7477 show_ref_view(struct tog_view *view)
7479 const struct got_error *err = NULL;
7480 struct tog_ref_view_state *s = &view->state.ref;
7481 struct tog_reflist_entry *re;
7482 char *line = NULL;
7483 wchar_t *wline;
7484 struct tog_color *tc;
7485 int width, n;
7486 int limit = view->nlines;
7488 werase(view->window);
7490 s->ndisplayed = 0;
7491 if (view_is_hsplit_top(view))
7492 --limit; /* border */
7494 if (limit == 0)
7495 return NULL;
7497 re = s->first_displayed_entry;
7499 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7500 s->nrefs) == -1)
7501 return got_error_from_errno("asprintf");
7503 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7504 if (err) {
7505 free(line);
7506 return err;
7508 if (view_needs_focus_indication(view))
7509 wstandout(view->window);
7510 waddwstr(view->window, wline);
7511 if (view_needs_focus_indication(view))
7512 wstandend(view->window);
7513 free(wline);
7514 wline = NULL;
7515 free(line);
7516 line = NULL;
7517 if (width < view->ncols - 1)
7518 waddch(view->window, '\n');
7519 if (--limit <= 0)
7520 return NULL;
7522 n = 0;
7523 while (re && limit > 0) {
7524 char *line = NULL;
7525 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7527 if (s->show_date) {
7528 struct got_commit_object *ci;
7529 struct got_tag_object *tag;
7530 struct got_object_id *id;
7531 struct tm tm;
7532 time_t t;
7534 err = got_ref_resolve(&id, s->repo, re->ref);
7535 if (err)
7536 return err;
7537 err = got_object_open_as_tag(&tag, s->repo, id);
7538 if (err) {
7539 if (err->code != GOT_ERR_OBJ_TYPE) {
7540 free(id);
7541 return err;
7543 err = got_object_open_as_commit(&ci, s->repo,
7544 id);
7545 if (err) {
7546 free(id);
7547 return err;
7549 t = got_object_commit_get_committer_time(ci);
7550 got_object_commit_close(ci);
7551 } else {
7552 t = got_object_tag_get_tagger_time(tag);
7553 got_object_tag_close(tag);
7555 free(id);
7556 if (gmtime_r(&t, &tm) == NULL)
7557 return got_error_from_errno("gmtime_r");
7558 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7559 return got_error(GOT_ERR_NO_SPACE);
7561 if (got_ref_is_symbolic(re->ref)) {
7562 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7563 ymd : "", got_ref_get_name(re->ref),
7564 got_ref_get_symref_target(re->ref)) == -1)
7565 return got_error_from_errno("asprintf");
7566 } else if (s->show_ids) {
7567 struct got_object_id *id;
7568 char *id_str;
7569 err = got_ref_resolve(&id, s->repo, re->ref);
7570 if (err)
7571 return err;
7572 err = got_object_id_str(&id_str, id);
7573 if (err) {
7574 free(id);
7575 return err;
7577 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7578 got_ref_get_name(re->ref), id_str) == -1) {
7579 err = got_error_from_errno("asprintf");
7580 free(id);
7581 free(id_str);
7582 return err;
7584 free(id);
7585 free(id_str);
7586 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7587 got_ref_get_name(re->ref)) == -1)
7588 return got_error_from_errno("asprintf");
7590 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7591 0, 0);
7592 if (err) {
7593 free(line);
7594 return err;
7596 if (n == s->selected) {
7597 if (view->focussed)
7598 wstandout(view->window);
7599 s->selected_entry = re;
7601 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7602 if (tc)
7603 wattr_on(view->window,
7604 COLOR_PAIR(tc->colorpair), NULL);
7605 waddwstr(view->window, wline);
7606 if (tc)
7607 wattr_off(view->window,
7608 COLOR_PAIR(tc->colorpair), NULL);
7609 if (width < view->ncols - 1)
7610 waddch(view->window, '\n');
7611 if (n == s->selected && view->focussed)
7612 wstandend(view->window);
7613 free(line);
7614 free(wline);
7615 wline = NULL;
7616 n++;
7617 s->ndisplayed++;
7618 s->last_displayed_entry = re;
7620 limit--;
7621 re = TAILQ_NEXT(re, entry);
7624 view_border(view);
7625 return err;
7628 static const struct got_error *
7629 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7630 struct tog_reflist_entry *re, struct got_repository *repo)
7632 const struct got_error *err = NULL;
7633 struct got_object_id *commit_id = NULL;
7634 struct tog_view *tree_view;
7636 *new_view = NULL;
7638 err = resolve_reflist_entry(&commit_id, re, repo);
7639 if (err) {
7640 if (err->code != GOT_ERR_OBJ_TYPE)
7641 return err;
7642 else
7643 return NULL;
7647 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7648 if (tree_view == NULL) {
7649 err = got_error_from_errno("view_open");
7650 goto done;
7653 err = open_tree_view(tree_view, commit_id,
7654 got_ref_get_name(re->ref), repo);
7655 if (err)
7656 goto done;
7658 *new_view = tree_view;
7659 done:
7660 free(commit_id);
7661 return err;
7663 static const struct got_error *
7664 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7666 const struct got_error *err = NULL;
7667 struct tog_ref_view_state *s = &view->state.ref;
7668 struct tog_view *log_view, *tree_view;
7669 struct tog_reflist_entry *re;
7670 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 1;
7672 switch (ch) {
7673 case 'i':
7674 s->show_ids = !s->show_ids;
7675 view->count = 0;
7676 break;
7677 case 'm':
7678 s->show_date = !s->show_date;
7679 view->count = 0;
7680 break;
7681 case 'o':
7682 s->sort_by_date = !s->sort_by_date;
7683 view->count = 0;
7684 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7685 got_ref_cmp_by_commit_timestamp_descending :
7686 tog_ref_cmp_by_name, s->repo);
7687 if (err)
7688 break;
7689 got_reflist_object_id_map_free(tog_refs_idmap);
7690 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7691 &tog_refs, s->repo);
7692 if (err)
7693 break;
7694 ref_view_free_refs(s);
7695 err = ref_view_load_refs(s);
7696 break;
7697 case KEY_ENTER:
7698 case '\r':
7699 view->count = 0;
7700 if (!s->selected_entry)
7701 break;
7702 if (view_is_parent_view(view))
7703 view_get_split(view, &begin_y, &begin_x);
7705 err = log_ref_entry(&log_view, begin_y, begin_x,
7706 s->selected_entry, s->repo);
7707 if (err)
7708 break;
7710 if (view_is_parent_view(view) &&
7711 view->mode == TOG_VIEW_SPLIT_HRZN) {
7712 err = view_init_hsplit(view, begin_y);
7713 if (err)
7714 break;
7717 view->focussed = 0;
7718 log_view->focussed = 1;
7719 log_view->mode = view->mode;
7720 log_view->nlines = view->lines - begin_y;
7721 if (view_is_parent_view(view)) {
7722 view_transfer_size(log_view, view);
7723 err = view_close_child(view);
7724 if (err)
7725 return err;
7726 err = view_set_child(view, log_view);
7727 if (err)
7728 return err;
7729 view->focus_child = 1;
7730 } else
7731 *new_view = log_view;
7732 break;
7733 case 't':
7734 view->count = 0;
7735 if (!s->selected_entry)
7736 break;
7737 if (view_is_parent_view(view))
7738 view_get_split(view, &begin_y, &begin_x);
7739 err = browse_ref_tree(&tree_view, begin_y, begin_x,
7740 s->selected_entry, s->repo);
7741 if (err || tree_view == NULL)
7742 break;
7743 if (view_is_parent_view(view) &&
7744 view->mode == TOG_VIEW_SPLIT_HRZN) {
7745 err = view_init_hsplit(view, begin_y);
7746 if (err)
7747 break;
7749 view->focussed = 0;
7750 tree_view->focussed = 1;
7751 tree_view->mode = view->mode;
7752 tree_view->nlines = view->lines - begin_y;
7753 if (view_is_parent_view(view)) {
7754 view_transfer_size(tree_view, view);
7755 err = view_close_child(view);
7756 if (err)
7757 return err;
7758 err = view_set_child(view, tree_view);
7759 if (err)
7760 return err;
7761 view->focus_child = 1;
7762 } else
7763 *new_view = tree_view;
7764 break;
7765 case 'g':
7766 case KEY_HOME:
7767 s->selected = 0;
7768 view->count = 0;
7769 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7770 break;
7771 case 'G':
7772 case KEY_END: {
7773 int eos = view->nlines - 1;
7775 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7776 --eos; /* border */
7777 s->selected = 0;
7778 view->count = 0;
7779 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7780 for (n = 0; n < eos; n++) {
7781 if (re == NULL)
7782 break;
7783 s->first_displayed_entry = re;
7784 re = TAILQ_PREV(re, tog_reflist_head, entry);
7786 if (n > 0)
7787 s->selected = n - 1;
7788 break;
7790 case 'k':
7791 case KEY_UP:
7792 case CTRL('p'):
7793 if (s->selected > 0) {
7794 s->selected--;
7795 break;
7797 ref_scroll_up(s, 1);
7798 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7799 view->count = 0;
7800 break;
7801 case CTRL('u'):
7802 case 'u':
7803 nscroll /= 2;
7804 /* FALL THROUGH */
7805 case KEY_PPAGE:
7806 case CTRL('b'):
7807 case 'b':
7808 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7809 s->selected -= MIN(nscroll, s->selected);
7810 ref_scroll_up(s, MAX(0, nscroll));
7811 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7812 view->count = 0;
7813 break;
7814 case 'j':
7815 case KEY_DOWN:
7816 case CTRL('n'):
7817 if (s->selected < s->ndisplayed - 1) {
7818 s->selected++;
7819 break;
7821 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7822 /* can't scroll any further */
7823 view->count = 0;
7824 break;
7826 ref_scroll_down(view, 1);
7827 break;
7828 case CTRL('d'):
7829 case 'd':
7830 nscroll /= 2;
7831 /* FALL THROUGH */
7832 case KEY_NPAGE:
7833 case CTRL('f'):
7834 case 'f':
7835 case ' ':
7836 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7837 /* can't scroll any further; move cursor down */
7838 if (s->selected < s->ndisplayed - 1)
7839 s->selected += MIN(nscroll,
7840 s->ndisplayed - s->selected - 1);
7841 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7842 s->selected += s->ndisplayed - s->selected - 1;
7843 view->count = 0;
7844 break;
7846 ref_scroll_down(view, nscroll);
7847 break;
7848 case CTRL('l'):
7849 view->count = 0;
7850 tog_free_refs();
7851 err = tog_load_refs(s->repo, s->sort_by_date);
7852 if (err)
7853 break;
7854 ref_view_free_refs(s);
7855 err = ref_view_load_refs(s);
7856 break;
7857 case KEY_RESIZE:
7858 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7859 s->selected = view->nlines - 2;
7860 break;
7861 default:
7862 view->count = 0;
7863 break;
7866 return err;
7869 __dead static void
7870 usage_ref(void)
7872 endwin();
7873 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7874 getprogname());
7875 exit(1);
7878 static const struct got_error *
7879 cmd_ref(int argc, char *argv[])
7881 const struct got_error *error;
7882 struct got_repository *repo = NULL;
7883 struct got_worktree *worktree = NULL;
7884 char *cwd = NULL, *repo_path = NULL;
7885 int ch;
7886 struct tog_view *view;
7887 int *pack_fds = NULL;
7889 while ((ch = getopt(argc, argv, "r:")) != -1) {
7890 switch (ch) {
7891 case 'r':
7892 repo_path = realpath(optarg, NULL);
7893 if (repo_path == NULL)
7894 return got_error_from_errno2("realpath",
7895 optarg);
7896 break;
7897 default:
7898 usage_ref();
7899 /* NOTREACHED */
7903 argc -= optind;
7904 argv += optind;
7906 if (argc > 1)
7907 usage_ref();
7909 error = got_repo_pack_fds_open(&pack_fds);
7910 if (error != NULL)
7911 goto done;
7913 if (repo_path == NULL) {
7914 cwd = getcwd(NULL, 0);
7915 if (cwd == NULL)
7916 return got_error_from_errno("getcwd");
7917 error = got_worktree_open(&worktree, cwd);
7918 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7919 goto done;
7920 if (worktree)
7921 repo_path =
7922 strdup(got_worktree_get_repo_path(worktree));
7923 else
7924 repo_path = strdup(cwd);
7925 if (repo_path == NULL) {
7926 error = got_error_from_errno("strdup");
7927 goto done;
7931 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7932 if (error != NULL)
7933 goto done;
7935 init_curses();
7937 error = apply_unveil(got_repo_get_path(repo), NULL);
7938 if (error)
7939 goto done;
7941 error = tog_load_refs(repo, 0);
7942 if (error)
7943 goto done;
7945 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7946 if (view == NULL) {
7947 error = got_error_from_errno("view_open");
7948 goto done;
7951 error = open_ref_view(view, repo);
7952 if (error)
7953 goto done;
7955 if (worktree) {
7956 /* Release work tree lock. */
7957 got_worktree_close(worktree);
7958 worktree = NULL;
7960 error = view_loop(view);
7961 done:
7962 free(repo_path);
7963 free(cwd);
7964 if (repo) {
7965 const struct got_error *close_err = got_repo_close(repo);
7966 if (close_err)
7967 error = close_err;
7969 if (pack_fds) {
7970 const struct got_error *pack_err =
7971 got_repo_pack_fds_close(pack_fds);
7972 if (error == NULL)
7973 error = pack_err;
7975 tog_free_refs();
7976 return error;
7980 * If view was scrolled down to move the selected line into view when opening a
7981 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7983 static void
7984 offset_selection_up(struct tog_view *view)
7986 switch (view->type) {
7987 case TOG_VIEW_BLAME: {
7988 struct tog_blame_view_state *s = &view->state.blame;
7989 if (s->first_displayed_line == 1) {
7990 s->selected_line = MAX(s->selected_line - view->offset,
7991 1);
7992 break;
7994 if (s->first_displayed_line > view->offset)
7995 s->first_displayed_line -= view->offset;
7996 else
7997 s->first_displayed_line = 1;
7998 s->selected_line += view->offset;
7999 break;
8001 case TOG_VIEW_LOG:
8002 log_scroll_up(&view->state.log, view->offset);
8003 view->state.log.selected += view->offset;
8004 break;
8005 case TOG_VIEW_REF:
8006 ref_scroll_up(&view->state.ref, view->offset);
8007 view->state.ref.selected += view->offset;
8008 break;
8009 case TOG_VIEW_TREE:
8010 tree_scroll_up(&view->state.tree, view->offset);
8011 view->state.tree.selected += view->offset;
8012 break;
8013 default:
8014 break;
8017 view->offset = 0;
8021 * If the selected line is in the section of screen covered by the bottom split,
8022 * scroll down offset lines to move it into view and index its new position.
8024 static const struct got_error *
8025 offset_selection_down(struct tog_view *view)
8027 const struct got_error *err = NULL;
8028 const struct got_error *(*scrolld)(struct tog_view *, int);
8029 int *selected = NULL;
8030 int header, offset;
8032 switch (view->type) {
8033 case TOG_VIEW_BLAME: {
8034 struct tog_blame_view_state *s = &view->state.blame;
8035 header = 3;
8036 scrolld = NULL;
8037 if (s->selected_line > view->nlines - header) {
8038 offset = abs(view->nlines - s->selected_line - header);
8039 s->first_displayed_line += offset;
8040 s->selected_line -= offset;
8041 view->offset = offset;
8043 break;
8045 case TOG_VIEW_LOG: {
8046 struct tog_log_view_state *s = &view->state.log;
8047 scrolld = &log_scroll_down;
8048 header = view_is_parent_view(view) ? 3 : 2;
8049 selected = &s->selected;
8050 break;
8052 case TOG_VIEW_REF: {
8053 struct tog_ref_view_state *s = &view->state.ref;
8054 scrolld = &ref_scroll_down;
8055 header = 3;
8056 selected = &s->selected;
8057 break;
8059 case TOG_VIEW_TREE: {
8060 struct tog_tree_view_state *s = &view->state.tree;
8061 scrolld = &tree_scroll_down;
8062 header = 5;
8063 selected = &s->selected;
8064 break;
8066 default:
8067 selected = NULL;
8068 scrolld = NULL;
8069 header = 0;
8070 break;
8073 if (selected && *selected > view->nlines - header) {
8074 offset = abs(view->nlines - *selected - header);
8075 view->offset = offset;
8076 if (scrolld && offset) {
8077 err = scrolld(view, offset);
8078 *selected -= offset;
8082 return err;
8085 static void
8086 list_commands(FILE *fp)
8088 size_t i;
8090 fprintf(fp, "commands:");
8091 for (i = 0; i < nitems(tog_commands); i++) {
8092 const struct tog_cmd *cmd = &tog_commands[i];
8093 fprintf(fp, " %s", cmd->name);
8095 fputc('\n', fp);
8098 __dead static void
8099 usage(int hflag, int status)
8101 FILE *fp = (status == 0) ? stdout : stderr;
8103 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8104 getprogname());
8105 if (hflag) {
8106 fprintf(fp, "lazy usage: %s path\n", getprogname());
8107 list_commands(fp);
8109 exit(status);
8112 static char **
8113 make_argv(int argc, ...)
8115 va_list ap;
8116 char **argv;
8117 int i;
8119 va_start(ap, argc);
8121 argv = calloc(argc, sizeof(char *));
8122 if (argv == NULL)
8123 err(1, "calloc");
8124 for (i = 0; i < argc; i++) {
8125 argv[i] = strdup(va_arg(ap, char *));
8126 if (argv[i] == NULL)
8127 err(1, "strdup");
8130 va_end(ap);
8131 return argv;
8135 * Try to convert 'tog path' into a 'tog log path' command.
8136 * The user could simply have mistyped the command rather than knowingly
8137 * provided a path. So check whether argv[0] can in fact be resolved
8138 * to a path in the HEAD commit and print a special error if not.
8139 * This hack is for mpi@ <3
8141 static const struct got_error *
8142 tog_log_with_path(int argc, char *argv[])
8144 const struct got_error *error = NULL, *close_err;
8145 const struct tog_cmd *cmd = NULL;
8146 struct got_repository *repo = NULL;
8147 struct got_worktree *worktree = NULL;
8148 struct got_object_id *commit_id = NULL, *id = NULL;
8149 struct got_commit_object *commit = NULL;
8150 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8151 char *commit_id_str = NULL, **cmd_argv = NULL;
8152 int *pack_fds = NULL;
8154 cwd = getcwd(NULL, 0);
8155 if (cwd == NULL)
8156 return got_error_from_errno("getcwd");
8158 error = got_repo_pack_fds_open(&pack_fds);
8159 if (error != NULL)
8160 goto done;
8162 error = got_worktree_open(&worktree, cwd);
8163 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8164 goto done;
8166 if (worktree)
8167 repo_path = strdup(got_worktree_get_repo_path(worktree));
8168 else
8169 repo_path = strdup(cwd);
8170 if (repo_path == NULL) {
8171 error = got_error_from_errno("strdup");
8172 goto done;
8175 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8176 if (error != NULL)
8177 goto done;
8179 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8180 repo, worktree);
8181 if (error)
8182 goto done;
8184 error = tog_load_refs(repo, 0);
8185 if (error)
8186 goto done;
8187 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8188 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8189 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8190 if (error)
8191 goto done;
8193 if (worktree) {
8194 got_worktree_close(worktree);
8195 worktree = NULL;
8198 error = got_object_open_as_commit(&commit, repo, commit_id);
8199 if (error)
8200 goto done;
8202 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8203 if (error) {
8204 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8205 goto done;
8206 fprintf(stderr, "%s: '%s' is no known command or path\n",
8207 getprogname(), argv[0]);
8208 usage(1, 1);
8209 /* not reached */
8212 close_err = got_repo_close(repo);
8213 if (error == NULL)
8214 error = close_err;
8215 repo = NULL;
8217 error = got_object_id_str(&commit_id_str, commit_id);
8218 if (error)
8219 goto done;
8221 cmd = &tog_commands[0]; /* log */
8222 argc = 4;
8223 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8224 error = cmd->cmd_main(argc, cmd_argv);
8225 done:
8226 if (repo) {
8227 close_err = got_repo_close(repo);
8228 if (error == NULL)
8229 error = close_err;
8231 if (commit)
8232 got_object_commit_close(commit);
8233 if (worktree)
8234 got_worktree_close(worktree);
8235 if (pack_fds) {
8236 const struct got_error *pack_err =
8237 got_repo_pack_fds_close(pack_fds);
8238 if (error == NULL)
8239 error = pack_err;
8241 free(id);
8242 free(commit_id_str);
8243 free(commit_id);
8244 free(cwd);
8245 free(repo_path);
8246 free(in_repo_path);
8247 if (cmd_argv) {
8248 int i;
8249 for (i = 0; i < argc; i++)
8250 free(cmd_argv[i]);
8251 free(cmd_argv);
8253 tog_free_refs();
8254 return error;
8257 int
8258 main(int argc, char *argv[])
8260 const struct got_error *error = NULL;
8261 const struct tog_cmd *cmd = NULL;
8262 int ch, hflag = 0, Vflag = 0;
8263 char **cmd_argv = NULL;
8264 static const struct option longopts[] = {
8265 { "version", no_argument, NULL, 'V' },
8266 { NULL, 0, NULL, 0}
8268 char *diff_algo_str = NULL;
8270 setlocale(LC_CTYPE, "");
8272 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8273 switch (ch) {
8274 case 'h':
8275 hflag = 1;
8276 break;
8277 case 'V':
8278 Vflag = 1;
8279 break;
8280 default:
8281 usage(hflag, 1);
8282 /* NOTREACHED */
8286 argc -= optind;
8287 argv += optind;
8288 optind = 1;
8289 optreset = 1;
8291 if (Vflag) {
8292 got_version_print_str();
8293 return 0;
8296 #ifndef PROFILE
8297 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8298 NULL) == -1)
8299 err(1, "pledge");
8300 #endif
8302 if (argc == 0) {
8303 if (hflag)
8304 usage(hflag, 0);
8305 /* Build an argument vector which runs a default command. */
8306 cmd = &tog_commands[0];
8307 argc = 1;
8308 cmd_argv = make_argv(argc, cmd->name);
8309 } else {
8310 size_t i;
8312 /* Did the user specify a command? */
8313 for (i = 0; i < nitems(tog_commands); i++) {
8314 if (strncmp(tog_commands[i].name, argv[0],
8315 strlen(argv[0])) == 0) {
8316 cmd = &tog_commands[i];
8317 break;
8322 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8323 if (diff_algo_str) {
8324 if (strcasecmp(diff_algo_str, "patience") == 0)
8325 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8326 if (strcasecmp(diff_algo_str, "myers") == 0)
8327 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8330 if (cmd == NULL) {
8331 if (argc != 1)
8332 usage(0, 1);
8333 /* No command specified; try log with a path */
8334 error = tog_log_with_path(argc, argv);
8335 } else {
8336 if (hflag)
8337 cmd->cmd_usage();
8338 else
8339 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8342 endwin();
8343 putchar('\n');
8344 if (cmd_argv) {
8345 int i;
8346 for (i = 0; i < argc; i++)
8347 free(cmd_argv[i]);
8348 free(cmd_argv);
8351 if (error && error->code != GOT_ERR_CANCELLED)
8352 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8353 return 0;