Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #if defined(__FreeBSD__) || defined(__APPLE__)
24 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
25 #endif
26 #include <curses.h>
27 #include <panel.h>
28 #include <locale.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_compat.h"
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 };
113 enum tog_view_mode {
114 TOG_VIEW_SPLIT_NONE,
115 TOG_VIEW_SPLIT_VERT,
116 TOG_VIEW_SPLIT_HRZN
117 };
119 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
121 #define TOG_EOF_STRING "(END)"
123 struct commit_queue_entry {
124 TAILQ_ENTRY(commit_queue_entry) entry;
125 struct got_object_id *id;
126 struct got_commit_object *commit;
127 int idx;
128 };
129 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
130 struct commit_queue {
131 int ncommits;
132 struct commit_queue_head head;
133 };
135 struct tog_color {
136 STAILQ_ENTRY(tog_color) entry;
137 regex_t regex;
138 short colorpair;
139 };
140 STAILQ_HEAD(tog_colors, tog_color);
142 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
143 static struct got_reflist_object_id_map *tog_refs_idmap;
144 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
146 static const struct got_error *
147 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
148 struct got_reference* re2)
150 const char *name1 = got_ref_get_name(re1);
151 const char *name2 = got_ref_get_name(re2);
152 int isbackup1, isbackup2;
154 /* Sort backup refs towards the bottom of the list. */
155 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
156 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
157 if (!isbackup1 && isbackup2) {
158 *cmp = -1;
159 return NULL;
160 } else if (isbackup1 && !isbackup2) {
161 *cmp = 1;
162 return NULL;
165 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
166 return NULL;
169 static const struct got_error *
170 tog_load_refs(struct got_repository *repo, int sort_by_date)
172 const struct got_error *err;
174 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
175 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
176 repo);
177 if (err)
178 return err;
180 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
181 repo);
184 static void
185 tog_free_refs(void)
187 if (tog_refs_idmap) {
188 got_reflist_object_id_map_free(tog_refs_idmap);
189 tog_refs_idmap = NULL;
191 got_ref_list_free(&tog_refs);
194 static const struct got_error *
195 add_color(struct tog_colors *colors, const char *pattern,
196 int idx, short color)
198 const struct got_error *err = NULL;
199 struct tog_color *tc;
200 int regerr = 0;
202 if (idx < 1 || idx > COLOR_PAIRS - 1)
203 return NULL;
205 init_pair(idx, color, -1);
207 tc = calloc(1, sizeof(*tc));
208 if (tc == NULL)
209 return got_error_from_errno("calloc");
210 regerr = regcomp(&tc->regex, pattern,
211 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
212 if (regerr) {
213 static char regerr_msg[512];
214 static char err_msg[512];
215 regerror(regerr, &tc->regex, regerr_msg,
216 sizeof(regerr_msg));
217 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
218 regerr_msg);
219 err = got_error_msg(GOT_ERR_REGEX, err_msg);
220 free(tc);
221 return err;
223 tc->colorpair = idx;
224 STAILQ_INSERT_HEAD(colors, tc, entry);
225 return NULL;
228 static void
229 free_colors(struct tog_colors *colors)
231 struct tog_color *tc;
233 while (!STAILQ_EMPTY(colors)) {
234 tc = STAILQ_FIRST(colors);
235 STAILQ_REMOVE_HEAD(colors, entry);
236 regfree(&tc->regex);
237 free(tc);
241 static struct tog_color *
242 get_color(struct tog_colors *colors, int colorpair)
244 struct tog_color *tc = NULL;
246 STAILQ_FOREACH(tc, colors, entry) {
247 if (tc->colorpair == colorpair)
248 return tc;
251 return NULL;
254 static int
255 default_color_value(const char *envvar)
257 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
258 return COLOR_MAGENTA;
259 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
260 return COLOR_CYAN;
261 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
262 return COLOR_YELLOW;
263 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
264 return COLOR_GREEN;
265 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
266 return COLOR_MAGENTA;
267 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
268 return COLOR_MAGENTA;
269 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
270 return COLOR_CYAN;
271 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
272 return COLOR_GREEN;
273 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
274 return COLOR_GREEN;
275 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
276 return COLOR_CYAN;
277 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
278 return COLOR_YELLOW;
279 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
280 return COLOR_GREEN;
281 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
282 return COLOR_MAGENTA;
283 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
284 return COLOR_YELLOW;
285 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
286 return COLOR_CYAN;
288 return -1;
291 static int
292 get_color_value(const char *envvar)
294 const char *val = getenv(envvar);
296 if (val == NULL)
297 return default_color_value(envvar);
299 if (strcasecmp(val, "black") == 0)
300 return COLOR_BLACK;
301 if (strcasecmp(val, "red") == 0)
302 return COLOR_RED;
303 if (strcasecmp(val, "green") == 0)
304 return COLOR_GREEN;
305 if (strcasecmp(val, "yellow") == 0)
306 return COLOR_YELLOW;
307 if (strcasecmp(val, "blue") == 0)
308 return COLOR_BLUE;
309 if (strcasecmp(val, "magenta") == 0)
310 return COLOR_MAGENTA;
311 if (strcasecmp(val, "cyan") == 0)
312 return COLOR_CYAN;
313 if (strcasecmp(val, "white") == 0)
314 return COLOR_WHITE;
315 if (strcasecmp(val, "default") == 0)
316 return -1;
318 return default_color_value(envvar);
321 struct tog_diff_view_state {
322 struct got_object_id *id1, *id2;
323 const char *label1, *label2;
324 FILE *f, *f1, *f2;
325 int fd1, fd2;
326 int lineno;
327 int first_displayed_line;
328 int last_displayed_line;
329 int eof;
330 int diff_context;
331 int ignore_whitespace;
332 int force_text_diff;
333 struct got_repository *repo;
334 struct got_diff_line *lines;
335 size_t nlines;
336 int matched_line;
337 int selected_line;
339 /* passed from log or blame view; may be NULL */
340 struct tog_view *parent_view;
341 };
343 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
344 static volatile sig_atomic_t tog_thread_error;
346 struct tog_log_thread_args {
347 pthread_cond_t need_commits;
348 pthread_cond_t commit_loaded;
349 int commits_needed;
350 int load_all;
351 struct got_commit_graph *graph;
352 struct commit_queue *commits;
353 const char *in_repo_path;
354 struct got_object_id *start_id;
355 struct got_repository *repo;
356 int *pack_fds;
357 int log_complete;
358 sig_atomic_t *quit;
359 struct commit_queue_entry **first_displayed_entry;
360 struct commit_queue_entry **selected_entry;
361 int *searching;
362 int *search_next_done;
363 regex_t *regex;
364 };
366 struct tog_log_view_state {
367 struct commit_queue commits;
368 struct commit_queue_entry *first_displayed_entry;
369 struct commit_queue_entry *last_displayed_entry;
370 struct commit_queue_entry *selected_entry;
371 int selected;
372 char *in_repo_path;
373 char *head_ref_name;
374 int log_branches;
375 struct got_repository *repo;
376 struct got_object_id *start_id;
377 sig_atomic_t quit;
378 pthread_t thread;
379 struct tog_log_thread_args thread_args;
380 struct commit_queue_entry *matched_entry;
381 struct commit_queue_entry *search_entry;
382 struct tog_colors colors;
383 int use_committer;
384 };
386 #define TOG_COLOR_DIFF_MINUS 1
387 #define TOG_COLOR_DIFF_PLUS 2
388 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
389 #define TOG_COLOR_DIFF_META 4
390 #define TOG_COLOR_TREE_SUBMODULE 5
391 #define TOG_COLOR_TREE_SYMLINK 6
392 #define TOG_COLOR_TREE_DIRECTORY 7
393 #define TOG_COLOR_TREE_EXECUTABLE 8
394 #define TOG_COLOR_COMMIT 9
395 #define TOG_COLOR_AUTHOR 10
396 #define TOG_COLOR_DATE 11
397 #define TOG_COLOR_REFS_HEADS 12
398 #define TOG_COLOR_REFS_TAGS 13
399 #define TOG_COLOR_REFS_REMOTES 14
400 #define TOG_COLOR_REFS_BACKUP 15
402 struct tog_blame_cb_args {
403 struct tog_blame_line *lines; /* one per line */
404 int nlines;
406 struct tog_view *view;
407 struct got_object_id *commit_id;
408 int *quit;
409 };
411 struct tog_blame_thread_args {
412 const char *path;
413 struct got_repository *repo;
414 struct tog_blame_cb_args *cb_args;
415 int *complete;
416 got_cancel_cb cancel_cb;
417 void *cancel_arg;
418 };
420 struct tog_blame {
421 FILE *f;
422 off_t filesize;
423 struct tog_blame_line *lines;
424 int nlines;
425 off_t *line_offsets;
426 pthread_t thread;
427 struct tog_blame_thread_args thread_args;
428 struct tog_blame_cb_args cb_args;
429 const char *path;
430 int *pack_fds;
431 };
433 struct tog_blame_view_state {
434 int first_displayed_line;
435 int last_displayed_line;
436 int selected_line;
437 int last_diffed_line;
438 int blame_complete;
439 int eof;
440 int done;
441 struct got_object_id_queue blamed_commits;
442 struct got_object_qid *blamed_commit;
443 char *path;
444 struct got_repository *repo;
445 struct got_object_id *commit_id;
446 struct got_object_id *id_to_log;
447 struct tog_blame blame;
448 int matched_line;
449 struct tog_colors colors;
450 };
452 struct tog_parent_tree {
453 TAILQ_ENTRY(tog_parent_tree) entry;
454 struct got_tree_object *tree;
455 struct got_tree_entry *first_displayed_entry;
456 struct got_tree_entry *selected_entry;
457 int selected;
458 };
460 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
462 struct tog_tree_view_state {
463 char *tree_label;
464 struct got_object_id *commit_id;/* commit which this tree belongs to */
465 struct got_tree_object *root; /* the commit's root tree entry */
466 struct got_tree_object *tree; /* currently displayed (sub-)tree */
467 struct got_tree_entry *first_displayed_entry;
468 struct got_tree_entry *last_displayed_entry;
469 struct got_tree_entry *selected_entry;
470 int ndisplayed, selected, show_ids;
471 struct tog_parent_trees parents; /* parent trees of current sub-tree */
472 char *head_ref_name;
473 struct got_repository *repo;
474 struct got_tree_entry *matched_entry;
475 struct tog_colors colors;
476 };
478 struct tog_reflist_entry {
479 TAILQ_ENTRY(tog_reflist_entry) entry;
480 struct got_reference *ref;
481 int idx;
482 };
484 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
486 struct tog_ref_view_state {
487 struct tog_reflist_head refs;
488 struct tog_reflist_entry *first_displayed_entry;
489 struct tog_reflist_entry *last_displayed_entry;
490 struct tog_reflist_entry *selected_entry;
491 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
492 struct got_repository *repo;
493 struct tog_reflist_entry *matched_entry;
494 struct tog_colors colors;
495 };
497 /*
498 * We implement two types of views: parent views and child views.
500 * The 'Tab' key switches focus between a parent view and its child view.
501 * Child views are shown side-by-side to their parent view, provided
502 * there is enough screen estate.
504 * When a new view is opened from within a parent view, this new view
505 * becomes a child view of the parent view, replacing any existing child.
507 * When a new view is opened from within a child view, this new view
508 * becomes a parent view which will obscure the views below until the
509 * user quits the new parent view by typing 'q'.
511 * This list of views contains parent views only.
512 * Child views are only pointed to by their parent view.
513 */
514 TAILQ_HEAD(tog_view_list_head, tog_view);
516 struct tog_view {
517 TAILQ_ENTRY(tog_view) entry;
518 WINDOW *window;
519 PANEL *panel;
520 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
521 int resized_y, resized_x; /* begin_y/x based on user resizing */
522 int maxx, x; /* max column and current start column */
523 int lines, cols; /* copies of LINES and COLS */
524 int nscrolled, offset; /* lines scrolled and hsplit line offset */
525 int gline, hiline; /* navigate to and highlight this nG line */
526 int ch, count; /* current keymap and count prefix */
527 int resized; /* set when in a resize event */
528 int focussed; /* Only set on one parent or child view at a time. */
529 int dying;
530 struct tog_view *parent;
531 struct tog_view *child;
533 /*
534 * This flag is initially set on parent views when a new child view
535 * is created. It gets toggled when the 'Tab' key switches focus
536 * between parent and child.
537 * The flag indicates whether focus should be passed on to our child
538 * view if this parent view gets picked for focus after another parent
539 * view was closed. This prevents child views from losing focus in such
540 * situations.
541 */
542 int focus_child;
544 enum tog_view_mode mode;
545 /* type-specific state */
546 enum tog_view_type type;
547 union {
548 struct tog_diff_view_state diff;
549 struct tog_log_view_state log;
550 struct tog_blame_view_state blame;
551 struct tog_tree_view_state tree;
552 struct tog_ref_view_state ref;
553 } state;
555 const struct got_error *(*show)(struct tog_view *);
556 const struct got_error *(*input)(struct tog_view **,
557 struct tog_view *, int);
558 const struct got_error *(*reset)(struct tog_view *);
559 const struct got_error *(*resize)(struct tog_view *, int);
560 const struct got_error *(*close)(struct tog_view *);
562 const struct got_error *(*search_start)(struct tog_view *);
563 const struct got_error *(*search_next)(struct tog_view *);
564 int search_started;
565 int searching;
566 #define TOG_SEARCH_FORWARD 1
567 #define TOG_SEARCH_BACKWARD 2
568 int search_next_done;
569 #define TOG_SEARCH_HAVE_MORE 1
570 #define TOG_SEARCH_NO_MORE 2
571 #define TOG_SEARCH_HAVE_NONE 3
572 regex_t regex;
573 regmatch_t regmatch;
574 };
576 static const struct got_error *open_diff_view(struct tog_view *,
577 struct got_object_id *, struct got_object_id *,
578 const char *, const char *, int, int, int, struct tog_view *,
579 struct got_repository *);
580 static const struct got_error *show_diff_view(struct tog_view *);
581 static const struct got_error *input_diff_view(struct tog_view **,
582 struct tog_view *, int);
583 static const struct got_error *reset_diff_view(struct tog_view *);
584 static const struct got_error* close_diff_view(struct tog_view *);
585 static const struct got_error *search_start_diff_view(struct tog_view *);
586 static const struct got_error *search_next_diff_view(struct tog_view *);
588 static const struct got_error *open_log_view(struct tog_view *,
589 struct got_object_id *, struct got_repository *,
590 const char *, const char *, int);
591 static const struct got_error * show_log_view(struct tog_view *);
592 static const struct got_error *input_log_view(struct tog_view **,
593 struct tog_view *, int);
594 static const struct got_error *resize_log_view(struct tog_view *, int);
595 static const struct got_error *close_log_view(struct tog_view *);
596 static const struct got_error *search_start_log_view(struct tog_view *);
597 static const struct got_error *search_next_log_view(struct tog_view *);
599 static const struct got_error *open_blame_view(struct tog_view *, char *,
600 struct got_object_id *, struct got_repository *);
601 static const struct got_error *show_blame_view(struct tog_view *);
602 static const struct got_error *input_blame_view(struct tog_view **,
603 struct tog_view *, int);
604 static const struct got_error *reset_blame_view(struct tog_view *);
605 static const struct got_error *close_blame_view(struct tog_view *);
606 static const struct got_error *search_start_blame_view(struct tog_view *);
607 static const struct got_error *search_next_blame_view(struct tog_view *);
609 static const struct got_error *open_tree_view(struct tog_view *,
610 struct got_object_id *, const char *, struct got_repository *);
611 static const struct got_error *show_tree_view(struct tog_view *);
612 static const struct got_error *input_tree_view(struct tog_view **,
613 struct tog_view *, int);
614 static const struct got_error *close_tree_view(struct tog_view *);
615 static const struct got_error *search_start_tree_view(struct tog_view *);
616 static const struct got_error *search_next_tree_view(struct tog_view *);
618 static const struct got_error *open_ref_view(struct tog_view *,
619 struct got_repository *);
620 static const struct got_error *show_ref_view(struct tog_view *);
621 static const struct got_error *input_ref_view(struct tog_view **,
622 struct tog_view *, int);
623 static const struct got_error *close_ref_view(struct tog_view *);
624 static const struct got_error *search_start_ref_view(struct tog_view *);
625 static const struct got_error *search_next_ref_view(struct tog_view *);
627 static volatile sig_atomic_t tog_sigwinch_received;
628 static volatile sig_atomic_t tog_sigpipe_received;
629 static volatile sig_atomic_t tog_sigcont_received;
630 static volatile sig_atomic_t tog_sigint_received;
631 static volatile sig_atomic_t tog_sigterm_received;
633 static void
634 tog_sigwinch(int signo)
636 tog_sigwinch_received = 1;
639 static void
640 tog_sigpipe(int signo)
642 tog_sigpipe_received = 1;
645 static void
646 tog_sigcont(int signo)
648 tog_sigcont_received = 1;
651 static void
652 tog_sigint(int signo)
654 tog_sigint_received = 1;
657 static void
658 tog_sigterm(int signo)
660 tog_sigterm_received = 1;
663 static int
664 tog_fatal_signal_received(void)
666 return (tog_sigpipe_received ||
667 tog_sigint_received || tog_sigint_received);
670 static const struct got_error *
671 view_close(struct tog_view *view)
673 const struct got_error *err = NULL, *child_err = NULL;
675 if (view->child) {
676 child_err = view_close(view->child);
677 view->child = NULL;
679 if (view->close)
680 err = view->close(view);
681 if (view->panel)
682 del_panel(view->panel);
683 if (view->window)
684 delwin(view->window);
685 free(view);
686 return err ? err : child_err;
689 static struct tog_view *
690 view_open(int nlines, int ncols, int begin_y, int begin_x,
691 enum tog_view_type type)
693 struct tog_view *view = calloc(1, sizeof(*view));
695 if (view == NULL)
696 return NULL;
698 view->type = type;
699 view->lines = LINES;
700 view->cols = COLS;
701 view->nlines = nlines ? nlines : LINES - begin_y;
702 view->ncols = ncols ? ncols : COLS - begin_x;
703 view->begin_y = begin_y;
704 view->begin_x = begin_x;
705 view->window = newwin(nlines, ncols, begin_y, begin_x);
706 if (view->window == NULL) {
707 view_close(view);
708 return NULL;
710 view->panel = new_panel(view->window);
711 if (view->panel == NULL ||
712 set_panel_userptr(view->panel, view) != OK) {
713 view_close(view);
714 return NULL;
717 keypad(view->window, TRUE);
718 return view;
721 static int
722 view_split_begin_x(int begin_x)
724 if (begin_x > 0 || COLS < 120)
725 return 0;
726 return (COLS - MAX(COLS / 2, 80));
729 /* XXX Stub till we decide what to do. */
730 static int
731 view_split_begin_y(int lines)
733 return lines * HSPLIT_SCALE;
736 static const struct got_error *view_resize(struct tog_view *);
738 static const struct got_error *
739 view_splitscreen(struct tog_view *view)
741 const struct got_error *err = NULL;
743 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
744 if (view->resized_y && view->resized_y < view->lines)
745 view->begin_y = view->resized_y;
746 else
747 view->begin_y = view_split_begin_y(view->nlines);
748 view->begin_x = 0;
749 } else if (!view->resized) {
750 if (view->resized_x && view->resized_x < view->cols - 1 &&
751 view->cols > 119)
752 view->begin_x = view->resized_x;
753 else
754 view->begin_x = view_split_begin_x(0);
755 view->begin_y = 0;
757 view->nlines = LINES - view->begin_y;
758 view->ncols = COLS - view->begin_x;
759 view->lines = LINES;
760 view->cols = COLS;
761 err = view_resize(view);
762 if (err)
763 return err;
765 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
766 view->parent->nlines = view->begin_y;
768 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
769 return got_error_from_errno("mvwin");
771 return NULL;
774 static const struct got_error *
775 view_fullscreen(struct tog_view *view)
777 const struct got_error *err = NULL;
779 view->begin_x = 0;
780 view->begin_y = view->resized ? view->begin_y : 0;
781 view->nlines = view->resized ? view->nlines : LINES;
782 view->ncols = COLS;
783 view->lines = LINES;
784 view->cols = COLS;
785 err = view_resize(view);
786 if (err)
787 return err;
789 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
790 return got_error_from_errno("mvwin");
792 return NULL;
795 static int
796 view_is_parent_view(struct tog_view *view)
798 return view->parent == NULL;
801 static int
802 view_is_splitscreen(struct tog_view *view)
804 return view->begin_x > 0 || view->begin_y > 0;
807 static int
808 view_is_fullscreen(struct tog_view *view)
810 return view->nlines == LINES && view->ncols == COLS;
813 static int
814 view_is_hsplit_top(struct tog_view *view)
816 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
817 view_is_splitscreen(view->child);
820 static void
821 view_border(struct tog_view *view)
823 PANEL *panel;
824 const struct tog_view *view_above;
826 if (view->parent)
827 return view_border(view->parent);
829 panel = panel_above(view->panel);
830 if (panel == NULL)
831 return;
833 view_above = panel_userptr(panel);
834 if (view->mode == TOG_VIEW_SPLIT_HRZN)
835 mvwhline(view->window, view_above->begin_y - 1,
836 view->begin_x, got_locale_is_utf8() ?
837 ACS_HLINE : '-', view->ncols);
838 else
839 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
840 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
843 static const struct got_error *view_init_hsplit(struct tog_view *, int);
844 static const struct got_error *request_log_commits(struct tog_view *);
845 static const struct got_error *offset_selection_down(struct tog_view *);
846 static void offset_selection_up(struct tog_view *);
847 static void view_get_split(struct tog_view *, int *, int *);
849 static const struct got_error *
850 view_resize(struct tog_view *view)
852 const struct got_error *err = NULL;
853 int dif, nlines, ncols;
855 dif = LINES - view->lines; /* line difference */
857 if (view->lines > LINES)
858 nlines = view->nlines - (view->lines - LINES);
859 else
860 nlines = view->nlines + (LINES - view->lines);
861 if (view->cols > COLS)
862 ncols = view->ncols - (view->cols - COLS);
863 else
864 ncols = view->ncols + (COLS - view->cols);
866 if (view->child) {
867 int hs = view->child->begin_y;
869 if (!view_is_fullscreen(view))
870 view->child->begin_x = view_split_begin_x(view->begin_x);
871 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
872 view->child->begin_x == 0) {
873 ncols = COLS;
875 view_fullscreen(view->child);
876 if (view->child->focussed)
877 show_panel(view->child->panel);
878 else
879 show_panel(view->panel);
880 } else {
881 ncols = view->child->begin_x;
883 view_splitscreen(view->child);
884 show_panel(view->child->panel);
886 /*
887 * XXX This is ugly and needs to be moved into the above
888 * logic but "works" for now and my attempts at moving it
889 * break either 'tab' or 'F' key maps in horizontal splits.
890 */
891 if (hs) {
892 err = view_splitscreen(view->child);
893 if (err)
894 return err;
895 if (dif < 0) { /* top split decreased */
896 err = offset_selection_down(view);
897 if (err)
898 return err;
900 view_border(view);
901 update_panels();
902 doupdate();
903 show_panel(view->child->panel);
904 nlines = view->nlines;
906 } else if (view->parent == NULL)
907 ncols = COLS;
909 if (view->resize && dif > 0) {
910 err = view->resize(view, dif);
911 if (err)
912 return err;
915 if (wresize(view->window, nlines, ncols) == ERR)
916 return got_error_from_errno("wresize");
917 if (replace_panel(view->panel, view->window) == ERR)
918 return got_error_from_errno("replace_panel");
919 wclear(view->window);
921 view->nlines = nlines;
922 view->ncols = ncols;
923 view->lines = LINES;
924 view->cols = COLS;
926 return NULL;
929 static const struct got_error *
930 resize_log_view(struct tog_view *view, int increase)
932 struct tog_log_view_state *s = &view->state.log;
933 const struct got_error *err = NULL;
934 int n = 0;
936 if (s->selected_entry)
937 n = s->selected_entry->idx + view->lines - s->selected;
939 /*
940 * Request commits to account for the increased
941 * height so we have enough to populate the view.
942 */
943 if (s->commits.ncommits < n) {
944 view->nscrolled = n - s->commits.ncommits + increase + 1;
945 err = request_log_commits(view);
948 return err;
951 static void
952 view_adjust_offset(struct tog_view *view, int n)
954 if (n == 0)
955 return;
957 if (view->parent && view->parent->offset) {
958 if (view->parent->offset + n >= 0)
959 view->parent->offset += n;
960 else
961 view->parent->offset = 0;
962 } else if (view->offset) {
963 if (view->offset - n >= 0)
964 view->offset -= n;
965 else
966 view->offset = 0;
970 static const struct got_error *
971 view_resize_split(struct tog_view *view, int resize)
973 const struct got_error *err = NULL;
974 struct tog_view *v = NULL;
976 if (view->parent)
977 v = view->parent;
978 else
979 v = view;
981 if (!v->child || !view_is_splitscreen(v->child))
982 return NULL;
984 v->resized = v->child->resized = resize; /* lock for resize event */
986 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
987 if (v->child->resized_y)
988 v->child->begin_y = v->child->resized_y;
989 if (view->parent)
990 v->child->begin_y -= resize;
991 else
992 v->child->begin_y += resize;
993 if (v->child->begin_y < 3) {
994 view->count = 0;
995 v->child->begin_y = 3;
996 } else if (v->child->begin_y > LINES - 1) {
997 view->count = 0;
998 v->child->begin_y = LINES - 1;
1000 v->ncols = COLS;
1001 v->child->ncols = COLS;
1002 view_adjust_offset(view, resize);
1003 err = view_init_hsplit(v, v->child->begin_y);
1004 if (err)
1005 return err;
1006 v->child->resized_y = v->child->begin_y;
1007 } else {
1008 if (v->child->resized_x)
1009 v->child->begin_x = v->child->resized_x;
1010 if (view->parent)
1011 v->child->begin_x -= resize;
1012 else
1013 v->child->begin_x += resize;
1014 if (v->child->begin_x < 11) {
1015 view->count = 0;
1016 v->child->begin_x = 11;
1017 } else if (v->child->begin_x > COLS - 1) {
1018 view->count = 0;
1019 v->child->begin_x = COLS - 1;
1021 v->child->resized_x = v->child->begin_x;
1024 v->child->mode = v->mode;
1025 v->child->nlines = v->lines - v->child->begin_y;
1026 v->child->ncols = v->cols - v->child->begin_x;
1027 v->focus_child = 1;
1029 err = view_fullscreen(v);
1030 if (err)
1031 return err;
1032 err = view_splitscreen(v->child);
1033 if (err)
1034 return err;
1036 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1037 err = offset_selection_down(v->child);
1038 if (err)
1039 return err;
1042 if (v->resize)
1043 err = v->resize(v, 0);
1044 else if (v->child->resize)
1045 err = v->child->resize(v->child, 0);
1047 v->resized = v->child->resized = 0;
1049 return err;
1052 static void
1053 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1055 struct tog_view *v = src->child ? src->child : src;
1057 dst->resized_x = v->resized_x;
1058 dst->resized_y = v->resized_y;
1061 static const struct got_error *
1062 view_close_child(struct tog_view *view)
1064 const struct got_error *err = NULL;
1066 if (view->child == NULL)
1067 return NULL;
1069 err = view_close(view->child);
1070 view->child = NULL;
1071 return err;
1074 static const struct got_error *
1075 view_set_child(struct tog_view *view, struct tog_view *child)
1077 const struct got_error *err = NULL;
1079 view->child = child;
1080 child->parent = view;
1082 err = view_resize(view);
1083 if (err)
1084 return err;
1086 if (view->child->resized_x || view->child->resized_y)
1087 err = view_resize_split(view, 0);
1089 return err;
1092 static const struct got_error *view_dispatch_request(struct tog_view **,
1093 struct tog_view *, enum tog_view_type, int, int);
1095 static const struct got_error *
1096 view_request_new(struct tog_view **requested, struct tog_view *view,
1097 enum tog_view_type request)
1099 struct tog_view *new_view = NULL;
1100 const struct got_error *err;
1101 int y = 0, x = 0;
1103 *requested = NULL;
1105 if (view_is_parent_view(view))
1106 view_get_split(view, &y, &x);
1108 err = view_dispatch_request(&new_view, view, request, y, x);
1109 if (err)
1110 return err;
1112 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN) {
1113 err = view_init_hsplit(view, y);
1114 if (err)
1115 return err;
1118 view->focussed = 0;
1119 new_view->focussed = 1;
1120 new_view->mode = view->mode;
1121 new_view->nlines = view->lines - y;
1123 if (view_is_parent_view(view)) {
1124 view_transfer_size(new_view, view);
1125 err = view_close_child(view);
1126 if (err)
1127 return err;
1128 err = view_set_child(view, new_view);
1129 if (err)
1130 return err;
1131 view->focus_child = 1;
1132 } else
1133 *requested = new_view;
1135 return NULL;
1138 static void
1139 tog_resizeterm(void)
1141 int cols, lines;
1142 struct winsize size;
1144 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1145 cols = 80; /* Default */
1146 lines = 24;
1147 } else {
1148 cols = size.ws_col;
1149 lines = size.ws_row;
1151 resize_term(lines, cols);
1154 static const struct got_error *
1155 view_search_start(struct tog_view *view)
1157 const struct got_error *err = NULL;
1158 struct tog_view *v = view;
1159 char pattern[1024];
1160 int ret;
1162 if (view->search_started) {
1163 regfree(&view->regex);
1164 view->searching = 0;
1165 memset(&view->regmatch, 0, sizeof(view->regmatch));
1167 view->search_started = 0;
1169 if (view->nlines < 1)
1170 return NULL;
1172 if (view_is_hsplit_top(view))
1173 v = view->child;
1175 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1176 wclrtoeol(v->window);
1178 nodelay(view->window, FALSE); /* block for search term input */
1179 nocbreak();
1180 echo();
1181 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1182 wrefresh(v->window);
1183 cbreak();
1184 noecho();
1185 nodelay(view->window, TRUE);
1186 if (ret == ERR)
1187 return NULL;
1189 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1190 err = view->search_start(view);
1191 if (err) {
1192 regfree(&view->regex);
1193 return err;
1195 view->search_started = 1;
1196 view->searching = TOG_SEARCH_FORWARD;
1197 view->search_next_done = 0;
1198 view->search_next(view);
1201 return NULL;
1204 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1205 static const struct got_error *
1206 switch_split(struct tog_view *view)
1208 const struct got_error *err = NULL;
1209 struct tog_view *v = NULL;
1211 if (view->parent)
1212 v = view->parent;
1213 else
1214 v = view;
1216 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1217 v->mode = TOG_VIEW_SPLIT_VERT;
1218 else
1219 v->mode = TOG_VIEW_SPLIT_HRZN;
1221 if (!v->child)
1222 return NULL;
1223 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1224 v->mode = TOG_VIEW_SPLIT_NONE;
1226 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1227 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1228 v->child->begin_y = v->child->resized_y;
1229 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1230 v->child->begin_x = v->child->resized_x;
1233 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1234 v->ncols = COLS;
1235 v->child->ncols = COLS;
1236 v->child->nscrolled = LINES - v->child->nlines;
1238 err = view_init_hsplit(v, v->child->begin_y);
1239 if (err)
1240 return err;
1242 v->child->mode = v->mode;
1243 v->child->nlines = v->lines - v->child->begin_y;
1244 v->focus_child = 1;
1246 err = view_fullscreen(v);
1247 if (err)
1248 return err;
1249 err = view_splitscreen(v->child);
1250 if (err)
1251 return err;
1253 if (v->mode == TOG_VIEW_SPLIT_NONE)
1254 v->mode = TOG_VIEW_SPLIT_VERT;
1255 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1256 err = offset_selection_down(v);
1257 if (err)
1258 return err;
1259 err = offset_selection_down(v->child);
1260 if (err)
1261 return err;
1262 } else {
1263 offset_selection_up(v);
1264 offset_selection_up(v->child);
1266 if (v->resize)
1267 err = v->resize(v, 0);
1268 else if (v->child->resize)
1269 err = v->child->resize(v->child, 0);
1271 return err;
1275 * Compute view->count from numeric input. Assign total to view->count and
1276 * return first non-numeric key entered.
1278 static int
1279 get_compound_key(struct tog_view *view, int c)
1281 struct tog_view *v = view;
1282 int x, n = 0;
1284 if (view_is_hsplit_top(view))
1285 v = view->child;
1286 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1287 v = view->parent;
1289 view->count = 0;
1290 cbreak(); /* block for input */
1291 nodelay(view->window, FALSE);
1292 wmove(v->window, v->nlines - 1, 0);
1293 wclrtoeol(v->window);
1294 waddch(v->window, ':');
1296 do {
1297 x = getcurx(v->window);
1298 if (x != ERR && x < view->ncols) {
1299 waddch(v->window, c);
1300 wrefresh(v->window);
1304 * Don't overflow. Max valid request should be the greatest
1305 * between the longest and total lines; cap at 10 million.
1307 if (n >= 9999999)
1308 n = 9999999;
1309 else
1310 n = n * 10 + (c - '0');
1311 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1313 if (c == 'G' || c == 'g') { /* nG key map */
1314 view->gline = view->hiline = n;
1315 n = 0;
1316 c = 0;
1319 /* Massage excessive or inapplicable values at the input handler. */
1320 view->count = n;
1322 return c;
1325 static const struct got_error *
1326 view_input(struct tog_view **new, int *done, struct tog_view *view,
1327 struct tog_view_list_head *views)
1329 const struct got_error *err = NULL;
1330 struct tog_view *v;
1331 int ch, errcode;
1333 *new = NULL;
1335 /* Clear "no matches" indicator. */
1336 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1337 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1338 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1339 view->count = 0;
1342 if (view->searching && !view->search_next_done) {
1343 errcode = pthread_mutex_unlock(&tog_mutex);
1344 if (errcode)
1345 return got_error_set_errno(errcode,
1346 "pthread_mutex_unlock");
1347 sched_yield();
1348 errcode = pthread_mutex_lock(&tog_mutex);
1349 if (errcode)
1350 return got_error_set_errno(errcode,
1351 "pthread_mutex_lock");
1352 view->search_next(view);
1353 return NULL;
1356 /* Allow threads to make progress while we are waiting for input. */
1357 errcode = pthread_mutex_unlock(&tog_mutex);
1358 if (errcode)
1359 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1360 /* If we have an unfinished count, let C-g or backspace abort. */
1361 if (view->count && --view->count) {
1362 cbreak();
1363 nodelay(view->window, TRUE);
1364 ch = wgetch(view->window);
1365 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1366 view->count = 0;
1367 else
1368 ch = view->ch;
1369 } else {
1370 ch = wgetch(view->window);
1371 if (ch >= '1' && ch <= '9')
1372 view->ch = ch = get_compound_key(view, ch);
1374 if (view->hiline && ch != ERR && ch != 0)
1375 view->hiline = 0; /* key pressed, clear line highlight */
1376 nodelay(view->window, TRUE);
1377 errcode = pthread_mutex_lock(&tog_mutex);
1378 if (errcode)
1379 return got_error_set_errno(errcode, "pthread_mutex_lock");
1381 if (tog_sigwinch_received || tog_sigcont_received) {
1382 tog_resizeterm();
1383 tog_sigwinch_received = 0;
1384 tog_sigcont_received = 0;
1385 TAILQ_FOREACH(v, views, entry) {
1386 err = view_resize(v);
1387 if (err)
1388 return err;
1389 err = v->input(new, v, KEY_RESIZE);
1390 if (err)
1391 return err;
1392 if (v->child) {
1393 err = view_resize(v->child);
1394 if (err)
1395 return err;
1396 err = v->child->input(new, v->child,
1397 KEY_RESIZE);
1398 if (err)
1399 return err;
1400 if (v->child->resized_x || v->child->resized_y) {
1401 err = view_resize_split(v, 0);
1402 if (err)
1403 return err;
1409 switch (ch) {
1410 case '\t':
1411 view->count = 0;
1412 if (view->child) {
1413 view->focussed = 0;
1414 view->child->focussed = 1;
1415 view->focus_child = 1;
1416 } else if (view->parent) {
1417 view->focussed = 0;
1418 view->parent->focussed = 1;
1419 view->parent->focus_child = 0;
1420 if (!view_is_splitscreen(view)) {
1421 if (view->parent->resize) {
1422 err = view->parent->resize(view->parent,
1423 0);
1424 if (err)
1425 return err;
1427 offset_selection_up(view->parent);
1428 err = view_fullscreen(view->parent);
1429 if (err)
1430 return err;
1433 break;
1434 case 'q':
1435 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1436 if (view->parent->resize) {
1437 /* might need more commits to fill fullscreen */
1438 err = view->parent->resize(view->parent, 0);
1439 if (err)
1440 break;
1442 offset_selection_up(view->parent);
1444 err = view->input(new, view, ch);
1445 view->dying = 1;
1446 break;
1447 case 'Q':
1448 *done = 1;
1449 break;
1450 case 'F':
1451 view->count = 0;
1452 if (view_is_parent_view(view)) {
1453 if (view->child == NULL)
1454 break;
1455 if (view_is_splitscreen(view->child)) {
1456 view->focussed = 0;
1457 view->child->focussed = 1;
1458 err = view_fullscreen(view->child);
1459 } else {
1460 err = view_splitscreen(view->child);
1461 if (!err)
1462 err = view_resize_split(view, 0);
1464 if (err)
1465 break;
1466 err = view->child->input(new, view->child,
1467 KEY_RESIZE);
1468 } else {
1469 if (view_is_splitscreen(view)) {
1470 view->parent->focussed = 0;
1471 view->focussed = 1;
1472 err = view_fullscreen(view);
1473 } else {
1474 err = view_splitscreen(view);
1475 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1476 err = view_resize(view->parent);
1477 if (!err)
1478 err = view_resize_split(view, 0);
1480 if (err)
1481 break;
1482 err = view->input(new, view, KEY_RESIZE);
1484 if (err)
1485 break;
1486 if (view->resize) {
1487 err = view->resize(view, 0);
1488 if (err)
1489 break;
1491 if (view->parent)
1492 err = offset_selection_down(view->parent);
1493 if (!err)
1494 err = offset_selection_down(view);
1495 break;
1496 case 'S':
1497 view->count = 0;
1498 err = switch_split(view);
1499 break;
1500 case '-':
1501 err = view_resize_split(view, -1);
1502 break;
1503 case '+':
1504 err = view_resize_split(view, 1);
1505 break;
1506 case KEY_RESIZE:
1507 break;
1508 case '/':
1509 view->count = 0;
1510 if (view->search_start)
1511 view_search_start(view);
1512 else
1513 err = view->input(new, view, ch);
1514 break;
1515 case 'N':
1516 case 'n':
1517 if (view->search_started && view->search_next) {
1518 view->searching = (ch == 'n' ?
1519 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1520 view->search_next_done = 0;
1521 view->search_next(view);
1522 } else
1523 err = view->input(new, view, ch);
1524 break;
1525 case 'A':
1526 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1527 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1528 else
1529 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1530 TAILQ_FOREACH(v, views, entry) {
1531 if (v->reset) {
1532 err = v->reset(v);
1533 if (err)
1534 return err;
1536 if (v->child && v->child->reset) {
1537 err = v->child->reset(v->child);
1538 if (err)
1539 return err;
1542 break;
1543 default:
1544 err = view->input(new, view, ch);
1545 break;
1548 return err;
1551 static int
1552 view_needs_focus_indication(struct tog_view *view)
1554 if (view_is_parent_view(view)) {
1555 if (view->child == NULL || view->child->focussed)
1556 return 0;
1557 if (!view_is_splitscreen(view->child))
1558 return 0;
1559 } else if (!view_is_splitscreen(view))
1560 return 0;
1562 return view->focussed;
1565 static const struct got_error *
1566 view_loop(struct tog_view *view)
1568 const struct got_error *err = NULL;
1569 struct tog_view_list_head views;
1570 struct tog_view *new_view;
1571 char *mode;
1572 int fast_refresh = 10;
1573 int done = 0, errcode;
1575 mode = getenv("TOG_VIEW_SPLIT_MODE");
1576 if (!mode || !(*mode == 'h' || *mode == 'H'))
1577 view->mode = TOG_VIEW_SPLIT_VERT;
1578 else
1579 view->mode = TOG_VIEW_SPLIT_HRZN;
1581 errcode = pthread_mutex_lock(&tog_mutex);
1582 if (errcode)
1583 return got_error_set_errno(errcode, "pthread_mutex_lock");
1585 TAILQ_INIT(&views);
1586 TAILQ_INSERT_HEAD(&views, view, entry);
1588 view->focussed = 1;
1589 err = view->show(view);
1590 if (err)
1591 return err;
1592 update_panels();
1593 doupdate();
1594 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1595 !tog_fatal_signal_received()) {
1596 /* Refresh fast during initialization, then become slower. */
1597 if (fast_refresh && fast_refresh-- == 0)
1598 halfdelay(10); /* switch to once per second */
1600 err = view_input(&new_view, &done, view, &views);
1601 if (err)
1602 break;
1603 if (view->dying) {
1604 struct tog_view *v, *prev = NULL;
1606 if (view_is_parent_view(view))
1607 prev = TAILQ_PREV(view, tog_view_list_head,
1608 entry);
1609 else if (view->parent)
1610 prev = view->parent;
1612 if (view->parent) {
1613 view->parent->child = NULL;
1614 view->parent->focus_child = 0;
1615 /* Restore fullscreen line height. */
1616 view->parent->nlines = view->parent->lines;
1617 err = view_resize(view->parent);
1618 if (err)
1619 break;
1620 /* Make resized splits persist. */
1621 view_transfer_size(view->parent, view);
1622 } else
1623 TAILQ_REMOVE(&views, view, entry);
1625 err = view_close(view);
1626 if (err)
1627 goto done;
1629 view = NULL;
1630 TAILQ_FOREACH(v, &views, entry) {
1631 if (v->focussed)
1632 break;
1634 if (view == NULL && new_view == NULL) {
1635 /* No view has focus. Try to pick one. */
1636 if (prev)
1637 view = prev;
1638 else if (!TAILQ_EMPTY(&views)) {
1639 view = TAILQ_LAST(&views,
1640 tog_view_list_head);
1642 if (view) {
1643 if (view->focus_child) {
1644 view->child->focussed = 1;
1645 view = view->child;
1646 } else
1647 view->focussed = 1;
1651 if (new_view) {
1652 struct tog_view *v, *t;
1653 /* Only allow one parent view per type. */
1654 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1655 if (v->type != new_view->type)
1656 continue;
1657 TAILQ_REMOVE(&views, v, entry);
1658 err = view_close(v);
1659 if (err)
1660 goto done;
1661 break;
1663 TAILQ_INSERT_TAIL(&views, new_view, entry);
1664 view = new_view;
1666 if (view) {
1667 if (view_is_parent_view(view)) {
1668 if (view->child && view->child->focussed)
1669 view = view->child;
1670 } else {
1671 if (view->parent && view->parent->focussed)
1672 view = view->parent;
1674 show_panel(view->panel);
1675 if (view->child && view_is_splitscreen(view->child))
1676 show_panel(view->child->panel);
1677 if (view->parent && view_is_splitscreen(view)) {
1678 err = view->parent->show(view->parent);
1679 if (err)
1680 goto done;
1682 err = view->show(view);
1683 if (err)
1684 goto done;
1685 if (view->child) {
1686 err = view->child->show(view->child);
1687 if (err)
1688 goto done;
1690 update_panels();
1691 doupdate();
1694 done:
1695 while (!TAILQ_EMPTY(&views)) {
1696 const struct got_error *close_err;
1697 view = TAILQ_FIRST(&views);
1698 TAILQ_REMOVE(&views, view, entry);
1699 close_err = view_close(view);
1700 if (close_err && err == NULL)
1701 err = close_err;
1704 errcode = pthread_mutex_unlock(&tog_mutex);
1705 if (errcode && err == NULL)
1706 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1708 return err;
1711 __dead static void
1712 usage_log(void)
1714 endwin();
1715 fprintf(stderr,
1716 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1717 getprogname());
1718 exit(1);
1721 /* Create newly allocated wide-character string equivalent to a byte string. */
1722 static const struct got_error *
1723 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1725 char *vis = NULL;
1726 const struct got_error *err = NULL;
1728 *ws = NULL;
1729 *wlen = mbstowcs(NULL, s, 0);
1730 if (*wlen == (size_t)-1) {
1731 int vislen;
1732 if (errno != EILSEQ)
1733 return got_error_from_errno("mbstowcs");
1735 /* byte string invalid in current encoding; try to "fix" it */
1736 err = got_mbsavis(&vis, &vislen, s);
1737 if (err)
1738 return err;
1739 *wlen = mbstowcs(NULL, vis, 0);
1740 if (*wlen == (size_t)-1) {
1741 err = got_error_from_errno("mbstowcs"); /* give up */
1742 goto done;
1746 *ws = calloc(*wlen + 1, sizeof(**ws));
1747 if (*ws == NULL) {
1748 err = got_error_from_errno("calloc");
1749 goto done;
1752 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1753 err = got_error_from_errno("mbstowcs");
1754 done:
1755 free(vis);
1756 if (err) {
1757 free(*ws);
1758 *ws = NULL;
1759 *wlen = 0;
1761 return err;
1764 static const struct got_error *
1765 expand_tab(char **ptr, const char *src)
1767 char *dst;
1768 size_t len, n, idx = 0, sz = 0;
1770 *ptr = NULL;
1771 n = len = strlen(src);
1772 dst = malloc(n + 1);
1773 if (dst == NULL)
1774 return got_error_from_errno("malloc");
1776 while (idx < len && src[idx]) {
1777 const char c = src[idx];
1779 if (c == '\t') {
1780 size_t nb = TABSIZE - sz % TABSIZE;
1781 char *p;
1783 p = realloc(dst, n + nb);
1784 if (p == NULL) {
1785 free(dst);
1786 return got_error_from_errno("realloc");
1789 dst = p;
1790 n += nb;
1791 memset(dst + sz, ' ', nb);
1792 sz += nb;
1793 } else
1794 dst[sz++] = src[idx];
1795 ++idx;
1798 dst[sz] = '\0';
1799 *ptr = dst;
1800 return NULL;
1804 * Advance at most n columns from wline starting at offset off.
1805 * Return the index to the first character after the span operation.
1806 * Return the combined column width of all spanned wide character in
1807 * *rcol.
1809 static int
1810 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1812 int width, i, cols = 0;
1814 if (n == 0) {
1815 *rcol = cols;
1816 return off;
1819 for (i = off; wline[i] != L'\0'; ++i) {
1820 if (wline[i] == L'\t')
1821 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1822 else
1823 width = wcwidth(wline[i]);
1825 if (width == -1) {
1826 width = 1;
1827 wline[i] = L'.';
1830 if (cols + width > n)
1831 break;
1832 cols += width;
1835 *rcol = cols;
1836 return i;
1840 * Format a line for display, ensuring that it won't overflow a width limit.
1841 * With scrolling, the width returned refers to the scrolled version of the
1842 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1844 static const struct got_error *
1845 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1846 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1848 const struct got_error *err = NULL;
1849 int cols;
1850 wchar_t *wline = NULL;
1851 char *exstr = NULL;
1852 size_t wlen;
1853 int i, scrollx;
1855 *wlinep = NULL;
1856 *widthp = 0;
1858 if (expand) {
1859 err = expand_tab(&exstr, line);
1860 if (err)
1861 return err;
1864 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1865 free(exstr);
1866 if (err)
1867 return err;
1869 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1871 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1872 wline[wlen - 1] = L'\0';
1873 wlen--;
1875 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1876 wline[wlen - 1] = L'\0';
1877 wlen--;
1880 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1881 wline[i] = L'\0';
1883 if (widthp)
1884 *widthp = cols;
1885 if (scrollxp)
1886 *scrollxp = scrollx;
1887 if (err)
1888 free(wline);
1889 else
1890 *wlinep = wline;
1891 return err;
1894 static const struct got_error*
1895 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1896 struct got_object_id *id, struct got_repository *repo)
1898 static const struct got_error *err = NULL;
1899 struct got_reflist_entry *re;
1900 char *s;
1901 const char *name;
1903 *refs_str = NULL;
1905 TAILQ_FOREACH(re, refs, entry) {
1906 struct got_tag_object *tag = NULL;
1907 struct got_object_id *ref_id;
1908 int cmp;
1910 name = got_ref_get_name(re->ref);
1911 if (strcmp(name, GOT_REF_HEAD) == 0)
1912 continue;
1913 if (strncmp(name, "refs/", 5) == 0)
1914 name += 5;
1915 if (strncmp(name, "got/", 4) == 0 &&
1916 strncmp(name, "got/backup/", 11) != 0)
1917 continue;
1918 if (strncmp(name, "heads/", 6) == 0)
1919 name += 6;
1920 if (strncmp(name, "remotes/", 8) == 0) {
1921 name += 8;
1922 s = strstr(name, "/" GOT_REF_HEAD);
1923 if (s != NULL && s[strlen(s)] == '\0')
1924 continue;
1926 err = got_ref_resolve(&ref_id, repo, re->ref);
1927 if (err)
1928 break;
1929 if (strncmp(name, "tags/", 5) == 0) {
1930 err = got_object_open_as_tag(&tag, repo, ref_id);
1931 if (err) {
1932 if (err->code != GOT_ERR_OBJ_TYPE) {
1933 free(ref_id);
1934 break;
1936 /* Ref points at something other than a tag. */
1937 err = NULL;
1938 tag = NULL;
1941 cmp = got_object_id_cmp(tag ?
1942 got_object_tag_get_object_id(tag) : ref_id, id);
1943 free(ref_id);
1944 if (tag)
1945 got_object_tag_close(tag);
1946 if (cmp != 0)
1947 continue;
1948 s = *refs_str;
1949 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1950 s ? ", " : "", name) == -1) {
1951 err = got_error_from_errno("asprintf");
1952 free(s);
1953 *refs_str = NULL;
1954 break;
1956 free(s);
1959 return err;
1962 static const struct got_error *
1963 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1964 int col_tab_align)
1966 char *smallerthan;
1968 smallerthan = strchr(author, '<');
1969 if (smallerthan && smallerthan[1] != '\0')
1970 author = smallerthan + 1;
1971 author[strcspn(author, "@>")] = '\0';
1972 return format_line(wauthor, author_width, NULL, author, 0, limit,
1973 col_tab_align, 0);
1976 static const struct got_error *
1977 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1978 struct got_object_id *id, const size_t date_display_cols,
1979 int author_display_cols)
1981 struct tog_log_view_state *s = &view->state.log;
1982 const struct got_error *err = NULL;
1983 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1984 char *logmsg0 = NULL, *logmsg = NULL;
1985 char *author = NULL;
1986 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1987 int author_width, logmsg_width;
1988 char *newline, *line = NULL;
1989 int col, limit, scrollx;
1990 const int avail = view->ncols;
1991 struct tm tm;
1992 time_t committer_time;
1993 struct tog_color *tc;
1995 committer_time = got_object_commit_get_committer_time(commit);
1996 if (gmtime_r(&committer_time, &tm) == NULL)
1997 return got_error_from_errno("gmtime_r");
1998 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1999 return got_error(GOT_ERR_NO_SPACE);
2001 if (avail <= date_display_cols)
2002 limit = MIN(sizeof(datebuf) - 1, avail);
2003 else
2004 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2005 tc = get_color(&s->colors, TOG_COLOR_DATE);
2006 if (tc)
2007 wattr_on(view->window,
2008 COLOR_PAIR(tc->colorpair), NULL);
2009 waddnstr(view->window, datebuf, limit);
2010 if (tc)
2011 wattr_off(view->window,
2012 COLOR_PAIR(tc->colorpair), NULL);
2013 col = limit;
2014 if (col > avail)
2015 goto done;
2017 if (avail >= 120) {
2018 char *id_str;
2019 err = got_object_id_str(&id_str, id);
2020 if (err)
2021 goto done;
2022 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2023 if (tc)
2024 wattr_on(view->window,
2025 COLOR_PAIR(tc->colorpair), NULL);
2026 wprintw(view->window, "%.8s ", id_str);
2027 if (tc)
2028 wattr_off(view->window,
2029 COLOR_PAIR(tc->colorpair), NULL);
2030 free(id_str);
2031 col += 9;
2032 if (col > avail)
2033 goto done;
2036 if (s->use_committer)
2037 author = strdup(got_object_commit_get_committer(commit));
2038 else
2039 author = strdup(got_object_commit_get_author(commit));
2040 if (author == NULL) {
2041 err = got_error_from_errno("strdup");
2042 goto done;
2044 err = format_author(&wauthor, &author_width, author, avail - col, col);
2045 if (err)
2046 goto done;
2047 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2048 if (tc)
2049 wattr_on(view->window,
2050 COLOR_PAIR(tc->colorpair), NULL);
2051 waddwstr(view->window, wauthor);
2052 if (tc)
2053 wattr_off(view->window,
2054 COLOR_PAIR(tc->colorpair), NULL);
2055 col += author_width;
2056 while (col < avail && author_width < author_display_cols + 2) {
2057 waddch(view->window, ' ');
2058 col++;
2059 author_width++;
2061 if (col > avail)
2062 goto done;
2064 err = got_object_commit_get_logmsg(&logmsg0, commit);
2065 if (err)
2066 goto done;
2067 logmsg = logmsg0;
2068 while (*logmsg == '\n')
2069 logmsg++;
2070 newline = strchr(logmsg, '\n');
2071 if (newline)
2072 *newline = '\0';
2073 limit = avail - col;
2074 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2075 limit--; /* for the border */
2076 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2077 limit, col, 1);
2078 if (err)
2079 goto done;
2080 waddwstr(view->window, &wlogmsg[scrollx]);
2081 col += MAX(logmsg_width, 0);
2082 while (col < avail) {
2083 waddch(view->window, ' ');
2084 col++;
2086 done:
2087 free(logmsg0);
2088 free(wlogmsg);
2089 free(author);
2090 free(wauthor);
2091 free(line);
2092 return err;
2095 static struct commit_queue_entry *
2096 alloc_commit_queue_entry(struct got_commit_object *commit,
2097 struct got_object_id *id)
2099 struct commit_queue_entry *entry;
2101 entry = calloc(1, sizeof(*entry));
2102 if (entry == NULL)
2103 return NULL;
2105 entry->id = id;
2106 entry->commit = commit;
2107 return entry;
2110 static void
2111 pop_commit(struct commit_queue *commits)
2113 struct commit_queue_entry *entry;
2115 entry = TAILQ_FIRST(&commits->head);
2116 TAILQ_REMOVE(&commits->head, entry, entry);
2117 got_object_commit_close(entry->commit);
2118 commits->ncommits--;
2119 /* Don't free entry->id! It is owned by the commit graph. */
2120 free(entry);
2123 static void
2124 free_commits(struct commit_queue *commits)
2126 while (!TAILQ_EMPTY(&commits->head))
2127 pop_commit(commits);
2130 static const struct got_error *
2131 match_commit(int *have_match, struct got_object_id *id,
2132 struct got_commit_object *commit, regex_t *regex)
2134 const struct got_error *err = NULL;
2135 regmatch_t regmatch;
2136 char *id_str = NULL, *logmsg = NULL;
2138 *have_match = 0;
2140 err = got_object_id_str(&id_str, id);
2141 if (err)
2142 return err;
2144 err = got_object_commit_get_logmsg(&logmsg, commit);
2145 if (err)
2146 goto done;
2148 if (regexec(regex, got_object_commit_get_author(commit), 1,
2149 &regmatch, 0) == 0 ||
2150 regexec(regex, got_object_commit_get_committer(commit), 1,
2151 &regmatch, 0) == 0 ||
2152 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2153 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2154 *have_match = 1;
2155 done:
2156 free(id_str);
2157 free(logmsg);
2158 return err;
2161 static const struct got_error *
2162 queue_commits(struct tog_log_thread_args *a)
2164 const struct got_error *err = NULL;
2167 * We keep all commits open throughout the lifetime of the log
2168 * view in order to avoid having to re-fetch commits from disk
2169 * while updating the display.
2171 do {
2172 struct got_object_id *id;
2173 struct got_commit_object *commit;
2174 struct commit_queue_entry *entry;
2175 int errcode;
2177 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2178 NULL, NULL);
2179 if (err || id == NULL)
2180 break;
2182 err = got_object_open_as_commit(&commit, a->repo, id);
2183 if (err)
2184 break;
2185 entry = alloc_commit_queue_entry(commit, id);
2186 if (entry == NULL) {
2187 err = got_error_from_errno("alloc_commit_queue_entry");
2188 break;
2191 errcode = pthread_mutex_lock(&tog_mutex);
2192 if (errcode) {
2193 err = got_error_set_errno(errcode,
2194 "pthread_mutex_lock");
2195 break;
2198 entry->idx = a->commits->ncommits;
2199 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2200 a->commits->ncommits++;
2202 if (*a->searching == TOG_SEARCH_FORWARD &&
2203 !*a->search_next_done) {
2204 int have_match;
2205 err = match_commit(&have_match, id, commit, a->regex);
2206 if (err)
2207 break;
2208 if (have_match)
2209 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2212 errcode = pthread_mutex_unlock(&tog_mutex);
2213 if (errcode && err == NULL)
2214 err = got_error_set_errno(errcode,
2215 "pthread_mutex_unlock");
2216 if (err)
2217 break;
2218 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2220 return err;
2223 static void
2224 select_commit(struct tog_log_view_state *s)
2226 struct commit_queue_entry *entry;
2227 int ncommits = 0;
2229 entry = s->first_displayed_entry;
2230 while (entry) {
2231 if (ncommits == s->selected) {
2232 s->selected_entry = entry;
2233 break;
2235 entry = TAILQ_NEXT(entry, entry);
2236 ncommits++;
2240 static const struct got_error *
2241 draw_commits(struct tog_view *view)
2243 const struct got_error *err = NULL;
2244 struct tog_log_view_state *s = &view->state.log;
2245 struct commit_queue_entry *entry = s->selected_entry;
2246 int limit = view->nlines;
2247 int width;
2248 int ncommits, author_cols = 4;
2249 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2250 char *refs_str = NULL;
2251 wchar_t *wline;
2252 struct tog_color *tc;
2253 static const size_t date_display_cols = 12;
2255 if (view_is_hsplit_top(view))
2256 --limit; /* account for border */
2258 if (s->selected_entry &&
2259 !(view->searching && view->search_next_done == 0)) {
2260 struct got_reflist_head *refs;
2261 err = got_object_id_str(&id_str, s->selected_entry->id);
2262 if (err)
2263 return err;
2264 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2265 s->selected_entry->id);
2266 if (refs) {
2267 err = build_refs_str(&refs_str, refs,
2268 s->selected_entry->id, s->repo);
2269 if (err)
2270 goto done;
2274 if (s->thread_args.commits_needed == 0)
2275 halfdelay(10); /* disable fast refresh */
2277 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2278 if (asprintf(&ncommits_str, " [%d/%d] %s",
2279 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2280 (view->searching && !view->search_next_done) ?
2281 "searching..." : "loading...") == -1) {
2282 err = got_error_from_errno("asprintf");
2283 goto done;
2285 } else {
2286 const char *search_str = NULL;
2288 if (view->searching) {
2289 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2290 search_str = "no more matches";
2291 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2292 search_str = "no matches found";
2293 else if (!view->search_next_done)
2294 search_str = "searching...";
2297 if (asprintf(&ncommits_str, " [%d/%d] %s",
2298 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2299 search_str ? search_str :
2300 (refs_str ? refs_str : "")) == -1) {
2301 err = got_error_from_errno("asprintf");
2302 goto done;
2306 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2307 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2308 "........................................",
2309 s->in_repo_path, ncommits_str) == -1) {
2310 err = got_error_from_errno("asprintf");
2311 header = NULL;
2312 goto done;
2314 } else if (asprintf(&header, "commit %s%s",
2315 id_str ? id_str : "........................................",
2316 ncommits_str) == -1) {
2317 err = got_error_from_errno("asprintf");
2318 header = NULL;
2319 goto done;
2321 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2322 if (err)
2323 goto done;
2325 werase(view->window);
2327 if (view_needs_focus_indication(view))
2328 wstandout(view->window);
2329 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2330 if (tc)
2331 wattr_on(view->window,
2332 COLOR_PAIR(tc->colorpair), NULL);
2333 waddwstr(view->window, wline);
2334 if (tc)
2335 wattr_off(view->window,
2336 COLOR_PAIR(tc->colorpair), NULL);
2337 while (width < view->ncols) {
2338 waddch(view->window, ' ');
2339 width++;
2341 if (view_needs_focus_indication(view))
2342 wstandend(view->window);
2343 free(wline);
2344 if (limit <= 1)
2345 goto done;
2347 /* Grow author column size if necessary, and set view->maxx. */
2348 entry = s->first_displayed_entry;
2349 ncommits = 0;
2350 view->maxx = 0;
2351 while (entry) {
2352 struct got_commit_object *c = entry->commit;
2353 char *author, *eol, *msg, *msg0;
2354 wchar_t *wauthor, *wmsg;
2355 int width;
2356 if (ncommits >= limit - 1)
2357 break;
2358 if (s->use_committer)
2359 author = strdup(got_object_commit_get_committer(c));
2360 else
2361 author = strdup(got_object_commit_get_author(c));
2362 if (author == NULL) {
2363 err = got_error_from_errno("strdup");
2364 goto done;
2366 err = format_author(&wauthor, &width, author, COLS,
2367 date_display_cols);
2368 if (author_cols < width)
2369 author_cols = width;
2370 free(wauthor);
2371 free(author);
2372 if (err)
2373 goto done;
2374 err = got_object_commit_get_logmsg(&msg0, c);
2375 if (err)
2376 goto done;
2377 msg = msg0;
2378 while (*msg == '\n')
2379 ++msg;
2380 if ((eol = strchr(msg, '\n')))
2381 *eol = '\0';
2382 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2383 date_display_cols + author_cols, 0);
2384 if (err)
2385 goto done;
2386 view->maxx = MAX(view->maxx, width);
2387 free(msg0);
2388 free(wmsg);
2389 ncommits++;
2390 entry = TAILQ_NEXT(entry, entry);
2393 entry = s->first_displayed_entry;
2394 s->last_displayed_entry = s->first_displayed_entry;
2395 ncommits = 0;
2396 while (entry) {
2397 if (ncommits >= limit - 1)
2398 break;
2399 if (ncommits == s->selected)
2400 wstandout(view->window);
2401 err = draw_commit(view, entry->commit, entry->id,
2402 date_display_cols, author_cols);
2403 if (ncommits == s->selected)
2404 wstandend(view->window);
2405 if (err)
2406 goto done;
2407 ncommits++;
2408 s->last_displayed_entry = entry;
2409 entry = TAILQ_NEXT(entry, entry);
2412 view_border(view);
2413 done:
2414 free(id_str);
2415 free(refs_str);
2416 free(ncommits_str);
2417 free(header);
2418 return err;
2421 static void
2422 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2424 struct commit_queue_entry *entry;
2425 int nscrolled = 0;
2427 entry = TAILQ_FIRST(&s->commits.head);
2428 if (s->first_displayed_entry == entry)
2429 return;
2431 entry = s->first_displayed_entry;
2432 while (entry && nscrolled < maxscroll) {
2433 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2434 if (entry) {
2435 s->first_displayed_entry = entry;
2436 nscrolled++;
2441 static const struct got_error *
2442 trigger_log_thread(struct tog_view *view, int wait)
2444 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2445 int errcode;
2447 halfdelay(1); /* fast refresh while loading commits */
2449 while (!ta->log_complete && !tog_thread_error &&
2450 (ta->commits_needed > 0 || ta->load_all)) {
2451 /* Wake the log thread. */
2452 errcode = pthread_cond_signal(&ta->need_commits);
2453 if (errcode)
2454 return got_error_set_errno(errcode,
2455 "pthread_cond_signal");
2458 * The mutex will be released while the view loop waits
2459 * in wgetch(), at which time the log thread will run.
2461 if (!wait)
2462 break;
2464 /* Display progress update in log view. */
2465 show_log_view(view);
2466 update_panels();
2467 doupdate();
2469 /* Wait right here while next commit is being loaded. */
2470 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2471 if (errcode)
2472 return got_error_set_errno(errcode,
2473 "pthread_cond_wait");
2475 /* Display progress update in log view. */
2476 show_log_view(view);
2477 update_panels();
2478 doupdate();
2481 return NULL;
2484 static const struct got_error *
2485 request_log_commits(struct tog_view *view)
2487 struct tog_log_view_state *state = &view->state.log;
2488 const struct got_error *err = NULL;
2490 if (state->thread_args.log_complete)
2491 return NULL;
2493 state->thread_args.commits_needed += view->nscrolled;
2494 err = trigger_log_thread(view, 1);
2495 view->nscrolled = 0;
2497 return err;
2500 static const struct got_error *
2501 log_scroll_down(struct tog_view *view, int maxscroll)
2503 struct tog_log_view_state *s = &view->state.log;
2504 const struct got_error *err = NULL;
2505 struct commit_queue_entry *pentry;
2506 int nscrolled = 0, ncommits_needed;
2508 if (s->last_displayed_entry == NULL)
2509 return NULL;
2511 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2512 if (s->commits.ncommits < ncommits_needed &&
2513 !s->thread_args.log_complete) {
2515 * Ask the log thread for required amount of commits.
2517 s->thread_args.commits_needed +=
2518 ncommits_needed - s->commits.ncommits;
2519 err = trigger_log_thread(view, 1);
2520 if (err)
2521 return err;
2524 do {
2525 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2526 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2527 break;
2529 s->last_displayed_entry = pentry ?
2530 pentry : s->last_displayed_entry;;
2532 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2533 if (pentry == NULL)
2534 break;
2535 s->first_displayed_entry = pentry;
2536 } while (++nscrolled < maxscroll);
2538 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2539 view->nscrolled += nscrolled;
2540 else
2541 view->nscrolled = 0;
2543 return err;
2546 static const struct got_error *
2547 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2548 struct got_commit_object *commit, struct got_object_id *commit_id,
2549 struct tog_view *log_view, struct got_repository *repo)
2551 const struct got_error *err;
2552 struct got_object_qid *parent_id;
2553 struct tog_view *diff_view;
2555 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2556 if (diff_view == NULL)
2557 return got_error_from_errno("view_open");
2559 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2560 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2561 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2562 if (err == NULL)
2563 *new_view = diff_view;
2564 return err;
2567 static const struct got_error *
2568 tree_view_visit_subtree(struct tog_tree_view_state *s,
2569 struct got_tree_object *subtree)
2571 struct tog_parent_tree *parent;
2573 parent = calloc(1, sizeof(*parent));
2574 if (parent == NULL)
2575 return got_error_from_errno("calloc");
2577 parent->tree = s->tree;
2578 parent->first_displayed_entry = s->first_displayed_entry;
2579 parent->selected_entry = s->selected_entry;
2580 parent->selected = s->selected;
2581 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2582 s->tree = subtree;
2583 s->selected = 0;
2584 s->first_displayed_entry = NULL;
2585 return NULL;
2588 static const struct got_error *
2589 tree_view_walk_path(struct tog_tree_view_state *s,
2590 struct got_commit_object *commit, const char *path)
2592 const struct got_error *err = NULL;
2593 struct got_tree_object *tree = NULL;
2594 const char *p;
2595 char *slash, *subpath = NULL;
2597 /* Walk the path and open corresponding tree objects. */
2598 p = path;
2599 while (*p) {
2600 struct got_tree_entry *te;
2601 struct got_object_id *tree_id;
2602 char *te_name;
2604 while (p[0] == '/')
2605 p++;
2607 /* Ensure the correct subtree entry is selected. */
2608 slash = strchr(p, '/');
2609 if (slash == NULL)
2610 te_name = strdup(p);
2611 else
2612 te_name = strndup(p, slash - p);
2613 if (te_name == NULL) {
2614 err = got_error_from_errno("strndup");
2615 break;
2617 te = got_object_tree_find_entry(s->tree, te_name);
2618 if (te == NULL) {
2619 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2620 free(te_name);
2621 break;
2623 free(te_name);
2624 s->first_displayed_entry = s->selected_entry = te;
2626 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2627 break; /* jump to this file's entry */
2629 slash = strchr(p, '/');
2630 if (slash)
2631 subpath = strndup(path, slash - path);
2632 else
2633 subpath = strdup(path);
2634 if (subpath == NULL) {
2635 err = got_error_from_errno("strdup");
2636 break;
2639 err = got_object_id_by_path(&tree_id, s->repo, commit,
2640 subpath);
2641 if (err)
2642 break;
2644 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2645 free(tree_id);
2646 if (err)
2647 break;
2649 err = tree_view_visit_subtree(s, tree);
2650 if (err) {
2651 got_object_tree_close(tree);
2652 break;
2654 if (slash == NULL)
2655 break;
2656 free(subpath);
2657 subpath = NULL;
2658 p = slash;
2661 free(subpath);
2662 return err;
2665 static const struct got_error *
2666 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2667 struct commit_queue_entry *entry, const char *path,
2668 const char *head_ref_name, struct got_repository *repo)
2670 const struct got_error *err = NULL;
2671 struct tog_tree_view_state *s;
2672 struct tog_view *tree_view;
2674 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2675 if (tree_view == NULL)
2676 return got_error_from_errno("view_open");
2678 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2679 if (err)
2680 return err;
2681 s = &tree_view->state.tree;
2683 *new_view = tree_view;
2685 if (got_path_is_root_dir(path))
2686 return NULL;
2688 return tree_view_walk_path(s, entry->commit, path);
2691 static const struct got_error *
2692 block_signals_used_by_main_thread(void)
2694 sigset_t sigset;
2695 int errcode;
2697 if (sigemptyset(&sigset) == -1)
2698 return got_error_from_errno("sigemptyset");
2700 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2701 if (sigaddset(&sigset, SIGWINCH) == -1)
2702 return got_error_from_errno("sigaddset");
2703 if (sigaddset(&sigset, SIGCONT) == -1)
2704 return got_error_from_errno("sigaddset");
2705 if (sigaddset(&sigset, SIGINT) == -1)
2706 return got_error_from_errno("sigaddset");
2707 if (sigaddset(&sigset, SIGTERM) == -1)
2708 return got_error_from_errno("sigaddset");
2710 /* ncurses handles SIGTSTP */
2711 if (sigaddset(&sigset, SIGTSTP) == -1)
2712 return got_error_from_errno("sigaddset");
2714 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2715 if (errcode)
2716 return got_error_set_errno(errcode, "pthread_sigmask");
2718 return NULL;
2721 static void *
2722 log_thread(void *arg)
2724 const struct got_error *err = NULL;
2725 int errcode = 0;
2726 struct tog_log_thread_args *a = arg;
2727 int done = 0;
2730 * Sync startup with main thread such that we begin our
2731 * work once view_input() has released the mutex.
2733 errcode = pthread_mutex_lock(&tog_mutex);
2734 if (errcode) {
2735 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2736 return (void *)err;
2739 err = block_signals_used_by_main_thread();
2740 if (err) {
2741 pthread_mutex_unlock(&tog_mutex);
2742 goto done;
2745 while (!done && !err && !tog_fatal_signal_received()) {
2746 errcode = pthread_mutex_unlock(&tog_mutex);
2747 if (errcode) {
2748 err = got_error_set_errno(errcode,
2749 "pthread_mutex_unlock");
2750 goto done;
2752 err = queue_commits(a);
2753 if (err) {
2754 if (err->code != GOT_ERR_ITER_COMPLETED)
2755 goto done;
2756 err = NULL;
2757 done = 1;
2758 } else if (a->commits_needed > 0 && !a->load_all)
2759 a->commits_needed--;
2761 errcode = pthread_mutex_lock(&tog_mutex);
2762 if (errcode) {
2763 err = got_error_set_errno(errcode,
2764 "pthread_mutex_lock");
2765 goto done;
2766 } else if (*a->quit)
2767 done = 1;
2768 else if (*a->first_displayed_entry == NULL) {
2769 *a->first_displayed_entry =
2770 TAILQ_FIRST(&a->commits->head);
2771 *a->selected_entry = *a->first_displayed_entry;
2774 errcode = pthread_cond_signal(&a->commit_loaded);
2775 if (errcode) {
2776 err = got_error_set_errno(errcode,
2777 "pthread_cond_signal");
2778 pthread_mutex_unlock(&tog_mutex);
2779 goto done;
2782 if (done)
2783 a->commits_needed = 0;
2784 else {
2785 if (a->commits_needed == 0 && !a->load_all) {
2786 errcode = pthread_cond_wait(&a->need_commits,
2787 &tog_mutex);
2788 if (errcode) {
2789 err = got_error_set_errno(errcode,
2790 "pthread_cond_wait");
2791 pthread_mutex_unlock(&tog_mutex);
2792 goto done;
2794 if (*a->quit)
2795 done = 1;
2799 a->log_complete = 1;
2800 errcode = pthread_mutex_unlock(&tog_mutex);
2801 if (errcode)
2802 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2803 done:
2804 if (err) {
2805 tog_thread_error = 1;
2806 pthread_cond_signal(&a->commit_loaded);
2808 return (void *)err;
2811 static const struct got_error *
2812 stop_log_thread(struct tog_log_view_state *s)
2814 const struct got_error *err = NULL, *thread_err = NULL;
2815 int errcode;
2817 if (s->thread) {
2818 s->quit = 1;
2819 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2820 if (errcode)
2821 return got_error_set_errno(errcode,
2822 "pthread_cond_signal");
2823 errcode = pthread_mutex_unlock(&tog_mutex);
2824 if (errcode)
2825 return got_error_set_errno(errcode,
2826 "pthread_mutex_unlock");
2827 errcode = pthread_join(s->thread, (void **)&thread_err);
2828 if (errcode)
2829 return got_error_set_errno(errcode, "pthread_join");
2830 errcode = pthread_mutex_lock(&tog_mutex);
2831 if (errcode)
2832 return got_error_set_errno(errcode,
2833 "pthread_mutex_lock");
2834 s->thread = 0; //NULL;
2837 if (s->thread_args.repo) {
2838 err = got_repo_close(s->thread_args.repo);
2839 s->thread_args.repo = NULL;
2842 if (s->thread_args.pack_fds) {
2843 const struct got_error *pack_err =
2844 got_repo_pack_fds_close(s->thread_args.pack_fds);
2845 if (err == NULL)
2846 err = pack_err;
2847 s->thread_args.pack_fds = NULL;
2850 if (s->thread_args.graph) {
2851 got_commit_graph_close(s->thread_args.graph);
2852 s->thread_args.graph = NULL;
2855 return err ? err : thread_err;
2858 static const struct got_error *
2859 close_log_view(struct tog_view *view)
2861 const struct got_error *err = NULL;
2862 struct tog_log_view_state *s = &view->state.log;
2863 int errcode;
2865 err = stop_log_thread(s);
2867 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2868 if (errcode && err == NULL)
2869 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2871 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2872 if (errcode && err == NULL)
2873 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2875 free_commits(&s->commits);
2876 free(s->in_repo_path);
2877 s->in_repo_path = NULL;
2878 free(s->start_id);
2879 s->start_id = NULL;
2880 free(s->head_ref_name);
2881 s->head_ref_name = NULL;
2882 return err;
2885 static const struct got_error *
2886 search_start_log_view(struct tog_view *view)
2888 struct tog_log_view_state *s = &view->state.log;
2890 s->matched_entry = NULL;
2891 s->search_entry = NULL;
2892 return NULL;
2895 static const struct got_error *
2896 search_next_log_view(struct tog_view *view)
2898 const struct got_error *err = NULL;
2899 struct tog_log_view_state *s = &view->state.log;
2900 struct commit_queue_entry *entry;
2902 /* Display progress update in log view. */
2903 show_log_view(view);
2904 update_panels();
2905 doupdate();
2907 if (s->search_entry) {
2908 int errcode, ch;
2909 errcode = pthread_mutex_unlock(&tog_mutex);
2910 if (errcode)
2911 return got_error_set_errno(errcode,
2912 "pthread_mutex_unlock");
2913 ch = wgetch(view->window);
2914 errcode = pthread_mutex_lock(&tog_mutex);
2915 if (errcode)
2916 return got_error_set_errno(errcode,
2917 "pthread_mutex_lock");
2918 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2919 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2920 return NULL;
2922 if (view->searching == TOG_SEARCH_FORWARD)
2923 entry = TAILQ_NEXT(s->search_entry, entry);
2924 else
2925 entry = TAILQ_PREV(s->search_entry,
2926 commit_queue_head, entry);
2927 } else if (s->matched_entry) {
2928 int matched_idx = s->matched_entry->idx;
2929 int selected_idx = s->selected_entry->idx;
2932 * If the user has moved the cursor after we hit a match,
2933 * the position from where we should continue searching
2934 * might have changed.
2936 if (view->searching == TOG_SEARCH_FORWARD) {
2937 if (matched_idx > selected_idx)
2938 entry = TAILQ_NEXT(s->selected_entry, entry);
2939 else
2940 entry = TAILQ_NEXT(s->matched_entry, entry);
2941 } else {
2942 if (matched_idx < selected_idx)
2943 entry = TAILQ_PREV(s->selected_entry,
2944 commit_queue_head, entry);
2945 else
2946 entry = TAILQ_PREV(s->matched_entry,
2947 commit_queue_head, entry);
2949 } else {
2950 entry = s->selected_entry;
2953 while (1) {
2954 int have_match = 0;
2956 if (entry == NULL) {
2957 if (s->thread_args.log_complete ||
2958 view->searching == TOG_SEARCH_BACKWARD) {
2959 view->search_next_done =
2960 (s->matched_entry == NULL ?
2961 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2962 s->search_entry = NULL;
2963 return NULL;
2966 * Poke the log thread for more commits and return,
2967 * allowing the main loop to make progress. Search
2968 * will resume at s->search_entry once we come back.
2970 s->thread_args.commits_needed++;
2971 return trigger_log_thread(view, 0);
2974 err = match_commit(&have_match, entry->id, entry->commit,
2975 &view->regex);
2976 if (err)
2977 break;
2978 if (have_match) {
2979 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2980 s->matched_entry = entry;
2981 break;
2984 s->search_entry = entry;
2985 if (view->searching == TOG_SEARCH_FORWARD)
2986 entry = TAILQ_NEXT(entry, entry);
2987 else
2988 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2991 if (s->matched_entry) {
2992 int cur = s->selected_entry->idx;
2993 while (cur < s->matched_entry->idx) {
2994 err = input_log_view(NULL, view, KEY_DOWN);
2995 if (err)
2996 return err;
2997 cur++;
2999 while (cur > s->matched_entry->idx) {
3000 err = input_log_view(NULL, view, KEY_UP);
3001 if (err)
3002 return err;
3003 cur--;
3007 s->search_entry = NULL;
3009 return NULL;
3012 static const struct got_error *
3013 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3014 struct got_repository *repo, const char *head_ref_name,
3015 const char *in_repo_path, int log_branches)
3017 const struct got_error *err = NULL;
3018 struct tog_log_view_state *s = &view->state.log;
3019 struct got_repository *thread_repo = NULL;
3020 struct got_commit_graph *thread_graph = NULL;
3021 int errcode;
3023 if (in_repo_path != s->in_repo_path) {
3024 free(s->in_repo_path);
3025 s->in_repo_path = strdup(in_repo_path);
3026 if (s->in_repo_path == NULL)
3027 return got_error_from_errno("strdup");
3030 /* The commit queue only contains commits being displayed. */
3031 TAILQ_INIT(&s->commits.head);
3032 s->commits.ncommits = 0;
3034 s->repo = repo;
3035 if (head_ref_name) {
3036 s->head_ref_name = strdup(head_ref_name);
3037 if (s->head_ref_name == NULL) {
3038 err = got_error_from_errno("strdup");
3039 goto done;
3042 s->start_id = got_object_id_dup(start_id);
3043 if (s->start_id == NULL) {
3044 err = got_error_from_errno("got_object_id_dup");
3045 goto done;
3047 s->log_branches = log_branches;
3049 STAILQ_INIT(&s->colors);
3050 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3051 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3052 get_color_value("TOG_COLOR_COMMIT"));
3053 if (err)
3054 goto done;
3055 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3056 get_color_value("TOG_COLOR_AUTHOR"));
3057 if (err) {
3058 free_colors(&s->colors);
3059 goto done;
3061 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3062 get_color_value("TOG_COLOR_DATE"));
3063 if (err) {
3064 free_colors(&s->colors);
3065 goto done;
3069 view->show = show_log_view;
3070 view->input = input_log_view;
3071 view->resize = resize_log_view;
3072 view->close = close_log_view;
3073 view->search_start = search_start_log_view;
3074 view->search_next = search_next_log_view;
3076 if (s->thread_args.pack_fds == NULL) {
3077 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3078 if (err)
3079 goto done;
3081 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3082 s->thread_args.pack_fds);
3083 if (err)
3084 goto done;
3085 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3086 !s->log_branches);
3087 if (err)
3088 goto done;
3089 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3090 s->repo, NULL, NULL);
3091 if (err)
3092 goto done;
3094 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3095 if (errcode) {
3096 err = got_error_set_errno(errcode, "pthread_cond_init");
3097 goto done;
3099 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3100 if (errcode) {
3101 err = got_error_set_errno(errcode, "pthread_cond_init");
3102 goto done;
3105 s->thread_args.commits_needed = view->nlines;
3106 s->thread_args.graph = thread_graph;
3107 s->thread_args.commits = &s->commits;
3108 s->thread_args.in_repo_path = s->in_repo_path;
3109 s->thread_args.start_id = s->start_id;
3110 s->thread_args.repo = thread_repo;
3111 s->thread_args.log_complete = 0;
3112 s->thread_args.quit = &s->quit;
3113 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3114 s->thread_args.selected_entry = &s->selected_entry;
3115 s->thread_args.searching = &view->searching;
3116 s->thread_args.search_next_done = &view->search_next_done;
3117 s->thread_args.regex = &view->regex;
3118 done:
3119 if (err)
3120 close_log_view(view);
3121 return err;
3124 static const struct got_error *
3125 show_log_view(struct tog_view *view)
3127 const struct got_error *err;
3128 struct tog_log_view_state *s = &view->state.log;
3130 if (s->thread == 0) { //NULL) {
3131 int errcode = pthread_create(&s->thread, NULL, log_thread,
3132 &s->thread_args);
3133 if (errcode)
3134 return got_error_set_errno(errcode, "pthread_create");
3135 if (s->thread_args.commits_needed > 0) {
3136 err = trigger_log_thread(view, 1);
3137 if (err)
3138 return err;
3142 return draw_commits(view);
3145 static void
3146 log_move_cursor_up(struct tog_view *view, int page, int home)
3148 struct tog_log_view_state *s = &view->state.log;
3150 if (s->selected_entry->idx == 0)
3151 view->count = 0;
3152 if (s->first_displayed_entry == NULL)
3153 return;
3155 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3156 || home)
3157 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3159 if (!page && !home && s->selected > 0)
3160 --s->selected;
3161 else
3162 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3164 select_commit(s);
3165 return;
3168 static const struct got_error *
3169 log_move_cursor_down(struct tog_view *view, int page)
3171 struct tog_log_view_state *s = &view->state.log;
3172 const struct got_error *err = NULL;
3174 if (s->thread_args.log_complete &&
3175 s->selected_entry->idx >= s->commits.ncommits - 1)
3176 return NULL;
3178 if (!page) {
3179 int eos = view->nlines - 2;
3181 if (view_is_hsplit_top(view))
3182 --eos; /* border consumes the last line */
3183 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3184 ++s->selected;
3185 else
3186 err = log_scroll_down(view, 1);
3187 } else if (s->thread_args.load_all) {
3188 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3189 s->selected += MIN(s->last_displayed_entry->idx -
3190 s->selected_entry->idx, page + 1);
3191 else
3192 err = log_scroll_down(view, MIN(page,
3193 s->commits.ncommits - s->selected_entry->idx - 1));
3194 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3195 } else {
3196 if (s->last_displayed_entry->idx == s->commits.ncommits - 1 &&
3197 s->thread_args.log_complete)
3198 s->selected += MIN(page,
3199 s->commits.ncommits - s->selected_entry->idx - 1);
3200 else
3201 err = log_scroll_down(view, page);
3203 if (err)
3204 return err;
3207 * We might necessarily overshoot in horizontal
3208 * splits; if so, select the last displayed commit.
3210 s->selected = MIN(s->selected,
3211 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3213 select_commit(s);
3215 if (s->thread_args.log_complete &&
3216 s->selected_entry->idx == s->commits.ncommits - 1)
3217 view->count = 0;
3219 return NULL;
3222 static void
3223 view_get_split(struct tog_view *view, int *y, int *x)
3225 *x = 0;
3226 *y = 0;
3228 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3229 if (view->child && view->child->resized_y)
3230 *y = view->child->resized_y;
3231 else if (view->resized_y)
3232 *y = view->resized_y;
3233 else
3234 *y = view_split_begin_y(view->lines);
3235 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3236 if (view->child && view->child->resized_x)
3237 *x = view->child->resized_x;
3238 else if (view->resized_x)
3239 *x = view->resized_x;
3240 else
3241 *x = view_split_begin_x(view->begin_x);
3245 /* Split view horizontally at y and offset view->state->selected line. */
3246 static const struct got_error *
3247 view_init_hsplit(struct tog_view *view, int y)
3249 const struct got_error *err = NULL;
3251 view->nlines = y;
3252 view->ncols = COLS;
3253 err = view_resize(view);
3254 if (err)
3255 return err;
3257 err = offset_selection_down(view);
3259 return err;
3262 static const struct got_error *
3263 log_goto_line(struct tog_view *view, int nlines)
3265 const struct got_error *err = NULL;
3266 struct tog_log_view_state *s = &view->state.log;
3267 int g, idx = s->selected_entry->idx;
3269 g = view->gline;
3270 view->gline = 0;
3272 if (g >= s->first_displayed_entry->idx + 1 &&
3273 g <= s->last_displayed_entry->idx + 1 &&
3274 g - s->first_displayed_entry->idx - 1 < nlines) {
3275 s->selected = g - s->first_displayed_entry->idx - 1;
3276 select_commit(s);
3277 return NULL;
3280 if (idx + 1 < g) {
3281 err = log_move_cursor_down(view, g - idx - 1);
3282 if (!err && g > s->selected_entry->idx + 1)
3283 err = log_move_cursor_down(view,
3284 g - s->first_displayed_entry->idx - 1);
3285 if (err)
3286 return err;
3287 } else if (idx + 1 > g)
3288 log_move_cursor_up(view, idx - g + 1, 0);
3290 if (g < nlines && s->first_displayed_entry->idx == 0)
3291 s->selected = g - 1;
3293 select_commit(s);
3294 return NULL;
3298 static const struct got_error *
3299 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3301 const struct got_error *err = NULL;
3302 struct tog_log_view_state *s = &view->state.log;
3303 struct commit_queue_entry *entry;
3304 int eos, n, nscroll;
3306 if (s->thread_args.load_all) {
3307 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3308 s->thread_args.load_all = 0;
3309 else if (s->thread_args.log_complete) {
3310 err = log_move_cursor_down(view, s->commits.ncommits);
3311 s->thread_args.load_all = 0;
3313 return err;
3316 eos = nscroll = view->nlines - 1;
3317 if (view_is_hsplit_top(view))
3318 --eos; /* border */
3320 if (view->gline)
3321 return log_goto_line(view, eos);
3323 switch (ch) {
3324 case 'q':
3325 s->quit = 1;
3326 break;
3327 case '0':
3328 view->x = 0;
3329 break;
3330 case '$':
3331 view->x = MAX(view->maxx - view->ncols / 2, 0);
3332 view->count = 0;
3333 break;
3334 case KEY_RIGHT:
3335 case 'l':
3336 if (view->x + view->ncols / 2 < view->maxx)
3337 view->x += 2; /* move two columns right */
3338 else
3339 view->count = 0;
3340 break;
3341 case KEY_LEFT:
3342 case 'h':
3343 view->x -= MIN(view->x, 2); /* move two columns back */
3344 if (view->x <= 0)
3345 view->count = 0;
3346 break;
3347 case 'k':
3348 case KEY_UP:
3349 case '<':
3350 case ',':
3351 case CTRL('p'):
3352 log_move_cursor_up(view, 0, 0);
3353 break;
3354 case 'g':
3355 case KEY_HOME:
3356 log_move_cursor_up(view, 0, 1);
3357 view->count = 0;
3358 break;
3359 case CTRL('u'):
3360 case 'u':
3361 nscroll /= 2;
3362 /* FALL THROUGH */
3363 case KEY_PPAGE:
3364 case CTRL('b'):
3365 case 'b':
3366 log_move_cursor_up(view, nscroll, 0);
3367 break;
3368 case 'j':
3369 case KEY_DOWN:
3370 case '>':
3371 case '.':
3372 case CTRL('n'):
3373 err = log_move_cursor_down(view, 0);
3374 break;
3375 case '@':
3376 s->use_committer = !s->use_committer;
3377 break;
3378 case 'G':
3379 case KEY_END: {
3380 /* We don't know yet how many commits, so we're forced to
3381 * traverse them all. */
3382 view->count = 0;
3383 if (!s->thread_args.log_complete) {
3384 s->thread_args.load_all = 1;
3385 return trigger_log_thread(view, 0);
3388 s->selected = 0;
3389 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3390 for (n = 0; n < eos; n++) {
3391 if (entry == NULL)
3392 break;
3393 s->first_displayed_entry = entry;
3394 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3396 if (n > 0)
3397 s->selected = n - 1;
3398 select_commit(s);
3399 break;
3401 case CTRL('d'):
3402 case 'd':
3403 nscroll /= 2;
3404 /* FALL THROUGH */
3405 case KEY_NPAGE:
3406 case CTRL('f'):
3407 case 'f':
3408 case ' ':
3409 err = log_move_cursor_down(view, nscroll);
3410 break;
3411 case KEY_RESIZE:
3412 if (s->selected > view->nlines - 2)
3413 s->selected = view->nlines - 2;
3414 if (s->selected > s->commits.ncommits - 1)
3415 s->selected = s->commits.ncommits - 1;
3416 select_commit(s);
3417 if (s->commits.ncommits < view->nlines - 1 &&
3418 !s->thread_args.log_complete) {
3419 s->thread_args.commits_needed += (view->nlines - 1) -
3420 s->commits.ncommits;
3421 err = trigger_log_thread(view, 1);
3423 break;
3424 case KEY_ENTER:
3425 case '\r':
3426 view->count = 0;
3427 if (s->selected_entry == NULL)
3428 break;
3429 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3430 break;
3431 case 'T':
3432 view->count = 0;
3433 if (s->selected_entry == NULL)
3434 break;
3435 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3436 break;
3437 case KEY_BACKSPACE:
3438 case CTRL('l'):
3439 case 'B':
3440 view->count = 0;
3441 if (ch == KEY_BACKSPACE &&
3442 got_path_is_root_dir(s->in_repo_path))
3443 break;
3444 err = stop_log_thread(s);
3445 if (err)
3446 return err;
3447 if (ch == KEY_BACKSPACE) {
3448 char *parent_path;
3449 err = got_path_dirname(&parent_path, s->in_repo_path);
3450 if (err)
3451 return err;
3452 free(s->in_repo_path);
3453 s->in_repo_path = parent_path;
3454 s->thread_args.in_repo_path = s->in_repo_path;
3455 } else if (ch == CTRL('l')) {
3456 struct got_object_id *start_id;
3457 err = got_repo_match_object_id(&start_id, NULL,
3458 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3459 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3460 if (err)
3461 return err;
3462 free(s->start_id);
3463 s->start_id = start_id;
3464 s->thread_args.start_id = s->start_id;
3465 } else /* 'B' */
3466 s->log_branches = !s->log_branches;
3468 if (s->thread_args.pack_fds == NULL) {
3469 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3470 if (err)
3471 return err;
3473 err = got_repo_open(&s->thread_args.repo,
3474 got_repo_get_path(s->repo), NULL,
3475 s->thread_args.pack_fds);
3476 if (err)
3477 return err;
3478 tog_free_refs();
3479 err = tog_load_refs(s->repo, 0);
3480 if (err)
3481 return err;
3482 err = got_commit_graph_open(&s->thread_args.graph,
3483 s->in_repo_path, !s->log_branches);
3484 if (err)
3485 return err;
3486 err = got_commit_graph_iter_start(s->thread_args.graph,
3487 s->start_id, s->repo, NULL, NULL);
3488 if (err)
3489 return err;
3490 free_commits(&s->commits);
3491 s->first_displayed_entry = NULL;
3492 s->last_displayed_entry = NULL;
3493 s->selected_entry = NULL;
3494 s->selected = 0;
3495 s->thread_args.log_complete = 0;
3496 s->quit = 0;
3497 s->thread_args.commits_needed = view->lines;
3498 s->matched_entry = NULL;
3499 s->search_entry = NULL;
3500 view->offset = 0;
3501 break;
3502 case 'R':
3503 view->count = 0;
3504 err = view_request_new(new_view, view, TOG_VIEW_REF);
3505 break;
3506 default:
3507 view->count = 0;
3508 break;
3511 return err;
3514 static const struct got_error *
3515 apply_unveil(const char *repo_path, const char *worktree_path)
3517 const struct got_error *error;
3519 #ifdef PROFILE
3520 if (unveil("gmon.out", "rwc") != 0)
3521 return got_error_from_errno2("unveil", "gmon.out");
3522 #endif
3523 if (repo_path && unveil(repo_path, "r") != 0)
3524 return got_error_from_errno2("unveil", repo_path);
3526 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3527 return got_error_from_errno2("unveil", worktree_path);
3529 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3530 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3532 error = got_privsep_unveil_exec_helpers();
3533 if (error != NULL)
3534 return error;
3536 if (unveil(NULL, NULL) != 0)
3537 return got_error_from_errno("unveil");
3539 return NULL;
3542 static void
3543 init_curses(void)
3546 * Override default signal handlers before starting ncurses.
3547 * This should prevent ncurses from installing its own
3548 * broken cleanup() signal handler.
3550 signal(SIGWINCH, tog_sigwinch);
3551 signal(SIGPIPE, tog_sigpipe);
3552 signal(SIGCONT, tog_sigcont);
3553 signal(SIGINT, tog_sigint);
3554 signal(SIGTERM, tog_sigterm);
3556 initscr();
3557 cbreak();
3558 halfdelay(1); /* Do fast refresh while initial view is loading. */
3559 noecho();
3560 nonl();
3561 intrflush(stdscr, FALSE);
3562 keypad(stdscr, TRUE);
3563 curs_set(0);
3564 if (getenv("TOG_COLORS") != NULL) {
3565 start_color();
3566 use_default_colors();
3570 static const struct got_error *
3571 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3572 struct got_repository *repo, struct got_worktree *worktree)
3574 const struct got_error *err = NULL;
3576 if (argc == 0) {
3577 *in_repo_path = strdup("/");
3578 if (*in_repo_path == NULL)
3579 return got_error_from_errno("strdup");
3580 return NULL;
3583 if (worktree) {
3584 const char *prefix = got_worktree_get_path_prefix(worktree);
3585 char *p;
3587 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3588 if (err)
3589 return err;
3590 if (asprintf(in_repo_path, "%s%s%s", prefix,
3591 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3592 p) == -1) {
3593 err = got_error_from_errno("asprintf");
3594 *in_repo_path = NULL;
3596 free(p);
3597 } else
3598 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3600 return err;
3603 static const struct got_error *
3604 cmd_log(int argc, char *argv[])
3606 const struct got_error *error;
3607 struct got_repository *repo = NULL;
3608 struct got_worktree *worktree = NULL;
3609 struct got_object_id *start_id = NULL;
3610 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3611 char *start_commit = NULL, *label = NULL;
3612 struct got_reference *ref = NULL;
3613 const char *head_ref_name = NULL;
3614 int ch, log_branches = 0;
3615 struct tog_view *view;
3616 int *pack_fds = NULL;
3618 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3619 switch (ch) {
3620 case 'b':
3621 log_branches = 1;
3622 break;
3623 case 'c':
3624 start_commit = optarg;
3625 break;
3626 case 'r':
3627 repo_path = realpath(optarg, NULL);
3628 if (repo_path == NULL)
3629 return got_error_from_errno2("realpath",
3630 optarg);
3631 break;
3632 default:
3633 usage_log();
3634 /* NOTREACHED */
3638 argc -= optind;
3639 argv += optind;
3641 if (argc > 1)
3642 usage_log();
3644 error = got_repo_pack_fds_open(&pack_fds);
3645 if (error != NULL)
3646 goto done;
3648 if (repo_path == NULL) {
3649 cwd = getcwd(NULL, 0);
3650 if (cwd == NULL)
3651 return got_error_from_errno("getcwd");
3652 error = got_worktree_open(&worktree, cwd);
3653 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3654 goto done;
3655 if (worktree)
3656 repo_path =
3657 strdup(got_worktree_get_repo_path(worktree));
3658 else
3659 repo_path = strdup(cwd);
3660 if (repo_path == NULL) {
3661 error = got_error_from_errno("strdup");
3662 goto done;
3666 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3667 if (error != NULL)
3668 goto done;
3670 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3671 repo, worktree);
3672 if (error)
3673 goto done;
3675 init_curses();
3677 error = apply_unveil(got_repo_get_path(repo),
3678 worktree ? got_worktree_get_root_path(worktree) : NULL);
3679 if (error)
3680 goto done;
3682 /* already loaded by tog_log_with_path()? */
3683 if (TAILQ_EMPTY(&tog_refs)) {
3684 error = tog_load_refs(repo, 0);
3685 if (error)
3686 goto done;
3689 if (start_commit == NULL) {
3690 error = got_repo_match_object_id(&start_id, &label,
3691 worktree ? got_worktree_get_head_ref_name(worktree) :
3692 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3693 if (error)
3694 goto done;
3695 head_ref_name = label;
3696 } else {
3697 error = got_ref_open(&ref, repo, start_commit, 0);
3698 if (error == NULL)
3699 head_ref_name = got_ref_get_name(ref);
3700 else if (error->code != GOT_ERR_NOT_REF)
3701 goto done;
3702 error = got_repo_match_object_id(&start_id, NULL,
3703 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3704 if (error)
3705 goto done;
3708 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3709 if (view == NULL) {
3710 error = got_error_from_errno("view_open");
3711 goto done;
3713 error = open_log_view(view, start_id, repo, head_ref_name,
3714 in_repo_path, log_branches);
3715 if (error)
3716 goto done;
3717 if (worktree) {
3718 /* Release work tree lock. */
3719 got_worktree_close(worktree);
3720 worktree = NULL;
3722 error = view_loop(view);
3723 done:
3724 free(in_repo_path);
3725 free(repo_path);
3726 free(cwd);
3727 free(start_id);
3728 free(label);
3729 if (ref)
3730 got_ref_close(ref);
3731 if (repo) {
3732 const struct got_error *close_err = got_repo_close(repo);
3733 if (error == NULL)
3734 error = close_err;
3736 if (worktree)
3737 got_worktree_close(worktree);
3738 if (pack_fds) {
3739 const struct got_error *pack_err =
3740 got_repo_pack_fds_close(pack_fds);
3741 if (error == NULL)
3742 error = pack_err;
3744 tog_free_refs();
3745 return error;
3748 __dead static void
3749 usage_diff(void)
3751 endwin();
3752 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3753 "[-w] object1 object2\n", getprogname());
3754 exit(1);
3757 static int
3758 match_line(const char *line, regex_t *regex, size_t nmatch,
3759 regmatch_t *regmatch)
3761 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3764 static struct tog_color *
3765 match_color(struct tog_colors *colors, const char *line)
3767 struct tog_color *tc = NULL;
3769 STAILQ_FOREACH(tc, colors, entry) {
3770 if (match_line(line, &tc->regex, 0, NULL))
3771 return tc;
3774 return NULL;
3777 static const struct got_error *
3778 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3779 WINDOW *window, int skipcol, regmatch_t *regmatch)
3781 const struct got_error *err = NULL;
3782 char *exstr = NULL;
3783 wchar_t *wline = NULL;
3784 int rme, rms, n, width, scrollx;
3785 int width0 = 0, width1 = 0, width2 = 0;
3786 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3788 *wtotal = 0;
3790 rms = regmatch->rm_so;
3791 rme = regmatch->rm_eo;
3793 err = expand_tab(&exstr, line);
3794 if (err)
3795 return err;
3797 /* Split the line into 3 segments, according to match offsets. */
3798 seg0 = strndup(exstr, rms);
3799 if (seg0 == NULL) {
3800 err = got_error_from_errno("strndup");
3801 goto done;
3803 seg1 = strndup(exstr + rms, rme - rms);
3804 if (seg1 == NULL) {
3805 err = got_error_from_errno("strndup");
3806 goto done;
3808 seg2 = strdup(exstr + rme);
3809 if (seg2 == NULL) {
3810 err = got_error_from_errno("strndup");
3811 goto done;
3814 /* draw up to matched token if we haven't scrolled past it */
3815 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3816 col_tab_align, 1);
3817 if (err)
3818 goto done;
3819 n = MAX(width0 - skipcol, 0);
3820 if (n) {
3821 free(wline);
3822 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3823 wlimit, col_tab_align, 1);
3824 if (err)
3825 goto done;
3826 waddwstr(window, &wline[scrollx]);
3827 wlimit -= width;
3828 *wtotal += width;
3831 if (wlimit > 0) {
3832 int i = 0, w = 0;
3833 size_t wlen;
3835 free(wline);
3836 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3837 col_tab_align, 1);
3838 if (err)
3839 goto done;
3840 wlen = wcslen(wline);
3841 while (i < wlen) {
3842 width = wcwidth(wline[i]);
3843 if (width == -1) {
3844 /* should not happen, tabs are expanded */
3845 err = got_error(GOT_ERR_RANGE);
3846 goto done;
3848 if (width0 + w + width > skipcol)
3849 break;
3850 w += width;
3851 i++;
3853 /* draw (visible part of) matched token (if scrolled into it) */
3854 if (width1 - w > 0) {
3855 wattron(window, A_STANDOUT);
3856 waddwstr(window, &wline[i]);
3857 wattroff(window, A_STANDOUT);
3858 wlimit -= (width1 - w);
3859 *wtotal += (width1 - w);
3863 if (wlimit > 0) { /* draw rest of line */
3864 free(wline);
3865 if (skipcol > width0 + width1) {
3866 err = format_line(&wline, &width2, &scrollx, seg2,
3867 skipcol - (width0 + width1), wlimit,
3868 col_tab_align, 1);
3869 if (err)
3870 goto done;
3871 waddwstr(window, &wline[scrollx]);
3872 } else {
3873 err = format_line(&wline, &width2, NULL, seg2, 0,
3874 wlimit, col_tab_align, 1);
3875 if (err)
3876 goto done;
3877 waddwstr(window, wline);
3879 *wtotal += width2;
3881 done:
3882 free(wline);
3883 free(exstr);
3884 free(seg0);
3885 free(seg1);
3886 free(seg2);
3887 return err;
3890 static int
3891 gotoline(struct tog_view *view, int *lineno, int *nprinted)
3893 FILE *f = NULL;
3894 int *eof, *first, *selected;
3896 if (view->type == TOG_VIEW_DIFF) {
3897 struct tog_diff_view_state *s = &view->state.diff;
3899 first = &s->first_displayed_line;
3900 selected = first;
3901 eof = &s->eof;
3902 f = s->f;
3903 } else if (view->type == TOG_VIEW_BLAME) {
3904 struct tog_blame_view_state *s = &view->state.blame;
3906 first = &s->first_displayed_line;
3907 selected = &s->selected_line;
3908 eof = &s->eof;
3909 f = s->blame.f;
3910 } else
3911 return 0;
3913 /* Center gline in the middle of the page like vi(1). */
3914 if (*lineno < view->gline - (view->nlines - 3) / 2)
3915 return 0;
3916 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
3917 rewind(f);
3918 *eof = 0;
3919 *first = 1;
3920 *lineno = 0;
3921 *nprinted = 0;
3922 return 0;
3925 *selected = view->gline <= (view->nlines - 3) / 2 ?
3926 view->gline : (view->nlines - 3) / 2 + 1;
3927 view->gline = 0;
3929 return 1;
3932 static const struct got_error *
3933 draw_file(struct tog_view *view, const char *header)
3935 struct tog_diff_view_state *s = &view->state.diff;
3936 regmatch_t *regmatch = &view->regmatch;
3937 const struct got_error *err;
3938 int nprinted = 0;
3939 char *line;
3940 size_t linesize = 0;
3941 ssize_t linelen;
3942 wchar_t *wline;
3943 int width;
3944 int max_lines = view->nlines;
3945 int nlines = s->nlines;
3946 off_t line_offset;
3948 s->lineno = s->first_displayed_line - 1;
3949 line_offset = s->lines[s->first_displayed_line - 1].offset;
3950 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3951 return got_error_from_errno("fseek");
3953 werase(view->window);
3955 if (view->gline > s->nlines - 1)
3956 view->gline = s->nlines - 1;
3958 if (header) {
3959 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
3960 1 : view->gline - (view->nlines - 3) / 2 :
3961 s->lineno + s->selected_line;
3963 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
3964 return got_error_from_errno("asprintf");
3965 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3966 0, 0);
3967 free(line);
3968 if (err)
3969 return err;
3971 if (view_needs_focus_indication(view))
3972 wstandout(view->window);
3973 waddwstr(view->window, wline);
3974 free(wline);
3975 wline = NULL;
3976 if (view_needs_focus_indication(view))
3977 wstandend(view->window);
3978 if (width <= view->ncols - 1)
3979 waddch(view->window, '\n');
3981 if (max_lines <= 1)
3982 return NULL;
3983 max_lines--;
3986 s->eof = 0;
3987 view->maxx = 0;
3988 line = NULL;
3989 while (max_lines > 0 && nprinted < max_lines) {
3990 enum got_diff_line_type linetype;
3991 attr_t attr = 0;
3993 linelen = getline(&line, &linesize, s->f);
3994 if (linelen == -1) {
3995 if (feof(s->f)) {
3996 s->eof = 1;
3997 break;
3999 free(line);
4000 return got_ferror(s->f, GOT_ERR_IO);
4003 if (++s->lineno < s->first_displayed_line)
4004 continue;
4005 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4006 continue;
4007 if (s->lineno == view->hiline)
4008 attr = A_STANDOUT;
4010 /* Set view->maxx based on full line length. */
4011 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4012 view->x ? 1 : 0);
4013 if (err) {
4014 free(line);
4015 return err;
4017 view->maxx = MAX(view->maxx, width);
4018 free(wline);
4019 wline = NULL;
4021 linetype = s->lines[s->lineno].type;
4022 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4023 linetype < GOT_DIFF_LINE_CONTEXT)
4024 attr |= COLOR_PAIR(linetype);
4025 if (attr)
4026 wattron(view->window, attr);
4027 if (s->first_displayed_line + nprinted == s->matched_line &&
4028 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4029 err = add_matched_line(&width, line, view->ncols, 0,
4030 view->window, view->x, regmatch);
4031 if (err) {
4032 free(line);
4033 return err;
4035 } else {
4036 int skip;
4037 err = format_line(&wline, &width, &skip, line,
4038 view->x, view->ncols, 0, view->x ? 1 : 0);
4039 if (err) {
4040 free(line);
4041 return err;
4043 waddwstr(view->window, &wline[skip]);
4044 free(wline);
4045 wline = NULL;
4047 if (s->lineno == view->hiline) {
4048 /* highlight full gline length */
4049 while (width++ < view->ncols)
4050 waddch(view->window, ' ');
4051 } else {
4052 if (width <= view->ncols - 1)
4053 waddch(view->window, '\n');
4055 if (attr)
4056 wattroff(view->window, attr);
4057 if (++nprinted == 1)
4058 s->first_displayed_line = s->lineno;
4060 free(line);
4061 if (nprinted >= 1)
4062 s->last_displayed_line = s->first_displayed_line +
4063 (nprinted - 1);
4064 else
4065 s->last_displayed_line = s->first_displayed_line;
4067 view_border(view);
4069 if (s->eof) {
4070 while (nprinted < view->nlines) {
4071 waddch(view->window, '\n');
4072 nprinted++;
4075 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4076 view->ncols, 0, 0);
4077 if (err) {
4078 return err;
4081 wstandout(view->window);
4082 waddwstr(view->window, wline);
4083 free(wline);
4084 wline = NULL;
4085 wstandend(view->window);
4088 return NULL;
4091 static char *
4092 get_datestr(time_t *time, char *datebuf)
4094 struct tm mytm, *tm;
4095 char *p, *s;
4097 tm = gmtime_r(time, &mytm);
4098 if (tm == NULL)
4099 return NULL;
4100 s = asctime_r(tm, datebuf);
4101 if (s == NULL)
4102 return NULL;
4103 p = strchr(s, '\n');
4104 if (p)
4105 *p = '\0';
4106 return s;
4109 static const struct got_error *
4110 get_changed_paths(struct got_pathlist_head *paths,
4111 struct got_commit_object *commit, struct got_repository *repo)
4113 const struct got_error *err = NULL;
4114 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4115 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4116 struct got_object_qid *qid;
4118 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4119 if (qid != NULL) {
4120 struct got_commit_object *pcommit;
4121 err = got_object_open_as_commit(&pcommit, repo,
4122 &qid->id);
4123 if (err)
4124 return err;
4126 tree_id1 = got_object_id_dup(
4127 got_object_commit_get_tree_id(pcommit));
4128 if (tree_id1 == NULL) {
4129 got_object_commit_close(pcommit);
4130 return got_error_from_errno("got_object_id_dup");
4132 got_object_commit_close(pcommit);
4136 if (tree_id1) {
4137 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4138 if (err)
4139 goto done;
4142 tree_id2 = got_object_commit_get_tree_id(commit);
4143 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4144 if (err)
4145 goto done;
4147 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4148 got_diff_tree_collect_changed_paths, paths, 0);
4149 done:
4150 if (tree1)
4151 got_object_tree_close(tree1);
4152 if (tree2)
4153 got_object_tree_close(tree2);
4154 free(tree_id1);
4155 return err;
4158 static const struct got_error *
4159 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4160 off_t off, uint8_t type)
4162 struct got_diff_line *p;
4164 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4165 if (p == NULL)
4166 return got_error_from_errno("reallocarray");
4167 *lines = p;
4168 (*lines)[*nlines].offset = off;
4169 (*lines)[*nlines].type = type;
4170 (*nlines)++;
4172 return NULL;
4175 static const struct got_error *
4176 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4177 struct got_object_id *commit_id, struct got_reflist_head *refs,
4178 struct got_repository *repo, FILE *outfile)
4180 const struct got_error *err = NULL;
4181 char datebuf[26], *datestr;
4182 struct got_commit_object *commit;
4183 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4184 time_t committer_time;
4185 const char *author, *committer;
4186 char *refs_str = NULL;
4187 struct got_pathlist_head changed_paths;
4188 struct got_pathlist_entry *pe;
4189 off_t outoff = 0;
4190 int n;
4192 TAILQ_INIT(&changed_paths);
4194 if (refs) {
4195 err = build_refs_str(&refs_str, refs, commit_id, repo);
4196 if (err)
4197 return err;
4200 err = got_object_open_as_commit(&commit, repo, commit_id);
4201 if (err)
4202 return err;
4204 err = got_object_id_str(&id_str, commit_id);
4205 if (err) {
4206 err = got_error_from_errno("got_object_id_str");
4207 goto done;
4210 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4211 if (err)
4212 goto done;
4214 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4215 refs_str ? refs_str : "", refs_str ? ")" : "");
4216 if (n < 0) {
4217 err = got_error_from_errno("fprintf");
4218 goto done;
4220 outoff += n;
4221 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4222 if (err)
4223 goto done;
4225 n = fprintf(outfile, "from: %s\n",
4226 got_object_commit_get_author(commit));
4227 if (n < 0) {
4228 err = got_error_from_errno("fprintf");
4229 goto done;
4231 outoff += n;
4232 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4233 if (err)
4234 goto done;
4236 committer_time = got_object_commit_get_committer_time(commit);
4237 datestr = get_datestr(&committer_time, datebuf);
4238 if (datestr) {
4239 n = fprintf(outfile, "date: %s UTC\n", datestr);
4240 if (n < 0) {
4241 err = got_error_from_errno("fprintf");
4242 goto done;
4244 outoff += n;
4245 err = add_line_metadata(lines, nlines, outoff,
4246 GOT_DIFF_LINE_DATE);
4247 if (err)
4248 goto done;
4250 author = got_object_commit_get_author(commit);
4251 committer = got_object_commit_get_committer(commit);
4252 if (strcmp(author, committer) != 0) {
4253 n = fprintf(outfile, "via: %s\n", committer);
4254 if (n < 0) {
4255 err = got_error_from_errno("fprintf");
4256 goto done;
4258 outoff += n;
4259 err = add_line_metadata(lines, nlines, outoff,
4260 GOT_DIFF_LINE_AUTHOR);
4261 if (err)
4262 goto done;
4264 if (got_object_commit_get_nparents(commit) > 1) {
4265 const struct got_object_id_queue *parent_ids;
4266 struct got_object_qid *qid;
4267 int pn = 1;
4268 parent_ids = got_object_commit_get_parent_ids(commit);
4269 STAILQ_FOREACH(qid, parent_ids, entry) {
4270 err = got_object_id_str(&id_str, &qid->id);
4271 if (err)
4272 goto done;
4273 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4274 if (n < 0) {
4275 err = got_error_from_errno("fprintf");
4276 goto done;
4278 outoff += n;
4279 err = add_line_metadata(lines, nlines, outoff,
4280 GOT_DIFF_LINE_META);
4281 if (err)
4282 goto done;
4283 free(id_str);
4284 id_str = NULL;
4288 err = got_object_commit_get_logmsg(&logmsg, commit);
4289 if (err)
4290 goto done;
4291 s = logmsg;
4292 while ((line = strsep(&s, "\n")) != NULL) {
4293 n = fprintf(outfile, "%s\n", line);
4294 if (n < 0) {
4295 err = got_error_from_errno("fprintf");
4296 goto done;
4298 outoff += n;
4299 err = add_line_metadata(lines, nlines, outoff,
4300 GOT_DIFF_LINE_LOGMSG);
4301 if (err)
4302 goto done;
4305 err = get_changed_paths(&changed_paths, commit, repo);
4306 if (err)
4307 goto done;
4308 TAILQ_FOREACH(pe, &changed_paths, entry) {
4309 struct got_diff_changed_path *cp = pe->data;
4310 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4311 if (n < 0) {
4312 err = got_error_from_errno("fprintf");
4313 goto done;
4315 outoff += n;
4316 err = add_line_metadata(lines, nlines, outoff,
4317 GOT_DIFF_LINE_CHANGES);
4318 if (err)
4319 goto done;
4320 free((char *)pe->path);
4321 free(pe->data);
4324 fputc('\n', outfile);
4325 outoff++;
4326 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4327 done:
4328 got_pathlist_free(&changed_paths);
4329 free(id_str);
4330 free(logmsg);
4331 free(refs_str);
4332 got_object_commit_close(commit);
4333 if (err) {
4334 free(*lines);
4335 *lines = NULL;
4336 *nlines = 0;
4338 return err;
4341 static const struct got_error *
4342 create_diff(struct tog_diff_view_state *s)
4344 const struct got_error *err = NULL;
4345 FILE *f = NULL;
4346 int obj_type;
4348 free(s->lines);
4349 s->lines = malloc(sizeof(*s->lines));
4350 if (s->lines == NULL)
4351 return got_error_from_errno("malloc");
4352 s->nlines = 0;
4354 f = got_opentemp();
4355 if (f == NULL) {
4356 err = got_error_from_errno("got_opentemp");
4357 goto done;
4359 if (s->f && fclose(s->f) == EOF) {
4360 err = got_error_from_errno("fclose");
4361 goto done;
4363 s->f = f;
4365 if (s->id1)
4366 err = got_object_get_type(&obj_type, s->repo, s->id1);
4367 else
4368 err = got_object_get_type(&obj_type, s->repo, s->id2);
4369 if (err)
4370 goto done;
4372 switch (obj_type) {
4373 case GOT_OBJ_TYPE_BLOB:
4374 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4375 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4376 s->label1, s->label2, tog_diff_algo, s->diff_context,
4377 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4378 break;
4379 case GOT_OBJ_TYPE_TREE:
4380 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4381 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4382 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4383 s->force_text_diff, s->repo, s->f);
4384 break;
4385 case GOT_OBJ_TYPE_COMMIT: {
4386 const struct got_object_id_queue *parent_ids;
4387 struct got_object_qid *pid;
4388 struct got_commit_object *commit2;
4389 struct got_reflist_head *refs;
4391 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4392 if (err)
4393 goto done;
4394 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4395 /* Show commit info if we're diffing to a parent/root commit. */
4396 if (s->id1 == NULL) {
4397 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4398 refs, s->repo, s->f);
4399 if (err)
4400 goto done;
4401 } else {
4402 parent_ids = got_object_commit_get_parent_ids(commit2);
4403 STAILQ_FOREACH(pid, parent_ids, entry) {
4404 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4405 err = write_commit_info(&s->lines,
4406 &s->nlines, s->id2, refs, s->repo,
4407 s->f);
4408 if (err)
4409 goto done;
4410 break;
4414 got_object_commit_close(commit2);
4416 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4417 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4418 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4419 s->force_text_diff, s->repo, s->f);
4420 break;
4422 default:
4423 err = got_error(GOT_ERR_OBJ_TYPE);
4424 break;
4426 done:
4427 if (s->f && fflush(s->f) != 0 && err == NULL)
4428 err = got_error_from_errno("fflush");
4429 return err;
4432 static void
4433 diff_view_indicate_progress(struct tog_view *view)
4435 mvwaddstr(view->window, 0, 0, "diffing...");
4436 update_panels();
4437 doupdate();
4440 static const struct got_error *
4441 search_start_diff_view(struct tog_view *view)
4443 struct tog_diff_view_state *s = &view->state.diff;
4445 s->matched_line = 0;
4446 return NULL;
4449 static const struct got_error *
4450 search_next_diff_view(struct tog_view *view)
4452 struct tog_diff_view_state *s = &view->state.diff;
4453 const struct got_error *err = NULL;
4454 int lineno;
4455 char *line = NULL;
4456 size_t linesize = 0;
4457 ssize_t linelen;
4459 if (!view->searching) {
4460 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4461 return NULL;
4464 if (s->matched_line) {
4465 if (view->searching == TOG_SEARCH_FORWARD)
4466 lineno = s->matched_line + 1;
4467 else
4468 lineno = s->matched_line - 1;
4469 } else
4470 lineno = s->first_displayed_line;
4472 while (1) {
4473 off_t offset;
4475 if (lineno <= 0 || lineno > s->nlines) {
4476 if (s->matched_line == 0) {
4477 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4478 break;
4481 if (view->searching == TOG_SEARCH_FORWARD)
4482 lineno = 1;
4483 else
4484 lineno = s->nlines;
4487 offset = s->lines[lineno - 1].offset;
4488 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4489 free(line);
4490 return got_error_from_errno("fseeko");
4492 linelen = getline(&line, &linesize, s->f);
4493 if (linelen != -1) {
4494 char *exstr;
4495 err = expand_tab(&exstr, line);
4496 if (err)
4497 break;
4498 if (match_line(exstr, &view->regex, 1,
4499 &view->regmatch)) {
4500 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4501 s->matched_line = lineno;
4502 free(exstr);
4503 break;
4505 free(exstr);
4507 if (view->searching == TOG_SEARCH_FORWARD)
4508 lineno++;
4509 else
4510 lineno--;
4512 free(line);
4514 if (s->matched_line) {
4515 s->first_displayed_line = s->matched_line;
4516 s->selected_line = 1;
4519 return err;
4522 static const struct got_error *
4523 close_diff_view(struct tog_view *view)
4525 const struct got_error *err = NULL;
4526 struct tog_diff_view_state *s = &view->state.diff;
4528 free(s->id1);
4529 s->id1 = NULL;
4530 free(s->id2);
4531 s->id2 = NULL;
4532 if (s->f && fclose(s->f) == EOF)
4533 err = got_error_from_errno("fclose");
4534 s->f = NULL;
4535 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4536 err = got_error_from_errno("fclose");
4537 s->f1 = NULL;
4538 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4539 err = got_error_from_errno("fclose");
4540 s->f2 = NULL;
4541 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4542 err = got_error_from_errno("close");
4543 s->fd1 = -1;
4544 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4545 err = got_error_from_errno("close");
4546 s->fd2 = -1;
4547 free(s->lines);
4548 s->lines = NULL;
4549 s->nlines = 0;
4550 return err;
4553 static const struct got_error *
4554 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4555 struct got_object_id *id2, const char *label1, const char *label2,
4556 int diff_context, int ignore_whitespace, int force_text_diff,
4557 struct tog_view *parent_view, struct got_repository *repo)
4559 const struct got_error *err;
4560 struct tog_diff_view_state *s = &view->state.diff;
4562 memset(s, 0, sizeof(*s));
4563 s->fd1 = -1;
4564 s->fd2 = -1;
4566 if (id1 != NULL && id2 != NULL) {
4567 int type1, type2;
4568 err = got_object_get_type(&type1, repo, id1);
4569 if (err)
4570 return err;
4571 err = got_object_get_type(&type2, repo, id2);
4572 if (err)
4573 return err;
4575 if (type1 != type2)
4576 return got_error(GOT_ERR_OBJ_TYPE);
4578 s->first_displayed_line = 1;
4579 s->last_displayed_line = view->nlines;
4580 s->selected_line = 1;
4581 s->repo = repo;
4582 s->id1 = id1;
4583 s->id2 = id2;
4584 s->label1 = label1;
4585 s->label2 = label2;
4587 if (id1) {
4588 s->id1 = got_object_id_dup(id1);
4589 if (s->id1 == NULL)
4590 return got_error_from_errno("got_object_id_dup");
4591 } else
4592 s->id1 = NULL;
4594 s->id2 = got_object_id_dup(id2);
4595 if (s->id2 == NULL) {
4596 err = got_error_from_errno("got_object_id_dup");
4597 goto done;
4600 s->f1 = got_opentemp();
4601 if (s->f1 == NULL) {
4602 err = got_error_from_errno("got_opentemp");
4603 goto done;
4606 s->f2 = got_opentemp();
4607 if (s->f2 == NULL) {
4608 err = got_error_from_errno("got_opentemp");
4609 goto done;
4612 s->fd1 = got_opentempfd();
4613 if (s->fd1 == -1) {
4614 err = got_error_from_errno("got_opentempfd");
4615 goto done;
4618 s->fd2 = got_opentempfd();
4619 if (s->fd2 == -1) {
4620 err = got_error_from_errno("got_opentempfd");
4621 goto done;
4624 s->first_displayed_line = 1;
4625 s->last_displayed_line = view->nlines;
4626 s->diff_context = diff_context;
4627 s->ignore_whitespace = ignore_whitespace;
4628 s->force_text_diff = force_text_diff;
4629 s->parent_view = parent_view;
4630 s->repo = repo;
4632 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4633 int rc;
4635 rc = init_pair(GOT_DIFF_LINE_MINUS,
4636 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
4637 if (rc != ERR)
4638 rc = init_pair(GOT_DIFF_LINE_PLUS,
4639 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
4640 if (rc != ERR)
4641 rc = init_pair(GOT_DIFF_LINE_HUNK,
4642 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
4643 if (rc != ERR)
4644 rc = init_pair(GOT_DIFF_LINE_META,
4645 get_color_value("TOG_COLOR_DIFF_META"), -1);
4646 if (rc != ERR)
4647 rc = init_pair(GOT_DIFF_LINE_CHANGES,
4648 get_color_value("TOG_COLOR_DIFF_META"), -1);
4649 if (rc != ERR)
4650 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
4651 get_color_value("TOG_COLOR_DIFF_META"), -1);
4652 if (rc != ERR)
4653 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
4654 get_color_value("TOG_COLOR_DIFF_META"), -1);
4655 if (rc != ERR)
4656 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
4657 get_color_value("TOG_COLOR_AUTHOR"), -1);
4658 if (rc != ERR)
4659 rc = init_pair(GOT_DIFF_LINE_DATE,
4660 get_color_value("TOG_COLOR_DATE"), -1);
4661 if (rc == ERR) {
4662 err = got_error(GOT_ERR_RANGE);
4663 goto done;
4667 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4668 view_is_splitscreen(view))
4669 show_log_view(parent_view); /* draw border */
4670 diff_view_indicate_progress(view);
4672 err = create_diff(s);
4674 view->show = show_diff_view;
4675 view->input = input_diff_view;
4676 view->reset = reset_diff_view;
4677 view->close = close_diff_view;
4678 view->search_start = search_start_diff_view;
4679 view->search_next = search_next_diff_view;
4680 done:
4681 if (err)
4682 close_diff_view(view);
4683 return err;
4686 static const struct got_error *
4687 show_diff_view(struct tog_view *view)
4689 const struct got_error *err;
4690 struct tog_diff_view_state *s = &view->state.diff;
4691 char *id_str1 = NULL, *id_str2, *header;
4692 const char *label1, *label2;
4694 if (s->id1) {
4695 err = got_object_id_str(&id_str1, s->id1);
4696 if (err)
4697 return err;
4698 label1 = s->label1 ? : id_str1;
4699 } else
4700 label1 = "/dev/null";
4702 err = got_object_id_str(&id_str2, s->id2);
4703 if (err)
4704 return err;
4705 label2 = s->label2 ? : id_str2;
4707 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4708 err = got_error_from_errno("asprintf");
4709 free(id_str1);
4710 free(id_str2);
4711 return err;
4713 free(id_str1);
4714 free(id_str2);
4716 err = draw_file(view, header);
4717 free(header);
4718 return err;
4721 static const struct got_error *
4722 set_selected_commit(struct tog_diff_view_state *s,
4723 struct commit_queue_entry *entry)
4725 const struct got_error *err;
4726 const struct got_object_id_queue *parent_ids;
4727 struct got_commit_object *selected_commit;
4728 struct got_object_qid *pid;
4730 free(s->id2);
4731 s->id2 = got_object_id_dup(entry->id);
4732 if (s->id2 == NULL)
4733 return got_error_from_errno("got_object_id_dup");
4735 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4736 if (err)
4737 return err;
4738 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4739 free(s->id1);
4740 pid = STAILQ_FIRST(parent_ids);
4741 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4742 got_object_commit_close(selected_commit);
4743 return NULL;
4746 static const struct got_error *
4747 reset_diff_view(struct tog_view *view)
4749 struct tog_diff_view_state *s = &view->state.diff;
4751 view->count = 0;
4752 wclear(view->window);
4753 s->first_displayed_line = 1;
4754 s->last_displayed_line = view->nlines;
4755 s->matched_line = 0;
4756 diff_view_indicate_progress(view);
4757 return create_diff(s);
4760 static void
4761 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4763 int start, i;
4765 i = start = s->first_displayed_line - 1;
4767 while (s->lines[i].type != type) {
4768 if (i == 0)
4769 i = s->nlines - 1;
4770 if (--i == start)
4771 return; /* do nothing, requested type not in file */
4774 s->selected_line = 1;
4775 s->first_displayed_line = i;
4778 static void
4779 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4781 int start, i;
4783 i = start = s->first_displayed_line + 1;
4785 while (s->lines[i].type != type) {
4786 if (i == s->nlines - 1)
4787 i = 0;
4788 if (++i == start)
4789 return; /* do nothing, requested type not in file */
4792 s->selected_line = 1;
4793 s->first_displayed_line = i;
4796 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4797 int, int, int);
4798 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4799 int, int);
4801 static const struct got_error *
4802 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4804 const struct got_error *err = NULL;
4805 struct tog_diff_view_state *s = &view->state.diff;
4806 struct tog_log_view_state *ls;
4807 struct commit_queue_entry *old_selected_entry;
4808 char *line = NULL;
4809 size_t linesize = 0;
4810 ssize_t linelen;
4811 int i, nscroll = view->nlines - 1, up = 0;
4813 s->lineno = s->first_displayed_line - 1 + s->selected_line;
4815 switch (ch) {
4816 case '0':
4817 view->x = 0;
4818 break;
4819 case '$':
4820 view->x = MAX(view->maxx - view->ncols / 3, 0);
4821 view->count = 0;
4822 break;
4823 case KEY_RIGHT:
4824 case 'l':
4825 if (view->x + view->ncols / 3 < view->maxx)
4826 view->x += 2; /* move two columns right */
4827 else
4828 view->count = 0;
4829 break;
4830 case KEY_LEFT:
4831 case 'h':
4832 view->x -= MIN(view->x, 2); /* move two columns back */
4833 if (view->x <= 0)
4834 view->count = 0;
4835 break;
4836 case 'a':
4837 case 'w':
4838 if (ch == 'a')
4839 s->force_text_diff = !s->force_text_diff;
4840 if (ch == 'w')
4841 s->ignore_whitespace = !s->ignore_whitespace;
4842 err = reset_diff_view(view);
4843 break;
4844 case 'g':
4845 case KEY_HOME:
4846 s->first_displayed_line = 1;
4847 view->count = 0;
4848 break;
4849 case 'G':
4850 case KEY_END:
4851 view->count = 0;
4852 if (s->eof)
4853 break;
4855 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4856 s->eof = 1;
4857 break;
4858 case 'k':
4859 case KEY_UP:
4860 case CTRL('p'):
4861 if (s->first_displayed_line > 1)
4862 s->first_displayed_line--;
4863 else
4864 view->count = 0;
4865 break;
4866 case CTRL('u'):
4867 case 'u':
4868 nscroll /= 2;
4869 /* FALL THROUGH */
4870 case KEY_PPAGE:
4871 case CTRL('b'):
4872 case 'b':
4873 if (s->first_displayed_line == 1) {
4874 view->count = 0;
4875 break;
4877 i = 0;
4878 while (i++ < nscroll && s->first_displayed_line > 1)
4879 s->first_displayed_line--;
4880 break;
4881 case 'j':
4882 case KEY_DOWN:
4883 case CTRL('n'):
4884 if (!s->eof)
4885 s->first_displayed_line++;
4886 else
4887 view->count = 0;
4888 break;
4889 case CTRL('d'):
4890 case 'd':
4891 nscroll /= 2;
4892 /* FALL THROUGH */
4893 case KEY_NPAGE:
4894 case CTRL('f'):
4895 case 'f':
4896 case ' ':
4897 if (s->eof) {
4898 view->count = 0;
4899 break;
4901 i = 0;
4902 while (!s->eof && i++ < nscroll) {
4903 linelen = getline(&line, &linesize, s->f);
4904 s->first_displayed_line++;
4905 if (linelen == -1) {
4906 if (feof(s->f)) {
4907 s->eof = 1;
4908 } else
4909 err = got_ferror(s->f, GOT_ERR_IO);
4910 break;
4913 free(line);
4914 break;
4915 case '(':
4916 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
4917 break;
4918 case ')':
4919 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
4920 break;
4921 case '{':
4922 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
4923 break;
4924 case '}':
4925 diff_next_index(s, GOT_DIFF_LINE_HUNK);
4926 break;
4927 case '[':
4928 if (s->diff_context > 0) {
4929 s->diff_context--;
4930 s->matched_line = 0;
4931 diff_view_indicate_progress(view);
4932 err = create_diff(s);
4933 if (s->first_displayed_line + view->nlines - 1 >
4934 s->nlines) {
4935 s->first_displayed_line = 1;
4936 s->last_displayed_line = view->nlines;
4938 } else
4939 view->count = 0;
4940 break;
4941 case ']':
4942 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4943 s->diff_context++;
4944 s->matched_line = 0;
4945 diff_view_indicate_progress(view);
4946 err = create_diff(s);
4947 } else
4948 view->count = 0;
4949 break;
4950 case '<':
4951 case ',':
4952 case 'K':
4953 up = 1;
4954 /* FALL THROUGH */
4955 case '>':
4956 case '.':
4957 case 'J':
4958 if (s->parent_view == NULL) {
4959 view->count = 0;
4960 break;
4962 s->parent_view->count = view->count;
4964 if (s->parent_view->type == TOG_VIEW_LOG) {
4965 ls = &s->parent_view->state.log;
4966 old_selected_entry = ls->selected_entry;
4968 err = input_log_view(NULL, s->parent_view,
4969 up ? KEY_UP : KEY_DOWN);
4970 if (err)
4971 break;
4972 view->count = s->parent_view->count;
4974 if (old_selected_entry == ls->selected_entry)
4975 break;
4977 err = set_selected_commit(s, ls->selected_entry);
4978 if (err)
4979 break;
4980 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4981 struct tog_blame_view_state *bs;
4982 struct got_object_id *id, *prev_id;
4984 bs = &s->parent_view->state.blame;
4985 prev_id = get_annotation_for_line(bs->blame.lines,
4986 bs->blame.nlines, bs->last_diffed_line);
4988 err = input_blame_view(&view, s->parent_view,
4989 up ? KEY_UP : KEY_DOWN);
4990 if (err)
4991 break;
4992 view->count = s->parent_view->count;
4994 if (prev_id == NULL)
4995 break;
4996 id = get_selected_commit_id(bs->blame.lines,
4997 bs->blame.nlines, bs->first_displayed_line,
4998 bs->selected_line);
4999 if (id == NULL)
5000 break;
5002 if (!got_object_id_cmp(prev_id, id))
5003 break;
5005 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5006 if (err)
5007 break;
5009 s->first_displayed_line = 1;
5010 s->last_displayed_line = view->nlines;
5011 s->matched_line = 0;
5012 view->x = 0;
5014 diff_view_indicate_progress(view);
5015 err = create_diff(s);
5016 break;
5017 default:
5018 view->count = 0;
5019 break;
5022 return err;
5025 static const struct got_error *
5026 cmd_diff(int argc, char *argv[])
5028 const struct got_error *error = NULL;
5029 struct got_repository *repo = NULL;
5030 struct got_worktree *worktree = NULL;
5031 struct got_object_id *id1 = NULL, *id2 = NULL;
5032 char *repo_path = NULL, *cwd = NULL;
5033 char *id_str1 = NULL, *id_str2 = NULL;
5034 char *label1 = NULL, *label2 = NULL;
5035 int diff_context = 3, ignore_whitespace = 0;
5036 int ch, force_text_diff = 0;
5037 const char *errstr;
5038 struct tog_view *view;
5039 int *pack_fds = NULL;
5041 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5042 switch (ch) {
5043 case 'a':
5044 force_text_diff = 1;
5045 break;
5046 case 'C':
5047 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5048 &errstr);
5049 if (errstr != NULL)
5050 errx(1, "number of context lines is %s: %s",
5051 errstr, errstr);
5052 break;
5053 case 'r':
5054 repo_path = realpath(optarg, NULL);
5055 if (repo_path == NULL)
5056 return got_error_from_errno2("realpath",
5057 optarg);
5058 got_path_strip_trailing_slashes(repo_path);
5059 break;
5060 case 'w':
5061 ignore_whitespace = 1;
5062 break;
5063 default:
5064 usage_diff();
5065 /* NOTREACHED */
5069 argc -= optind;
5070 argv += optind;
5072 if (argc == 0) {
5073 usage_diff(); /* TODO show local worktree changes */
5074 } else if (argc == 2) {
5075 id_str1 = argv[0];
5076 id_str2 = argv[1];
5077 } else
5078 usage_diff();
5080 error = got_repo_pack_fds_open(&pack_fds);
5081 if (error)
5082 goto done;
5084 if (repo_path == NULL) {
5085 cwd = getcwd(NULL, 0);
5086 if (cwd == NULL)
5087 return got_error_from_errno("getcwd");
5088 error = got_worktree_open(&worktree, cwd);
5089 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5090 goto done;
5091 if (worktree)
5092 repo_path =
5093 strdup(got_worktree_get_repo_path(worktree));
5094 else
5095 repo_path = strdup(cwd);
5096 if (repo_path == NULL) {
5097 error = got_error_from_errno("strdup");
5098 goto done;
5102 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5103 if (error)
5104 goto done;
5106 init_curses();
5108 error = apply_unveil(got_repo_get_path(repo), NULL);
5109 if (error)
5110 goto done;
5112 error = tog_load_refs(repo, 0);
5113 if (error)
5114 goto done;
5116 error = got_repo_match_object_id(&id1, &label1, id_str1,
5117 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5118 if (error)
5119 goto done;
5121 error = got_repo_match_object_id(&id2, &label2, id_str2,
5122 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5123 if (error)
5124 goto done;
5126 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5127 if (view == NULL) {
5128 error = got_error_from_errno("view_open");
5129 goto done;
5131 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5132 ignore_whitespace, force_text_diff, NULL, repo);
5133 if (error)
5134 goto done;
5135 error = view_loop(view);
5136 done:
5137 free(label1);
5138 free(label2);
5139 free(repo_path);
5140 free(cwd);
5141 if (repo) {
5142 const struct got_error *close_err = got_repo_close(repo);
5143 if (error == NULL)
5144 error = close_err;
5146 if (worktree)
5147 got_worktree_close(worktree);
5148 if (pack_fds) {
5149 const struct got_error *pack_err =
5150 got_repo_pack_fds_close(pack_fds);
5151 if (error == NULL)
5152 error = pack_err;
5154 tog_free_refs();
5155 return error;
5158 __dead static void
5159 usage_blame(void)
5161 endwin();
5162 fprintf(stderr,
5163 "usage: %s blame [-c commit] [-r repository-path] path\n",
5164 getprogname());
5165 exit(1);
5168 struct tog_blame_line {
5169 int annotated;
5170 struct got_object_id *id;
5173 static const struct got_error *
5174 draw_blame(struct tog_view *view)
5176 struct tog_blame_view_state *s = &view->state.blame;
5177 struct tog_blame *blame = &s->blame;
5178 regmatch_t *regmatch = &view->regmatch;
5179 const struct got_error *err;
5180 int lineno = 0, nprinted = 0;
5181 char *line = NULL;
5182 size_t linesize = 0;
5183 ssize_t linelen;
5184 wchar_t *wline;
5185 int width;
5186 struct tog_blame_line *blame_line;
5187 struct got_object_id *prev_id = NULL;
5188 char *id_str;
5189 struct tog_color *tc;
5191 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5192 if (err)
5193 return err;
5195 rewind(blame->f);
5196 werase(view->window);
5198 if (asprintf(&line, "commit %s", id_str) == -1) {
5199 err = got_error_from_errno("asprintf");
5200 free(id_str);
5201 return err;
5204 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5205 free(line);
5206 line = NULL;
5207 if (err)
5208 return err;
5209 if (view_needs_focus_indication(view))
5210 wstandout(view->window);
5211 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5212 if (tc)
5213 wattr_on(view->window,
5214 COLOR_PAIR(tc->colorpair), NULL);
5215 waddwstr(view->window, wline);
5216 if (tc)
5217 wattr_off(view->window,
5218 COLOR_PAIR(tc->colorpair), NULL);
5219 if (view_needs_focus_indication(view))
5220 wstandend(view->window);
5221 free(wline);
5222 wline = NULL;
5223 if (width < view->ncols - 1)
5224 waddch(view->window, '\n');
5226 if (view->gline > blame->nlines)
5227 view->gline = blame->nlines;
5229 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5230 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5231 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5232 free(id_str);
5233 return got_error_from_errno("asprintf");
5235 free(id_str);
5236 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5237 free(line);
5238 line = NULL;
5239 if (err)
5240 return err;
5241 waddwstr(view->window, wline);
5242 free(wline);
5243 wline = NULL;
5244 if (width < view->ncols - 1)
5245 waddch(view->window, '\n');
5247 s->eof = 0;
5248 view->maxx = 0;
5249 while (nprinted < view->nlines - 2) {
5250 linelen = getline(&line, &linesize, blame->f);
5251 if (linelen == -1) {
5252 if (feof(blame->f)) {
5253 s->eof = 1;
5254 break;
5256 free(line);
5257 return got_ferror(blame->f, GOT_ERR_IO);
5259 if (++lineno < s->first_displayed_line)
5260 continue;
5261 if (view->gline && !gotoline(view, &lineno, &nprinted))
5262 continue;
5264 /* Set view->maxx based on full line length. */
5265 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5266 if (err) {
5267 free(line);
5268 return err;
5270 free(wline);
5271 wline = NULL;
5272 view->maxx = MAX(view->maxx, width);
5274 if (nprinted == s->selected_line - 1)
5275 wstandout(view->window);
5277 if (blame->nlines > 0) {
5278 blame_line = &blame->lines[lineno - 1];
5279 if (blame_line->annotated && prev_id &&
5280 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5281 !(nprinted == s->selected_line - 1)) {
5282 waddstr(view->window, " ");
5283 } else if (blame_line->annotated) {
5284 char *id_str;
5285 err = got_object_id_str(&id_str,
5286 blame_line->id);
5287 if (err) {
5288 free(line);
5289 return err;
5291 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5292 if (tc)
5293 wattr_on(view->window,
5294 COLOR_PAIR(tc->colorpair), NULL);
5295 wprintw(view->window, "%.8s", id_str);
5296 if (tc)
5297 wattr_off(view->window,
5298 COLOR_PAIR(tc->colorpair), NULL);
5299 free(id_str);
5300 prev_id = blame_line->id;
5301 } else {
5302 waddstr(view->window, "........");
5303 prev_id = NULL;
5305 } else {
5306 waddstr(view->window, "........");
5307 prev_id = NULL;
5310 if (nprinted == s->selected_line - 1)
5311 wstandend(view->window);
5312 waddstr(view->window, " ");
5314 if (view->ncols <= 9) {
5315 width = 9;
5316 } else if (s->first_displayed_line + nprinted ==
5317 s->matched_line &&
5318 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5319 err = add_matched_line(&width, line, view->ncols - 9, 9,
5320 view->window, view->x, regmatch);
5321 if (err) {
5322 free(line);
5323 return err;
5325 width += 9;
5326 } else {
5327 int skip;
5328 err = format_line(&wline, &width, &skip, line,
5329 view->x, view->ncols - 9, 9, 1);
5330 if (err) {
5331 free(line);
5332 return err;
5334 waddwstr(view->window, &wline[skip]);
5335 width += 9;
5336 free(wline);
5337 wline = NULL;
5340 if (width <= view->ncols - 1)
5341 waddch(view->window, '\n');
5342 if (++nprinted == 1)
5343 s->first_displayed_line = lineno;
5345 free(line);
5346 s->last_displayed_line = lineno;
5348 view_border(view);
5350 return NULL;
5353 static const struct got_error *
5354 blame_cb(void *arg, int nlines, int lineno,
5355 struct got_commit_object *commit, struct got_object_id *id)
5357 const struct got_error *err = NULL;
5358 struct tog_blame_cb_args *a = arg;
5359 struct tog_blame_line *line;
5360 int errcode;
5362 if (nlines != a->nlines ||
5363 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5364 return got_error(GOT_ERR_RANGE);
5366 errcode = pthread_mutex_lock(&tog_mutex);
5367 if (errcode)
5368 return got_error_set_errno(errcode, "pthread_mutex_lock");
5370 if (*a->quit) { /* user has quit the blame view */
5371 err = got_error(GOT_ERR_ITER_COMPLETED);
5372 goto done;
5375 if (lineno == -1)
5376 goto done; /* no change in this commit */
5378 line = &a->lines[lineno - 1];
5379 if (line->annotated)
5380 goto done;
5382 line->id = got_object_id_dup(id);
5383 if (line->id == NULL) {
5384 err = got_error_from_errno("got_object_id_dup");
5385 goto done;
5387 line->annotated = 1;
5388 done:
5389 errcode = pthread_mutex_unlock(&tog_mutex);
5390 if (errcode)
5391 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5392 return err;
5395 static void *
5396 blame_thread(void *arg)
5398 const struct got_error *err, *close_err;
5399 struct tog_blame_thread_args *ta = arg;
5400 struct tog_blame_cb_args *a = ta->cb_args;
5401 int errcode, fd1 = -1, fd2 = -1;
5402 FILE *f1 = NULL, *f2 = NULL;
5404 fd1 = got_opentempfd();
5405 if (fd1 == -1)
5406 return (void *)got_error_from_errno("got_opentempfd");
5408 fd2 = got_opentempfd();
5409 if (fd2 == -1) {
5410 err = got_error_from_errno("got_opentempfd");
5411 goto done;
5414 f1 = got_opentemp();
5415 if (f1 == NULL) {
5416 err = (void *)got_error_from_errno("got_opentemp");
5417 goto done;
5419 f2 = got_opentemp();
5420 if (f2 == NULL) {
5421 err = (void *)got_error_from_errno("got_opentemp");
5422 goto done;
5425 err = block_signals_used_by_main_thread();
5426 if (err)
5427 goto done;
5429 err = got_blame(ta->path, a->commit_id, ta->repo,
5430 tog_diff_algo, blame_cb, ta->cb_args,
5431 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5432 if (err && err->code == GOT_ERR_CANCELLED)
5433 err = NULL;
5435 errcode = pthread_mutex_lock(&tog_mutex);
5436 if (errcode) {
5437 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5438 goto done;
5441 close_err = got_repo_close(ta->repo);
5442 if (err == NULL)
5443 err = close_err;
5444 ta->repo = NULL;
5445 *ta->complete = 1;
5447 errcode = pthread_mutex_unlock(&tog_mutex);
5448 if (errcode && err == NULL)
5449 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5451 done:
5452 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5453 err = got_error_from_errno("close");
5454 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5455 err = got_error_from_errno("close");
5456 if (f1 && fclose(f1) == EOF && err == NULL)
5457 err = got_error_from_errno("fclose");
5458 if (f2 && fclose(f2) == EOF && err == NULL)
5459 err = got_error_from_errno("fclose");
5461 return (void *)err;
5464 static struct got_object_id *
5465 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5466 int first_displayed_line, int selected_line)
5468 struct tog_blame_line *line;
5470 if (nlines <= 0)
5471 return NULL;
5473 line = &lines[first_displayed_line - 1 + selected_line - 1];
5474 if (!line->annotated)
5475 return NULL;
5477 return line->id;
5480 static struct got_object_id *
5481 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5482 int lineno)
5484 struct tog_blame_line *line;
5486 if (nlines <= 0 || lineno >= nlines)
5487 return NULL;
5489 line = &lines[lineno - 1];
5490 if (!line->annotated)
5491 return NULL;
5493 return line->id;
5496 static const struct got_error *
5497 stop_blame(struct tog_blame *blame)
5499 const struct got_error *err = NULL;
5500 int i;
5502 if (blame->thread) {
5503 int errcode;
5504 errcode = pthread_mutex_unlock(&tog_mutex);
5505 if (errcode)
5506 return got_error_set_errno(errcode,
5507 "pthread_mutex_unlock");
5508 errcode = pthread_join(blame->thread, (void **)&err);
5509 if (errcode)
5510 return got_error_set_errno(errcode, "pthread_join");
5511 errcode = pthread_mutex_lock(&tog_mutex);
5512 if (errcode)
5513 return got_error_set_errno(errcode,
5514 "pthread_mutex_lock");
5515 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5516 err = NULL;
5517 blame->thread = 0; //NULL;
5519 if (blame->thread_args.repo) {
5520 const struct got_error *close_err;
5521 close_err = got_repo_close(blame->thread_args.repo);
5522 if (err == NULL)
5523 err = close_err;
5524 blame->thread_args.repo = NULL;
5526 if (blame->f) {
5527 if (fclose(blame->f) == EOF && err == NULL)
5528 err = got_error_from_errno("fclose");
5529 blame->f = NULL;
5531 if (blame->lines) {
5532 for (i = 0; i < blame->nlines; i++)
5533 free(blame->lines[i].id);
5534 free(blame->lines);
5535 blame->lines = NULL;
5537 free(blame->cb_args.commit_id);
5538 blame->cb_args.commit_id = NULL;
5539 if (blame->pack_fds) {
5540 const struct got_error *pack_err =
5541 got_repo_pack_fds_close(blame->pack_fds);
5542 if (err == NULL)
5543 err = pack_err;
5544 blame->pack_fds = NULL;
5546 return err;
5549 static const struct got_error *
5550 cancel_blame_view(void *arg)
5552 const struct got_error *err = NULL;
5553 int *done = arg;
5554 int errcode;
5556 errcode = pthread_mutex_lock(&tog_mutex);
5557 if (errcode)
5558 return got_error_set_errno(errcode,
5559 "pthread_mutex_unlock");
5561 if (*done)
5562 err = got_error(GOT_ERR_CANCELLED);
5564 errcode = pthread_mutex_unlock(&tog_mutex);
5565 if (errcode)
5566 return got_error_set_errno(errcode,
5567 "pthread_mutex_lock");
5569 return err;
5572 static const struct got_error *
5573 run_blame(struct tog_view *view)
5575 struct tog_blame_view_state *s = &view->state.blame;
5576 struct tog_blame *blame = &s->blame;
5577 const struct got_error *err = NULL;
5578 struct got_commit_object *commit = NULL;
5579 struct got_blob_object *blob = NULL;
5580 struct got_repository *thread_repo = NULL;
5581 struct got_object_id *obj_id = NULL;
5582 int obj_type, fd = -1;
5583 int *pack_fds = NULL;
5585 err = got_object_open_as_commit(&commit, s->repo,
5586 &s->blamed_commit->id);
5587 if (err)
5588 return err;
5590 fd = got_opentempfd();
5591 if (fd == -1) {
5592 err = got_error_from_errno("got_opentempfd");
5593 goto done;
5596 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5597 if (err)
5598 goto done;
5600 err = got_object_get_type(&obj_type, s->repo, obj_id);
5601 if (err)
5602 goto done;
5604 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5605 err = got_error(GOT_ERR_OBJ_TYPE);
5606 goto done;
5609 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5610 if (err)
5611 goto done;
5612 blame->f = got_opentemp();
5613 if (blame->f == NULL) {
5614 err = got_error_from_errno("got_opentemp");
5615 goto done;
5617 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5618 &blame->line_offsets, blame->f, blob);
5619 if (err)
5620 goto done;
5621 if (blame->nlines == 0) {
5622 s->blame_complete = 1;
5623 goto done;
5626 /* Don't include \n at EOF in the blame line count. */
5627 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5628 blame->nlines--;
5630 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5631 if (blame->lines == NULL) {
5632 err = got_error_from_errno("calloc");
5633 goto done;
5636 err = got_repo_pack_fds_open(&pack_fds);
5637 if (err)
5638 goto done;
5639 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5640 pack_fds);
5641 if (err)
5642 goto done;
5644 blame->pack_fds = pack_fds;
5645 blame->cb_args.view = view;
5646 blame->cb_args.lines = blame->lines;
5647 blame->cb_args.nlines = blame->nlines;
5648 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5649 if (blame->cb_args.commit_id == NULL) {
5650 err = got_error_from_errno("got_object_id_dup");
5651 goto done;
5653 blame->cb_args.quit = &s->done;
5655 blame->thread_args.path = s->path;
5656 blame->thread_args.repo = thread_repo;
5657 blame->thread_args.cb_args = &blame->cb_args;
5658 blame->thread_args.complete = &s->blame_complete;
5659 blame->thread_args.cancel_cb = cancel_blame_view;
5660 blame->thread_args.cancel_arg = &s->done;
5661 s->blame_complete = 0;
5663 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5664 s->first_displayed_line = 1;
5665 s->last_displayed_line = view->nlines;
5666 s->selected_line = 1;
5668 s->matched_line = 0;
5670 done:
5671 if (commit)
5672 got_object_commit_close(commit);
5673 if (fd != -1 && close(fd) == -1 && err == NULL)
5674 err = got_error_from_errno("close");
5675 if (blob)
5676 got_object_blob_close(blob);
5677 free(obj_id);
5678 if (err)
5679 stop_blame(blame);
5680 return err;
5683 static const struct got_error *
5684 open_blame_view(struct tog_view *view, char *path,
5685 struct got_object_id *commit_id, struct got_repository *repo)
5687 const struct got_error *err = NULL;
5688 struct tog_blame_view_state *s = &view->state.blame;
5690 STAILQ_INIT(&s->blamed_commits);
5692 s->path = strdup(path);
5693 if (s->path == NULL)
5694 return got_error_from_errno("strdup");
5696 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5697 if (err) {
5698 free(s->path);
5699 return err;
5702 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5703 s->first_displayed_line = 1;
5704 s->last_displayed_line = view->nlines;
5705 s->selected_line = 1;
5706 s->blame_complete = 0;
5707 s->repo = repo;
5708 s->commit_id = commit_id;
5709 memset(&s->blame, 0, sizeof(s->blame));
5711 STAILQ_INIT(&s->colors);
5712 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5713 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5714 get_color_value("TOG_COLOR_COMMIT"));
5715 if (err)
5716 return err;
5719 view->show = show_blame_view;
5720 view->input = input_blame_view;
5721 view->reset = reset_blame_view;
5722 view->close = close_blame_view;
5723 view->search_start = search_start_blame_view;
5724 view->search_next = search_next_blame_view;
5726 return run_blame(view);
5729 static const struct got_error *
5730 close_blame_view(struct tog_view *view)
5732 const struct got_error *err = NULL;
5733 struct tog_blame_view_state *s = &view->state.blame;
5735 if (s->blame.thread)
5736 err = stop_blame(&s->blame);
5738 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5739 struct got_object_qid *blamed_commit;
5740 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5741 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5742 got_object_qid_free(blamed_commit);
5745 free(s->path);
5746 free_colors(&s->colors);
5747 return err;
5750 static const struct got_error *
5751 search_start_blame_view(struct tog_view *view)
5753 struct tog_blame_view_state *s = &view->state.blame;
5755 s->matched_line = 0;
5756 return NULL;
5759 static const struct got_error *
5760 search_next_blame_view(struct tog_view *view)
5762 struct tog_blame_view_state *s = &view->state.blame;
5763 const struct got_error *err = NULL;
5764 int lineno;
5765 char *line = NULL;
5766 size_t linesize = 0;
5767 ssize_t linelen;
5769 if (!view->searching) {
5770 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5771 return NULL;
5774 if (s->matched_line) {
5775 if (view->searching == TOG_SEARCH_FORWARD)
5776 lineno = s->matched_line + 1;
5777 else
5778 lineno = s->matched_line - 1;
5779 } else
5780 lineno = s->first_displayed_line - 1 + s->selected_line;
5782 while (1) {
5783 off_t offset;
5785 if (lineno <= 0 || lineno > s->blame.nlines) {
5786 if (s->matched_line == 0) {
5787 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5788 break;
5791 if (view->searching == TOG_SEARCH_FORWARD)
5792 lineno = 1;
5793 else
5794 lineno = s->blame.nlines;
5797 offset = s->blame.line_offsets[lineno - 1];
5798 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5799 free(line);
5800 return got_error_from_errno("fseeko");
5802 linelen = getline(&line, &linesize, s->blame.f);
5803 if (linelen != -1) {
5804 char *exstr;
5805 err = expand_tab(&exstr, line);
5806 if (err)
5807 break;
5808 if (match_line(exstr, &view->regex, 1,
5809 &view->regmatch)) {
5810 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5811 s->matched_line = lineno;
5812 free(exstr);
5813 break;
5815 free(exstr);
5817 if (view->searching == TOG_SEARCH_FORWARD)
5818 lineno++;
5819 else
5820 lineno--;
5822 free(line);
5824 if (s->matched_line) {
5825 s->first_displayed_line = s->matched_line;
5826 s->selected_line = 1;
5829 return err;
5832 static const struct got_error *
5833 show_blame_view(struct tog_view *view)
5835 const struct got_error *err = NULL;
5836 struct tog_blame_view_state *s = &view->state.blame;
5837 int errcode;
5839 if (s->blame.thread == 0 && !s->blame_complete) {
5840 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5841 &s->blame.thread_args);
5842 if (errcode)
5843 return got_error_set_errno(errcode, "pthread_create");
5845 halfdelay(1); /* fast refresh while annotating */
5848 if (s->blame_complete)
5849 halfdelay(10); /* disable fast refresh */
5851 err = draw_blame(view);
5853 view_border(view);
5854 return err;
5857 static const struct got_error *
5858 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5859 struct got_repository *repo, struct got_object_id *id)
5861 struct tog_view *log_view;
5862 const struct got_error *err = NULL;
5864 *new_view = NULL;
5866 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5867 if (log_view == NULL)
5868 return got_error_from_errno("view_open");
5870 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5871 if (err)
5872 view_close(log_view);
5873 else
5874 *new_view = log_view;
5876 return err;
5879 static const struct got_error *
5880 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5882 const struct got_error *err = NULL, *thread_err = NULL;
5883 struct tog_view *diff_view;
5884 struct tog_blame_view_state *s = &view->state.blame;
5885 int eos, nscroll, begin_y = 0, begin_x = 0;
5887 eos = nscroll = view->nlines - 2;
5888 if (view_is_hsplit_top(view))
5889 --eos; /* border */
5891 switch (ch) {
5892 case '0':
5893 view->x = 0;
5894 break;
5895 case '$':
5896 view->x = MAX(view->maxx - view->ncols / 3, 0);
5897 view->count = 0;
5898 break;
5899 case KEY_RIGHT:
5900 case 'l':
5901 if (view->x + view->ncols / 3 < view->maxx)
5902 view->x += 2; /* move two columns right */
5903 else
5904 view->count = 0;
5905 break;
5906 case KEY_LEFT:
5907 case 'h':
5908 view->x -= MIN(view->x, 2); /* move two columns back */
5909 if (view->x <= 0)
5910 view->count = 0;
5911 break;
5912 case 'q':
5913 s->done = 1;
5914 break;
5915 case 'g':
5916 case KEY_HOME:
5917 s->selected_line = 1;
5918 s->first_displayed_line = 1;
5919 view->count = 0;
5920 break;
5921 case 'G':
5922 case KEY_END:
5923 if (s->blame.nlines < eos) {
5924 s->selected_line = s->blame.nlines;
5925 s->first_displayed_line = 1;
5926 } else {
5927 s->selected_line = eos;
5928 s->first_displayed_line = s->blame.nlines - (eos - 1);
5930 view->count = 0;
5931 break;
5932 case 'k':
5933 case KEY_UP:
5934 case CTRL('p'):
5935 if (s->selected_line > 1)
5936 s->selected_line--;
5937 else if (s->selected_line == 1 &&
5938 s->first_displayed_line > 1)
5939 s->first_displayed_line--;
5940 else
5941 view->count = 0;
5942 break;
5943 case CTRL('u'):
5944 case 'u':
5945 nscroll /= 2;
5946 /* FALL THROUGH */
5947 case KEY_PPAGE:
5948 case CTRL('b'):
5949 case 'b':
5950 if (s->first_displayed_line == 1) {
5951 if (view->count > 1)
5952 nscroll += nscroll;
5953 s->selected_line = MAX(1, s->selected_line - nscroll);
5954 view->count = 0;
5955 break;
5957 if (s->first_displayed_line > nscroll)
5958 s->first_displayed_line -= nscroll;
5959 else
5960 s->first_displayed_line = 1;
5961 break;
5962 case 'j':
5963 case KEY_DOWN:
5964 case CTRL('n'):
5965 if (s->selected_line < eos && s->first_displayed_line +
5966 s->selected_line <= s->blame.nlines)
5967 s->selected_line++;
5968 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5969 s->first_displayed_line++;
5970 else
5971 view->count = 0;
5972 break;
5973 case 'c':
5974 case 'p': {
5975 struct got_object_id *id = NULL;
5977 view->count = 0;
5978 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5979 s->first_displayed_line, s->selected_line);
5980 if (id == NULL)
5981 break;
5982 if (ch == 'p') {
5983 struct got_commit_object *commit, *pcommit;
5984 struct got_object_qid *pid;
5985 struct got_object_id *blob_id = NULL;
5986 int obj_type;
5987 err = got_object_open_as_commit(&commit,
5988 s->repo, id);
5989 if (err)
5990 break;
5991 pid = STAILQ_FIRST(
5992 got_object_commit_get_parent_ids(commit));
5993 if (pid == NULL) {
5994 got_object_commit_close(commit);
5995 break;
5997 /* Check if path history ends here. */
5998 err = got_object_open_as_commit(&pcommit,
5999 s->repo, &pid->id);
6000 if (err)
6001 break;
6002 err = got_object_id_by_path(&blob_id, s->repo,
6003 pcommit, s->path);
6004 got_object_commit_close(pcommit);
6005 if (err) {
6006 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6007 err = NULL;
6008 got_object_commit_close(commit);
6009 break;
6011 err = got_object_get_type(&obj_type, s->repo,
6012 blob_id);
6013 free(blob_id);
6014 /* Can't blame non-blob type objects. */
6015 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6016 got_object_commit_close(commit);
6017 break;
6019 err = got_object_qid_alloc(&s->blamed_commit,
6020 &pid->id);
6021 got_object_commit_close(commit);
6022 } else {
6023 if (got_object_id_cmp(id,
6024 &s->blamed_commit->id) == 0)
6025 break;
6026 err = got_object_qid_alloc(&s->blamed_commit,
6027 id);
6029 if (err)
6030 break;
6031 s->done = 1;
6032 thread_err = stop_blame(&s->blame);
6033 s->done = 0;
6034 if (thread_err)
6035 break;
6036 STAILQ_INSERT_HEAD(&s->blamed_commits,
6037 s->blamed_commit, entry);
6038 err = run_blame(view);
6039 if (err)
6040 break;
6041 break;
6043 case 'C': {
6044 struct got_object_qid *first;
6046 view->count = 0;
6047 first = STAILQ_FIRST(&s->blamed_commits);
6048 if (!got_object_id_cmp(&first->id, s->commit_id))
6049 break;
6050 s->done = 1;
6051 thread_err = stop_blame(&s->blame);
6052 s->done = 0;
6053 if (thread_err)
6054 break;
6055 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6056 got_object_qid_free(s->blamed_commit);
6057 s->blamed_commit =
6058 STAILQ_FIRST(&s->blamed_commits);
6059 err = run_blame(view);
6060 if (err)
6061 break;
6062 break;
6064 case 'L':
6065 view->count = 0;
6066 s->id_to_log = get_selected_commit_id(s->blame.lines,
6067 s->blame.nlines, s->first_displayed_line, s->selected_line);
6068 if (s->id_to_log)
6069 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6070 break;
6071 case KEY_ENTER:
6072 case '\r': {
6073 struct got_object_id *id = NULL;
6074 struct got_object_qid *pid;
6075 struct got_commit_object *commit = NULL;
6077 view->count = 0;
6078 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6079 s->first_displayed_line, s->selected_line);
6080 if (id == NULL)
6081 break;
6082 err = got_object_open_as_commit(&commit, s->repo, id);
6083 if (err)
6084 break;
6085 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6086 if (*new_view) {
6087 /* traversed from diff view, release diff resources */
6088 err = close_diff_view(*new_view);
6089 if (err)
6090 break;
6091 diff_view = *new_view;
6092 } else {
6093 if (view_is_parent_view(view))
6094 view_get_split(view, &begin_y, &begin_x);
6096 diff_view = view_open(0, 0, begin_y, begin_x,
6097 TOG_VIEW_DIFF);
6098 if (diff_view == NULL) {
6099 got_object_commit_close(commit);
6100 err = got_error_from_errno("view_open");
6101 break;
6104 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6105 id, NULL, NULL, 3, 0, 0, view, s->repo);
6106 got_object_commit_close(commit);
6107 if (err) {
6108 view_close(diff_view);
6109 break;
6111 s->last_diffed_line = s->first_displayed_line - 1 +
6112 s->selected_line;
6113 if (*new_view)
6114 break; /* still open from active diff view */
6115 if (view_is_parent_view(view) &&
6116 view->mode == TOG_VIEW_SPLIT_HRZN) {
6117 err = view_init_hsplit(view, begin_y);
6118 if (err)
6119 break;
6122 view->focussed = 0;
6123 diff_view->focussed = 1;
6124 diff_view->mode = view->mode;
6125 diff_view->nlines = view->lines - begin_y;
6126 if (view_is_parent_view(view)) {
6127 view_transfer_size(diff_view, view);
6128 err = view_close_child(view);
6129 if (err)
6130 break;
6131 err = view_set_child(view, diff_view);
6132 if (err)
6133 break;
6134 view->focus_child = 1;
6135 } else
6136 *new_view = diff_view;
6137 if (err)
6138 break;
6139 break;
6141 case CTRL('d'):
6142 case 'd':
6143 nscroll /= 2;
6144 /* FALL THROUGH */
6145 case KEY_NPAGE:
6146 case CTRL('f'):
6147 case 'f':
6148 case ' ':
6149 if (s->last_displayed_line >= s->blame.nlines &&
6150 s->selected_line >= MIN(s->blame.nlines,
6151 view->nlines - 2)) {
6152 view->count = 0;
6153 break;
6155 if (s->last_displayed_line >= s->blame.nlines &&
6156 s->selected_line < view->nlines - 2) {
6157 s->selected_line +=
6158 MIN(nscroll, s->last_displayed_line -
6159 s->first_displayed_line - s->selected_line + 1);
6161 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6162 s->first_displayed_line += nscroll;
6163 else
6164 s->first_displayed_line =
6165 s->blame.nlines - (view->nlines - 3);
6166 break;
6167 case KEY_RESIZE:
6168 if (s->selected_line > view->nlines - 2) {
6169 s->selected_line = MIN(s->blame.nlines,
6170 view->nlines - 2);
6172 break;
6173 default:
6174 view->count = 0;
6175 break;
6177 return thread_err ? thread_err : err;
6180 static const struct got_error *
6181 reset_blame_view(struct tog_view *view)
6183 const struct got_error *err;
6184 struct tog_blame_view_state *s = &view->state.blame;
6186 view->count = 0;
6187 s->done = 1;
6188 err = stop_blame(&s->blame);
6189 s->done = 0;
6190 if (err)
6191 return err;
6192 return run_blame(view);
6195 static const struct got_error *
6196 cmd_blame(int argc, char *argv[])
6198 const struct got_error *error;
6199 struct got_repository *repo = NULL;
6200 struct got_worktree *worktree = NULL;
6201 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6202 char *link_target = NULL;
6203 struct got_object_id *commit_id = NULL;
6204 struct got_commit_object *commit = NULL;
6205 char *commit_id_str = NULL;
6206 int ch;
6207 struct tog_view *view;
6208 int *pack_fds = NULL;
6210 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6211 switch (ch) {
6212 case 'c':
6213 commit_id_str = optarg;
6214 break;
6215 case 'r':
6216 repo_path = realpath(optarg, NULL);
6217 if (repo_path == NULL)
6218 return got_error_from_errno2("realpath",
6219 optarg);
6220 break;
6221 default:
6222 usage_blame();
6223 /* NOTREACHED */
6227 argc -= optind;
6228 argv += optind;
6230 if (argc != 1)
6231 usage_blame();
6233 error = got_repo_pack_fds_open(&pack_fds);
6234 if (error != NULL)
6235 goto done;
6237 if (repo_path == NULL) {
6238 cwd = getcwd(NULL, 0);
6239 if (cwd == NULL)
6240 return got_error_from_errno("getcwd");
6241 error = got_worktree_open(&worktree, cwd);
6242 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6243 goto done;
6244 if (worktree)
6245 repo_path =
6246 strdup(got_worktree_get_repo_path(worktree));
6247 else
6248 repo_path = strdup(cwd);
6249 if (repo_path == NULL) {
6250 error = got_error_from_errno("strdup");
6251 goto done;
6255 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6256 if (error != NULL)
6257 goto done;
6259 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6260 worktree);
6261 if (error)
6262 goto done;
6264 init_curses();
6266 error = apply_unveil(got_repo_get_path(repo), NULL);
6267 if (error)
6268 goto done;
6270 error = tog_load_refs(repo, 0);
6271 if (error)
6272 goto done;
6274 if (commit_id_str == NULL) {
6275 struct got_reference *head_ref;
6276 error = got_ref_open(&head_ref, repo, worktree ?
6277 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6278 if (error != NULL)
6279 goto done;
6280 error = got_ref_resolve(&commit_id, repo, head_ref);
6281 got_ref_close(head_ref);
6282 } else {
6283 error = got_repo_match_object_id(&commit_id, NULL,
6284 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6286 if (error != NULL)
6287 goto done;
6289 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6290 if (view == NULL) {
6291 error = got_error_from_errno("view_open");
6292 goto done;
6295 error = got_object_open_as_commit(&commit, repo, commit_id);
6296 if (error)
6297 goto done;
6299 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6300 commit, repo);
6301 if (error)
6302 goto done;
6304 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6305 commit_id, repo);
6306 if (error)
6307 goto done;
6308 if (worktree) {
6309 /* Release work tree lock. */
6310 got_worktree_close(worktree);
6311 worktree = NULL;
6313 error = view_loop(view);
6314 done:
6315 free(repo_path);
6316 free(in_repo_path);
6317 free(link_target);
6318 free(cwd);
6319 free(commit_id);
6320 if (commit)
6321 got_object_commit_close(commit);
6322 if (worktree)
6323 got_worktree_close(worktree);
6324 if (repo) {
6325 const struct got_error *close_err = got_repo_close(repo);
6326 if (error == NULL)
6327 error = close_err;
6329 if (pack_fds) {
6330 const struct got_error *pack_err =
6331 got_repo_pack_fds_close(pack_fds);
6332 if (error == NULL)
6333 error = pack_err;
6335 tog_free_refs();
6336 return error;
6339 static const struct got_error *
6340 draw_tree_entries(struct tog_view *view, const char *parent_path)
6342 struct tog_tree_view_state *s = &view->state.tree;
6343 const struct got_error *err = NULL;
6344 struct got_tree_entry *te;
6345 wchar_t *wline;
6346 struct tog_color *tc;
6347 int width, n, nentries, i = 1;
6348 int limit = view->nlines;
6350 s->ndisplayed = 0;
6351 if (view_is_hsplit_top(view))
6352 --limit; /* border */
6354 werase(view->window);
6356 if (limit == 0)
6357 return NULL;
6359 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6360 0, 0);
6361 if (err)
6362 return err;
6363 if (view_needs_focus_indication(view))
6364 wstandout(view->window);
6365 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6366 if (tc)
6367 wattr_on(view->window,
6368 COLOR_PAIR(tc->colorpair), NULL);
6369 waddwstr(view->window, wline);
6370 if (tc)
6371 wattr_off(view->window,
6372 COLOR_PAIR(tc->colorpair), NULL);
6373 if (view_needs_focus_indication(view))
6374 wstandend(view->window);
6375 free(wline);
6376 wline = NULL;
6378 if (s->selected_entry) {
6379 i = got_tree_entry_get_index(s->selected_entry);
6380 i += s->tree == s->root ? 1 : 2; /* account for ".." entry */
6382 nentries = got_object_tree_get_nentries(s->tree);
6383 wprintw(view->window, " [%d/%d]", i,
6384 nentries + (s->tree == s->root ? 0 : 1)); /* ".." in !root tree */
6386 if (width < view->ncols - 1)
6387 waddch(view->window, '\n');
6388 if (--limit <= 0)
6389 return NULL;
6390 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6391 0, 0);
6392 if (err)
6393 return err;
6394 waddwstr(view->window, wline);
6395 free(wline);
6396 wline = NULL;
6397 if (width < view->ncols - 1)
6398 waddch(view->window, '\n');
6399 if (--limit <= 0)
6400 return NULL;
6401 waddch(view->window, '\n');
6402 if (--limit <= 0)
6403 return NULL;
6405 if (s->first_displayed_entry == NULL) {
6406 te = got_object_tree_get_first_entry(s->tree);
6407 if (s->selected == 0) {
6408 if (view->focussed)
6409 wstandout(view->window);
6410 s->selected_entry = NULL;
6412 waddstr(view->window, " ..\n"); /* parent directory */
6413 if (s->selected == 0 && view->focussed)
6414 wstandend(view->window);
6415 s->ndisplayed++;
6416 if (--limit <= 0)
6417 return NULL;
6418 n = 1;
6419 } else {
6420 n = 0;
6421 te = s->first_displayed_entry;
6424 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6425 char *line = NULL, *id_str = NULL, *link_target = NULL;
6426 const char *modestr = "";
6427 mode_t mode;
6429 te = got_object_tree_get_entry(s->tree, i);
6430 mode = got_tree_entry_get_mode(te);
6432 if (s->show_ids) {
6433 err = got_object_id_str(&id_str,
6434 got_tree_entry_get_id(te));
6435 if (err)
6436 return got_error_from_errno(
6437 "got_object_id_str");
6439 if (got_object_tree_entry_is_submodule(te))
6440 modestr = "$";
6441 else if (S_ISLNK(mode)) {
6442 int i;
6444 err = got_tree_entry_get_symlink_target(&link_target,
6445 te, s->repo);
6446 if (err) {
6447 free(id_str);
6448 return err;
6450 for (i = 0; i < strlen(link_target); i++) {
6451 if (!isprint((unsigned char)link_target[i]))
6452 link_target[i] = '?';
6454 modestr = "@";
6456 else if (S_ISDIR(mode))
6457 modestr = "/";
6458 else if (mode & S_IXUSR)
6459 modestr = "*";
6460 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6461 got_tree_entry_get_name(te), modestr,
6462 link_target ? " -> ": "",
6463 link_target ? link_target : "") == -1) {
6464 free(id_str);
6465 free(link_target);
6466 return got_error_from_errno("asprintf");
6468 free(id_str);
6469 free(link_target);
6470 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6471 0, 0);
6472 if (err) {
6473 free(line);
6474 break;
6476 if (n == s->selected) {
6477 if (view->focussed)
6478 wstandout(view->window);
6479 s->selected_entry = te;
6481 tc = match_color(&s->colors, line);
6482 if (tc)
6483 wattr_on(view->window,
6484 COLOR_PAIR(tc->colorpair), NULL);
6485 waddwstr(view->window, wline);
6486 if (tc)
6487 wattr_off(view->window,
6488 COLOR_PAIR(tc->colorpair), NULL);
6489 if (width < view->ncols - 1)
6490 waddch(view->window, '\n');
6491 if (n == s->selected && view->focussed)
6492 wstandend(view->window);
6493 free(line);
6494 free(wline);
6495 wline = NULL;
6496 n++;
6497 s->ndisplayed++;
6498 s->last_displayed_entry = te;
6499 if (--limit <= 0)
6500 break;
6503 return err;
6506 static void
6507 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6509 struct got_tree_entry *te;
6510 int isroot = s->tree == s->root;
6511 int i = 0;
6513 if (s->first_displayed_entry == NULL)
6514 return;
6516 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6517 while (i++ < maxscroll) {
6518 if (te == NULL) {
6519 if (!isroot)
6520 s->first_displayed_entry = NULL;
6521 break;
6523 s->first_displayed_entry = te;
6524 te = got_tree_entry_get_prev(s->tree, te);
6528 static const struct got_error *
6529 tree_scroll_down(struct tog_view *view, int maxscroll)
6531 struct tog_tree_view_state *s = &view->state.tree;
6532 struct got_tree_entry *next, *last;
6533 int n = 0;
6535 if (s->first_displayed_entry)
6536 next = got_tree_entry_get_next(s->tree,
6537 s->first_displayed_entry);
6538 else
6539 next = got_object_tree_get_first_entry(s->tree);
6541 last = s->last_displayed_entry;
6542 while (next && n++ < maxscroll) {
6543 if (last) {
6544 s->last_displayed_entry = last;
6545 last = got_tree_entry_get_next(s->tree, last);
6547 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6548 s->first_displayed_entry = next;
6549 next = got_tree_entry_get_next(s->tree, next);
6553 return NULL;
6556 static const struct got_error *
6557 tree_entry_path(char **path, struct tog_parent_trees *parents,
6558 struct got_tree_entry *te)
6560 const struct got_error *err = NULL;
6561 struct tog_parent_tree *pt;
6562 size_t len = 2; /* for leading slash and NUL */
6564 TAILQ_FOREACH(pt, parents, entry)
6565 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6566 + 1 /* slash */;
6567 if (te)
6568 len += strlen(got_tree_entry_get_name(te));
6570 *path = calloc(1, len);
6571 if (path == NULL)
6572 return got_error_from_errno("calloc");
6574 (*path)[0] = '/';
6575 pt = TAILQ_LAST(parents, tog_parent_trees);
6576 while (pt) {
6577 const char *name = got_tree_entry_get_name(pt->selected_entry);
6578 if (strlcat(*path, name, len) >= len) {
6579 err = got_error(GOT_ERR_NO_SPACE);
6580 goto done;
6582 if (strlcat(*path, "/", len) >= len) {
6583 err = got_error(GOT_ERR_NO_SPACE);
6584 goto done;
6586 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6588 if (te) {
6589 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6590 err = got_error(GOT_ERR_NO_SPACE);
6591 goto done;
6594 done:
6595 if (err) {
6596 free(*path);
6597 *path = NULL;
6599 return err;
6602 static const struct got_error *
6603 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6604 struct got_tree_entry *te, struct tog_parent_trees *parents,
6605 struct got_object_id *commit_id, struct got_repository *repo)
6607 const struct got_error *err = NULL;
6608 char *path;
6609 struct tog_view *blame_view;
6611 *new_view = NULL;
6613 err = tree_entry_path(&path, parents, te);
6614 if (err)
6615 return err;
6617 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6618 if (blame_view == NULL) {
6619 err = got_error_from_errno("view_open");
6620 goto done;
6623 err = open_blame_view(blame_view, path, commit_id, repo);
6624 if (err) {
6625 if (err->code == GOT_ERR_CANCELLED)
6626 err = NULL;
6627 view_close(blame_view);
6628 } else
6629 *new_view = blame_view;
6630 done:
6631 free(path);
6632 return err;
6635 static const struct got_error *
6636 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6637 struct tog_tree_view_state *s)
6639 struct tog_view *log_view;
6640 const struct got_error *err = NULL;
6641 char *path;
6643 *new_view = NULL;
6645 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6646 if (log_view == NULL)
6647 return got_error_from_errno("view_open");
6649 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6650 if (err)
6651 return err;
6653 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6654 path, 0);
6655 if (err)
6656 view_close(log_view);
6657 else
6658 *new_view = log_view;
6659 free(path);
6660 return err;
6663 static const struct got_error *
6664 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6665 const char *head_ref_name, struct got_repository *repo)
6667 const struct got_error *err = NULL;
6668 char *commit_id_str = NULL;
6669 struct tog_tree_view_state *s = &view->state.tree;
6670 struct got_commit_object *commit = NULL;
6672 TAILQ_INIT(&s->parents);
6673 STAILQ_INIT(&s->colors);
6675 s->commit_id = got_object_id_dup(commit_id);
6676 if (s->commit_id == NULL)
6677 return got_error_from_errno("got_object_id_dup");
6679 err = got_object_open_as_commit(&commit, repo, commit_id);
6680 if (err)
6681 goto done;
6684 * The root is opened here and will be closed when the view is closed.
6685 * Any visited subtrees and their path-wise parents are opened and
6686 * closed on demand.
6688 err = got_object_open_as_tree(&s->root, repo,
6689 got_object_commit_get_tree_id(commit));
6690 if (err)
6691 goto done;
6692 s->tree = s->root;
6694 err = got_object_id_str(&commit_id_str, commit_id);
6695 if (err != NULL)
6696 goto done;
6698 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6699 err = got_error_from_errno("asprintf");
6700 goto done;
6703 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6704 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6705 if (head_ref_name) {
6706 s->head_ref_name = strdup(head_ref_name);
6707 if (s->head_ref_name == NULL) {
6708 err = got_error_from_errno("strdup");
6709 goto done;
6712 s->repo = repo;
6714 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6715 err = add_color(&s->colors, "\\$$",
6716 TOG_COLOR_TREE_SUBMODULE,
6717 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6718 if (err)
6719 goto done;
6720 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6721 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6722 if (err)
6723 goto done;
6724 err = add_color(&s->colors, "/$",
6725 TOG_COLOR_TREE_DIRECTORY,
6726 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6727 if (err)
6728 goto done;
6730 err = add_color(&s->colors, "\\*$",
6731 TOG_COLOR_TREE_EXECUTABLE,
6732 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6733 if (err)
6734 goto done;
6736 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6737 get_color_value("TOG_COLOR_COMMIT"));
6738 if (err)
6739 goto done;
6742 view->show = show_tree_view;
6743 view->input = input_tree_view;
6744 view->close = close_tree_view;
6745 view->search_start = search_start_tree_view;
6746 view->search_next = search_next_tree_view;
6747 done:
6748 free(commit_id_str);
6749 if (commit)
6750 got_object_commit_close(commit);
6751 if (err)
6752 close_tree_view(view);
6753 return err;
6756 static const struct got_error *
6757 close_tree_view(struct tog_view *view)
6759 struct tog_tree_view_state *s = &view->state.tree;
6761 free_colors(&s->colors);
6762 free(s->tree_label);
6763 s->tree_label = NULL;
6764 free(s->commit_id);
6765 s->commit_id = NULL;
6766 free(s->head_ref_name);
6767 s->head_ref_name = NULL;
6768 while (!TAILQ_EMPTY(&s->parents)) {
6769 struct tog_parent_tree *parent;
6770 parent = TAILQ_FIRST(&s->parents);
6771 TAILQ_REMOVE(&s->parents, parent, entry);
6772 if (parent->tree != s->root)
6773 got_object_tree_close(parent->tree);
6774 free(parent);
6777 if (s->tree != NULL && s->tree != s->root)
6778 got_object_tree_close(s->tree);
6779 if (s->root)
6780 got_object_tree_close(s->root);
6781 return NULL;
6784 static const struct got_error *
6785 search_start_tree_view(struct tog_view *view)
6787 struct tog_tree_view_state *s = &view->state.tree;
6789 s->matched_entry = NULL;
6790 return NULL;
6793 static int
6794 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6796 regmatch_t regmatch;
6798 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6799 0) == 0;
6802 static const struct got_error *
6803 search_next_tree_view(struct tog_view *view)
6805 struct tog_tree_view_state *s = &view->state.tree;
6806 struct got_tree_entry *te = NULL;
6808 if (!view->searching) {
6809 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6810 return NULL;
6813 if (s->matched_entry) {
6814 if (view->searching == TOG_SEARCH_FORWARD) {
6815 if (s->selected_entry)
6816 te = got_tree_entry_get_next(s->tree,
6817 s->selected_entry);
6818 else
6819 te = got_object_tree_get_first_entry(s->tree);
6820 } else {
6821 if (s->selected_entry == NULL)
6822 te = got_object_tree_get_last_entry(s->tree);
6823 else
6824 te = got_tree_entry_get_prev(s->tree,
6825 s->selected_entry);
6827 } else {
6828 if (s->selected_entry)
6829 te = s->selected_entry;
6830 else if (view->searching == TOG_SEARCH_FORWARD)
6831 te = got_object_tree_get_first_entry(s->tree);
6832 else
6833 te = got_object_tree_get_last_entry(s->tree);
6836 while (1) {
6837 if (te == NULL) {
6838 if (s->matched_entry == NULL) {
6839 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6840 return NULL;
6842 if (view->searching == TOG_SEARCH_FORWARD)
6843 te = got_object_tree_get_first_entry(s->tree);
6844 else
6845 te = got_object_tree_get_last_entry(s->tree);
6848 if (match_tree_entry(te, &view->regex)) {
6849 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6850 s->matched_entry = te;
6851 break;
6854 if (view->searching == TOG_SEARCH_FORWARD)
6855 te = got_tree_entry_get_next(s->tree, te);
6856 else
6857 te = got_tree_entry_get_prev(s->tree, te);
6860 if (s->matched_entry) {
6861 s->first_displayed_entry = s->matched_entry;
6862 s->selected = 0;
6865 return NULL;
6868 static const struct got_error *
6869 show_tree_view(struct tog_view *view)
6871 const struct got_error *err = NULL;
6872 struct tog_tree_view_state *s = &view->state.tree;
6873 char *parent_path;
6875 err = tree_entry_path(&parent_path, &s->parents, NULL);
6876 if (err)
6877 return err;
6879 err = draw_tree_entries(view, parent_path);
6880 free(parent_path);
6882 view_border(view);
6883 return err;
6886 static const struct got_error *
6887 tree_goto_line(struct tog_view *view, int nlines)
6889 const struct got_error *err = NULL;
6890 struct tog_tree_view_state *s = &view->state.tree;
6891 struct got_tree_entry **fte, **lte, **ste;
6892 int g, last, first = 1, i = 1;
6893 int root = s->tree == s->root;
6894 int off = root ? 1 : 2;
6896 g = view->gline;
6897 view->gline = 0;
6899 if (g == 0)
6900 g = 1;
6901 else if (g > got_object_tree_get_nentries(s->tree))
6902 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
6904 fte = &s->first_displayed_entry;
6905 lte = &s->last_displayed_entry;
6906 ste = &s->selected_entry;
6908 if (*fte != NULL) {
6909 first = got_tree_entry_get_index(*fte);
6910 first += off; /* account for ".." */
6912 last = got_tree_entry_get_index(*lte);
6913 last += off;
6915 if (g >= first && g <= last && g - first < nlines) {
6916 s->selected = g - first;
6917 return NULL; /* gline is on the current page */
6920 if (*ste != NULL) {
6921 i = got_tree_entry_get_index(*ste);
6922 i += off;
6925 if (i < g) {
6926 err = tree_scroll_down(view, g - i);
6927 if (err)
6928 return err;
6929 if (got_tree_entry_get_index(*lte) >=
6930 got_object_tree_get_nentries(s->tree) - 1 &&
6931 first + s->selected < g &&
6932 s->selected < s->ndisplayed - 1) {
6933 first = got_tree_entry_get_index(*fte);
6934 first += off;
6935 s->selected = g - first;
6937 } else if (i > g)
6938 tree_scroll_up(s, i - g);
6940 if (g < nlines &&
6941 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
6942 s->selected = g - 1;
6944 return NULL;
6947 static const struct got_error *
6948 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6950 const struct got_error *err = NULL;
6951 struct tog_tree_view_state *s = &view->state.tree;
6952 struct got_tree_entry *te;
6953 int n, nscroll = view->nlines - 3;
6955 if (view->gline)
6956 return tree_goto_line(view, nscroll);
6958 switch (ch) {
6959 case 'i':
6960 s->show_ids = !s->show_ids;
6961 view->count = 0;
6962 break;
6963 case 'L':
6964 view->count = 0;
6965 if (!s->selected_entry)
6966 break;
6967 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6968 break;
6969 case 'R':
6970 view->count = 0;
6971 err = view_request_new(new_view, view, TOG_VIEW_REF);
6972 break;
6973 case 'g':
6974 case KEY_HOME:
6975 s->selected = 0;
6976 view->count = 0;
6977 if (s->tree == s->root)
6978 s->first_displayed_entry =
6979 got_object_tree_get_first_entry(s->tree);
6980 else
6981 s->first_displayed_entry = NULL;
6982 break;
6983 case 'G':
6984 case KEY_END: {
6985 int eos = view->nlines - 3;
6987 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6988 --eos; /* border */
6989 s->selected = 0;
6990 view->count = 0;
6991 te = got_object_tree_get_last_entry(s->tree);
6992 for (n = 0; n < eos; n++) {
6993 if (te == NULL) {
6994 if (s->tree != s->root) {
6995 s->first_displayed_entry = NULL;
6996 n++;
6998 break;
7000 s->first_displayed_entry = te;
7001 te = got_tree_entry_get_prev(s->tree, te);
7003 if (n > 0)
7004 s->selected = n - 1;
7005 break;
7007 case 'k':
7008 case KEY_UP:
7009 case CTRL('p'):
7010 if (s->selected > 0) {
7011 s->selected--;
7012 break;
7014 tree_scroll_up(s, 1);
7015 if (s->selected_entry == NULL ||
7016 (s->tree == s->root && s->selected_entry ==
7017 got_object_tree_get_first_entry(s->tree)))
7018 view->count = 0;
7019 break;
7020 case CTRL('u'):
7021 case 'u':
7022 nscroll /= 2;
7023 /* FALL THROUGH */
7024 case KEY_PPAGE:
7025 case CTRL('b'):
7026 case 'b':
7027 if (s->tree == s->root) {
7028 if (got_object_tree_get_first_entry(s->tree) ==
7029 s->first_displayed_entry)
7030 s->selected -= MIN(s->selected, nscroll);
7031 } else {
7032 if (s->first_displayed_entry == NULL)
7033 s->selected -= MIN(s->selected, nscroll);
7035 tree_scroll_up(s, MAX(0, nscroll));
7036 if (s->selected_entry == NULL ||
7037 (s->tree == s->root && s->selected_entry ==
7038 got_object_tree_get_first_entry(s->tree)))
7039 view->count = 0;
7040 break;
7041 case 'j':
7042 case KEY_DOWN:
7043 case CTRL('n'):
7044 if (s->selected < s->ndisplayed - 1) {
7045 s->selected++;
7046 break;
7048 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7049 == NULL) {
7050 /* can't scroll any further */
7051 view->count = 0;
7052 break;
7054 tree_scroll_down(view, 1);
7055 break;
7056 case CTRL('d'):
7057 case 'd':
7058 nscroll /= 2;
7059 /* FALL THROUGH */
7060 case KEY_NPAGE:
7061 case CTRL('f'):
7062 case 'f':
7063 case ' ':
7064 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7065 == NULL) {
7066 /* can't scroll any further; move cursor down */
7067 if (s->selected < s->ndisplayed - 1)
7068 s->selected += MIN(nscroll,
7069 s->ndisplayed - s->selected - 1);
7070 else
7071 view->count = 0;
7072 break;
7074 tree_scroll_down(view, nscroll);
7075 break;
7076 case KEY_ENTER:
7077 case '\r':
7078 case KEY_BACKSPACE:
7079 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7080 struct tog_parent_tree *parent;
7081 /* user selected '..' */
7082 if (s->tree == s->root) {
7083 view->count = 0;
7084 break;
7086 parent = TAILQ_FIRST(&s->parents);
7087 TAILQ_REMOVE(&s->parents, parent,
7088 entry);
7089 got_object_tree_close(s->tree);
7090 s->tree = parent->tree;
7091 s->first_displayed_entry =
7092 parent->first_displayed_entry;
7093 s->selected_entry =
7094 parent->selected_entry;
7095 s->selected = parent->selected;
7096 if (s->selected > view->nlines - 3) {
7097 err = offset_selection_down(view);
7098 if (err)
7099 break;
7101 free(parent);
7102 } else if (S_ISDIR(got_tree_entry_get_mode(
7103 s->selected_entry))) {
7104 struct got_tree_object *subtree;
7105 view->count = 0;
7106 err = got_object_open_as_tree(&subtree, s->repo,
7107 got_tree_entry_get_id(s->selected_entry));
7108 if (err)
7109 break;
7110 err = tree_view_visit_subtree(s, subtree);
7111 if (err) {
7112 got_object_tree_close(subtree);
7113 break;
7115 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7116 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7117 break;
7118 case KEY_RESIZE:
7119 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7120 s->selected = view->nlines - 4;
7121 view->count = 0;
7122 break;
7123 default:
7124 view->count = 0;
7125 break;
7128 return err;
7131 __dead static void
7132 usage_tree(void)
7134 endwin();
7135 fprintf(stderr,
7136 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7137 getprogname());
7138 exit(1);
7141 static const struct got_error *
7142 cmd_tree(int argc, char *argv[])
7144 const struct got_error *error;
7145 struct got_repository *repo = NULL;
7146 struct got_worktree *worktree = NULL;
7147 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7148 struct got_object_id *commit_id = NULL;
7149 struct got_commit_object *commit = NULL;
7150 const char *commit_id_arg = NULL;
7151 char *label = NULL;
7152 struct got_reference *ref = NULL;
7153 const char *head_ref_name = NULL;
7154 int ch;
7155 struct tog_view *view;
7156 int *pack_fds = NULL;
7158 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7159 switch (ch) {
7160 case 'c':
7161 commit_id_arg = optarg;
7162 break;
7163 case 'r':
7164 repo_path = realpath(optarg, NULL);
7165 if (repo_path == NULL)
7166 return got_error_from_errno2("realpath",
7167 optarg);
7168 break;
7169 default:
7170 usage_tree();
7171 /* NOTREACHED */
7175 argc -= optind;
7176 argv += optind;
7178 if (argc > 1)
7179 usage_tree();
7181 error = got_repo_pack_fds_open(&pack_fds);
7182 if (error != NULL)
7183 goto done;
7185 if (repo_path == NULL) {
7186 cwd = getcwd(NULL, 0);
7187 if (cwd == NULL)
7188 return got_error_from_errno("getcwd");
7189 error = got_worktree_open(&worktree, cwd);
7190 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7191 goto done;
7192 if (worktree)
7193 repo_path =
7194 strdup(got_worktree_get_repo_path(worktree));
7195 else
7196 repo_path = strdup(cwd);
7197 if (repo_path == NULL) {
7198 error = got_error_from_errno("strdup");
7199 goto done;
7203 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7204 if (error != NULL)
7205 goto done;
7207 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7208 repo, worktree);
7209 if (error)
7210 goto done;
7212 init_curses();
7214 error = apply_unveil(got_repo_get_path(repo), NULL);
7215 if (error)
7216 goto done;
7218 error = tog_load_refs(repo, 0);
7219 if (error)
7220 goto done;
7222 if (commit_id_arg == NULL) {
7223 error = got_repo_match_object_id(&commit_id, &label,
7224 worktree ? got_worktree_get_head_ref_name(worktree) :
7225 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7226 if (error)
7227 goto done;
7228 head_ref_name = label;
7229 } else {
7230 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7231 if (error == NULL)
7232 head_ref_name = got_ref_get_name(ref);
7233 else if (error->code != GOT_ERR_NOT_REF)
7234 goto done;
7235 error = got_repo_match_object_id(&commit_id, NULL,
7236 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7237 if (error)
7238 goto done;
7241 error = got_object_open_as_commit(&commit, repo, commit_id);
7242 if (error)
7243 goto done;
7245 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7246 if (view == NULL) {
7247 error = got_error_from_errno("view_open");
7248 goto done;
7250 error = open_tree_view(view, commit_id, head_ref_name, repo);
7251 if (error)
7252 goto done;
7253 if (!got_path_is_root_dir(in_repo_path)) {
7254 error = tree_view_walk_path(&view->state.tree, commit,
7255 in_repo_path);
7256 if (error)
7257 goto done;
7260 if (worktree) {
7261 /* Release work tree lock. */
7262 got_worktree_close(worktree);
7263 worktree = NULL;
7265 error = view_loop(view);
7266 done:
7267 free(repo_path);
7268 free(cwd);
7269 free(commit_id);
7270 free(label);
7271 if (ref)
7272 got_ref_close(ref);
7273 if (repo) {
7274 const struct got_error *close_err = got_repo_close(repo);
7275 if (error == NULL)
7276 error = close_err;
7278 if (pack_fds) {
7279 const struct got_error *pack_err =
7280 got_repo_pack_fds_close(pack_fds);
7281 if (error == NULL)
7282 error = pack_err;
7284 tog_free_refs();
7285 return error;
7288 static const struct got_error *
7289 ref_view_load_refs(struct tog_ref_view_state *s)
7291 struct got_reflist_entry *sre;
7292 struct tog_reflist_entry *re;
7294 s->nrefs = 0;
7295 TAILQ_FOREACH(sre, &tog_refs, entry) {
7296 if (strncmp(got_ref_get_name(sre->ref),
7297 "refs/got/", 9) == 0 &&
7298 strncmp(got_ref_get_name(sre->ref),
7299 "refs/got/backup/", 16) != 0)
7300 continue;
7302 re = malloc(sizeof(*re));
7303 if (re == NULL)
7304 return got_error_from_errno("malloc");
7306 re->ref = got_ref_dup(sre->ref);
7307 if (re->ref == NULL)
7308 return got_error_from_errno("got_ref_dup");
7309 re->idx = s->nrefs++;
7310 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7313 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7314 return NULL;
7317 static void
7318 ref_view_free_refs(struct tog_ref_view_state *s)
7320 struct tog_reflist_entry *re;
7322 while (!TAILQ_EMPTY(&s->refs)) {
7323 re = TAILQ_FIRST(&s->refs);
7324 TAILQ_REMOVE(&s->refs, re, entry);
7325 got_ref_close(re->ref);
7326 free(re);
7330 static const struct got_error *
7331 open_ref_view(struct tog_view *view, struct got_repository *repo)
7333 const struct got_error *err = NULL;
7334 struct tog_ref_view_state *s = &view->state.ref;
7336 s->selected_entry = 0;
7337 s->repo = repo;
7339 TAILQ_INIT(&s->refs);
7340 STAILQ_INIT(&s->colors);
7342 err = ref_view_load_refs(s);
7343 if (err)
7344 return err;
7346 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7347 err = add_color(&s->colors, "^refs/heads/",
7348 TOG_COLOR_REFS_HEADS,
7349 get_color_value("TOG_COLOR_REFS_HEADS"));
7350 if (err)
7351 goto done;
7353 err = add_color(&s->colors, "^refs/tags/",
7354 TOG_COLOR_REFS_TAGS,
7355 get_color_value("TOG_COLOR_REFS_TAGS"));
7356 if (err)
7357 goto done;
7359 err = add_color(&s->colors, "^refs/remotes/",
7360 TOG_COLOR_REFS_REMOTES,
7361 get_color_value("TOG_COLOR_REFS_REMOTES"));
7362 if (err)
7363 goto done;
7365 err = add_color(&s->colors, "^refs/got/backup/",
7366 TOG_COLOR_REFS_BACKUP,
7367 get_color_value("TOG_COLOR_REFS_BACKUP"));
7368 if (err)
7369 goto done;
7372 view->show = show_ref_view;
7373 view->input = input_ref_view;
7374 view->close = close_ref_view;
7375 view->search_start = search_start_ref_view;
7376 view->search_next = search_next_ref_view;
7377 done:
7378 if (err)
7379 free_colors(&s->colors);
7380 return err;
7383 static const struct got_error *
7384 close_ref_view(struct tog_view *view)
7386 struct tog_ref_view_state *s = &view->state.ref;
7388 ref_view_free_refs(s);
7389 free_colors(&s->colors);
7391 return NULL;
7394 static const struct got_error *
7395 resolve_reflist_entry(struct got_object_id **commit_id,
7396 struct tog_reflist_entry *re, struct got_repository *repo)
7398 const struct got_error *err = NULL;
7399 struct got_object_id *obj_id;
7400 struct got_tag_object *tag = NULL;
7401 int obj_type;
7403 *commit_id = NULL;
7405 err = got_ref_resolve(&obj_id, repo, re->ref);
7406 if (err)
7407 return err;
7409 err = got_object_get_type(&obj_type, repo, obj_id);
7410 if (err)
7411 goto done;
7413 switch (obj_type) {
7414 case GOT_OBJ_TYPE_COMMIT:
7415 *commit_id = obj_id;
7416 break;
7417 case GOT_OBJ_TYPE_TAG:
7418 err = got_object_open_as_tag(&tag, repo, obj_id);
7419 if (err)
7420 goto done;
7421 free(obj_id);
7422 err = got_object_get_type(&obj_type, repo,
7423 got_object_tag_get_object_id(tag));
7424 if (err)
7425 goto done;
7426 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7427 err = got_error(GOT_ERR_OBJ_TYPE);
7428 goto done;
7430 *commit_id = got_object_id_dup(
7431 got_object_tag_get_object_id(tag));
7432 if (*commit_id == NULL) {
7433 err = got_error_from_errno("got_object_id_dup");
7434 goto done;
7436 break;
7437 default:
7438 err = got_error(GOT_ERR_OBJ_TYPE);
7439 break;
7442 done:
7443 if (tag)
7444 got_object_tag_close(tag);
7445 if (err) {
7446 free(*commit_id);
7447 *commit_id = NULL;
7449 return err;
7452 static const struct got_error *
7453 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7454 struct tog_reflist_entry *re, struct got_repository *repo)
7456 struct tog_view *log_view;
7457 const struct got_error *err = NULL;
7458 struct got_object_id *commit_id = NULL;
7460 *new_view = NULL;
7462 err = resolve_reflist_entry(&commit_id, re, repo);
7463 if (err) {
7464 if (err->code != GOT_ERR_OBJ_TYPE)
7465 return err;
7466 else
7467 return NULL;
7470 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7471 if (log_view == NULL) {
7472 err = got_error_from_errno("view_open");
7473 goto done;
7476 err = open_log_view(log_view, commit_id, repo,
7477 got_ref_get_name(re->ref), "", 0);
7478 done:
7479 if (err)
7480 view_close(log_view);
7481 else
7482 *new_view = log_view;
7483 free(commit_id);
7484 return err;
7487 static void
7488 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7490 struct tog_reflist_entry *re;
7491 int i = 0;
7493 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7494 return;
7496 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7497 while (i++ < maxscroll) {
7498 if (re == NULL)
7499 break;
7500 s->first_displayed_entry = re;
7501 re = TAILQ_PREV(re, tog_reflist_head, entry);
7505 static const struct got_error *
7506 ref_scroll_down(struct tog_view *view, int maxscroll)
7508 struct tog_ref_view_state *s = &view->state.ref;
7509 struct tog_reflist_entry *next, *last;
7510 int n = 0;
7512 if (s->first_displayed_entry)
7513 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7514 else
7515 next = TAILQ_FIRST(&s->refs);
7517 last = s->last_displayed_entry;
7518 while (next && n++ < maxscroll) {
7519 if (last) {
7520 s->last_displayed_entry = last;
7521 last = TAILQ_NEXT(last, entry);
7523 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7524 s->first_displayed_entry = next;
7525 next = TAILQ_NEXT(next, entry);
7529 return NULL;
7532 static const struct got_error *
7533 search_start_ref_view(struct tog_view *view)
7535 struct tog_ref_view_state *s = &view->state.ref;
7537 s->matched_entry = NULL;
7538 return NULL;
7541 static int
7542 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7544 regmatch_t regmatch;
7546 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7547 0) == 0;
7550 static const struct got_error *
7551 search_next_ref_view(struct tog_view *view)
7553 struct tog_ref_view_state *s = &view->state.ref;
7554 struct tog_reflist_entry *re = NULL;
7556 if (!view->searching) {
7557 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7558 return NULL;
7561 if (s->matched_entry) {
7562 if (view->searching == TOG_SEARCH_FORWARD) {
7563 if (s->selected_entry)
7564 re = TAILQ_NEXT(s->selected_entry, entry);
7565 else
7566 re = TAILQ_PREV(s->selected_entry,
7567 tog_reflist_head, entry);
7568 } else {
7569 if (s->selected_entry == NULL)
7570 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7571 else
7572 re = TAILQ_PREV(s->selected_entry,
7573 tog_reflist_head, entry);
7575 } else {
7576 if (s->selected_entry)
7577 re = s->selected_entry;
7578 else if (view->searching == TOG_SEARCH_FORWARD)
7579 re = TAILQ_FIRST(&s->refs);
7580 else
7581 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7584 while (1) {
7585 if (re == NULL) {
7586 if (s->matched_entry == NULL) {
7587 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7588 return NULL;
7590 if (view->searching == TOG_SEARCH_FORWARD)
7591 re = TAILQ_FIRST(&s->refs);
7592 else
7593 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7596 if (match_reflist_entry(re, &view->regex)) {
7597 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7598 s->matched_entry = re;
7599 break;
7602 if (view->searching == TOG_SEARCH_FORWARD)
7603 re = TAILQ_NEXT(re, entry);
7604 else
7605 re = TAILQ_PREV(re, tog_reflist_head, entry);
7608 if (s->matched_entry) {
7609 s->first_displayed_entry = s->matched_entry;
7610 s->selected = 0;
7613 return NULL;
7616 static const struct got_error *
7617 show_ref_view(struct tog_view *view)
7619 const struct got_error *err = NULL;
7620 struct tog_ref_view_state *s = &view->state.ref;
7621 struct tog_reflist_entry *re;
7622 char *line = NULL;
7623 wchar_t *wline;
7624 struct tog_color *tc;
7625 int width, n;
7626 int limit = view->nlines;
7628 werase(view->window);
7630 s->ndisplayed = 0;
7631 if (view_is_hsplit_top(view))
7632 --limit; /* border */
7634 if (limit == 0)
7635 return NULL;
7637 re = s->first_displayed_entry;
7639 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7640 s->nrefs) == -1)
7641 return got_error_from_errno("asprintf");
7643 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7644 if (err) {
7645 free(line);
7646 return err;
7648 if (view_needs_focus_indication(view))
7649 wstandout(view->window);
7650 waddwstr(view->window, wline);
7651 if (view_needs_focus_indication(view))
7652 wstandend(view->window);
7653 free(wline);
7654 wline = NULL;
7655 free(line);
7656 line = NULL;
7657 if (width < view->ncols - 1)
7658 waddch(view->window, '\n');
7659 if (--limit <= 0)
7660 return NULL;
7662 n = 0;
7663 while (re && limit > 0) {
7664 char *line = NULL;
7665 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7667 if (s->show_date) {
7668 struct got_commit_object *ci;
7669 struct got_tag_object *tag;
7670 struct got_object_id *id;
7671 struct tm tm;
7672 time_t t;
7674 err = got_ref_resolve(&id, s->repo, re->ref);
7675 if (err)
7676 return err;
7677 err = got_object_open_as_tag(&tag, s->repo, id);
7678 if (err) {
7679 if (err->code != GOT_ERR_OBJ_TYPE) {
7680 free(id);
7681 return err;
7683 err = got_object_open_as_commit(&ci, s->repo,
7684 id);
7685 if (err) {
7686 free(id);
7687 return err;
7689 t = got_object_commit_get_committer_time(ci);
7690 got_object_commit_close(ci);
7691 } else {
7692 t = got_object_tag_get_tagger_time(tag);
7693 got_object_tag_close(tag);
7695 free(id);
7696 if (gmtime_r(&t, &tm) == NULL)
7697 return got_error_from_errno("gmtime_r");
7698 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7699 return got_error(GOT_ERR_NO_SPACE);
7701 if (got_ref_is_symbolic(re->ref)) {
7702 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7703 ymd : "", got_ref_get_name(re->ref),
7704 got_ref_get_symref_target(re->ref)) == -1)
7705 return got_error_from_errno("asprintf");
7706 } else if (s->show_ids) {
7707 struct got_object_id *id;
7708 char *id_str;
7709 err = got_ref_resolve(&id, s->repo, re->ref);
7710 if (err)
7711 return err;
7712 err = got_object_id_str(&id_str, id);
7713 if (err) {
7714 free(id);
7715 return err;
7717 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7718 got_ref_get_name(re->ref), id_str) == -1) {
7719 err = got_error_from_errno("asprintf");
7720 free(id);
7721 free(id_str);
7722 return err;
7724 free(id);
7725 free(id_str);
7726 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7727 got_ref_get_name(re->ref)) == -1)
7728 return got_error_from_errno("asprintf");
7730 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7731 0, 0);
7732 if (err) {
7733 free(line);
7734 return err;
7736 if (n == s->selected) {
7737 if (view->focussed)
7738 wstandout(view->window);
7739 s->selected_entry = re;
7741 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7742 if (tc)
7743 wattr_on(view->window,
7744 COLOR_PAIR(tc->colorpair), NULL);
7745 waddwstr(view->window, wline);
7746 if (tc)
7747 wattr_off(view->window,
7748 COLOR_PAIR(tc->colorpair), NULL);
7749 if (width < view->ncols - 1)
7750 waddch(view->window, '\n');
7751 if (n == s->selected && view->focussed)
7752 wstandend(view->window);
7753 free(line);
7754 free(wline);
7755 wline = NULL;
7756 n++;
7757 s->ndisplayed++;
7758 s->last_displayed_entry = re;
7760 limit--;
7761 re = TAILQ_NEXT(re, entry);
7764 view_border(view);
7765 return err;
7768 static const struct got_error *
7769 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7770 struct tog_reflist_entry *re, struct got_repository *repo)
7772 const struct got_error *err = NULL;
7773 struct got_object_id *commit_id = NULL;
7774 struct tog_view *tree_view;
7776 *new_view = NULL;
7778 err = resolve_reflist_entry(&commit_id, re, repo);
7779 if (err) {
7780 if (err->code != GOT_ERR_OBJ_TYPE)
7781 return err;
7782 else
7783 return NULL;
7787 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7788 if (tree_view == NULL) {
7789 err = got_error_from_errno("view_open");
7790 goto done;
7793 err = open_tree_view(tree_view, commit_id,
7794 got_ref_get_name(re->ref), repo);
7795 if (err)
7796 goto done;
7798 *new_view = tree_view;
7799 done:
7800 free(commit_id);
7801 return err;
7804 static const struct got_error *
7805 ref_goto_line(struct tog_view *view, int nlines)
7807 const struct got_error *err = NULL;
7808 struct tog_ref_view_state *s = &view->state.ref;
7809 int g, idx = s->selected_entry->idx;
7811 g = view->gline;
7812 view->gline = 0;
7814 if (g == 0)
7815 g = 1;
7816 else if (g > s->nrefs)
7817 g = s->nrefs;
7819 if (g >= s->first_displayed_entry->idx + 1 &&
7820 g <= s->last_displayed_entry->idx + 1 &&
7821 g - s->first_displayed_entry->idx - 1 < nlines) {
7822 s->selected = g - s->first_displayed_entry->idx - 1;
7823 return NULL;
7826 if (idx + 1 < g) {
7827 err = ref_scroll_down(view, g - idx - 1);
7828 if (err)
7829 return err;
7830 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
7831 s->first_displayed_entry->idx + s->selected < g &&
7832 s->selected < s->ndisplayed - 1)
7833 s->selected = g - s->first_displayed_entry->idx - 1;
7834 } else if (idx + 1 > g)
7835 ref_scroll_up(s, idx - g + 1);
7837 if (g < nlines && s->first_displayed_entry->idx == 0)
7838 s->selected = g - 1;
7840 return NULL;
7844 static const struct got_error *
7845 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7847 const struct got_error *err = NULL;
7848 struct tog_ref_view_state *s = &view->state.ref;
7849 struct tog_reflist_entry *re;
7850 int n, nscroll = view->nlines - 1;
7852 if (view->gline)
7853 return ref_goto_line(view, nscroll);
7855 switch (ch) {
7856 case 'i':
7857 s->show_ids = !s->show_ids;
7858 view->count = 0;
7859 break;
7860 case 'm':
7861 s->show_date = !s->show_date;
7862 view->count = 0;
7863 break;
7864 case 'o':
7865 s->sort_by_date = !s->sort_by_date;
7866 view->count = 0;
7867 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7868 got_ref_cmp_by_commit_timestamp_descending :
7869 tog_ref_cmp_by_name, s->repo);
7870 if (err)
7871 break;
7872 got_reflist_object_id_map_free(tog_refs_idmap);
7873 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7874 &tog_refs, s->repo);
7875 if (err)
7876 break;
7877 ref_view_free_refs(s);
7878 err = ref_view_load_refs(s);
7879 break;
7880 case KEY_ENTER:
7881 case '\r':
7882 view->count = 0;
7883 if (!s->selected_entry)
7884 break;
7885 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7886 break;
7887 case 'T':
7888 view->count = 0;
7889 if (!s->selected_entry)
7890 break;
7891 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7892 break;
7893 case 'g':
7894 case KEY_HOME:
7895 s->selected = 0;
7896 view->count = 0;
7897 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7898 break;
7899 case 'G':
7900 case KEY_END: {
7901 int eos = view->nlines - 1;
7903 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7904 --eos; /* border */
7905 s->selected = 0;
7906 view->count = 0;
7907 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7908 for (n = 0; n < eos; n++) {
7909 if (re == NULL)
7910 break;
7911 s->first_displayed_entry = re;
7912 re = TAILQ_PREV(re, tog_reflist_head, entry);
7914 if (n > 0)
7915 s->selected = n - 1;
7916 break;
7918 case 'k':
7919 case KEY_UP:
7920 case CTRL('p'):
7921 if (s->selected > 0) {
7922 s->selected--;
7923 break;
7925 ref_scroll_up(s, 1);
7926 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7927 view->count = 0;
7928 break;
7929 case CTRL('u'):
7930 case 'u':
7931 nscroll /= 2;
7932 /* FALL THROUGH */
7933 case KEY_PPAGE:
7934 case CTRL('b'):
7935 case 'b':
7936 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7937 s->selected -= MIN(nscroll, s->selected);
7938 ref_scroll_up(s, MAX(0, nscroll));
7939 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7940 view->count = 0;
7941 break;
7942 case 'j':
7943 case KEY_DOWN:
7944 case CTRL('n'):
7945 if (s->selected < s->ndisplayed - 1) {
7946 s->selected++;
7947 break;
7949 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7950 /* can't scroll any further */
7951 view->count = 0;
7952 break;
7954 ref_scroll_down(view, 1);
7955 break;
7956 case CTRL('d'):
7957 case 'd':
7958 nscroll /= 2;
7959 /* FALL THROUGH */
7960 case KEY_NPAGE:
7961 case CTRL('f'):
7962 case 'f':
7963 case ' ':
7964 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7965 /* can't scroll any further; move cursor down */
7966 if (s->selected < s->ndisplayed - 1)
7967 s->selected += MIN(nscroll,
7968 s->ndisplayed - s->selected - 1);
7969 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7970 s->selected += s->ndisplayed - s->selected - 1;
7971 view->count = 0;
7972 break;
7974 ref_scroll_down(view, nscroll);
7975 break;
7976 case CTRL('l'):
7977 view->count = 0;
7978 tog_free_refs();
7979 err = tog_load_refs(s->repo, s->sort_by_date);
7980 if (err)
7981 break;
7982 ref_view_free_refs(s);
7983 err = ref_view_load_refs(s);
7984 break;
7985 case KEY_RESIZE:
7986 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7987 s->selected = view->nlines - 2;
7988 break;
7989 default:
7990 view->count = 0;
7991 break;
7994 return err;
7997 __dead static void
7998 usage_ref(void)
8000 endwin();
8001 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8002 getprogname());
8003 exit(1);
8006 static const struct got_error *
8007 cmd_ref(int argc, char *argv[])
8009 const struct got_error *error;
8010 struct got_repository *repo = NULL;
8011 struct got_worktree *worktree = NULL;
8012 char *cwd = NULL, *repo_path = NULL;
8013 int ch;
8014 struct tog_view *view;
8015 int *pack_fds = NULL;
8017 while ((ch = getopt(argc, argv, "r:")) != -1) {
8018 switch (ch) {
8019 case 'r':
8020 repo_path = realpath(optarg, NULL);
8021 if (repo_path == NULL)
8022 return got_error_from_errno2("realpath",
8023 optarg);
8024 break;
8025 default:
8026 usage_ref();
8027 /* NOTREACHED */
8031 argc -= optind;
8032 argv += optind;
8034 if (argc > 1)
8035 usage_ref();
8037 error = got_repo_pack_fds_open(&pack_fds);
8038 if (error != NULL)
8039 goto done;
8041 if (repo_path == NULL) {
8042 cwd = getcwd(NULL, 0);
8043 if (cwd == NULL)
8044 return got_error_from_errno("getcwd");
8045 error = got_worktree_open(&worktree, cwd);
8046 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8047 goto done;
8048 if (worktree)
8049 repo_path =
8050 strdup(got_worktree_get_repo_path(worktree));
8051 else
8052 repo_path = strdup(cwd);
8053 if (repo_path == NULL) {
8054 error = got_error_from_errno("strdup");
8055 goto done;
8059 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8060 if (error != NULL)
8061 goto done;
8063 init_curses();
8065 error = apply_unveil(got_repo_get_path(repo), NULL);
8066 if (error)
8067 goto done;
8069 error = tog_load_refs(repo, 0);
8070 if (error)
8071 goto done;
8073 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8074 if (view == NULL) {
8075 error = got_error_from_errno("view_open");
8076 goto done;
8079 error = open_ref_view(view, repo);
8080 if (error)
8081 goto done;
8083 if (worktree) {
8084 /* Release work tree lock. */
8085 got_worktree_close(worktree);
8086 worktree = NULL;
8088 error = view_loop(view);
8089 done:
8090 free(repo_path);
8091 free(cwd);
8092 if (repo) {
8093 const struct got_error *close_err = got_repo_close(repo);
8094 if (close_err)
8095 error = close_err;
8097 if (pack_fds) {
8098 const struct got_error *pack_err =
8099 got_repo_pack_fds_close(pack_fds);
8100 if (error == NULL)
8101 error = pack_err;
8103 tog_free_refs();
8104 return error;
8107 static const struct got_error *
8108 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8109 enum tog_view_type request, int y, int x)
8111 const struct got_error *err = NULL;
8113 *new_view = NULL;
8115 switch (request) {
8116 case TOG_VIEW_DIFF:
8117 if (view->type == TOG_VIEW_LOG) {
8118 struct tog_log_view_state *s = &view->state.log;
8120 err = open_diff_view_for_commit(new_view, y, x,
8121 s->selected_entry->commit, s->selected_entry->id,
8122 view, s->repo);
8123 } else
8124 return got_error_msg(GOT_ERR_NOT_IMPL,
8125 "parent/child view pair not supported");
8126 break;
8127 case TOG_VIEW_BLAME:
8128 if (view->type == TOG_VIEW_TREE) {
8129 struct tog_tree_view_state *s = &view->state.tree;
8131 err = blame_tree_entry(new_view, y, x,
8132 s->selected_entry, &s->parents, s->commit_id,
8133 s->repo);
8134 } else
8135 return got_error_msg(GOT_ERR_NOT_IMPL,
8136 "parent/child view pair not supported");
8137 break;
8138 case TOG_VIEW_LOG:
8139 if (view->type == TOG_VIEW_BLAME)
8140 err = log_annotated_line(new_view, y, x,
8141 view->state.blame.repo, view->state.blame.id_to_log);
8142 else if (view->type == TOG_VIEW_TREE)
8143 err = log_selected_tree_entry(new_view, y, x,
8144 &view->state.tree);
8145 else if (view->type == TOG_VIEW_REF)
8146 err = log_ref_entry(new_view, y, x,
8147 view->state.ref.selected_entry,
8148 view->state.ref.repo);
8149 else
8150 return got_error_msg(GOT_ERR_NOT_IMPL,
8151 "parent/child view pair not supported");
8152 break;
8153 case TOG_VIEW_TREE:
8154 if (view->type == TOG_VIEW_LOG)
8155 err = browse_commit_tree(new_view, y, x,
8156 view->state.log.selected_entry,
8157 view->state.log.in_repo_path,
8158 view->state.log.head_ref_name,
8159 view->state.log.repo);
8160 else if (view->type == TOG_VIEW_REF)
8161 err = browse_ref_tree(new_view, y, x,
8162 view->state.ref.selected_entry,
8163 view->state.ref.repo);
8164 else
8165 return got_error_msg(GOT_ERR_NOT_IMPL,
8166 "parent/child view pair not supported");
8167 break;
8168 case TOG_VIEW_REF:
8169 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8170 if (*new_view == NULL)
8171 return got_error_from_errno("view_open");
8172 if (view->type == TOG_VIEW_LOG)
8173 err = open_ref_view(*new_view, view->state.log.repo);
8174 else if (view->type == TOG_VIEW_TREE)
8175 err = open_ref_view(*new_view, view->state.tree.repo);
8176 else
8177 err = got_error_msg(GOT_ERR_NOT_IMPL,
8178 "parent/child view pair not supported");
8179 if (err)
8180 view_close(*new_view);
8181 break;
8182 default:
8183 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8186 return err;
8190 * If view was scrolled down to move the selected line into view when opening a
8191 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8193 static void
8194 offset_selection_up(struct tog_view *view)
8196 switch (view->type) {
8197 case TOG_VIEW_BLAME: {
8198 struct tog_blame_view_state *s = &view->state.blame;
8199 if (s->first_displayed_line == 1) {
8200 s->selected_line = MAX(s->selected_line - view->offset,
8201 1);
8202 break;
8204 if (s->first_displayed_line > view->offset)
8205 s->first_displayed_line -= view->offset;
8206 else
8207 s->first_displayed_line = 1;
8208 s->selected_line += view->offset;
8209 break;
8211 case TOG_VIEW_LOG:
8212 log_scroll_up(&view->state.log, view->offset);
8213 view->state.log.selected += view->offset;
8214 break;
8215 case TOG_VIEW_REF:
8216 ref_scroll_up(&view->state.ref, view->offset);
8217 view->state.ref.selected += view->offset;
8218 break;
8219 case TOG_VIEW_TREE:
8220 tree_scroll_up(&view->state.tree, view->offset);
8221 view->state.tree.selected += view->offset;
8222 break;
8223 default:
8224 break;
8227 view->offset = 0;
8231 * If the selected line is in the section of screen covered by the bottom split,
8232 * scroll down offset lines to move it into view and index its new position.
8234 static const struct got_error *
8235 offset_selection_down(struct tog_view *view)
8237 const struct got_error *err = NULL;
8238 const struct got_error *(*scrolld)(struct tog_view *, int);
8239 int *selected = NULL;
8240 int header, offset;
8242 switch (view->type) {
8243 case TOG_VIEW_BLAME: {
8244 struct tog_blame_view_state *s = &view->state.blame;
8245 header = 3;
8246 scrolld = NULL;
8247 if (s->selected_line > view->nlines - header) {
8248 offset = abs(view->nlines - s->selected_line - header);
8249 s->first_displayed_line += offset;
8250 s->selected_line -= offset;
8251 view->offset = offset;
8253 break;
8255 case TOG_VIEW_LOG: {
8256 struct tog_log_view_state *s = &view->state.log;
8257 scrolld = &log_scroll_down;
8258 header = view_is_parent_view(view) ? 3 : 2;
8259 selected = &s->selected;
8260 break;
8262 case TOG_VIEW_REF: {
8263 struct tog_ref_view_state *s = &view->state.ref;
8264 scrolld = &ref_scroll_down;
8265 header = 3;
8266 selected = &s->selected;
8267 break;
8269 case TOG_VIEW_TREE: {
8270 struct tog_tree_view_state *s = &view->state.tree;
8271 scrolld = &tree_scroll_down;
8272 header = 5;
8273 selected = &s->selected;
8274 break;
8276 default:
8277 selected = NULL;
8278 scrolld = NULL;
8279 header = 0;
8280 break;
8283 if (selected && *selected > view->nlines - header) {
8284 offset = abs(view->nlines - *selected - header);
8285 view->offset = offset;
8286 if (scrolld && offset) {
8287 err = scrolld(view, offset);
8288 *selected -= offset;
8292 return err;
8295 static void
8296 list_commands(FILE *fp)
8298 size_t i;
8300 fprintf(fp, "commands:");
8301 for (i = 0; i < nitems(tog_commands); i++) {
8302 const struct tog_cmd *cmd = &tog_commands[i];
8303 fprintf(fp, " %s", cmd->name);
8305 fputc('\n', fp);
8308 __dead static void
8309 usage(int hflag, int status)
8311 FILE *fp = (status == 0) ? stdout : stderr;
8313 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8314 getprogname());
8315 if (hflag) {
8316 fprintf(fp, "lazy usage: %s path\n", getprogname());
8317 list_commands(fp);
8319 exit(status);
8322 static char **
8323 make_argv(int argc, ...)
8325 va_list ap;
8326 char **argv;
8327 int i;
8329 va_start(ap, argc);
8331 argv = calloc(argc, sizeof(char *));
8332 if (argv == NULL)
8333 err(1, "calloc");
8334 for (i = 0; i < argc; i++) {
8335 argv[i] = strdup(va_arg(ap, char *));
8336 if (argv[i] == NULL)
8337 err(1, "strdup");
8340 va_end(ap);
8341 return argv;
8345 * Try to convert 'tog path' into a 'tog log path' command.
8346 * The user could simply have mistyped the command rather than knowingly
8347 * provided a path. So check whether argv[0] can in fact be resolved
8348 * to a path in the HEAD commit and print a special error if not.
8349 * This hack is for mpi@ <3
8351 static const struct got_error *
8352 tog_log_with_path(int argc, char *argv[])
8354 const struct got_error *error = NULL, *close_err;
8355 const struct tog_cmd *cmd = NULL;
8356 struct got_repository *repo = NULL;
8357 struct got_worktree *worktree = NULL;
8358 struct got_object_id *commit_id = NULL, *id = NULL;
8359 struct got_commit_object *commit = NULL;
8360 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8361 char *commit_id_str = NULL, **cmd_argv = NULL;
8362 int *pack_fds = NULL;
8364 cwd = getcwd(NULL, 0);
8365 if (cwd == NULL)
8366 return got_error_from_errno("getcwd");
8368 error = got_repo_pack_fds_open(&pack_fds);
8369 if (error != NULL)
8370 goto done;
8372 error = got_worktree_open(&worktree, cwd);
8373 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8374 goto done;
8376 if (worktree)
8377 repo_path = strdup(got_worktree_get_repo_path(worktree));
8378 else
8379 repo_path = strdup(cwd);
8380 if (repo_path == NULL) {
8381 error = got_error_from_errno("strdup");
8382 goto done;
8385 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8386 if (error != NULL)
8387 goto done;
8389 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8390 repo, worktree);
8391 if (error)
8392 goto done;
8394 error = tog_load_refs(repo, 0);
8395 if (error)
8396 goto done;
8397 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8398 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8399 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8400 if (error)
8401 goto done;
8403 if (worktree) {
8404 got_worktree_close(worktree);
8405 worktree = NULL;
8408 error = got_object_open_as_commit(&commit, repo, commit_id);
8409 if (error)
8410 goto done;
8412 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8413 if (error) {
8414 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8415 goto done;
8416 fprintf(stderr, "%s: '%s' is no known command or path\n",
8417 getprogname(), argv[0]);
8418 usage(1, 1);
8419 /* not reached */
8422 error = got_object_id_str(&commit_id_str, commit_id);
8423 if (error)
8424 goto done;
8426 cmd = &tog_commands[0]; /* log */
8427 argc = 4;
8428 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8429 error = cmd->cmd_main(argc, cmd_argv);
8430 done:
8431 if (repo) {
8432 close_err = got_repo_close(repo);
8433 if (error == NULL)
8434 error = close_err;
8436 if (commit)
8437 got_object_commit_close(commit);
8438 if (worktree)
8439 got_worktree_close(worktree);
8440 if (pack_fds) {
8441 const struct got_error *pack_err =
8442 got_repo_pack_fds_close(pack_fds);
8443 if (error == NULL)
8444 error = pack_err;
8446 free(id);
8447 free(commit_id_str);
8448 free(commit_id);
8449 free(cwd);
8450 free(repo_path);
8451 free(in_repo_path);
8452 if (cmd_argv) {
8453 int i;
8454 for (i = 0; i < argc; i++)
8455 free(cmd_argv[i]);
8456 free(cmd_argv);
8458 tog_free_refs();
8459 return error;
8462 int
8463 main(int argc, char *argv[])
8465 const struct got_error *error = NULL;
8466 const struct tog_cmd *cmd = NULL;
8467 int ch, hflag = 0, Vflag = 0;
8468 char **cmd_argv = NULL;
8469 static const struct option longopts[] = {
8470 { "version", no_argument, NULL, 'V' },
8471 { NULL, 0, NULL, 0}
8473 char *diff_algo_str = NULL;
8475 setlocale(LC_CTYPE, "");
8477 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8478 switch (ch) {
8479 case 'h':
8480 hflag = 1;
8481 break;
8482 case 'V':
8483 Vflag = 1;
8484 break;
8485 default:
8486 usage(hflag, 1);
8487 /* NOTREACHED */
8491 argc -= optind;
8492 argv += optind;
8493 optind = 1;
8494 optreset = 1;
8496 if (Vflag) {
8497 got_version_print_str();
8498 return 0;
8501 #ifndef PROFILE
8502 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8503 NULL) == -1)
8504 err(1, "pledge");
8505 #endif
8507 if (argc == 0) {
8508 if (hflag)
8509 usage(hflag, 0);
8510 /* Build an argument vector which runs a default command. */
8511 cmd = &tog_commands[0];
8512 argc = 1;
8513 cmd_argv = make_argv(argc, cmd->name);
8514 } else {
8515 size_t i;
8517 /* Did the user specify a command? */
8518 for (i = 0; i < nitems(tog_commands); i++) {
8519 if (strncmp(tog_commands[i].name, argv[0],
8520 strlen(argv[0])) == 0) {
8521 cmd = &tog_commands[i];
8522 break;
8527 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8528 if (diff_algo_str) {
8529 if (strcasecmp(diff_algo_str, "patience") == 0)
8530 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8531 if (strcasecmp(diff_algo_str, "myers") == 0)
8532 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8535 if (cmd == NULL) {
8536 if (argc != 1)
8537 usage(0, 1);
8538 /* No command specified; try log with a path */
8539 error = tog_log_with_path(argc, argv);
8540 } else {
8541 if (hflag)
8542 cmd->cmd_usage();
8543 else
8544 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8547 endwin();
8548 putchar('\n');
8549 if (cmd_argv) {
8550 int i;
8551 for (i = 0; i < argc; i++)
8552 free(cmd_argv[i]);
8553 free(cmd_argv);
8556 if (error && error->code != GOT_ERR_CANCELLED)
8557 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8558 return 0;