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 err = offset_selection_down(v->child);
1253 } else {
1254 offset_selection_up(v);
1255 offset_selection_up(v->child);
1257 if (v->resize)
1258 err = v->resize(v, 0);
1259 else if (v->child->resize)
1260 err = v->child->resize(v->child, 0);
1262 return err;
1266 * Compute view->count from numeric input. Assign total to view->count and
1267 * return first non-numeric key entered.
1269 static int
1270 get_compound_key(struct tog_view *view, int c)
1272 struct tog_view *v = view;
1273 int x, n = 0;
1275 if (view_is_hsplit_top(view))
1276 v = view->child;
1277 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1278 v = view->parent;
1280 view->count = 0;
1281 cbreak(); /* block for input */
1282 wmove(v->window, v->nlines - 1, 0);
1283 wclrtoeol(v->window);
1284 waddch(v->window, ':');
1286 do {
1287 x = getcurx(v->window);
1288 if (x != ERR && x < view->ncols) {
1289 waddch(v->window, c);
1290 wrefresh(v->window);
1294 * Don't overflow. Max valid request should be the greatest
1295 * between the longest and total lines; cap at 10 million.
1297 if (n >= 9999999)
1298 n = 9999999;
1299 else
1300 n = n * 10 + (c - '0');
1301 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1303 /* Massage excessive or inapplicable values at the input handler. */
1304 view->count = n;
1306 return c;
1309 static const struct got_error *
1310 view_input(struct tog_view **new, int *done, struct tog_view *view,
1311 struct tog_view_list_head *views)
1313 const struct got_error *err = NULL;
1314 struct tog_view *v;
1315 int ch, errcode;
1317 *new = NULL;
1319 /* Clear "no matches" indicator. */
1320 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1321 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1322 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1323 view->count = 0;
1326 if (view->searching && !view->search_next_done) {
1327 errcode = pthread_mutex_unlock(&tog_mutex);
1328 if (errcode)
1329 return got_error_set_errno(errcode,
1330 "pthread_mutex_unlock");
1331 sched_yield();
1332 errcode = pthread_mutex_lock(&tog_mutex);
1333 if (errcode)
1334 return got_error_set_errno(errcode,
1335 "pthread_mutex_lock");
1336 view->search_next(view);
1337 return NULL;
1340 nodelay(view->window, FALSE);
1341 /* Allow threads to make progress while we are waiting for input. */
1342 errcode = pthread_mutex_unlock(&tog_mutex);
1343 if (errcode)
1344 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1345 /* If we have an unfinished count, let C-g or backspace abort. */
1346 if (view->count && --view->count) {
1347 cbreak();
1348 nodelay(view->window, TRUE);
1349 ch = wgetch(view->window);
1350 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1351 view->count = 0;
1352 else
1353 ch = view->ch;
1354 } else {
1355 ch = wgetch(view->window);
1356 if (ch >= '1' && ch <= '9')
1357 view->ch = ch = get_compound_key(view, ch);
1359 errcode = pthread_mutex_lock(&tog_mutex);
1360 if (errcode)
1361 return got_error_set_errno(errcode, "pthread_mutex_lock");
1362 nodelay(view->window, TRUE);
1364 if (tog_sigwinch_received || tog_sigcont_received) {
1365 tog_resizeterm();
1366 tog_sigwinch_received = 0;
1367 tog_sigcont_received = 0;
1368 TAILQ_FOREACH(v, views, entry) {
1369 err = view_resize(v);
1370 if (err)
1371 return err;
1372 err = v->input(new, v, KEY_RESIZE);
1373 if (err)
1374 return err;
1375 if (v->child) {
1376 err = view_resize(v->child);
1377 if (err)
1378 return err;
1379 err = v->child->input(new, v->child,
1380 KEY_RESIZE);
1381 if (err)
1382 return err;
1383 if (v->child->resized_x || v->child->resized_y) {
1384 err = view_resize_split(v, 0);
1385 if (err)
1386 return err;
1392 switch (ch) {
1393 case '\t':
1394 view->count = 0;
1395 if (view->child) {
1396 view->focussed = 0;
1397 view->child->focussed = 1;
1398 view->focus_child = 1;
1399 } else if (view->parent) {
1400 view->focussed = 0;
1401 view->parent->focussed = 1;
1402 view->parent->focus_child = 0;
1403 if (!view_is_splitscreen(view)) {
1404 if (view->parent->resize) {
1405 err = view->parent->resize(view->parent,
1406 0);
1407 if (err)
1408 return err;
1410 offset_selection_up(view->parent);
1411 err = view_fullscreen(view->parent);
1412 if (err)
1413 return err;
1416 break;
1417 case 'q':
1418 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1419 if (view->parent->resize) {
1420 /* might need more commits to fill fullscreen */
1421 err = view->parent->resize(view->parent, 0);
1422 if (err)
1423 break;
1425 offset_selection_up(view->parent);
1427 err = view->input(new, view, ch);
1428 view->dying = 1;
1429 break;
1430 case 'Q':
1431 *done = 1;
1432 break;
1433 case 'F':
1434 view->count = 0;
1435 if (view_is_parent_view(view)) {
1436 if (view->child == NULL)
1437 break;
1438 if (view_is_splitscreen(view->child)) {
1439 view->focussed = 0;
1440 view->child->focussed = 1;
1441 err = view_fullscreen(view->child);
1442 } else {
1443 err = view_splitscreen(view->child);
1444 if (!err)
1445 err = view_resize_split(view, 0);
1447 if (err)
1448 break;
1449 err = view->child->input(new, view->child,
1450 KEY_RESIZE);
1451 } else {
1452 if (view_is_splitscreen(view)) {
1453 view->parent->focussed = 0;
1454 view->focussed = 1;
1455 err = view_fullscreen(view);
1456 } else {
1457 err = view_splitscreen(view);
1458 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1459 err = view_resize(view->parent);
1460 if (!err)
1461 err = view_resize_split(view, 0);
1463 if (err)
1464 break;
1465 err = view->input(new, view, KEY_RESIZE);
1467 if (err)
1468 break;
1469 if (view->resize) {
1470 err = view->resize(view, 0);
1471 if (err)
1472 break;
1474 if (view->parent)
1475 err = offset_selection_down(view->parent);
1476 if (!err)
1477 err = offset_selection_down(view);
1478 break;
1479 case 'S':
1480 view->count = 0;
1481 err = switch_split(view);
1482 break;
1483 case '-':
1484 err = view_resize_split(view, -1);
1485 break;
1486 case '+':
1487 err = view_resize_split(view, 1);
1488 break;
1489 case KEY_RESIZE:
1490 break;
1491 case '/':
1492 view->count = 0;
1493 if (view->search_start)
1494 view_search_start(view);
1495 else
1496 err = view->input(new, view, ch);
1497 break;
1498 case 'N':
1499 case 'n':
1500 if (view->search_started && view->search_next) {
1501 view->searching = (ch == 'n' ?
1502 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1503 view->search_next_done = 0;
1504 view->search_next(view);
1505 } else
1506 err = view->input(new, view, ch);
1507 break;
1508 case 'A':
1509 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1510 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1511 else
1512 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1513 TAILQ_FOREACH(v, views, entry) {
1514 if (v->reset) {
1515 err = v->reset(v);
1516 if (err)
1517 return err;
1519 if (v->child && v->child->reset) {
1520 err = v->child->reset(v->child);
1521 if (err)
1522 return err;
1525 break;
1526 default:
1527 err = view->input(new, view, ch);
1528 break;
1531 return err;
1534 static int
1535 view_needs_focus_indication(struct tog_view *view)
1537 if (view_is_parent_view(view)) {
1538 if (view->child == NULL || view->child->focussed)
1539 return 0;
1540 if (!view_is_splitscreen(view->child))
1541 return 0;
1542 } else if (!view_is_splitscreen(view))
1543 return 0;
1545 return view->focussed;
1548 static const struct got_error *
1549 view_loop(struct tog_view *view)
1551 const struct got_error *err = NULL;
1552 struct tog_view_list_head views;
1553 struct tog_view *new_view;
1554 char *mode;
1555 int fast_refresh = 10;
1556 int done = 0, errcode;
1558 mode = getenv("TOG_VIEW_SPLIT_MODE");
1559 if (!mode || !(*mode == 'h' || *mode == 'H'))
1560 view->mode = TOG_VIEW_SPLIT_VERT;
1561 else
1562 view->mode = TOG_VIEW_SPLIT_HRZN;
1564 errcode = pthread_mutex_lock(&tog_mutex);
1565 if (errcode)
1566 return got_error_set_errno(errcode, "pthread_mutex_lock");
1568 TAILQ_INIT(&views);
1569 TAILQ_INSERT_HEAD(&views, view, entry);
1571 view->focussed = 1;
1572 err = view->show(view);
1573 if (err)
1574 return err;
1575 update_panels();
1576 doupdate();
1577 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1578 !tog_fatal_signal_received()) {
1579 /* Refresh fast during initialization, then become slower. */
1580 if (fast_refresh && fast_refresh-- == 0)
1581 halfdelay(10); /* switch to once per second */
1583 err = view_input(&new_view, &done, view, &views);
1584 if (err)
1585 break;
1586 if (view->dying) {
1587 struct tog_view *v, *prev = NULL;
1589 if (view_is_parent_view(view))
1590 prev = TAILQ_PREV(view, tog_view_list_head,
1591 entry);
1592 else if (view->parent)
1593 prev = view->parent;
1595 if (view->parent) {
1596 view->parent->child = NULL;
1597 view->parent->focus_child = 0;
1598 /* Restore fullscreen line height. */
1599 view->parent->nlines = view->parent->lines;
1600 err = view_resize(view->parent);
1601 if (err)
1602 break;
1603 /* Make resized splits persist. */
1604 view_transfer_size(view->parent, view);
1605 } else
1606 TAILQ_REMOVE(&views, view, entry);
1608 err = view_close(view);
1609 if (err)
1610 goto done;
1612 view = NULL;
1613 TAILQ_FOREACH(v, &views, entry) {
1614 if (v->focussed)
1615 break;
1617 if (view == NULL && new_view == NULL) {
1618 /* No view has focus. Try to pick one. */
1619 if (prev)
1620 view = prev;
1621 else if (!TAILQ_EMPTY(&views)) {
1622 view = TAILQ_LAST(&views,
1623 tog_view_list_head);
1625 if (view) {
1626 if (view->focus_child) {
1627 view->child->focussed = 1;
1628 view = view->child;
1629 } else
1630 view->focussed = 1;
1634 if (new_view) {
1635 struct tog_view *v, *t;
1636 /* Only allow one parent view per type. */
1637 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1638 if (v->type != new_view->type)
1639 continue;
1640 TAILQ_REMOVE(&views, v, entry);
1641 err = view_close(v);
1642 if (err)
1643 goto done;
1644 break;
1646 TAILQ_INSERT_TAIL(&views, new_view, entry);
1647 view = new_view;
1649 if (view) {
1650 if (view_is_parent_view(view)) {
1651 if (view->child && view->child->focussed)
1652 view = view->child;
1653 } else {
1654 if (view->parent && view->parent->focussed)
1655 view = view->parent;
1657 show_panel(view->panel);
1658 if (view->child && view_is_splitscreen(view->child))
1659 show_panel(view->child->panel);
1660 if (view->parent && view_is_splitscreen(view)) {
1661 err = view->parent->show(view->parent);
1662 if (err)
1663 goto done;
1665 err = view->show(view);
1666 if (err)
1667 goto done;
1668 if (view->child) {
1669 err = view->child->show(view->child);
1670 if (err)
1671 goto done;
1673 update_panels();
1674 doupdate();
1677 done:
1678 while (!TAILQ_EMPTY(&views)) {
1679 const struct got_error *close_err;
1680 view = TAILQ_FIRST(&views);
1681 TAILQ_REMOVE(&views, view, entry);
1682 close_err = view_close(view);
1683 if (close_err && err == NULL)
1684 err = close_err;
1687 errcode = pthread_mutex_unlock(&tog_mutex);
1688 if (errcode && err == NULL)
1689 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1691 return err;
1694 __dead static void
1695 usage_log(void)
1697 endwin();
1698 fprintf(stderr,
1699 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1700 getprogname());
1701 exit(1);
1704 /* Create newly allocated wide-character string equivalent to a byte string. */
1705 static const struct got_error *
1706 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1708 char *vis = NULL;
1709 const struct got_error *err = NULL;
1711 *ws = NULL;
1712 *wlen = mbstowcs(NULL, s, 0);
1713 if (*wlen == (size_t)-1) {
1714 int vislen;
1715 if (errno != EILSEQ)
1716 return got_error_from_errno("mbstowcs");
1718 /* byte string invalid in current encoding; try to "fix" it */
1719 err = got_mbsavis(&vis, &vislen, s);
1720 if (err)
1721 return err;
1722 *wlen = mbstowcs(NULL, vis, 0);
1723 if (*wlen == (size_t)-1) {
1724 err = got_error_from_errno("mbstowcs"); /* give up */
1725 goto done;
1729 *ws = calloc(*wlen + 1, sizeof(**ws));
1730 if (*ws == NULL) {
1731 err = got_error_from_errno("calloc");
1732 goto done;
1735 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1736 err = got_error_from_errno("mbstowcs");
1737 done:
1738 free(vis);
1739 if (err) {
1740 free(*ws);
1741 *ws = NULL;
1742 *wlen = 0;
1744 return err;
1747 static const struct got_error *
1748 expand_tab(char **ptr, const char *src)
1750 char *dst;
1751 size_t len, n, idx = 0, sz = 0;
1753 *ptr = NULL;
1754 n = len = strlen(src);
1755 dst = malloc(n + 1);
1756 if (dst == NULL)
1757 return got_error_from_errno("malloc");
1759 while (idx < len && src[idx]) {
1760 const char c = src[idx];
1762 if (c == '\t') {
1763 size_t nb = TABSIZE - sz % TABSIZE;
1764 char *p;
1766 p = realloc(dst, n + nb);
1767 if (p == NULL) {
1768 free(dst);
1769 return got_error_from_errno("realloc");
1772 dst = p;
1773 n += nb;
1774 memset(dst + sz, ' ', nb);
1775 sz += nb;
1776 } else
1777 dst[sz++] = src[idx];
1778 ++idx;
1781 dst[sz] = '\0';
1782 *ptr = dst;
1783 return NULL;
1787 * Advance at most n columns from wline starting at offset off.
1788 * Return the index to the first character after the span operation.
1789 * Return the combined column width of all spanned wide character in
1790 * *rcol.
1792 static int
1793 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1795 int width, i, cols = 0;
1797 if (n == 0) {
1798 *rcol = cols;
1799 return off;
1802 for (i = off; wline[i] != L'\0'; ++i) {
1803 if (wline[i] == L'\t')
1804 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1805 else
1806 width = wcwidth(wline[i]);
1808 if (width == -1) {
1809 width = 1;
1810 wline[i] = L'.';
1813 if (cols + width > n)
1814 break;
1815 cols += width;
1818 *rcol = cols;
1819 return i;
1823 * Format a line for display, ensuring that it won't overflow a width limit.
1824 * With scrolling, the width returned refers to the scrolled version of the
1825 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1827 static const struct got_error *
1828 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1829 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1831 const struct got_error *err = NULL;
1832 int cols;
1833 wchar_t *wline = NULL;
1834 char *exstr = NULL;
1835 size_t wlen;
1836 int i, scrollx;
1838 *wlinep = NULL;
1839 *widthp = 0;
1841 if (expand) {
1842 err = expand_tab(&exstr, line);
1843 if (err)
1844 return err;
1847 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1848 free(exstr);
1849 if (err)
1850 return err;
1852 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1854 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1855 wline[wlen - 1] = L'\0';
1856 wlen--;
1858 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1859 wline[wlen - 1] = L'\0';
1860 wlen--;
1863 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1864 wline[i] = L'\0';
1866 if (widthp)
1867 *widthp = cols;
1868 if (scrollxp)
1869 *scrollxp = scrollx;
1870 if (err)
1871 free(wline);
1872 else
1873 *wlinep = wline;
1874 return err;
1877 static const struct got_error*
1878 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1879 struct got_object_id *id, struct got_repository *repo)
1881 static const struct got_error *err = NULL;
1882 struct got_reflist_entry *re;
1883 char *s;
1884 const char *name;
1886 *refs_str = NULL;
1888 TAILQ_FOREACH(re, refs, entry) {
1889 struct got_tag_object *tag = NULL;
1890 struct got_object_id *ref_id;
1891 int cmp;
1893 name = got_ref_get_name(re->ref);
1894 if (strcmp(name, GOT_REF_HEAD) == 0)
1895 continue;
1896 if (strncmp(name, "refs/", 5) == 0)
1897 name += 5;
1898 if (strncmp(name, "got/", 4) == 0 &&
1899 strncmp(name, "got/backup/", 11) != 0)
1900 continue;
1901 if (strncmp(name, "heads/", 6) == 0)
1902 name += 6;
1903 if (strncmp(name, "remotes/", 8) == 0) {
1904 name += 8;
1905 s = strstr(name, "/" GOT_REF_HEAD);
1906 if (s != NULL && s[strlen(s)] == '\0')
1907 continue;
1909 err = got_ref_resolve(&ref_id, repo, re->ref);
1910 if (err)
1911 break;
1912 if (strncmp(name, "tags/", 5) == 0) {
1913 err = got_object_open_as_tag(&tag, repo, ref_id);
1914 if (err) {
1915 if (err->code != GOT_ERR_OBJ_TYPE) {
1916 free(ref_id);
1917 break;
1919 /* Ref points at something other than a tag. */
1920 err = NULL;
1921 tag = NULL;
1924 cmp = got_object_id_cmp(tag ?
1925 got_object_tag_get_object_id(tag) : ref_id, id);
1926 free(ref_id);
1927 if (tag)
1928 got_object_tag_close(tag);
1929 if (cmp != 0)
1930 continue;
1931 s = *refs_str;
1932 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1933 s ? ", " : "", name) == -1) {
1934 err = got_error_from_errno("asprintf");
1935 free(s);
1936 *refs_str = NULL;
1937 break;
1939 free(s);
1942 return err;
1945 static const struct got_error *
1946 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1947 int col_tab_align)
1949 char *smallerthan;
1951 smallerthan = strchr(author, '<');
1952 if (smallerthan && smallerthan[1] != '\0')
1953 author = smallerthan + 1;
1954 author[strcspn(author, "@>")] = '\0';
1955 return format_line(wauthor, author_width, NULL, author, 0, limit,
1956 col_tab_align, 0);
1959 static const struct got_error *
1960 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1961 struct got_object_id *id, const size_t date_display_cols,
1962 int author_display_cols)
1964 struct tog_log_view_state *s = &view->state.log;
1965 const struct got_error *err = NULL;
1966 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1967 char *logmsg0 = NULL, *logmsg = NULL;
1968 char *author = NULL;
1969 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1970 int author_width, logmsg_width;
1971 char *newline, *line = NULL;
1972 int col, limit, scrollx;
1973 const int avail = view->ncols;
1974 struct tm tm;
1975 time_t committer_time;
1976 struct tog_color *tc;
1978 committer_time = got_object_commit_get_committer_time(commit);
1979 if (gmtime_r(&committer_time, &tm) == NULL)
1980 return got_error_from_errno("gmtime_r");
1981 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1982 return got_error(GOT_ERR_NO_SPACE);
1984 if (avail <= date_display_cols)
1985 limit = MIN(sizeof(datebuf) - 1, avail);
1986 else
1987 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1988 tc = get_color(&s->colors, TOG_COLOR_DATE);
1989 if (tc)
1990 wattr_on(view->window,
1991 COLOR_PAIR(tc->colorpair), NULL);
1992 waddnstr(view->window, datebuf, limit);
1993 if (tc)
1994 wattr_off(view->window,
1995 COLOR_PAIR(tc->colorpair), NULL);
1996 col = limit;
1997 if (col > avail)
1998 goto done;
2000 if (avail >= 120) {
2001 char *id_str;
2002 err = got_object_id_str(&id_str, id);
2003 if (err)
2004 goto done;
2005 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2006 if (tc)
2007 wattr_on(view->window,
2008 COLOR_PAIR(tc->colorpair), NULL);
2009 wprintw(view->window, "%.8s ", id_str);
2010 if (tc)
2011 wattr_off(view->window,
2012 COLOR_PAIR(tc->colorpair), NULL);
2013 free(id_str);
2014 col += 9;
2015 if (col > avail)
2016 goto done;
2019 if (s->use_committer)
2020 author = strdup(got_object_commit_get_committer(commit));
2021 else
2022 author = strdup(got_object_commit_get_author(commit));
2023 if (author == NULL) {
2024 err = got_error_from_errno("strdup");
2025 goto done;
2027 err = format_author(&wauthor, &author_width, author, avail - col, col);
2028 if (err)
2029 goto done;
2030 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2031 if (tc)
2032 wattr_on(view->window,
2033 COLOR_PAIR(tc->colorpair), NULL);
2034 waddwstr(view->window, wauthor);
2035 if (tc)
2036 wattr_off(view->window,
2037 COLOR_PAIR(tc->colorpair), NULL);
2038 col += author_width;
2039 while (col < avail && author_width < author_display_cols + 2) {
2040 waddch(view->window, ' ');
2041 col++;
2042 author_width++;
2044 if (col > avail)
2045 goto done;
2047 err = got_object_commit_get_logmsg(&logmsg0, commit);
2048 if (err)
2049 goto done;
2050 logmsg = logmsg0;
2051 while (*logmsg == '\n')
2052 logmsg++;
2053 newline = strchr(logmsg, '\n');
2054 if (newline)
2055 *newline = '\0';
2056 limit = avail - col;
2057 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2058 limit--; /* for the border */
2059 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2060 limit, col, 1);
2061 if (err)
2062 goto done;
2063 waddwstr(view->window, &wlogmsg[scrollx]);
2064 col += MAX(logmsg_width, 0);
2065 while (col < avail) {
2066 waddch(view->window, ' ');
2067 col++;
2069 done:
2070 free(logmsg0);
2071 free(wlogmsg);
2072 free(author);
2073 free(wauthor);
2074 free(line);
2075 return err;
2078 static struct commit_queue_entry *
2079 alloc_commit_queue_entry(struct got_commit_object *commit,
2080 struct got_object_id *id)
2082 struct commit_queue_entry *entry;
2084 entry = calloc(1, sizeof(*entry));
2085 if (entry == NULL)
2086 return NULL;
2088 entry->id = id;
2089 entry->commit = commit;
2090 return entry;
2093 static void
2094 pop_commit(struct commit_queue *commits)
2096 struct commit_queue_entry *entry;
2098 entry = TAILQ_FIRST(&commits->head);
2099 TAILQ_REMOVE(&commits->head, entry, entry);
2100 got_object_commit_close(entry->commit);
2101 commits->ncommits--;
2102 /* Don't free entry->id! It is owned by the commit graph. */
2103 free(entry);
2106 static void
2107 free_commits(struct commit_queue *commits)
2109 while (!TAILQ_EMPTY(&commits->head))
2110 pop_commit(commits);
2113 static const struct got_error *
2114 match_commit(int *have_match, struct got_object_id *id,
2115 struct got_commit_object *commit, regex_t *regex)
2117 const struct got_error *err = NULL;
2118 regmatch_t regmatch;
2119 char *id_str = NULL, *logmsg = NULL;
2121 *have_match = 0;
2123 err = got_object_id_str(&id_str, id);
2124 if (err)
2125 return err;
2127 err = got_object_commit_get_logmsg(&logmsg, commit);
2128 if (err)
2129 goto done;
2131 if (regexec(regex, got_object_commit_get_author(commit), 1,
2132 &regmatch, 0) == 0 ||
2133 regexec(regex, got_object_commit_get_committer(commit), 1,
2134 &regmatch, 0) == 0 ||
2135 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2136 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2137 *have_match = 1;
2138 done:
2139 free(id_str);
2140 free(logmsg);
2141 return err;
2144 static const struct got_error *
2145 queue_commits(struct tog_log_thread_args *a)
2147 const struct got_error *err = NULL;
2150 * We keep all commits open throughout the lifetime of the log
2151 * view in order to avoid having to re-fetch commits from disk
2152 * while updating the display.
2154 do {
2155 struct got_object_id *id;
2156 struct got_commit_object *commit;
2157 struct commit_queue_entry *entry;
2158 int errcode;
2160 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2161 NULL, NULL);
2162 if (err || id == NULL)
2163 break;
2165 err = got_object_open_as_commit(&commit, a->repo, id);
2166 if (err)
2167 break;
2168 entry = alloc_commit_queue_entry(commit, id);
2169 if (entry == NULL) {
2170 err = got_error_from_errno("alloc_commit_queue_entry");
2171 break;
2174 errcode = pthread_mutex_lock(&tog_mutex);
2175 if (errcode) {
2176 err = got_error_set_errno(errcode,
2177 "pthread_mutex_lock");
2178 break;
2181 entry->idx = a->commits->ncommits;
2182 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2183 a->commits->ncommits++;
2185 if (*a->searching == TOG_SEARCH_FORWARD &&
2186 !*a->search_next_done) {
2187 int have_match;
2188 err = match_commit(&have_match, id, commit, a->regex);
2189 if (err)
2190 break;
2191 if (have_match)
2192 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2195 errcode = pthread_mutex_unlock(&tog_mutex);
2196 if (errcode && err == NULL)
2197 err = got_error_set_errno(errcode,
2198 "pthread_mutex_unlock");
2199 if (err)
2200 break;
2201 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2203 return err;
2206 static void
2207 select_commit(struct tog_log_view_state *s)
2209 struct commit_queue_entry *entry;
2210 int ncommits = 0;
2212 entry = s->first_displayed_entry;
2213 while (entry) {
2214 if (ncommits == s->selected) {
2215 s->selected_entry = entry;
2216 break;
2218 entry = TAILQ_NEXT(entry, entry);
2219 ncommits++;
2223 static const struct got_error *
2224 draw_commits(struct tog_view *view)
2226 const struct got_error *err = NULL;
2227 struct tog_log_view_state *s = &view->state.log;
2228 struct commit_queue_entry *entry = s->selected_entry;
2229 const int limit = view->nlines;
2230 int width;
2231 int ncommits, author_cols = 4;
2232 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2233 char *refs_str = NULL;
2234 wchar_t *wline;
2235 struct tog_color *tc;
2236 static const size_t date_display_cols = 12;
2238 if (s->selected_entry &&
2239 !(view->searching && view->search_next_done == 0)) {
2240 struct got_reflist_head *refs;
2241 err = got_object_id_str(&id_str, s->selected_entry->id);
2242 if (err)
2243 return err;
2244 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2245 s->selected_entry->id);
2246 if (refs) {
2247 err = build_refs_str(&refs_str, refs,
2248 s->selected_entry->id, s->repo);
2249 if (err)
2250 goto done;
2254 if (s->thread_args.commits_needed == 0)
2255 halfdelay(10); /* disable fast refresh */
2257 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2258 if (asprintf(&ncommits_str, " [%d/%d] %s",
2259 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2260 (view->searching && !view->search_next_done) ?
2261 "searching..." : "loading...") == -1) {
2262 err = got_error_from_errno("asprintf");
2263 goto done;
2265 } else {
2266 const char *search_str = NULL;
2268 if (view->searching) {
2269 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2270 search_str = "no more matches";
2271 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2272 search_str = "no matches found";
2273 else if (!view->search_next_done)
2274 search_str = "searching...";
2277 if (asprintf(&ncommits_str, " [%d/%d] %s",
2278 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2279 search_str ? search_str :
2280 (refs_str ? refs_str : "")) == -1) {
2281 err = got_error_from_errno("asprintf");
2282 goto done;
2286 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2287 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2288 "........................................",
2289 s->in_repo_path, ncommits_str) == -1) {
2290 err = got_error_from_errno("asprintf");
2291 header = NULL;
2292 goto done;
2294 } else if (asprintf(&header, "commit %s%s",
2295 id_str ? id_str : "........................................",
2296 ncommits_str) == -1) {
2297 err = got_error_from_errno("asprintf");
2298 header = NULL;
2299 goto done;
2301 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2302 if (err)
2303 goto done;
2305 werase(view->window);
2307 if (view_needs_focus_indication(view))
2308 wstandout(view->window);
2309 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2310 if (tc)
2311 wattr_on(view->window,
2312 COLOR_PAIR(tc->colorpair), NULL);
2313 waddwstr(view->window, wline);
2314 if (tc)
2315 wattr_off(view->window,
2316 COLOR_PAIR(tc->colorpair), NULL);
2317 while (width < view->ncols) {
2318 waddch(view->window, ' ');
2319 width++;
2321 if (view_needs_focus_indication(view))
2322 wstandend(view->window);
2323 free(wline);
2324 if (limit <= 1)
2325 goto done;
2327 /* Grow author column size if necessary, and set view->maxx. */
2328 entry = s->first_displayed_entry;
2329 ncommits = 0;
2330 view->maxx = 0;
2331 while (entry) {
2332 struct got_commit_object *c = entry->commit;
2333 char *author, *eol, *msg, *msg0;
2334 wchar_t *wauthor, *wmsg;
2335 int width;
2336 if (ncommits >= limit - 1)
2337 break;
2338 if (s->use_committer)
2339 author = strdup(got_object_commit_get_committer(c));
2340 else
2341 author = strdup(got_object_commit_get_author(c));
2342 if (author == NULL) {
2343 err = got_error_from_errno("strdup");
2344 goto done;
2346 err = format_author(&wauthor, &width, author, COLS,
2347 date_display_cols);
2348 if (author_cols < width)
2349 author_cols = width;
2350 free(wauthor);
2351 free(author);
2352 if (err)
2353 goto done;
2354 err = got_object_commit_get_logmsg(&msg0, c);
2355 if (err)
2356 goto done;
2357 msg = msg0;
2358 while (*msg == '\n')
2359 ++msg;
2360 if ((eol = strchr(msg, '\n')))
2361 *eol = '\0';
2362 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2363 date_display_cols + author_cols, 0);
2364 if (err)
2365 goto done;
2366 view->maxx = MAX(view->maxx, width);
2367 free(msg0);
2368 free(wmsg);
2369 ncommits++;
2370 entry = TAILQ_NEXT(entry, entry);
2373 entry = s->first_displayed_entry;
2374 s->last_displayed_entry = s->first_displayed_entry;
2375 ncommits = 0;
2376 while (entry) {
2377 if (ncommits >= limit - 1)
2378 break;
2379 if (ncommits == s->selected)
2380 wstandout(view->window);
2381 err = draw_commit(view, entry->commit, entry->id,
2382 date_display_cols, author_cols);
2383 if (ncommits == s->selected)
2384 wstandend(view->window);
2385 if (err)
2386 goto done;
2387 ncommits++;
2388 s->last_displayed_entry = entry;
2389 entry = TAILQ_NEXT(entry, entry);
2392 view_border(view);
2393 done:
2394 free(id_str);
2395 free(refs_str);
2396 free(ncommits_str);
2397 free(header);
2398 return err;
2401 static void
2402 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2404 struct commit_queue_entry *entry;
2405 int nscrolled = 0;
2407 entry = TAILQ_FIRST(&s->commits.head);
2408 if (s->first_displayed_entry == entry)
2409 return;
2411 entry = s->first_displayed_entry;
2412 while (entry && nscrolled < maxscroll) {
2413 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2414 if (entry) {
2415 s->first_displayed_entry = entry;
2416 nscrolled++;
2421 static const struct got_error *
2422 trigger_log_thread(struct tog_view *view, int wait)
2424 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2425 int errcode;
2427 halfdelay(1); /* fast refresh while loading commits */
2429 while (!ta->log_complete && !tog_thread_error &&
2430 (ta->commits_needed > 0 || ta->load_all)) {
2431 /* Wake the log thread. */
2432 errcode = pthread_cond_signal(&ta->need_commits);
2433 if (errcode)
2434 return got_error_set_errno(errcode,
2435 "pthread_cond_signal");
2438 * The mutex will be released while the view loop waits
2439 * in wgetch(), at which time the log thread will run.
2441 if (!wait)
2442 break;
2444 /* Display progress update in log view. */
2445 show_log_view(view);
2446 update_panels();
2447 doupdate();
2449 /* Wait right here while next commit is being loaded. */
2450 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2451 if (errcode)
2452 return got_error_set_errno(errcode,
2453 "pthread_cond_wait");
2455 /* Display progress update in log view. */
2456 show_log_view(view);
2457 update_panels();
2458 doupdate();
2461 return NULL;
2464 static const struct got_error *
2465 request_log_commits(struct tog_view *view)
2467 struct tog_log_view_state *state = &view->state.log;
2468 const struct got_error *err = NULL;
2470 if (state->thread_args.log_complete)
2471 return NULL;
2473 state->thread_args.commits_needed += view->nscrolled;
2474 err = trigger_log_thread(view, 1);
2475 view->nscrolled = 0;
2477 return err;
2480 static const struct got_error *
2481 log_scroll_down(struct tog_view *view, int maxscroll)
2483 struct tog_log_view_state *s = &view->state.log;
2484 const struct got_error *err = NULL;
2485 struct commit_queue_entry *pentry;
2486 int nscrolled = 0, ncommits_needed;
2488 if (s->last_displayed_entry == NULL)
2489 return NULL;
2491 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2492 if (s->commits.ncommits < ncommits_needed &&
2493 !s->thread_args.log_complete) {
2495 * Ask the log thread for required amount of commits.
2497 s->thread_args.commits_needed += maxscroll;
2498 err = trigger_log_thread(view, 1);
2499 if (err)
2500 return err;
2503 do {
2504 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2505 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2506 break;
2508 s->last_displayed_entry = pentry ?
2509 pentry : s->last_displayed_entry;;
2511 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2512 if (pentry == NULL)
2513 break;
2514 s->first_displayed_entry = pentry;
2515 } while (++nscrolled < maxscroll);
2517 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2518 view->nscrolled += nscrolled;
2519 else
2520 view->nscrolled = 0;
2522 return err;
2525 static const struct got_error *
2526 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2527 struct got_commit_object *commit, struct got_object_id *commit_id,
2528 struct tog_view *log_view, struct got_repository *repo)
2530 const struct got_error *err;
2531 struct got_object_qid *parent_id;
2532 struct tog_view *diff_view;
2534 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2535 if (diff_view == NULL)
2536 return got_error_from_errno("view_open");
2538 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2539 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2540 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2541 if (err == NULL)
2542 *new_view = diff_view;
2543 return err;
2546 static const struct got_error *
2547 tree_view_visit_subtree(struct tog_tree_view_state *s,
2548 struct got_tree_object *subtree)
2550 struct tog_parent_tree *parent;
2552 parent = calloc(1, sizeof(*parent));
2553 if (parent == NULL)
2554 return got_error_from_errno("calloc");
2556 parent->tree = s->tree;
2557 parent->first_displayed_entry = s->first_displayed_entry;
2558 parent->selected_entry = s->selected_entry;
2559 parent->selected = s->selected;
2560 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2561 s->tree = subtree;
2562 s->selected = 0;
2563 s->first_displayed_entry = NULL;
2564 return NULL;
2567 static const struct got_error *
2568 tree_view_walk_path(struct tog_tree_view_state *s,
2569 struct got_commit_object *commit, const char *path)
2571 const struct got_error *err = NULL;
2572 struct got_tree_object *tree = NULL;
2573 const char *p;
2574 char *slash, *subpath = NULL;
2576 /* Walk the path and open corresponding tree objects. */
2577 p = path;
2578 while (*p) {
2579 struct got_tree_entry *te;
2580 struct got_object_id *tree_id;
2581 char *te_name;
2583 while (p[0] == '/')
2584 p++;
2586 /* Ensure the correct subtree entry is selected. */
2587 slash = strchr(p, '/');
2588 if (slash == NULL)
2589 te_name = strdup(p);
2590 else
2591 te_name = strndup(p, slash - p);
2592 if (te_name == NULL) {
2593 err = got_error_from_errno("strndup");
2594 break;
2596 te = got_object_tree_find_entry(s->tree, te_name);
2597 if (te == NULL) {
2598 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2599 free(te_name);
2600 break;
2602 free(te_name);
2603 s->first_displayed_entry = s->selected_entry = te;
2605 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2606 break; /* jump to this file's entry */
2608 slash = strchr(p, '/');
2609 if (slash)
2610 subpath = strndup(path, slash - path);
2611 else
2612 subpath = strdup(path);
2613 if (subpath == NULL) {
2614 err = got_error_from_errno("strdup");
2615 break;
2618 err = got_object_id_by_path(&tree_id, s->repo, commit,
2619 subpath);
2620 if (err)
2621 break;
2623 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2624 free(tree_id);
2625 if (err)
2626 break;
2628 err = tree_view_visit_subtree(s, tree);
2629 if (err) {
2630 got_object_tree_close(tree);
2631 break;
2633 if (slash == NULL)
2634 break;
2635 free(subpath);
2636 subpath = NULL;
2637 p = slash;
2640 free(subpath);
2641 return err;
2644 static const struct got_error *
2645 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2646 struct commit_queue_entry *entry, const char *path,
2647 const char *head_ref_name, struct got_repository *repo)
2649 const struct got_error *err = NULL;
2650 struct tog_tree_view_state *s;
2651 struct tog_view *tree_view;
2653 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2654 if (tree_view == NULL)
2655 return got_error_from_errno("view_open");
2657 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2658 if (err)
2659 return err;
2660 s = &tree_view->state.tree;
2662 *new_view = tree_view;
2664 if (got_path_is_root_dir(path))
2665 return NULL;
2667 return tree_view_walk_path(s, entry->commit, path);
2670 static const struct got_error *
2671 block_signals_used_by_main_thread(void)
2673 sigset_t sigset;
2674 int errcode;
2676 if (sigemptyset(&sigset) == -1)
2677 return got_error_from_errno("sigemptyset");
2679 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2680 if (sigaddset(&sigset, SIGWINCH) == -1)
2681 return got_error_from_errno("sigaddset");
2682 if (sigaddset(&sigset, SIGCONT) == -1)
2683 return got_error_from_errno("sigaddset");
2684 if (sigaddset(&sigset, SIGINT) == -1)
2685 return got_error_from_errno("sigaddset");
2686 if (sigaddset(&sigset, SIGTERM) == -1)
2687 return got_error_from_errno("sigaddset");
2689 /* ncurses handles SIGTSTP */
2690 if (sigaddset(&sigset, SIGTSTP) == -1)
2691 return got_error_from_errno("sigaddset");
2693 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2694 if (errcode)
2695 return got_error_set_errno(errcode, "pthread_sigmask");
2697 return NULL;
2700 static void *
2701 log_thread(void *arg)
2703 const struct got_error *err = NULL;
2704 int errcode = 0;
2705 struct tog_log_thread_args *a = arg;
2706 int done = 0;
2709 * Sync startup with main thread such that we begin our
2710 * work once view_input() has released the mutex.
2712 errcode = pthread_mutex_lock(&tog_mutex);
2713 if (errcode) {
2714 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2715 return (void *)err;
2718 err = block_signals_used_by_main_thread();
2719 if (err) {
2720 pthread_mutex_unlock(&tog_mutex);
2721 goto done;
2724 while (!done && !err && !tog_fatal_signal_received()) {
2725 errcode = pthread_mutex_unlock(&tog_mutex);
2726 if (errcode) {
2727 err = got_error_set_errno(errcode,
2728 "pthread_mutex_unlock");
2729 goto done;
2731 err = queue_commits(a);
2732 if (err) {
2733 if (err->code != GOT_ERR_ITER_COMPLETED)
2734 goto done;
2735 err = NULL;
2736 done = 1;
2737 } else if (a->commits_needed > 0 && !a->load_all)
2738 a->commits_needed--;
2740 errcode = pthread_mutex_lock(&tog_mutex);
2741 if (errcode) {
2742 err = got_error_set_errno(errcode,
2743 "pthread_mutex_lock");
2744 goto done;
2745 } else if (*a->quit)
2746 done = 1;
2747 else if (*a->first_displayed_entry == NULL) {
2748 *a->first_displayed_entry =
2749 TAILQ_FIRST(&a->commits->head);
2750 *a->selected_entry = *a->first_displayed_entry;
2753 errcode = pthread_cond_signal(&a->commit_loaded);
2754 if (errcode) {
2755 err = got_error_set_errno(errcode,
2756 "pthread_cond_signal");
2757 pthread_mutex_unlock(&tog_mutex);
2758 goto done;
2761 if (done)
2762 a->commits_needed = 0;
2763 else {
2764 if (a->commits_needed == 0 && !a->load_all) {
2765 errcode = pthread_cond_wait(&a->need_commits,
2766 &tog_mutex);
2767 if (errcode) {
2768 err = got_error_set_errno(errcode,
2769 "pthread_cond_wait");
2770 pthread_mutex_unlock(&tog_mutex);
2771 goto done;
2773 if (*a->quit)
2774 done = 1;
2778 a->log_complete = 1;
2779 errcode = pthread_mutex_unlock(&tog_mutex);
2780 if (errcode)
2781 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2782 done:
2783 if (err) {
2784 tog_thread_error = 1;
2785 pthread_cond_signal(&a->commit_loaded);
2787 return (void *)err;
2790 static const struct got_error *
2791 stop_log_thread(struct tog_log_view_state *s)
2793 const struct got_error *err = NULL, *thread_err = NULL;
2794 int errcode;
2796 if (s->thread) {
2797 s->quit = 1;
2798 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2799 if (errcode)
2800 return got_error_set_errno(errcode,
2801 "pthread_cond_signal");
2802 errcode = pthread_mutex_unlock(&tog_mutex);
2803 if (errcode)
2804 return got_error_set_errno(errcode,
2805 "pthread_mutex_unlock");
2806 errcode = pthread_join(s->thread, (void **)&thread_err);
2807 if (errcode)
2808 return got_error_set_errno(errcode, "pthread_join");
2809 errcode = pthread_mutex_lock(&tog_mutex);
2810 if (errcode)
2811 return got_error_set_errno(errcode,
2812 "pthread_mutex_lock");
2813 s->thread = NULL;
2816 if (s->thread_args.repo) {
2817 err = got_repo_close(s->thread_args.repo);
2818 s->thread_args.repo = NULL;
2821 if (s->thread_args.pack_fds) {
2822 const struct got_error *pack_err =
2823 got_repo_pack_fds_close(s->thread_args.pack_fds);
2824 if (err == NULL)
2825 err = pack_err;
2826 s->thread_args.pack_fds = NULL;
2829 if (s->thread_args.graph) {
2830 got_commit_graph_close(s->thread_args.graph);
2831 s->thread_args.graph = NULL;
2834 return err ? err : thread_err;
2837 static const struct got_error *
2838 close_log_view(struct tog_view *view)
2840 const struct got_error *err = NULL;
2841 struct tog_log_view_state *s = &view->state.log;
2842 int errcode;
2844 err = stop_log_thread(s);
2846 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2847 if (errcode && err == NULL)
2848 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2850 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2851 if (errcode && err == NULL)
2852 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2854 free_commits(&s->commits);
2855 free(s->in_repo_path);
2856 s->in_repo_path = NULL;
2857 free(s->start_id);
2858 s->start_id = NULL;
2859 free(s->head_ref_name);
2860 s->head_ref_name = NULL;
2861 return err;
2864 static const struct got_error *
2865 search_start_log_view(struct tog_view *view)
2867 struct tog_log_view_state *s = &view->state.log;
2869 s->matched_entry = NULL;
2870 s->search_entry = NULL;
2871 return NULL;
2874 static const struct got_error *
2875 search_next_log_view(struct tog_view *view)
2877 const struct got_error *err = NULL;
2878 struct tog_log_view_state *s = &view->state.log;
2879 struct commit_queue_entry *entry;
2881 /* Display progress update in log view. */
2882 show_log_view(view);
2883 update_panels();
2884 doupdate();
2886 if (s->search_entry) {
2887 int errcode, ch;
2888 errcode = pthread_mutex_unlock(&tog_mutex);
2889 if (errcode)
2890 return got_error_set_errno(errcode,
2891 "pthread_mutex_unlock");
2892 ch = wgetch(view->window);
2893 errcode = pthread_mutex_lock(&tog_mutex);
2894 if (errcode)
2895 return got_error_set_errno(errcode,
2896 "pthread_mutex_lock");
2897 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2898 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2899 return NULL;
2901 if (view->searching == TOG_SEARCH_FORWARD)
2902 entry = TAILQ_NEXT(s->search_entry, entry);
2903 else
2904 entry = TAILQ_PREV(s->search_entry,
2905 commit_queue_head, entry);
2906 } else if (s->matched_entry) {
2907 int matched_idx = s->matched_entry->idx;
2908 int selected_idx = s->selected_entry->idx;
2911 * If the user has moved the cursor after we hit a match,
2912 * the position from where we should continue searching
2913 * might have changed.
2915 if (view->searching == TOG_SEARCH_FORWARD) {
2916 if (matched_idx > selected_idx)
2917 entry = TAILQ_NEXT(s->selected_entry, entry);
2918 else
2919 entry = TAILQ_NEXT(s->matched_entry, entry);
2920 } else {
2921 if (matched_idx < selected_idx)
2922 entry = TAILQ_PREV(s->selected_entry,
2923 commit_queue_head, entry);
2924 else
2925 entry = TAILQ_PREV(s->matched_entry,
2926 commit_queue_head, entry);
2928 } else {
2929 entry = s->selected_entry;
2932 while (1) {
2933 int have_match = 0;
2935 if (entry == NULL) {
2936 if (s->thread_args.log_complete ||
2937 view->searching == TOG_SEARCH_BACKWARD) {
2938 view->search_next_done =
2939 (s->matched_entry == NULL ?
2940 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2941 s->search_entry = NULL;
2942 return NULL;
2945 * Poke the log thread for more commits and return,
2946 * allowing the main loop to make progress. Search
2947 * will resume at s->search_entry once we come back.
2949 s->thread_args.commits_needed++;
2950 return trigger_log_thread(view, 0);
2953 err = match_commit(&have_match, entry->id, entry->commit,
2954 &view->regex);
2955 if (err)
2956 break;
2957 if (have_match) {
2958 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2959 s->matched_entry = entry;
2960 break;
2963 s->search_entry = entry;
2964 if (view->searching == TOG_SEARCH_FORWARD)
2965 entry = TAILQ_NEXT(entry, entry);
2966 else
2967 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2970 if (s->matched_entry) {
2971 int cur = s->selected_entry->idx;
2972 while (cur < s->matched_entry->idx) {
2973 err = input_log_view(NULL, view, KEY_DOWN);
2974 if (err)
2975 return err;
2976 cur++;
2978 while (cur > s->matched_entry->idx) {
2979 err = input_log_view(NULL, view, KEY_UP);
2980 if (err)
2981 return err;
2982 cur--;
2986 s->search_entry = NULL;
2988 return NULL;
2991 static const struct got_error *
2992 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2993 struct got_repository *repo, const char *head_ref_name,
2994 const char *in_repo_path, int log_branches)
2996 const struct got_error *err = NULL;
2997 struct tog_log_view_state *s = &view->state.log;
2998 struct got_repository *thread_repo = NULL;
2999 struct got_commit_graph *thread_graph = NULL;
3000 int errcode;
3002 if (in_repo_path != s->in_repo_path) {
3003 free(s->in_repo_path);
3004 s->in_repo_path = strdup(in_repo_path);
3005 if (s->in_repo_path == NULL)
3006 return got_error_from_errno("strdup");
3009 /* The commit queue only contains commits being displayed. */
3010 TAILQ_INIT(&s->commits.head);
3011 s->commits.ncommits = 0;
3013 s->repo = repo;
3014 if (head_ref_name) {
3015 s->head_ref_name = strdup(head_ref_name);
3016 if (s->head_ref_name == NULL) {
3017 err = got_error_from_errno("strdup");
3018 goto done;
3021 s->start_id = got_object_id_dup(start_id);
3022 if (s->start_id == NULL) {
3023 err = got_error_from_errno("got_object_id_dup");
3024 goto done;
3026 s->log_branches = log_branches;
3028 STAILQ_INIT(&s->colors);
3029 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3030 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3031 get_color_value("TOG_COLOR_COMMIT"));
3032 if (err)
3033 goto done;
3034 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3035 get_color_value("TOG_COLOR_AUTHOR"));
3036 if (err) {
3037 free_colors(&s->colors);
3038 goto done;
3040 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3041 get_color_value("TOG_COLOR_DATE"));
3042 if (err) {
3043 free_colors(&s->colors);
3044 goto done;
3048 view->show = show_log_view;
3049 view->input = input_log_view;
3050 view->resize = resize_log_view;
3051 view->close = close_log_view;
3052 view->search_start = search_start_log_view;
3053 view->search_next = search_next_log_view;
3055 if (s->thread_args.pack_fds == NULL) {
3056 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3057 if (err)
3058 goto done;
3060 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3061 s->thread_args.pack_fds);
3062 if (err)
3063 goto done;
3064 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3065 !s->log_branches);
3066 if (err)
3067 goto done;
3068 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3069 s->repo, NULL, NULL);
3070 if (err)
3071 goto done;
3073 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3074 if (errcode) {
3075 err = got_error_set_errno(errcode, "pthread_cond_init");
3076 goto done;
3078 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3079 if (errcode) {
3080 err = got_error_set_errno(errcode, "pthread_cond_init");
3081 goto done;
3084 s->thread_args.commits_needed = view->nlines;
3085 s->thread_args.graph = thread_graph;
3086 s->thread_args.commits = &s->commits;
3087 s->thread_args.in_repo_path = s->in_repo_path;
3088 s->thread_args.start_id = s->start_id;
3089 s->thread_args.repo = thread_repo;
3090 s->thread_args.log_complete = 0;
3091 s->thread_args.quit = &s->quit;
3092 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3093 s->thread_args.selected_entry = &s->selected_entry;
3094 s->thread_args.searching = &view->searching;
3095 s->thread_args.search_next_done = &view->search_next_done;
3096 s->thread_args.regex = &view->regex;
3097 done:
3098 if (err)
3099 close_log_view(view);
3100 return err;
3103 static const struct got_error *
3104 show_log_view(struct tog_view *view)
3106 const struct got_error *err;
3107 struct tog_log_view_state *s = &view->state.log;
3109 if (s->thread == NULL) {
3110 int errcode = pthread_create(&s->thread, NULL, log_thread,
3111 &s->thread_args);
3112 if (errcode)
3113 return got_error_set_errno(errcode, "pthread_create");
3114 if (s->thread_args.commits_needed > 0) {
3115 err = trigger_log_thread(view, 1);
3116 if (err)
3117 return err;
3121 return draw_commits(view);
3124 static void
3125 log_move_cursor_up(struct tog_view *view, int page, int home)
3127 struct tog_log_view_state *s = &view->state.log;
3129 if (s->selected_entry->idx == 0)
3130 view->count = 0;
3131 if (s->first_displayed_entry == NULL)
3132 return;
3134 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3135 || home)
3136 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3138 if (!page && !home && s->selected > 0)
3139 --s->selected;
3140 else
3141 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3143 select_commit(s);
3144 return;
3147 static const struct got_error *
3148 log_move_cursor_down(struct tog_view *view, int page)
3150 struct tog_log_view_state *s = &view->state.log;
3151 struct commit_queue_entry *first;
3152 const struct got_error *err = NULL;
3154 first = s->first_displayed_entry;
3155 if (first == NULL) {
3156 view->count = 0;
3157 return NULL;
3160 if (s->thread_args.log_complete &&
3161 s->selected_entry->idx >= s->commits.ncommits - 1)
3162 return NULL;
3164 if (!page) {
3165 int eos = view->nlines - 2;
3167 if (view_is_hsplit_top(view))
3168 --eos; /* border consumes the last line */
3169 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3170 ++s->selected;
3171 else
3172 err = log_scroll_down(view, 1);
3173 } else if (s->thread_args.load_all) {
3174 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3175 s->selected += MIN(s->last_displayed_entry->idx -
3176 s->selected_entry->idx, page + 1);
3177 else
3178 err = log_scroll_down(view, MIN(page,
3179 s->commits.ncommits - s->selected_entry->idx - 1));
3180 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3181 } else {
3182 err = log_scroll_down(view, page);
3183 if (err)
3184 return err;
3185 if (first == s->first_displayed_entry && s->selected <
3186 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
3187 s->selected = MIN(s->commits.ncommits - 1, page);
3190 if (err)
3191 return err;
3194 * We might necessarily overshoot in horizontal
3195 * splits; if so, select the last displayed commit.
3197 s->selected = MIN(s->selected,
3198 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3200 select_commit(s);
3202 if (s->thread_args.log_complete &&
3203 s->selected_entry->idx == s->commits.ncommits - 1)
3204 view->count = 0;
3206 return NULL;
3209 static void
3210 view_get_split(struct tog_view *view, int *y, int *x)
3212 *x = 0;
3213 *y = 0;
3215 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3216 if (view->child && view->child->resized_y)
3217 *y = view->child->resized_y;
3218 else if (view->resized_y)
3219 *y = view->resized_y;
3220 else
3221 *y = view_split_begin_y(view->lines);
3222 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3223 if (view->child && view->child->resized_x)
3224 *x = view->child->resized_x;
3225 else if (view->resized_x)
3226 *x = view->resized_x;
3227 else
3228 *x = view_split_begin_x(view->begin_x);
3232 /* Split view horizontally at y and offset view->state->selected line. */
3233 static const struct got_error *
3234 view_init_hsplit(struct tog_view *view, int y)
3236 const struct got_error *err = NULL;
3238 view->nlines = y;
3239 view->ncols = COLS;
3240 err = view_resize(view);
3241 if (err)
3242 return err;
3244 err = offset_selection_down(view);
3246 return err;
3249 static const struct got_error *
3250 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3252 const struct got_error *err = NULL;
3253 struct tog_log_view_state *s = &view->state.log;
3254 struct commit_queue_entry *entry;
3255 int eos, n, nscroll;
3257 if (s->thread_args.load_all) {
3258 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3259 s->thread_args.load_all = 0;
3260 else if (s->thread_args.log_complete) {
3261 err = log_move_cursor_down(view, s->commits.ncommits);
3262 s->thread_args.load_all = 0;
3264 return err;
3267 eos = nscroll = view->nlines - 1;
3268 if (view_is_hsplit_top(view))
3269 --eos; /* border */
3271 switch (ch) {
3272 case 'q':
3273 s->quit = 1;
3274 break;
3275 case '0':
3276 view->x = 0;
3277 break;
3278 case '$':
3279 view->x = MAX(view->maxx - view->ncols / 2, 0);
3280 view->count = 0;
3281 break;
3282 case KEY_RIGHT:
3283 case 'l':
3284 if (view->x + view->ncols / 2 < view->maxx)
3285 view->x += 2; /* move two columns right */
3286 else
3287 view->count = 0;
3288 break;
3289 case KEY_LEFT:
3290 case 'h':
3291 view->x -= MIN(view->x, 2); /* move two columns back */
3292 if (view->x <= 0)
3293 view->count = 0;
3294 break;
3295 case 'k':
3296 case KEY_UP:
3297 case '<':
3298 case ',':
3299 case CTRL('p'):
3300 log_move_cursor_up(view, 0, 0);
3301 break;
3302 case 'g':
3303 case KEY_HOME:
3304 log_move_cursor_up(view, 0, 1);
3305 view->count = 0;
3306 break;
3307 case CTRL('u'):
3308 case 'u':
3309 nscroll /= 2;
3310 /* FALL THROUGH */
3311 case KEY_PPAGE:
3312 case CTRL('b'):
3313 case 'b':
3314 log_move_cursor_up(view, nscroll, 0);
3315 break;
3316 case 'j':
3317 case KEY_DOWN:
3318 case '>':
3319 case '.':
3320 case CTRL('n'):
3321 err = log_move_cursor_down(view, 0);
3322 break;
3323 case '@':
3324 s->use_committer = !s->use_committer;
3325 break;
3326 case 'G':
3327 case KEY_END: {
3328 /* We don't know yet how many commits, so we're forced to
3329 * traverse them all. */
3330 view->count = 0;
3331 if (!s->thread_args.log_complete) {
3332 s->thread_args.load_all = 1;
3333 return trigger_log_thread(view, 0);
3336 s->selected = 0;
3337 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3338 for (n = 0; n < eos; n++) {
3339 if (entry == NULL)
3340 break;
3341 s->first_displayed_entry = entry;
3342 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3344 if (n > 0)
3345 s->selected = n - 1;
3346 select_commit(s);
3347 break;
3349 case CTRL('d'):
3350 case 'd':
3351 nscroll /= 2;
3352 /* FALL THROUGH */
3353 case KEY_NPAGE:
3354 case CTRL('f'):
3355 case 'f':
3356 case ' ':
3357 err = log_move_cursor_down(view, nscroll);
3358 break;
3359 case KEY_RESIZE:
3360 if (s->selected > view->nlines - 2)
3361 s->selected = view->nlines - 2;
3362 if (s->selected > s->commits.ncommits - 1)
3363 s->selected = s->commits.ncommits - 1;
3364 select_commit(s);
3365 if (s->commits.ncommits < view->nlines - 1 &&
3366 !s->thread_args.log_complete) {
3367 s->thread_args.commits_needed += (view->nlines - 1) -
3368 s->commits.ncommits;
3369 err = trigger_log_thread(view, 1);
3371 break;
3372 case KEY_ENTER:
3373 case '\r':
3374 view->count = 0;
3375 if (s->selected_entry == NULL)
3376 break;
3377 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3378 break;
3379 case 'T':
3380 view->count = 0;
3381 if (s->selected_entry == NULL)
3382 break;
3383 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3384 break;
3385 case KEY_BACKSPACE:
3386 case CTRL('l'):
3387 case 'B':
3388 view->count = 0;
3389 if (ch == KEY_BACKSPACE &&
3390 got_path_is_root_dir(s->in_repo_path))
3391 break;
3392 err = stop_log_thread(s);
3393 if (err)
3394 return err;
3395 if (ch == KEY_BACKSPACE) {
3396 char *parent_path;
3397 err = got_path_dirname(&parent_path, s->in_repo_path);
3398 if (err)
3399 return err;
3400 free(s->in_repo_path);
3401 s->in_repo_path = parent_path;
3402 s->thread_args.in_repo_path = s->in_repo_path;
3403 } else if (ch == CTRL('l')) {
3404 struct got_object_id *start_id;
3405 err = got_repo_match_object_id(&start_id, NULL,
3406 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3407 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3408 if (err)
3409 return err;
3410 free(s->start_id);
3411 s->start_id = start_id;
3412 s->thread_args.start_id = s->start_id;
3413 } else /* 'B' */
3414 s->log_branches = !s->log_branches;
3416 if (s->thread_args.pack_fds == NULL) {
3417 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3418 if (err)
3419 return err;
3421 err = got_repo_open(&s->thread_args.repo,
3422 got_repo_get_path(s->repo), NULL,
3423 s->thread_args.pack_fds);
3424 if (err)
3425 return err;
3426 tog_free_refs();
3427 err = tog_load_refs(s->repo, 0);
3428 if (err)
3429 return err;
3430 err = got_commit_graph_open(&s->thread_args.graph,
3431 s->in_repo_path, !s->log_branches);
3432 if (err)
3433 return err;
3434 err = got_commit_graph_iter_start(s->thread_args.graph,
3435 s->start_id, s->repo, NULL, NULL);
3436 if (err)
3437 return err;
3438 free_commits(&s->commits);
3439 s->first_displayed_entry = NULL;
3440 s->last_displayed_entry = NULL;
3441 s->selected_entry = NULL;
3442 s->selected = 0;
3443 s->thread_args.log_complete = 0;
3444 s->quit = 0;
3445 s->thread_args.commits_needed = view->lines;
3446 s->matched_entry = NULL;
3447 s->search_entry = NULL;
3448 view->offset = 0;
3449 break;
3450 case 'R':
3451 view->count = 0;
3452 err = view_request_new(new_view, view, TOG_VIEW_REF);
3453 break;
3454 default:
3455 view->count = 0;
3456 break;
3459 return err;
3462 static const struct got_error *
3463 apply_unveil(const char *repo_path, const char *worktree_path)
3465 const struct got_error *error;
3467 #ifdef PROFILE
3468 if (unveil("gmon.out", "rwc") != 0)
3469 return got_error_from_errno2("unveil", "gmon.out");
3470 #endif
3471 if (repo_path && unveil(repo_path, "r") != 0)
3472 return got_error_from_errno2("unveil", repo_path);
3474 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3475 return got_error_from_errno2("unveil", worktree_path);
3477 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3478 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3480 error = got_privsep_unveil_exec_helpers();
3481 if (error != NULL)
3482 return error;
3484 if (unveil(NULL, NULL) != 0)
3485 return got_error_from_errno("unveil");
3487 return NULL;
3490 static void
3491 init_curses(void)
3494 * Override default signal handlers before starting ncurses.
3495 * This should prevent ncurses from installing its own
3496 * broken cleanup() signal handler.
3498 signal(SIGWINCH, tog_sigwinch);
3499 signal(SIGPIPE, tog_sigpipe);
3500 signal(SIGCONT, tog_sigcont);
3501 signal(SIGINT, tog_sigint);
3502 signal(SIGTERM, tog_sigterm);
3504 initscr();
3505 cbreak();
3506 halfdelay(1); /* Do fast refresh while initial view is loading. */
3507 noecho();
3508 nonl();
3509 intrflush(stdscr, FALSE);
3510 keypad(stdscr, TRUE);
3511 curs_set(0);
3512 if (getenv("TOG_COLORS") != NULL) {
3513 start_color();
3514 use_default_colors();
3518 static const struct got_error *
3519 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3520 struct got_repository *repo, struct got_worktree *worktree)
3522 const struct got_error *err = NULL;
3524 if (argc == 0) {
3525 *in_repo_path = strdup("/");
3526 if (*in_repo_path == NULL)
3527 return got_error_from_errno("strdup");
3528 return NULL;
3531 if (worktree) {
3532 const char *prefix = got_worktree_get_path_prefix(worktree);
3533 char *p;
3535 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3536 if (err)
3537 return err;
3538 if (asprintf(in_repo_path, "%s%s%s", prefix,
3539 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3540 p) == -1) {
3541 err = got_error_from_errno("asprintf");
3542 *in_repo_path = NULL;
3544 free(p);
3545 } else
3546 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3548 return err;
3551 static const struct got_error *
3552 cmd_log(int argc, char *argv[])
3554 const struct got_error *error;
3555 struct got_repository *repo = NULL;
3556 struct got_worktree *worktree = NULL;
3557 struct got_object_id *start_id = NULL;
3558 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3559 char *start_commit = NULL, *label = NULL;
3560 struct got_reference *ref = NULL;
3561 const char *head_ref_name = NULL;
3562 int ch, log_branches = 0;
3563 struct tog_view *view;
3564 int *pack_fds = NULL;
3566 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3567 switch (ch) {
3568 case 'b':
3569 log_branches = 1;
3570 break;
3571 case 'c':
3572 start_commit = optarg;
3573 break;
3574 case 'r':
3575 repo_path = realpath(optarg, NULL);
3576 if (repo_path == NULL)
3577 return got_error_from_errno2("realpath",
3578 optarg);
3579 break;
3580 default:
3581 usage_log();
3582 /* NOTREACHED */
3586 argc -= optind;
3587 argv += optind;
3589 if (argc > 1)
3590 usage_log();
3592 error = got_repo_pack_fds_open(&pack_fds);
3593 if (error != NULL)
3594 goto done;
3596 if (repo_path == NULL) {
3597 cwd = getcwd(NULL, 0);
3598 if (cwd == NULL)
3599 return got_error_from_errno("getcwd");
3600 error = got_worktree_open(&worktree, cwd);
3601 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3602 goto done;
3603 if (worktree)
3604 repo_path =
3605 strdup(got_worktree_get_repo_path(worktree));
3606 else
3607 repo_path = strdup(cwd);
3608 if (repo_path == NULL) {
3609 error = got_error_from_errno("strdup");
3610 goto done;
3614 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3615 if (error != NULL)
3616 goto done;
3618 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3619 repo, worktree);
3620 if (error)
3621 goto done;
3623 init_curses();
3625 error = apply_unveil(got_repo_get_path(repo),
3626 worktree ? got_worktree_get_root_path(worktree) : NULL);
3627 if (error)
3628 goto done;
3630 /* already loaded by tog_log_with_path()? */
3631 if (TAILQ_EMPTY(&tog_refs)) {
3632 error = tog_load_refs(repo, 0);
3633 if (error)
3634 goto done;
3637 if (start_commit == NULL) {
3638 error = got_repo_match_object_id(&start_id, &label,
3639 worktree ? got_worktree_get_head_ref_name(worktree) :
3640 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3641 if (error)
3642 goto done;
3643 head_ref_name = label;
3644 } else {
3645 error = got_ref_open(&ref, repo, start_commit, 0);
3646 if (error == NULL)
3647 head_ref_name = got_ref_get_name(ref);
3648 else if (error->code != GOT_ERR_NOT_REF)
3649 goto done;
3650 error = got_repo_match_object_id(&start_id, NULL,
3651 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3652 if (error)
3653 goto done;
3656 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3657 if (view == NULL) {
3658 error = got_error_from_errno("view_open");
3659 goto done;
3661 error = open_log_view(view, start_id, repo, head_ref_name,
3662 in_repo_path, log_branches);
3663 if (error)
3664 goto done;
3665 if (worktree) {
3666 /* Release work tree lock. */
3667 got_worktree_close(worktree);
3668 worktree = NULL;
3670 error = view_loop(view);
3671 done:
3672 free(in_repo_path);
3673 free(repo_path);
3674 free(cwd);
3675 free(start_id);
3676 free(label);
3677 if (ref)
3678 got_ref_close(ref);
3679 if (repo) {
3680 const struct got_error *close_err = got_repo_close(repo);
3681 if (error == NULL)
3682 error = close_err;
3684 if (worktree)
3685 got_worktree_close(worktree);
3686 if (pack_fds) {
3687 const struct got_error *pack_err =
3688 got_repo_pack_fds_close(pack_fds);
3689 if (error == NULL)
3690 error = pack_err;
3692 tog_free_refs();
3693 return error;
3696 __dead static void
3697 usage_diff(void)
3699 endwin();
3700 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3701 "[-w] object1 object2\n", getprogname());
3702 exit(1);
3705 static int
3706 match_line(const char *line, regex_t *regex, size_t nmatch,
3707 regmatch_t *regmatch)
3709 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3712 static struct tog_color *
3713 match_color(struct tog_colors *colors, const char *line)
3715 struct tog_color *tc = NULL;
3717 STAILQ_FOREACH(tc, colors, entry) {
3718 if (match_line(line, &tc->regex, 0, NULL))
3719 return tc;
3722 return NULL;
3725 static const struct got_error *
3726 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3727 WINDOW *window, int skipcol, regmatch_t *regmatch)
3729 const struct got_error *err = NULL;
3730 char *exstr = NULL;
3731 wchar_t *wline = NULL;
3732 int rme, rms, n, width, scrollx;
3733 int width0 = 0, width1 = 0, width2 = 0;
3734 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3736 *wtotal = 0;
3738 rms = regmatch->rm_so;
3739 rme = regmatch->rm_eo;
3741 err = expand_tab(&exstr, line);
3742 if (err)
3743 return err;
3745 /* Split the line into 3 segments, according to match offsets. */
3746 seg0 = strndup(exstr, rms);
3747 if (seg0 == NULL) {
3748 err = got_error_from_errno("strndup");
3749 goto done;
3751 seg1 = strndup(exstr + rms, rme - rms);
3752 if (seg1 == NULL) {
3753 err = got_error_from_errno("strndup");
3754 goto done;
3756 seg2 = strdup(exstr + rme);
3757 if (seg2 == NULL) {
3758 err = got_error_from_errno("strndup");
3759 goto done;
3762 /* draw up to matched token if we haven't scrolled past it */
3763 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3764 col_tab_align, 1);
3765 if (err)
3766 goto done;
3767 n = MAX(width0 - skipcol, 0);
3768 if (n) {
3769 free(wline);
3770 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3771 wlimit, col_tab_align, 1);
3772 if (err)
3773 goto done;
3774 waddwstr(window, &wline[scrollx]);
3775 wlimit -= width;
3776 *wtotal += width;
3779 if (wlimit > 0) {
3780 int i = 0, w = 0;
3781 size_t wlen;
3783 free(wline);
3784 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3785 col_tab_align, 1);
3786 if (err)
3787 goto done;
3788 wlen = wcslen(wline);
3789 while (i < wlen) {
3790 width = wcwidth(wline[i]);
3791 if (width == -1) {
3792 /* should not happen, tabs are expanded */
3793 err = got_error(GOT_ERR_RANGE);
3794 goto done;
3796 if (width0 + w + width > skipcol)
3797 break;
3798 w += width;
3799 i++;
3801 /* draw (visible part of) matched token (if scrolled into it) */
3802 if (width1 - w > 0) {
3803 wattron(window, A_STANDOUT);
3804 waddwstr(window, &wline[i]);
3805 wattroff(window, A_STANDOUT);
3806 wlimit -= (width1 - w);
3807 *wtotal += (width1 - w);
3811 if (wlimit > 0) { /* draw rest of line */
3812 free(wline);
3813 if (skipcol > width0 + width1) {
3814 err = format_line(&wline, &width2, &scrollx, seg2,
3815 skipcol - (width0 + width1), wlimit,
3816 col_tab_align, 1);
3817 if (err)
3818 goto done;
3819 waddwstr(window, &wline[scrollx]);
3820 } else {
3821 err = format_line(&wline, &width2, NULL, seg2, 0,
3822 wlimit, col_tab_align, 1);
3823 if (err)
3824 goto done;
3825 waddwstr(window, wline);
3827 *wtotal += width2;
3829 done:
3830 free(wline);
3831 free(exstr);
3832 free(seg0);
3833 free(seg1);
3834 free(seg2);
3835 return err;
3838 static const struct got_error *
3839 draw_file(struct tog_view *view, const char *header)
3841 struct tog_diff_view_state *s = &view->state.diff;
3842 regmatch_t *regmatch = &view->regmatch;
3843 const struct got_error *err;
3844 int nprinted = 0;
3845 char *line;
3846 size_t linesize = 0;
3847 ssize_t linelen;
3848 struct tog_color *tc;
3849 wchar_t *wline;
3850 int width;
3851 int max_lines = view->nlines;
3852 int nlines = s->nlines;
3853 off_t line_offset;
3855 line_offset = s->line_offsets[s->first_displayed_line - 1];
3856 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3857 return got_error_from_errno("fseek");
3859 werase(view->window);
3861 if (header) {
3862 if (asprintf(&line, "[%d/%d] %s",
3863 s->first_displayed_line - 1 + s->selected_line, nlines,
3864 header) == -1)
3865 return got_error_from_errno("asprintf");
3866 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3867 0, 0);
3868 free(line);
3869 if (err)
3870 return err;
3872 if (view_needs_focus_indication(view))
3873 wstandout(view->window);
3874 waddwstr(view->window, wline);
3875 free(wline);
3876 wline = NULL;
3877 if (view_needs_focus_indication(view))
3878 wstandend(view->window);
3879 if (width <= view->ncols - 1)
3880 waddch(view->window, '\n');
3882 if (max_lines <= 1)
3883 return NULL;
3884 max_lines--;
3887 s->eof = 0;
3888 view->maxx = 0;
3889 line = NULL;
3890 while (max_lines > 0 && nprinted < max_lines) {
3891 linelen = getline(&line, &linesize, s->f);
3892 if (linelen == -1) {
3893 if (feof(s->f)) {
3894 s->eof = 1;
3895 break;
3897 free(line);
3898 return got_ferror(s->f, GOT_ERR_IO);
3901 /* Set view->maxx based on full line length. */
3902 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3903 view->x ? 1 : 0);
3904 if (err) {
3905 free(line);
3906 return err;
3908 view->maxx = MAX(view->maxx, width);
3909 free(wline);
3910 wline = NULL;
3912 tc = match_color(&s->colors, line);
3913 if (tc)
3914 wattr_on(view->window,
3915 COLOR_PAIR(tc->colorpair), NULL);
3916 if (s->first_displayed_line + nprinted == s->matched_line &&
3917 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3918 err = add_matched_line(&width, line, view->ncols, 0,
3919 view->window, view->x, regmatch);
3920 if (err) {
3921 free(line);
3922 return err;
3924 } else {
3925 int skip;
3926 err = format_line(&wline, &width, &skip, line,
3927 view->x, view->ncols, 0, view->x ? 1 : 0);
3928 if (err) {
3929 free(line);
3930 return err;
3932 waddwstr(view->window, &wline[skip]);
3933 free(wline);
3934 wline = NULL;
3936 if (tc)
3937 wattr_off(view->window,
3938 COLOR_PAIR(tc->colorpair), NULL);
3939 if (width <= view->ncols - 1)
3940 waddch(view->window, '\n');
3941 nprinted++;
3943 free(line);
3944 if (nprinted >= 1)
3945 s->last_displayed_line = s->first_displayed_line +
3946 (nprinted - 1);
3947 else
3948 s->last_displayed_line = s->first_displayed_line;
3950 view_border(view);
3952 if (s->eof) {
3953 while (nprinted < view->nlines) {
3954 waddch(view->window, '\n');
3955 nprinted++;
3958 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3959 view->ncols, 0, 0);
3960 if (err) {
3961 return err;
3964 wstandout(view->window);
3965 waddwstr(view->window, wline);
3966 free(wline);
3967 wline = NULL;
3968 wstandend(view->window);
3971 return NULL;
3974 static char *
3975 get_datestr(time_t *time, char *datebuf)
3977 struct tm mytm, *tm;
3978 char *p, *s;
3980 tm = gmtime_r(time, &mytm);
3981 if (tm == NULL)
3982 return NULL;
3983 s = asctime_r(tm, datebuf);
3984 if (s == NULL)
3985 return NULL;
3986 p = strchr(s, '\n');
3987 if (p)
3988 *p = '\0';
3989 return s;
3992 static const struct got_error *
3993 get_changed_paths(struct got_pathlist_head *paths,
3994 struct got_commit_object *commit, struct got_repository *repo)
3996 const struct got_error *err = NULL;
3997 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3998 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3999 struct got_object_qid *qid;
4001 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4002 if (qid != NULL) {
4003 struct got_commit_object *pcommit;
4004 err = got_object_open_as_commit(&pcommit, repo,
4005 &qid->id);
4006 if (err)
4007 return err;
4009 tree_id1 = got_object_id_dup(
4010 got_object_commit_get_tree_id(pcommit));
4011 if (tree_id1 == NULL) {
4012 got_object_commit_close(pcommit);
4013 return got_error_from_errno("got_object_id_dup");
4015 got_object_commit_close(pcommit);
4019 if (tree_id1) {
4020 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4021 if (err)
4022 goto done;
4025 tree_id2 = got_object_commit_get_tree_id(commit);
4026 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4027 if (err)
4028 goto done;
4030 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4031 got_diff_tree_collect_changed_paths, paths, 0);
4032 done:
4033 if (tree1)
4034 got_object_tree_close(tree1);
4035 if (tree2)
4036 got_object_tree_close(tree2);
4037 free(tree_id1);
4038 return err;
4041 static const struct got_error *
4042 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
4044 off_t *p;
4046 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
4047 if (p == NULL)
4048 return got_error_from_errno("reallocarray");
4049 *line_offsets = p;
4050 (*line_offsets)[*nlines] = off;
4051 (*nlines)++;
4052 return NULL;
4055 static const struct got_error *
4056 write_commit_info(off_t **line_offsets, size_t *nlines,
4057 struct got_object_id *commit_id, struct got_reflist_head *refs,
4058 struct got_repository *repo, FILE *outfile)
4060 const struct got_error *err = NULL;
4061 char datebuf[26], *datestr;
4062 struct got_commit_object *commit;
4063 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4064 time_t committer_time;
4065 const char *author, *committer;
4066 char *refs_str = NULL;
4067 struct got_pathlist_head changed_paths;
4068 struct got_pathlist_entry *pe;
4069 off_t outoff = 0;
4070 int n;
4072 TAILQ_INIT(&changed_paths);
4074 if (refs) {
4075 err = build_refs_str(&refs_str, refs, commit_id, repo);
4076 if (err)
4077 return err;
4080 err = got_object_open_as_commit(&commit, repo, commit_id);
4081 if (err)
4082 return err;
4084 err = got_object_id_str(&id_str, commit_id);
4085 if (err) {
4086 err = got_error_from_errno("got_object_id_str");
4087 goto done;
4090 err = add_line_offset(line_offsets, nlines, 0);
4091 if (err)
4092 goto done;
4094 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4095 refs_str ? refs_str : "", refs_str ? ")" : "");
4096 if (n < 0) {
4097 err = got_error_from_errno("fprintf");
4098 goto done;
4100 outoff += n;
4101 err = add_line_offset(line_offsets, nlines, outoff);
4102 if (err)
4103 goto done;
4105 n = fprintf(outfile, "from: %s\n",
4106 got_object_commit_get_author(commit));
4107 if (n < 0) {
4108 err = got_error_from_errno("fprintf");
4109 goto done;
4111 outoff += n;
4112 err = add_line_offset(line_offsets, nlines, outoff);
4113 if (err)
4114 goto done;
4116 committer_time = got_object_commit_get_committer_time(commit);
4117 datestr = get_datestr(&committer_time, datebuf);
4118 if (datestr) {
4119 n = fprintf(outfile, "date: %s UTC\n", datestr);
4120 if (n < 0) {
4121 err = got_error_from_errno("fprintf");
4122 goto done;
4124 outoff += n;
4125 err = add_line_offset(line_offsets, nlines, outoff);
4126 if (err)
4127 goto done;
4129 author = got_object_commit_get_author(commit);
4130 committer = got_object_commit_get_committer(commit);
4131 if (strcmp(author, committer) != 0) {
4132 n = fprintf(outfile, "via: %s\n", committer);
4133 if (n < 0) {
4134 err = got_error_from_errno("fprintf");
4135 goto done;
4137 outoff += n;
4138 err = add_line_offset(line_offsets, nlines, outoff);
4139 if (err)
4140 goto done;
4142 if (got_object_commit_get_nparents(commit) > 1) {
4143 const struct got_object_id_queue *parent_ids;
4144 struct got_object_qid *qid;
4145 int pn = 1;
4146 parent_ids = got_object_commit_get_parent_ids(commit);
4147 STAILQ_FOREACH(qid, parent_ids, entry) {
4148 err = got_object_id_str(&id_str, &qid->id);
4149 if (err)
4150 goto done;
4151 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4152 if (n < 0) {
4153 err = got_error_from_errno("fprintf");
4154 goto done;
4156 outoff += n;
4157 err = add_line_offset(line_offsets, nlines, outoff);
4158 if (err)
4159 goto done;
4160 free(id_str);
4161 id_str = NULL;
4165 err = got_object_commit_get_logmsg(&logmsg, commit);
4166 if (err)
4167 goto done;
4168 s = logmsg;
4169 while ((line = strsep(&s, "\n")) != NULL) {
4170 n = fprintf(outfile, "%s\n", line);
4171 if (n < 0) {
4172 err = got_error_from_errno("fprintf");
4173 goto done;
4175 outoff += n;
4176 err = add_line_offset(line_offsets, nlines, outoff);
4177 if (err)
4178 goto done;
4181 err = get_changed_paths(&changed_paths, commit, repo);
4182 if (err)
4183 goto done;
4184 TAILQ_FOREACH(pe, &changed_paths, entry) {
4185 struct got_diff_changed_path *cp = pe->data;
4186 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4187 if (n < 0) {
4188 err = got_error_from_errno("fprintf");
4189 goto done;
4191 outoff += n;
4192 err = add_line_offset(line_offsets, nlines, outoff);
4193 if (err)
4194 goto done;
4195 free((char *)pe->path);
4196 free(pe->data);
4199 fputc('\n', outfile);
4200 outoff++;
4201 err = add_line_offset(line_offsets, nlines, outoff);
4202 done:
4203 got_pathlist_free(&changed_paths);
4204 free(id_str);
4205 free(logmsg);
4206 free(refs_str);
4207 got_object_commit_close(commit);
4208 if (err) {
4209 free(*line_offsets);
4210 *line_offsets = NULL;
4211 *nlines = 0;
4213 return err;
4216 static const struct got_error *
4217 create_diff(struct tog_diff_view_state *s)
4219 const struct got_error *err = NULL;
4220 FILE *f = NULL;
4221 int obj_type;
4223 free(s->line_offsets);
4224 s->line_offsets = malloc(sizeof(off_t));
4225 if (s->line_offsets == NULL)
4226 return got_error_from_errno("malloc");
4227 s->nlines = 0;
4229 f = got_opentemp();
4230 if (f == NULL) {
4231 err = got_error_from_errno("got_opentemp");
4232 goto done;
4234 if (s->f && fclose(s->f) == EOF) {
4235 err = got_error_from_errno("fclose");
4236 goto done;
4238 s->f = f;
4240 if (s->id1)
4241 err = got_object_get_type(&obj_type, s->repo, s->id1);
4242 else
4243 err = got_object_get_type(&obj_type, s->repo, s->id2);
4244 if (err)
4245 goto done;
4247 switch (obj_type) {
4248 case GOT_OBJ_TYPE_BLOB:
4249 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
4250 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4251 s->label1, s->label2, tog_diff_algo, s->diff_context,
4252 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4253 break;
4254 case GOT_OBJ_TYPE_TREE:
4255 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
4256 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4257 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4258 s->force_text_diff, s->repo, s->f);
4259 break;
4260 case GOT_OBJ_TYPE_COMMIT: {
4261 const struct got_object_id_queue *parent_ids;
4262 struct got_object_qid *pid;
4263 struct got_commit_object *commit2;
4264 struct got_reflist_head *refs;
4266 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4267 if (err)
4268 goto done;
4269 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4270 /* Show commit info if we're diffing to a parent/root commit. */
4271 if (s->id1 == NULL) {
4272 err = write_commit_info(&s->line_offsets, &s->nlines,
4273 s->id2, refs, s->repo, s->f);
4274 if (err)
4275 goto done;
4276 } else {
4277 parent_ids = got_object_commit_get_parent_ids(commit2);
4278 STAILQ_FOREACH(pid, parent_ids, entry) {
4279 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4280 err = write_commit_info(
4281 &s->line_offsets, &s->nlines,
4282 s->id2, refs, s->repo, s->f);
4283 if (err)
4284 goto done;
4285 break;
4289 got_object_commit_close(commit2);
4291 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4292 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4293 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4294 s->force_text_diff, s->repo, s->f);
4295 break;
4297 default:
4298 err = got_error(GOT_ERR_OBJ_TYPE);
4299 break;
4301 if (err)
4302 goto done;
4303 done:
4304 if (s->f && fflush(s->f) != 0 && err == NULL)
4305 err = got_error_from_errno("fflush");
4306 return err;
4309 static void
4310 diff_view_indicate_progress(struct tog_view *view)
4312 mvwaddstr(view->window, 0, 0, "diffing...");
4313 update_panels();
4314 doupdate();
4317 static const struct got_error *
4318 search_start_diff_view(struct tog_view *view)
4320 struct tog_diff_view_state *s = &view->state.diff;
4322 s->matched_line = 0;
4323 return NULL;
4326 static const struct got_error *
4327 search_next_diff_view(struct tog_view *view)
4329 struct tog_diff_view_state *s = &view->state.diff;
4330 const struct got_error *err = NULL;
4331 int lineno;
4332 char *line = NULL;
4333 size_t linesize = 0;
4334 ssize_t linelen;
4336 if (!view->searching) {
4337 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4338 return NULL;
4341 if (s->matched_line) {
4342 if (view->searching == TOG_SEARCH_FORWARD)
4343 lineno = s->matched_line + 1;
4344 else
4345 lineno = s->matched_line - 1;
4346 } else
4347 lineno = s->first_displayed_line;
4349 while (1) {
4350 off_t offset;
4352 if (lineno <= 0 || lineno > s->nlines) {
4353 if (s->matched_line == 0) {
4354 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4355 break;
4358 if (view->searching == TOG_SEARCH_FORWARD)
4359 lineno = 1;
4360 else
4361 lineno = s->nlines;
4364 offset = s->line_offsets[lineno - 1];
4365 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4366 free(line);
4367 return got_error_from_errno("fseeko");
4369 linelen = getline(&line, &linesize, s->f);
4370 if (linelen != -1) {
4371 char *exstr;
4372 err = expand_tab(&exstr, line);
4373 if (err)
4374 break;
4375 if (match_line(exstr, &view->regex, 1,
4376 &view->regmatch)) {
4377 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4378 s->matched_line = lineno;
4379 free(exstr);
4380 break;
4382 free(exstr);
4384 if (view->searching == TOG_SEARCH_FORWARD)
4385 lineno++;
4386 else
4387 lineno--;
4389 free(line);
4391 if (s->matched_line) {
4392 s->first_displayed_line = s->matched_line;
4393 s->selected_line = 1;
4396 return err;
4399 static const struct got_error *
4400 close_diff_view(struct tog_view *view)
4402 const struct got_error *err = NULL;
4403 struct tog_diff_view_state *s = &view->state.diff;
4405 free(s->id1);
4406 s->id1 = NULL;
4407 free(s->id2);
4408 s->id2 = NULL;
4409 if (s->f && fclose(s->f) == EOF)
4410 err = got_error_from_errno("fclose");
4411 s->f = NULL;
4412 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4413 err = got_error_from_errno("fclose");
4414 s->f1 = NULL;
4415 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4416 err = got_error_from_errno("fclose");
4417 s->f2 = NULL;
4418 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4419 err = got_error_from_errno("close");
4420 s->fd1 = -1;
4421 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4422 err = got_error_from_errno("close");
4423 s->fd2 = -1;
4424 free_colors(&s->colors);
4425 free(s->line_offsets);
4426 s->line_offsets = NULL;
4427 s->nlines = 0;
4428 return err;
4431 static const struct got_error *
4432 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4433 struct got_object_id *id2, const char *label1, const char *label2,
4434 int diff_context, int ignore_whitespace, int force_text_diff,
4435 struct tog_view *parent_view, struct got_repository *repo)
4437 const struct got_error *err;
4438 struct tog_diff_view_state *s = &view->state.diff;
4440 memset(s, 0, sizeof(*s));
4441 s->fd1 = -1;
4442 s->fd2 = -1;
4444 if (id1 != NULL && id2 != NULL) {
4445 int type1, type2;
4446 err = got_object_get_type(&type1, repo, id1);
4447 if (err)
4448 return err;
4449 err = got_object_get_type(&type2, repo, id2);
4450 if (err)
4451 return err;
4453 if (type1 != type2)
4454 return got_error(GOT_ERR_OBJ_TYPE);
4456 s->first_displayed_line = 1;
4457 s->last_displayed_line = view->nlines;
4458 s->selected_line = 1;
4459 s->repo = repo;
4460 s->id1 = id1;
4461 s->id2 = id2;
4462 s->label1 = label1;
4463 s->label2 = label2;
4465 if (id1) {
4466 s->id1 = got_object_id_dup(id1);
4467 if (s->id1 == NULL)
4468 return got_error_from_errno("got_object_id_dup");
4469 } else
4470 s->id1 = NULL;
4472 s->id2 = got_object_id_dup(id2);
4473 if (s->id2 == NULL) {
4474 err = got_error_from_errno("got_object_id_dup");
4475 goto done;
4478 s->f1 = got_opentemp();
4479 if (s->f1 == NULL) {
4480 err = got_error_from_errno("got_opentemp");
4481 goto done;
4484 s->f2 = got_opentemp();
4485 if (s->f2 == NULL) {
4486 err = got_error_from_errno("got_opentemp");
4487 goto done;
4490 s->fd1 = got_opentempfd();
4491 if (s->fd1 == -1) {
4492 err = got_error_from_errno("got_opentempfd");
4493 goto done;
4496 s->fd2 = got_opentempfd();
4497 if (s->fd2 == -1) {
4498 err = got_error_from_errno("got_opentempfd");
4499 goto done;
4502 s->first_displayed_line = 1;
4503 s->last_displayed_line = view->nlines;
4504 s->diff_context = diff_context;
4505 s->ignore_whitespace = ignore_whitespace;
4506 s->force_text_diff = force_text_diff;
4507 s->parent_view = parent_view;
4508 s->repo = repo;
4510 STAILQ_INIT(&s->colors);
4511 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4512 err = add_color(&s->colors,
4513 "^-", TOG_COLOR_DIFF_MINUS,
4514 get_color_value("TOG_COLOR_DIFF_MINUS"));
4515 if (err)
4516 goto done;
4517 err = add_color(&s->colors, "^\\+",
4518 TOG_COLOR_DIFF_PLUS,
4519 get_color_value("TOG_COLOR_DIFF_PLUS"));
4520 if (err)
4521 goto done;
4522 err = add_color(&s->colors,
4523 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4524 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4525 if (err)
4526 goto done;
4528 err = add_color(&s->colors,
4529 "^(commit [0-9a-f]|parent [0-9]|"
4530 "(blob|file|tree|commit) [-+] |"
4531 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4532 get_color_value("TOG_COLOR_DIFF_META"));
4533 if (err)
4534 goto done;
4536 err = add_color(&s->colors,
4537 "^(from|via): ", TOG_COLOR_AUTHOR,
4538 get_color_value("TOG_COLOR_AUTHOR"));
4539 if (err)
4540 goto done;
4542 err = add_color(&s->colors,
4543 "^date: ", TOG_COLOR_DATE,
4544 get_color_value("TOG_COLOR_DATE"));
4545 if (err)
4546 goto done;
4549 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4550 view_is_splitscreen(view))
4551 show_log_view(parent_view); /* draw border */
4552 diff_view_indicate_progress(view);
4554 err = create_diff(s);
4556 view->show = show_diff_view;
4557 view->input = input_diff_view;
4558 view->reset = reset_diff_view;
4559 view->close = close_diff_view;
4560 view->search_start = search_start_diff_view;
4561 view->search_next = search_next_diff_view;
4562 done:
4563 if (err)
4564 close_diff_view(view);
4565 return err;
4568 static const struct got_error *
4569 show_diff_view(struct tog_view *view)
4571 const struct got_error *err;
4572 struct tog_diff_view_state *s = &view->state.diff;
4573 char *id_str1 = NULL, *id_str2, *header;
4574 const char *label1, *label2;
4576 if (s->id1) {
4577 err = got_object_id_str(&id_str1, s->id1);
4578 if (err)
4579 return err;
4580 label1 = s->label1 ? : id_str1;
4581 } else
4582 label1 = "/dev/null";
4584 err = got_object_id_str(&id_str2, s->id2);
4585 if (err)
4586 return err;
4587 label2 = s->label2 ? : id_str2;
4589 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4590 err = got_error_from_errno("asprintf");
4591 free(id_str1);
4592 free(id_str2);
4593 return err;
4595 free(id_str1);
4596 free(id_str2);
4598 err = draw_file(view, header);
4599 free(header);
4600 return err;
4603 static const struct got_error *
4604 set_selected_commit(struct tog_diff_view_state *s,
4605 struct commit_queue_entry *entry)
4607 const struct got_error *err;
4608 const struct got_object_id_queue *parent_ids;
4609 struct got_commit_object *selected_commit;
4610 struct got_object_qid *pid;
4612 free(s->id2);
4613 s->id2 = got_object_id_dup(entry->id);
4614 if (s->id2 == NULL)
4615 return got_error_from_errno("got_object_id_dup");
4617 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4618 if (err)
4619 return err;
4620 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4621 free(s->id1);
4622 pid = STAILQ_FIRST(parent_ids);
4623 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4624 got_object_commit_close(selected_commit);
4625 return NULL;
4628 static const struct got_error *
4629 reset_diff_view(struct tog_view *view)
4631 struct tog_diff_view_state *s = &view->state.diff;
4633 view->count = 0;
4634 wclear(view->window);
4635 s->first_displayed_line = 1;
4636 s->last_displayed_line = view->nlines;
4637 s->matched_line = 0;
4638 diff_view_indicate_progress(view);
4639 return create_diff(s);
4642 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4643 int, int, int);
4644 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4645 int, int);
4647 static const struct got_error *
4648 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4650 const struct got_error *err = NULL;
4651 struct tog_diff_view_state *s = &view->state.diff;
4652 struct tog_log_view_state *ls;
4653 struct commit_queue_entry *old_selected_entry;
4654 char *line = NULL;
4655 size_t linesize = 0;
4656 ssize_t linelen;
4657 int i, nscroll = view->nlines - 1, up = 0;
4659 switch (ch) {
4660 case '0':
4661 view->x = 0;
4662 break;
4663 case '$':
4664 view->x = MAX(view->maxx - view->ncols / 3, 0);
4665 view->count = 0;
4666 break;
4667 case KEY_RIGHT:
4668 case 'l':
4669 if (view->x + view->ncols / 3 < view->maxx)
4670 view->x += 2; /* move two columns right */
4671 else
4672 view->count = 0;
4673 break;
4674 case KEY_LEFT:
4675 case 'h':
4676 view->x -= MIN(view->x, 2); /* move two columns back */
4677 if (view->x <= 0)
4678 view->count = 0;
4679 break;
4680 case 'a':
4681 case 'w':
4682 if (ch == 'a')
4683 s->force_text_diff = !s->force_text_diff;
4684 if (ch == 'w')
4685 s->ignore_whitespace = !s->ignore_whitespace;
4686 err = reset_diff_view(view);
4687 break;
4688 case 'g':
4689 case KEY_HOME:
4690 s->first_displayed_line = 1;
4691 view->count = 0;
4692 break;
4693 case 'G':
4694 case KEY_END:
4695 view->count = 0;
4696 if (s->eof)
4697 break;
4699 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4700 s->eof = 1;
4701 break;
4702 case 'k':
4703 case KEY_UP:
4704 case CTRL('p'):
4705 if (s->first_displayed_line > 1)
4706 s->first_displayed_line--;
4707 else
4708 view->count = 0;
4709 break;
4710 case CTRL('u'):
4711 case 'u':
4712 nscroll /= 2;
4713 /* FALL THROUGH */
4714 case KEY_PPAGE:
4715 case CTRL('b'):
4716 case 'b':
4717 if (s->first_displayed_line == 1) {
4718 view->count = 0;
4719 break;
4721 i = 0;
4722 while (i++ < nscroll && s->first_displayed_line > 1)
4723 s->first_displayed_line--;
4724 break;
4725 case 'j':
4726 case KEY_DOWN:
4727 case CTRL('n'):
4728 if (!s->eof)
4729 s->first_displayed_line++;
4730 else
4731 view->count = 0;
4732 break;
4733 case CTRL('d'):
4734 case 'd':
4735 nscroll /= 2;
4736 /* FALL THROUGH */
4737 case KEY_NPAGE:
4738 case CTRL('f'):
4739 case 'f':
4740 case ' ':
4741 if (s->eof) {
4742 view->count = 0;
4743 break;
4745 i = 0;
4746 while (!s->eof && i++ < nscroll) {
4747 linelen = getline(&line, &linesize, s->f);
4748 s->first_displayed_line++;
4749 if (linelen == -1) {
4750 if (feof(s->f)) {
4751 s->eof = 1;
4752 } else
4753 err = got_ferror(s->f, GOT_ERR_IO);
4754 break;
4757 free(line);
4758 break;
4759 case '[':
4760 if (s->diff_context > 0) {
4761 s->diff_context--;
4762 s->matched_line = 0;
4763 diff_view_indicate_progress(view);
4764 err = create_diff(s);
4765 if (s->first_displayed_line + view->nlines - 1 >
4766 s->nlines) {
4767 s->first_displayed_line = 1;
4768 s->last_displayed_line = view->nlines;
4770 } else
4771 view->count = 0;
4772 break;
4773 case ']':
4774 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4775 s->diff_context++;
4776 s->matched_line = 0;
4777 diff_view_indicate_progress(view);
4778 err = create_diff(s);
4779 } else
4780 view->count = 0;
4781 break;
4782 case '<':
4783 case ',':
4784 case 'K':
4785 up = 1;
4786 /* FALL THROUGH */
4787 case '>':
4788 case '.':
4789 case 'J':
4790 if (s->parent_view == NULL) {
4791 view->count = 0;
4792 break;
4794 s->parent_view->count = view->count;
4796 if (s->parent_view->type == TOG_VIEW_LOG) {
4797 ls = &s->parent_view->state.log;
4798 old_selected_entry = ls->selected_entry;
4800 err = input_log_view(NULL, s->parent_view,
4801 up ? KEY_UP : KEY_DOWN);
4802 if (err)
4803 break;
4804 view->count = s->parent_view->count;
4806 if (old_selected_entry == ls->selected_entry)
4807 break;
4809 err = set_selected_commit(s, ls->selected_entry);
4810 if (err)
4811 break;
4812 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4813 struct tog_blame_view_state *bs;
4814 struct got_object_id *id, *prev_id;
4816 bs = &s->parent_view->state.blame;
4817 prev_id = get_annotation_for_line(bs->blame.lines,
4818 bs->blame.nlines, bs->last_diffed_line);
4820 err = input_blame_view(&view, s->parent_view,
4821 up ? KEY_UP : KEY_DOWN);
4822 if (err)
4823 break;
4824 view->count = s->parent_view->count;
4826 if (prev_id == NULL)
4827 break;
4828 id = get_selected_commit_id(bs->blame.lines,
4829 bs->blame.nlines, bs->first_displayed_line,
4830 bs->selected_line);
4831 if (id == NULL)
4832 break;
4834 if (!got_object_id_cmp(prev_id, id))
4835 break;
4837 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
4838 if (err)
4839 break;
4841 s->first_displayed_line = 1;
4842 s->last_displayed_line = view->nlines;
4843 s->matched_line = 0;
4844 view->x = 0;
4846 diff_view_indicate_progress(view);
4847 err = create_diff(s);
4848 break;
4849 default:
4850 view->count = 0;
4851 break;
4854 return err;
4857 static const struct got_error *
4858 cmd_diff(int argc, char *argv[])
4860 const struct got_error *error = NULL;
4861 struct got_repository *repo = NULL;
4862 struct got_worktree *worktree = NULL;
4863 struct got_object_id *id1 = NULL, *id2 = NULL;
4864 char *repo_path = NULL, *cwd = NULL;
4865 char *id_str1 = NULL, *id_str2 = NULL;
4866 char *label1 = NULL, *label2 = NULL;
4867 int diff_context = 3, ignore_whitespace = 0;
4868 int ch, force_text_diff = 0;
4869 const char *errstr;
4870 struct tog_view *view;
4871 int *pack_fds = NULL;
4873 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4874 switch (ch) {
4875 case 'a':
4876 force_text_diff = 1;
4877 break;
4878 case 'C':
4879 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4880 &errstr);
4881 if (errstr != NULL)
4882 errx(1, "number of context lines is %s: %s",
4883 errstr, errstr);
4884 break;
4885 case 'r':
4886 repo_path = realpath(optarg, NULL);
4887 if (repo_path == NULL)
4888 return got_error_from_errno2("realpath",
4889 optarg);
4890 got_path_strip_trailing_slashes(repo_path);
4891 break;
4892 case 'w':
4893 ignore_whitespace = 1;
4894 break;
4895 default:
4896 usage_diff();
4897 /* NOTREACHED */
4901 argc -= optind;
4902 argv += optind;
4904 if (argc == 0) {
4905 usage_diff(); /* TODO show local worktree changes */
4906 } else if (argc == 2) {
4907 id_str1 = argv[0];
4908 id_str2 = argv[1];
4909 } else
4910 usage_diff();
4912 error = got_repo_pack_fds_open(&pack_fds);
4913 if (error)
4914 goto done;
4916 if (repo_path == NULL) {
4917 cwd = getcwd(NULL, 0);
4918 if (cwd == NULL)
4919 return got_error_from_errno("getcwd");
4920 error = got_worktree_open(&worktree, cwd);
4921 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4922 goto done;
4923 if (worktree)
4924 repo_path =
4925 strdup(got_worktree_get_repo_path(worktree));
4926 else
4927 repo_path = strdup(cwd);
4928 if (repo_path == NULL) {
4929 error = got_error_from_errno("strdup");
4930 goto done;
4934 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4935 if (error)
4936 goto done;
4938 init_curses();
4940 error = apply_unveil(got_repo_get_path(repo), NULL);
4941 if (error)
4942 goto done;
4944 error = tog_load_refs(repo, 0);
4945 if (error)
4946 goto done;
4948 error = got_repo_match_object_id(&id1, &label1, id_str1,
4949 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4950 if (error)
4951 goto done;
4953 error = got_repo_match_object_id(&id2, &label2, id_str2,
4954 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4955 if (error)
4956 goto done;
4958 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4959 if (view == NULL) {
4960 error = got_error_from_errno("view_open");
4961 goto done;
4963 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4964 ignore_whitespace, force_text_diff, NULL, repo);
4965 if (error)
4966 goto done;
4967 error = view_loop(view);
4968 done:
4969 free(label1);
4970 free(label2);
4971 free(repo_path);
4972 free(cwd);
4973 if (repo) {
4974 const struct got_error *close_err = got_repo_close(repo);
4975 if (error == NULL)
4976 error = close_err;
4978 if (worktree)
4979 got_worktree_close(worktree);
4980 if (pack_fds) {
4981 const struct got_error *pack_err =
4982 got_repo_pack_fds_close(pack_fds);
4983 if (error == NULL)
4984 error = pack_err;
4986 tog_free_refs();
4987 return error;
4990 __dead static void
4991 usage_blame(void)
4993 endwin();
4994 fprintf(stderr,
4995 "usage: %s blame [-c commit] [-r repository-path] path\n",
4996 getprogname());
4997 exit(1);
5000 struct tog_blame_line {
5001 int annotated;
5002 struct got_object_id *id;
5005 static const struct got_error *
5006 draw_blame(struct tog_view *view)
5008 struct tog_blame_view_state *s = &view->state.blame;
5009 struct tog_blame *blame = &s->blame;
5010 regmatch_t *regmatch = &view->regmatch;
5011 const struct got_error *err;
5012 int lineno = 0, nprinted = 0;
5013 char *line = NULL;
5014 size_t linesize = 0;
5015 ssize_t linelen;
5016 wchar_t *wline;
5017 int width;
5018 struct tog_blame_line *blame_line;
5019 struct got_object_id *prev_id = NULL;
5020 char *id_str;
5021 struct tog_color *tc;
5023 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5024 if (err)
5025 return err;
5027 rewind(blame->f);
5028 werase(view->window);
5030 if (asprintf(&line, "commit %s", id_str) == -1) {
5031 err = got_error_from_errno("asprintf");
5032 free(id_str);
5033 return err;
5036 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5037 free(line);
5038 line = NULL;
5039 if (err)
5040 return err;
5041 if (view_needs_focus_indication(view))
5042 wstandout(view->window);
5043 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5044 if (tc)
5045 wattr_on(view->window,
5046 COLOR_PAIR(tc->colorpair), NULL);
5047 waddwstr(view->window, wline);
5048 if (tc)
5049 wattr_off(view->window,
5050 COLOR_PAIR(tc->colorpair), NULL);
5051 if (view_needs_focus_indication(view))
5052 wstandend(view->window);
5053 free(wline);
5054 wline = NULL;
5055 if (width < view->ncols - 1)
5056 waddch(view->window, '\n');
5058 if (asprintf(&line, "[%d/%d] %s%s",
5059 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5060 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5061 free(id_str);
5062 return got_error_from_errno("asprintf");
5064 free(id_str);
5065 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5066 free(line);
5067 line = NULL;
5068 if (err)
5069 return err;
5070 waddwstr(view->window, wline);
5071 free(wline);
5072 wline = NULL;
5073 if (width < view->ncols - 1)
5074 waddch(view->window, '\n');
5076 s->eof = 0;
5077 view->maxx = 0;
5078 while (nprinted < view->nlines - 2) {
5079 linelen = getline(&line, &linesize, blame->f);
5080 if (linelen == -1) {
5081 if (feof(blame->f)) {
5082 s->eof = 1;
5083 break;
5085 free(line);
5086 return got_ferror(blame->f, GOT_ERR_IO);
5088 if (++lineno < s->first_displayed_line)
5089 continue;
5091 /* Set view->maxx based on full line length. */
5092 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5093 if (err) {
5094 free(line);
5095 return err;
5097 free(wline);
5098 wline = NULL;
5099 view->maxx = MAX(view->maxx, width);
5101 if (nprinted == s->selected_line - 1)
5102 wstandout(view->window);
5104 if (blame->nlines > 0) {
5105 blame_line = &blame->lines[lineno - 1];
5106 if (blame_line->annotated && prev_id &&
5107 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5108 !(nprinted == s->selected_line - 1)) {
5109 waddstr(view->window, " ");
5110 } else if (blame_line->annotated) {
5111 char *id_str;
5112 err = got_object_id_str(&id_str,
5113 blame_line->id);
5114 if (err) {
5115 free(line);
5116 return err;
5118 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5119 if (tc)
5120 wattr_on(view->window,
5121 COLOR_PAIR(tc->colorpair), NULL);
5122 wprintw(view->window, "%.8s", id_str);
5123 if (tc)
5124 wattr_off(view->window,
5125 COLOR_PAIR(tc->colorpair), NULL);
5126 free(id_str);
5127 prev_id = blame_line->id;
5128 } else {
5129 waddstr(view->window, "........");
5130 prev_id = NULL;
5132 } else {
5133 waddstr(view->window, "........");
5134 prev_id = NULL;
5137 if (nprinted == s->selected_line - 1)
5138 wstandend(view->window);
5139 waddstr(view->window, " ");
5141 if (view->ncols <= 9) {
5142 width = 9;
5143 } else if (s->first_displayed_line + nprinted ==
5144 s->matched_line &&
5145 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5146 err = add_matched_line(&width, line, view->ncols - 9, 9,
5147 view->window, view->x, regmatch);
5148 if (err) {
5149 free(line);
5150 return err;
5152 width += 9;
5153 } else {
5154 int skip;
5155 err = format_line(&wline, &width, &skip, line,
5156 view->x, view->ncols - 9, 9, 1);
5157 if (err) {
5158 free(line);
5159 return err;
5161 waddwstr(view->window, &wline[skip]);
5162 width += 9;
5163 free(wline);
5164 wline = NULL;
5167 if (width <= view->ncols - 1)
5168 waddch(view->window, '\n');
5169 if (++nprinted == 1)
5170 s->first_displayed_line = lineno;
5172 free(line);
5173 s->last_displayed_line = lineno;
5175 view_border(view);
5177 return NULL;
5180 static const struct got_error *
5181 blame_cb(void *arg, int nlines, int lineno,
5182 struct got_commit_object *commit, struct got_object_id *id)
5184 const struct got_error *err = NULL;
5185 struct tog_blame_cb_args *a = arg;
5186 struct tog_blame_line *line;
5187 int errcode;
5189 if (nlines != a->nlines ||
5190 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5191 return got_error(GOT_ERR_RANGE);
5193 errcode = pthread_mutex_lock(&tog_mutex);
5194 if (errcode)
5195 return got_error_set_errno(errcode, "pthread_mutex_lock");
5197 if (*a->quit) { /* user has quit the blame view */
5198 err = got_error(GOT_ERR_ITER_COMPLETED);
5199 goto done;
5202 if (lineno == -1)
5203 goto done; /* no change in this commit */
5205 line = &a->lines[lineno - 1];
5206 if (line->annotated)
5207 goto done;
5209 line->id = got_object_id_dup(id);
5210 if (line->id == NULL) {
5211 err = got_error_from_errno("got_object_id_dup");
5212 goto done;
5214 line->annotated = 1;
5215 done:
5216 errcode = pthread_mutex_unlock(&tog_mutex);
5217 if (errcode)
5218 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5219 return err;
5222 static void *
5223 blame_thread(void *arg)
5225 const struct got_error *err, *close_err;
5226 struct tog_blame_thread_args *ta = arg;
5227 struct tog_blame_cb_args *a = ta->cb_args;
5228 int errcode, fd1 = -1, fd2 = -1;
5229 FILE *f1 = NULL, *f2 = NULL;
5231 fd1 = got_opentempfd();
5232 if (fd1 == -1)
5233 return (void *)got_error_from_errno("got_opentempfd");
5235 fd2 = got_opentempfd();
5236 if (fd2 == -1) {
5237 err = got_error_from_errno("got_opentempfd");
5238 goto done;
5241 f1 = got_opentemp();
5242 if (f1 == NULL) {
5243 err = (void *)got_error_from_errno("got_opentemp");
5244 goto done;
5246 f2 = got_opentemp();
5247 if (f2 == NULL) {
5248 err = (void *)got_error_from_errno("got_opentemp");
5249 goto done;
5252 err = block_signals_used_by_main_thread();
5253 if (err)
5254 goto done;
5256 err = got_blame(ta->path, a->commit_id, ta->repo,
5257 tog_diff_algo, blame_cb, ta->cb_args,
5258 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5259 if (err && err->code == GOT_ERR_CANCELLED)
5260 err = NULL;
5262 errcode = pthread_mutex_lock(&tog_mutex);
5263 if (errcode) {
5264 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5265 goto done;
5268 close_err = got_repo_close(ta->repo);
5269 if (err == NULL)
5270 err = close_err;
5271 ta->repo = NULL;
5272 *ta->complete = 1;
5274 errcode = pthread_mutex_unlock(&tog_mutex);
5275 if (errcode && err == NULL)
5276 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5278 done:
5279 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5280 err = got_error_from_errno("close");
5281 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5282 err = got_error_from_errno("close");
5283 if (f1 && fclose(f1) == EOF && err == NULL)
5284 err = got_error_from_errno("fclose");
5285 if (f2 && fclose(f2) == EOF && err == NULL)
5286 err = got_error_from_errno("fclose");
5288 return (void *)err;
5291 static struct got_object_id *
5292 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5293 int first_displayed_line, int selected_line)
5295 struct tog_blame_line *line;
5297 if (nlines <= 0)
5298 return NULL;
5300 line = &lines[first_displayed_line - 1 + selected_line - 1];
5301 if (!line->annotated)
5302 return NULL;
5304 return line->id;
5307 static struct got_object_id *
5308 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5309 int lineno)
5311 struct tog_blame_line *line;
5313 if (nlines <= 0 || lineno >= nlines)
5314 return NULL;
5316 line = &lines[lineno - 1];
5317 if (!line->annotated)
5318 return NULL;
5320 return line->id;
5323 static const struct got_error *
5324 stop_blame(struct tog_blame *blame)
5326 const struct got_error *err = NULL;
5327 int i;
5329 if (blame->thread) {
5330 int errcode;
5331 errcode = pthread_mutex_unlock(&tog_mutex);
5332 if (errcode)
5333 return got_error_set_errno(errcode,
5334 "pthread_mutex_unlock");
5335 errcode = pthread_join(blame->thread, (void **)&err);
5336 if (errcode)
5337 return got_error_set_errno(errcode, "pthread_join");
5338 errcode = pthread_mutex_lock(&tog_mutex);
5339 if (errcode)
5340 return got_error_set_errno(errcode,
5341 "pthread_mutex_lock");
5342 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5343 err = NULL;
5344 blame->thread = NULL;
5346 if (blame->thread_args.repo) {
5347 const struct got_error *close_err;
5348 close_err = got_repo_close(blame->thread_args.repo);
5349 if (err == NULL)
5350 err = close_err;
5351 blame->thread_args.repo = NULL;
5353 if (blame->f) {
5354 if (fclose(blame->f) == EOF && err == NULL)
5355 err = got_error_from_errno("fclose");
5356 blame->f = NULL;
5358 if (blame->lines) {
5359 for (i = 0; i < blame->nlines; i++)
5360 free(blame->lines[i].id);
5361 free(blame->lines);
5362 blame->lines = NULL;
5364 free(blame->cb_args.commit_id);
5365 blame->cb_args.commit_id = NULL;
5366 if (blame->pack_fds) {
5367 const struct got_error *pack_err =
5368 got_repo_pack_fds_close(blame->pack_fds);
5369 if (err == NULL)
5370 err = pack_err;
5371 blame->pack_fds = NULL;
5373 return err;
5376 static const struct got_error *
5377 cancel_blame_view(void *arg)
5379 const struct got_error *err = NULL;
5380 int *done = arg;
5381 int errcode;
5383 errcode = pthread_mutex_lock(&tog_mutex);
5384 if (errcode)
5385 return got_error_set_errno(errcode,
5386 "pthread_mutex_unlock");
5388 if (*done)
5389 err = got_error(GOT_ERR_CANCELLED);
5391 errcode = pthread_mutex_unlock(&tog_mutex);
5392 if (errcode)
5393 return got_error_set_errno(errcode,
5394 "pthread_mutex_lock");
5396 return err;
5399 static const struct got_error *
5400 run_blame(struct tog_view *view)
5402 struct tog_blame_view_state *s = &view->state.blame;
5403 struct tog_blame *blame = &s->blame;
5404 const struct got_error *err = NULL;
5405 struct got_commit_object *commit = NULL;
5406 struct got_blob_object *blob = NULL;
5407 struct got_repository *thread_repo = NULL;
5408 struct got_object_id *obj_id = NULL;
5409 int obj_type, fd = -1;
5410 int *pack_fds = NULL;
5412 err = got_object_open_as_commit(&commit, s->repo,
5413 &s->blamed_commit->id);
5414 if (err)
5415 return err;
5417 fd = got_opentempfd();
5418 if (fd == -1) {
5419 err = got_error_from_errno("got_opentempfd");
5420 goto done;
5423 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5424 if (err)
5425 goto done;
5427 err = got_object_get_type(&obj_type, s->repo, obj_id);
5428 if (err)
5429 goto done;
5431 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5432 err = got_error(GOT_ERR_OBJ_TYPE);
5433 goto done;
5436 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5437 if (err)
5438 goto done;
5439 blame->f = got_opentemp();
5440 if (blame->f == NULL) {
5441 err = got_error_from_errno("got_opentemp");
5442 goto done;
5444 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5445 &blame->line_offsets, blame->f, blob);
5446 if (err)
5447 goto done;
5448 if (blame->nlines == 0) {
5449 s->blame_complete = 1;
5450 goto done;
5453 /* Don't include \n at EOF in the blame line count. */
5454 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5455 blame->nlines--;
5457 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5458 if (blame->lines == NULL) {
5459 err = got_error_from_errno("calloc");
5460 goto done;
5463 err = got_repo_pack_fds_open(&pack_fds);
5464 if (err)
5465 goto done;
5466 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5467 pack_fds);
5468 if (err)
5469 goto done;
5471 blame->pack_fds = pack_fds;
5472 blame->cb_args.view = view;
5473 blame->cb_args.lines = blame->lines;
5474 blame->cb_args.nlines = blame->nlines;
5475 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5476 if (blame->cb_args.commit_id == NULL) {
5477 err = got_error_from_errno("got_object_id_dup");
5478 goto done;
5480 blame->cb_args.quit = &s->done;
5482 blame->thread_args.path = s->path;
5483 blame->thread_args.repo = thread_repo;
5484 blame->thread_args.cb_args = &blame->cb_args;
5485 blame->thread_args.complete = &s->blame_complete;
5486 blame->thread_args.cancel_cb = cancel_blame_view;
5487 blame->thread_args.cancel_arg = &s->done;
5488 s->blame_complete = 0;
5490 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5491 s->first_displayed_line = 1;
5492 s->last_displayed_line = view->nlines;
5493 s->selected_line = 1;
5495 s->matched_line = 0;
5497 done:
5498 if (commit)
5499 got_object_commit_close(commit);
5500 if (fd != -1 && close(fd) == -1 && err == NULL)
5501 err = got_error_from_errno("close");
5502 if (blob)
5503 got_object_blob_close(blob);
5504 free(obj_id);
5505 if (err)
5506 stop_blame(blame);
5507 return err;
5510 static const struct got_error *
5511 open_blame_view(struct tog_view *view, char *path,
5512 struct got_object_id *commit_id, struct got_repository *repo)
5514 const struct got_error *err = NULL;
5515 struct tog_blame_view_state *s = &view->state.blame;
5517 STAILQ_INIT(&s->blamed_commits);
5519 s->path = strdup(path);
5520 if (s->path == NULL)
5521 return got_error_from_errno("strdup");
5523 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5524 if (err) {
5525 free(s->path);
5526 return err;
5529 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5530 s->first_displayed_line = 1;
5531 s->last_displayed_line = view->nlines;
5532 s->selected_line = 1;
5533 s->blame_complete = 0;
5534 s->repo = repo;
5535 s->commit_id = commit_id;
5536 memset(&s->blame, 0, sizeof(s->blame));
5538 STAILQ_INIT(&s->colors);
5539 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5540 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5541 get_color_value("TOG_COLOR_COMMIT"));
5542 if (err)
5543 return err;
5546 view->show = show_blame_view;
5547 view->input = input_blame_view;
5548 view->reset = reset_blame_view;
5549 view->close = close_blame_view;
5550 view->search_start = search_start_blame_view;
5551 view->search_next = search_next_blame_view;
5553 return run_blame(view);
5556 static const struct got_error *
5557 close_blame_view(struct tog_view *view)
5559 const struct got_error *err = NULL;
5560 struct tog_blame_view_state *s = &view->state.blame;
5562 if (s->blame.thread)
5563 err = stop_blame(&s->blame);
5565 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5566 struct got_object_qid *blamed_commit;
5567 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5568 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5569 got_object_qid_free(blamed_commit);
5572 free(s->path);
5573 free_colors(&s->colors);
5574 return err;
5577 static const struct got_error *
5578 search_start_blame_view(struct tog_view *view)
5580 struct tog_blame_view_state *s = &view->state.blame;
5582 s->matched_line = 0;
5583 return NULL;
5586 static const struct got_error *
5587 search_next_blame_view(struct tog_view *view)
5589 struct tog_blame_view_state *s = &view->state.blame;
5590 const struct got_error *err = NULL;
5591 int lineno;
5592 char *line = NULL;
5593 size_t linesize = 0;
5594 ssize_t linelen;
5596 if (!view->searching) {
5597 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5598 return NULL;
5601 if (s->matched_line) {
5602 if (view->searching == TOG_SEARCH_FORWARD)
5603 lineno = s->matched_line + 1;
5604 else
5605 lineno = s->matched_line - 1;
5606 } else
5607 lineno = s->first_displayed_line - 1 + s->selected_line;
5609 while (1) {
5610 off_t offset;
5612 if (lineno <= 0 || lineno > s->blame.nlines) {
5613 if (s->matched_line == 0) {
5614 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5615 break;
5618 if (view->searching == TOG_SEARCH_FORWARD)
5619 lineno = 1;
5620 else
5621 lineno = s->blame.nlines;
5624 offset = s->blame.line_offsets[lineno - 1];
5625 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5626 free(line);
5627 return got_error_from_errno("fseeko");
5629 linelen = getline(&line, &linesize, s->blame.f);
5630 if (linelen != -1) {
5631 char *exstr;
5632 err = expand_tab(&exstr, line);
5633 if (err)
5634 break;
5635 if (match_line(exstr, &view->regex, 1,
5636 &view->regmatch)) {
5637 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5638 s->matched_line = lineno;
5639 free(exstr);
5640 break;
5642 free(exstr);
5644 if (view->searching == TOG_SEARCH_FORWARD)
5645 lineno++;
5646 else
5647 lineno--;
5649 free(line);
5651 if (s->matched_line) {
5652 s->first_displayed_line = s->matched_line;
5653 s->selected_line = 1;
5656 return err;
5659 static const struct got_error *
5660 show_blame_view(struct tog_view *view)
5662 const struct got_error *err = NULL;
5663 struct tog_blame_view_state *s = &view->state.blame;
5664 int errcode;
5666 if (s->blame.thread == NULL && !s->blame_complete) {
5667 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5668 &s->blame.thread_args);
5669 if (errcode)
5670 return got_error_set_errno(errcode, "pthread_create");
5672 halfdelay(1); /* fast refresh while annotating */
5675 if (s->blame_complete)
5676 halfdelay(10); /* disable fast refresh */
5678 err = draw_blame(view);
5680 view_border(view);
5681 return err;
5684 static const struct got_error *
5685 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5686 struct got_repository *repo, struct got_object_id *id)
5688 struct tog_view *log_view;
5689 const struct got_error *err = NULL;
5691 *new_view = NULL;
5693 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5694 if (log_view == NULL)
5695 return got_error_from_errno("view_open");
5697 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5698 if (err)
5699 view_close(log_view);
5700 else
5701 *new_view = log_view;
5703 return err;
5706 static const struct got_error *
5707 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5709 const struct got_error *err = NULL, *thread_err = NULL;
5710 struct tog_view *diff_view;
5711 struct tog_blame_view_state *s = &view->state.blame;
5712 int eos, nscroll, begin_y = 0, begin_x = 0;
5714 eos = nscroll = view->nlines - 2;
5715 if (view_is_hsplit_top(view))
5716 --eos; /* border */
5718 switch (ch) {
5719 case '0':
5720 view->x = 0;
5721 break;
5722 case '$':
5723 view->x = MAX(view->maxx - view->ncols / 3, 0);
5724 view->count = 0;
5725 break;
5726 case KEY_RIGHT:
5727 case 'l':
5728 if (view->x + view->ncols / 3 < view->maxx)
5729 view->x += 2; /* move two columns right */
5730 else
5731 view->count = 0;
5732 break;
5733 case KEY_LEFT:
5734 case 'h':
5735 view->x -= MIN(view->x, 2); /* move two columns back */
5736 if (view->x <= 0)
5737 view->count = 0;
5738 break;
5739 case 'q':
5740 s->done = 1;
5741 break;
5742 case 'g':
5743 case KEY_HOME:
5744 s->selected_line = 1;
5745 s->first_displayed_line = 1;
5746 view->count = 0;
5747 break;
5748 case 'G':
5749 case KEY_END:
5750 if (s->blame.nlines < eos) {
5751 s->selected_line = s->blame.nlines;
5752 s->first_displayed_line = 1;
5753 } else {
5754 s->selected_line = eos;
5755 s->first_displayed_line = s->blame.nlines - (eos - 1);
5757 view->count = 0;
5758 break;
5759 case 'k':
5760 case KEY_UP:
5761 case CTRL('p'):
5762 if (s->selected_line > 1)
5763 s->selected_line--;
5764 else if (s->selected_line == 1 &&
5765 s->first_displayed_line > 1)
5766 s->first_displayed_line--;
5767 else
5768 view->count = 0;
5769 break;
5770 case CTRL('u'):
5771 case 'u':
5772 nscroll /= 2;
5773 /* FALL THROUGH */
5774 case KEY_PPAGE:
5775 case CTRL('b'):
5776 case 'b':
5777 if (s->first_displayed_line == 1) {
5778 if (view->count > 1)
5779 nscroll += nscroll;
5780 s->selected_line = MAX(1, s->selected_line - nscroll);
5781 view->count = 0;
5782 break;
5784 if (s->first_displayed_line > nscroll)
5785 s->first_displayed_line -= nscroll;
5786 else
5787 s->first_displayed_line = 1;
5788 break;
5789 case 'j':
5790 case KEY_DOWN:
5791 case CTRL('n'):
5792 if (s->selected_line < eos && s->first_displayed_line +
5793 s->selected_line <= s->blame.nlines)
5794 s->selected_line++;
5795 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5796 s->first_displayed_line++;
5797 else
5798 view->count = 0;
5799 break;
5800 case 'c':
5801 case 'p': {
5802 struct got_object_id *id = NULL;
5804 view->count = 0;
5805 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5806 s->first_displayed_line, s->selected_line);
5807 if (id == NULL)
5808 break;
5809 if (ch == 'p') {
5810 struct got_commit_object *commit, *pcommit;
5811 struct got_object_qid *pid;
5812 struct got_object_id *blob_id = NULL;
5813 int obj_type;
5814 err = got_object_open_as_commit(&commit,
5815 s->repo, id);
5816 if (err)
5817 break;
5818 pid = STAILQ_FIRST(
5819 got_object_commit_get_parent_ids(commit));
5820 if (pid == NULL) {
5821 got_object_commit_close(commit);
5822 break;
5824 /* Check if path history ends here. */
5825 err = got_object_open_as_commit(&pcommit,
5826 s->repo, &pid->id);
5827 if (err)
5828 break;
5829 err = got_object_id_by_path(&blob_id, s->repo,
5830 pcommit, s->path);
5831 got_object_commit_close(pcommit);
5832 if (err) {
5833 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5834 err = NULL;
5835 got_object_commit_close(commit);
5836 break;
5838 err = got_object_get_type(&obj_type, s->repo,
5839 blob_id);
5840 free(blob_id);
5841 /* Can't blame non-blob type objects. */
5842 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5843 got_object_commit_close(commit);
5844 break;
5846 err = got_object_qid_alloc(&s->blamed_commit,
5847 &pid->id);
5848 got_object_commit_close(commit);
5849 } else {
5850 if (got_object_id_cmp(id,
5851 &s->blamed_commit->id) == 0)
5852 break;
5853 err = got_object_qid_alloc(&s->blamed_commit,
5854 id);
5856 if (err)
5857 break;
5858 s->done = 1;
5859 thread_err = stop_blame(&s->blame);
5860 s->done = 0;
5861 if (thread_err)
5862 break;
5863 STAILQ_INSERT_HEAD(&s->blamed_commits,
5864 s->blamed_commit, entry);
5865 err = run_blame(view);
5866 if (err)
5867 break;
5868 break;
5870 case 'C': {
5871 struct got_object_qid *first;
5873 view->count = 0;
5874 first = STAILQ_FIRST(&s->blamed_commits);
5875 if (!got_object_id_cmp(&first->id, s->commit_id))
5876 break;
5877 s->done = 1;
5878 thread_err = stop_blame(&s->blame);
5879 s->done = 0;
5880 if (thread_err)
5881 break;
5882 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5883 got_object_qid_free(s->blamed_commit);
5884 s->blamed_commit =
5885 STAILQ_FIRST(&s->blamed_commits);
5886 err = run_blame(view);
5887 if (err)
5888 break;
5889 break;
5891 case 'L':
5892 view->count = 0;
5893 s->id_to_log = get_selected_commit_id(s->blame.lines,
5894 s->blame.nlines, s->first_displayed_line, s->selected_line);
5895 if (s->id_to_log)
5896 err = view_request_new(new_view, view, TOG_VIEW_LOG);
5897 break;
5898 case KEY_ENTER:
5899 case '\r': {
5900 struct got_object_id *id = NULL;
5901 struct got_object_qid *pid;
5902 struct got_commit_object *commit = NULL;
5904 view->count = 0;
5905 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5906 s->first_displayed_line, s->selected_line);
5907 if (id == NULL)
5908 break;
5909 err = got_object_open_as_commit(&commit, s->repo, id);
5910 if (err)
5911 break;
5912 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5913 if (*new_view) {
5914 /* traversed from diff view, release diff resources */
5915 err = close_diff_view(*new_view);
5916 if (err)
5917 break;
5918 diff_view = *new_view;
5919 } else {
5920 if (view_is_parent_view(view))
5921 view_get_split(view, &begin_y, &begin_x);
5923 diff_view = view_open(0, 0, begin_y, begin_x,
5924 TOG_VIEW_DIFF);
5925 if (diff_view == NULL) {
5926 got_object_commit_close(commit);
5927 err = got_error_from_errno("view_open");
5928 break;
5931 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5932 id, NULL, NULL, 3, 0, 0, view, s->repo);
5933 got_object_commit_close(commit);
5934 if (err) {
5935 view_close(diff_view);
5936 break;
5938 s->last_diffed_line = s->first_displayed_line - 1 +
5939 s->selected_line;
5940 if (*new_view)
5941 break; /* still open from active diff view */
5942 if (view_is_parent_view(view) &&
5943 view->mode == TOG_VIEW_SPLIT_HRZN) {
5944 err = view_init_hsplit(view, begin_y);
5945 if (err)
5946 break;
5949 view->focussed = 0;
5950 diff_view->focussed = 1;
5951 diff_view->mode = view->mode;
5952 diff_view->nlines = view->lines - begin_y;
5953 if (view_is_parent_view(view)) {
5954 view_transfer_size(diff_view, view);
5955 err = view_close_child(view);
5956 if (err)
5957 break;
5958 err = view_set_child(view, diff_view);
5959 if (err)
5960 break;
5961 view->focus_child = 1;
5962 } else
5963 *new_view = diff_view;
5964 if (err)
5965 break;
5966 break;
5968 case CTRL('d'):
5969 case 'd':
5970 nscroll /= 2;
5971 /* FALL THROUGH */
5972 case KEY_NPAGE:
5973 case CTRL('f'):
5974 case 'f':
5975 case ' ':
5976 if (s->last_displayed_line >= s->blame.nlines &&
5977 s->selected_line >= MIN(s->blame.nlines,
5978 view->nlines - 2)) {
5979 view->count = 0;
5980 break;
5982 if (s->last_displayed_line >= s->blame.nlines &&
5983 s->selected_line < view->nlines - 2) {
5984 s->selected_line +=
5985 MIN(nscroll, s->last_displayed_line -
5986 s->first_displayed_line - s->selected_line + 1);
5988 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5989 s->first_displayed_line += nscroll;
5990 else
5991 s->first_displayed_line =
5992 s->blame.nlines - (view->nlines - 3);
5993 break;
5994 case KEY_RESIZE:
5995 if (s->selected_line > view->nlines - 2) {
5996 s->selected_line = MIN(s->blame.nlines,
5997 view->nlines - 2);
5999 break;
6000 default:
6001 view->count = 0;
6002 break;
6004 return thread_err ? thread_err : err;
6007 static const struct got_error *
6008 reset_blame_view(struct tog_view *view)
6010 const struct got_error *err;
6011 struct tog_blame_view_state *s = &view->state.blame;
6013 view->count = 0;
6014 s->done = 1;
6015 err = stop_blame(&s->blame);
6016 s->done = 0;
6017 if (err)
6018 return err;
6019 return run_blame(view);
6022 static const struct got_error *
6023 cmd_blame(int argc, char *argv[])
6025 const struct got_error *error;
6026 struct got_repository *repo = NULL;
6027 struct got_worktree *worktree = NULL;
6028 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6029 char *link_target = NULL;
6030 struct got_object_id *commit_id = NULL;
6031 struct got_commit_object *commit = NULL;
6032 char *commit_id_str = NULL;
6033 int ch;
6034 struct tog_view *view;
6035 int *pack_fds = NULL;
6037 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6038 switch (ch) {
6039 case 'c':
6040 commit_id_str = optarg;
6041 break;
6042 case 'r':
6043 repo_path = realpath(optarg, NULL);
6044 if (repo_path == NULL)
6045 return got_error_from_errno2("realpath",
6046 optarg);
6047 break;
6048 default:
6049 usage_blame();
6050 /* NOTREACHED */
6054 argc -= optind;
6055 argv += optind;
6057 if (argc != 1)
6058 usage_blame();
6060 error = got_repo_pack_fds_open(&pack_fds);
6061 if (error != NULL)
6062 goto done;
6064 if (repo_path == NULL) {
6065 cwd = getcwd(NULL, 0);
6066 if (cwd == NULL)
6067 return got_error_from_errno("getcwd");
6068 error = got_worktree_open(&worktree, cwd);
6069 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6070 goto done;
6071 if (worktree)
6072 repo_path =
6073 strdup(got_worktree_get_repo_path(worktree));
6074 else
6075 repo_path = strdup(cwd);
6076 if (repo_path == NULL) {
6077 error = got_error_from_errno("strdup");
6078 goto done;
6082 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6083 if (error != NULL)
6084 goto done;
6086 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6087 worktree);
6088 if (error)
6089 goto done;
6091 init_curses();
6093 error = apply_unveil(got_repo_get_path(repo), NULL);
6094 if (error)
6095 goto done;
6097 error = tog_load_refs(repo, 0);
6098 if (error)
6099 goto done;
6101 if (commit_id_str == NULL) {
6102 struct got_reference *head_ref;
6103 error = got_ref_open(&head_ref, repo, worktree ?
6104 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6105 if (error != NULL)
6106 goto done;
6107 error = got_ref_resolve(&commit_id, repo, head_ref);
6108 got_ref_close(head_ref);
6109 } else {
6110 error = got_repo_match_object_id(&commit_id, NULL,
6111 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6113 if (error != NULL)
6114 goto done;
6116 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6117 if (view == NULL) {
6118 error = got_error_from_errno("view_open");
6119 goto done;
6122 error = got_object_open_as_commit(&commit, repo, commit_id);
6123 if (error)
6124 goto done;
6126 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6127 commit, repo);
6128 if (error)
6129 goto done;
6131 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6132 commit_id, repo);
6133 if (error)
6134 goto done;
6135 if (worktree) {
6136 /* Release work tree lock. */
6137 got_worktree_close(worktree);
6138 worktree = NULL;
6140 error = view_loop(view);
6141 done:
6142 free(repo_path);
6143 free(in_repo_path);
6144 free(link_target);
6145 free(cwd);
6146 free(commit_id);
6147 if (commit)
6148 got_object_commit_close(commit);
6149 if (worktree)
6150 got_worktree_close(worktree);
6151 if (repo) {
6152 const struct got_error *close_err = got_repo_close(repo);
6153 if (error == NULL)
6154 error = close_err;
6156 if (pack_fds) {
6157 const struct got_error *pack_err =
6158 got_repo_pack_fds_close(pack_fds);
6159 if (error == NULL)
6160 error = pack_err;
6162 tog_free_refs();
6163 return error;
6166 static const struct got_error *
6167 draw_tree_entries(struct tog_view *view, const char *parent_path)
6169 struct tog_tree_view_state *s = &view->state.tree;
6170 const struct got_error *err = NULL;
6171 struct got_tree_entry *te;
6172 wchar_t *wline;
6173 struct tog_color *tc;
6174 int width, n, i, nentries;
6175 int limit = view->nlines;
6177 s->ndisplayed = 0;
6178 if (view_is_hsplit_top(view))
6179 --limit; /* border */
6181 werase(view->window);
6183 if (limit == 0)
6184 return NULL;
6186 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6187 0, 0);
6188 if (err)
6189 return err;
6190 if (view_needs_focus_indication(view))
6191 wstandout(view->window);
6192 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6193 if (tc)
6194 wattr_on(view->window,
6195 COLOR_PAIR(tc->colorpair), NULL);
6196 waddwstr(view->window, wline);
6197 if (tc)
6198 wattr_off(view->window,
6199 COLOR_PAIR(tc->colorpair), NULL);
6200 if (view_needs_focus_indication(view))
6201 wstandend(view->window);
6202 free(wline);
6203 wline = NULL;
6204 if (width < view->ncols - 1)
6205 waddch(view->window, '\n');
6206 if (--limit <= 0)
6207 return NULL;
6208 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6209 0, 0);
6210 if (err)
6211 return err;
6212 waddwstr(view->window, wline);
6213 free(wline);
6214 wline = NULL;
6215 if (width < view->ncols - 1)
6216 waddch(view->window, '\n');
6217 if (--limit <= 0)
6218 return NULL;
6219 waddch(view->window, '\n');
6220 if (--limit <= 0)
6221 return NULL;
6223 if (s->first_displayed_entry == NULL) {
6224 te = got_object_tree_get_first_entry(s->tree);
6225 if (s->selected == 0) {
6226 if (view->focussed)
6227 wstandout(view->window);
6228 s->selected_entry = NULL;
6230 waddstr(view->window, " ..\n"); /* parent directory */
6231 if (s->selected == 0 && view->focussed)
6232 wstandend(view->window);
6233 s->ndisplayed++;
6234 if (--limit <= 0)
6235 return NULL;
6236 n = 1;
6237 } else {
6238 n = 0;
6239 te = s->first_displayed_entry;
6242 nentries = got_object_tree_get_nentries(s->tree);
6243 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6244 char *line = NULL, *id_str = NULL, *link_target = NULL;
6245 const char *modestr = "";
6246 mode_t mode;
6248 te = got_object_tree_get_entry(s->tree, i);
6249 mode = got_tree_entry_get_mode(te);
6251 if (s->show_ids) {
6252 err = got_object_id_str(&id_str,
6253 got_tree_entry_get_id(te));
6254 if (err)
6255 return got_error_from_errno(
6256 "got_object_id_str");
6258 if (got_object_tree_entry_is_submodule(te))
6259 modestr = "$";
6260 else if (S_ISLNK(mode)) {
6261 int i;
6263 err = got_tree_entry_get_symlink_target(&link_target,
6264 te, s->repo);
6265 if (err) {
6266 free(id_str);
6267 return err;
6269 for (i = 0; i < strlen(link_target); i++) {
6270 if (!isprint((unsigned char)link_target[i]))
6271 link_target[i] = '?';
6273 modestr = "@";
6275 else if (S_ISDIR(mode))
6276 modestr = "/";
6277 else if (mode & S_IXUSR)
6278 modestr = "*";
6279 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6280 got_tree_entry_get_name(te), modestr,
6281 link_target ? " -> ": "",
6282 link_target ? link_target : "") == -1) {
6283 free(id_str);
6284 free(link_target);
6285 return got_error_from_errno("asprintf");
6287 free(id_str);
6288 free(link_target);
6289 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6290 0, 0);
6291 if (err) {
6292 free(line);
6293 break;
6295 if (n == s->selected) {
6296 if (view->focussed)
6297 wstandout(view->window);
6298 s->selected_entry = te;
6300 tc = match_color(&s->colors, line);
6301 if (tc)
6302 wattr_on(view->window,
6303 COLOR_PAIR(tc->colorpair), NULL);
6304 waddwstr(view->window, wline);
6305 if (tc)
6306 wattr_off(view->window,
6307 COLOR_PAIR(tc->colorpair), NULL);
6308 if (width < view->ncols - 1)
6309 waddch(view->window, '\n');
6310 if (n == s->selected && view->focussed)
6311 wstandend(view->window);
6312 free(line);
6313 free(wline);
6314 wline = NULL;
6315 n++;
6316 s->ndisplayed++;
6317 s->last_displayed_entry = te;
6318 if (--limit <= 0)
6319 break;
6322 return err;
6325 static void
6326 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6328 struct got_tree_entry *te;
6329 int isroot = s->tree == s->root;
6330 int i = 0;
6332 if (s->first_displayed_entry == NULL)
6333 return;
6335 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6336 while (i++ < maxscroll) {
6337 if (te == NULL) {
6338 if (!isroot)
6339 s->first_displayed_entry = NULL;
6340 break;
6342 s->first_displayed_entry = te;
6343 te = got_tree_entry_get_prev(s->tree, te);
6347 static const struct got_error *
6348 tree_scroll_down(struct tog_view *view, int maxscroll)
6350 struct tog_tree_view_state *s = &view->state.tree;
6351 struct got_tree_entry *next, *last;
6352 int n = 0;
6354 if (s->first_displayed_entry)
6355 next = got_tree_entry_get_next(s->tree,
6356 s->first_displayed_entry);
6357 else
6358 next = got_object_tree_get_first_entry(s->tree);
6360 last = s->last_displayed_entry;
6361 while (next && n++ < maxscroll) {
6362 if (last)
6363 last = got_tree_entry_get_next(s->tree, last);
6364 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6365 s->first_displayed_entry = next;
6366 next = got_tree_entry_get_next(s->tree, next);
6370 return NULL;
6373 static const struct got_error *
6374 tree_entry_path(char **path, struct tog_parent_trees *parents,
6375 struct got_tree_entry *te)
6377 const struct got_error *err = NULL;
6378 struct tog_parent_tree *pt;
6379 size_t len = 2; /* for leading slash and NUL */
6381 TAILQ_FOREACH(pt, parents, entry)
6382 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6383 + 1 /* slash */;
6384 if (te)
6385 len += strlen(got_tree_entry_get_name(te));
6387 *path = calloc(1, len);
6388 if (path == NULL)
6389 return got_error_from_errno("calloc");
6391 (*path)[0] = '/';
6392 pt = TAILQ_LAST(parents, tog_parent_trees);
6393 while (pt) {
6394 const char *name = got_tree_entry_get_name(pt->selected_entry);
6395 if (strlcat(*path, name, len) >= len) {
6396 err = got_error(GOT_ERR_NO_SPACE);
6397 goto done;
6399 if (strlcat(*path, "/", len) >= len) {
6400 err = got_error(GOT_ERR_NO_SPACE);
6401 goto done;
6403 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6405 if (te) {
6406 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6407 err = got_error(GOT_ERR_NO_SPACE);
6408 goto done;
6411 done:
6412 if (err) {
6413 free(*path);
6414 *path = NULL;
6416 return err;
6419 static const struct got_error *
6420 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6421 struct got_tree_entry *te, struct tog_parent_trees *parents,
6422 struct got_object_id *commit_id, struct got_repository *repo)
6424 const struct got_error *err = NULL;
6425 char *path;
6426 struct tog_view *blame_view;
6428 *new_view = NULL;
6430 err = tree_entry_path(&path, parents, te);
6431 if (err)
6432 return err;
6434 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6435 if (blame_view == NULL) {
6436 err = got_error_from_errno("view_open");
6437 goto done;
6440 err = open_blame_view(blame_view, path, commit_id, repo);
6441 if (err) {
6442 if (err->code == GOT_ERR_CANCELLED)
6443 err = NULL;
6444 view_close(blame_view);
6445 } else
6446 *new_view = blame_view;
6447 done:
6448 free(path);
6449 return err;
6452 static const struct got_error *
6453 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6454 struct tog_tree_view_state *s)
6456 struct tog_view *log_view;
6457 const struct got_error *err = NULL;
6458 char *path;
6460 *new_view = NULL;
6462 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6463 if (log_view == NULL)
6464 return got_error_from_errno("view_open");
6466 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6467 if (err)
6468 return err;
6470 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6471 path, 0);
6472 if (err)
6473 view_close(log_view);
6474 else
6475 *new_view = log_view;
6476 free(path);
6477 return err;
6480 static const struct got_error *
6481 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6482 const char *head_ref_name, struct got_repository *repo)
6484 const struct got_error *err = NULL;
6485 char *commit_id_str = NULL;
6486 struct tog_tree_view_state *s = &view->state.tree;
6487 struct got_commit_object *commit = NULL;
6489 TAILQ_INIT(&s->parents);
6490 STAILQ_INIT(&s->colors);
6492 s->commit_id = got_object_id_dup(commit_id);
6493 if (s->commit_id == NULL)
6494 return got_error_from_errno("got_object_id_dup");
6496 err = got_object_open_as_commit(&commit, repo, commit_id);
6497 if (err)
6498 goto done;
6501 * The root is opened here and will be closed when the view is closed.
6502 * Any visited subtrees and their path-wise parents are opened and
6503 * closed on demand.
6505 err = got_object_open_as_tree(&s->root, repo,
6506 got_object_commit_get_tree_id(commit));
6507 if (err)
6508 goto done;
6509 s->tree = s->root;
6511 err = got_object_id_str(&commit_id_str, commit_id);
6512 if (err != NULL)
6513 goto done;
6515 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6516 err = got_error_from_errno("asprintf");
6517 goto done;
6520 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6521 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6522 if (head_ref_name) {
6523 s->head_ref_name = strdup(head_ref_name);
6524 if (s->head_ref_name == NULL) {
6525 err = got_error_from_errno("strdup");
6526 goto done;
6529 s->repo = repo;
6531 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6532 err = add_color(&s->colors, "\\$$",
6533 TOG_COLOR_TREE_SUBMODULE,
6534 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6535 if (err)
6536 goto done;
6537 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6538 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6539 if (err)
6540 goto done;
6541 err = add_color(&s->colors, "/$",
6542 TOG_COLOR_TREE_DIRECTORY,
6543 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6544 if (err)
6545 goto done;
6547 err = add_color(&s->colors, "\\*$",
6548 TOG_COLOR_TREE_EXECUTABLE,
6549 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6550 if (err)
6551 goto done;
6553 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6554 get_color_value("TOG_COLOR_COMMIT"));
6555 if (err)
6556 goto done;
6559 view->show = show_tree_view;
6560 view->input = input_tree_view;
6561 view->close = close_tree_view;
6562 view->search_start = search_start_tree_view;
6563 view->search_next = search_next_tree_view;
6564 done:
6565 free(commit_id_str);
6566 if (commit)
6567 got_object_commit_close(commit);
6568 if (err)
6569 close_tree_view(view);
6570 return err;
6573 static const struct got_error *
6574 close_tree_view(struct tog_view *view)
6576 struct tog_tree_view_state *s = &view->state.tree;
6578 free_colors(&s->colors);
6579 free(s->tree_label);
6580 s->tree_label = NULL;
6581 free(s->commit_id);
6582 s->commit_id = NULL;
6583 free(s->head_ref_name);
6584 s->head_ref_name = NULL;
6585 while (!TAILQ_EMPTY(&s->parents)) {
6586 struct tog_parent_tree *parent;
6587 parent = TAILQ_FIRST(&s->parents);
6588 TAILQ_REMOVE(&s->parents, parent, entry);
6589 if (parent->tree != s->root)
6590 got_object_tree_close(parent->tree);
6591 free(parent);
6594 if (s->tree != NULL && s->tree != s->root)
6595 got_object_tree_close(s->tree);
6596 if (s->root)
6597 got_object_tree_close(s->root);
6598 return NULL;
6601 static const struct got_error *
6602 search_start_tree_view(struct tog_view *view)
6604 struct tog_tree_view_state *s = &view->state.tree;
6606 s->matched_entry = NULL;
6607 return NULL;
6610 static int
6611 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6613 regmatch_t regmatch;
6615 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6616 0) == 0;
6619 static const struct got_error *
6620 search_next_tree_view(struct tog_view *view)
6622 struct tog_tree_view_state *s = &view->state.tree;
6623 struct got_tree_entry *te = NULL;
6625 if (!view->searching) {
6626 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6627 return NULL;
6630 if (s->matched_entry) {
6631 if (view->searching == TOG_SEARCH_FORWARD) {
6632 if (s->selected_entry)
6633 te = got_tree_entry_get_next(s->tree,
6634 s->selected_entry);
6635 else
6636 te = got_object_tree_get_first_entry(s->tree);
6637 } else {
6638 if (s->selected_entry == NULL)
6639 te = got_object_tree_get_last_entry(s->tree);
6640 else
6641 te = got_tree_entry_get_prev(s->tree,
6642 s->selected_entry);
6644 } else {
6645 if (s->selected_entry)
6646 te = s->selected_entry;
6647 else if (view->searching == TOG_SEARCH_FORWARD)
6648 te = got_object_tree_get_first_entry(s->tree);
6649 else
6650 te = got_object_tree_get_last_entry(s->tree);
6653 while (1) {
6654 if (te == NULL) {
6655 if (s->matched_entry == NULL) {
6656 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6657 return NULL;
6659 if (view->searching == TOG_SEARCH_FORWARD)
6660 te = got_object_tree_get_first_entry(s->tree);
6661 else
6662 te = got_object_tree_get_last_entry(s->tree);
6665 if (match_tree_entry(te, &view->regex)) {
6666 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6667 s->matched_entry = te;
6668 break;
6671 if (view->searching == TOG_SEARCH_FORWARD)
6672 te = got_tree_entry_get_next(s->tree, te);
6673 else
6674 te = got_tree_entry_get_prev(s->tree, te);
6677 if (s->matched_entry) {
6678 s->first_displayed_entry = s->matched_entry;
6679 s->selected = 0;
6682 return NULL;
6685 static const struct got_error *
6686 show_tree_view(struct tog_view *view)
6688 const struct got_error *err = NULL;
6689 struct tog_tree_view_state *s = &view->state.tree;
6690 char *parent_path;
6692 err = tree_entry_path(&parent_path, &s->parents, NULL);
6693 if (err)
6694 return err;
6696 err = draw_tree_entries(view, parent_path);
6697 free(parent_path);
6699 view_border(view);
6700 return err;
6703 static const struct got_error *
6704 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6706 const struct got_error *err = NULL;
6707 struct tog_tree_view_state *s = &view->state.tree;
6708 struct got_tree_entry *te;
6709 int n, nscroll = view->nlines - 3;
6711 switch (ch) {
6712 case 'i':
6713 s->show_ids = !s->show_ids;
6714 view->count = 0;
6715 break;
6716 case 'L':
6717 view->count = 0;
6718 if (!s->selected_entry)
6719 break;
6720 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6721 break;
6722 case 'R':
6723 view->count = 0;
6724 err = view_request_new(new_view, view, TOG_VIEW_REF);
6725 break;
6726 case 'g':
6727 case KEY_HOME:
6728 s->selected = 0;
6729 view->count = 0;
6730 if (s->tree == s->root)
6731 s->first_displayed_entry =
6732 got_object_tree_get_first_entry(s->tree);
6733 else
6734 s->first_displayed_entry = NULL;
6735 break;
6736 case 'G':
6737 case KEY_END: {
6738 int eos = view->nlines - 3;
6740 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6741 --eos; /* border */
6742 s->selected = 0;
6743 view->count = 0;
6744 te = got_object_tree_get_last_entry(s->tree);
6745 for (n = 0; n < eos; n++) {
6746 if (te == NULL) {
6747 if (s->tree != s->root) {
6748 s->first_displayed_entry = NULL;
6749 n++;
6751 break;
6753 s->first_displayed_entry = te;
6754 te = got_tree_entry_get_prev(s->tree, te);
6756 if (n > 0)
6757 s->selected = n - 1;
6758 break;
6760 case 'k':
6761 case KEY_UP:
6762 case CTRL('p'):
6763 if (s->selected > 0) {
6764 s->selected--;
6765 break;
6767 tree_scroll_up(s, 1);
6768 if (s->selected_entry == NULL ||
6769 (s->tree == s->root && s->selected_entry ==
6770 got_object_tree_get_first_entry(s->tree)))
6771 view->count = 0;
6772 break;
6773 case CTRL('u'):
6774 case 'u':
6775 nscroll /= 2;
6776 /* FALL THROUGH */
6777 case KEY_PPAGE:
6778 case CTRL('b'):
6779 case 'b':
6780 if (s->tree == s->root) {
6781 if (got_object_tree_get_first_entry(s->tree) ==
6782 s->first_displayed_entry)
6783 s->selected -= MIN(s->selected, nscroll);
6784 } else {
6785 if (s->first_displayed_entry == NULL)
6786 s->selected -= MIN(s->selected, nscroll);
6788 tree_scroll_up(s, MAX(0, nscroll));
6789 if (s->selected_entry == NULL ||
6790 (s->tree == s->root && s->selected_entry ==
6791 got_object_tree_get_first_entry(s->tree)))
6792 view->count = 0;
6793 break;
6794 case 'j':
6795 case KEY_DOWN:
6796 case CTRL('n'):
6797 if (s->selected < s->ndisplayed - 1) {
6798 s->selected++;
6799 break;
6801 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6802 == NULL) {
6803 /* can't scroll any further */
6804 view->count = 0;
6805 break;
6807 tree_scroll_down(view, 1);
6808 break;
6809 case CTRL('d'):
6810 case 'd':
6811 nscroll /= 2;
6812 /* FALL THROUGH */
6813 case KEY_NPAGE:
6814 case CTRL('f'):
6815 case 'f':
6816 case ' ':
6817 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6818 == NULL) {
6819 /* can't scroll any further; move cursor down */
6820 if (s->selected < s->ndisplayed - 1)
6821 s->selected += MIN(nscroll,
6822 s->ndisplayed - s->selected - 1);
6823 else
6824 view->count = 0;
6825 break;
6827 tree_scroll_down(view, nscroll);
6828 break;
6829 case KEY_ENTER:
6830 case '\r':
6831 case KEY_BACKSPACE:
6832 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6833 struct tog_parent_tree *parent;
6834 /* user selected '..' */
6835 if (s->tree == s->root) {
6836 view->count = 0;
6837 break;
6839 parent = TAILQ_FIRST(&s->parents);
6840 TAILQ_REMOVE(&s->parents, parent,
6841 entry);
6842 got_object_tree_close(s->tree);
6843 s->tree = parent->tree;
6844 s->first_displayed_entry =
6845 parent->first_displayed_entry;
6846 s->selected_entry =
6847 parent->selected_entry;
6848 s->selected = parent->selected;
6849 if (s->selected > view->nlines - 3) {
6850 err = offset_selection_down(view);
6851 if (err)
6852 break;
6854 free(parent);
6855 } else if (S_ISDIR(got_tree_entry_get_mode(
6856 s->selected_entry))) {
6857 struct got_tree_object *subtree;
6858 view->count = 0;
6859 err = got_object_open_as_tree(&subtree, s->repo,
6860 got_tree_entry_get_id(s->selected_entry));
6861 if (err)
6862 break;
6863 err = tree_view_visit_subtree(s, subtree);
6864 if (err) {
6865 got_object_tree_close(subtree);
6866 break;
6868 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
6869 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
6870 break;
6871 case KEY_RESIZE:
6872 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6873 s->selected = view->nlines - 4;
6874 view->count = 0;
6875 break;
6876 default:
6877 view->count = 0;
6878 break;
6881 return err;
6884 __dead static void
6885 usage_tree(void)
6887 endwin();
6888 fprintf(stderr,
6889 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6890 getprogname());
6891 exit(1);
6894 static const struct got_error *
6895 cmd_tree(int argc, char *argv[])
6897 const struct got_error *error;
6898 struct got_repository *repo = NULL;
6899 struct got_worktree *worktree = NULL;
6900 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6901 struct got_object_id *commit_id = NULL;
6902 struct got_commit_object *commit = NULL;
6903 const char *commit_id_arg = NULL;
6904 char *label = NULL;
6905 struct got_reference *ref = NULL;
6906 const char *head_ref_name = NULL;
6907 int ch;
6908 struct tog_view *view;
6909 int *pack_fds = NULL;
6911 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6912 switch (ch) {
6913 case 'c':
6914 commit_id_arg = optarg;
6915 break;
6916 case 'r':
6917 repo_path = realpath(optarg, NULL);
6918 if (repo_path == NULL)
6919 return got_error_from_errno2("realpath",
6920 optarg);
6921 break;
6922 default:
6923 usage_tree();
6924 /* NOTREACHED */
6928 argc -= optind;
6929 argv += optind;
6931 if (argc > 1)
6932 usage_tree();
6934 error = got_repo_pack_fds_open(&pack_fds);
6935 if (error != NULL)
6936 goto done;
6938 if (repo_path == NULL) {
6939 cwd = getcwd(NULL, 0);
6940 if (cwd == NULL)
6941 return got_error_from_errno("getcwd");
6942 error = got_worktree_open(&worktree, cwd);
6943 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6944 goto done;
6945 if (worktree)
6946 repo_path =
6947 strdup(got_worktree_get_repo_path(worktree));
6948 else
6949 repo_path = strdup(cwd);
6950 if (repo_path == NULL) {
6951 error = got_error_from_errno("strdup");
6952 goto done;
6956 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6957 if (error != NULL)
6958 goto done;
6960 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6961 repo, worktree);
6962 if (error)
6963 goto done;
6965 init_curses();
6967 error = apply_unveil(got_repo_get_path(repo), NULL);
6968 if (error)
6969 goto done;
6971 error = tog_load_refs(repo, 0);
6972 if (error)
6973 goto done;
6975 if (commit_id_arg == NULL) {
6976 error = got_repo_match_object_id(&commit_id, &label,
6977 worktree ? got_worktree_get_head_ref_name(worktree) :
6978 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6979 if (error)
6980 goto done;
6981 head_ref_name = label;
6982 } else {
6983 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6984 if (error == NULL)
6985 head_ref_name = got_ref_get_name(ref);
6986 else if (error->code != GOT_ERR_NOT_REF)
6987 goto done;
6988 error = got_repo_match_object_id(&commit_id, NULL,
6989 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6990 if (error)
6991 goto done;
6994 error = got_object_open_as_commit(&commit, repo, commit_id);
6995 if (error)
6996 goto done;
6998 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6999 if (view == NULL) {
7000 error = got_error_from_errno("view_open");
7001 goto done;
7003 error = open_tree_view(view, commit_id, head_ref_name, repo);
7004 if (error)
7005 goto done;
7006 if (!got_path_is_root_dir(in_repo_path)) {
7007 error = tree_view_walk_path(&view->state.tree, commit,
7008 in_repo_path);
7009 if (error)
7010 goto done;
7013 if (worktree) {
7014 /* Release work tree lock. */
7015 got_worktree_close(worktree);
7016 worktree = NULL;
7018 error = view_loop(view);
7019 done:
7020 free(repo_path);
7021 free(cwd);
7022 free(commit_id);
7023 free(label);
7024 if (ref)
7025 got_ref_close(ref);
7026 if (repo) {
7027 const struct got_error *close_err = got_repo_close(repo);
7028 if (error == NULL)
7029 error = close_err;
7031 if (pack_fds) {
7032 const struct got_error *pack_err =
7033 got_repo_pack_fds_close(pack_fds);
7034 if (error == NULL)
7035 error = pack_err;
7037 tog_free_refs();
7038 return error;
7041 static const struct got_error *
7042 ref_view_load_refs(struct tog_ref_view_state *s)
7044 struct got_reflist_entry *sre;
7045 struct tog_reflist_entry *re;
7047 s->nrefs = 0;
7048 TAILQ_FOREACH(sre, &tog_refs, entry) {
7049 if (strncmp(got_ref_get_name(sre->ref),
7050 "refs/got/", 9) == 0 &&
7051 strncmp(got_ref_get_name(sre->ref),
7052 "refs/got/backup/", 16) != 0)
7053 continue;
7055 re = malloc(sizeof(*re));
7056 if (re == NULL)
7057 return got_error_from_errno("malloc");
7059 re->ref = got_ref_dup(sre->ref);
7060 if (re->ref == NULL)
7061 return got_error_from_errno("got_ref_dup");
7062 re->idx = s->nrefs++;
7063 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7066 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7067 return NULL;
7070 static void
7071 ref_view_free_refs(struct tog_ref_view_state *s)
7073 struct tog_reflist_entry *re;
7075 while (!TAILQ_EMPTY(&s->refs)) {
7076 re = TAILQ_FIRST(&s->refs);
7077 TAILQ_REMOVE(&s->refs, re, entry);
7078 got_ref_close(re->ref);
7079 free(re);
7083 static const struct got_error *
7084 open_ref_view(struct tog_view *view, struct got_repository *repo)
7086 const struct got_error *err = NULL;
7087 struct tog_ref_view_state *s = &view->state.ref;
7089 s->selected_entry = 0;
7090 s->repo = repo;
7092 TAILQ_INIT(&s->refs);
7093 STAILQ_INIT(&s->colors);
7095 err = ref_view_load_refs(s);
7096 if (err)
7097 return err;
7099 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7100 err = add_color(&s->colors, "^refs/heads/",
7101 TOG_COLOR_REFS_HEADS,
7102 get_color_value("TOG_COLOR_REFS_HEADS"));
7103 if (err)
7104 goto done;
7106 err = add_color(&s->colors, "^refs/tags/",
7107 TOG_COLOR_REFS_TAGS,
7108 get_color_value("TOG_COLOR_REFS_TAGS"));
7109 if (err)
7110 goto done;
7112 err = add_color(&s->colors, "^refs/remotes/",
7113 TOG_COLOR_REFS_REMOTES,
7114 get_color_value("TOG_COLOR_REFS_REMOTES"));
7115 if (err)
7116 goto done;
7118 err = add_color(&s->colors, "^refs/got/backup/",
7119 TOG_COLOR_REFS_BACKUP,
7120 get_color_value("TOG_COLOR_REFS_BACKUP"));
7121 if (err)
7122 goto done;
7125 view->show = show_ref_view;
7126 view->input = input_ref_view;
7127 view->close = close_ref_view;
7128 view->search_start = search_start_ref_view;
7129 view->search_next = search_next_ref_view;
7130 done:
7131 if (err)
7132 free_colors(&s->colors);
7133 return err;
7136 static const struct got_error *
7137 close_ref_view(struct tog_view *view)
7139 struct tog_ref_view_state *s = &view->state.ref;
7141 ref_view_free_refs(s);
7142 free_colors(&s->colors);
7144 return NULL;
7147 static const struct got_error *
7148 resolve_reflist_entry(struct got_object_id **commit_id,
7149 struct tog_reflist_entry *re, struct got_repository *repo)
7151 const struct got_error *err = NULL;
7152 struct got_object_id *obj_id;
7153 struct got_tag_object *tag = NULL;
7154 int obj_type;
7156 *commit_id = NULL;
7158 err = got_ref_resolve(&obj_id, repo, re->ref);
7159 if (err)
7160 return err;
7162 err = got_object_get_type(&obj_type, repo, obj_id);
7163 if (err)
7164 goto done;
7166 switch (obj_type) {
7167 case GOT_OBJ_TYPE_COMMIT:
7168 *commit_id = obj_id;
7169 break;
7170 case GOT_OBJ_TYPE_TAG:
7171 err = got_object_open_as_tag(&tag, repo, obj_id);
7172 if (err)
7173 goto done;
7174 free(obj_id);
7175 err = got_object_get_type(&obj_type, repo,
7176 got_object_tag_get_object_id(tag));
7177 if (err)
7178 goto done;
7179 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7180 err = got_error(GOT_ERR_OBJ_TYPE);
7181 goto done;
7183 *commit_id = got_object_id_dup(
7184 got_object_tag_get_object_id(tag));
7185 if (*commit_id == NULL) {
7186 err = got_error_from_errno("got_object_id_dup");
7187 goto done;
7189 break;
7190 default:
7191 err = got_error(GOT_ERR_OBJ_TYPE);
7192 break;
7195 done:
7196 if (tag)
7197 got_object_tag_close(tag);
7198 if (err) {
7199 free(*commit_id);
7200 *commit_id = NULL;
7202 return err;
7205 static const struct got_error *
7206 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7207 struct tog_reflist_entry *re, struct got_repository *repo)
7209 struct tog_view *log_view;
7210 const struct got_error *err = NULL;
7211 struct got_object_id *commit_id = NULL;
7213 *new_view = NULL;
7215 err = resolve_reflist_entry(&commit_id, re, repo);
7216 if (err) {
7217 if (err->code != GOT_ERR_OBJ_TYPE)
7218 return err;
7219 else
7220 return NULL;
7223 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7224 if (log_view == NULL) {
7225 err = got_error_from_errno("view_open");
7226 goto done;
7229 err = open_log_view(log_view, commit_id, repo,
7230 got_ref_get_name(re->ref), "", 0);
7231 done:
7232 if (err)
7233 view_close(log_view);
7234 else
7235 *new_view = log_view;
7236 free(commit_id);
7237 return err;
7240 static void
7241 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7243 struct tog_reflist_entry *re;
7244 int i = 0;
7246 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7247 return;
7249 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7250 while (i++ < maxscroll) {
7251 if (re == NULL)
7252 break;
7253 s->first_displayed_entry = re;
7254 re = TAILQ_PREV(re, tog_reflist_head, entry);
7258 static const struct got_error *
7259 ref_scroll_down(struct tog_view *view, int maxscroll)
7261 struct tog_ref_view_state *s = &view->state.ref;
7262 struct tog_reflist_entry *next, *last;
7263 int n = 0;
7265 if (s->first_displayed_entry)
7266 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7267 else
7268 next = TAILQ_FIRST(&s->refs);
7270 last = s->last_displayed_entry;
7271 while (next && n++ < maxscroll) {
7272 if (last)
7273 last = TAILQ_NEXT(last, entry);
7274 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7275 s->first_displayed_entry = next;
7276 next = TAILQ_NEXT(next, entry);
7280 return NULL;
7283 static const struct got_error *
7284 search_start_ref_view(struct tog_view *view)
7286 struct tog_ref_view_state *s = &view->state.ref;
7288 s->matched_entry = NULL;
7289 return NULL;
7292 static int
7293 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7295 regmatch_t regmatch;
7297 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7298 0) == 0;
7301 static const struct got_error *
7302 search_next_ref_view(struct tog_view *view)
7304 struct tog_ref_view_state *s = &view->state.ref;
7305 struct tog_reflist_entry *re = NULL;
7307 if (!view->searching) {
7308 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7309 return NULL;
7312 if (s->matched_entry) {
7313 if (view->searching == TOG_SEARCH_FORWARD) {
7314 if (s->selected_entry)
7315 re = TAILQ_NEXT(s->selected_entry, entry);
7316 else
7317 re = TAILQ_PREV(s->selected_entry,
7318 tog_reflist_head, entry);
7319 } else {
7320 if (s->selected_entry == NULL)
7321 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7322 else
7323 re = TAILQ_PREV(s->selected_entry,
7324 tog_reflist_head, entry);
7326 } else {
7327 if (s->selected_entry)
7328 re = s->selected_entry;
7329 else if (view->searching == TOG_SEARCH_FORWARD)
7330 re = TAILQ_FIRST(&s->refs);
7331 else
7332 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7335 while (1) {
7336 if (re == NULL) {
7337 if (s->matched_entry == NULL) {
7338 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7339 return NULL;
7341 if (view->searching == TOG_SEARCH_FORWARD)
7342 re = TAILQ_FIRST(&s->refs);
7343 else
7344 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7347 if (match_reflist_entry(re, &view->regex)) {
7348 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7349 s->matched_entry = re;
7350 break;
7353 if (view->searching == TOG_SEARCH_FORWARD)
7354 re = TAILQ_NEXT(re, entry);
7355 else
7356 re = TAILQ_PREV(re, tog_reflist_head, entry);
7359 if (s->matched_entry) {
7360 s->first_displayed_entry = s->matched_entry;
7361 s->selected = 0;
7364 return NULL;
7367 static const struct got_error *
7368 show_ref_view(struct tog_view *view)
7370 const struct got_error *err = NULL;
7371 struct tog_ref_view_state *s = &view->state.ref;
7372 struct tog_reflist_entry *re;
7373 char *line = NULL;
7374 wchar_t *wline;
7375 struct tog_color *tc;
7376 int width, n;
7377 int limit = view->nlines;
7379 werase(view->window);
7381 s->ndisplayed = 0;
7382 if (view_is_hsplit_top(view))
7383 --limit; /* border */
7385 if (limit == 0)
7386 return NULL;
7388 re = s->first_displayed_entry;
7390 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7391 s->nrefs) == -1)
7392 return got_error_from_errno("asprintf");
7394 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7395 if (err) {
7396 free(line);
7397 return err;
7399 if (view_needs_focus_indication(view))
7400 wstandout(view->window);
7401 waddwstr(view->window, wline);
7402 if (view_needs_focus_indication(view))
7403 wstandend(view->window);
7404 free(wline);
7405 wline = NULL;
7406 free(line);
7407 line = NULL;
7408 if (width < view->ncols - 1)
7409 waddch(view->window, '\n');
7410 if (--limit <= 0)
7411 return NULL;
7413 n = 0;
7414 while (re && limit > 0) {
7415 char *line = NULL;
7416 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7418 if (s->show_date) {
7419 struct got_commit_object *ci;
7420 struct got_tag_object *tag;
7421 struct got_object_id *id;
7422 struct tm tm;
7423 time_t t;
7425 err = got_ref_resolve(&id, s->repo, re->ref);
7426 if (err)
7427 return err;
7428 err = got_object_open_as_tag(&tag, s->repo, id);
7429 if (err) {
7430 if (err->code != GOT_ERR_OBJ_TYPE) {
7431 free(id);
7432 return err;
7434 err = got_object_open_as_commit(&ci, s->repo,
7435 id);
7436 if (err) {
7437 free(id);
7438 return err;
7440 t = got_object_commit_get_committer_time(ci);
7441 got_object_commit_close(ci);
7442 } else {
7443 t = got_object_tag_get_tagger_time(tag);
7444 got_object_tag_close(tag);
7446 free(id);
7447 if (gmtime_r(&t, &tm) == NULL)
7448 return got_error_from_errno("gmtime_r");
7449 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7450 return got_error(GOT_ERR_NO_SPACE);
7452 if (got_ref_is_symbolic(re->ref)) {
7453 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7454 ymd : "", got_ref_get_name(re->ref),
7455 got_ref_get_symref_target(re->ref)) == -1)
7456 return got_error_from_errno("asprintf");
7457 } else if (s->show_ids) {
7458 struct got_object_id *id;
7459 char *id_str;
7460 err = got_ref_resolve(&id, s->repo, re->ref);
7461 if (err)
7462 return err;
7463 err = got_object_id_str(&id_str, id);
7464 if (err) {
7465 free(id);
7466 return err;
7468 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7469 got_ref_get_name(re->ref), id_str) == -1) {
7470 err = got_error_from_errno("asprintf");
7471 free(id);
7472 free(id_str);
7473 return err;
7475 free(id);
7476 free(id_str);
7477 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7478 got_ref_get_name(re->ref)) == -1)
7479 return got_error_from_errno("asprintf");
7481 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7482 0, 0);
7483 if (err) {
7484 free(line);
7485 return err;
7487 if (n == s->selected) {
7488 if (view->focussed)
7489 wstandout(view->window);
7490 s->selected_entry = re;
7492 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7493 if (tc)
7494 wattr_on(view->window,
7495 COLOR_PAIR(tc->colorpair), NULL);
7496 waddwstr(view->window, wline);
7497 if (tc)
7498 wattr_off(view->window,
7499 COLOR_PAIR(tc->colorpair), NULL);
7500 if (width < view->ncols - 1)
7501 waddch(view->window, '\n');
7502 if (n == s->selected && view->focussed)
7503 wstandend(view->window);
7504 free(line);
7505 free(wline);
7506 wline = NULL;
7507 n++;
7508 s->ndisplayed++;
7509 s->last_displayed_entry = re;
7511 limit--;
7512 re = TAILQ_NEXT(re, entry);
7515 view_border(view);
7516 return err;
7519 static const struct got_error *
7520 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7521 struct tog_reflist_entry *re, struct got_repository *repo)
7523 const struct got_error *err = NULL;
7524 struct got_object_id *commit_id = NULL;
7525 struct tog_view *tree_view;
7527 *new_view = NULL;
7529 err = resolve_reflist_entry(&commit_id, re, repo);
7530 if (err) {
7531 if (err->code != GOT_ERR_OBJ_TYPE)
7532 return err;
7533 else
7534 return NULL;
7538 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7539 if (tree_view == NULL) {
7540 err = got_error_from_errno("view_open");
7541 goto done;
7544 err = open_tree_view(tree_view, commit_id,
7545 got_ref_get_name(re->ref), repo);
7546 if (err)
7547 goto done;
7549 *new_view = tree_view;
7550 done:
7551 free(commit_id);
7552 return err;
7554 static const struct got_error *
7555 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7557 const struct got_error *err = NULL;
7558 struct tog_ref_view_state *s = &view->state.ref;
7559 struct tog_reflist_entry *re;
7560 int n, nscroll = view->nlines - 1;
7562 switch (ch) {
7563 case 'i':
7564 s->show_ids = !s->show_ids;
7565 view->count = 0;
7566 break;
7567 case 'm':
7568 s->show_date = !s->show_date;
7569 view->count = 0;
7570 break;
7571 case 'o':
7572 s->sort_by_date = !s->sort_by_date;
7573 view->count = 0;
7574 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7575 got_ref_cmp_by_commit_timestamp_descending :
7576 tog_ref_cmp_by_name, s->repo);
7577 if (err)
7578 break;
7579 got_reflist_object_id_map_free(tog_refs_idmap);
7580 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7581 &tog_refs, s->repo);
7582 if (err)
7583 break;
7584 ref_view_free_refs(s);
7585 err = ref_view_load_refs(s);
7586 break;
7587 case KEY_ENTER:
7588 case '\r':
7589 view->count = 0;
7590 if (!s->selected_entry)
7591 break;
7592 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7593 break;
7594 case 'T':
7595 view->count = 0;
7596 if (!s->selected_entry)
7597 break;
7598 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7599 break;
7600 case 'g':
7601 case KEY_HOME:
7602 s->selected = 0;
7603 view->count = 0;
7604 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7605 break;
7606 case 'G':
7607 case KEY_END: {
7608 int eos = view->nlines - 1;
7610 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7611 --eos; /* border */
7612 s->selected = 0;
7613 view->count = 0;
7614 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7615 for (n = 0; n < eos; n++) {
7616 if (re == NULL)
7617 break;
7618 s->first_displayed_entry = re;
7619 re = TAILQ_PREV(re, tog_reflist_head, entry);
7621 if (n > 0)
7622 s->selected = n - 1;
7623 break;
7625 case 'k':
7626 case KEY_UP:
7627 case CTRL('p'):
7628 if (s->selected > 0) {
7629 s->selected--;
7630 break;
7632 ref_scroll_up(s, 1);
7633 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7634 view->count = 0;
7635 break;
7636 case CTRL('u'):
7637 case 'u':
7638 nscroll /= 2;
7639 /* FALL THROUGH */
7640 case KEY_PPAGE:
7641 case CTRL('b'):
7642 case 'b':
7643 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7644 s->selected -= MIN(nscroll, s->selected);
7645 ref_scroll_up(s, MAX(0, nscroll));
7646 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7647 view->count = 0;
7648 break;
7649 case 'j':
7650 case KEY_DOWN:
7651 case CTRL('n'):
7652 if (s->selected < s->ndisplayed - 1) {
7653 s->selected++;
7654 break;
7656 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7657 /* can't scroll any further */
7658 view->count = 0;
7659 break;
7661 ref_scroll_down(view, 1);
7662 break;
7663 case CTRL('d'):
7664 case 'd':
7665 nscroll /= 2;
7666 /* FALL THROUGH */
7667 case KEY_NPAGE:
7668 case CTRL('f'):
7669 case 'f':
7670 case ' ':
7671 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7672 /* can't scroll any further; move cursor down */
7673 if (s->selected < s->ndisplayed - 1)
7674 s->selected += MIN(nscroll,
7675 s->ndisplayed - s->selected - 1);
7676 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7677 s->selected += s->ndisplayed - s->selected - 1;
7678 view->count = 0;
7679 break;
7681 ref_scroll_down(view, nscroll);
7682 break;
7683 case CTRL('l'):
7684 view->count = 0;
7685 tog_free_refs();
7686 err = tog_load_refs(s->repo, s->sort_by_date);
7687 if (err)
7688 break;
7689 ref_view_free_refs(s);
7690 err = ref_view_load_refs(s);
7691 break;
7692 case KEY_RESIZE:
7693 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7694 s->selected = view->nlines - 2;
7695 break;
7696 default:
7697 view->count = 0;
7698 break;
7701 return err;
7704 __dead static void
7705 usage_ref(void)
7707 endwin();
7708 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7709 getprogname());
7710 exit(1);
7713 static const struct got_error *
7714 cmd_ref(int argc, char *argv[])
7716 const struct got_error *error;
7717 struct got_repository *repo = NULL;
7718 struct got_worktree *worktree = NULL;
7719 char *cwd = NULL, *repo_path = NULL;
7720 int ch;
7721 struct tog_view *view;
7722 int *pack_fds = NULL;
7724 while ((ch = getopt(argc, argv, "r:")) != -1) {
7725 switch (ch) {
7726 case 'r':
7727 repo_path = realpath(optarg, NULL);
7728 if (repo_path == NULL)
7729 return got_error_from_errno2("realpath",
7730 optarg);
7731 break;
7732 default:
7733 usage_ref();
7734 /* NOTREACHED */
7738 argc -= optind;
7739 argv += optind;
7741 if (argc > 1)
7742 usage_ref();
7744 error = got_repo_pack_fds_open(&pack_fds);
7745 if (error != NULL)
7746 goto done;
7748 if (repo_path == NULL) {
7749 cwd = getcwd(NULL, 0);
7750 if (cwd == NULL)
7751 return got_error_from_errno("getcwd");
7752 error = got_worktree_open(&worktree, cwd);
7753 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7754 goto done;
7755 if (worktree)
7756 repo_path =
7757 strdup(got_worktree_get_repo_path(worktree));
7758 else
7759 repo_path = strdup(cwd);
7760 if (repo_path == NULL) {
7761 error = got_error_from_errno("strdup");
7762 goto done;
7766 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7767 if (error != NULL)
7768 goto done;
7770 init_curses();
7772 error = apply_unveil(got_repo_get_path(repo), NULL);
7773 if (error)
7774 goto done;
7776 error = tog_load_refs(repo, 0);
7777 if (error)
7778 goto done;
7780 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7781 if (view == NULL) {
7782 error = got_error_from_errno("view_open");
7783 goto done;
7786 error = open_ref_view(view, repo);
7787 if (error)
7788 goto done;
7790 if (worktree) {
7791 /* Release work tree lock. */
7792 got_worktree_close(worktree);
7793 worktree = NULL;
7795 error = view_loop(view);
7796 done:
7797 free(repo_path);
7798 free(cwd);
7799 if (repo) {
7800 const struct got_error *close_err = got_repo_close(repo);
7801 if (close_err)
7802 error = close_err;
7804 if (pack_fds) {
7805 const struct got_error *pack_err =
7806 got_repo_pack_fds_close(pack_fds);
7807 if (error == NULL)
7808 error = pack_err;
7810 tog_free_refs();
7811 return error;
7814 static const struct got_error *
7815 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
7816 enum tog_view_type request, int y, int x)
7818 const struct got_error *err = NULL;
7820 *new_view = NULL;
7822 switch (request) {
7823 case TOG_VIEW_DIFF:
7824 if (view->type == TOG_VIEW_LOG) {
7825 struct tog_log_view_state *s = &view->state.log;
7827 err = open_diff_view_for_commit(new_view, y, x,
7828 s->selected_entry->commit, s->selected_entry->id,
7829 view, s->repo);
7830 } else
7831 return got_error_msg(GOT_ERR_NOT_IMPL,
7832 "parent/child view pair not supported");
7833 break;
7834 case TOG_VIEW_BLAME:
7835 if (view->type == TOG_VIEW_TREE) {
7836 struct tog_tree_view_state *s = &view->state.tree;
7838 err = blame_tree_entry(new_view, y, x,
7839 s->selected_entry, &s->parents, s->commit_id,
7840 s->repo);
7841 } else
7842 return got_error_msg(GOT_ERR_NOT_IMPL,
7843 "parent/child view pair not supported");
7844 break;
7845 case TOG_VIEW_LOG:
7846 if (view->type == TOG_VIEW_BLAME)
7847 err = log_annotated_line(new_view, y, x,
7848 view->state.blame.repo, view->state.blame.id_to_log);
7849 else if (view->type == TOG_VIEW_TREE)
7850 err = log_selected_tree_entry(new_view, y, x,
7851 &view->state.tree);
7852 else if (view->type == TOG_VIEW_REF)
7853 err = log_ref_entry(new_view, y, x,
7854 view->state.ref.selected_entry,
7855 view->state.ref.repo);
7856 else
7857 return got_error_msg(GOT_ERR_NOT_IMPL,
7858 "parent/child view pair not supported");
7859 break;
7860 case TOG_VIEW_TREE:
7861 if (view->type == TOG_VIEW_LOG)
7862 err = browse_commit_tree(new_view, y, x,
7863 view->state.log.selected_entry,
7864 view->state.log.in_repo_path,
7865 view->state.log.head_ref_name,
7866 view->state.log.repo);
7867 else if (view->type == TOG_VIEW_REF)
7868 err = browse_ref_tree(new_view, y, x,
7869 view->state.ref.selected_entry,
7870 view->state.ref.repo);
7871 else
7872 return got_error_msg(GOT_ERR_NOT_IMPL,
7873 "parent/child view pair not supported");
7874 break;
7875 case TOG_VIEW_REF:
7876 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
7877 if (*new_view == NULL)
7878 return got_error_from_errno("view_open");
7879 if (view->type == TOG_VIEW_LOG)
7880 err = open_ref_view(*new_view, view->state.log.repo);
7881 else if (view->type == TOG_VIEW_TREE)
7882 err = open_ref_view(*new_view, view->state.tree.repo);
7883 else
7884 err = got_error_msg(GOT_ERR_NOT_IMPL,
7885 "parent/child view pair not supported");
7886 if (err)
7887 view_close(*new_view);
7888 break;
7889 default:
7890 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
7893 return err;
7897 * If view was scrolled down to move the selected line into view when opening a
7898 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7900 static void
7901 offset_selection_up(struct tog_view *view)
7903 switch (view->type) {
7904 case TOG_VIEW_BLAME: {
7905 struct tog_blame_view_state *s = &view->state.blame;
7906 if (s->first_displayed_line == 1) {
7907 s->selected_line = MAX(s->selected_line - view->offset,
7908 1);
7909 break;
7911 if (s->first_displayed_line > view->offset)
7912 s->first_displayed_line -= view->offset;
7913 else
7914 s->first_displayed_line = 1;
7915 s->selected_line += view->offset;
7916 break;
7918 case TOG_VIEW_LOG:
7919 log_scroll_up(&view->state.log, view->offset);
7920 view->state.log.selected += view->offset;
7921 break;
7922 case TOG_VIEW_REF:
7923 ref_scroll_up(&view->state.ref, view->offset);
7924 view->state.ref.selected += view->offset;
7925 break;
7926 case TOG_VIEW_TREE:
7927 tree_scroll_up(&view->state.tree, view->offset);
7928 view->state.tree.selected += view->offset;
7929 break;
7930 default:
7931 break;
7934 view->offset = 0;
7938 * If the selected line is in the section of screen covered by the bottom split,
7939 * scroll down offset lines to move it into view and index its new position.
7941 static const struct got_error *
7942 offset_selection_down(struct tog_view *view)
7944 const struct got_error *err = NULL;
7945 const struct got_error *(*scrolld)(struct tog_view *, int);
7946 int *selected = NULL;
7947 int header, offset;
7949 switch (view->type) {
7950 case TOG_VIEW_BLAME: {
7951 struct tog_blame_view_state *s = &view->state.blame;
7952 header = 3;
7953 scrolld = NULL;
7954 if (s->selected_line > view->nlines - header) {
7955 offset = abs(view->nlines - s->selected_line - header);
7956 s->first_displayed_line += offset;
7957 s->selected_line -= offset;
7958 view->offset = offset;
7960 break;
7962 case TOG_VIEW_LOG: {
7963 struct tog_log_view_state *s = &view->state.log;
7964 scrolld = &log_scroll_down;
7965 header = view_is_parent_view(view) ? 3 : 2;
7966 selected = &s->selected;
7967 break;
7969 case TOG_VIEW_REF: {
7970 struct tog_ref_view_state *s = &view->state.ref;
7971 scrolld = &ref_scroll_down;
7972 header = 3;
7973 selected = &s->selected;
7974 break;
7976 case TOG_VIEW_TREE: {
7977 struct tog_tree_view_state *s = &view->state.tree;
7978 scrolld = &tree_scroll_down;
7979 header = 5;
7980 selected = &s->selected;
7981 break;
7983 default:
7984 selected = NULL;
7985 scrolld = NULL;
7986 header = 0;
7987 break;
7990 if (selected && *selected > view->nlines - header) {
7991 offset = abs(view->nlines - *selected - header);
7992 view->offset = offset;
7993 if (scrolld && offset) {
7994 err = scrolld(view, offset);
7995 *selected -= offset;
7999 return err;
8002 static void
8003 list_commands(FILE *fp)
8005 size_t i;
8007 fprintf(fp, "commands:");
8008 for (i = 0; i < nitems(tog_commands); i++) {
8009 const struct tog_cmd *cmd = &tog_commands[i];
8010 fprintf(fp, " %s", cmd->name);
8012 fputc('\n', fp);
8015 __dead static void
8016 usage(int hflag, int status)
8018 FILE *fp = (status == 0) ? stdout : stderr;
8020 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8021 getprogname());
8022 if (hflag) {
8023 fprintf(fp, "lazy usage: %s path\n", getprogname());
8024 list_commands(fp);
8026 exit(status);
8029 static char **
8030 make_argv(int argc, ...)
8032 va_list ap;
8033 char **argv;
8034 int i;
8036 va_start(ap, argc);
8038 argv = calloc(argc, sizeof(char *));
8039 if (argv == NULL)
8040 err(1, "calloc");
8041 for (i = 0; i < argc; i++) {
8042 argv[i] = strdup(va_arg(ap, char *));
8043 if (argv[i] == NULL)
8044 err(1, "strdup");
8047 va_end(ap);
8048 return argv;
8052 * Try to convert 'tog path' into a 'tog log path' command.
8053 * The user could simply have mistyped the command rather than knowingly
8054 * provided a path. So check whether argv[0] can in fact be resolved
8055 * to a path in the HEAD commit and print a special error if not.
8056 * This hack is for mpi@ <3
8058 static const struct got_error *
8059 tog_log_with_path(int argc, char *argv[])
8061 const struct got_error *error = NULL, *close_err;
8062 const struct tog_cmd *cmd = NULL;
8063 struct got_repository *repo = NULL;
8064 struct got_worktree *worktree = NULL;
8065 struct got_object_id *commit_id = NULL, *id = NULL;
8066 struct got_commit_object *commit = NULL;
8067 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8068 char *commit_id_str = NULL, **cmd_argv = NULL;
8069 int *pack_fds = NULL;
8071 cwd = getcwd(NULL, 0);
8072 if (cwd == NULL)
8073 return got_error_from_errno("getcwd");
8075 error = got_repo_pack_fds_open(&pack_fds);
8076 if (error != NULL)
8077 goto done;
8079 error = got_worktree_open(&worktree, cwd);
8080 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8081 goto done;
8083 if (worktree)
8084 repo_path = strdup(got_worktree_get_repo_path(worktree));
8085 else
8086 repo_path = strdup(cwd);
8087 if (repo_path == NULL) {
8088 error = got_error_from_errno("strdup");
8089 goto done;
8092 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8093 if (error != NULL)
8094 goto done;
8096 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8097 repo, worktree);
8098 if (error)
8099 goto done;
8101 error = tog_load_refs(repo, 0);
8102 if (error)
8103 goto done;
8104 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8105 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8106 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8107 if (error)
8108 goto done;
8110 if (worktree) {
8111 got_worktree_close(worktree);
8112 worktree = NULL;
8115 error = got_object_open_as_commit(&commit, repo, commit_id);
8116 if (error)
8117 goto done;
8119 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8120 if (error) {
8121 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8122 goto done;
8123 fprintf(stderr, "%s: '%s' is no known command or path\n",
8124 getprogname(), argv[0]);
8125 usage(1, 1);
8126 /* not reached */
8129 close_err = got_repo_close(repo);
8130 if (error == NULL)
8131 error = close_err;
8132 repo = NULL;
8134 error = got_object_id_str(&commit_id_str, commit_id);
8135 if (error)
8136 goto done;
8138 cmd = &tog_commands[0]; /* log */
8139 argc = 4;
8140 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8141 error = cmd->cmd_main(argc, cmd_argv);
8142 done:
8143 if (repo) {
8144 close_err = got_repo_close(repo);
8145 if (error == NULL)
8146 error = close_err;
8148 if (commit)
8149 got_object_commit_close(commit);
8150 if (worktree)
8151 got_worktree_close(worktree);
8152 if (pack_fds) {
8153 const struct got_error *pack_err =
8154 got_repo_pack_fds_close(pack_fds);
8155 if (error == NULL)
8156 error = pack_err;
8158 free(id);
8159 free(commit_id_str);
8160 free(commit_id);
8161 free(cwd);
8162 free(repo_path);
8163 free(in_repo_path);
8164 if (cmd_argv) {
8165 int i;
8166 for (i = 0; i < argc; i++)
8167 free(cmd_argv[i]);
8168 free(cmd_argv);
8170 tog_free_refs();
8171 return error;
8174 int
8175 main(int argc, char *argv[])
8177 const struct got_error *error = NULL;
8178 const struct tog_cmd *cmd = NULL;
8179 int ch, hflag = 0, Vflag = 0;
8180 char **cmd_argv = NULL;
8181 static const struct option longopts[] = {
8182 { "version", no_argument, NULL, 'V' },
8183 { NULL, 0, NULL, 0}
8185 char *diff_algo_str = NULL;
8187 setlocale(LC_CTYPE, "");
8189 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8190 switch (ch) {
8191 case 'h':
8192 hflag = 1;
8193 break;
8194 case 'V':
8195 Vflag = 1;
8196 break;
8197 default:
8198 usage(hflag, 1);
8199 /* NOTREACHED */
8203 argc -= optind;
8204 argv += optind;
8205 optind = 1;
8206 optreset = 1;
8208 if (Vflag) {
8209 got_version_print_str();
8210 return 0;
8213 #ifndef PROFILE
8214 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8215 NULL) == -1)
8216 err(1, "pledge");
8217 #endif
8219 if (argc == 0) {
8220 if (hflag)
8221 usage(hflag, 0);
8222 /* Build an argument vector which runs a default command. */
8223 cmd = &tog_commands[0];
8224 argc = 1;
8225 cmd_argv = make_argv(argc, cmd->name);
8226 } else {
8227 size_t i;
8229 /* Did the user specify a command? */
8230 for (i = 0; i < nitems(tog_commands); i++) {
8231 if (strncmp(tog_commands[i].name, argv[0],
8232 strlen(argv[0])) == 0) {
8233 cmd = &tog_commands[i];
8234 break;
8239 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8240 if (diff_algo_str) {
8241 if (strcasecmp(diff_algo_str, "patience") == 0)
8242 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8243 if (strcasecmp(diff_algo_str, "myers") == 0)
8244 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8247 if (cmd == NULL) {
8248 if (argc != 1)
8249 usage(0, 1);
8250 /* No command specified; try log with a path */
8251 error = tog_log_with_path(argc, argv);
8252 } else {
8253 if (hflag)
8254 cmd->cmd_usage();
8255 else
8256 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8259 endwin();
8260 putchar('\n');
8261 if (cmd_argv) {
8262 int i;
8263 for (i = 0; i < argc; i++)
8264 free(cmd_argv[i]);
8265 free(cmd_argv);
8268 if (error && error->code != GOT_ERR_CANCELLED)
8269 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8270 return 0;