Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 };
108 enum tog_view_mode {
109 TOG_VIEW_SPLIT_NONE,
110 TOG_VIEW_SPLIT_VERT,
111 TOG_VIEW_SPLIT_HRZN
112 };
114 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
116 #define TOG_EOF_STRING "(END)"
118 struct commit_queue_entry {
119 TAILQ_ENTRY(commit_queue_entry) entry;
120 struct got_object_id *id;
121 struct got_commit_object *commit;
122 int idx;
123 };
124 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
125 struct commit_queue {
126 int ncommits;
127 struct commit_queue_head head;
128 };
130 struct tog_color {
131 STAILQ_ENTRY(tog_color) entry;
132 regex_t regex;
133 short colorpair;
134 };
135 STAILQ_HEAD(tog_colors, tog_color);
137 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
138 static struct got_reflist_object_id_map *tog_refs_idmap;
139 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
141 static const struct got_error *
142 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
143 struct got_reference* re2)
145 const char *name1 = got_ref_get_name(re1);
146 const char *name2 = got_ref_get_name(re2);
147 int isbackup1, isbackup2;
149 /* Sort backup refs towards the bottom of the list. */
150 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
151 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
152 if (!isbackup1 && isbackup2) {
153 *cmp = -1;
154 return NULL;
155 } else if (isbackup1 && !isbackup2) {
156 *cmp = 1;
157 return NULL;
160 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
161 return NULL;
164 static const struct got_error *
165 tog_load_refs(struct got_repository *repo, int sort_by_date)
167 const struct got_error *err;
169 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
170 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
171 repo);
172 if (err)
173 return err;
175 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
176 repo);
179 static void
180 tog_free_refs(void)
182 if (tog_refs_idmap) {
183 got_reflist_object_id_map_free(tog_refs_idmap);
184 tog_refs_idmap = NULL;
186 got_ref_list_free(&tog_refs);
189 static const struct got_error *
190 add_color(struct tog_colors *colors, const char *pattern,
191 int idx, short color)
193 const struct got_error *err = NULL;
194 struct tog_color *tc;
195 int regerr = 0;
197 if (idx < 1 || idx > COLOR_PAIRS - 1)
198 return NULL;
200 init_pair(idx, color, -1);
202 tc = calloc(1, sizeof(*tc));
203 if (tc == NULL)
204 return got_error_from_errno("calloc");
205 regerr = regcomp(&tc->regex, pattern,
206 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
207 if (regerr) {
208 static char regerr_msg[512];
209 static char err_msg[512];
210 regerror(regerr, &tc->regex, regerr_msg,
211 sizeof(regerr_msg));
212 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
213 regerr_msg);
214 err = got_error_msg(GOT_ERR_REGEX, err_msg);
215 free(tc);
216 return err;
218 tc->colorpair = idx;
219 STAILQ_INSERT_HEAD(colors, tc, entry);
220 return NULL;
223 static void
224 free_colors(struct tog_colors *colors)
226 struct tog_color *tc;
228 while (!STAILQ_EMPTY(colors)) {
229 tc = STAILQ_FIRST(colors);
230 STAILQ_REMOVE_HEAD(colors, entry);
231 regfree(&tc->regex);
232 free(tc);
236 static struct tog_color *
237 get_color(struct tog_colors *colors, int colorpair)
239 struct tog_color *tc = NULL;
241 STAILQ_FOREACH(tc, colors, entry) {
242 if (tc->colorpair == colorpair)
243 return tc;
246 return NULL;
249 static int
250 default_color_value(const char *envvar)
252 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
253 return COLOR_MAGENTA;
254 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
255 return COLOR_CYAN;
256 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
257 return COLOR_YELLOW;
258 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
259 return COLOR_GREEN;
260 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
261 return COLOR_MAGENTA;
262 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
263 return COLOR_MAGENTA;
264 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
265 return COLOR_CYAN;
266 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
267 return COLOR_GREEN;
268 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
269 return COLOR_GREEN;
270 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
271 return COLOR_CYAN;
272 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
273 return COLOR_YELLOW;
274 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
275 return COLOR_GREEN;
276 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
279 return COLOR_YELLOW;
280 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
281 return COLOR_CYAN;
283 return -1;
286 static int
287 get_color_value(const char *envvar)
289 const char *val = getenv(envvar);
291 if (val == NULL)
292 return default_color_value(envvar);
294 if (strcasecmp(val, "black") == 0)
295 return COLOR_BLACK;
296 if (strcasecmp(val, "red") == 0)
297 return COLOR_RED;
298 if (strcasecmp(val, "green") == 0)
299 return COLOR_GREEN;
300 if (strcasecmp(val, "yellow") == 0)
301 return COLOR_YELLOW;
302 if (strcasecmp(val, "blue") == 0)
303 return COLOR_BLUE;
304 if (strcasecmp(val, "magenta") == 0)
305 return COLOR_MAGENTA;
306 if (strcasecmp(val, "cyan") == 0)
307 return COLOR_CYAN;
308 if (strcasecmp(val, "white") == 0)
309 return COLOR_WHITE;
310 if (strcasecmp(val, "default") == 0)
311 return -1;
313 return default_color_value(envvar);
317 struct tog_diff_view_state {
318 struct got_object_id *id1, *id2;
319 const char *label1, *label2;
320 FILE *f, *f1, *f2;
321 int fd1, fd2;
322 int first_displayed_line;
323 int last_displayed_line;
324 int eof;
325 int diff_context;
326 int ignore_whitespace;
327 int force_text_diff;
328 struct got_repository *repo;
329 struct tog_colors colors;
330 size_t nlines;
331 off_t *line_offsets;
332 int matched_line;
333 int selected_line;
335 /* passed from log or blame view; may be NULL */
336 struct tog_view *parent_view;
337 };
339 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
340 static volatile sig_atomic_t tog_thread_error;
342 struct tog_log_thread_args {
343 pthread_cond_t need_commits;
344 pthread_cond_t commit_loaded;
345 int commits_needed;
346 int load_all;
347 struct got_commit_graph *graph;
348 struct commit_queue *commits;
349 const char *in_repo_path;
350 struct got_object_id *start_id;
351 struct got_repository *repo;
352 int *pack_fds;
353 int log_complete;
354 sig_atomic_t *quit;
355 struct commit_queue_entry **first_displayed_entry;
356 struct commit_queue_entry **selected_entry;
357 int *searching;
358 int *search_next_done;
359 regex_t *regex;
360 };
362 struct tog_log_view_state {
363 struct commit_queue commits;
364 struct commit_queue_entry *first_displayed_entry;
365 struct commit_queue_entry *last_displayed_entry;
366 struct commit_queue_entry *selected_entry;
367 int selected;
368 char *in_repo_path;
369 char *head_ref_name;
370 int log_branches;
371 struct got_repository *repo;
372 struct got_object_id *start_id;
373 sig_atomic_t quit;
374 pthread_t thread;
375 struct tog_log_thread_args thread_args;
376 struct commit_queue_entry *matched_entry;
377 struct commit_queue_entry *search_entry;
378 struct tog_colors colors;
379 int use_committer;
380 };
382 #define TOG_COLOR_DIFF_MINUS 1
383 #define TOG_COLOR_DIFF_PLUS 2
384 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
385 #define TOG_COLOR_DIFF_META 4
386 #define TOG_COLOR_TREE_SUBMODULE 5
387 #define TOG_COLOR_TREE_SYMLINK 6
388 #define TOG_COLOR_TREE_DIRECTORY 7
389 #define TOG_COLOR_TREE_EXECUTABLE 8
390 #define TOG_COLOR_COMMIT 9
391 #define TOG_COLOR_AUTHOR 10
392 #define TOG_COLOR_DATE 11
393 #define TOG_COLOR_REFS_HEADS 12
394 #define TOG_COLOR_REFS_TAGS 13
395 #define TOG_COLOR_REFS_REMOTES 14
396 #define TOG_COLOR_REFS_BACKUP 15
398 struct tog_blame_cb_args {
399 struct tog_blame_line *lines; /* one per line */
400 int nlines;
402 struct tog_view *view;
403 struct got_object_id *commit_id;
404 int *quit;
405 };
407 struct tog_blame_thread_args {
408 const char *path;
409 struct got_repository *repo;
410 struct tog_blame_cb_args *cb_args;
411 int *complete;
412 got_cancel_cb cancel_cb;
413 void *cancel_arg;
414 };
416 struct tog_blame {
417 FILE *f;
418 off_t filesize;
419 struct tog_blame_line *lines;
420 int nlines;
421 off_t *line_offsets;
422 pthread_t thread;
423 struct tog_blame_thread_args thread_args;
424 struct tog_blame_cb_args cb_args;
425 const char *path;
426 int *pack_fds;
427 };
429 struct tog_blame_view_state {
430 int first_displayed_line;
431 int last_displayed_line;
432 int selected_line;
433 int last_diffed_line;
434 int blame_complete;
435 int eof;
436 int done;
437 struct got_object_id_queue blamed_commits;
438 struct got_object_qid *blamed_commit;
439 char *path;
440 struct got_repository *repo;
441 struct got_object_id *commit_id;
442 struct got_object_id *id_to_log;
443 struct tog_blame blame;
444 int matched_line;
445 struct tog_colors colors;
446 };
448 struct tog_parent_tree {
449 TAILQ_ENTRY(tog_parent_tree) entry;
450 struct got_tree_object *tree;
451 struct got_tree_entry *first_displayed_entry;
452 struct got_tree_entry *selected_entry;
453 int selected;
454 };
456 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
458 struct tog_tree_view_state {
459 char *tree_label;
460 struct got_object_id *commit_id;/* commit which this tree belongs to */
461 struct got_tree_object *root; /* the commit's root tree entry */
462 struct got_tree_object *tree; /* currently displayed (sub-)tree */
463 struct got_tree_entry *first_displayed_entry;
464 struct got_tree_entry *last_displayed_entry;
465 struct got_tree_entry *selected_entry;
466 int ndisplayed, selected, show_ids;
467 struct tog_parent_trees parents; /* parent trees of current sub-tree */
468 char *head_ref_name;
469 struct got_repository *repo;
470 struct got_tree_entry *matched_entry;
471 struct tog_colors colors;
472 };
474 struct tog_reflist_entry {
475 TAILQ_ENTRY(tog_reflist_entry) entry;
476 struct got_reference *ref;
477 int idx;
478 };
480 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
482 struct tog_ref_view_state {
483 struct tog_reflist_head refs;
484 struct tog_reflist_entry *first_displayed_entry;
485 struct tog_reflist_entry *last_displayed_entry;
486 struct tog_reflist_entry *selected_entry;
487 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
488 struct got_repository *repo;
489 struct tog_reflist_entry *matched_entry;
490 struct tog_colors colors;
491 };
493 /*
494 * We implement two types of views: parent views and child views.
496 * The 'Tab' key switches focus between a parent view and its child view.
497 * Child views are shown side-by-side to their parent view, provided
498 * there is enough screen estate.
500 * When a new view is opened from within a parent view, this new view
501 * becomes a child view of the parent view, replacing any existing child.
503 * When a new view is opened from within a child view, this new view
504 * becomes a parent view which will obscure the views below until the
505 * user quits the new parent view by typing 'q'.
507 * This list of views contains parent views only.
508 * Child views are only pointed to by their parent view.
509 */
510 TAILQ_HEAD(tog_view_list_head, tog_view);
512 struct tog_view {
513 TAILQ_ENTRY(tog_view) entry;
514 WINDOW *window;
515 PANEL *panel;
516 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
517 int resized_y, resized_x; /* begin_y/x based on user resizing */
518 int maxx, x; /* max column and current start column */
519 int lines, cols; /* copies of LINES and COLS */
520 int nscrolled, offset; /* lines scrolled and hsplit line offset */
521 int ch, count; /* current keymap and count prefix */
522 int resized; /* set when in a resize event */
523 int focussed; /* Only set on one parent or child view at a time. */
524 int dying;
525 struct tog_view *parent;
526 struct tog_view *child;
528 /*
529 * This flag is initially set on parent views when a new child view
530 * is created. It gets toggled when the 'Tab' key switches focus
531 * between parent and child.
532 * The flag indicates whether focus should be passed on to our child
533 * view if this parent view gets picked for focus after another parent
534 * view was closed. This prevents child views from losing focus in such
535 * situations.
536 */
537 int focus_child;
539 enum tog_view_mode mode;
540 /* type-specific state */
541 enum tog_view_type type;
542 union {
543 struct tog_diff_view_state diff;
544 struct tog_log_view_state log;
545 struct tog_blame_view_state blame;
546 struct tog_tree_view_state tree;
547 struct tog_ref_view_state ref;
548 } state;
550 const struct got_error *(*show)(struct tog_view *);
551 const struct got_error *(*input)(struct tog_view **,
552 struct tog_view *, int);
553 const struct got_error *(*reset)(struct tog_view *);
554 const struct got_error *(*resize)(struct tog_view *, int);
555 const struct got_error *(*close)(struct tog_view *);
557 const struct got_error *(*search_start)(struct tog_view *);
558 const struct got_error *(*search_next)(struct tog_view *);
559 int search_started;
560 int searching;
561 #define TOG_SEARCH_FORWARD 1
562 #define TOG_SEARCH_BACKWARD 2
563 int search_next_done;
564 #define TOG_SEARCH_HAVE_MORE 1
565 #define TOG_SEARCH_NO_MORE 2
566 #define TOG_SEARCH_HAVE_NONE 3
567 regex_t regex;
568 regmatch_t regmatch;
569 };
571 static const struct got_error *open_diff_view(struct tog_view *,
572 struct got_object_id *, struct got_object_id *,
573 const char *, const char *, int, int, int, struct tog_view *,
574 struct got_repository *);
575 static const struct got_error *show_diff_view(struct tog_view *);
576 static const struct got_error *input_diff_view(struct tog_view **,
577 struct tog_view *, int);
578 static const struct got_error *reset_diff_view(struct tog_view *);
579 static const struct got_error* close_diff_view(struct tog_view *);
580 static const struct got_error *search_start_diff_view(struct tog_view *);
581 static const struct got_error *search_next_diff_view(struct tog_view *);
583 static const struct got_error *open_log_view(struct tog_view *,
584 struct got_object_id *, struct got_repository *,
585 const char *, const char *, int);
586 static const struct got_error * show_log_view(struct tog_view *);
587 static const struct got_error *input_log_view(struct tog_view **,
588 struct tog_view *, int);
589 static const struct got_error *resize_log_view(struct tog_view *, int);
590 static const struct got_error *close_log_view(struct tog_view *);
591 static const struct got_error *search_start_log_view(struct tog_view *);
592 static const struct got_error *search_next_log_view(struct tog_view *);
594 static const struct got_error *open_blame_view(struct tog_view *, char *,
595 struct got_object_id *, struct got_repository *);
596 static const struct got_error *show_blame_view(struct tog_view *);
597 static const struct got_error *input_blame_view(struct tog_view **,
598 struct tog_view *, int);
599 static const struct got_error *reset_blame_view(struct tog_view *);
600 static const struct got_error *close_blame_view(struct tog_view *);
601 static const struct got_error *search_start_blame_view(struct tog_view *);
602 static const struct got_error *search_next_blame_view(struct tog_view *);
604 static const struct got_error *open_tree_view(struct tog_view *,
605 struct got_object_id *, const char *, struct got_repository *);
606 static const struct got_error *show_tree_view(struct tog_view *);
607 static const struct got_error *input_tree_view(struct tog_view **,
608 struct tog_view *, int);
609 static const struct got_error *close_tree_view(struct tog_view *);
610 static const struct got_error *search_start_tree_view(struct tog_view *);
611 static const struct got_error *search_next_tree_view(struct tog_view *);
613 static const struct got_error *open_ref_view(struct tog_view *,
614 struct got_repository *);
615 static const struct got_error *show_ref_view(struct tog_view *);
616 static const struct got_error *input_ref_view(struct tog_view **,
617 struct tog_view *, int);
618 static const struct got_error *close_ref_view(struct tog_view *);
619 static const struct got_error *search_start_ref_view(struct tog_view *);
620 static const struct got_error *search_next_ref_view(struct tog_view *);
622 static volatile sig_atomic_t tog_sigwinch_received;
623 static volatile sig_atomic_t tog_sigpipe_received;
624 static volatile sig_atomic_t tog_sigcont_received;
625 static volatile sig_atomic_t tog_sigint_received;
626 static volatile sig_atomic_t tog_sigterm_received;
628 static void
629 tog_sigwinch(int signo)
631 tog_sigwinch_received = 1;
634 static void
635 tog_sigpipe(int signo)
637 tog_sigpipe_received = 1;
640 static void
641 tog_sigcont(int signo)
643 tog_sigcont_received = 1;
646 static void
647 tog_sigint(int signo)
649 tog_sigint_received = 1;
652 static void
653 tog_sigterm(int signo)
655 tog_sigterm_received = 1;
658 static int
659 tog_fatal_signal_received(void)
661 return (tog_sigpipe_received ||
662 tog_sigint_received || tog_sigint_received);
665 static const struct got_error *
666 view_close(struct tog_view *view)
668 const struct got_error *err = NULL, *child_err = NULL;
670 if (view->child) {
671 child_err = view_close(view->child);
672 view->child = NULL;
674 if (view->close)
675 err = view->close(view);
676 if (view->panel)
677 del_panel(view->panel);
678 if (view->window)
679 delwin(view->window);
680 free(view);
681 return err ? err : child_err;
684 static struct tog_view *
685 view_open(int nlines, int ncols, int begin_y, int begin_x,
686 enum tog_view_type type)
688 struct tog_view *view = calloc(1, sizeof(*view));
690 if (view == NULL)
691 return NULL;
693 view->type = type;
694 view->lines = LINES;
695 view->cols = COLS;
696 view->nlines = nlines ? nlines : LINES - begin_y;
697 view->ncols = ncols ? ncols : COLS - begin_x;
698 view->begin_y = begin_y;
699 view->begin_x = begin_x;
700 view->window = newwin(nlines, ncols, begin_y, begin_x);
701 if (view->window == NULL) {
702 view_close(view);
703 return NULL;
705 view->panel = new_panel(view->window);
706 if (view->panel == NULL ||
707 set_panel_userptr(view->panel, view) != OK) {
708 view_close(view);
709 return NULL;
712 keypad(view->window, TRUE);
713 return view;
716 static int
717 view_split_begin_x(int begin_x)
719 if (begin_x > 0 || COLS < 120)
720 return 0;
721 return (COLS - MAX(COLS / 2, 80));
724 /* XXX Stub till we decide what to do. */
725 static int
726 view_split_begin_y(int lines)
728 return lines * HSPLIT_SCALE;
731 static const struct got_error *view_resize(struct tog_view *);
733 static const struct got_error *
734 view_splitscreen(struct tog_view *view)
736 const struct got_error *err = NULL;
738 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
739 if (view->resized_y && view->resized_y < view->lines)
740 view->begin_y = view->resized_y;
741 else
742 view->begin_y = view_split_begin_y(view->nlines);
743 view->begin_x = 0;
744 } else if (!view->resized) {
745 if (view->resized_x && view->resized_x < view->cols - 1 &&
746 view->cols > 119)
747 view->begin_x = view->resized_x;
748 else
749 view->begin_x = view_split_begin_x(0);
750 view->begin_y = 0;
752 view->nlines = LINES - view->begin_y;
753 view->ncols = COLS - view->begin_x;
754 view->lines = LINES;
755 view->cols = COLS;
756 err = view_resize(view);
757 if (err)
758 return err;
760 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
761 view->parent->nlines = view->begin_y;
763 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
764 return got_error_from_errno("mvwin");
766 return NULL;
769 static const struct got_error *
770 view_fullscreen(struct tog_view *view)
772 const struct got_error *err = NULL;
774 view->begin_x = 0;
775 view->begin_y = view->resized ? view->begin_y : 0;
776 view->nlines = view->resized ? view->nlines : LINES;
777 view->ncols = COLS;
778 view->lines = LINES;
779 view->cols = COLS;
780 err = view_resize(view);
781 if (err)
782 return err;
784 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
785 return got_error_from_errno("mvwin");
787 return NULL;
790 static int
791 view_is_parent_view(struct tog_view *view)
793 return view->parent == NULL;
796 static int
797 view_is_splitscreen(struct tog_view *view)
799 return view->begin_x > 0 || view->begin_y > 0;
802 static int
803 view_is_fullscreen(struct tog_view *view)
805 return view->nlines == LINES && view->ncols == COLS;
808 static int
809 view_is_hsplit_top(struct tog_view *view)
811 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
812 view_is_splitscreen(view->child);
815 static void
816 view_border(struct tog_view *view)
818 PANEL *panel;
819 const struct tog_view *view_above;
821 if (view->parent)
822 return view_border(view->parent);
824 panel = panel_above(view->panel);
825 if (panel == NULL)
826 return;
828 view_above = panel_userptr(panel);
829 if (view->mode == TOG_VIEW_SPLIT_HRZN)
830 mvwhline(view->window, view_above->begin_y - 1,
831 view->begin_x, got_locale_is_utf8() ?
832 ACS_HLINE : '-', view->ncols);
833 else
834 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
835 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
838 static const struct got_error *view_init_hsplit(struct tog_view *, int);
839 static const struct got_error *request_log_commits(struct tog_view *);
840 static const struct got_error *offset_selection_down(struct tog_view *);
841 static void offset_selection_up(struct tog_view *);
842 static void view_get_split(struct tog_view *, int *, int *);
844 static const struct got_error *
845 view_resize(struct tog_view *view)
847 const struct got_error *err = NULL;
848 int dif, nlines, ncols;
850 dif = LINES - view->lines; /* line difference */
852 if (view->lines > LINES)
853 nlines = view->nlines - (view->lines - LINES);
854 else
855 nlines = view->nlines + (LINES - view->lines);
856 if (view->cols > COLS)
857 ncols = view->ncols - (view->cols - COLS);
858 else
859 ncols = view->ncols + (COLS - view->cols);
861 if (view->child) {
862 int hs = view->child->begin_y;
864 if (!view_is_fullscreen(view))
865 view->child->begin_x = view_split_begin_x(view->begin_x);
866 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
867 view->child->begin_x == 0) {
868 ncols = COLS;
870 view_fullscreen(view->child);
871 if (view->child->focussed)
872 show_panel(view->child->panel);
873 else
874 show_panel(view->panel);
875 } else {
876 ncols = view->child->begin_x;
878 view_splitscreen(view->child);
879 show_panel(view->child->panel);
881 /*
882 * XXX This is ugly and needs to be moved into the above
883 * logic but "works" for now and my attempts at moving it
884 * break either 'tab' or 'F' key maps in horizontal splits.
885 */
886 if (hs) {
887 err = view_splitscreen(view->child);
888 if (err)
889 return err;
890 if (dif < 0) { /* top split decreased */
891 err = offset_selection_down(view);
892 if (err)
893 return err;
895 view_border(view);
896 update_panels();
897 doupdate();
898 show_panel(view->child->panel);
899 nlines = view->nlines;
901 } else if (view->parent == NULL)
902 ncols = COLS;
904 if (view->resize && dif > 0) {
905 err = view->resize(view, dif);
906 if (err)
907 return err;
910 if (wresize(view->window, nlines, ncols) == ERR)
911 return got_error_from_errno("wresize");
912 if (replace_panel(view->panel, view->window) == ERR)
913 return got_error_from_errno("replace_panel");
914 wclear(view->window);
916 view->nlines = nlines;
917 view->ncols = ncols;
918 view->lines = LINES;
919 view->cols = COLS;
921 return NULL;
924 static const struct got_error *
925 resize_log_view(struct tog_view *view, int increase)
927 struct tog_log_view_state *s = &view->state.log;
928 const struct got_error *err = NULL;
929 int n = 0;
931 if (s->selected_entry)
932 n = s->selected_entry->idx + view->lines - s->selected;
934 /*
935 * Request commits to account for the increased
936 * height so we have enough to populate the view.
937 */
938 if (s->commits.ncommits < n) {
939 view->nscrolled = n - s->commits.ncommits + increase + 1;
940 err = request_log_commits(view);
943 return err;
946 static void
947 view_adjust_offset(struct tog_view *view, int n)
949 if (n == 0)
950 return;
952 if (view->parent && view->parent->offset) {
953 if (view->parent->offset + n >= 0)
954 view->parent->offset += n;
955 else
956 view->parent->offset = 0;
957 } else if (view->offset) {
958 if (view->offset - n >= 0)
959 view->offset -= n;
960 else
961 view->offset = 0;
965 static const struct got_error *
966 view_resize_split(struct tog_view *view, int resize)
968 const struct got_error *err = NULL;
969 struct tog_view *v = NULL;
971 if (view->parent)
972 v = view->parent;
973 else
974 v = view;
976 if (!v->child || !view_is_splitscreen(v->child))
977 return NULL;
979 v->resized = v->child->resized = resize; /* lock for resize event */
981 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
982 if (v->child->resized_y)
983 v->child->begin_y = v->child->resized_y;
984 if (view->parent)
985 v->child->begin_y -= resize;
986 else
987 v->child->begin_y += resize;
988 if (v->child->begin_y < 3) {
989 view->count = 0;
990 v->child->begin_y = 3;
991 } else if (v->child->begin_y > LINES - 1) {
992 view->count = 0;
993 v->child->begin_y = LINES - 1;
995 v->ncols = COLS;
996 v->child->ncols = COLS;
997 view_adjust_offset(view, resize);
998 err = view_init_hsplit(v, v->child->begin_y);
999 if (err)
1000 return err;
1001 v->child->resized_y = v->child->begin_y;
1002 } else {
1003 if (v->child->resized_x)
1004 v->child->begin_x = v->child->resized_x;
1005 if (view->parent)
1006 v->child->begin_x -= resize;
1007 else
1008 v->child->begin_x += resize;
1009 if (v->child->begin_x < 11) {
1010 view->count = 0;
1011 v->child->begin_x = 11;
1012 } else if (v->child->begin_x > COLS - 1) {
1013 view->count = 0;
1014 v->child->begin_x = COLS - 1;
1016 v->child->resized_x = v->child->begin_x;
1019 v->child->mode = v->mode;
1020 v->child->nlines = v->lines - v->child->begin_y;
1021 v->child->ncols = v->cols - v->child->begin_x;
1022 v->focus_child = 1;
1024 err = view_fullscreen(v);
1025 if (err)
1026 return err;
1027 err = view_splitscreen(v->child);
1028 if (err)
1029 return err;
1031 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1032 err = offset_selection_down(v->child);
1033 if (err)
1034 return err;
1037 if (v->resize)
1038 err = v->resize(v, 0);
1039 else if (v->child->resize)
1040 err = v->child->resize(v->child, 0);
1042 v->resized = v->child->resized = 0;
1044 return err;
1047 static void
1048 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1050 struct tog_view *v = src->child ? src->child : src;
1052 dst->resized_x = v->resized_x;
1053 dst->resized_y = v->resized_y;
1056 static const struct got_error *
1057 view_close_child(struct tog_view *view)
1059 const struct got_error *err = NULL;
1061 if (view->child == NULL)
1062 return NULL;
1064 err = view_close(view->child);
1065 view->child = NULL;
1066 return err;
1069 static const struct got_error *
1070 view_set_child(struct tog_view *view, struct tog_view *child)
1072 const struct got_error *err = NULL;
1074 view->child = child;
1075 child->parent = view;
1077 err = view_resize(view);
1078 if (err)
1079 return err;
1081 if (view->child->resized_x || view->child->resized_y)
1082 err = view_resize_split(view, 0);
1084 return err;
1087 static const struct got_error *view_dispatch_request(struct tog_view **,
1088 struct tog_view *, enum tog_view_type, int, int);
1090 static const struct got_error *
1091 view_request_new(struct tog_view **requested, struct tog_view *view,
1092 enum tog_view_type request)
1094 struct tog_view *new_view = NULL;
1095 const struct got_error *err;
1096 int y = 0, x = 0;
1098 *requested = NULL;
1100 if (view_is_parent_view(view))
1101 view_get_split(view, &y, &x);
1103 err = view_dispatch_request(&new_view, view, request, y, x);
1104 if (err)
1105 return err;
1107 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN) {
1108 err = view_init_hsplit(view, y);
1109 if (err)
1110 return err;
1113 view->focussed = 0;
1114 new_view->focussed = 1;
1115 new_view->mode = view->mode;
1116 new_view->nlines = view->lines - y;
1118 if (view_is_parent_view(view)) {
1119 view_transfer_size(new_view, view);
1120 err = view_close_child(view);
1121 if (err)
1122 return err;
1123 err = view_set_child(view, new_view);
1124 if (err)
1125 return err;
1126 view->focus_child = 1;
1127 } else
1128 *requested = new_view;
1130 return NULL;
1133 static void
1134 tog_resizeterm(void)
1136 int cols, lines;
1137 struct winsize size;
1139 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1140 cols = 80; /* Default */
1141 lines = 24;
1142 } else {
1143 cols = size.ws_col;
1144 lines = size.ws_row;
1146 resize_term(lines, cols);
1149 static const struct got_error *
1150 view_search_start(struct tog_view *view)
1152 const struct got_error *err = NULL;
1153 struct tog_view *v = view;
1154 char pattern[1024];
1155 int ret;
1157 if (view->search_started) {
1158 regfree(&view->regex);
1159 view->searching = 0;
1160 memset(&view->regmatch, 0, sizeof(view->regmatch));
1162 view->search_started = 0;
1164 if (view->nlines < 1)
1165 return NULL;
1167 if (view_is_hsplit_top(view))
1168 v = view->child;
1170 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1171 wclrtoeol(v->window);
1173 nodelay(view->window, FALSE); /* block for search term input */
1174 nocbreak();
1175 echo();
1176 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1177 wrefresh(v->window);
1178 cbreak();
1179 noecho();
1180 nodelay(view->window, TRUE);
1181 if (ret == ERR)
1182 return NULL;
1184 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1185 err = view->search_start(view);
1186 if (err) {
1187 regfree(&view->regex);
1188 return err;
1190 view->search_started = 1;
1191 view->searching = TOG_SEARCH_FORWARD;
1192 view->search_next_done = 0;
1193 view->search_next(view);
1196 return NULL;
1199 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1200 static const struct got_error *
1201 switch_split(struct tog_view *view)
1203 const struct got_error *err = NULL;
1204 struct tog_view *v = NULL;
1206 if (view->parent)
1207 v = view->parent;
1208 else
1209 v = view;
1211 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1212 v->mode = TOG_VIEW_SPLIT_VERT;
1213 else
1214 v->mode = TOG_VIEW_SPLIT_HRZN;
1216 if (!v->child)
1217 return NULL;
1218 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1219 v->mode = TOG_VIEW_SPLIT_NONE;
1221 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1222 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1223 v->child->begin_y = v->child->resized_y;
1224 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1225 v->child->begin_x = v->child->resized_x;
1228 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1229 v->ncols = COLS;
1230 v->child->ncols = COLS;
1231 v->child->nscrolled = LINES - v->child->nlines;
1233 err = view_init_hsplit(v, v->child->begin_y);
1234 if (err)
1235 return err;
1237 v->child->mode = v->mode;
1238 v->child->nlines = v->lines - v->child->begin_y;
1239 v->focus_child = 1;
1241 err = view_fullscreen(v);
1242 if (err)
1243 return err;
1244 err = view_splitscreen(v->child);
1245 if (err)
1246 return err;
1248 if (v->mode == TOG_VIEW_SPLIT_NONE)
1249 v->mode = TOG_VIEW_SPLIT_VERT;
1250 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1251 err = offset_selection_down(v);
1252 if (err)
1253 return err;
1254 err = offset_selection_down(v->child);
1255 if (err)
1256 return err;
1257 } else {
1258 offset_selection_up(v);
1259 offset_selection_up(v->child);
1261 if (v->resize)
1262 err = v->resize(v, 0);
1263 else if (v->child->resize)
1264 err = v->child->resize(v->child, 0);
1266 return err;
1270 * Compute view->count from numeric input. Assign total to view->count and
1271 * return first non-numeric key entered.
1273 static int
1274 get_compound_key(struct tog_view *view, int c)
1276 struct tog_view *v = view;
1277 int x, n = 0;
1279 if (view_is_hsplit_top(view))
1280 v = view->child;
1281 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1282 v = view->parent;
1284 view->count = 0;
1285 cbreak(); /* block for input */
1286 wmove(v->window, v->nlines - 1, 0);
1287 wclrtoeol(v->window);
1288 waddch(v->window, ':');
1290 do {
1291 x = getcurx(v->window);
1292 if (x != ERR && x < view->ncols) {
1293 waddch(v->window, c);
1294 wrefresh(v->window);
1298 * Don't overflow. Max valid request should be the greatest
1299 * between the longest and total lines; cap at 10 million.
1301 if (n >= 9999999)
1302 n = 9999999;
1303 else
1304 n = n * 10 + (c - '0');
1305 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1307 /* Massage excessive or inapplicable values at the input handler. */
1308 view->count = n;
1310 return c;
1313 static const struct got_error *
1314 view_input(struct tog_view **new, int *done, struct tog_view *view,
1315 struct tog_view_list_head *views)
1317 const struct got_error *err = NULL;
1318 struct tog_view *v;
1319 int ch, errcode;
1321 *new = NULL;
1323 /* Clear "no matches" indicator. */
1324 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1325 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1326 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1327 view->count = 0;
1330 if (view->searching && !view->search_next_done) {
1331 errcode = pthread_mutex_unlock(&tog_mutex);
1332 if (errcode)
1333 return got_error_set_errno(errcode,
1334 "pthread_mutex_unlock");
1335 sched_yield();
1336 errcode = pthread_mutex_lock(&tog_mutex);
1337 if (errcode)
1338 return got_error_set_errno(errcode,
1339 "pthread_mutex_lock");
1340 view->search_next(view);
1341 return NULL;
1344 nodelay(view->window, FALSE);
1345 /* Allow threads to make progress while we are waiting for input. */
1346 errcode = pthread_mutex_unlock(&tog_mutex);
1347 if (errcode)
1348 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1349 /* If we have an unfinished count, let C-g or backspace abort. */
1350 if (view->count && --view->count) {
1351 cbreak();
1352 nodelay(view->window, TRUE);
1353 ch = wgetch(view->window);
1354 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1355 view->count = 0;
1356 else
1357 ch = view->ch;
1358 } else {
1359 ch = wgetch(view->window);
1360 if (ch >= '1' && ch <= '9')
1361 view->ch = ch = get_compound_key(view, ch);
1363 errcode = pthread_mutex_lock(&tog_mutex);
1364 if (errcode)
1365 return got_error_set_errno(errcode, "pthread_mutex_lock");
1366 nodelay(view->window, TRUE);
1368 if (tog_sigwinch_received || tog_sigcont_received) {
1369 tog_resizeterm();
1370 tog_sigwinch_received = 0;
1371 tog_sigcont_received = 0;
1372 TAILQ_FOREACH(v, views, entry) {
1373 err = view_resize(v);
1374 if (err)
1375 return err;
1376 err = v->input(new, v, KEY_RESIZE);
1377 if (err)
1378 return err;
1379 if (v->child) {
1380 err = view_resize(v->child);
1381 if (err)
1382 return err;
1383 err = v->child->input(new, v->child,
1384 KEY_RESIZE);
1385 if (err)
1386 return err;
1387 if (v->child->resized_x || v->child->resized_y) {
1388 err = view_resize_split(v, 0);
1389 if (err)
1390 return err;
1396 switch (ch) {
1397 case '\t':
1398 view->count = 0;
1399 if (view->child) {
1400 view->focussed = 0;
1401 view->child->focussed = 1;
1402 view->focus_child = 1;
1403 } else if (view->parent) {
1404 view->focussed = 0;
1405 view->parent->focussed = 1;
1406 view->parent->focus_child = 0;
1407 if (!view_is_splitscreen(view)) {
1408 if (view->parent->resize) {
1409 err = view->parent->resize(view->parent,
1410 0);
1411 if (err)
1412 return err;
1414 offset_selection_up(view->parent);
1415 err = view_fullscreen(view->parent);
1416 if (err)
1417 return err;
1420 break;
1421 case 'q':
1422 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1423 if (view->parent->resize) {
1424 /* might need more commits to fill fullscreen */
1425 err = view->parent->resize(view->parent, 0);
1426 if (err)
1427 break;
1429 offset_selection_up(view->parent);
1431 err = view->input(new, view, ch);
1432 view->dying = 1;
1433 break;
1434 case 'Q':
1435 *done = 1;
1436 break;
1437 case 'F':
1438 view->count = 0;
1439 if (view_is_parent_view(view)) {
1440 if (view->child == NULL)
1441 break;
1442 if (view_is_splitscreen(view->child)) {
1443 view->focussed = 0;
1444 view->child->focussed = 1;
1445 err = view_fullscreen(view->child);
1446 } else {
1447 err = view_splitscreen(view->child);
1448 if (!err)
1449 err = view_resize_split(view, 0);
1451 if (err)
1452 break;
1453 err = view->child->input(new, view->child,
1454 KEY_RESIZE);
1455 } else {
1456 if (view_is_splitscreen(view)) {
1457 view->parent->focussed = 0;
1458 view->focussed = 1;
1459 err = view_fullscreen(view);
1460 } else {
1461 err = view_splitscreen(view);
1462 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1463 err = view_resize(view->parent);
1464 if (!err)
1465 err = view_resize_split(view, 0);
1467 if (err)
1468 break;
1469 err = view->input(new, view, KEY_RESIZE);
1471 if (err)
1472 break;
1473 if (view->resize) {
1474 err = view->resize(view, 0);
1475 if (err)
1476 break;
1478 if (view->parent)
1479 err = offset_selection_down(view->parent);
1480 if (!err)
1481 err = offset_selection_down(view);
1482 break;
1483 case 'S':
1484 view->count = 0;
1485 err = switch_split(view);
1486 break;
1487 case '-':
1488 err = view_resize_split(view, -1);
1489 break;
1490 case '+':
1491 err = view_resize_split(view, 1);
1492 break;
1493 case KEY_RESIZE:
1494 break;
1495 case '/':
1496 view->count = 0;
1497 if (view->search_start)
1498 view_search_start(view);
1499 else
1500 err = view->input(new, view, ch);
1501 break;
1502 case 'N':
1503 case 'n':
1504 if (view->search_started && view->search_next) {
1505 view->searching = (ch == 'n' ?
1506 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1507 view->search_next_done = 0;
1508 view->search_next(view);
1509 } else
1510 err = view->input(new, view, ch);
1511 break;
1512 case 'A':
1513 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1514 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1515 else
1516 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1517 TAILQ_FOREACH(v, views, entry) {
1518 if (v->reset) {
1519 err = v->reset(v);
1520 if (err)
1521 return err;
1523 if (v->child && v->child->reset) {
1524 err = v->child->reset(v->child);
1525 if (err)
1526 return err;
1529 break;
1530 default:
1531 err = view->input(new, view, ch);
1532 break;
1535 return err;
1538 static int
1539 view_needs_focus_indication(struct tog_view *view)
1541 if (view_is_parent_view(view)) {
1542 if (view->child == NULL || view->child->focussed)
1543 return 0;
1544 if (!view_is_splitscreen(view->child))
1545 return 0;
1546 } else if (!view_is_splitscreen(view))
1547 return 0;
1549 return view->focussed;
1552 static const struct got_error *
1553 view_loop(struct tog_view *view)
1555 const struct got_error *err = NULL;
1556 struct tog_view_list_head views;
1557 struct tog_view *new_view;
1558 char *mode;
1559 int fast_refresh = 10;
1560 int done = 0, errcode;
1562 mode = getenv("TOG_VIEW_SPLIT_MODE");
1563 if (!mode || !(*mode == 'h' || *mode == 'H'))
1564 view->mode = TOG_VIEW_SPLIT_VERT;
1565 else
1566 view->mode = TOG_VIEW_SPLIT_HRZN;
1568 errcode = pthread_mutex_lock(&tog_mutex);
1569 if (errcode)
1570 return got_error_set_errno(errcode, "pthread_mutex_lock");
1572 TAILQ_INIT(&views);
1573 TAILQ_INSERT_HEAD(&views, view, entry);
1575 view->focussed = 1;
1576 err = view->show(view);
1577 if (err)
1578 return err;
1579 update_panels();
1580 doupdate();
1581 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1582 !tog_fatal_signal_received()) {
1583 /* Refresh fast during initialization, then become slower. */
1584 if (fast_refresh && fast_refresh-- == 0)
1585 halfdelay(10); /* switch to once per second */
1587 err = view_input(&new_view, &done, view, &views);
1588 if (err)
1589 break;
1590 if (view->dying) {
1591 struct tog_view *v, *prev = NULL;
1593 if (view_is_parent_view(view))
1594 prev = TAILQ_PREV(view, tog_view_list_head,
1595 entry);
1596 else if (view->parent)
1597 prev = view->parent;
1599 if (view->parent) {
1600 view->parent->child = NULL;
1601 view->parent->focus_child = 0;
1602 /* Restore fullscreen line height. */
1603 view->parent->nlines = view->parent->lines;
1604 err = view_resize(view->parent);
1605 if (err)
1606 break;
1607 /* Make resized splits persist. */
1608 view_transfer_size(view->parent, view);
1609 } else
1610 TAILQ_REMOVE(&views, view, entry);
1612 err = view_close(view);
1613 if (err)
1614 goto done;
1616 view = NULL;
1617 TAILQ_FOREACH(v, &views, entry) {
1618 if (v->focussed)
1619 break;
1621 if (view == NULL && new_view == NULL) {
1622 /* No view has focus. Try to pick one. */
1623 if (prev)
1624 view = prev;
1625 else if (!TAILQ_EMPTY(&views)) {
1626 view = TAILQ_LAST(&views,
1627 tog_view_list_head);
1629 if (view) {
1630 if (view->focus_child) {
1631 view->child->focussed = 1;
1632 view = view->child;
1633 } else
1634 view->focussed = 1;
1638 if (new_view) {
1639 struct tog_view *v, *t;
1640 /* Only allow one parent view per type. */
1641 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1642 if (v->type != new_view->type)
1643 continue;
1644 TAILQ_REMOVE(&views, v, entry);
1645 err = view_close(v);
1646 if (err)
1647 goto done;
1648 break;
1650 TAILQ_INSERT_TAIL(&views, new_view, entry);
1651 view = new_view;
1653 if (view) {
1654 if (view_is_parent_view(view)) {
1655 if (view->child && view->child->focussed)
1656 view = view->child;
1657 } else {
1658 if (view->parent && view->parent->focussed)
1659 view = view->parent;
1661 show_panel(view->panel);
1662 if (view->child && view_is_splitscreen(view->child))
1663 show_panel(view->child->panel);
1664 if (view->parent && view_is_splitscreen(view)) {
1665 err = view->parent->show(view->parent);
1666 if (err)
1667 goto done;
1669 err = view->show(view);
1670 if (err)
1671 goto done;
1672 if (view->child) {
1673 err = view->child->show(view->child);
1674 if (err)
1675 goto done;
1677 update_panels();
1678 doupdate();
1681 done:
1682 while (!TAILQ_EMPTY(&views)) {
1683 const struct got_error *close_err;
1684 view = TAILQ_FIRST(&views);
1685 TAILQ_REMOVE(&views, view, entry);
1686 close_err = view_close(view);
1687 if (close_err && err == NULL)
1688 err = close_err;
1691 errcode = pthread_mutex_unlock(&tog_mutex);
1692 if (errcode && err == NULL)
1693 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1695 return err;
1698 __dead static void
1699 usage_log(void)
1701 endwin();
1702 fprintf(stderr,
1703 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1704 getprogname());
1705 exit(1);
1708 /* Create newly allocated wide-character string equivalent to a byte string. */
1709 static const struct got_error *
1710 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1712 char *vis = NULL;
1713 const struct got_error *err = NULL;
1715 *ws = NULL;
1716 *wlen = mbstowcs(NULL, s, 0);
1717 if (*wlen == (size_t)-1) {
1718 int vislen;
1719 if (errno != EILSEQ)
1720 return got_error_from_errno("mbstowcs");
1722 /* byte string invalid in current encoding; try to "fix" it */
1723 err = got_mbsavis(&vis, &vislen, s);
1724 if (err)
1725 return err;
1726 *wlen = mbstowcs(NULL, vis, 0);
1727 if (*wlen == (size_t)-1) {
1728 err = got_error_from_errno("mbstowcs"); /* give up */
1729 goto done;
1733 *ws = calloc(*wlen + 1, sizeof(**ws));
1734 if (*ws == NULL) {
1735 err = got_error_from_errno("calloc");
1736 goto done;
1739 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1740 err = got_error_from_errno("mbstowcs");
1741 done:
1742 free(vis);
1743 if (err) {
1744 free(*ws);
1745 *ws = NULL;
1746 *wlen = 0;
1748 return err;
1751 static const struct got_error *
1752 expand_tab(char **ptr, const char *src)
1754 char *dst;
1755 size_t len, n, idx = 0, sz = 0;
1757 *ptr = NULL;
1758 n = len = strlen(src);
1759 dst = malloc(n + 1);
1760 if (dst == NULL)
1761 return got_error_from_errno("malloc");
1763 while (idx < len && src[idx]) {
1764 const char c = src[idx];
1766 if (c == '\t') {
1767 size_t nb = TABSIZE - sz % TABSIZE;
1768 char *p;
1770 p = realloc(dst, n + nb);
1771 if (p == NULL) {
1772 free(dst);
1773 return got_error_from_errno("realloc");
1776 dst = p;
1777 n += nb;
1778 memset(dst + sz, ' ', nb);
1779 sz += nb;
1780 } else
1781 dst[sz++] = src[idx];
1782 ++idx;
1785 dst[sz] = '\0';
1786 *ptr = dst;
1787 return NULL;
1791 * Advance at most n columns from wline starting at offset off.
1792 * Return the index to the first character after the span operation.
1793 * Return the combined column width of all spanned wide character in
1794 * *rcol.
1796 static int
1797 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1799 int width, i, cols = 0;
1801 if (n == 0) {
1802 *rcol = cols;
1803 return off;
1806 for (i = off; wline[i] != L'\0'; ++i) {
1807 if (wline[i] == L'\t')
1808 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1809 else
1810 width = wcwidth(wline[i]);
1812 if (width == -1) {
1813 width = 1;
1814 wline[i] = L'.';
1817 if (cols + width > n)
1818 break;
1819 cols += width;
1822 *rcol = cols;
1823 return i;
1827 * Format a line for display, ensuring that it won't overflow a width limit.
1828 * With scrolling, the width returned refers to the scrolled version of the
1829 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1831 static const struct got_error *
1832 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1833 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1835 const struct got_error *err = NULL;
1836 int cols;
1837 wchar_t *wline = NULL;
1838 char *exstr = NULL;
1839 size_t wlen;
1840 int i, scrollx;
1842 *wlinep = NULL;
1843 *widthp = 0;
1845 if (expand) {
1846 err = expand_tab(&exstr, line);
1847 if (err)
1848 return err;
1851 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1852 free(exstr);
1853 if (err)
1854 return err;
1856 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1858 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1859 wline[wlen - 1] = L'\0';
1860 wlen--;
1862 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1863 wline[wlen - 1] = L'\0';
1864 wlen--;
1867 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1868 wline[i] = L'\0';
1870 if (widthp)
1871 *widthp = cols;
1872 if (scrollxp)
1873 *scrollxp = scrollx;
1874 if (err)
1875 free(wline);
1876 else
1877 *wlinep = wline;
1878 return err;
1881 static const struct got_error*
1882 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1883 struct got_object_id *id, struct got_repository *repo)
1885 static const struct got_error *err = NULL;
1886 struct got_reflist_entry *re;
1887 char *s;
1888 const char *name;
1890 *refs_str = NULL;
1892 TAILQ_FOREACH(re, refs, entry) {
1893 struct got_tag_object *tag = NULL;
1894 struct got_object_id *ref_id;
1895 int cmp;
1897 name = got_ref_get_name(re->ref);
1898 if (strcmp(name, GOT_REF_HEAD) == 0)
1899 continue;
1900 if (strncmp(name, "refs/", 5) == 0)
1901 name += 5;
1902 if (strncmp(name, "got/", 4) == 0 &&
1903 strncmp(name, "got/backup/", 11) != 0)
1904 continue;
1905 if (strncmp(name, "heads/", 6) == 0)
1906 name += 6;
1907 if (strncmp(name, "remotes/", 8) == 0) {
1908 name += 8;
1909 s = strstr(name, "/" GOT_REF_HEAD);
1910 if (s != NULL && s[strlen(s)] == '\0')
1911 continue;
1913 err = got_ref_resolve(&ref_id, repo, re->ref);
1914 if (err)
1915 break;
1916 if (strncmp(name, "tags/", 5) == 0) {
1917 err = got_object_open_as_tag(&tag, repo, ref_id);
1918 if (err) {
1919 if (err->code != GOT_ERR_OBJ_TYPE) {
1920 free(ref_id);
1921 break;
1923 /* Ref points at something other than a tag. */
1924 err = NULL;
1925 tag = NULL;
1928 cmp = got_object_id_cmp(tag ?
1929 got_object_tag_get_object_id(tag) : ref_id, id);
1930 free(ref_id);
1931 if (tag)
1932 got_object_tag_close(tag);
1933 if (cmp != 0)
1934 continue;
1935 s = *refs_str;
1936 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1937 s ? ", " : "", name) == -1) {
1938 err = got_error_from_errno("asprintf");
1939 free(s);
1940 *refs_str = NULL;
1941 break;
1943 free(s);
1946 return err;
1949 static const struct got_error *
1950 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1951 int col_tab_align)
1953 char *smallerthan;
1955 smallerthan = strchr(author, '<');
1956 if (smallerthan && smallerthan[1] != '\0')
1957 author = smallerthan + 1;
1958 author[strcspn(author, "@>")] = '\0';
1959 return format_line(wauthor, author_width, NULL, author, 0, limit,
1960 col_tab_align, 0);
1963 static const struct got_error *
1964 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1965 struct got_object_id *id, const size_t date_display_cols,
1966 int author_display_cols)
1968 struct tog_log_view_state *s = &view->state.log;
1969 const struct got_error *err = NULL;
1970 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1971 char *logmsg0 = NULL, *logmsg = NULL;
1972 char *author = NULL;
1973 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1974 int author_width, logmsg_width;
1975 char *newline, *line = NULL;
1976 int col, limit, scrollx;
1977 const int avail = view->ncols;
1978 struct tm tm;
1979 time_t committer_time;
1980 struct tog_color *tc;
1982 committer_time = got_object_commit_get_committer_time(commit);
1983 if (gmtime_r(&committer_time, &tm) == NULL)
1984 return got_error_from_errno("gmtime_r");
1985 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1986 return got_error(GOT_ERR_NO_SPACE);
1988 if (avail <= date_display_cols)
1989 limit = MIN(sizeof(datebuf) - 1, avail);
1990 else
1991 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1992 tc = get_color(&s->colors, TOG_COLOR_DATE);
1993 if (tc)
1994 wattr_on(view->window,
1995 COLOR_PAIR(tc->colorpair), NULL);
1996 waddnstr(view->window, datebuf, limit);
1997 if (tc)
1998 wattr_off(view->window,
1999 COLOR_PAIR(tc->colorpair), NULL);
2000 col = limit;
2001 if (col > avail)
2002 goto done;
2004 if (avail >= 120) {
2005 char *id_str;
2006 err = got_object_id_str(&id_str, id);
2007 if (err)
2008 goto done;
2009 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2010 if (tc)
2011 wattr_on(view->window,
2012 COLOR_PAIR(tc->colorpair), NULL);
2013 wprintw(view->window, "%.8s ", id_str);
2014 if (tc)
2015 wattr_off(view->window,
2016 COLOR_PAIR(tc->colorpair), NULL);
2017 free(id_str);
2018 col += 9;
2019 if (col > avail)
2020 goto done;
2023 if (s->use_committer)
2024 author = strdup(got_object_commit_get_committer(commit));
2025 else
2026 author = strdup(got_object_commit_get_author(commit));
2027 if (author == NULL) {
2028 err = got_error_from_errno("strdup");
2029 goto done;
2031 err = format_author(&wauthor, &author_width, author, avail - col, col);
2032 if (err)
2033 goto done;
2034 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2035 if (tc)
2036 wattr_on(view->window,
2037 COLOR_PAIR(tc->colorpair), NULL);
2038 waddwstr(view->window, wauthor);
2039 if (tc)
2040 wattr_off(view->window,
2041 COLOR_PAIR(tc->colorpair), NULL);
2042 col += author_width;
2043 while (col < avail && author_width < author_display_cols + 2) {
2044 waddch(view->window, ' ');
2045 col++;
2046 author_width++;
2048 if (col > avail)
2049 goto done;
2051 err = got_object_commit_get_logmsg(&logmsg0, commit);
2052 if (err)
2053 goto done;
2054 logmsg = logmsg0;
2055 while (*logmsg == '\n')
2056 logmsg++;
2057 newline = strchr(logmsg, '\n');
2058 if (newline)
2059 *newline = '\0';
2060 limit = avail - col;
2061 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2062 limit--; /* for the border */
2063 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2064 limit, col, 1);
2065 if (err)
2066 goto done;
2067 waddwstr(view->window, &wlogmsg[scrollx]);
2068 col += MAX(logmsg_width, 0);
2069 while (col < avail) {
2070 waddch(view->window, ' ');
2071 col++;
2073 done:
2074 free(logmsg0);
2075 free(wlogmsg);
2076 free(author);
2077 free(wauthor);
2078 free(line);
2079 return err;
2082 static struct commit_queue_entry *
2083 alloc_commit_queue_entry(struct got_commit_object *commit,
2084 struct got_object_id *id)
2086 struct commit_queue_entry *entry;
2088 entry = calloc(1, sizeof(*entry));
2089 if (entry == NULL)
2090 return NULL;
2092 entry->id = id;
2093 entry->commit = commit;
2094 return entry;
2097 static void
2098 pop_commit(struct commit_queue *commits)
2100 struct commit_queue_entry *entry;
2102 entry = TAILQ_FIRST(&commits->head);
2103 TAILQ_REMOVE(&commits->head, entry, entry);
2104 got_object_commit_close(entry->commit);
2105 commits->ncommits--;
2106 /* Don't free entry->id! It is owned by the commit graph. */
2107 free(entry);
2110 static void
2111 free_commits(struct commit_queue *commits)
2113 while (!TAILQ_EMPTY(&commits->head))
2114 pop_commit(commits);
2117 static const struct got_error *
2118 match_commit(int *have_match, struct got_object_id *id,
2119 struct got_commit_object *commit, regex_t *regex)
2121 const struct got_error *err = NULL;
2122 regmatch_t regmatch;
2123 char *id_str = NULL, *logmsg = NULL;
2125 *have_match = 0;
2127 err = got_object_id_str(&id_str, id);
2128 if (err)
2129 return err;
2131 err = got_object_commit_get_logmsg(&logmsg, commit);
2132 if (err)
2133 goto done;
2135 if (regexec(regex, got_object_commit_get_author(commit), 1,
2136 &regmatch, 0) == 0 ||
2137 regexec(regex, got_object_commit_get_committer(commit), 1,
2138 &regmatch, 0) == 0 ||
2139 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2140 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2141 *have_match = 1;
2142 done:
2143 free(id_str);
2144 free(logmsg);
2145 return err;
2148 static const struct got_error *
2149 queue_commits(struct tog_log_thread_args *a)
2151 const struct got_error *err = NULL;
2154 * We keep all commits open throughout the lifetime of the log
2155 * view in order to avoid having to re-fetch commits from disk
2156 * while updating the display.
2158 do {
2159 struct got_object_id *id;
2160 struct got_commit_object *commit;
2161 struct commit_queue_entry *entry;
2162 int errcode;
2164 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2165 NULL, NULL);
2166 if (err || id == NULL)
2167 break;
2169 err = got_object_open_as_commit(&commit, a->repo, id);
2170 if (err)
2171 break;
2172 entry = alloc_commit_queue_entry(commit, id);
2173 if (entry == NULL) {
2174 err = got_error_from_errno("alloc_commit_queue_entry");
2175 break;
2178 errcode = pthread_mutex_lock(&tog_mutex);
2179 if (errcode) {
2180 err = got_error_set_errno(errcode,
2181 "pthread_mutex_lock");
2182 break;
2185 entry->idx = a->commits->ncommits;
2186 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2187 a->commits->ncommits++;
2189 if (*a->searching == TOG_SEARCH_FORWARD &&
2190 !*a->search_next_done) {
2191 int have_match;
2192 err = match_commit(&have_match, id, commit, a->regex);
2193 if (err)
2194 break;
2195 if (have_match)
2196 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2199 errcode = pthread_mutex_unlock(&tog_mutex);
2200 if (errcode && err == NULL)
2201 err = got_error_set_errno(errcode,
2202 "pthread_mutex_unlock");
2203 if (err)
2204 break;
2205 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2207 return err;
2210 static void
2211 select_commit(struct tog_log_view_state *s)
2213 struct commit_queue_entry *entry;
2214 int ncommits = 0;
2216 entry = s->first_displayed_entry;
2217 while (entry) {
2218 if (ncommits == s->selected) {
2219 s->selected_entry = entry;
2220 break;
2222 entry = TAILQ_NEXT(entry, entry);
2223 ncommits++;
2227 static const struct got_error *
2228 draw_commits(struct tog_view *view)
2230 const struct got_error *err = NULL;
2231 struct tog_log_view_state *s = &view->state.log;
2232 struct commit_queue_entry *entry = s->selected_entry;
2233 const int limit = view->nlines;
2234 int width;
2235 int ncommits, author_cols = 4;
2236 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2237 char *refs_str = NULL;
2238 wchar_t *wline;
2239 struct tog_color *tc;
2240 static const size_t date_display_cols = 12;
2242 if (s->selected_entry &&
2243 !(view->searching && view->search_next_done == 0)) {
2244 struct got_reflist_head *refs;
2245 err = got_object_id_str(&id_str, s->selected_entry->id);
2246 if (err)
2247 return err;
2248 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2249 s->selected_entry->id);
2250 if (refs) {
2251 err = build_refs_str(&refs_str, refs,
2252 s->selected_entry->id, s->repo);
2253 if (err)
2254 goto done;
2258 if (s->thread_args.commits_needed == 0)
2259 halfdelay(10); /* disable fast refresh */
2261 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2262 if (asprintf(&ncommits_str, " [%d/%d] %s",
2263 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2264 (view->searching && !view->search_next_done) ?
2265 "searching..." : "loading...") == -1) {
2266 err = got_error_from_errno("asprintf");
2267 goto done;
2269 } else {
2270 const char *search_str = NULL;
2272 if (view->searching) {
2273 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2274 search_str = "no more matches";
2275 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2276 search_str = "no matches found";
2277 else if (!view->search_next_done)
2278 search_str = "searching...";
2281 if (asprintf(&ncommits_str, " [%d/%d] %s",
2282 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2283 search_str ? search_str :
2284 (refs_str ? refs_str : "")) == -1) {
2285 err = got_error_from_errno("asprintf");
2286 goto done;
2290 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2291 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2292 "........................................",
2293 s->in_repo_path, ncommits_str) == -1) {
2294 err = got_error_from_errno("asprintf");
2295 header = NULL;
2296 goto done;
2298 } else if (asprintf(&header, "commit %s%s",
2299 id_str ? id_str : "........................................",
2300 ncommits_str) == -1) {
2301 err = got_error_from_errno("asprintf");
2302 header = NULL;
2303 goto done;
2305 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2306 if (err)
2307 goto done;
2309 werase(view->window);
2311 if (view_needs_focus_indication(view))
2312 wstandout(view->window);
2313 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2314 if (tc)
2315 wattr_on(view->window,
2316 COLOR_PAIR(tc->colorpair), NULL);
2317 waddwstr(view->window, wline);
2318 if (tc)
2319 wattr_off(view->window,
2320 COLOR_PAIR(tc->colorpair), NULL);
2321 while (width < view->ncols) {
2322 waddch(view->window, ' ');
2323 width++;
2325 if (view_needs_focus_indication(view))
2326 wstandend(view->window);
2327 free(wline);
2328 if (limit <= 1)
2329 goto done;
2331 /* Grow author column size if necessary, and set view->maxx. */
2332 entry = s->first_displayed_entry;
2333 ncommits = 0;
2334 view->maxx = 0;
2335 while (entry) {
2336 struct got_commit_object *c = entry->commit;
2337 char *author, *eol, *msg, *msg0;
2338 wchar_t *wauthor, *wmsg;
2339 int width;
2340 if (ncommits >= limit - 1)
2341 break;
2342 if (s->use_committer)
2343 author = strdup(got_object_commit_get_committer(c));
2344 else
2345 author = strdup(got_object_commit_get_author(c));
2346 if (author == NULL) {
2347 err = got_error_from_errno("strdup");
2348 goto done;
2350 err = format_author(&wauthor, &width, author, COLS,
2351 date_display_cols);
2352 if (author_cols < width)
2353 author_cols = width;
2354 free(wauthor);
2355 free(author);
2356 if (err)
2357 goto done;
2358 err = got_object_commit_get_logmsg(&msg0, c);
2359 if (err)
2360 goto done;
2361 msg = msg0;
2362 while (*msg == '\n')
2363 ++msg;
2364 if ((eol = strchr(msg, '\n')))
2365 *eol = '\0';
2366 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2367 date_display_cols + author_cols, 0);
2368 if (err)
2369 goto done;
2370 view->maxx = MAX(view->maxx, width);
2371 free(msg0);
2372 free(wmsg);
2373 ncommits++;
2374 entry = TAILQ_NEXT(entry, entry);
2377 entry = s->first_displayed_entry;
2378 s->last_displayed_entry = s->first_displayed_entry;
2379 ncommits = 0;
2380 while (entry) {
2381 if (ncommits >= limit - 1)
2382 break;
2383 if (ncommits == s->selected)
2384 wstandout(view->window);
2385 err = draw_commit(view, entry->commit, entry->id,
2386 date_display_cols, author_cols);
2387 if (ncommits == s->selected)
2388 wstandend(view->window);
2389 if (err)
2390 goto done;
2391 ncommits++;
2392 s->last_displayed_entry = entry;
2393 entry = TAILQ_NEXT(entry, entry);
2396 view_border(view);
2397 done:
2398 free(id_str);
2399 free(refs_str);
2400 free(ncommits_str);
2401 free(header);
2402 return err;
2405 static void
2406 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2408 struct commit_queue_entry *entry;
2409 int nscrolled = 0;
2411 entry = TAILQ_FIRST(&s->commits.head);
2412 if (s->first_displayed_entry == entry)
2413 return;
2415 entry = s->first_displayed_entry;
2416 while (entry && nscrolled < maxscroll) {
2417 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2418 if (entry) {
2419 s->first_displayed_entry = entry;
2420 nscrolled++;
2425 static const struct got_error *
2426 trigger_log_thread(struct tog_view *view, int wait)
2428 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2429 int errcode;
2431 halfdelay(1); /* fast refresh while loading commits */
2433 while (!ta->log_complete && !tog_thread_error &&
2434 (ta->commits_needed > 0 || ta->load_all)) {
2435 /* Wake the log thread. */
2436 errcode = pthread_cond_signal(&ta->need_commits);
2437 if (errcode)
2438 return got_error_set_errno(errcode,
2439 "pthread_cond_signal");
2442 * The mutex will be released while the view loop waits
2443 * in wgetch(), at which time the log thread will run.
2445 if (!wait)
2446 break;
2448 /* Display progress update in log view. */
2449 show_log_view(view);
2450 update_panels();
2451 doupdate();
2453 /* Wait right here while next commit is being loaded. */
2454 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2455 if (errcode)
2456 return got_error_set_errno(errcode,
2457 "pthread_cond_wait");
2459 /* Display progress update in log view. */
2460 show_log_view(view);
2461 update_panels();
2462 doupdate();
2465 return NULL;
2468 static const struct got_error *
2469 request_log_commits(struct tog_view *view)
2471 struct tog_log_view_state *state = &view->state.log;
2472 const struct got_error *err = NULL;
2474 if (state->thread_args.log_complete)
2475 return NULL;
2477 state->thread_args.commits_needed += view->nscrolled;
2478 err = trigger_log_thread(view, 1);
2479 view->nscrolled = 0;
2481 return err;
2484 static const struct got_error *
2485 log_scroll_down(struct tog_view *view, int maxscroll)
2487 struct tog_log_view_state *s = &view->state.log;
2488 const struct got_error *err = NULL;
2489 struct commit_queue_entry *pentry;
2490 int nscrolled = 0, ncommits_needed;
2492 if (s->last_displayed_entry == NULL)
2493 return NULL;
2495 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2496 if (s->commits.ncommits < ncommits_needed &&
2497 !s->thread_args.log_complete) {
2499 * Ask the log thread for required amount of commits.
2501 s->thread_args.commits_needed += maxscroll;
2502 err = trigger_log_thread(view, 1);
2503 if (err)
2504 return err;
2507 do {
2508 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2509 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2510 break;
2512 s->last_displayed_entry = pentry ?
2513 pentry : s->last_displayed_entry;;
2515 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2516 if (pentry == NULL)
2517 break;
2518 s->first_displayed_entry = pentry;
2519 } while (++nscrolled < maxscroll);
2521 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2522 view->nscrolled += nscrolled;
2523 else
2524 view->nscrolled = 0;
2526 return err;
2529 static const struct got_error *
2530 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2531 struct got_commit_object *commit, struct got_object_id *commit_id,
2532 struct tog_view *log_view, struct got_repository *repo)
2534 const struct got_error *err;
2535 struct got_object_qid *parent_id;
2536 struct tog_view *diff_view;
2538 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2539 if (diff_view == NULL)
2540 return got_error_from_errno("view_open");
2542 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2543 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2544 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2545 if (err == NULL)
2546 *new_view = diff_view;
2547 return err;
2550 static const struct got_error *
2551 tree_view_visit_subtree(struct tog_tree_view_state *s,
2552 struct got_tree_object *subtree)
2554 struct tog_parent_tree *parent;
2556 parent = calloc(1, sizeof(*parent));
2557 if (parent == NULL)
2558 return got_error_from_errno("calloc");
2560 parent->tree = s->tree;
2561 parent->first_displayed_entry = s->first_displayed_entry;
2562 parent->selected_entry = s->selected_entry;
2563 parent->selected = s->selected;
2564 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2565 s->tree = subtree;
2566 s->selected = 0;
2567 s->first_displayed_entry = NULL;
2568 return NULL;
2571 static const struct got_error *
2572 tree_view_walk_path(struct tog_tree_view_state *s,
2573 struct got_commit_object *commit, const char *path)
2575 const struct got_error *err = NULL;
2576 struct got_tree_object *tree = NULL;
2577 const char *p;
2578 char *slash, *subpath = NULL;
2580 /* Walk the path and open corresponding tree objects. */
2581 p = path;
2582 while (*p) {
2583 struct got_tree_entry *te;
2584 struct got_object_id *tree_id;
2585 char *te_name;
2587 while (p[0] == '/')
2588 p++;
2590 /* Ensure the correct subtree entry is selected. */
2591 slash = strchr(p, '/');
2592 if (slash == NULL)
2593 te_name = strdup(p);
2594 else
2595 te_name = strndup(p, slash - p);
2596 if (te_name == NULL) {
2597 err = got_error_from_errno("strndup");
2598 break;
2600 te = got_object_tree_find_entry(s->tree, te_name);
2601 if (te == NULL) {
2602 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2603 free(te_name);
2604 break;
2606 free(te_name);
2607 s->first_displayed_entry = s->selected_entry = te;
2609 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2610 break; /* jump to this file's entry */
2612 slash = strchr(p, '/');
2613 if (slash)
2614 subpath = strndup(path, slash - path);
2615 else
2616 subpath = strdup(path);
2617 if (subpath == NULL) {
2618 err = got_error_from_errno("strdup");
2619 break;
2622 err = got_object_id_by_path(&tree_id, s->repo, commit,
2623 subpath);
2624 if (err)
2625 break;
2627 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2628 free(tree_id);
2629 if (err)
2630 break;
2632 err = tree_view_visit_subtree(s, tree);
2633 if (err) {
2634 got_object_tree_close(tree);
2635 break;
2637 if (slash == NULL)
2638 break;
2639 free(subpath);
2640 subpath = NULL;
2641 p = slash;
2644 free(subpath);
2645 return err;
2648 static const struct got_error *
2649 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2650 struct commit_queue_entry *entry, const char *path,
2651 const char *head_ref_name, struct got_repository *repo)
2653 const struct got_error *err = NULL;
2654 struct tog_tree_view_state *s;
2655 struct tog_view *tree_view;
2657 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2658 if (tree_view == NULL)
2659 return got_error_from_errno("view_open");
2661 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2662 if (err)
2663 return err;
2664 s = &tree_view->state.tree;
2666 *new_view = tree_view;
2668 if (got_path_is_root_dir(path))
2669 return NULL;
2671 return tree_view_walk_path(s, entry->commit, path);
2674 static const struct got_error *
2675 block_signals_used_by_main_thread(void)
2677 sigset_t sigset;
2678 int errcode;
2680 if (sigemptyset(&sigset) == -1)
2681 return got_error_from_errno("sigemptyset");
2683 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2684 if (sigaddset(&sigset, SIGWINCH) == -1)
2685 return got_error_from_errno("sigaddset");
2686 if (sigaddset(&sigset, SIGCONT) == -1)
2687 return got_error_from_errno("sigaddset");
2688 if (sigaddset(&sigset, SIGINT) == -1)
2689 return got_error_from_errno("sigaddset");
2690 if (sigaddset(&sigset, SIGTERM) == -1)
2691 return got_error_from_errno("sigaddset");
2693 /* ncurses handles SIGTSTP */
2694 if (sigaddset(&sigset, SIGTSTP) == -1)
2695 return got_error_from_errno("sigaddset");
2697 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2698 if (errcode)
2699 return got_error_set_errno(errcode, "pthread_sigmask");
2701 return NULL;
2704 static void *
2705 log_thread(void *arg)
2707 const struct got_error *err = NULL;
2708 int errcode = 0;
2709 struct tog_log_thread_args *a = arg;
2710 int done = 0;
2713 * Sync startup with main thread such that we begin our
2714 * work once view_input() has released the mutex.
2716 errcode = pthread_mutex_lock(&tog_mutex);
2717 if (errcode) {
2718 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2719 return (void *)err;
2722 err = block_signals_used_by_main_thread();
2723 if (err) {
2724 pthread_mutex_unlock(&tog_mutex);
2725 goto done;
2728 while (!done && !err && !tog_fatal_signal_received()) {
2729 errcode = pthread_mutex_unlock(&tog_mutex);
2730 if (errcode) {
2731 err = got_error_set_errno(errcode,
2732 "pthread_mutex_unlock");
2733 goto done;
2735 err = queue_commits(a);
2736 if (err) {
2737 if (err->code != GOT_ERR_ITER_COMPLETED)
2738 goto done;
2739 err = NULL;
2740 done = 1;
2741 } else if (a->commits_needed > 0 && !a->load_all)
2742 a->commits_needed--;
2744 errcode = pthread_mutex_lock(&tog_mutex);
2745 if (errcode) {
2746 err = got_error_set_errno(errcode,
2747 "pthread_mutex_lock");
2748 goto done;
2749 } else if (*a->quit)
2750 done = 1;
2751 else if (*a->first_displayed_entry == NULL) {
2752 *a->first_displayed_entry =
2753 TAILQ_FIRST(&a->commits->head);
2754 *a->selected_entry = *a->first_displayed_entry;
2757 errcode = pthread_cond_signal(&a->commit_loaded);
2758 if (errcode) {
2759 err = got_error_set_errno(errcode,
2760 "pthread_cond_signal");
2761 pthread_mutex_unlock(&tog_mutex);
2762 goto done;
2765 if (done)
2766 a->commits_needed = 0;
2767 else {
2768 if (a->commits_needed == 0 && !a->load_all) {
2769 errcode = pthread_cond_wait(&a->need_commits,
2770 &tog_mutex);
2771 if (errcode) {
2772 err = got_error_set_errno(errcode,
2773 "pthread_cond_wait");
2774 pthread_mutex_unlock(&tog_mutex);
2775 goto done;
2777 if (*a->quit)
2778 done = 1;
2782 a->log_complete = 1;
2783 errcode = pthread_mutex_unlock(&tog_mutex);
2784 if (errcode)
2785 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2786 done:
2787 if (err) {
2788 tog_thread_error = 1;
2789 pthread_cond_signal(&a->commit_loaded);
2791 return (void *)err;
2794 static const struct got_error *
2795 stop_log_thread(struct tog_log_view_state *s)
2797 const struct got_error *err = NULL, *thread_err = NULL;
2798 int errcode;
2800 if (s->thread) {
2801 s->quit = 1;
2802 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2803 if (errcode)
2804 return got_error_set_errno(errcode,
2805 "pthread_cond_signal");
2806 errcode = pthread_mutex_unlock(&tog_mutex);
2807 if (errcode)
2808 return got_error_set_errno(errcode,
2809 "pthread_mutex_unlock");
2810 errcode = pthread_join(s->thread, (void **)&thread_err);
2811 if (errcode)
2812 return got_error_set_errno(errcode, "pthread_join");
2813 errcode = pthread_mutex_lock(&tog_mutex);
2814 if (errcode)
2815 return got_error_set_errno(errcode,
2816 "pthread_mutex_lock");
2817 s->thread = NULL;
2820 if (s->thread_args.repo) {
2821 err = got_repo_close(s->thread_args.repo);
2822 s->thread_args.repo = NULL;
2825 if (s->thread_args.pack_fds) {
2826 const struct got_error *pack_err =
2827 got_repo_pack_fds_close(s->thread_args.pack_fds);
2828 if (err == NULL)
2829 err = pack_err;
2830 s->thread_args.pack_fds = NULL;
2833 if (s->thread_args.graph) {
2834 got_commit_graph_close(s->thread_args.graph);
2835 s->thread_args.graph = NULL;
2838 return err ? err : thread_err;
2841 static const struct got_error *
2842 close_log_view(struct tog_view *view)
2844 const struct got_error *err = NULL;
2845 struct tog_log_view_state *s = &view->state.log;
2846 int errcode;
2848 err = stop_log_thread(s);
2850 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2851 if (errcode && err == NULL)
2852 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2854 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2855 if (errcode && err == NULL)
2856 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2858 free_commits(&s->commits);
2859 free(s->in_repo_path);
2860 s->in_repo_path = NULL;
2861 free(s->start_id);
2862 s->start_id = NULL;
2863 free(s->head_ref_name);
2864 s->head_ref_name = NULL;
2865 return err;
2868 static const struct got_error *
2869 search_start_log_view(struct tog_view *view)
2871 struct tog_log_view_state *s = &view->state.log;
2873 s->matched_entry = NULL;
2874 s->search_entry = NULL;
2875 return NULL;
2878 static const struct got_error *
2879 search_next_log_view(struct tog_view *view)
2881 const struct got_error *err = NULL;
2882 struct tog_log_view_state *s = &view->state.log;
2883 struct commit_queue_entry *entry;
2885 /* Display progress update in log view. */
2886 show_log_view(view);
2887 update_panels();
2888 doupdate();
2890 if (s->search_entry) {
2891 int errcode, ch;
2892 errcode = pthread_mutex_unlock(&tog_mutex);
2893 if (errcode)
2894 return got_error_set_errno(errcode,
2895 "pthread_mutex_unlock");
2896 ch = wgetch(view->window);
2897 errcode = pthread_mutex_lock(&tog_mutex);
2898 if (errcode)
2899 return got_error_set_errno(errcode,
2900 "pthread_mutex_lock");
2901 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2902 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2903 return NULL;
2905 if (view->searching == TOG_SEARCH_FORWARD)
2906 entry = TAILQ_NEXT(s->search_entry, entry);
2907 else
2908 entry = TAILQ_PREV(s->search_entry,
2909 commit_queue_head, entry);
2910 } else if (s->matched_entry) {
2911 int matched_idx = s->matched_entry->idx;
2912 int selected_idx = s->selected_entry->idx;
2915 * If the user has moved the cursor after we hit a match,
2916 * the position from where we should continue searching
2917 * might have changed.
2919 if (view->searching == TOG_SEARCH_FORWARD) {
2920 if (matched_idx > selected_idx)
2921 entry = TAILQ_NEXT(s->selected_entry, entry);
2922 else
2923 entry = TAILQ_NEXT(s->matched_entry, entry);
2924 } else {
2925 if (matched_idx < selected_idx)
2926 entry = TAILQ_PREV(s->selected_entry,
2927 commit_queue_head, entry);
2928 else
2929 entry = TAILQ_PREV(s->matched_entry,
2930 commit_queue_head, entry);
2932 } else {
2933 entry = s->selected_entry;
2936 while (1) {
2937 int have_match = 0;
2939 if (entry == NULL) {
2940 if (s->thread_args.log_complete ||
2941 view->searching == TOG_SEARCH_BACKWARD) {
2942 view->search_next_done =
2943 (s->matched_entry == NULL ?
2944 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2945 s->search_entry = NULL;
2946 return NULL;
2949 * Poke the log thread for more commits and return,
2950 * allowing the main loop to make progress. Search
2951 * will resume at s->search_entry once we come back.
2953 s->thread_args.commits_needed++;
2954 return trigger_log_thread(view, 0);
2957 err = match_commit(&have_match, entry->id, entry->commit,
2958 &view->regex);
2959 if (err)
2960 break;
2961 if (have_match) {
2962 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2963 s->matched_entry = entry;
2964 break;
2967 s->search_entry = entry;
2968 if (view->searching == TOG_SEARCH_FORWARD)
2969 entry = TAILQ_NEXT(entry, entry);
2970 else
2971 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2974 if (s->matched_entry) {
2975 int cur = s->selected_entry->idx;
2976 while (cur < s->matched_entry->idx) {
2977 err = input_log_view(NULL, view, KEY_DOWN);
2978 if (err)
2979 return err;
2980 cur++;
2982 while (cur > s->matched_entry->idx) {
2983 err = input_log_view(NULL, view, KEY_UP);
2984 if (err)
2985 return err;
2986 cur--;
2990 s->search_entry = NULL;
2992 return NULL;
2995 static const struct got_error *
2996 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2997 struct got_repository *repo, const char *head_ref_name,
2998 const char *in_repo_path, int log_branches)
3000 const struct got_error *err = NULL;
3001 struct tog_log_view_state *s = &view->state.log;
3002 struct got_repository *thread_repo = NULL;
3003 struct got_commit_graph *thread_graph = NULL;
3004 int errcode;
3006 if (in_repo_path != s->in_repo_path) {
3007 free(s->in_repo_path);
3008 s->in_repo_path = strdup(in_repo_path);
3009 if (s->in_repo_path == NULL)
3010 return got_error_from_errno("strdup");
3013 /* The commit queue only contains commits being displayed. */
3014 TAILQ_INIT(&s->commits.head);
3015 s->commits.ncommits = 0;
3017 s->repo = repo;
3018 if (head_ref_name) {
3019 s->head_ref_name = strdup(head_ref_name);
3020 if (s->head_ref_name == NULL) {
3021 err = got_error_from_errno("strdup");
3022 goto done;
3025 s->start_id = got_object_id_dup(start_id);
3026 if (s->start_id == NULL) {
3027 err = got_error_from_errno("got_object_id_dup");
3028 goto done;
3030 s->log_branches = log_branches;
3032 STAILQ_INIT(&s->colors);
3033 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3034 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3035 get_color_value("TOG_COLOR_COMMIT"));
3036 if (err)
3037 goto done;
3038 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3039 get_color_value("TOG_COLOR_AUTHOR"));
3040 if (err) {
3041 free_colors(&s->colors);
3042 goto done;
3044 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3045 get_color_value("TOG_COLOR_DATE"));
3046 if (err) {
3047 free_colors(&s->colors);
3048 goto done;
3052 view->show = show_log_view;
3053 view->input = input_log_view;
3054 view->resize = resize_log_view;
3055 view->close = close_log_view;
3056 view->search_start = search_start_log_view;
3057 view->search_next = search_next_log_view;
3059 if (s->thread_args.pack_fds == NULL) {
3060 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3061 if (err)
3062 goto done;
3064 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3065 s->thread_args.pack_fds);
3066 if (err)
3067 goto done;
3068 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3069 !s->log_branches);
3070 if (err)
3071 goto done;
3072 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3073 s->repo, NULL, NULL);
3074 if (err)
3075 goto done;
3077 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3078 if (errcode) {
3079 err = got_error_set_errno(errcode, "pthread_cond_init");
3080 goto done;
3082 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3083 if (errcode) {
3084 err = got_error_set_errno(errcode, "pthread_cond_init");
3085 goto done;
3088 s->thread_args.commits_needed = view->nlines;
3089 s->thread_args.graph = thread_graph;
3090 s->thread_args.commits = &s->commits;
3091 s->thread_args.in_repo_path = s->in_repo_path;
3092 s->thread_args.start_id = s->start_id;
3093 s->thread_args.repo = thread_repo;
3094 s->thread_args.log_complete = 0;
3095 s->thread_args.quit = &s->quit;
3096 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3097 s->thread_args.selected_entry = &s->selected_entry;
3098 s->thread_args.searching = &view->searching;
3099 s->thread_args.search_next_done = &view->search_next_done;
3100 s->thread_args.regex = &view->regex;
3101 done:
3102 if (err)
3103 close_log_view(view);
3104 return err;
3107 static const struct got_error *
3108 show_log_view(struct tog_view *view)
3110 const struct got_error *err;
3111 struct tog_log_view_state *s = &view->state.log;
3113 if (s->thread == NULL) {
3114 int errcode = pthread_create(&s->thread, NULL, log_thread,
3115 &s->thread_args);
3116 if (errcode)
3117 return got_error_set_errno(errcode, "pthread_create");
3118 if (s->thread_args.commits_needed > 0) {
3119 err = trigger_log_thread(view, 1);
3120 if (err)
3121 return err;
3125 return draw_commits(view);
3128 static void
3129 log_move_cursor_up(struct tog_view *view, int page, int home)
3131 struct tog_log_view_state *s = &view->state.log;
3133 if (s->selected_entry->idx == 0)
3134 view->count = 0;
3135 if (s->first_displayed_entry == NULL)
3136 return;
3138 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3139 || home)
3140 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3142 if (!page && !home && s->selected > 0)
3143 --s->selected;
3144 else
3145 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3147 select_commit(s);
3148 return;
3151 static const struct got_error *
3152 log_move_cursor_down(struct tog_view *view, int page)
3154 struct tog_log_view_state *s = &view->state.log;
3155 struct commit_queue_entry *first;
3156 const struct got_error *err = NULL;
3158 first = s->first_displayed_entry;
3159 if (first == NULL) {
3160 view->count = 0;
3161 return NULL;
3164 if (s->thread_args.log_complete &&
3165 s->selected_entry->idx >= s->commits.ncommits - 1)
3166 return NULL;
3168 if (!page) {
3169 int eos = view->nlines - 2;
3171 if (view_is_hsplit_top(view))
3172 --eos; /* border consumes the last line */
3173 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3174 ++s->selected;
3175 else
3176 err = log_scroll_down(view, 1);
3177 } else if (s->thread_args.load_all) {
3178 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3179 s->selected += MIN(s->last_displayed_entry->idx -
3180 s->selected_entry->idx, page + 1);
3181 else
3182 err = log_scroll_down(view, MIN(page,
3183 s->commits.ncommits - s->selected_entry->idx - 1));
3184 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3185 } else {
3186 err = log_scroll_down(view, page);
3187 if (err)
3188 return err;
3189 if (first == s->first_displayed_entry && s->selected <
3190 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
3191 s->selected = MIN(s->commits.ncommits - 1, page);
3194 if (err)
3195 return err;
3198 * We might necessarily overshoot in horizontal
3199 * splits; if so, select the last displayed commit.
3201 s->selected = MIN(s->selected,
3202 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3204 select_commit(s);
3206 if (s->thread_args.log_complete &&
3207 s->selected_entry->idx == s->commits.ncommits - 1)
3208 view->count = 0;
3210 return NULL;
3213 static void
3214 view_get_split(struct tog_view *view, int *y, int *x)
3216 *x = 0;
3217 *y = 0;
3219 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3220 if (view->child && view->child->resized_y)
3221 *y = view->child->resized_y;
3222 else if (view->resized_y)
3223 *y = view->resized_y;
3224 else
3225 *y = view_split_begin_y(view->lines);
3226 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3227 if (view->child && view->child->resized_x)
3228 *x = view->child->resized_x;
3229 else if (view->resized_x)
3230 *x = view->resized_x;
3231 else
3232 *x = view_split_begin_x(view->begin_x);
3236 /* Split view horizontally at y and offset view->state->selected line. */
3237 static const struct got_error *
3238 view_init_hsplit(struct tog_view *view, int y)
3240 const struct got_error *err = NULL;
3242 view->nlines = y;
3243 view->ncols = COLS;
3244 err = view_resize(view);
3245 if (err)
3246 return err;
3248 err = offset_selection_down(view);
3250 return err;
3253 static const struct got_error *
3254 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3256 const struct got_error *err = NULL;
3257 struct tog_log_view_state *s = &view->state.log;
3258 struct commit_queue_entry *entry;
3259 int eos, n, nscroll;
3261 if (s->thread_args.load_all) {
3262 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3263 s->thread_args.load_all = 0;
3264 else if (s->thread_args.log_complete) {
3265 err = log_move_cursor_down(view, s->commits.ncommits);
3266 s->thread_args.load_all = 0;
3268 return err;
3271 eos = nscroll = view->nlines - 1;
3272 if (view_is_hsplit_top(view))
3273 --eos; /* border */
3275 switch (ch) {
3276 case 'q':
3277 s->quit = 1;
3278 break;
3279 case '0':
3280 view->x = 0;
3281 break;
3282 case '$':
3283 view->x = MAX(view->maxx - view->ncols / 2, 0);
3284 view->count = 0;
3285 break;
3286 case KEY_RIGHT:
3287 case 'l':
3288 if (view->x + view->ncols / 2 < view->maxx)
3289 view->x += 2; /* move two columns right */
3290 else
3291 view->count = 0;
3292 break;
3293 case KEY_LEFT:
3294 case 'h':
3295 view->x -= MIN(view->x, 2); /* move two columns back */
3296 if (view->x <= 0)
3297 view->count = 0;
3298 break;
3299 case 'k':
3300 case KEY_UP:
3301 case '<':
3302 case ',':
3303 case CTRL('p'):
3304 log_move_cursor_up(view, 0, 0);
3305 break;
3306 case 'g':
3307 case KEY_HOME:
3308 log_move_cursor_up(view, 0, 1);
3309 view->count = 0;
3310 break;
3311 case CTRL('u'):
3312 case 'u':
3313 nscroll /= 2;
3314 /* FALL THROUGH */
3315 case KEY_PPAGE:
3316 case CTRL('b'):
3317 case 'b':
3318 log_move_cursor_up(view, nscroll, 0);
3319 break;
3320 case 'j':
3321 case KEY_DOWN:
3322 case '>':
3323 case '.':
3324 case CTRL('n'):
3325 err = log_move_cursor_down(view, 0);
3326 break;
3327 case '@':
3328 s->use_committer = !s->use_committer;
3329 break;
3330 case 'G':
3331 case KEY_END: {
3332 /* We don't know yet how many commits, so we're forced to
3333 * traverse them all. */
3334 view->count = 0;
3335 if (!s->thread_args.log_complete) {
3336 s->thread_args.load_all = 1;
3337 return trigger_log_thread(view, 0);
3340 s->selected = 0;
3341 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3342 for (n = 0; n < eos; n++) {
3343 if (entry == NULL)
3344 break;
3345 s->first_displayed_entry = entry;
3346 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3348 if (n > 0)
3349 s->selected = n - 1;
3350 select_commit(s);
3351 break;
3353 case CTRL('d'):
3354 case 'd':
3355 nscroll /= 2;
3356 /* FALL THROUGH */
3357 case KEY_NPAGE:
3358 case CTRL('f'):
3359 case 'f':
3360 case ' ':
3361 err = log_move_cursor_down(view, nscroll);
3362 break;
3363 case KEY_RESIZE:
3364 if (s->selected > view->nlines - 2)
3365 s->selected = view->nlines - 2;
3366 if (s->selected > s->commits.ncommits - 1)
3367 s->selected = s->commits.ncommits - 1;
3368 select_commit(s);
3369 if (s->commits.ncommits < view->nlines - 1 &&
3370 !s->thread_args.log_complete) {
3371 s->thread_args.commits_needed += (view->nlines - 1) -
3372 s->commits.ncommits;
3373 err = trigger_log_thread(view, 1);
3375 break;
3376 case KEY_ENTER:
3377 case '\r':
3378 view->count = 0;
3379 if (s->selected_entry == NULL)
3380 break;
3381 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3382 break;
3383 case 'T':
3384 view->count = 0;
3385 if (s->selected_entry == NULL)
3386 break;
3387 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3388 break;
3389 case KEY_BACKSPACE:
3390 case CTRL('l'):
3391 case 'B':
3392 view->count = 0;
3393 if (ch == KEY_BACKSPACE &&
3394 got_path_is_root_dir(s->in_repo_path))
3395 break;
3396 err = stop_log_thread(s);
3397 if (err)
3398 return err;
3399 if (ch == KEY_BACKSPACE) {
3400 char *parent_path;
3401 err = got_path_dirname(&parent_path, s->in_repo_path);
3402 if (err)
3403 return err;
3404 free(s->in_repo_path);
3405 s->in_repo_path = parent_path;
3406 s->thread_args.in_repo_path = s->in_repo_path;
3407 } else if (ch == CTRL('l')) {
3408 struct got_object_id *start_id;
3409 err = got_repo_match_object_id(&start_id, NULL,
3410 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3411 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3412 if (err)
3413 return err;
3414 free(s->start_id);
3415 s->start_id = start_id;
3416 s->thread_args.start_id = s->start_id;
3417 } else /* 'B' */
3418 s->log_branches = !s->log_branches;
3420 if (s->thread_args.pack_fds == NULL) {
3421 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3422 if (err)
3423 return err;
3425 err = got_repo_open(&s->thread_args.repo,
3426 got_repo_get_path(s->repo), NULL,
3427 s->thread_args.pack_fds);
3428 if (err)
3429 return err;
3430 tog_free_refs();
3431 err = tog_load_refs(s->repo, 0);
3432 if (err)
3433 return err;
3434 err = got_commit_graph_open(&s->thread_args.graph,
3435 s->in_repo_path, !s->log_branches);
3436 if (err)
3437 return err;
3438 err = got_commit_graph_iter_start(s->thread_args.graph,
3439 s->start_id, s->repo, NULL, NULL);
3440 if (err)
3441 return err;
3442 free_commits(&s->commits);
3443 s->first_displayed_entry = NULL;
3444 s->last_displayed_entry = NULL;
3445 s->selected_entry = NULL;
3446 s->selected = 0;
3447 s->thread_args.log_complete = 0;
3448 s->quit = 0;
3449 s->thread_args.commits_needed = view->lines;
3450 s->matched_entry = NULL;
3451 s->search_entry = NULL;
3452 view->offset = 0;
3453 break;
3454 case 'R':
3455 view->count = 0;
3456 err = view_request_new(new_view, view, TOG_VIEW_REF);
3457 break;
3458 default:
3459 view->count = 0;
3460 break;
3463 return err;
3466 static const struct got_error *
3467 apply_unveil(const char *repo_path, const char *worktree_path)
3469 const struct got_error *error;
3471 #ifdef PROFILE
3472 if (unveil("gmon.out", "rwc") != 0)
3473 return got_error_from_errno2("unveil", "gmon.out");
3474 #endif
3475 if (repo_path && unveil(repo_path, "r") != 0)
3476 return got_error_from_errno2("unveil", repo_path);
3478 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3479 return got_error_from_errno2("unveil", worktree_path);
3481 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3482 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3484 error = got_privsep_unveil_exec_helpers();
3485 if (error != NULL)
3486 return error;
3488 if (unveil(NULL, NULL) != 0)
3489 return got_error_from_errno("unveil");
3491 return NULL;
3494 static void
3495 init_curses(void)
3498 * Override default signal handlers before starting ncurses.
3499 * This should prevent ncurses from installing its own
3500 * broken cleanup() signal handler.
3502 signal(SIGWINCH, tog_sigwinch);
3503 signal(SIGPIPE, tog_sigpipe);
3504 signal(SIGCONT, tog_sigcont);
3505 signal(SIGINT, tog_sigint);
3506 signal(SIGTERM, tog_sigterm);
3508 initscr();
3509 cbreak();
3510 halfdelay(1); /* Do fast refresh while initial view is loading. */
3511 noecho();
3512 nonl();
3513 intrflush(stdscr, FALSE);
3514 keypad(stdscr, TRUE);
3515 curs_set(0);
3516 if (getenv("TOG_COLORS") != NULL) {
3517 start_color();
3518 use_default_colors();
3522 static const struct got_error *
3523 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3524 struct got_repository *repo, struct got_worktree *worktree)
3526 const struct got_error *err = NULL;
3528 if (argc == 0) {
3529 *in_repo_path = strdup("/");
3530 if (*in_repo_path == NULL)
3531 return got_error_from_errno("strdup");
3532 return NULL;
3535 if (worktree) {
3536 const char *prefix = got_worktree_get_path_prefix(worktree);
3537 char *p;
3539 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3540 if (err)
3541 return err;
3542 if (asprintf(in_repo_path, "%s%s%s", prefix,
3543 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3544 p) == -1) {
3545 err = got_error_from_errno("asprintf");
3546 *in_repo_path = NULL;
3548 free(p);
3549 } else
3550 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3552 return err;
3555 static const struct got_error *
3556 cmd_log(int argc, char *argv[])
3558 const struct got_error *error;
3559 struct got_repository *repo = NULL;
3560 struct got_worktree *worktree = NULL;
3561 struct got_object_id *start_id = NULL;
3562 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3563 char *start_commit = NULL, *label = NULL;
3564 struct got_reference *ref = NULL;
3565 const char *head_ref_name = NULL;
3566 int ch, log_branches = 0;
3567 struct tog_view *view;
3568 int *pack_fds = NULL;
3570 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3571 switch (ch) {
3572 case 'b':
3573 log_branches = 1;
3574 break;
3575 case 'c':
3576 start_commit = optarg;
3577 break;
3578 case 'r':
3579 repo_path = realpath(optarg, NULL);
3580 if (repo_path == NULL)
3581 return got_error_from_errno2("realpath",
3582 optarg);
3583 break;
3584 default:
3585 usage_log();
3586 /* NOTREACHED */
3590 argc -= optind;
3591 argv += optind;
3593 if (argc > 1)
3594 usage_log();
3596 error = got_repo_pack_fds_open(&pack_fds);
3597 if (error != NULL)
3598 goto done;
3600 if (repo_path == NULL) {
3601 cwd = getcwd(NULL, 0);
3602 if (cwd == NULL)
3603 return got_error_from_errno("getcwd");
3604 error = got_worktree_open(&worktree, cwd);
3605 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3606 goto done;
3607 if (worktree)
3608 repo_path =
3609 strdup(got_worktree_get_repo_path(worktree));
3610 else
3611 repo_path = strdup(cwd);
3612 if (repo_path == NULL) {
3613 error = got_error_from_errno("strdup");
3614 goto done;
3618 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3619 if (error != NULL)
3620 goto done;
3622 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3623 repo, worktree);
3624 if (error)
3625 goto done;
3627 init_curses();
3629 error = apply_unveil(got_repo_get_path(repo),
3630 worktree ? got_worktree_get_root_path(worktree) : NULL);
3631 if (error)
3632 goto done;
3634 /* already loaded by tog_log_with_path()? */
3635 if (TAILQ_EMPTY(&tog_refs)) {
3636 error = tog_load_refs(repo, 0);
3637 if (error)
3638 goto done;
3641 if (start_commit == NULL) {
3642 error = got_repo_match_object_id(&start_id, &label,
3643 worktree ? got_worktree_get_head_ref_name(worktree) :
3644 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3645 if (error)
3646 goto done;
3647 head_ref_name = label;
3648 } else {
3649 error = got_ref_open(&ref, repo, start_commit, 0);
3650 if (error == NULL)
3651 head_ref_name = got_ref_get_name(ref);
3652 else if (error->code != GOT_ERR_NOT_REF)
3653 goto done;
3654 error = got_repo_match_object_id(&start_id, NULL,
3655 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3656 if (error)
3657 goto done;
3660 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3661 if (view == NULL) {
3662 error = got_error_from_errno("view_open");
3663 goto done;
3665 error = open_log_view(view, start_id, repo, head_ref_name,
3666 in_repo_path, log_branches);
3667 if (error)
3668 goto done;
3669 if (worktree) {
3670 /* Release work tree lock. */
3671 got_worktree_close(worktree);
3672 worktree = NULL;
3674 error = view_loop(view);
3675 done:
3676 free(in_repo_path);
3677 free(repo_path);
3678 free(cwd);
3679 free(start_id);
3680 free(label);
3681 if (ref)
3682 got_ref_close(ref);
3683 if (repo) {
3684 const struct got_error *close_err = got_repo_close(repo);
3685 if (error == NULL)
3686 error = close_err;
3688 if (worktree)
3689 got_worktree_close(worktree);
3690 if (pack_fds) {
3691 const struct got_error *pack_err =
3692 got_repo_pack_fds_close(pack_fds);
3693 if (error == NULL)
3694 error = pack_err;
3696 tog_free_refs();
3697 return error;
3700 __dead static void
3701 usage_diff(void)
3703 endwin();
3704 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3705 "[-w] object1 object2\n", getprogname());
3706 exit(1);
3709 static int
3710 match_line(const char *line, regex_t *regex, size_t nmatch,
3711 regmatch_t *regmatch)
3713 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3716 static struct tog_color *
3717 match_color(struct tog_colors *colors, const char *line)
3719 struct tog_color *tc = NULL;
3721 STAILQ_FOREACH(tc, colors, entry) {
3722 if (match_line(line, &tc->regex, 0, NULL))
3723 return tc;
3726 return NULL;
3729 static const struct got_error *
3730 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3731 WINDOW *window, int skipcol, regmatch_t *regmatch)
3733 const struct got_error *err = NULL;
3734 char *exstr = NULL;
3735 wchar_t *wline = NULL;
3736 int rme, rms, n, width, scrollx;
3737 int width0 = 0, width1 = 0, width2 = 0;
3738 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3740 *wtotal = 0;
3742 rms = regmatch->rm_so;
3743 rme = regmatch->rm_eo;
3745 err = expand_tab(&exstr, line);
3746 if (err)
3747 return err;
3749 /* Split the line into 3 segments, according to match offsets. */
3750 seg0 = strndup(exstr, rms);
3751 if (seg0 == NULL) {
3752 err = got_error_from_errno("strndup");
3753 goto done;
3755 seg1 = strndup(exstr + rms, rme - rms);
3756 if (seg1 == NULL) {
3757 err = got_error_from_errno("strndup");
3758 goto done;
3760 seg2 = strdup(exstr + rme);
3761 if (seg2 == NULL) {
3762 err = got_error_from_errno("strndup");
3763 goto done;
3766 /* draw up to matched token if we haven't scrolled past it */
3767 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3768 col_tab_align, 1);
3769 if (err)
3770 goto done;
3771 n = MAX(width0 - skipcol, 0);
3772 if (n) {
3773 free(wline);
3774 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3775 wlimit, col_tab_align, 1);
3776 if (err)
3777 goto done;
3778 waddwstr(window, &wline[scrollx]);
3779 wlimit -= width;
3780 *wtotal += width;
3783 if (wlimit > 0) {
3784 int i = 0, w = 0;
3785 size_t wlen;
3787 free(wline);
3788 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3789 col_tab_align, 1);
3790 if (err)
3791 goto done;
3792 wlen = wcslen(wline);
3793 while (i < wlen) {
3794 width = wcwidth(wline[i]);
3795 if (width == -1) {
3796 /* should not happen, tabs are expanded */
3797 err = got_error(GOT_ERR_RANGE);
3798 goto done;
3800 if (width0 + w + width > skipcol)
3801 break;
3802 w += width;
3803 i++;
3805 /* draw (visible part of) matched token (if scrolled into it) */
3806 if (width1 - w > 0) {
3807 wattron(window, A_STANDOUT);
3808 waddwstr(window, &wline[i]);
3809 wattroff(window, A_STANDOUT);
3810 wlimit -= (width1 - w);
3811 *wtotal += (width1 - w);
3815 if (wlimit > 0) { /* draw rest of line */
3816 free(wline);
3817 if (skipcol > width0 + width1) {
3818 err = format_line(&wline, &width2, &scrollx, seg2,
3819 skipcol - (width0 + width1), wlimit,
3820 col_tab_align, 1);
3821 if (err)
3822 goto done;
3823 waddwstr(window, &wline[scrollx]);
3824 } else {
3825 err = format_line(&wline, &width2, NULL, seg2, 0,
3826 wlimit, col_tab_align, 1);
3827 if (err)
3828 goto done;
3829 waddwstr(window, wline);
3831 *wtotal += width2;
3833 done:
3834 free(wline);
3835 free(exstr);
3836 free(seg0);
3837 free(seg1);
3838 free(seg2);
3839 return err;
3842 static const struct got_error *
3843 draw_file(struct tog_view *view, const char *header)
3845 struct tog_diff_view_state *s = &view->state.diff;
3846 regmatch_t *regmatch = &view->regmatch;
3847 const struct got_error *err;
3848 int nprinted = 0;
3849 char *line;
3850 size_t linesize = 0;
3851 ssize_t linelen;
3852 struct tog_color *tc;
3853 wchar_t *wline;
3854 int width;
3855 int max_lines = view->nlines;
3856 int nlines = s->nlines;
3857 off_t line_offset;
3859 line_offset = s->line_offsets[s->first_displayed_line - 1];
3860 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3861 return got_error_from_errno("fseek");
3863 werase(view->window);
3865 if (header) {
3866 if (asprintf(&line, "[%d/%d] %s",
3867 s->first_displayed_line - 1 + s->selected_line, nlines,
3868 header) == -1)
3869 return got_error_from_errno("asprintf");
3870 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3871 0, 0);
3872 free(line);
3873 if (err)
3874 return err;
3876 if (view_needs_focus_indication(view))
3877 wstandout(view->window);
3878 waddwstr(view->window, wline);
3879 free(wline);
3880 wline = NULL;
3881 if (view_needs_focus_indication(view))
3882 wstandend(view->window);
3883 if (width <= view->ncols - 1)
3884 waddch(view->window, '\n');
3886 if (max_lines <= 1)
3887 return NULL;
3888 max_lines--;
3891 s->eof = 0;
3892 view->maxx = 0;
3893 line = NULL;
3894 while (max_lines > 0 && nprinted < max_lines) {
3895 linelen = getline(&line, &linesize, s->f);
3896 if (linelen == -1) {
3897 if (feof(s->f)) {
3898 s->eof = 1;
3899 break;
3901 free(line);
3902 return got_ferror(s->f, GOT_ERR_IO);
3905 /* Set view->maxx based on full line length. */
3906 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3907 view->x ? 1 : 0);
3908 if (err) {
3909 free(line);
3910 return err;
3912 view->maxx = MAX(view->maxx, width);
3913 free(wline);
3914 wline = NULL;
3916 tc = match_color(&s->colors, line);
3917 if (tc)
3918 wattr_on(view->window,
3919 COLOR_PAIR(tc->colorpair), NULL);
3920 if (s->first_displayed_line + nprinted == s->matched_line &&
3921 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3922 err = add_matched_line(&width, line, view->ncols, 0,
3923 view->window, view->x, regmatch);
3924 if (err) {
3925 free(line);
3926 return err;
3928 } else {
3929 int skip;
3930 err = format_line(&wline, &width, &skip, line,
3931 view->x, view->ncols, 0, view->x ? 1 : 0);
3932 if (err) {
3933 free(line);
3934 return err;
3936 waddwstr(view->window, &wline[skip]);
3937 free(wline);
3938 wline = NULL;
3940 if (tc)
3941 wattr_off(view->window,
3942 COLOR_PAIR(tc->colorpair), NULL);
3943 if (width <= view->ncols - 1)
3944 waddch(view->window, '\n');
3945 nprinted++;
3947 free(line);
3948 if (nprinted >= 1)
3949 s->last_displayed_line = s->first_displayed_line +
3950 (nprinted - 1);
3951 else
3952 s->last_displayed_line = s->first_displayed_line;
3954 view_border(view);
3956 if (s->eof) {
3957 while (nprinted < view->nlines) {
3958 waddch(view->window, '\n');
3959 nprinted++;
3962 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3963 view->ncols, 0, 0);
3964 if (err) {
3965 return err;
3968 wstandout(view->window);
3969 waddwstr(view->window, wline);
3970 free(wline);
3971 wline = NULL;
3972 wstandend(view->window);
3975 return NULL;
3978 static char *
3979 get_datestr(time_t *time, char *datebuf)
3981 struct tm mytm, *tm;
3982 char *p, *s;
3984 tm = gmtime_r(time, &mytm);
3985 if (tm == NULL)
3986 return NULL;
3987 s = asctime_r(tm, datebuf);
3988 if (s == NULL)
3989 return NULL;
3990 p = strchr(s, '\n');
3991 if (p)
3992 *p = '\0';
3993 return s;
3996 static const struct got_error *
3997 get_changed_paths(struct got_pathlist_head *paths,
3998 struct got_commit_object *commit, struct got_repository *repo)
4000 const struct got_error *err = NULL;
4001 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4002 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4003 struct got_object_qid *qid;
4005 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4006 if (qid != NULL) {
4007 struct got_commit_object *pcommit;
4008 err = got_object_open_as_commit(&pcommit, repo,
4009 &qid->id);
4010 if (err)
4011 return err;
4013 tree_id1 = got_object_id_dup(
4014 got_object_commit_get_tree_id(pcommit));
4015 if (tree_id1 == NULL) {
4016 got_object_commit_close(pcommit);
4017 return got_error_from_errno("got_object_id_dup");
4019 got_object_commit_close(pcommit);
4023 if (tree_id1) {
4024 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4025 if (err)
4026 goto done;
4029 tree_id2 = got_object_commit_get_tree_id(commit);
4030 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4031 if (err)
4032 goto done;
4034 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4035 got_diff_tree_collect_changed_paths, paths, 0);
4036 done:
4037 if (tree1)
4038 got_object_tree_close(tree1);
4039 if (tree2)
4040 got_object_tree_close(tree2);
4041 free(tree_id1);
4042 return err;
4045 static const struct got_error *
4046 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
4048 off_t *p;
4050 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
4051 if (p == NULL)
4052 return got_error_from_errno("reallocarray");
4053 *line_offsets = p;
4054 (*line_offsets)[*nlines] = off;
4055 (*nlines)++;
4056 return NULL;
4059 static const struct got_error *
4060 write_commit_info(off_t **line_offsets, size_t *nlines,
4061 struct got_object_id *commit_id, struct got_reflist_head *refs,
4062 struct got_repository *repo, FILE *outfile)
4064 const struct got_error *err = NULL;
4065 char datebuf[26], *datestr;
4066 struct got_commit_object *commit;
4067 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4068 time_t committer_time;
4069 const char *author, *committer;
4070 char *refs_str = NULL;
4071 struct got_pathlist_head changed_paths;
4072 struct got_pathlist_entry *pe;
4073 off_t outoff = 0;
4074 int n;
4076 TAILQ_INIT(&changed_paths);
4078 if (refs) {
4079 err = build_refs_str(&refs_str, refs, commit_id, repo);
4080 if (err)
4081 return err;
4084 err = got_object_open_as_commit(&commit, repo, commit_id);
4085 if (err)
4086 return err;
4088 err = got_object_id_str(&id_str, commit_id);
4089 if (err) {
4090 err = got_error_from_errno("got_object_id_str");
4091 goto done;
4094 err = add_line_offset(line_offsets, nlines, 0);
4095 if (err)
4096 goto done;
4098 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4099 refs_str ? refs_str : "", refs_str ? ")" : "");
4100 if (n < 0) {
4101 err = got_error_from_errno("fprintf");
4102 goto done;
4104 outoff += n;
4105 err = add_line_offset(line_offsets, nlines, outoff);
4106 if (err)
4107 goto done;
4109 n = fprintf(outfile, "from: %s\n",
4110 got_object_commit_get_author(commit));
4111 if (n < 0) {
4112 err = got_error_from_errno("fprintf");
4113 goto done;
4115 outoff += n;
4116 err = add_line_offset(line_offsets, nlines, outoff);
4117 if (err)
4118 goto done;
4120 committer_time = got_object_commit_get_committer_time(commit);
4121 datestr = get_datestr(&committer_time, datebuf);
4122 if (datestr) {
4123 n = fprintf(outfile, "date: %s UTC\n", datestr);
4124 if (n < 0) {
4125 err = got_error_from_errno("fprintf");
4126 goto done;
4128 outoff += n;
4129 err = add_line_offset(line_offsets, nlines, outoff);
4130 if (err)
4131 goto done;
4133 author = got_object_commit_get_author(commit);
4134 committer = got_object_commit_get_committer(commit);
4135 if (strcmp(author, committer) != 0) {
4136 n = fprintf(outfile, "via: %s\n", committer);
4137 if (n < 0) {
4138 err = got_error_from_errno("fprintf");
4139 goto done;
4141 outoff += n;
4142 err = add_line_offset(line_offsets, nlines, outoff);
4143 if (err)
4144 goto done;
4146 if (got_object_commit_get_nparents(commit) > 1) {
4147 const struct got_object_id_queue *parent_ids;
4148 struct got_object_qid *qid;
4149 int pn = 1;
4150 parent_ids = got_object_commit_get_parent_ids(commit);
4151 STAILQ_FOREACH(qid, parent_ids, entry) {
4152 err = got_object_id_str(&id_str, &qid->id);
4153 if (err)
4154 goto done;
4155 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4156 if (n < 0) {
4157 err = got_error_from_errno("fprintf");
4158 goto done;
4160 outoff += n;
4161 err = add_line_offset(line_offsets, nlines, outoff);
4162 if (err)
4163 goto done;
4164 free(id_str);
4165 id_str = NULL;
4169 err = got_object_commit_get_logmsg(&logmsg, commit);
4170 if (err)
4171 goto done;
4172 s = logmsg;
4173 while ((line = strsep(&s, "\n")) != NULL) {
4174 n = fprintf(outfile, "%s\n", line);
4175 if (n < 0) {
4176 err = got_error_from_errno("fprintf");
4177 goto done;
4179 outoff += n;
4180 err = add_line_offset(line_offsets, nlines, outoff);
4181 if (err)
4182 goto done;
4185 err = get_changed_paths(&changed_paths, commit, repo);
4186 if (err)
4187 goto done;
4188 TAILQ_FOREACH(pe, &changed_paths, entry) {
4189 struct got_diff_changed_path *cp = pe->data;
4190 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4191 if (n < 0) {
4192 err = got_error_from_errno("fprintf");
4193 goto done;
4195 outoff += n;
4196 err = add_line_offset(line_offsets, nlines, outoff);
4197 if (err)
4198 goto done;
4199 free((char *)pe->path);
4200 free(pe->data);
4203 fputc('\n', outfile);
4204 outoff++;
4205 err = add_line_offset(line_offsets, nlines, outoff);
4206 done:
4207 got_pathlist_free(&changed_paths);
4208 free(id_str);
4209 free(logmsg);
4210 free(refs_str);
4211 got_object_commit_close(commit);
4212 if (err) {
4213 free(*line_offsets);
4214 *line_offsets = NULL;
4215 *nlines = 0;
4217 return err;
4220 static const struct got_error *
4221 create_diff(struct tog_diff_view_state *s)
4223 const struct got_error *err = NULL;
4224 FILE *f = NULL;
4225 int obj_type;
4227 free(s->line_offsets);
4228 s->line_offsets = malloc(sizeof(off_t));
4229 if (s->line_offsets == NULL)
4230 return got_error_from_errno("malloc");
4231 s->nlines = 0;
4233 f = got_opentemp();
4234 if (f == NULL) {
4235 err = got_error_from_errno("got_opentemp");
4236 goto done;
4238 if (s->f && fclose(s->f) == EOF) {
4239 err = got_error_from_errno("fclose");
4240 goto done;
4242 s->f = f;
4244 if (s->id1)
4245 err = got_object_get_type(&obj_type, s->repo, s->id1);
4246 else
4247 err = got_object_get_type(&obj_type, s->repo, s->id2);
4248 if (err)
4249 goto done;
4251 switch (obj_type) {
4252 case GOT_OBJ_TYPE_BLOB:
4253 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
4254 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4255 s->label1, s->label2, tog_diff_algo, s->diff_context,
4256 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4257 break;
4258 case GOT_OBJ_TYPE_TREE:
4259 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
4260 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4261 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4262 s->force_text_diff, s->repo, s->f);
4263 break;
4264 case GOT_OBJ_TYPE_COMMIT: {
4265 const struct got_object_id_queue *parent_ids;
4266 struct got_object_qid *pid;
4267 struct got_commit_object *commit2;
4268 struct got_reflist_head *refs;
4270 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4271 if (err)
4272 goto done;
4273 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4274 /* Show commit info if we're diffing to a parent/root commit. */
4275 if (s->id1 == NULL) {
4276 err = write_commit_info(&s->line_offsets, &s->nlines,
4277 s->id2, refs, s->repo, s->f);
4278 if (err)
4279 goto done;
4280 } else {
4281 parent_ids = got_object_commit_get_parent_ids(commit2);
4282 STAILQ_FOREACH(pid, parent_ids, entry) {
4283 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4284 err = write_commit_info(
4285 &s->line_offsets, &s->nlines,
4286 s->id2, refs, s->repo, s->f);
4287 if (err)
4288 goto done;
4289 break;
4293 got_object_commit_close(commit2);
4295 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4296 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4297 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4298 s->force_text_diff, s->repo, s->f);
4299 break;
4301 default:
4302 err = got_error(GOT_ERR_OBJ_TYPE);
4303 break;
4305 if (err)
4306 goto done;
4307 done:
4308 if (s->f && fflush(s->f) != 0 && err == NULL)
4309 err = got_error_from_errno("fflush");
4310 return err;
4313 static void
4314 diff_view_indicate_progress(struct tog_view *view)
4316 mvwaddstr(view->window, 0, 0, "diffing...");
4317 update_panels();
4318 doupdate();
4321 static const struct got_error *
4322 search_start_diff_view(struct tog_view *view)
4324 struct tog_diff_view_state *s = &view->state.diff;
4326 s->matched_line = 0;
4327 return NULL;
4330 static const struct got_error *
4331 search_next_diff_view(struct tog_view *view)
4333 struct tog_diff_view_state *s = &view->state.diff;
4334 const struct got_error *err = NULL;
4335 int lineno;
4336 char *line = NULL;
4337 size_t linesize = 0;
4338 ssize_t linelen;
4340 if (!view->searching) {
4341 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4342 return NULL;
4345 if (s->matched_line) {
4346 if (view->searching == TOG_SEARCH_FORWARD)
4347 lineno = s->matched_line + 1;
4348 else
4349 lineno = s->matched_line - 1;
4350 } else
4351 lineno = s->first_displayed_line;
4353 while (1) {
4354 off_t offset;
4356 if (lineno <= 0 || lineno > s->nlines) {
4357 if (s->matched_line == 0) {
4358 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4359 break;
4362 if (view->searching == TOG_SEARCH_FORWARD)
4363 lineno = 1;
4364 else
4365 lineno = s->nlines;
4368 offset = s->line_offsets[lineno - 1];
4369 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4370 free(line);
4371 return got_error_from_errno("fseeko");
4373 linelen = getline(&line, &linesize, s->f);
4374 if (linelen != -1) {
4375 char *exstr;
4376 err = expand_tab(&exstr, line);
4377 if (err)
4378 break;
4379 if (match_line(exstr, &view->regex, 1,
4380 &view->regmatch)) {
4381 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4382 s->matched_line = lineno;
4383 free(exstr);
4384 break;
4386 free(exstr);
4388 if (view->searching == TOG_SEARCH_FORWARD)
4389 lineno++;
4390 else
4391 lineno--;
4393 free(line);
4395 if (s->matched_line) {
4396 s->first_displayed_line = s->matched_line;
4397 s->selected_line = 1;
4400 return err;
4403 static const struct got_error *
4404 close_diff_view(struct tog_view *view)
4406 const struct got_error *err = NULL;
4407 struct tog_diff_view_state *s = &view->state.diff;
4409 free(s->id1);
4410 s->id1 = NULL;
4411 free(s->id2);
4412 s->id2 = NULL;
4413 if (s->f && fclose(s->f) == EOF)
4414 err = got_error_from_errno("fclose");
4415 s->f = NULL;
4416 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4417 err = got_error_from_errno("fclose");
4418 s->f1 = NULL;
4419 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4420 err = got_error_from_errno("fclose");
4421 s->f2 = NULL;
4422 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4423 err = got_error_from_errno("close");
4424 s->fd1 = -1;
4425 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4426 err = got_error_from_errno("close");
4427 s->fd2 = -1;
4428 free_colors(&s->colors);
4429 free(s->line_offsets);
4430 s->line_offsets = NULL;
4431 s->nlines = 0;
4432 return err;
4435 static const struct got_error *
4436 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4437 struct got_object_id *id2, const char *label1, const char *label2,
4438 int diff_context, int ignore_whitespace, int force_text_diff,
4439 struct tog_view *parent_view, struct got_repository *repo)
4441 const struct got_error *err;
4442 struct tog_diff_view_state *s = &view->state.diff;
4444 memset(s, 0, sizeof(*s));
4445 s->fd1 = -1;
4446 s->fd2 = -1;
4448 if (id1 != NULL && id2 != NULL) {
4449 int type1, type2;
4450 err = got_object_get_type(&type1, repo, id1);
4451 if (err)
4452 return err;
4453 err = got_object_get_type(&type2, repo, id2);
4454 if (err)
4455 return err;
4457 if (type1 != type2)
4458 return got_error(GOT_ERR_OBJ_TYPE);
4460 s->first_displayed_line = 1;
4461 s->last_displayed_line = view->nlines;
4462 s->selected_line = 1;
4463 s->repo = repo;
4464 s->id1 = id1;
4465 s->id2 = id2;
4466 s->label1 = label1;
4467 s->label2 = label2;
4469 if (id1) {
4470 s->id1 = got_object_id_dup(id1);
4471 if (s->id1 == NULL)
4472 return got_error_from_errno("got_object_id_dup");
4473 } else
4474 s->id1 = NULL;
4476 s->id2 = got_object_id_dup(id2);
4477 if (s->id2 == NULL) {
4478 err = got_error_from_errno("got_object_id_dup");
4479 goto done;
4482 s->f1 = got_opentemp();
4483 if (s->f1 == NULL) {
4484 err = got_error_from_errno("got_opentemp");
4485 goto done;
4488 s->f2 = got_opentemp();
4489 if (s->f2 == NULL) {
4490 err = got_error_from_errno("got_opentemp");
4491 goto done;
4494 s->fd1 = got_opentempfd();
4495 if (s->fd1 == -1) {
4496 err = got_error_from_errno("got_opentempfd");
4497 goto done;
4500 s->fd2 = got_opentempfd();
4501 if (s->fd2 == -1) {
4502 err = got_error_from_errno("got_opentempfd");
4503 goto done;
4506 s->first_displayed_line = 1;
4507 s->last_displayed_line = view->nlines;
4508 s->diff_context = diff_context;
4509 s->ignore_whitespace = ignore_whitespace;
4510 s->force_text_diff = force_text_diff;
4511 s->parent_view = parent_view;
4512 s->repo = repo;
4514 STAILQ_INIT(&s->colors);
4515 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4516 err = add_color(&s->colors,
4517 "^-", TOG_COLOR_DIFF_MINUS,
4518 get_color_value("TOG_COLOR_DIFF_MINUS"));
4519 if (err)
4520 goto done;
4521 err = add_color(&s->colors, "^\\+",
4522 TOG_COLOR_DIFF_PLUS,
4523 get_color_value("TOG_COLOR_DIFF_PLUS"));
4524 if (err)
4525 goto done;
4526 err = add_color(&s->colors,
4527 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4528 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4529 if (err)
4530 goto done;
4532 err = add_color(&s->colors,
4533 "^(commit [0-9a-f]|parent [0-9]|"
4534 "(blob|file|tree|commit) [-+] |"
4535 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4536 get_color_value("TOG_COLOR_DIFF_META"));
4537 if (err)
4538 goto done;
4540 err = add_color(&s->colors,
4541 "^(from|via): ", TOG_COLOR_AUTHOR,
4542 get_color_value("TOG_COLOR_AUTHOR"));
4543 if (err)
4544 goto done;
4546 err = add_color(&s->colors,
4547 "^date: ", TOG_COLOR_DATE,
4548 get_color_value("TOG_COLOR_DATE"));
4549 if (err)
4550 goto done;
4553 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4554 view_is_splitscreen(view))
4555 show_log_view(parent_view); /* draw border */
4556 diff_view_indicate_progress(view);
4558 err = create_diff(s);
4560 view->show = show_diff_view;
4561 view->input = input_diff_view;
4562 view->reset = reset_diff_view;
4563 view->close = close_diff_view;
4564 view->search_start = search_start_diff_view;
4565 view->search_next = search_next_diff_view;
4566 done:
4567 if (err)
4568 close_diff_view(view);
4569 return err;
4572 static const struct got_error *
4573 show_diff_view(struct tog_view *view)
4575 const struct got_error *err;
4576 struct tog_diff_view_state *s = &view->state.diff;
4577 char *id_str1 = NULL, *id_str2, *header;
4578 const char *label1, *label2;
4580 if (s->id1) {
4581 err = got_object_id_str(&id_str1, s->id1);
4582 if (err)
4583 return err;
4584 label1 = s->label1 ? : id_str1;
4585 } else
4586 label1 = "/dev/null";
4588 err = got_object_id_str(&id_str2, s->id2);
4589 if (err)
4590 return err;
4591 label2 = s->label2 ? : id_str2;
4593 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4594 err = got_error_from_errno("asprintf");
4595 free(id_str1);
4596 free(id_str2);
4597 return err;
4599 free(id_str1);
4600 free(id_str2);
4602 err = draw_file(view, header);
4603 free(header);
4604 return err;
4607 static const struct got_error *
4608 set_selected_commit(struct tog_diff_view_state *s,
4609 struct commit_queue_entry *entry)
4611 const struct got_error *err;
4612 const struct got_object_id_queue *parent_ids;
4613 struct got_commit_object *selected_commit;
4614 struct got_object_qid *pid;
4616 free(s->id2);
4617 s->id2 = got_object_id_dup(entry->id);
4618 if (s->id2 == NULL)
4619 return got_error_from_errno("got_object_id_dup");
4621 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4622 if (err)
4623 return err;
4624 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4625 free(s->id1);
4626 pid = STAILQ_FIRST(parent_ids);
4627 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4628 got_object_commit_close(selected_commit);
4629 return NULL;
4632 static const struct got_error *
4633 reset_diff_view(struct tog_view *view)
4635 struct tog_diff_view_state *s = &view->state.diff;
4637 view->count = 0;
4638 wclear(view->window);
4639 s->first_displayed_line = 1;
4640 s->last_displayed_line = view->nlines;
4641 s->matched_line = 0;
4642 diff_view_indicate_progress(view);
4643 return create_diff(s);
4646 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4647 int, int, int);
4648 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4649 int, int);
4651 static const struct got_error *
4652 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4654 const struct got_error *err = NULL;
4655 struct tog_diff_view_state *s = &view->state.diff;
4656 struct tog_log_view_state *ls;
4657 struct commit_queue_entry *old_selected_entry;
4658 char *line = NULL;
4659 size_t linesize = 0;
4660 ssize_t linelen;
4661 int i, nscroll = view->nlines - 1, up = 0;
4663 switch (ch) {
4664 case '0':
4665 view->x = 0;
4666 break;
4667 case '$':
4668 view->x = MAX(view->maxx - view->ncols / 3, 0);
4669 view->count = 0;
4670 break;
4671 case KEY_RIGHT:
4672 case 'l':
4673 if (view->x + view->ncols / 3 < view->maxx)
4674 view->x += 2; /* move two columns right */
4675 else
4676 view->count = 0;
4677 break;
4678 case KEY_LEFT:
4679 case 'h':
4680 view->x -= MIN(view->x, 2); /* move two columns back */
4681 if (view->x <= 0)
4682 view->count = 0;
4683 break;
4684 case 'a':
4685 case 'w':
4686 if (ch == 'a')
4687 s->force_text_diff = !s->force_text_diff;
4688 if (ch == 'w')
4689 s->ignore_whitespace = !s->ignore_whitespace;
4690 err = reset_diff_view(view);
4691 break;
4692 case 'g':
4693 case KEY_HOME:
4694 s->first_displayed_line = 1;
4695 view->count = 0;
4696 break;
4697 case 'G':
4698 case KEY_END:
4699 view->count = 0;
4700 if (s->eof)
4701 break;
4703 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4704 s->eof = 1;
4705 break;
4706 case 'k':
4707 case KEY_UP:
4708 case CTRL('p'):
4709 if (s->first_displayed_line > 1)
4710 s->first_displayed_line--;
4711 else
4712 view->count = 0;
4713 break;
4714 case CTRL('u'):
4715 case 'u':
4716 nscroll /= 2;
4717 /* FALL THROUGH */
4718 case KEY_PPAGE:
4719 case CTRL('b'):
4720 case 'b':
4721 if (s->first_displayed_line == 1) {
4722 view->count = 0;
4723 break;
4725 i = 0;
4726 while (i++ < nscroll && s->first_displayed_line > 1)
4727 s->first_displayed_line--;
4728 break;
4729 case 'j':
4730 case KEY_DOWN:
4731 case CTRL('n'):
4732 if (!s->eof)
4733 s->first_displayed_line++;
4734 else
4735 view->count = 0;
4736 break;
4737 case CTRL('d'):
4738 case 'd':
4739 nscroll /= 2;
4740 /* FALL THROUGH */
4741 case KEY_NPAGE:
4742 case CTRL('f'):
4743 case 'f':
4744 case ' ':
4745 if (s->eof) {
4746 view->count = 0;
4747 break;
4749 i = 0;
4750 while (!s->eof && i++ < nscroll) {
4751 linelen = getline(&line, &linesize, s->f);
4752 s->first_displayed_line++;
4753 if (linelen == -1) {
4754 if (feof(s->f)) {
4755 s->eof = 1;
4756 } else
4757 err = got_ferror(s->f, GOT_ERR_IO);
4758 break;
4761 free(line);
4762 break;
4763 case '[':
4764 if (s->diff_context > 0) {
4765 s->diff_context--;
4766 s->matched_line = 0;
4767 diff_view_indicate_progress(view);
4768 err = create_diff(s);
4769 if (s->first_displayed_line + view->nlines - 1 >
4770 s->nlines) {
4771 s->first_displayed_line = 1;
4772 s->last_displayed_line = view->nlines;
4774 } else
4775 view->count = 0;
4776 break;
4777 case ']':
4778 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4779 s->diff_context++;
4780 s->matched_line = 0;
4781 diff_view_indicate_progress(view);
4782 err = create_diff(s);
4783 } else
4784 view->count = 0;
4785 break;
4786 case '<':
4787 case ',':
4788 case 'K':
4789 up = 1;
4790 /* FALL THROUGH */
4791 case '>':
4792 case '.':
4793 case 'J':
4794 if (s->parent_view == NULL) {
4795 view->count = 0;
4796 break;
4798 s->parent_view->count = view->count;
4800 if (s->parent_view->type == TOG_VIEW_LOG) {
4801 ls = &s->parent_view->state.log;
4802 old_selected_entry = ls->selected_entry;
4804 err = input_log_view(NULL, s->parent_view,
4805 up ? KEY_UP : KEY_DOWN);
4806 if (err)
4807 break;
4808 view->count = s->parent_view->count;
4810 if (old_selected_entry == ls->selected_entry)
4811 break;
4813 err = set_selected_commit(s, ls->selected_entry);
4814 if (err)
4815 break;
4816 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4817 struct tog_blame_view_state *bs;
4818 struct got_object_id *id, *prev_id;
4820 bs = &s->parent_view->state.blame;
4821 prev_id = get_annotation_for_line(bs->blame.lines,
4822 bs->blame.nlines, bs->last_diffed_line);
4824 err = input_blame_view(&view, s->parent_view,
4825 up ? KEY_UP : KEY_DOWN);
4826 if (err)
4827 break;
4828 view->count = s->parent_view->count;
4830 if (prev_id == NULL)
4831 break;
4832 id = get_selected_commit_id(bs->blame.lines,
4833 bs->blame.nlines, bs->first_displayed_line,
4834 bs->selected_line);
4835 if (id == NULL)
4836 break;
4838 if (!got_object_id_cmp(prev_id, id))
4839 break;
4841 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
4842 if (err)
4843 break;
4845 s->first_displayed_line = 1;
4846 s->last_displayed_line = view->nlines;
4847 s->matched_line = 0;
4848 view->x = 0;
4850 diff_view_indicate_progress(view);
4851 err = create_diff(s);
4852 break;
4853 default:
4854 view->count = 0;
4855 break;
4858 return err;
4861 static const struct got_error *
4862 cmd_diff(int argc, char *argv[])
4864 const struct got_error *error = NULL;
4865 struct got_repository *repo = NULL;
4866 struct got_worktree *worktree = NULL;
4867 struct got_object_id *id1 = NULL, *id2 = NULL;
4868 char *repo_path = NULL, *cwd = NULL;
4869 char *id_str1 = NULL, *id_str2 = NULL;
4870 char *label1 = NULL, *label2 = NULL;
4871 int diff_context = 3, ignore_whitespace = 0;
4872 int ch, force_text_diff = 0;
4873 const char *errstr;
4874 struct tog_view *view;
4875 int *pack_fds = NULL;
4877 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4878 switch (ch) {
4879 case 'a':
4880 force_text_diff = 1;
4881 break;
4882 case 'C':
4883 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4884 &errstr);
4885 if (errstr != NULL)
4886 errx(1, "number of context lines is %s: %s",
4887 errstr, errstr);
4888 break;
4889 case 'r':
4890 repo_path = realpath(optarg, NULL);
4891 if (repo_path == NULL)
4892 return got_error_from_errno2("realpath",
4893 optarg);
4894 got_path_strip_trailing_slashes(repo_path);
4895 break;
4896 case 'w':
4897 ignore_whitespace = 1;
4898 break;
4899 default:
4900 usage_diff();
4901 /* NOTREACHED */
4905 argc -= optind;
4906 argv += optind;
4908 if (argc == 0) {
4909 usage_diff(); /* TODO show local worktree changes */
4910 } else if (argc == 2) {
4911 id_str1 = argv[0];
4912 id_str2 = argv[1];
4913 } else
4914 usage_diff();
4916 error = got_repo_pack_fds_open(&pack_fds);
4917 if (error)
4918 goto done;
4920 if (repo_path == NULL) {
4921 cwd = getcwd(NULL, 0);
4922 if (cwd == NULL)
4923 return got_error_from_errno("getcwd");
4924 error = got_worktree_open(&worktree, cwd);
4925 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4926 goto done;
4927 if (worktree)
4928 repo_path =
4929 strdup(got_worktree_get_repo_path(worktree));
4930 else
4931 repo_path = strdup(cwd);
4932 if (repo_path == NULL) {
4933 error = got_error_from_errno("strdup");
4934 goto done;
4938 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4939 if (error)
4940 goto done;
4942 init_curses();
4944 error = apply_unveil(got_repo_get_path(repo), NULL);
4945 if (error)
4946 goto done;
4948 error = tog_load_refs(repo, 0);
4949 if (error)
4950 goto done;
4952 error = got_repo_match_object_id(&id1, &label1, id_str1,
4953 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4954 if (error)
4955 goto done;
4957 error = got_repo_match_object_id(&id2, &label2, id_str2,
4958 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4959 if (error)
4960 goto done;
4962 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4963 if (view == NULL) {
4964 error = got_error_from_errno("view_open");
4965 goto done;
4967 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4968 ignore_whitespace, force_text_diff, NULL, repo);
4969 if (error)
4970 goto done;
4971 error = view_loop(view);
4972 done:
4973 free(label1);
4974 free(label2);
4975 free(repo_path);
4976 free(cwd);
4977 if (repo) {
4978 const struct got_error *close_err = got_repo_close(repo);
4979 if (error == NULL)
4980 error = close_err;
4982 if (worktree)
4983 got_worktree_close(worktree);
4984 if (pack_fds) {
4985 const struct got_error *pack_err =
4986 got_repo_pack_fds_close(pack_fds);
4987 if (error == NULL)
4988 error = pack_err;
4990 tog_free_refs();
4991 return error;
4994 __dead static void
4995 usage_blame(void)
4997 endwin();
4998 fprintf(stderr,
4999 "usage: %s blame [-c commit] [-r repository-path] path\n",
5000 getprogname());
5001 exit(1);
5004 struct tog_blame_line {
5005 int annotated;
5006 struct got_object_id *id;
5009 static const struct got_error *
5010 draw_blame(struct tog_view *view)
5012 struct tog_blame_view_state *s = &view->state.blame;
5013 struct tog_blame *blame = &s->blame;
5014 regmatch_t *regmatch = &view->regmatch;
5015 const struct got_error *err;
5016 int lineno = 0, nprinted = 0;
5017 char *line = NULL;
5018 size_t linesize = 0;
5019 ssize_t linelen;
5020 wchar_t *wline;
5021 int width;
5022 struct tog_blame_line *blame_line;
5023 struct got_object_id *prev_id = NULL;
5024 char *id_str;
5025 struct tog_color *tc;
5027 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5028 if (err)
5029 return err;
5031 rewind(blame->f);
5032 werase(view->window);
5034 if (asprintf(&line, "commit %s", id_str) == -1) {
5035 err = got_error_from_errno("asprintf");
5036 free(id_str);
5037 return err;
5040 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5041 free(line);
5042 line = NULL;
5043 if (err)
5044 return err;
5045 if (view_needs_focus_indication(view))
5046 wstandout(view->window);
5047 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5048 if (tc)
5049 wattr_on(view->window,
5050 COLOR_PAIR(tc->colorpair), NULL);
5051 waddwstr(view->window, wline);
5052 if (tc)
5053 wattr_off(view->window,
5054 COLOR_PAIR(tc->colorpair), NULL);
5055 if (view_needs_focus_indication(view))
5056 wstandend(view->window);
5057 free(wline);
5058 wline = NULL;
5059 if (width < view->ncols - 1)
5060 waddch(view->window, '\n');
5062 if (asprintf(&line, "[%d/%d] %s%s",
5063 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5064 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5065 free(id_str);
5066 return got_error_from_errno("asprintf");
5068 free(id_str);
5069 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5070 free(line);
5071 line = NULL;
5072 if (err)
5073 return err;
5074 waddwstr(view->window, wline);
5075 free(wline);
5076 wline = NULL;
5077 if (width < view->ncols - 1)
5078 waddch(view->window, '\n');
5080 s->eof = 0;
5081 view->maxx = 0;
5082 while (nprinted < view->nlines - 2) {
5083 linelen = getline(&line, &linesize, blame->f);
5084 if (linelen == -1) {
5085 if (feof(blame->f)) {
5086 s->eof = 1;
5087 break;
5089 free(line);
5090 return got_ferror(blame->f, GOT_ERR_IO);
5092 if (++lineno < s->first_displayed_line)
5093 continue;
5095 /* Set view->maxx based on full line length. */
5096 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5097 if (err) {
5098 free(line);
5099 return err;
5101 free(wline);
5102 wline = NULL;
5103 view->maxx = MAX(view->maxx, width);
5105 if (nprinted == s->selected_line - 1)
5106 wstandout(view->window);
5108 if (blame->nlines > 0) {
5109 blame_line = &blame->lines[lineno - 1];
5110 if (blame_line->annotated && prev_id &&
5111 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5112 !(nprinted == s->selected_line - 1)) {
5113 waddstr(view->window, " ");
5114 } else if (blame_line->annotated) {
5115 char *id_str;
5116 err = got_object_id_str(&id_str,
5117 blame_line->id);
5118 if (err) {
5119 free(line);
5120 return err;
5122 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5123 if (tc)
5124 wattr_on(view->window,
5125 COLOR_PAIR(tc->colorpair), NULL);
5126 wprintw(view->window, "%.8s", id_str);
5127 if (tc)
5128 wattr_off(view->window,
5129 COLOR_PAIR(tc->colorpair), NULL);
5130 free(id_str);
5131 prev_id = blame_line->id;
5132 } else {
5133 waddstr(view->window, "........");
5134 prev_id = NULL;
5136 } else {
5137 waddstr(view->window, "........");
5138 prev_id = NULL;
5141 if (nprinted == s->selected_line - 1)
5142 wstandend(view->window);
5143 waddstr(view->window, " ");
5145 if (view->ncols <= 9) {
5146 width = 9;
5147 } else if (s->first_displayed_line + nprinted ==
5148 s->matched_line &&
5149 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5150 err = add_matched_line(&width, line, view->ncols - 9, 9,
5151 view->window, view->x, regmatch);
5152 if (err) {
5153 free(line);
5154 return err;
5156 width += 9;
5157 } else {
5158 int skip;
5159 err = format_line(&wline, &width, &skip, line,
5160 view->x, view->ncols - 9, 9, 1);
5161 if (err) {
5162 free(line);
5163 return err;
5165 waddwstr(view->window, &wline[skip]);
5166 width += 9;
5167 free(wline);
5168 wline = NULL;
5171 if (width <= view->ncols - 1)
5172 waddch(view->window, '\n');
5173 if (++nprinted == 1)
5174 s->first_displayed_line = lineno;
5176 free(line);
5177 s->last_displayed_line = lineno;
5179 view_border(view);
5181 return NULL;
5184 static const struct got_error *
5185 blame_cb(void *arg, int nlines, int lineno,
5186 struct got_commit_object *commit, struct got_object_id *id)
5188 const struct got_error *err = NULL;
5189 struct tog_blame_cb_args *a = arg;
5190 struct tog_blame_line *line;
5191 int errcode;
5193 if (nlines != a->nlines ||
5194 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5195 return got_error(GOT_ERR_RANGE);
5197 errcode = pthread_mutex_lock(&tog_mutex);
5198 if (errcode)
5199 return got_error_set_errno(errcode, "pthread_mutex_lock");
5201 if (*a->quit) { /* user has quit the blame view */
5202 err = got_error(GOT_ERR_ITER_COMPLETED);
5203 goto done;
5206 if (lineno == -1)
5207 goto done; /* no change in this commit */
5209 line = &a->lines[lineno - 1];
5210 if (line->annotated)
5211 goto done;
5213 line->id = got_object_id_dup(id);
5214 if (line->id == NULL) {
5215 err = got_error_from_errno("got_object_id_dup");
5216 goto done;
5218 line->annotated = 1;
5219 done:
5220 errcode = pthread_mutex_unlock(&tog_mutex);
5221 if (errcode)
5222 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5223 return err;
5226 static void *
5227 blame_thread(void *arg)
5229 const struct got_error *err, *close_err;
5230 struct tog_blame_thread_args *ta = arg;
5231 struct tog_blame_cb_args *a = ta->cb_args;
5232 int errcode, fd1 = -1, fd2 = -1;
5233 FILE *f1 = NULL, *f2 = NULL;
5235 fd1 = got_opentempfd();
5236 if (fd1 == -1)
5237 return (void *)got_error_from_errno("got_opentempfd");
5239 fd2 = got_opentempfd();
5240 if (fd2 == -1) {
5241 err = got_error_from_errno("got_opentempfd");
5242 goto done;
5245 f1 = got_opentemp();
5246 if (f1 == NULL) {
5247 err = (void *)got_error_from_errno("got_opentemp");
5248 goto done;
5250 f2 = got_opentemp();
5251 if (f2 == NULL) {
5252 err = (void *)got_error_from_errno("got_opentemp");
5253 goto done;
5256 err = block_signals_used_by_main_thread();
5257 if (err)
5258 goto done;
5260 err = got_blame(ta->path, a->commit_id, ta->repo,
5261 tog_diff_algo, blame_cb, ta->cb_args,
5262 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5263 if (err && err->code == GOT_ERR_CANCELLED)
5264 err = NULL;
5266 errcode = pthread_mutex_lock(&tog_mutex);
5267 if (errcode) {
5268 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5269 goto done;
5272 close_err = got_repo_close(ta->repo);
5273 if (err == NULL)
5274 err = close_err;
5275 ta->repo = NULL;
5276 *ta->complete = 1;
5278 errcode = pthread_mutex_unlock(&tog_mutex);
5279 if (errcode && err == NULL)
5280 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5282 done:
5283 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5284 err = got_error_from_errno("close");
5285 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5286 err = got_error_from_errno("close");
5287 if (f1 && fclose(f1) == EOF && err == NULL)
5288 err = got_error_from_errno("fclose");
5289 if (f2 && fclose(f2) == EOF && err == NULL)
5290 err = got_error_from_errno("fclose");
5292 return (void *)err;
5295 static struct got_object_id *
5296 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5297 int first_displayed_line, int selected_line)
5299 struct tog_blame_line *line;
5301 if (nlines <= 0)
5302 return NULL;
5304 line = &lines[first_displayed_line - 1 + selected_line - 1];
5305 if (!line->annotated)
5306 return NULL;
5308 return line->id;
5311 static struct got_object_id *
5312 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5313 int lineno)
5315 struct tog_blame_line *line;
5317 if (nlines <= 0 || lineno >= nlines)
5318 return NULL;
5320 line = &lines[lineno - 1];
5321 if (!line->annotated)
5322 return NULL;
5324 return line->id;
5327 static const struct got_error *
5328 stop_blame(struct tog_blame *blame)
5330 const struct got_error *err = NULL;
5331 int i;
5333 if (blame->thread) {
5334 int errcode;
5335 errcode = pthread_mutex_unlock(&tog_mutex);
5336 if (errcode)
5337 return got_error_set_errno(errcode,
5338 "pthread_mutex_unlock");
5339 errcode = pthread_join(blame->thread, (void **)&err);
5340 if (errcode)
5341 return got_error_set_errno(errcode, "pthread_join");
5342 errcode = pthread_mutex_lock(&tog_mutex);
5343 if (errcode)
5344 return got_error_set_errno(errcode,
5345 "pthread_mutex_lock");
5346 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5347 err = NULL;
5348 blame->thread = NULL;
5350 if (blame->thread_args.repo) {
5351 const struct got_error *close_err;
5352 close_err = got_repo_close(blame->thread_args.repo);
5353 if (err == NULL)
5354 err = close_err;
5355 blame->thread_args.repo = NULL;
5357 if (blame->f) {
5358 if (fclose(blame->f) == EOF && err == NULL)
5359 err = got_error_from_errno("fclose");
5360 blame->f = NULL;
5362 if (blame->lines) {
5363 for (i = 0; i < blame->nlines; i++)
5364 free(blame->lines[i].id);
5365 free(blame->lines);
5366 blame->lines = NULL;
5368 free(blame->cb_args.commit_id);
5369 blame->cb_args.commit_id = NULL;
5370 if (blame->pack_fds) {
5371 const struct got_error *pack_err =
5372 got_repo_pack_fds_close(blame->pack_fds);
5373 if (err == NULL)
5374 err = pack_err;
5375 blame->pack_fds = NULL;
5377 return err;
5380 static const struct got_error *
5381 cancel_blame_view(void *arg)
5383 const struct got_error *err = NULL;
5384 int *done = arg;
5385 int errcode;
5387 errcode = pthread_mutex_lock(&tog_mutex);
5388 if (errcode)
5389 return got_error_set_errno(errcode,
5390 "pthread_mutex_unlock");
5392 if (*done)
5393 err = got_error(GOT_ERR_CANCELLED);
5395 errcode = pthread_mutex_unlock(&tog_mutex);
5396 if (errcode)
5397 return got_error_set_errno(errcode,
5398 "pthread_mutex_lock");
5400 return err;
5403 static const struct got_error *
5404 run_blame(struct tog_view *view)
5406 struct tog_blame_view_state *s = &view->state.blame;
5407 struct tog_blame *blame = &s->blame;
5408 const struct got_error *err = NULL;
5409 struct got_commit_object *commit = NULL;
5410 struct got_blob_object *blob = NULL;
5411 struct got_repository *thread_repo = NULL;
5412 struct got_object_id *obj_id = NULL;
5413 int obj_type, fd = -1;
5414 int *pack_fds = NULL;
5416 err = got_object_open_as_commit(&commit, s->repo,
5417 &s->blamed_commit->id);
5418 if (err)
5419 return err;
5421 fd = got_opentempfd();
5422 if (fd == -1) {
5423 err = got_error_from_errno("got_opentempfd");
5424 goto done;
5427 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5428 if (err)
5429 goto done;
5431 err = got_object_get_type(&obj_type, s->repo, obj_id);
5432 if (err)
5433 goto done;
5435 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5436 err = got_error(GOT_ERR_OBJ_TYPE);
5437 goto done;
5440 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5441 if (err)
5442 goto done;
5443 blame->f = got_opentemp();
5444 if (blame->f == NULL) {
5445 err = got_error_from_errno("got_opentemp");
5446 goto done;
5448 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5449 &blame->line_offsets, blame->f, blob);
5450 if (err)
5451 goto done;
5452 if (blame->nlines == 0) {
5453 s->blame_complete = 1;
5454 goto done;
5457 /* Don't include \n at EOF in the blame line count. */
5458 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5459 blame->nlines--;
5461 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5462 if (blame->lines == NULL) {
5463 err = got_error_from_errno("calloc");
5464 goto done;
5467 err = got_repo_pack_fds_open(&pack_fds);
5468 if (err)
5469 goto done;
5470 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5471 pack_fds);
5472 if (err)
5473 goto done;
5475 blame->pack_fds = pack_fds;
5476 blame->cb_args.view = view;
5477 blame->cb_args.lines = blame->lines;
5478 blame->cb_args.nlines = blame->nlines;
5479 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5480 if (blame->cb_args.commit_id == NULL) {
5481 err = got_error_from_errno("got_object_id_dup");
5482 goto done;
5484 blame->cb_args.quit = &s->done;
5486 blame->thread_args.path = s->path;
5487 blame->thread_args.repo = thread_repo;
5488 blame->thread_args.cb_args = &blame->cb_args;
5489 blame->thread_args.complete = &s->blame_complete;
5490 blame->thread_args.cancel_cb = cancel_blame_view;
5491 blame->thread_args.cancel_arg = &s->done;
5492 s->blame_complete = 0;
5494 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5495 s->first_displayed_line = 1;
5496 s->last_displayed_line = view->nlines;
5497 s->selected_line = 1;
5499 s->matched_line = 0;
5501 done:
5502 if (commit)
5503 got_object_commit_close(commit);
5504 if (fd != -1 && close(fd) == -1 && err == NULL)
5505 err = got_error_from_errno("close");
5506 if (blob)
5507 got_object_blob_close(blob);
5508 free(obj_id);
5509 if (err)
5510 stop_blame(blame);
5511 return err;
5514 static const struct got_error *
5515 open_blame_view(struct tog_view *view, char *path,
5516 struct got_object_id *commit_id, struct got_repository *repo)
5518 const struct got_error *err = NULL;
5519 struct tog_blame_view_state *s = &view->state.blame;
5521 STAILQ_INIT(&s->blamed_commits);
5523 s->path = strdup(path);
5524 if (s->path == NULL)
5525 return got_error_from_errno("strdup");
5527 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5528 if (err) {
5529 free(s->path);
5530 return err;
5533 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5534 s->first_displayed_line = 1;
5535 s->last_displayed_line = view->nlines;
5536 s->selected_line = 1;
5537 s->blame_complete = 0;
5538 s->repo = repo;
5539 s->commit_id = commit_id;
5540 memset(&s->blame, 0, sizeof(s->blame));
5542 STAILQ_INIT(&s->colors);
5543 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5544 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5545 get_color_value("TOG_COLOR_COMMIT"));
5546 if (err)
5547 return err;
5550 view->show = show_blame_view;
5551 view->input = input_blame_view;
5552 view->reset = reset_blame_view;
5553 view->close = close_blame_view;
5554 view->search_start = search_start_blame_view;
5555 view->search_next = search_next_blame_view;
5557 return run_blame(view);
5560 static const struct got_error *
5561 close_blame_view(struct tog_view *view)
5563 const struct got_error *err = NULL;
5564 struct tog_blame_view_state *s = &view->state.blame;
5566 if (s->blame.thread)
5567 err = stop_blame(&s->blame);
5569 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5570 struct got_object_qid *blamed_commit;
5571 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5572 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5573 got_object_qid_free(blamed_commit);
5576 free(s->path);
5577 free_colors(&s->colors);
5578 return err;
5581 static const struct got_error *
5582 search_start_blame_view(struct tog_view *view)
5584 struct tog_blame_view_state *s = &view->state.blame;
5586 s->matched_line = 0;
5587 return NULL;
5590 static const struct got_error *
5591 search_next_blame_view(struct tog_view *view)
5593 struct tog_blame_view_state *s = &view->state.blame;
5594 const struct got_error *err = NULL;
5595 int lineno;
5596 char *line = NULL;
5597 size_t linesize = 0;
5598 ssize_t linelen;
5600 if (!view->searching) {
5601 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5602 return NULL;
5605 if (s->matched_line) {
5606 if (view->searching == TOG_SEARCH_FORWARD)
5607 lineno = s->matched_line + 1;
5608 else
5609 lineno = s->matched_line - 1;
5610 } else
5611 lineno = s->first_displayed_line - 1 + s->selected_line;
5613 while (1) {
5614 off_t offset;
5616 if (lineno <= 0 || lineno > s->blame.nlines) {
5617 if (s->matched_line == 0) {
5618 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5619 break;
5622 if (view->searching == TOG_SEARCH_FORWARD)
5623 lineno = 1;
5624 else
5625 lineno = s->blame.nlines;
5628 offset = s->blame.line_offsets[lineno - 1];
5629 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5630 free(line);
5631 return got_error_from_errno("fseeko");
5633 linelen = getline(&line, &linesize, s->blame.f);
5634 if (linelen != -1) {
5635 char *exstr;
5636 err = expand_tab(&exstr, line);
5637 if (err)
5638 break;
5639 if (match_line(exstr, &view->regex, 1,
5640 &view->regmatch)) {
5641 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5642 s->matched_line = lineno;
5643 free(exstr);
5644 break;
5646 free(exstr);
5648 if (view->searching == TOG_SEARCH_FORWARD)
5649 lineno++;
5650 else
5651 lineno--;
5653 free(line);
5655 if (s->matched_line) {
5656 s->first_displayed_line = s->matched_line;
5657 s->selected_line = 1;
5660 return err;
5663 static const struct got_error *
5664 show_blame_view(struct tog_view *view)
5666 const struct got_error *err = NULL;
5667 struct tog_blame_view_state *s = &view->state.blame;
5668 int errcode;
5670 if (s->blame.thread == NULL && !s->blame_complete) {
5671 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5672 &s->blame.thread_args);
5673 if (errcode)
5674 return got_error_set_errno(errcode, "pthread_create");
5676 halfdelay(1); /* fast refresh while annotating */
5679 if (s->blame_complete)
5680 halfdelay(10); /* disable fast refresh */
5682 err = draw_blame(view);
5684 view_border(view);
5685 return err;
5688 static const struct got_error *
5689 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5690 struct got_repository *repo, struct got_object_id *id)
5692 struct tog_view *log_view;
5693 const struct got_error *err = NULL;
5695 *new_view = NULL;
5697 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5698 if (log_view == NULL)
5699 return got_error_from_errno("view_open");
5701 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5702 if (err)
5703 view_close(log_view);
5704 else
5705 *new_view = log_view;
5707 return err;
5710 static const struct got_error *
5711 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5713 const struct got_error *err = NULL, *thread_err = NULL;
5714 struct tog_view *diff_view;
5715 struct tog_blame_view_state *s = &view->state.blame;
5716 int eos, nscroll, begin_y = 0, begin_x = 0;
5718 eos = nscroll = view->nlines - 2;
5719 if (view_is_hsplit_top(view))
5720 --eos; /* border */
5722 switch (ch) {
5723 case '0':
5724 view->x = 0;
5725 break;
5726 case '$':
5727 view->x = MAX(view->maxx - view->ncols / 3, 0);
5728 view->count = 0;
5729 break;
5730 case KEY_RIGHT:
5731 case 'l':
5732 if (view->x + view->ncols / 3 < view->maxx)
5733 view->x += 2; /* move two columns right */
5734 else
5735 view->count = 0;
5736 break;
5737 case KEY_LEFT:
5738 case 'h':
5739 view->x -= MIN(view->x, 2); /* move two columns back */
5740 if (view->x <= 0)
5741 view->count = 0;
5742 break;
5743 case 'q':
5744 s->done = 1;
5745 break;
5746 case 'g':
5747 case KEY_HOME:
5748 s->selected_line = 1;
5749 s->first_displayed_line = 1;
5750 view->count = 0;
5751 break;
5752 case 'G':
5753 case KEY_END:
5754 if (s->blame.nlines < eos) {
5755 s->selected_line = s->blame.nlines;
5756 s->first_displayed_line = 1;
5757 } else {
5758 s->selected_line = eos;
5759 s->first_displayed_line = s->blame.nlines - (eos - 1);
5761 view->count = 0;
5762 break;
5763 case 'k':
5764 case KEY_UP:
5765 case CTRL('p'):
5766 if (s->selected_line > 1)
5767 s->selected_line--;
5768 else if (s->selected_line == 1 &&
5769 s->first_displayed_line > 1)
5770 s->first_displayed_line--;
5771 else
5772 view->count = 0;
5773 break;
5774 case CTRL('u'):
5775 case 'u':
5776 nscroll /= 2;
5777 /* FALL THROUGH */
5778 case KEY_PPAGE:
5779 case CTRL('b'):
5780 case 'b':
5781 if (s->first_displayed_line == 1) {
5782 if (view->count > 1)
5783 nscroll += nscroll;
5784 s->selected_line = MAX(1, s->selected_line - nscroll);
5785 view->count = 0;
5786 break;
5788 if (s->first_displayed_line > nscroll)
5789 s->first_displayed_line -= nscroll;
5790 else
5791 s->first_displayed_line = 1;
5792 break;
5793 case 'j':
5794 case KEY_DOWN:
5795 case CTRL('n'):
5796 if (s->selected_line < eos && s->first_displayed_line +
5797 s->selected_line <= s->blame.nlines)
5798 s->selected_line++;
5799 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5800 s->first_displayed_line++;
5801 else
5802 view->count = 0;
5803 break;
5804 case 'c':
5805 case 'p': {
5806 struct got_object_id *id = NULL;
5808 view->count = 0;
5809 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5810 s->first_displayed_line, s->selected_line);
5811 if (id == NULL)
5812 break;
5813 if (ch == 'p') {
5814 struct got_commit_object *commit, *pcommit;
5815 struct got_object_qid *pid;
5816 struct got_object_id *blob_id = NULL;
5817 int obj_type;
5818 err = got_object_open_as_commit(&commit,
5819 s->repo, id);
5820 if (err)
5821 break;
5822 pid = STAILQ_FIRST(
5823 got_object_commit_get_parent_ids(commit));
5824 if (pid == NULL) {
5825 got_object_commit_close(commit);
5826 break;
5828 /* Check if path history ends here. */
5829 err = got_object_open_as_commit(&pcommit,
5830 s->repo, &pid->id);
5831 if (err)
5832 break;
5833 err = got_object_id_by_path(&blob_id, s->repo,
5834 pcommit, s->path);
5835 got_object_commit_close(pcommit);
5836 if (err) {
5837 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5838 err = NULL;
5839 got_object_commit_close(commit);
5840 break;
5842 err = got_object_get_type(&obj_type, s->repo,
5843 blob_id);
5844 free(blob_id);
5845 /* Can't blame non-blob type objects. */
5846 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5847 got_object_commit_close(commit);
5848 break;
5850 err = got_object_qid_alloc(&s->blamed_commit,
5851 &pid->id);
5852 got_object_commit_close(commit);
5853 } else {
5854 if (got_object_id_cmp(id,
5855 &s->blamed_commit->id) == 0)
5856 break;
5857 err = got_object_qid_alloc(&s->blamed_commit,
5858 id);
5860 if (err)
5861 break;
5862 s->done = 1;
5863 thread_err = stop_blame(&s->blame);
5864 s->done = 0;
5865 if (thread_err)
5866 break;
5867 STAILQ_INSERT_HEAD(&s->blamed_commits,
5868 s->blamed_commit, entry);
5869 err = run_blame(view);
5870 if (err)
5871 break;
5872 break;
5874 case 'C': {
5875 struct got_object_qid *first;
5877 view->count = 0;
5878 first = STAILQ_FIRST(&s->blamed_commits);
5879 if (!got_object_id_cmp(&first->id, s->commit_id))
5880 break;
5881 s->done = 1;
5882 thread_err = stop_blame(&s->blame);
5883 s->done = 0;
5884 if (thread_err)
5885 break;
5886 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5887 got_object_qid_free(s->blamed_commit);
5888 s->blamed_commit =
5889 STAILQ_FIRST(&s->blamed_commits);
5890 err = run_blame(view);
5891 if (err)
5892 break;
5893 break;
5895 case 'L':
5896 view->count = 0;
5897 s->id_to_log = get_selected_commit_id(s->blame.lines,
5898 s->blame.nlines, s->first_displayed_line, s->selected_line);
5899 if (s->id_to_log)
5900 err = view_request_new(new_view, view, TOG_VIEW_LOG);
5901 break;
5902 case KEY_ENTER:
5903 case '\r': {
5904 struct got_object_id *id = NULL;
5905 struct got_object_qid *pid;
5906 struct got_commit_object *commit = NULL;
5908 view->count = 0;
5909 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5910 s->first_displayed_line, s->selected_line);
5911 if (id == NULL)
5912 break;
5913 err = got_object_open_as_commit(&commit, s->repo, id);
5914 if (err)
5915 break;
5916 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5917 if (*new_view) {
5918 /* traversed from diff view, release diff resources */
5919 err = close_diff_view(*new_view);
5920 if (err)
5921 break;
5922 diff_view = *new_view;
5923 } else {
5924 if (view_is_parent_view(view))
5925 view_get_split(view, &begin_y, &begin_x);
5927 diff_view = view_open(0, 0, begin_y, begin_x,
5928 TOG_VIEW_DIFF);
5929 if (diff_view == NULL) {
5930 got_object_commit_close(commit);
5931 err = got_error_from_errno("view_open");
5932 break;
5935 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5936 id, NULL, NULL, 3, 0, 0, view, s->repo);
5937 got_object_commit_close(commit);
5938 if (err) {
5939 view_close(diff_view);
5940 break;
5942 s->last_diffed_line = s->first_displayed_line - 1 +
5943 s->selected_line;
5944 if (*new_view)
5945 break; /* still open from active diff view */
5946 if (view_is_parent_view(view) &&
5947 view->mode == TOG_VIEW_SPLIT_HRZN) {
5948 err = view_init_hsplit(view, begin_y);
5949 if (err)
5950 break;
5953 view->focussed = 0;
5954 diff_view->focussed = 1;
5955 diff_view->mode = view->mode;
5956 diff_view->nlines = view->lines - begin_y;
5957 if (view_is_parent_view(view)) {
5958 view_transfer_size(diff_view, view);
5959 err = view_close_child(view);
5960 if (err)
5961 break;
5962 err = view_set_child(view, diff_view);
5963 if (err)
5964 break;
5965 view->focus_child = 1;
5966 } else
5967 *new_view = diff_view;
5968 if (err)
5969 break;
5970 break;
5972 case CTRL('d'):
5973 case 'd':
5974 nscroll /= 2;
5975 /* FALL THROUGH */
5976 case KEY_NPAGE:
5977 case CTRL('f'):
5978 case 'f':
5979 case ' ':
5980 if (s->last_displayed_line >= s->blame.nlines &&
5981 s->selected_line >= MIN(s->blame.nlines,
5982 view->nlines - 2)) {
5983 view->count = 0;
5984 break;
5986 if (s->last_displayed_line >= s->blame.nlines &&
5987 s->selected_line < view->nlines - 2) {
5988 s->selected_line +=
5989 MIN(nscroll, s->last_displayed_line -
5990 s->first_displayed_line - s->selected_line + 1);
5992 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5993 s->first_displayed_line += nscroll;
5994 else
5995 s->first_displayed_line =
5996 s->blame.nlines - (view->nlines - 3);
5997 break;
5998 case KEY_RESIZE:
5999 if (s->selected_line > view->nlines - 2) {
6000 s->selected_line = MIN(s->blame.nlines,
6001 view->nlines - 2);
6003 break;
6004 default:
6005 view->count = 0;
6006 break;
6008 return thread_err ? thread_err : err;
6011 static const struct got_error *
6012 reset_blame_view(struct tog_view *view)
6014 const struct got_error *err;
6015 struct tog_blame_view_state *s = &view->state.blame;
6017 view->count = 0;
6018 s->done = 1;
6019 err = stop_blame(&s->blame);
6020 s->done = 0;
6021 if (err)
6022 return err;
6023 return run_blame(view);
6026 static const struct got_error *
6027 cmd_blame(int argc, char *argv[])
6029 const struct got_error *error;
6030 struct got_repository *repo = NULL;
6031 struct got_worktree *worktree = NULL;
6032 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6033 char *link_target = NULL;
6034 struct got_object_id *commit_id = NULL;
6035 struct got_commit_object *commit = NULL;
6036 char *commit_id_str = NULL;
6037 int ch;
6038 struct tog_view *view;
6039 int *pack_fds = NULL;
6041 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6042 switch (ch) {
6043 case 'c':
6044 commit_id_str = optarg;
6045 break;
6046 case 'r':
6047 repo_path = realpath(optarg, NULL);
6048 if (repo_path == NULL)
6049 return got_error_from_errno2("realpath",
6050 optarg);
6051 break;
6052 default:
6053 usage_blame();
6054 /* NOTREACHED */
6058 argc -= optind;
6059 argv += optind;
6061 if (argc != 1)
6062 usage_blame();
6064 error = got_repo_pack_fds_open(&pack_fds);
6065 if (error != NULL)
6066 goto done;
6068 if (repo_path == NULL) {
6069 cwd = getcwd(NULL, 0);
6070 if (cwd == NULL)
6071 return got_error_from_errno("getcwd");
6072 error = got_worktree_open(&worktree, cwd);
6073 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6074 goto done;
6075 if (worktree)
6076 repo_path =
6077 strdup(got_worktree_get_repo_path(worktree));
6078 else
6079 repo_path = strdup(cwd);
6080 if (repo_path == NULL) {
6081 error = got_error_from_errno("strdup");
6082 goto done;
6086 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6087 if (error != NULL)
6088 goto done;
6090 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6091 worktree);
6092 if (error)
6093 goto done;
6095 init_curses();
6097 error = apply_unveil(got_repo_get_path(repo), NULL);
6098 if (error)
6099 goto done;
6101 error = tog_load_refs(repo, 0);
6102 if (error)
6103 goto done;
6105 if (commit_id_str == NULL) {
6106 struct got_reference *head_ref;
6107 error = got_ref_open(&head_ref, repo, worktree ?
6108 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6109 if (error != NULL)
6110 goto done;
6111 error = got_ref_resolve(&commit_id, repo, head_ref);
6112 got_ref_close(head_ref);
6113 } else {
6114 error = got_repo_match_object_id(&commit_id, NULL,
6115 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6117 if (error != NULL)
6118 goto done;
6120 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6121 if (view == NULL) {
6122 error = got_error_from_errno("view_open");
6123 goto done;
6126 error = got_object_open_as_commit(&commit, repo, commit_id);
6127 if (error)
6128 goto done;
6130 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6131 commit, repo);
6132 if (error)
6133 goto done;
6135 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6136 commit_id, repo);
6137 if (error)
6138 goto done;
6139 if (worktree) {
6140 /* Release work tree lock. */
6141 got_worktree_close(worktree);
6142 worktree = NULL;
6144 error = view_loop(view);
6145 done:
6146 free(repo_path);
6147 free(in_repo_path);
6148 free(link_target);
6149 free(cwd);
6150 free(commit_id);
6151 if (commit)
6152 got_object_commit_close(commit);
6153 if (worktree)
6154 got_worktree_close(worktree);
6155 if (repo) {
6156 const struct got_error *close_err = got_repo_close(repo);
6157 if (error == NULL)
6158 error = close_err;
6160 if (pack_fds) {
6161 const struct got_error *pack_err =
6162 got_repo_pack_fds_close(pack_fds);
6163 if (error == NULL)
6164 error = pack_err;
6166 tog_free_refs();
6167 return error;
6170 static const struct got_error *
6171 draw_tree_entries(struct tog_view *view, const char *parent_path)
6173 struct tog_tree_view_state *s = &view->state.tree;
6174 const struct got_error *err = NULL;
6175 struct got_tree_entry *te;
6176 wchar_t *wline;
6177 struct tog_color *tc;
6178 int width, n, i, nentries;
6179 int limit = view->nlines;
6181 s->ndisplayed = 0;
6182 if (view_is_hsplit_top(view))
6183 --limit; /* border */
6185 werase(view->window);
6187 if (limit == 0)
6188 return NULL;
6190 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6191 0, 0);
6192 if (err)
6193 return err;
6194 if (view_needs_focus_indication(view))
6195 wstandout(view->window);
6196 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6197 if (tc)
6198 wattr_on(view->window,
6199 COLOR_PAIR(tc->colorpair), NULL);
6200 waddwstr(view->window, wline);
6201 if (tc)
6202 wattr_off(view->window,
6203 COLOR_PAIR(tc->colorpair), NULL);
6204 if (view_needs_focus_indication(view))
6205 wstandend(view->window);
6206 free(wline);
6207 wline = NULL;
6208 if (width < view->ncols - 1)
6209 waddch(view->window, '\n');
6210 if (--limit <= 0)
6211 return NULL;
6212 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6213 0, 0);
6214 if (err)
6215 return err;
6216 waddwstr(view->window, wline);
6217 free(wline);
6218 wline = NULL;
6219 if (width < view->ncols - 1)
6220 waddch(view->window, '\n');
6221 if (--limit <= 0)
6222 return NULL;
6223 waddch(view->window, '\n');
6224 if (--limit <= 0)
6225 return NULL;
6227 if (s->first_displayed_entry == NULL) {
6228 te = got_object_tree_get_first_entry(s->tree);
6229 if (s->selected == 0) {
6230 if (view->focussed)
6231 wstandout(view->window);
6232 s->selected_entry = NULL;
6234 waddstr(view->window, " ..\n"); /* parent directory */
6235 if (s->selected == 0 && view->focussed)
6236 wstandend(view->window);
6237 s->ndisplayed++;
6238 if (--limit <= 0)
6239 return NULL;
6240 n = 1;
6241 } else {
6242 n = 0;
6243 te = s->first_displayed_entry;
6246 nentries = got_object_tree_get_nentries(s->tree);
6247 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6248 char *line = NULL, *id_str = NULL, *link_target = NULL;
6249 const char *modestr = "";
6250 mode_t mode;
6252 te = got_object_tree_get_entry(s->tree, i);
6253 mode = got_tree_entry_get_mode(te);
6255 if (s->show_ids) {
6256 err = got_object_id_str(&id_str,
6257 got_tree_entry_get_id(te));
6258 if (err)
6259 return got_error_from_errno(
6260 "got_object_id_str");
6262 if (got_object_tree_entry_is_submodule(te))
6263 modestr = "$";
6264 else if (S_ISLNK(mode)) {
6265 int i;
6267 err = got_tree_entry_get_symlink_target(&link_target,
6268 te, s->repo);
6269 if (err) {
6270 free(id_str);
6271 return err;
6273 for (i = 0; i < strlen(link_target); i++) {
6274 if (!isprint((unsigned char)link_target[i]))
6275 link_target[i] = '?';
6277 modestr = "@";
6279 else if (S_ISDIR(mode))
6280 modestr = "/";
6281 else if (mode & S_IXUSR)
6282 modestr = "*";
6283 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6284 got_tree_entry_get_name(te), modestr,
6285 link_target ? " -> ": "",
6286 link_target ? link_target : "") == -1) {
6287 free(id_str);
6288 free(link_target);
6289 return got_error_from_errno("asprintf");
6291 free(id_str);
6292 free(link_target);
6293 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6294 0, 0);
6295 if (err) {
6296 free(line);
6297 break;
6299 if (n == s->selected) {
6300 if (view->focussed)
6301 wstandout(view->window);
6302 s->selected_entry = te;
6304 tc = match_color(&s->colors, line);
6305 if (tc)
6306 wattr_on(view->window,
6307 COLOR_PAIR(tc->colorpair), NULL);
6308 waddwstr(view->window, wline);
6309 if (tc)
6310 wattr_off(view->window,
6311 COLOR_PAIR(tc->colorpair), NULL);
6312 if (width < view->ncols - 1)
6313 waddch(view->window, '\n');
6314 if (n == s->selected && view->focussed)
6315 wstandend(view->window);
6316 free(line);
6317 free(wline);
6318 wline = NULL;
6319 n++;
6320 s->ndisplayed++;
6321 s->last_displayed_entry = te;
6322 if (--limit <= 0)
6323 break;
6326 return err;
6329 static void
6330 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6332 struct got_tree_entry *te;
6333 int isroot = s->tree == s->root;
6334 int i = 0;
6336 if (s->first_displayed_entry == NULL)
6337 return;
6339 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6340 while (i++ < maxscroll) {
6341 if (te == NULL) {
6342 if (!isroot)
6343 s->first_displayed_entry = NULL;
6344 break;
6346 s->first_displayed_entry = te;
6347 te = got_tree_entry_get_prev(s->tree, te);
6351 static const struct got_error *
6352 tree_scroll_down(struct tog_view *view, int maxscroll)
6354 struct tog_tree_view_state *s = &view->state.tree;
6355 struct got_tree_entry *next, *last;
6356 int n = 0;
6358 if (s->first_displayed_entry)
6359 next = got_tree_entry_get_next(s->tree,
6360 s->first_displayed_entry);
6361 else
6362 next = got_object_tree_get_first_entry(s->tree);
6364 last = s->last_displayed_entry;
6365 while (next && n++ < maxscroll) {
6366 if (last)
6367 last = got_tree_entry_get_next(s->tree, last);
6368 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6369 s->first_displayed_entry = next;
6370 next = got_tree_entry_get_next(s->tree, next);
6374 return NULL;
6377 static const struct got_error *
6378 tree_entry_path(char **path, struct tog_parent_trees *parents,
6379 struct got_tree_entry *te)
6381 const struct got_error *err = NULL;
6382 struct tog_parent_tree *pt;
6383 size_t len = 2; /* for leading slash and NUL */
6385 TAILQ_FOREACH(pt, parents, entry)
6386 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6387 + 1 /* slash */;
6388 if (te)
6389 len += strlen(got_tree_entry_get_name(te));
6391 *path = calloc(1, len);
6392 if (path == NULL)
6393 return got_error_from_errno("calloc");
6395 (*path)[0] = '/';
6396 pt = TAILQ_LAST(parents, tog_parent_trees);
6397 while (pt) {
6398 const char *name = got_tree_entry_get_name(pt->selected_entry);
6399 if (strlcat(*path, name, len) >= len) {
6400 err = got_error(GOT_ERR_NO_SPACE);
6401 goto done;
6403 if (strlcat(*path, "/", len) >= len) {
6404 err = got_error(GOT_ERR_NO_SPACE);
6405 goto done;
6407 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6409 if (te) {
6410 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6411 err = got_error(GOT_ERR_NO_SPACE);
6412 goto done;
6415 done:
6416 if (err) {
6417 free(*path);
6418 *path = NULL;
6420 return err;
6423 static const struct got_error *
6424 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6425 struct got_tree_entry *te, struct tog_parent_trees *parents,
6426 struct got_object_id *commit_id, struct got_repository *repo)
6428 const struct got_error *err = NULL;
6429 char *path;
6430 struct tog_view *blame_view;
6432 *new_view = NULL;
6434 err = tree_entry_path(&path, parents, te);
6435 if (err)
6436 return err;
6438 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6439 if (blame_view == NULL) {
6440 err = got_error_from_errno("view_open");
6441 goto done;
6444 err = open_blame_view(blame_view, path, commit_id, repo);
6445 if (err) {
6446 if (err->code == GOT_ERR_CANCELLED)
6447 err = NULL;
6448 view_close(blame_view);
6449 } else
6450 *new_view = blame_view;
6451 done:
6452 free(path);
6453 return err;
6456 static const struct got_error *
6457 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6458 struct tog_tree_view_state *s)
6460 struct tog_view *log_view;
6461 const struct got_error *err = NULL;
6462 char *path;
6464 *new_view = NULL;
6466 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6467 if (log_view == NULL)
6468 return got_error_from_errno("view_open");
6470 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6471 if (err)
6472 return err;
6474 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6475 path, 0);
6476 if (err)
6477 view_close(log_view);
6478 else
6479 *new_view = log_view;
6480 free(path);
6481 return err;
6484 static const struct got_error *
6485 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6486 const char *head_ref_name, struct got_repository *repo)
6488 const struct got_error *err = NULL;
6489 char *commit_id_str = NULL;
6490 struct tog_tree_view_state *s = &view->state.tree;
6491 struct got_commit_object *commit = NULL;
6493 TAILQ_INIT(&s->parents);
6494 STAILQ_INIT(&s->colors);
6496 s->commit_id = got_object_id_dup(commit_id);
6497 if (s->commit_id == NULL)
6498 return got_error_from_errno("got_object_id_dup");
6500 err = got_object_open_as_commit(&commit, repo, commit_id);
6501 if (err)
6502 goto done;
6505 * The root is opened here and will be closed when the view is closed.
6506 * Any visited subtrees and their path-wise parents are opened and
6507 * closed on demand.
6509 err = got_object_open_as_tree(&s->root, repo,
6510 got_object_commit_get_tree_id(commit));
6511 if (err)
6512 goto done;
6513 s->tree = s->root;
6515 err = got_object_id_str(&commit_id_str, commit_id);
6516 if (err != NULL)
6517 goto done;
6519 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6520 err = got_error_from_errno("asprintf");
6521 goto done;
6524 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6525 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6526 if (head_ref_name) {
6527 s->head_ref_name = strdup(head_ref_name);
6528 if (s->head_ref_name == NULL) {
6529 err = got_error_from_errno("strdup");
6530 goto done;
6533 s->repo = repo;
6535 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6536 err = add_color(&s->colors, "\\$$",
6537 TOG_COLOR_TREE_SUBMODULE,
6538 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6539 if (err)
6540 goto done;
6541 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6542 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6543 if (err)
6544 goto done;
6545 err = add_color(&s->colors, "/$",
6546 TOG_COLOR_TREE_DIRECTORY,
6547 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6548 if (err)
6549 goto done;
6551 err = add_color(&s->colors, "\\*$",
6552 TOG_COLOR_TREE_EXECUTABLE,
6553 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6554 if (err)
6555 goto done;
6557 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6558 get_color_value("TOG_COLOR_COMMIT"));
6559 if (err)
6560 goto done;
6563 view->show = show_tree_view;
6564 view->input = input_tree_view;
6565 view->close = close_tree_view;
6566 view->search_start = search_start_tree_view;
6567 view->search_next = search_next_tree_view;
6568 done:
6569 free(commit_id_str);
6570 if (commit)
6571 got_object_commit_close(commit);
6572 if (err)
6573 close_tree_view(view);
6574 return err;
6577 static const struct got_error *
6578 close_tree_view(struct tog_view *view)
6580 struct tog_tree_view_state *s = &view->state.tree;
6582 free_colors(&s->colors);
6583 free(s->tree_label);
6584 s->tree_label = NULL;
6585 free(s->commit_id);
6586 s->commit_id = NULL;
6587 free(s->head_ref_name);
6588 s->head_ref_name = NULL;
6589 while (!TAILQ_EMPTY(&s->parents)) {
6590 struct tog_parent_tree *parent;
6591 parent = TAILQ_FIRST(&s->parents);
6592 TAILQ_REMOVE(&s->parents, parent, entry);
6593 if (parent->tree != s->root)
6594 got_object_tree_close(parent->tree);
6595 free(parent);
6598 if (s->tree != NULL && s->tree != s->root)
6599 got_object_tree_close(s->tree);
6600 if (s->root)
6601 got_object_tree_close(s->root);
6602 return NULL;
6605 static const struct got_error *
6606 search_start_tree_view(struct tog_view *view)
6608 struct tog_tree_view_state *s = &view->state.tree;
6610 s->matched_entry = NULL;
6611 return NULL;
6614 static int
6615 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6617 regmatch_t regmatch;
6619 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6620 0) == 0;
6623 static const struct got_error *
6624 search_next_tree_view(struct tog_view *view)
6626 struct tog_tree_view_state *s = &view->state.tree;
6627 struct got_tree_entry *te = NULL;
6629 if (!view->searching) {
6630 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6631 return NULL;
6634 if (s->matched_entry) {
6635 if (view->searching == TOG_SEARCH_FORWARD) {
6636 if (s->selected_entry)
6637 te = got_tree_entry_get_next(s->tree,
6638 s->selected_entry);
6639 else
6640 te = got_object_tree_get_first_entry(s->tree);
6641 } else {
6642 if (s->selected_entry == NULL)
6643 te = got_object_tree_get_last_entry(s->tree);
6644 else
6645 te = got_tree_entry_get_prev(s->tree,
6646 s->selected_entry);
6648 } else {
6649 if (s->selected_entry)
6650 te = s->selected_entry;
6651 else if (view->searching == TOG_SEARCH_FORWARD)
6652 te = got_object_tree_get_first_entry(s->tree);
6653 else
6654 te = got_object_tree_get_last_entry(s->tree);
6657 while (1) {
6658 if (te == NULL) {
6659 if (s->matched_entry == NULL) {
6660 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6661 return NULL;
6663 if (view->searching == TOG_SEARCH_FORWARD)
6664 te = got_object_tree_get_first_entry(s->tree);
6665 else
6666 te = got_object_tree_get_last_entry(s->tree);
6669 if (match_tree_entry(te, &view->regex)) {
6670 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6671 s->matched_entry = te;
6672 break;
6675 if (view->searching == TOG_SEARCH_FORWARD)
6676 te = got_tree_entry_get_next(s->tree, te);
6677 else
6678 te = got_tree_entry_get_prev(s->tree, te);
6681 if (s->matched_entry) {
6682 s->first_displayed_entry = s->matched_entry;
6683 s->selected = 0;
6686 return NULL;
6689 static const struct got_error *
6690 show_tree_view(struct tog_view *view)
6692 const struct got_error *err = NULL;
6693 struct tog_tree_view_state *s = &view->state.tree;
6694 char *parent_path;
6696 err = tree_entry_path(&parent_path, &s->parents, NULL);
6697 if (err)
6698 return err;
6700 err = draw_tree_entries(view, parent_path);
6701 free(parent_path);
6703 view_border(view);
6704 return err;
6707 static const struct got_error *
6708 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6710 const struct got_error *err = NULL;
6711 struct tog_tree_view_state *s = &view->state.tree;
6712 struct got_tree_entry *te;
6713 int n, nscroll = view->nlines - 3;
6715 switch (ch) {
6716 case 'i':
6717 s->show_ids = !s->show_ids;
6718 view->count = 0;
6719 break;
6720 case 'L':
6721 view->count = 0;
6722 if (!s->selected_entry)
6723 break;
6724 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6725 break;
6726 case 'R':
6727 view->count = 0;
6728 err = view_request_new(new_view, view, TOG_VIEW_REF);
6729 break;
6730 case 'g':
6731 case KEY_HOME:
6732 s->selected = 0;
6733 view->count = 0;
6734 if (s->tree == s->root)
6735 s->first_displayed_entry =
6736 got_object_tree_get_first_entry(s->tree);
6737 else
6738 s->first_displayed_entry = NULL;
6739 break;
6740 case 'G':
6741 case KEY_END: {
6742 int eos = view->nlines - 3;
6744 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6745 --eos; /* border */
6746 s->selected = 0;
6747 view->count = 0;
6748 te = got_object_tree_get_last_entry(s->tree);
6749 for (n = 0; n < eos; n++) {
6750 if (te == NULL) {
6751 if (s->tree != s->root) {
6752 s->first_displayed_entry = NULL;
6753 n++;
6755 break;
6757 s->first_displayed_entry = te;
6758 te = got_tree_entry_get_prev(s->tree, te);
6760 if (n > 0)
6761 s->selected = n - 1;
6762 break;
6764 case 'k':
6765 case KEY_UP:
6766 case CTRL('p'):
6767 if (s->selected > 0) {
6768 s->selected--;
6769 break;
6771 tree_scroll_up(s, 1);
6772 if (s->selected_entry == NULL ||
6773 (s->tree == s->root && s->selected_entry ==
6774 got_object_tree_get_first_entry(s->tree)))
6775 view->count = 0;
6776 break;
6777 case CTRL('u'):
6778 case 'u':
6779 nscroll /= 2;
6780 /* FALL THROUGH */
6781 case KEY_PPAGE:
6782 case CTRL('b'):
6783 case 'b':
6784 if (s->tree == s->root) {
6785 if (got_object_tree_get_first_entry(s->tree) ==
6786 s->first_displayed_entry)
6787 s->selected -= MIN(s->selected, nscroll);
6788 } else {
6789 if (s->first_displayed_entry == NULL)
6790 s->selected -= MIN(s->selected, nscroll);
6792 tree_scroll_up(s, MAX(0, nscroll));
6793 if (s->selected_entry == NULL ||
6794 (s->tree == s->root && s->selected_entry ==
6795 got_object_tree_get_first_entry(s->tree)))
6796 view->count = 0;
6797 break;
6798 case 'j':
6799 case KEY_DOWN:
6800 case CTRL('n'):
6801 if (s->selected < s->ndisplayed - 1) {
6802 s->selected++;
6803 break;
6805 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6806 == NULL) {
6807 /* can't scroll any further */
6808 view->count = 0;
6809 break;
6811 tree_scroll_down(view, 1);
6812 break;
6813 case CTRL('d'):
6814 case 'd':
6815 nscroll /= 2;
6816 /* FALL THROUGH */
6817 case KEY_NPAGE:
6818 case CTRL('f'):
6819 case 'f':
6820 case ' ':
6821 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6822 == NULL) {
6823 /* can't scroll any further; move cursor down */
6824 if (s->selected < s->ndisplayed - 1)
6825 s->selected += MIN(nscroll,
6826 s->ndisplayed - s->selected - 1);
6827 else
6828 view->count = 0;
6829 break;
6831 tree_scroll_down(view, nscroll);
6832 break;
6833 case KEY_ENTER:
6834 case '\r':
6835 case KEY_BACKSPACE:
6836 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6837 struct tog_parent_tree *parent;
6838 /* user selected '..' */
6839 if (s->tree == s->root) {
6840 view->count = 0;
6841 break;
6843 parent = TAILQ_FIRST(&s->parents);
6844 TAILQ_REMOVE(&s->parents, parent,
6845 entry);
6846 got_object_tree_close(s->tree);
6847 s->tree = parent->tree;
6848 s->first_displayed_entry =
6849 parent->first_displayed_entry;
6850 s->selected_entry =
6851 parent->selected_entry;
6852 s->selected = parent->selected;
6853 if (s->selected > view->nlines - 3) {
6854 err = offset_selection_down(view);
6855 if (err)
6856 break;
6858 free(parent);
6859 } else if (S_ISDIR(got_tree_entry_get_mode(
6860 s->selected_entry))) {
6861 struct got_tree_object *subtree;
6862 view->count = 0;
6863 err = got_object_open_as_tree(&subtree, s->repo,
6864 got_tree_entry_get_id(s->selected_entry));
6865 if (err)
6866 break;
6867 err = tree_view_visit_subtree(s, subtree);
6868 if (err) {
6869 got_object_tree_close(subtree);
6870 break;
6872 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
6873 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
6874 break;
6875 case KEY_RESIZE:
6876 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6877 s->selected = view->nlines - 4;
6878 view->count = 0;
6879 break;
6880 default:
6881 view->count = 0;
6882 break;
6885 return err;
6888 __dead static void
6889 usage_tree(void)
6891 endwin();
6892 fprintf(stderr,
6893 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6894 getprogname());
6895 exit(1);
6898 static const struct got_error *
6899 cmd_tree(int argc, char *argv[])
6901 const struct got_error *error;
6902 struct got_repository *repo = NULL;
6903 struct got_worktree *worktree = NULL;
6904 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6905 struct got_object_id *commit_id = NULL;
6906 struct got_commit_object *commit = NULL;
6907 const char *commit_id_arg = NULL;
6908 char *label = NULL;
6909 struct got_reference *ref = NULL;
6910 const char *head_ref_name = NULL;
6911 int ch;
6912 struct tog_view *view;
6913 int *pack_fds = NULL;
6915 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6916 switch (ch) {
6917 case 'c':
6918 commit_id_arg = optarg;
6919 break;
6920 case 'r':
6921 repo_path = realpath(optarg, NULL);
6922 if (repo_path == NULL)
6923 return got_error_from_errno2("realpath",
6924 optarg);
6925 break;
6926 default:
6927 usage_tree();
6928 /* NOTREACHED */
6932 argc -= optind;
6933 argv += optind;
6935 if (argc > 1)
6936 usage_tree();
6938 error = got_repo_pack_fds_open(&pack_fds);
6939 if (error != NULL)
6940 goto done;
6942 if (repo_path == NULL) {
6943 cwd = getcwd(NULL, 0);
6944 if (cwd == NULL)
6945 return got_error_from_errno("getcwd");
6946 error = got_worktree_open(&worktree, cwd);
6947 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6948 goto done;
6949 if (worktree)
6950 repo_path =
6951 strdup(got_worktree_get_repo_path(worktree));
6952 else
6953 repo_path = strdup(cwd);
6954 if (repo_path == NULL) {
6955 error = got_error_from_errno("strdup");
6956 goto done;
6960 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6961 if (error != NULL)
6962 goto done;
6964 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6965 repo, worktree);
6966 if (error)
6967 goto done;
6969 init_curses();
6971 error = apply_unveil(got_repo_get_path(repo), NULL);
6972 if (error)
6973 goto done;
6975 error = tog_load_refs(repo, 0);
6976 if (error)
6977 goto done;
6979 if (commit_id_arg == NULL) {
6980 error = got_repo_match_object_id(&commit_id, &label,
6981 worktree ? got_worktree_get_head_ref_name(worktree) :
6982 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6983 if (error)
6984 goto done;
6985 head_ref_name = label;
6986 } else {
6987 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6988 if (error == NULL)
6989 head_ref_name = got_ref_get_name(ref);
6990 else if (error->code != GOT_ERR_NOT_REF)
6991 goto done;
6992 error = got_repo_match_object_id(&commit_id, NULL,
6993 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6994 if (error)
6995 goto done;
6998 error = got_object_open_as_commit(&commit, repo, commit_id);
6999 if (error)
7000 goto done;
7002 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7003 if (view == NULL) {
7004 error = got_error_from_errno("view_open");
7005 goto done;
7007 error = open_tree_view(view, commit_id, head_ref_name, repo);
7008 if (error)
7009 goto done;
7010 if (!got_path_is_root_dir(in_repo_path)) {
7011 error = tree_view_walk_path(&view->state.tree, commit,
7012 in_repo_path);
7013 if (error)
7014 goto done;
7017 if (worktree) {
7018 /* Release work tree lock. */
7019 got_worktree_close(worktree);
7020 worktree = NULL;
7022 error = view_loop(view);
7023 done:
7024 free(repo_path);
7025 free(cwd);
7026 free(commit_id);
7027 free(label);
7028 if (ref)
7029 got_ref_close(ref);
7030 if (repo) {
7031 const struct got_error *close_err = got_repo_close(repo);
7032 if (error == NULL)
7033 error = close_err;
7035 if (pack_fds) {
7036 const struct got_error *pack_err =
7037 got_repo_pack_fds_close(pack_fds);
7038 if (error == NULL)
7039 error = pack_err;
7041 tog_free_refs();
7042 return error;
7045 static const struct got_error *
7046 ref_view_load_refs(struct tog_ref_view_state *s)
7048 struct got_reflist_entry *sre;
7049 struct tog_reflist_entry *re;
7051 s->nrefs = 0;
7052 TAILQ_FOREACH(sre, &tog_refs, entry) {
7053 if (strncmp(got_ref_get_name(sre->ref),
7054 "refs/got/", 9) == 0 &&
7055 strncmp(got_ref_get_name(sre->ref),
7056 "refs/got/backup/", 16) != 0)
7057 continue;
7059 re = malloc(sizeof(*re));
7060 if (re == NULL)
7061 return got_error_from_errno("malloc");
7063 re->ref = got_ref_dup(sre->ref);
7064 if (re->ref == NULL)
7065 return got_error_from_errno("got_ref_dup");
7066 re->idx = s->nrefs++;
7067 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7070 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7071 return NULL;
7074 static void
7075 ref_view_free_refs(struct tog_ref_view_state *s)
7077 struct tog_reflist_entry *re;
7079 while (!TAILQ_EMPTY(&s->refs)) {
7080 re = TAILQ_FIRST(&s->refs);
7081 TAILQ_REMOVE(&s->refs, re, entry);
7082 got_ref_close(re->ref);
7083 free(re);
7087 static const struct got_error *
7088 open_ref_view(struct tog_view *view, struct got_repository *repo)
7090 const struct got_error *err = NULL;
7091 struct tog_ref_view_state *s = &view->state.ref;
7093 s->selected_entry = 0;
7094 s->repo = repo;
7096 TAILQ_INIT(&s->refs);
7097 STAILQ_INIT(&s->colors);
7099 err = ref_view_load_refs(s);
7100 if (err)
7101 return err;
7103 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7104 err = add_color(&s->colors, "^refs/heads/",
7105 TOG_COLOR_REFS_HEADS,
7106 get_color_value("TOG_COLOR_REFS_HEADS"));
7107 if (err)
7108 goto done;
7110 err = add_color(&s->colors, "^refs/tags/",
7111 TOG_COLOR_REFS_TAGS,
7112 get_color_value("TOG_COLOR_REFS_TAGS"));
7113 if (err)
7114 goto done;
7116 err = add_color(&s->colors, "^refs/remotes/",
7117 TOG_COLOR_REFS_REMOTES,
7118 get_color_value("TOG_COLOR_REFS_REMOTES"));
7119 if (err)
7120 goto done;
7122 err = add_color(&s->colors, "^refs/got/backup/",
7123 TOG_COLOR_REFS_BACKUP,
7124 get_color_value("TOG_COLOR_REFS_BACKUP"));
7125 if (err)
7126 goto done;
7129 view->show = show_ref_view;
7130 view->input = input_ref_view;
7131 view->close = close_ref_view;
7132 view->search_start = search_start_ref_view;
7133 view->search_next = search_next_ref_view;
7134 done:
7135 if (err)
7136 free_colors(&s->colors);
7137 return err;
7140 static const struct got_error *
7141 close_ref_view(struct tog_view *view)
7143 struct tog_ref_view_state *s = &view->state.ref;
7145 ref_view_free_refs(s);
7146 free_colors(&s->colors);
7148 return NULL;
7151 static const struct got_error *
7152 resolve_reflist_entry(struct got_object_id **commit_id,
7153 struct tog_reflist_entry *re, struct got_repository *repo)
7155 const struct got_error *err = NULL;
7156 struct got_object_id *obj_id;
7157 struct got_tag_object *tag = NULL;
7158 int obj_type;
7160 *commit_id = NULL;
7162 err = got_ref_resolve(&obj_id, repo, re->ref);
7163 if (err)
7164 return err;
7166 err = got_object_get_type(&obj_type, repo, obj_id);
7167 if (err)
7168 goto done;
7170 switch (obj_type) {
7171 case GOT_OBJ_TYPE_COMMIT:
7172 *commit_id = obj_id;
7173 break;
7174 case GOT_OBJ_TYPE_TAG:
7175 err = got_object_open_as_tag(&tag, repo, obj_id);
7176 if (err)
7177 goto done;
7178 free(obj_id);
7179 err = got_object_get_type(&obj_type, repo,
7180 got_object_tag_get_object_id(tag));
7181 if (err)
7182 goto done;
7183 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7184 err = got_error(GOT_ERR_OBJ_TYPE);
7185 goto done;
7187 *commit_id = got_object_id_dup(
7188 got_object_tag_get_object_id(tag));
7189 if (*commit_id == NULL) {
7190 err = got_error_from_errno("got_object_id_dup");
7191 goto done;
7193 break;
7194 default:
7195 err = got_error(GOT_ERR_OBJ_TYPE);
7196 break;
7199 done:
7200 if (tag)
7201 got_object_tag_close(tag);
7202 if (err) {
7203 free(*commit_id);
7204 *commit_id = NULL;
7206 return err;
7209 static const struct got_error *
7210 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7211 struct tog_reflist_entry *re, struct got_repository *repo)
7213 struct tog_view *log_view;
7214 const struct got_error *err = NULL;
7215 struct got_object_id *commit_id = NULL;
7217 *new_view = NULL;
7219 err = resolve_reflist_entry(&commit_id, re, repo);
7220 if (err) {
7221 if (err->code != GOT_ERR_OBJ_TYPE)
7222 return err;
7223 else
7224 return NULL;
7227 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7228 if (log_view == NULL) {
7229 err = got_error_from_errno("view_open");
7230 goto done;
7233 err = open_log_view(log_view, commit_id, repo,
7234 got_ref_get_name(re->ref), "", 0);
7235 done:
7236 if (err)
7237 view_close(log_view);
7238 else
7239 *new_view = log_view;
7240 free(commit_id);
7241 return err;
7244 static void
7245 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7247 struct tog_reflist_entry *re;
7248 int i = 0;
7250 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7251 return;
7253 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7254 while (i++ < maxscroll) {
7255 if (re == NULL)
7256 break;
7257 s->first_displayed_entry = re;
7258 re = TAILQ_PREV(re, tog_reflist_head, entry);
7262 static const struct got_error *
7263 ref_scroll_down(struct tog_view *view, int maxscroll)
7265 struct tog_ref_view_state *s = &view->state.ref;
7266 struct tog_reflist_entry *next, *last;
7267 int n = 0;
7269 if (s->first_displayed_entry)
7270 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7271 else
7272 next = TAILQ_FIRST(&s->refs);
7274 last = s->last_displayed_entry;
7275 while (next && n++ < maxscroll) {
7276 if (last)
7277 last = TAILQ_NEXT(last, entry);
7278 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7279 s->first_displayed_entry = next;
7280 next = TAILQ_NEXT(next, entry);
7284 return NULL;
7287 static const struct got_error *
7288 search_start_ref_view(struct tog_view *view)
7290 struct tog_ref_view_state *s = &view->state.ref;
7292 s->matched_entry = NULL;
7293 return NULL;
7296 static int
7297 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7299 regmatch_t regmatch;
7301 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7302 0) == 0;
7305 static const struct got_error *
7306 search_next_ref_view(struct tog_view *view)
7308 struct tog_ref_view_state *s = &view->state.ref;
7309 struct tog_reflist_entry *re = NULL;
7311 if (!view->searching) {
7312 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7313 return NULL;
7316 if (s->matched_entry) {
7317 if (view->searching == TOG_SEARCH_FORWARD) {
7318 if (s->selected_entry)
7319 re = TAILQ_NEXT(s->selected_entry, entry);
7320 else
7321 re = TAILQ_PREV(s->selected_entry,
7322 tog_reflist_head, entry);
7323 } else {
7324 if (s->selected_entry == NULL)
7325 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7326 else
7327 re = TAILQ_PREV(s->selected_entry,
7328 tog_reflist_head, entry);
7330 } else {
7331 if (s->selected_entry)
7332 re = s->selected_entry;
7333 else if (view->searching == TOG_SEARCH_FORWARD)
7334 re = TAILQ_FIRST(&s->refs);
7335 else
7336 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7339 while (1) {
7340 if (re == NULL) {
7341 if (s->matched_entry == NULL) {
7342 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7343 return NULL;
7345 if (view->searching == TOG_SEARCH_FORWARD)
7346 re = TAILQ_FIRST(&s->refs);
7347 else
7348 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7351 if (match_reflist_entry(re, &view->regex)) {
7352 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7353 s->matched_entry = re;
7354 break;
7357 if (view->searching == TOG_SEARCH_FORWARD)
7358 re = TAILQ_NEXT(re, entry);
7359 else
7360 re = TAILQ_PREV(re, tog_reflist_head, entry);
7363 if (s->matched_entry) {
7364 s->first_displayed_entry = s->matched_entry;
7365 s->selected = 0;
7368 return NULL;
7371 static const struct got_error *
7372 show_ref_view(struct tog_view *view)
7374 const struct got_error *err = NULL;
7375 struct tog_ref_view_state *s = &view->state.ref;
7376 struct tog_reflist_entry *re;
7377 char *line = NULL;
7378 wchar_t *wline;
7379 struct tog_color *tc;
7380 int width, n;
7381 int limit = view->nlines;
7383 werase(view->window);
7385 s->ndisplayed = 0;
7386 if (view_is_hsplit_top(view))
7387 --limit; /* border */
7389 if (limit == 0)
7390 return NULL;
7392 re = s->first_displayed_entry;
7394 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7395 s->nrefs) == -1)
7396 return got_error_from_errno("asprintf");
7398 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7399 if (err) {
7400 free(line);
7401 return err;
7403 if (view_needs_focus_indication(view))
7404 wstandout(view->window);
7405 waddwstr(view->window, wline);
7406 if (view_needs_focus_indication(view))
7407 wstandend(view->window);
7408 free(wline);
7409 wline = NULL;
7410 free(line);
7411 line = NULL;
7412 if (width < view->ncols - 1)
7413 waddch(view->window, '\n');
7414 if (--limit <= 0)
7415 return NULL;
7417 n = 0;
7418 while (re && limit > 0) {
7419 char *line = NULL;
7420 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7422 if (s->show_date) {
7423 struct got_commit_object *ci;
7424 struct got_tag_object *tag;
7425 struct got_object_id *id;
7426 struct tm tm;
7427 time_t t;
7429 err = got_ref_resolve(&id, s->repo, re->ref);
7430 if (err)
7431 return err;
7432 err = got_object_open_as_tag(&tag, s->repo, id);
7433 if (err) {
7434 if (err->code != GOT_ERR_OBJ_TYPE) {
7435 free(id);
7436 return err;
7438 err = got_object_open_as_commit(&ci, s->repo,
7439 id);
7440 if (err) {
7441 free(id);
7442 return err;
7444 t = got_object_commit_get_committer_time(ci);
7445 got_object_commit_close(ci);
7446 } else {
7447 t = got_object_tag_get_tagger_time(tag);
7448 got_object_tag_close(tag);
7450 free(id);
7451 if (gmtime_r(&t, &tm) == NULL)
7452 return got_error_from_errno("gmtime_r");
7453 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7454 return got_error(GOT_ERR_NO_SPACE);
7456 if (got_ref_is_symbolic(re->ref)) {
7457 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7458 ymd : "", got_ref_get_name(re->ref),
7459 got_ref_get_symref_target(re->ref)) == -1)
7460 return got_error_from_errno("asprintf");
7461 } else if (s->show_ids) {
7462 struct got_object_id *id;
7463 char *id_str;
7464 err = got_ref_resolve(&id, s->repo, re->ref);
7465 if (err)
7466 return err;
7467 err = got_object_id_str(&id_str, id);
7468 if (err) {
7469 free(id);
7470 return err;
7472 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7473 got_ref_get_name(re->ref), id_str) == -1) {
7474 err = got_error_from_errno("asprintf");
7475 free(id);
7476 free(id_str);
7477 return err;
7479 free(id);
7480 free(id_str);
7481 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7482 got_ref_get_name(re->ref)) == -1)
7483 return got_error_from_errno("asprintf");
7485 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7486 0, 0);
7487 if (err) {
7488 free(line);
7489 return err;
7491 if (n == s->selected) {
7492 if (view->focussed)
7493 wstandout(view->window);
7494 s->selected_entry = re;
7496 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7497 if (tc)
7498 wattr_on(view->window,
7499 COLOR_PAIR(tc->colorpair), NULL);
7500 waddwstr(view->window, wline);
7501 if (tc)
7502 wattr_off(view->window,
7503 COLOR_PAIR(tc->colorpair), NULL);
7504 if (width < view->ncols - 1)
7505 waddch(view->window, '\n');
7506 if (n == s->selected && view->focussed)
7507 wstandend(view->window);
7508 free(line);
7509 free(wline);
7510 wline = NULL;
7511 n++;
7512 s->ndisplayed++;
7513 s->last_displayed_entry = re;
7515 limit--;
7516 re = TAILQ_NEXT(re, entry);
7519 view_border(view);
7520 return err;
7523 static const struct got_error *
7524 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7525 struct tog_reflist_entry *re, struct got_repository *repo)
7527 const struct got_error *err = NULL;
7528 struct got_object_id *commit_id = NULL;
7529 struct tog_view *tree_view;
7531 *new_view = NULL;
7533 err = resolve_reflist_entry(&commit_id, re, repo);
7534 if (err) {
7535 if (err->code != GOT_ERR_OBJ_TYPE)
7536 return err;
7537 else
7538 return NULL;
7542 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7543 if (tree_view == NULL) {
7544 err = got_error_from_errno("view_open");
7545 goto done;
7548 err = open_tree_view(tree_view, commit_id,
7549 got_ref_get_name(re->ref), repo);
7550 if (err)
7551 goto done;
7553 *new_view = tree_view;
7554 done:
7555 free(commit_id);
7556 return err;
7558 static const struct got_error *
7559 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7561 const struct got_error *err = NULL;
7562 struct tog_ref_view_state *s = &view->state.ref;
7563 struct tog_reflist_entry *re;
7564 int n, nscroll = view->nlines - 1;
7566 switch (ch) {
7567 case 'i':
7568 s->show_ids = !s->show_ids;
7569 view->count = 0;
7570 break;
7571 case 'm':
7572 s->show_date = !s->show_date;
7573 view->count = 0;
7574 break;
7575 case 'o':
7576 s->sort_by_date = !s->sort_by_date;
7577 view->count = 0;
7578 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7579 got_ref_cmp_by_commit_timestamp_descending :
7580 tog_ref_cmp_by_name, s->repo);
7581 if (err)
7582 break;
7583 got_reflist_object_id_map_free(tog_refs_idmap);
7584 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7585 &tog_refs, s->repo);
7586 if (err)
7587 break;
7588 ref_view_free_refs(s);
7589 err = ref_view_load_refs(s);
7590 break;
7591 case KEY_ENTER:
7592 case '\r':
7593 view->count = 0;
7594 if (!s->selected_entry)
7595 break;
7596 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7597 break;
7598 case 'T':
7599 view->count = 0;
7600 if (!s->selected_entry)
7601 break;
7602 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7603 break;
7604 case 'g':
7605 case KEY_HOME:
7606 s->selected = 0;
7607 view->count = 0;
7608 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7609 break;
7610 case 'G':
7611 case KEY_END: {
7612 int eos = view->nlines - 1;
7614 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7615 --eos; /* border */
7616 s->selected = 0;
7617 view->count = 0;
7618 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7619 for (n = 0; n < eos; n++) {
7620 if (re == NULL)
7621 break;
7622 s->first_displayed_entry = re;
7623 re = TAILQ_PREV(re, tog_reflist_head, entry);
7625 if (n > 0)
7626 s->selected = n - 1;
7627 break;
7629 case 'k':
7630 case KEY_UP:
7631 case CTRL('p'):
7632 if (s->selected > 0) {
7633 s->selected--;
7634 break;
7636 ref_scroll_up(s, 1);
7637 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7638 view->count = 0;
7639 break;
7640 case CTRL('u'):
7641 case 'u':
7642 nscroll /= 2;
7643 /* FALL THROUGH */
7644 case KEY_PPAGE:
7645 case CTRL('b'):
7646 case 'b':
7647 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7648 s->selected -= MIN(nscroll, s->selected);
7649 ref_scroll_up(s, MAX(0, nscroll));
7650 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7651 view->count = 0;
7652 break;
7653 case 'j':
7654 case KEY_DOWN:
7655 case CTRL('n'):
7656 if (s->selected < s->ndisplayed - 1) {
7657 s->selected++;
7658 break;
7660 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7661 /* can't scroll any further */
7662 view->count = 0;
7663 break;
7665 ref_scroll_down(view, 1);
7666 break;
7667 case CTRL('d'):
7668 case 'd':
7669 nscroll /= 2;
7670 /* FALL THROUGH */
7671 case KEY_NPAGE:
7672 case CTRL('f'):
7673 case 'f':
7674 case ' ':
7675 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7676 /* can't scroll any further; move cursor down */
7677 if (s->selected < s->ndisplayed - 1)
7678 s->selected += MIN(nscroll,
7679 s->ndisplayed - s->selected - 1);
7680 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7681 s->selected += s->ndisplayed - s->selected - 1;
7682 view->count = 0;
7683 break;
7685 ref_scroll_down(view, nscroll);
7686 break;
7687 case CTRL('l'):
7688 view->count = 0;
7689 tog_free_refs();
7690 err = tog_load_refs(s->repo, s->sort_by_date);
7691 if (err)
7692 break;
7693 ref_view_free_refs(s);
7694 err = ref_view_load_refs(s);
7695 break;
7696 case KEY_RESIZE:
7697 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7698 s->selected = view->nlines - 2;
7699 break;
7700 default:
7701 view->count = 0;
7702 break;
7705 return err;
7708 __dead static void
7709 usage_ref(void)
7711 endwin();
7712 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7713 getprogname());
7714 exit(1);
7717 static const struct got_error *
7718 cmd_ref(int argc, char *argv[])
7720 const struct got_error *error;
7721 struct got_repository *repo = NULL;
7722 struct got_worktree *worktree = NULL;
7723 char *cwd = NULL, *repo_path = NULL;
7724 int ch;
7725 struct tog_view *view;
7726 int *pack_fds = NULL;
7728 while ((ch = getopt(argc, argv, "r:")) != -1) {
7729 switch (ch) {
7730 case 'r':
7731 repo_path = realpath(optarg, NULL);
7732 if (repo_path == NULL)
7733 return got_error_from_errno2("realpath",
7734 optarg);
7735 break;
7736 default:
7737 usage_ref();
7738 /* NOTREACHED */
7742 argc -= optind;
7743 argv += optind;
7745 if (argc > 1)
7746 usage_ref();
7748 error = got_repo_pack_fds_open(&pack_fds);
7749 if (error != NULL)
7750 goto done;
7752 if (repo_path == NULL) {
7753 cwd = getcwd(NULL, 0);
7754 if (cwd == NULL)
7755 return got_error_from_errno("getcwd");
7756 error = got_worktree_open(&worktree, cwd);
7757 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7758 goto done;
7759 if (worktree)
7760 repo_path =
7761 strdup(got_worktree_get_repo_path(worktree));
7762 else
7763 repo_path = strdup(cwd);
7764 if (repo_path == NULL) {
7765 error = got_error_from_errno("strdup");
7766 goto done;
7770 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7771 if (error != NULL)
7772 goto done;
7774 init_curses();
7776 error = apply_unveil(got_repo_get_path(repo), NULL);
7777 if (error)
7778 goto done;
7780 error = tog_load_refs(repo, 0);
7781 if (error)
7782 goto done;
7784 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7785 if (view == NULL) {
7786 error = got_error_from_errno("view_open");
7787 goto done;
7790 error = open_ref_view(view, repo);
7791 if (error)
7792 goto done;
7794 if (worktree) {
7795 /* Release work tree lock. */
7796 got_worktree_close(worktree);
7797 worktree = NULL;
7799 error = view_loop(view);
7800 done:
7801 free(repo_path);
7802 free(cwd);
7803 if (repo) {
7804 const struct got_error *close_err = got_repo_close(repo);
7805 if (close_err)
7806 error = close_err;
7808 if (pack_fds) {
7809 const struct got_error *pack_err =
7810 got_repo_pack_fds_close(pack_fds);
7811 if (error == NULL)
7812 error = pack_err;
7814 tog_free_refs();
7815 return error;
7818 static const struct got_error *
7819 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
7820 enum tog_view_type request, int y, int x)
7822 const struct got_error *err = NULL;
7824 *new_view = NULL;
7826 switch (request) {
7827 case TOG_VIEW_DIFF:
7828 if (view->type == TOG_VIEW_LOG) {
7829 struct tog_log_view_state *s = &view->state.log;
7831 err = open_diff_view_for_commit(new_view, y, x,
7832 s->selected_entry->commit, s->selected_entry->id,
7833 view, s->repo);
7834 } else
7835 return got_error_msg(GOT_ERR_NOT_IMPL,
7836 "parent/child view pair not supported");
7837 break;
7838 case TOG_VIEW_BLAME:
7839 if (view->type == TOG_VIEW_TREE) {
7840 struct tog_tree_view_state *s = &view->state.tree;
7842 err = blame_tree_entry(new_view, y, x,
7843 s->selected_entry, &s->parents, s->commit_id,
7844 s->repo);
7845 } else
7846 return got_error_msg(GOT_ERR_NOT_IMPL,
7847 "parent/child view pair not supported");
7848 break;
7849 case TOG_VIEW_LOG:
7850 if (view->type == TOG_VIEW_BLAME)
7851 err = log_annotated_line(new_view, y, x,
7852 view->state.blame.repo, view->state.blame.id_to_log);
7853 else if (view->type == TOG_VIEW_TREE)
7854 err = log_selected_tree_entry(new_view, y, x,
7855 &view->state.tree);
7856 else if (view->type == TOG_VIEW_REF)
7857 err = log_ref_entry(new_view, y, x,
7858 view->state.ref.selected_entry,
7859 view->state.ref.repo);
7860 else
7861 return got_error_msg(GOT_ERR_NOT_IMPL,
7862 "parent/child view pair not supported");
7863 break;
7864 case TOG_VIEW_TREE:
7865 if (view->type == TOG_VIEW_LOG)
7866 err = browse_commit_tree(new_view, y, x,
7867 view->state.log.selected_entry,
7868 view->state.log.in_repo_path,
7869 view->state.log.head_ref_name,
7870 view->state.log.repo);
7871 else if (view->type == TOG_VIEW_REF)
7872 err = browse_ref_tree(new_view, y, x,
7873 view->state.ref.selected_entry,
7874 view->state.ref.repo);
7875 else
7876 return got_error_msg(GOT_ERR_NOT_IMPL,
7877 "parent/child view pair not supported");
7878 break;
7879 case TOG_VIEW_REF:
7880 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
7881 if (*new_view == NULL)
7882 return got_error_from_errno("view_open");
7883 if (view->type == TOG_VIEW_LOG)
7884 err = open_ref_view(*new_view, view->state.log.repo);
7885 else if (view->type == TOG_VIEW_TREE)
7886 err = open_ref_view(*new_view, view->state.tree.repo);
7887 else
7888 err = got_error_msg(GOT_ERR_NOT_IMPL,
7889 "parent/child view pair not supported");
7890 if (err)
7891 view_close(*new_view);
7892 break;
7893 default:
7894 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
7897 return err;
7901 * If view was scrolled down to move the selected line into view when opening a
7902 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7904 static void
7905 offset_selection_up(struct tog_view *view)
7907 switch (view->type) {
7908 case TOG_VIEW_BLAME: {
7909 struct tog_blame_view_state *s = &view->state.blame;
7910 if (s->first_displayed_line == 1) {
7911 s->selected_line = MAX(s->selected_line - view->offset,
7912 1);
7913 break;
7915 if (s->first_displayed_line > view->offset)
7916 s->first_displayed_line -= view->offset;
7917 else
7918 s->first_displayed_line = 1;
7919 s->selected_line += view->offset;
7920 break;
7922 case TOG_VIEW_LOG:
7923 log_scroll_up(&view->state.log, view->offset);
7924 view->state.log.selected += view->offset;
7925 break;
7926 case TOG_VIEW_REF:
7927 ref_scroll_up(&view->state.ref, view->offset);
7928 view->state.ref.selected += view->offset;
7929 break;
7930 case TOG_VIEW_TREE:
7931 tree_scroll_up(&view->state.tree, view->offset);
7932 view->state.tree.selected += view->offset;
7933 break;
7934 default:
7935 break;
7938 view->offset = 0;
7942 * If the selected line is in the section of screen covered by the bottom split,
7943 * scroll down offset lines to move it into view and index its new position.
7945 static const struct got_error *
7946 offset_selection_down(struct tog_view *view)
7948 const struct got_error *err = NULL;
7949 const struct got_error *(*scrolld)(struct tog_view *, int);
7950 int *selected = NULL;
7951 int header, offset;
7953 switch (view->type) {
7954 case TOG_VIEW_BLAME: {
7955 struct tog_blame_view_state *s = &view->state.blame;
7956 header = 3;
7957 scrolld = NULL;
7958 if (s->selected_line > view->nlines - header) {
7959 offset = abs(view->nlines - s->selected_line - header);
7960 s->first_displayed_line += offset;
7961 s->selected_line -= offset;
7962 view->offset = offset;
7964 break;
7966 case TOG_VIEW_LOG: {
7967 struct tog_log_view_state *s = &view->state.log;
7968 scrolld = &log_scroll_down;
7969 header = view_is_parent_view(view) ? 3 : 2;
7970 selected = &s->selected;
7971 break;
7973 case TOG_VIEW_REF: {
7974 struct tog_ref_view_state *s = &view->state.ref;
7975 scrolld = &ref_scroll_down;
7976 header = 3;
7977 selected = &s->selected;
7978 break;
7980 case TOG_VIEW_TREE: {
7981 struct tog_tree_view_state *s = &view->state.tree;
7982 scrolld = &tree_scroll_down;
7983 header = 5;
7984 selected = &s->selected;
7985 break;
7987 default:
7988 selected = NULL;
7989 scrolld = NULL;
7990 header = 0;
7991 break;
7994 if (selected && *selected > view->nlines - header) {
7995 offset = abs(view->nlines - *selected - header);
7996 view->offset = offset;
7997 if (scrolld && offset) {
7998 err = scrolld(view, offset);
7999 *selected -= offset;
8003 return err;
8006 static void
8007 list_commands(FILE *fp)
8009 size_t i;
8011 fprintf(fp, "commands:");
8012 for (i = 0; i < nitems(tog_commands); i++) {
8013 const struct tog_cmd *cmd = &tog_commands[i];
8014 fprintf(fp, " %s", cmd->name);
8016 fputc('\n', fp);
8019 __dead static void
8020 usage(int hflag, int status)
8022 FILE *fp = (status == 0) ? stdout : stderr;
8024 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8025 getprogname());
8026 if (hflag) {
8027 fprintf(fp, "lazy usage: %s path\n", getprogname());
8028 list_commands(fp);
8030 exit(status);
8033 static char **
8034 make_argv(int argc, ...)
8036 va_list ap;
8037 char **argv;
8038 int i;
8040 va_start(ap, argc);
8042 argv = calloc(argc, sizeof(char *));
8043 if (argv == NULL)
8044 err(1, "calloc");
8045 for (i = 0; i < argc; i++) {
8046 argv[i] = strdup(va_arg(ap, char *));
8047 if (argv[i] == NULL)
8048 err(1, "strdup");
8051 va_end(ap);
8052 return argv;
8056 * Try to convert 'tog path' into a 'tog log path' command.
8057 * The user could simply have mistyped the command rather than knowingly
8058 * provided a path. So check whether argv[0] can in fact be resolved
8059 * to a path in the HEAD commit and print a special error if not.
8060 * This hack is for mpi@ <3
8062 static const struct got_error *
8063 tog_log_with_path(int argc, char *argv[])
8065 const struct got_error *error = NULL, *close_err;
8066 const struct tog_cmd *cmd = NULL;
8067 struct got_repository *repo = NULL;
8068 struct got_worktree *worktree = NULL;
8069 struct got_object_id *commit_id = NULL, *id = NULL;
8070 struct got_commit_object *commit = NULL;
8071 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8072 char *commit_id_str = NULL, **cmd_argv = NULL;
8073 int *pack_fds = NULL;
8075 cwd = getcwd(NULL, 0);
8076 if (cwd == NULL)
8077 return got_error_from_errno("getcwd");
8079 error = got_repo_pack_fds_open(&pack_fds);
8080 if (error != NULL)
8081 goto done;
8083 error = got_worktree_open(&worktree, cwd);
8084 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8085 goto done;
8087 if (worktree)
8088 repo_path = strdup(got_worktree_get_repo_path(worktree));
8089 else
8090 repo_path = strdup(cwd);
8091 if (repo_path == NULL) {
8092 error = got_error_from_errno("strdup");
8093 goto done;
8096 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8097 if (error != NULL)
8098 goto done;
8100 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8101 repo, worktree);
8102 if (error)
8103 goto done;
8105 error = tog_load_refs(repo, 0);
8106 if (error)
8107 goto done;
8108 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8109 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8110 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8111 if (error)
8112 goto done;
8114 if (worktree) {
8115 got_worktree_close(worktree);
8116 worktree = NULL;
8119 error = got_object_open_as_commit(&commit, repo, commit_id);
8120 if (error)
8121 goto done;
8123 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8124 if (error) {
8125 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8126 goto done;
8127 fprintf(stderr, "%s: '%s' is no known command or path\n",
8128 getprogname(), argv[0]);
8129 usage(1, 1);
8130 /* not reached */
8133 error = got_object_id_str(&commit_id_str, commit_id);
8134 if (error)
8135 goto done;
8137 cmd = &tog_commands[0]; /* log */
8138 argc = 4;
8139 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8140 error = cmd->cmd_main(argc, cmd_argv);
8141 done:
8142 if (repo) {
8143 close_err = got_repo_close(repo);
8144 if (error == NULL)
8145 error = close_err;
8147 if (commit)
8148 got_object_commit_close(commit);
8149 if (worktree)
8150 got_worktree_close(worktree);
8151 if (pack_fds) {
8152 const struct got_error *pack_err =
8153 got_repo_pack_fds_close(pack_fds);
8154 if (error == NULL)
8155 error = pack_err;
8157 free(id);
8158 free(commit_id_str);
8159 free(commit_id);
8160 free(cwd);
8161 free(repo_path);
8162 free(in_repo_path);
8163 if (cmd_argv) {
8164 int i;
8165 for (i = 0; i < argc; i++)
8166 free(cmd_argv[i]);
8167 free(cmd_argv);
8169 tog_free_refs();
8170 return error;
8173 int
8174 main(int argc, char *argv[])
8176 const struct got_error *error = NULL;
8177 const struct tog_cmd *cmd = NULL;
8178 int ch, hflag = 0, Vflag = 0;
8179 char **cmd_argv = NULL;
8180 static const struct option longopts[] = {
8181 { "version", no_argument, NULL, 'V' },
8182 { NULL, 0, NULL, 0}
8184 char *diff_algo_str = NULL;
8186 setlocale(LC_CTYPE, "");
8188 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8189 switch (ch) {
8190 case 'h':
8191 hflag = 1;
8192 break;
8193 case 'V':
8194 Vflag = 1;
8195 break;
8196 default:
8197 usage(hflag, 1);
8198 /* NOTREACHED */
8202 argc -= optind;
8203 argv += optind;
8204 optind = 1;
8205 optreset = 1;
8207 if (Vflag) {
8208 got_version_print_str();
8209 return 0;
8212 #ifndef PROFILE
8213 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8214 NULL) == -1)
8215 err(1, "pledge");
8216 #endif
8218 if (argc == 0) {
8219 if (hflag)
8220 usage(hflag, 0);
8221 /* Build an argument vector which runs a default command. */
8222 cmd = &tog_commands[0];
8223 argc = 1;
8224 cmd_argv = make_argv(argc, cmd->name);
8225 } else {
8226 size_t i;
8228 /* Did the user specify a command? */
8229 for (i = 0; i < nitems(tog_commands); i++) {
8230 if (strncmp(tog_commands[i].name, argv[0],
8231 strlen(argv[0])) == 0) {
8232 cmd = &tog_commands[i];
8233 break;
8238 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8239 if (diff_algo_str) {
8240 if (strcasecmp(diff_algo_str, "patience") == 0)
8241 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8242 if (strcasecmp(diff_algo_str, "myers") == 0)
8243 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8246 if (cmd == NULL) {
8247 if (argc != 1)
8248 usage(0, 1);
8249 /* No command specified; try log with a path */
8250 error = tog_log_with_path(argc, argv);
8251 } else {
8252 if (hflag)
8253 cmd->cmd_usage();
8254 else
8255 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8258 endwin();
8259 putchar('\n');
8260 if (cmd_argv) {
8261 int i;
8262 for (i = 0; i < argc; i++)
8263 free(cmd_argv[i]);
8264 free(cmd_argv);
8267 if (error && error->code != GOT_ERR_CANCELLED)
8268 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8269 return 0;