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;
3173 int eos = view->nlines - 2;
3175 if (s->thread_args.log_complete &&
3176 s->selected_entry->idx >= s->commits.ncommits - 1)
3177 return NULL;
3179 if (view_is_hsplit_top(view))
3180 --eos; /* border consumes the last line */
3182 if (!page) {
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 && s->thread_args.log_complete) {
3188 struct commit_queue_entry *entry;
3189 int n;
3191 s->selected = 0;
3192 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3193 s->last_displayed_entry = entry;
3194 for (n = 0; n <= eos; n++) {
3195 if (entry == NULL)
3196 break;
3197 s->first_displayed_entry = entry;
3198 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3200 if (n > 0)
3201 s->selected = n - 1;
3202 } else {
3203 if (s->last_displayed_entry->idx == s->commits.ncommits - 1 &&
3204 s->thread_args.log_complete)
3205 s->selected += MIN(page,
3206 s->commits.ncommits - s->selected_entry->idx - 1);
3207 else
3208 err = log_scroll_down(view, page);
3210 if (err)
3211 return err;
3214 * We might necessarily overshoot in horizontal
3215 * splits; if so, select the last displayed commit.
3217 if (s->first_displayed_entry && s->last_displayed_entry) {
3218 s->selected = MIN(s->selected,
3219 s->last_displayed_entry->idx -
3220 s->first_displayed_entry->idx);
3223 select_commit(s);
3225 if (s->thread_args.log_complete &&
3226 s->selected_entry->idx == s->commits.ncommits - 1)
3227 view->count = 0;
3229 return NULL;
3232 static void
3233 view_get_split(struct tog_view *view, int *y, int *x)
3235 *x = 0;
3236 *y = 0;
3238 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3239 if (view->child && view->child->resized_y)
3240 *y = view->child->resized_y;
3241 else if (view->resized_y)
3242 *y = view->resized_y;
3243 else
3244 *y = view_split_begin_y(view->lines);
3245 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3246 if (view->child && view->child->resized_x)
3247 *x = view->child->resized_x;
3248 else if (view->resized_x)
3249 *x = view->resized_x;
3250 else
3251 *x = view_split_begin_x(view->begin_x);
3255 /* Split view horizontally at y and offset view->state->selected line. */
3256 static const struct got_error *
3257 view_init_hsplit(struct tog_view *view, int y)
3259 const struct got_error *err = NULL;
3261 view->nlines = y;
3262 view->ncols = COLS;
3263 err = view_resize(view);
3264 if (err)
3265 return err;
3267 err = offset_selection_down(view);
3269 return err;
3272 static const struct got_error *
3273 log_goto_line(struct tog_view *view, int nlines)
3275 const struct got_error *err = NULL;
3276 struct tog_log_view_state *s = &view->state.log;
3277 int g, idx = s->selected_entry->idx;
3279 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3280 return NULL;
3282 g = view->gline;
3283 view->gline = 0;
3285 if (g >= s->first_displayed_entry->idx + 1 &&
3286 g <= s->last_displayed_entry->idx + 1 &&
3287 g - s->first_displayed_entry->idx - 1 < nlines) {
3288 s->selected = g - s->first_displayed_entry->idx - 1;
3289 select_commit(s);
3290 return NULL;
3293 if (idx + 1 < g) {
3294 err = log_move_cursor_down(view, g - idx - 1);
3295 if (!err && g > s->selected_entry->idx + 1)
3296 err = log_move_cursor_down(view,
3297 g - s->first_displayed_entry->idx - 1);
3298 if (err)
3299 return err;
3300 } else if (idx + 1 > g)
3301 log_move_cursor_up(view, idx - g + 1, 0);
3303 if (g < nlines && s->first_displayed_entry->idx == 0)
3304 s->selected = g - 1;
3306 select_commit(s);
3307 return NULL;
3311 static const struct got_error *
3312 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3314 const struct got_error *err = NULL;
3315 struct tog_log_view_state *s = &view->state.log;
3316 int eos, nscroll;
3318 if (s->thread_args.load_all) {
3319 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3320 s->thread_args.load_all = 0;
3321 else if (s->thread_args.log_complete) {
3322 err = log_move_cursor_down(view, s->commits.ncommits);
3323 s->thread_args.load_all = 0;
3325 if (err)
3326 return err;
3329 eos = nscroll = view->nlines - 1;
3330 if (view_is_hsplit_top(view))
3331 --eos; /* border */
3333 if (view->gline)
3334 return log_goto_line(view, eos);
3336 switch (ch) {
3337 case 'q':
3338 s->quit = 1;
3339 break;
3340 case '0':
3341 view->x = 0;
3342 break;
3343 case '$':
3344 view->x = MAX(view->maxx - view->ncols / 2, 0);
3345 view->count = 0;
3346 break;
3347 case KEY_RIGHT:
3348 case 'l':
3349 if (view->x + view->ncols / 2 < view->maxx)
3350 view->x += 2; /* move two columns right */
3351 else
3352 view->count = 0;
3353 break;
3354 case KEY_LEFT:
3355 case 'h':
3356 view->x -= MIN(view->x, 2); /* move two columns back */
3357 if (view->x <= 0)
3358 view->count = 0;
3359 break;
3360 case 'k':
3361 case KEY_UP:
3362 case '<':
3363 case ',':
3364 case CTRL('p'):
3365 log_move_cursor_up(view, 0, 0);
3366 break;
3367 case 'g':
3368 case KEY_HOME:
3369 log_move_cursor_up(view, 0, 1);
3370 view->count = 0;
3371 break;
3372 case CTRL('u'):
3373 case 'u':
3374 nscroll /= 2;
3375 /* FALL THROUGH */
3376 case KEY_PPAGE:
3377 case CTRL('b'):
3378 case 'b':
3379 log_move_cursor_up(view, nscroll, 0);
3380 break;
3381 case 'j':
3382 case KEY_DOWN:
3383 case '>':
3384 case '.':
3385 case CTRL('n'):
3386 err = log_move_cursor_down(view, 0);
3387 break;
3388 case '@':
3389 s->use_committer = !s->use_committer;
3390 break;
3391 case 'G':
3392 case KEY_END: {
3393 /* We don't know yet how many commits, so we're forced to
3394 * traverse them all. */
3395 view->count = 0;
3396 s->thread_args.load_all = 1;
3397 if (!s->thread_args.log_complete)
3398 return trigger_log_thread(view, 0);
3399 err = log_move_cursor_down(view, s->commits.ncommits);
3400 s->thread_args.load_all = 0;
3401 break;
3403 case CTRL('d'):
3404 case 'd':
3405 nscroll /= 2;
3406 /* FALL THROUGH */
3407 case KEY_NPAGE:
3408 case CTRL('f'):
3409 case 'f':
3410 case ' ':
3411 err = log_move_cursor_down(view, nscroll);
3412 break;
3413 case KEY_RESIZE:
3414 if (s->selected > view->nlines - 2)
3415 s->selected = view->nlines - 2;
3416 if (s->selected > s->commits.ncommits - 1)
3417 s->selected = s->commits.ncommits - 1;
3418 select_commit(s);
3419 if (s->commits.ncommits < view->nlines - 1 &&
3420 !s->thread_args.log_complete) {
3421 s->thread_args.commits_needed += (view->nlines - 1) -
3422 s->commits.ncommits;
3423 err = trigger_log_thread(view, 1);
3425 break;
3426 case KEY_ENTER:
3427 case '\r':
3428 view->count = 0;
3429 if (s->selected_entry == NULL)
3430 break;
3431 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3432 break;
3433 case 'T':
3434 view->count = 0;
3435 if (s->selected_entry == NULL)
3436 break;
3437 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3438 break;
3439 case KEY_BACKSPACE:
3440 case CTRL('l'):
3441 case 'B':
3442 view->count = 0;
3443 if (ch == KEY_BACKSPACE &&
3444 got_path_is_root_dir(s->in_repo_path))
3445 break;
3446 err = stop_log_thread(s);
3447 if (err)
3448 return err;
3449 if (ch == KEY_BACKSPACE) {
3450 char *parent_path;
3451 err = got_path_dirname(&parent_path, s->in_repo_path);
3452 if (err)
3453 return err;
3454 free(s->in_repo_path);
3455 s->in_repo_path = parent_path;
3456 s->thread_args.in_repo_path = s->in_repo_path;
3457 } else if (ch == CTRL('l')) {
3458 struct got_object_id *start_id;
3459 err = got_repo_match_object_id(&start_id, NULL,
3460 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3461 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3462 if (err)
3463 return err;
3464 free(s->start_id);
3465 s->start_id = start_id;
3466 s->thread_args.start_id = s->start_id;
3467 } else /* 'B' */
3468 s->log_branches = !s->log_branches;
3470 if (s->thread_args.pack_fds == NULL) {
3471 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3472 if (err)
3473 return err;
3475 err = got_repo_open(&s->thread_args.repo,
3476 got_repo_get_path(s->repo), NULL,
3477 s->thread_args.pack_fds);
3478 if (err)
3479 return err;
3480 tog_free_refs();
3481 err = tog_load_refs(s->repo, 0);
3482 if (err)
3483 return err;
3484 err = got_commit_graph_open(&s->thread_args.graph,
3485 s->in_repo_path, !s->log_branches);
3486 if (err)
3487 return err;
3488 err = got_commit_graph_iter_start(s->thread_args.graph,
3489 s->start_id, s->repo, NULL, NULL);
3490 if (err)
3491 return err;
3492 free_commits(&s->commits);
3493 s->first_displayed_entry = NULL;
3494 s->last_displayed_entry = NULL;
3495 s->selected_entry = NULL;
3496 s->selected = 0;
3497 s->thread_args.log_complete = 0;
3498 s->quit = 0;
3499 s->thread_args.commits_needed = view->lines;
3500 s->matched_entry = NULL;
3501 s->search_entry = NULL;
3502 view->offset = 0;
3503 break;
3504 case 'R':
3505 view->count = 0;
3506 err = view_request_new(new_view, view, TOG_VIEW_REF);
3507 break;
3508 default:
3509 view->count = 0;
3510 break;
3513 return err;
3516 static const struct got_error *
3517 apply_unveil(const char *repo_path, const char *worktree_path)
3519 const struct got_error *error;
3521 #ifdef PROFILE
3522 if (unveil("gmon.out", "rwc") != 0)
3523 return got_error_from_errno2("unveil", "gmon.out");
3524 #endif
3525 if (repo_path && unveil(repo_path, "r") != 0)
3526 return got_error_from_errno2("unveil", repo_path);
3528 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3529 return got_error_from_errno2("unveil", worktree_path);
3531 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3532 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3534 error = got_privsep_unveil_exec_helpers();
3535 if (error != NULL)
3536 return error;
3538 if (unveil(NULL, NULL) != 0)
3539 return got_error_from_errno("unveil");
3541 return NULL;
3544 static void
3545 init_curses(void)
3548 * Override default signal handlers before starting ncurses.
3549 * This should prevent ncurses from installing its own
3550 * broken cleanup() signal handler.
3552 signal(SIGWINCH, tog_sigwinch);
3553 signal(SIGPIPE, tog_sigpipe);
3554 signal(SIGCONT, tog_sigcont);
3555 signal(SIGINT, tog_sigint);
3556 signal(SIGTERM, tog_sigterm);
3558 initscr();
3559 cbreak();
3560 halfdelay(1); /* Do fast refresh while initial view is loading. */
3561 noecho();
3562 nonl();
3563 intrflush(stdscr, FALSE);
3564 keypad(stdscr, TRUE);
3565 curs_set(0);
3566 if (getenv("TOG_COLORS") != NULL) {
3567 start_color();
3568 use_default_colors();
3572 static const struct got_error *
3573 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3574 struct got_repository *repo, struct got_worktree *worktree)
3576 const struct got_error *err = NULL;
3578 if (argc == 0) {
3579 *in_repo_path = strdup("/");
3580 if (*in_repo_path == NULL)
3581 return got_error_from_errno("strdup");
3582 return NULL;
3585 if (worktree) {
3586 const char *prefix = got_worktree_get_path_prefix(worktree);
3587 char *p;
3589 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3590 if (err)
3591 return err;
3592 if (asprintf(in_repo_path, "%s%s%s", prefix,
3593 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3594 p) == -1) {
3595 err = got_error_from_errno("asprintf");
3596 *in_repo_path = NULL;
3598 free(p);
3599 } else
3600 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3602 return err;
3605 static const struct got_error *
3606 cmd_log(int argc, char *argv[])
3608 const struct got_error *error;
3609 struct got_repository *repo = NULL;
3610 struct got_worktree *worktree = NULL;
3611 struct got_object_id *start_id = NULL;
3612 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3613 char *start_commit = NULL, *label = NULL;
3614 struct got_reference *ref = NULL;
3615 const char *head_ref_name = NULL;
3616 int ch, log_branches = 0;
3617 struct tog_view *view;
3618 int *pack_fds = NULL;
3620 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3621 switch (ch) {
3622 case 'b':
3623 log_branches = 1;
3624 break;
3625 case 'c':
3626 start_commit = optarg;
3627 break;
3628 case 'r':
3629 repo_path = realpath(optarg, NULL);
3630 if (repo_path == NULL)
3631 return got_error_from_errno2("realpath",
3632 optarg);
3633 break;
3634 default:
3635 usage_log();
3636 /* NOTREACHED */
3640 argc -= optind;
3641 argv += optind;
3643 if (argc > 1)
3644 usage_log();
3646 error = got_repo_pack_fds_open(&pack_fds);
3647 if (error != NULL)
3648 goto done;
3650 if (repo_path == NULL) {
3651 cwd = getcwd(NULL, 0);
3652 if (cwd == NULL)
3653 return got_error_from_errno("getcwd");
3654 error = got_worktree_open(&worktree, cwd);
3655 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3656 goto done;
3657 if (worktree)
3658 repo_path =
3659 strdup(got_worktree_get_repo_path(worktree));
3660 else
3661 repo_path = strdup(cwd);
3662 if (repo_path == NULL) {
3663 error = got_error_from_errno("strdup");
3664 goto done;
3668 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3669 if (error != NULL)
3670 goto done;
3672 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3673 repo, worktree);
3674 if (error)
3675 goto done;
3677 init_curses();
3679 error = apply_unveil(got_repo_get_path(repo),
3680 worktree ? got_worktree_get_root_path(worktree) : NULL);
3681 if (error)
3682 goto done;
3684 /* already loaded by tog_log_with_path()? */
3685 if (TAILQ_EMPTY(&tog_refs)) {
3686 error = tog_load_refs(repo, 0);
3687 if (error)
3688 goto done;
3691 if (start_commit == NULL) {
3692 error = got_repo_match_object_id(&start_id, &label,
3693 worktree ? got_worktree_get_head_ref_name(worktree) :
3694 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3695 if (error)
3696 goto done;
3697 head_ref_name = label;
3698 } else {
3699 error = got_ref_open(&ref, repo, start_commit, 0);
3700 if (error == NULL)
3701 head_ref_name = got_ref_get_name(ref);
3702 else if (error->code != GOT_ERR_NOT_REF)
3703 goto done;
3704 error = got_repo_match_object_id(&start_id, NULL,
3705 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3706 if (error)
3707 goto done;
3710 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3711 if (view == NULL) {
3712 error = got_error_from_errno("view_open");
3713 goto done;
3715 error = open_log_view(view, start_id, repo, head_ref_name,
3716 in_repo_path, log_branches);
3717 if (error)
3718 goto done;
3719 if (worktree) {
3720 /* Release work tree lock. */
3721 got_worktree_close(worktree);
3722 worktree = NULL;
3724 error = view_loop(view);
3725 done:
3726 free(in_repo_path);
3727 free(repo_path);
3728 free(cwd);
3729 free(start_id);
3730 free(label);
3731 if (ref)
3732 got_ref_close(ref);
3733 if (repo) {
3734 const struct got_error *close_err = got_repo_close(repo);
3735 if (error == NULL)
3736 error = close_err;
3738 if (worktree)
3739 got_worktree_close(worktree);
3740 if (pack_fds) {
3741 const struct got_error *pack_err =
3742 got_repo_pack_fds_close(pack_fds);
3743 if (error == NULL)
3744 error = pack_err;
3746 tog_free_refs();
3747 return error;
3750 __dead static void
3751 usage_diff(void)
3753 endwin();
3754 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
3755 "object1 object2\n", getprogname());
3756 exit(1);
3759 static int
3760 match_line(const char *line, regex_t *regex, size_t nmatch,
3761 regmatch_t *regmatch)
3763 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3766 static struct tog_color *
3767 match_color(struct tog_colors *colors, const char *line)
3769 struct tog_color *tc = NULL;
3771 STAILQ_FOREACH(tc, colors, entry) {
3772 if (match_line(line, &tc->regex, 0, NULL))
3773 return tc;
3776 return NULL;
3779 static const struct got_error *
3780 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3781 WINDOW *window, int skipcol, regmatch_t *regmatch)
3783 const struct got_error *err = NULL;
3784 char *exstr = NULL;
3785 wchar_t *wline = NULL;
3786 int rme, rms, n, width, scrollx;
3787 int width0 = 0, width1 = 0, width2 = 0;
3788 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3790 *wtotal = 0;
3792 rms = regmatch->rm_so;
3793 rme = regmatch->rm_eo;
3795 err = expand_tab(&exstr, line);
3796 if (err)
3797 return err;
3799 /* Split the line into 3 segments, according to match offsets. */
3800 seg0 = strndup(exstr, rms);
3801 if (seg0 == NULL) {
3802 err = got_error_from_errno("strndup");
3803 goto done;
3805 seg1 = strndup(exstr + rms, rme - rms);
3806 if (seg1 == NULL) {
3807 err = got_error_from_errno("strndup");
3808 goto done;
3810 seg2 = strdup(exstr + rme);
3811 if (seg2 == NULL) {
3812 err = got_error_from_errno("strndup");
3813 goto done;
3816 /* draw up to matched token if we haven't scrolled past it */
3817 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3818 col_tab_align, 1);
3819 if (err)
3820 goto done;
3821 n = MAX(width0 - skipcol, 0);
3822 if (n) {
3823 free(wline);
3824 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3825 wlimit, col_tab_align, 1);
3826 if (err)
3827 goto done;
3828 waddwstr(window, &wline[scrollx]);
3829 wlimit -= width;
3830 *wtotal += width;
3833 if (wlimit > 0) {
3834 int i = 0, w = 0;
3835 size_t wlen;
3837 free(wline);
3838 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3839 col_tab_align, 1);
3840 if (err)
3841 goto done;
3842 wlen = wcslen(wline);
3843 while (i < wlen) {
3844 width = wcwidth(wline[i]);
3845 if (width == -1) {
3846 /* should not happen, tabs are expanded */
3847 err = got_error(GOT_ERR_RANGE);
3848 goto done;
3850 if (width0 + w + width > skipcol)
3851 break;
3852 w += width;
3853 i++;
3855 /* draw (visible part of) matched token (if scrolled into it) */
3856 if (width1 - w > 0) {
3857 wattron(window, A_STANDOUT);
3858 waddwstr(window, &wline[i]);
3859 wattroff(window, A_STANDOUT);
3860 wlimit -= (width1 - w);
3861 *wtotal += (width1 - w);
3865 if (wlimit > 0) { /* draw rest of line */
3866 free(wline);
3867 if (skipcol > width0 + width1) {
3868 err = format_line(&wline, &width2, &scrollx, seg2,
3869 skipcol - (width0 + width1), wlimit,
3870 col_tab_align, 1);
3871 if (err)
3872 goto done;
3873 waddwstr(window, &wline[scrollx]);
3874 } else {
3875 err = format_line(&wline, &width2, NULL, seg2, 0,
3876 wlimit, col_tab_align, 1);
3877 if (err)
3878 goto done;
3879 waddwstr(window, wline);
3881 *wtotal += width2;
3883 done:
3884 free(wline);
3885 free(exstr);
3886 free(seg0);
3887 free(seg1);
3888 free(seg2);
3889 return err;
3892 static int
3893 gotoline(struct tog_view *view, int *lineno, int *nprinted)
3895 FILE *f = NULL;
3896 int *eof, *first, *selected;
3898 if (view->type == TOG_VIEW_DIFF) {
3899 struct tog_diff_view_state *s = &view->state.diff;
3901 first = &s->first_displayed_line;
3902 selected = first;
3903 eof = &s->eof;
3904 f = s->f;
3905 } else if (view->type == TOG_VIEW_BLAME) {
3906 struct tog_blame_view_state *s = &view->state.blame;
3908 first = &s->first_displayed_line;
3909 selected = &s->selected_line;
3910 eof = &s->eof;
3911 f = s->blame.f;
3912 } else
3913 return 0;
3915 /* Center gline in the middle of the page like vi(1). */
3916 if (*lineno < view->gline - (view->nlines - 3) / 2)
3917 return 0;
3918 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
3919 rewind(f);
3920 *eof = 0;
3921 *first = 1;
3922 *lineno = 0;
3923 *nprinted = 0;
3924 return 0;
3927 *selected = view->gline <= (view->nlines - 3) / 2 ?
3928 view->gline : (view->nlines - 3) / 2 + 1;
3929 view->gline = 0;
3931 return 1;
3934 static const struct got_error *
3935 draw_file(struct tog_view *view, const char *header)
3937 struct tog_diff_view_state *s = &view->state.diff;
3938 regmatch_t *regmatch = &view->regmatch;
3939 const struct got_error *err;
3940 int nprinted = 0;
3941 char *line;
3942 size_t linesize = 0;
3943 ssize_t linelen;
3944 wchar_t *wline;
3945 int width;
3946 int max_lines = view->nlines;
3947 int nlines = s->nlines;
3948 off_t line_offset;
3950 s->lineno = s->first_displayed_line - 1;
3951 line_offset = s->lines[s->first_displayed_line - 1].offset;
3952 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3953 return got_error_from_errno("fseek");
3955 werase(view->window);
3957 if (view->gline > s->nlines - 1)
3958 view->gline = s->nlines - 1;
3960 if (header) {
3961 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
3962 1 : view->gline - (view->nlines - 3) / 2 :
3963 s->lineno + s->selected_line;
3965 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
3966 return got_error_from_errno("asprintf");
3967 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3968 0, 0);
3969 free(line);
3970 if (err)
3971 return err;
3973 if (view_needs_focus_indication(view))
3974 wstandout(view->window);
3975 waddwstr(view->window, wline);
3976 free(wline);
3977 wline = NULL;
3978 if (view_needs_focus_indication(view))
3979 wstandend(view->window);
3980 if (width <= view->ncols - 1)
3981 waddch(view->window, '\n');
3983 if (max_lines <= 1)
3984 return NULL;
3985 max_lines--;
3988 s->eof = 0;
3989 view->maxx = 0;
3990 line = NULL;
3991 while (max_lines > 0 && nprinted < max_lines) {
3992 enum got_diff_line_type linetype;
3993 attr_t attr = 0;
3995 linelen = getline(&line, &linesize, s->f);
3996 if (linelen == -1) {
3997 if (feof(s->f)) {
3998 s->eof = 1;
3999 break;
4001 free(line);
4002 return got_ferror(s->f, GOT_ERR_IO);
4005 if (++s->lineno < s->first_displayed_line)
4006 continue;
4007 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4008 continue;
4009 if (s->lineno == view->hiline)
4010 attr = A_STANDOUT;
4012 /* Set view->maxx based on full line length. */
4013 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4014 view->x ? 1 : 0);
4015 if (err) {
4016 free(line);
4017 return err;
4019 view->maxx = MAX(view->maxx, width);
4020 free(wline);
4021 wline = NULL;
4023 linetype = s->lines[s->lineno].type;
4024 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4025 linetype < GOT_DIFF_LINE_CONTEXT)
4026 attr |= COLOR_PAIR(linetype);
4027 if (attr)
4028 wattron(view->window, attr);
4029 if (s->first_displayed_line + nprinted == s->matched_line &&
4030 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4031 err = add_matched_line(&width, line, view->ncols, 0,
4032 view->window, view->x, regmatch);
4033 if (err) {
4034 free(line);
4035 return err;
4037 } else {
4038 int skip;
4039 err = format_line(&wline, &width, &skip, line,
4040 view->x, view->ncols, 0, view->x ? 1 : 0);
4041 if (err) {
4042 free(line);
4043 return err;
4045 waddwstr(view->window, &wline[skip]);
4046 free(wline);
4047 wline = NULL;
4049 if (s->lineno == view->hiline) {
4050 /* highlight full gline length */
4051 while (width++ < view->ncols)
4052 waddch(view->window, ' ');
4053 } else {
4054 if (width <= view->ncols - 1)
4055 waddch(view->window, '\n');
4057 if (attr)
4058 wattroff(view->window, attr);
4059 if (++nprinted == 1)
4060 s->first_displayed_line = s->lineno;
4062 free(line);
4063 if (nprinted >= 1)
4064 s->last_displayed_line = s->first_displayed_line +
4065 (nprinted - 1);
4066 else
4067 s->last_displayed_line = s->first_displayed_line;
4069 view_border(view);
4071 if (s->eof) {
4072 while (nprinted < view->nlines) {
4073 waddch(view->window, '\n');
4074 nprinted++;
4077 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4078 view->ncols, 0, 0);
4079 if (err) {
4080 return err;
4083 wstandout(view->window);
4084 waddwstr(view->window, wline);
4085 free(wline);
4086 wline = NULL;
4087 wstandend(view->window);
4090 return NULL;
4093 static char *
4094 get_datestr(time_t *time, char *datebuf)
4096 struct tm mytm, *tm;
4097 char *p, *s;
4099 tm = gmtime_r(time, &mytm);
4100 if (tm == NULL)
4101 return NULL;
4102 s = asctime_r(tm, datebuf);
4103 if (s == NULL)
4104 return NULL;
4105 p = strchr(s, '\n');
4106 if (p)
4107 *p = '\0';
4108 return s;
4111 static const struct got_error *
4112 get_changed_paths(struct got_pathlist_head *paths,
4113 struct got_commit_object *commit, struct got_repository *repo)
4115 const struct got_error *err = NULL;
4116 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4117 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4118 struct got_object_qid *qid;
4120 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4121 if (qid != NULL) {
4122 struct got_commit_object *pcommit;
4123 err = got_object_open_as_commit(&pcommit, repo,
4124 &qid->id);
4125 if (err)
4126 return err;
4128 tree_id1 = got_object_id_dup(
4129 got_object_commit_get_tree_id(pcommit));
4130 if (tree_id1 == NULL) {
4131 got_object_commit_close(pcommit);
4132 return got_error_from_errno("got_object_id_dup");
4134 got_object_commit_close(pcommit);
4138 if (tree_id1) {
4139 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4140 if (err)
4141 goto done;
4144 tree_id2 = got_object_commit_get_tree_id(commit);
4145 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4146 if (err)
4147 goto done;
4149 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4150 got_diff_tree_collect_changed_paths, paths, 0);
4151 done:
4152 if (tree1)
4153 got_object_tree_close(tree1);
4154 if (tree2)
4155 got_object_tree_close(tree2);
4156 free(tree_id1);
4157 return err;
4160 static const struct got_error *
4161 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4162 off_t off, uint8_t type)
4164 struct got_diff_line *p;
4166 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4167 if (p == NULL)
4168 return got_error_from_errno("reallocarray");
4169 *lines = p;
4170 (*lines)[*nlines].offset = off;
4171 (*lines)[*nlines].type = type;
4172 (*nlines)++;
4174 return NULL;
4177 static const struct got_error *
4178 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4179 struct got_object_id *commit_id, struct got_reflist_head *refs,
4180 struct got_repository *repo, FILE *outfile)
4182 const struct got_error *err = NULL;
4183 char datebuf[26], *datestr;
4184 struct got_commit_object *commit;
4185 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4186 time_t committer_time;
4187 const char *author, *committer;
4188 char *refs_str = NULL;
4189 struct got_pathlist_head changed_paths;
4190 struct got_pathlist_entry *pe;
4191 off_t outoff = 0;
4192 int n;
4194 TAILQ_INIT(&changed_paths);
4196 if (refs) {
4197 err = build_refs_str(&refs_str, refs, commit_id, repo);
4198 if (err)
4199 return err;
4202 err = got_object_open_as_commit(&commit, repo, commit_id);
4203 if (err)
4204 return err;
4206 err = got_object_id_str(&id_str, commit_id);
4207 if (err) {
4208 err = got_error_from_errno("got_object_id_str");
4209 goto done;
4212 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4213 if (err)
4214 goto done;
4216 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4217 refs_str ? refs_str : "", refs_str ? ")" : "");
4218 if (n < 0) {
4219 err = got_error_from_errno("fprintf");
4220 goto done;
4222 outoff += n;
4223 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4224 if (err)
4225 goto done;
4227 n = fprintf(outfile, "from: %s\n",
4228 got_object_commit_get_author(commit));
4229 if (n < 0) {
4230 err = got_error_from_errno("fprintf");
4231 goto done;
4233 outoff += n;
4234 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4235 if (err)
4236 goto done;
4238 committer_time = got_object_commit_get_committer_time(commit);
4239 datestr = get_datestr(&committer_time, datebuf);
4240 if (datestr) {
4241 n = fprintf(outfile, "date: %s UTC\n", datestr);
4242 if (n < 0) {
4243 err = got_error_from_errno("fprintf");
4244 goto done;
4246 outoff += n;
4247 err = add_line_metadata(lines, nlines, outoff,
4248 GOT_DIFF_LINE_DATE);
4249 if (err)
4250 goto done;
4252 author = got_object_commit_get_author(commit);
4253 committer = got_object_commit_get_committer(commit);
4254 if (strcmp(author, committer) != 0) {
4255 n = fprintf(outfile, "via: %s\n", committer);
4256 if (n < 0) {
4257 err = got_error_from_errno("fprintf");
4258 goto done;
4260 outoff += n;
4261 err = add_line_metadata(lines, nlines, outoff,
4262 GOT_DIFF_LINE_AUTHOR);
4263 if (err)
4264 goto done;
4266 if (got_object_commit_get_nparents(commit) > 1) {
4267 const struct got_object_id_queue *parent_ids;
4268 struct got_object_qid *qid;
4269 int pn = 1;
4270 parent_ids = got_object_commit_get_parent_ids(commit);
4271 STAILQ_FOREACH(qid, parent_ids, entry) {
4272 err = got_object_id_str(&id_str, &qid->id);
4273 if (err)
4274 goto done;
4275 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4276 if (n < 0) {
4277 err = got_error_from_errno("fprintf");
4278 goto done;
4280 outoff += n;
4281 err = add_line_metadata(lines, nlines, outoff,
4282 GOT_DIFF_LINE_META);
4283 if (err)
4284 goto done;
4285 free(id_str);
4286 id_str = NULL;
4290 err = got_object_commit_get_logmsg(&logmsg, commit);
4291 if (err)
4292 goto done;
4293 s = logmsg;
4294 while ((line = strsep(&s, "\n")) != NULL) {
4295 n = fprintf(outfile, "%s\n", line);
4296 if (n < 0) {
4297 err = got_error_from_errno("fprintf");
4298 goto done;
4300 outoff += n;
4301 err = add_line_metadata(lines, nlines, outoff,
4302 GOT_DIFF_LINE_LOGMSG);
4303 if (err)
4304 goto done;
4307 err = get_changed_paths(&changed_paths, commit, repo);
4308 if (err)
4309 goto done;
4310 TAILQ_FOREACH(pe, &changed_paths, entry) {
4311 struct got_diff_changed_path *cp = pe->data;
4312 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4313 if (n < 0) {
4314 err = got_error_from_errno("fprintf");
4315 goto done;
4317 outoff += n;
4318 err = add_line_metadata(lines, nlines, outoff,
4319 GOT_DIFF_LINE_CHANGES);
4320 if (err)
4321 goto done;
4322 free((char *)pe->path);
4323 free(pe->data);
4326 fputc('\n', outfile);
4327 outoff++;
4328 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4329 done:
4330 got_pathlist_free(&changed_paths);
4331 free(id_str);
4332 free(logmsg);
4333 free(refs_str);
4334 got_object_commit_close(commit);
4335 if (err) {
4336 free(*lines);
4337 *lines = NULL;
4338 *nlines = 0;
4340 return err;
4343 static const struct got_error *
4344 create_diff(struct tog_diff_view_state *s)
4346 const struct got_error *err = NULL;
4347 FILE *f = NULL;
4348 int obj_type;
4350 free(s->lines);
4351 s->lines = malloc(sizeof(*s->lines));
4352 if (s->lines == NULL)
4353 return got_error_from_errno("malloc");
4354 s->nlines = 0;
4356 f = got_opentemp();
4357 if (f == NULL) {
4358 err = got_error_from_errno("got_opentemp");
4359 goto done;
4361 if (s->f && fclose(s->f) == EOF) {
4362 err = got_error_from_errno("fclose");
4363 goto done;
4365 s->f = f;
4367 if (s->id1)
4368 err = got_object_get_type(&obj_type, s->repo, s->id1);
4369 else
4370 err = got_object_get_type(&obj_type, s->repo, s->id2);
4371 if (err)
4372 goto done;
4374 switch (obj_type) {
4375 case GOT_OBJ_TYPE_BLOB:
4376 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4377 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4378 s->label1, s->label2, tog_diff_algo, s->diff_context,
4379 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4380 break;
4381 case GOT_OBJ_TYPE_TREE:
4382 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4383 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4384 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4385 s->force_text_diff, s->repo, s->f);
4386 break;
4387 case GOT_OBJ_TYPE_COMMIT: {
4388 const struct got_object_id_queue *parent_ids;
4389 struct got_object_qid *pid;
4390 struct got_commit_object *commit2;
4391 struct got_reflist_head *refs;
4393 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4394 if (err)
4395 goto done;
4396 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4397 /* Show commit info if we're diffing to a parent/root commit. */
4398 if (s->id1 == NULL) {
4399 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4400 refs, s->repo, s->f);
4401 if (err)
4402 goto done;
4403 } else {
4404 parent_ids = got_object_commit_get_parent_ids(commit2);
4405 STAILQ_FOREACH(pid, parent_ids, entry) {
4406 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4407 err = write_commit_info(&s->lines,
4408 &s->nlines, s->id2, refs, s->repo,
4409 s->f);
4410 if (err)
4411 goto done;
4412 break;
4416 got_object_commit_close(commit2);
4418 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4419 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4420 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4421 s->force_text_diff, s->repo, s->f);
4422 break;
4424 default:
4425 err = got_error(GOT_ERR_OBJ_TYPE);
4426 break;
4428 done:
4429 if (s->f && fflush(s->f) != 0 && err == NULL)
4430 err = got_error_from_errno("fflush");
4431 return err;
4434 static void
4435 diff_view_indicate_progress(struct tog_view *view)
4437 mvwaddstr(view->window, 0, 0, "diffing...");
4438 update_panels();
4439 doupdate();
4442 static const struct got_error *
4443 search_start_diff_view(struct tog_view *view)
4445 struct tog_diff_view_state *s = &view->state.diff;
4447 s->matched_line = 0;
4448 return NULL;
4451 static const struct got_error *
4452 search_next_diff_view(struct tog_view *view)
4454 struct tog_diff_view_state *s = &view->state.diff;
4455 const struct got_error *err = NULL;
4456 int lineno;
4457 char *line = NULL;
4458 size_t linesize = 0;
4459 ssize_t linelen;
4461 if (!view->searching) {
4462 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4463 return NULL;
4466 if (s->matched_line) {
4467 if (view->searching == TOG_SEARCH_FORWARD)
4468 lineno = s->matched_line + 1;
4469 else
4470 lineno = s->matched_line - 1;
4471 } else
4472 lineno = s->first_displayed_line;
4474 while (1) {
4475 off_t offset;
4477 if (lineno <= 0 || lineno > s->nlines) {
4478 if (s->matched_line == 0) {
4479 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4480 break;
4483 if (view->searching == TOG_SEARCH_FORWARD)
4484 lineno = 1;
4485 else
4486 lineno = s->nlines;
4489 offset = s->lines[lineno - 1].offset;
4490 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4491 free(line);
4492 return got_error_from_errno("fseeko");
4494 linelen = getline(&line, &linesize, s->f);
4495 if (linelen != -1) {
4496 char *exstr;
4497 err = expand_tab(&exstr, line);
4498 if (err)
4499 break;
4500 if (match_line(exstr, &view->regex, 1,
4501 &view->regmatch)) {
4502 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4503 s->matched_line = lineno;
4504 free(exstr);
4505 break;
4507 free(exstr);
4509 if (view->searching == TOG_SEARCH_FORWARD)
4510 lineno++;
4511 else
4512 lineno--;
4514 free(line);
4516 if (s->matched_line) {
4517 s->first_displayed_line = s->matched_line;
4518 s->selected_line = 1;
4521 return err;
4524 static const struct got_error *
4525 close_diff_view(struct tog_view *view)
4527 const struct got_error *err = NULL;
4528 struct tog_diff_view_state *s = &view->state.diff;
4530 free(s->id1);
4531 s->id1 = NULL;
4532 free(s->id2);
4533 s->id2 = NULL;
4534 if (s->f && fclose(s->f) == EOF)
4535 err = got_error_from_errno("fclose");
4536 s->f = NULL;
4537 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4538 err = got_error_from_errno("fclose");
4539 s->f1 = NULL;
4540 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4541 err = got_error_from_errno("fclose");
4542 s->f2 = NULL;
4543 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4544 err = got_error_from_errno("close");
4545 s->fd1 = -1;
4546 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4547 err = got_error_from_errno("close");
4548 s->fd2 = -1;
4549 free(s->lines);
4550 s->lines = NULL;
4551 s->nlines = 0;
4552 return err;
4555 static const struct got_error *
4556 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4557 struct got_object_id *id2, const char *label1, const char *label2,
4558 int diff_context, int ignore_whitespace, int force_text_diff,
4559 struct tog_view *parent_view, struct got_repository *repo)
4561 const struct got_error *err;
4562 struct tog_diff_view_state *s = &view->state.diff;
4564 memset(s, 0, sizeof(*s));
4565 s->fd1 = -1;
4566 s->fd2 = -1;
4568 if (id1 != NULL && id2 != NULL) {
4569 int type1, type2;
4570 err = got_object_get_type(&type1, repo, id1);
4571 if (err)
4572 return err;
4573 err = got_object_get_type(&type2, repo, id2);
4574 if (err)
4575 return err;
4577 if (type1 != type2)
4578 return got_error(GOT_ERR_OBJ_TYPE);
4580 s->first_displayed_line = 1;
4581 s->last_displayed_line = view->nlines;
4582 s->selected_line = 1;
4583 s->repo = repo;
4584 s->id1 = id1;
4585 s->id2 = id2;
4586 s->label1 = label1;
4587 s->label2 = label2;
4589 if (id1) {
4590 s->id1 = got_object_id_dup(id1);
4591 if (s->id1 == NULL)
4592 return got_error_from_errno("got_object_id_dup");
4593 } else
4594 s->id1 = NULL;
4596 s->id2 = got_object_id_dup(id2);
4597 if (s->id2 == NULL) {
4598 err = got_error_from_errno("got_object_id_dup");
4599 goto done;
4602 s->f1 = got_opentemp();
4603 if (s->f1 == NULL) {
4604 err = got_error_from_errno("got_opentemp");
4605 goto done;
4608 s->f2 = got_opentemp();
4609 if (s->f2 == NULL) {
4610 err = got_error_from_errno("got_opentemp");
4611 goto done;
4614 s->fd1 = got_opentempfd();
4615 if (s->fd1 == -1) {
4616 err = got_error_from_errno("got_opentempfd");
4617 goto done;
4620 s->fd2 = got_opentempfd();
4621 if (s->fd2 == -1) {
4622 err = got_error_from_errno("got_opentempfd");
4623 goto done;
4626 s->first_displayed_line = 1;
4627 s->last_displayed_line = view->nlines;
4628 s->diff_context = diff_context;
4629 s->ignore_whitespace = ignore_whitespace;
4630 s->force_text_diff = force_text_diff;
4631 s->parent_view = parent_view;
4632 s->repo = repo;
4634 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4635 int rc;
4637 rc = init_pair(GOT_DIFF_LINE_MINUS,
4638 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
4639 if (rc != ERR)
4640 rc = init_pair(GOT_DIFF_LINE_PLUS,
4641 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
4642 if (rc != ERR)
4643 rc = init_pair(GOT_DIFF_LINE_HUNK,
4644 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
4645 if (rc != ERR)
4646 rc = init_pair(GOT_DIFF_LINE_META,
4647 get_color_value("TOG_COLOR_DIFF_META"), -1);
4648 if (rc != ERR)
4649 rc = init_pair(GOT_DIFF_LINE_CHANGES,
4650 get_color_value("TOG_COLOR_DIFF_META"), -1);
4651 if (rc != ERR)
4652 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
4653 get_color_value("TOG_COLOR_DIFF_META"), -1);
4654 if (rc != ERR)
4655 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
4656 get_color_value("TOG_COLOR_DIFF_META"), -1);
4657 if (rc != ERR)
4658 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
4659 get_color_value("TOG_COLOR_AUTHOR"), -1);
4660 if (rc != ERR)
4661 rc = init_pair(GOT_DIFF_LINE_DATE,
4662 get_color_value("TOG_COLOR_DATE"), -1);
4663 if (rc == ERR) {
4664 err = got_error(GOT_ERR_RANGE);
4665 goto done;
4669 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4670 view_is_splitscreen(view))
4671 show_log_view(parent_view); /* draw border */
4672 diff_view_indicate_progress(view);
4674 err = create_diff(s);
4676 view->show = show_diff_view;
4677 view->input = input_diff_view;
4678 view->reset = reset_diff_view;
4679 view->close = close_diff_view;
4680 view->search_start = search_start_diff_view;
4681 view->search_next = search_next_diff_view;
4682 done:
4683 if (err)
4684 close_diff_view(view);
4685 return err;
4688 static const struct got_error *
4689 show_diff_view(struct tog_view *view)
4691 const struct got_error *err;
4692 struct tog_diff_view_state *s = &view->state.diff;
4693 char *id_str1 = NULL, *id_str2, *header;
4694 const char *label1, *label2;
4696 if (s->id1) {
4697 err = got_object_id_str(&id_str1, s->id1);
4698 if (err)
4699 return err;
4700 label1 = s->label1 ? s->label1 : id_str1;
4701 } else
4702 label1 = "/dev/null";
4704 err = got_object_id_str(&id_str2, s->id2);
4705 if (err)
4706 return err;
4707 label2 = s->label2 ? s->label2 : id_str2;
4709 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4710 err = got_error_from_errno("asprintf");
4711 free(id_str1);
4712 free(id_str2);
4713 return err;
4715 free(id_str1);
4716 free(id_str2);
4718 err = draw_file(view, header);
4719 free(header);
4720 return err;
4723 static const struct got_error *
4724 set_selected_commit(struct tog_diff_view_state *s,
4725 struct commit_queue_entry *entry)
4727 const struct got_error *err;
4728 const struct got_object_id_queue *parent_ids;
4729 struct got_commit_object *selected_commit;
4730 struct got_object_qid *pid;
4732 free(s->id2);
4733 s->id2 = got_object_id_dup(entry->id);
4734 if (s->id2 == NULL)
4735 return got_error_from_errno("got_object_id_dup");
4737 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4738 if (err)
4739 return err;
4740 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4741 free(s->id1);
4742 pid = STAILQ_FIRST(parent_ids);
4743 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4744 got_object_commit_close(selected_commit);
4745 return NULL;
4748 static const struct got_error *
4749 reset_diff_view(struct tog_view *view)
4751 struct tog_diff_view_state *s = &view->state.diff;
4753 view->count = 0;
4754 wclear(view->window);
4755 s->first_displayed_line = 1;
4756 s->last_displayed_line = view->nlines;
4757 s->matched_line = 0;
4758 diff_view_indicate_progress(view);
4759 return create_diff(s);
4762 static void
4763 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4765 int start, i;
4767 i = start = s->first_displayed_line - 1;
4769 while (s->lines[i].type != type) {
4770 if (i == 0)
4771 i = s->nlines - 1;
4772 if (--i == start)
4773 return; /* do nothing, requested type not in file */
4776 s->selected_line = 1;
4777 s->first_displayed_line = i;
4780 static void
4781 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4783 int start, i;
4785 i = start = s->first_displayed_line + 1;
4787 while (s->lines[i].type != type) {
4788 if (i == s->nlines - 1)
4789 i = 0;
4790 if (++i == start)
4791 return; /* do nothing, requested type not in file */
4794 s->selected_line = 1;
4795 s->first_displayed_line = i;
4798 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4799 int, int, int);
4800 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4801 int, int);
4803 static const struct got_error *
4804 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4806 const struct got_error *err = NULL;
4807 struct tog_diff_view_state *s = &view->state.diff;
4808 struct tog_log_view_state *ls;
4809 struct commit_queue_entry *old_selected_entry;
4810 char *line = NULL;
4811 size_t linesize = 0;
4812 ssize_t linelen;
4813 int i, nscroll = view->nlines - 1, up = 0;
4815 s->lineno = s->first_displayed_line - 1 + s->selected_line;
4817 switch (ch) {
4818 case '0':
4819 view->x = 0;
4820 break;
4821 case '$':
4822 view->x = MAX(view->maxx - view->ncols / 3, 0);
4823 view->count = 0;
4824 break;
4825 case KEY_RIGHT:
4826 case 'l':
4827 if (view->x + view->ncols / 3 < view->maxx)
4828 view->x += 2; /* move two columns right */
4829 else
4830 view->count = 0;
4831 break;
4832 case KEY_LEFT:
4833 case 'h':
4834 view->x -= MIN(view->x, 2); /* move two columns back */
4835 if (view->x <= 0)
4836 view->count = 0;
4837 break;
4838 case 'a':
4839 case 'w':
4840 if (ch == 'a')
4841 s->force_text_diff = !s->force_text_diff;
4842 if (ch == 'w')
4843 s->ignore_whitespace = !s->ignore_whitespace;
4844 err = reset_diff_view(view);
4845 break;
4846 case 'g':
4847 case KEY_HOME:
4848 s->first_displayed_line = 1;
4849 view->count = 0;
4850 break;
4851 case 'G':
4852 case KEY_END:
4853 view->count = 0;
4854 if (s->eof)
4855 break;
4857 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4858 s->eof = 1;
4859 break;
4860 case 'k':
4861 case KEY_UP:
4862 case CTRL('p'):
4863 if (s->first_displayed_line > 1)
4864 s->first_displayed_line--;
4865 else
4866 view->count = 0;
4867 break;
4868 case CTRL('u'):
4869 case 'u':
4870 nscroll /= 2;
4871 /* FALL THROUGH */
4872 case KEY_PPAGE:
4873 case CTRL('b'):
4874 case 'b':
4875 if (s->first_displayed_line == 1) {
4876 view->count = 0;
4877 break;
4879 i = 0;
4880 while (i++ < nscroll && s->first_displayed_line > 1)
4881 s->first_displayed_line--;
4882 break;
4883 case 'j':
4884 case KEY_DOWN:
4885 case CTRL('n'):
4886 if (!s->eof)
4887 s->first_displayed_line++;
4888 else
4889 view->count = 0;
4890 break;
4891 case CTRL('d'):
4892 case 'd':
4893 nscroll /= 2;
4894 /* FALL THROUGH */
4895 case KEY_NPAGE:
4896 case CTRL('f'):
4897 case 'f':
4898 case ' ':
4899 if (s->eof) {
4900 view->count = 0;
4901 break;
4903 i = 0;
4904 while (!s->eof && i++ < nscroll) {
4905 linelen = getline(&line, &linesize, s->f);
4906 s->first_displayed_line++;
4907 if (linelen == -1) {
4908 if (feof(s->f)) {
4909 s->eof = 1;
4910 } else
4911 err = got_ferror(s->f, GOT_ERR_IO);
4912 break;
4915 free(line);
4916 break;
4917 case '(':
4918 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
4919 break;
4920 case ')':
4921 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
4922 break;
4923 case '{':
4924 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
4925 break;
4926 case '}':
4927 diff_next_index(s, GOT_DIFF_LINE_HUNK);
4928 break;
4929 case '[':
4930 if (s->diff_context > 0) {
4931 s->diff_context--;
4932 s->matched_line = 0;
4933 diff_view_indicate_progress(view);
4934 err = create_diff(s);
4935 if (s->first_displayed_line + view->nlines - 1 >
4936 s->nlines) {
4937 s->first_displayed_line = 1;
4938 s->last_displayed_line = view->nlines;
4940 } else
4941 view->count = 0;
4942 break;
4943 case ']':
4944 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4945 s->diff_context++;
4946 s->matched_line = 0;
4947 diff_view_indicate_progress(view);
4948 err = create_diff(s);
4949 } else
4950 view->count = 0;
4951 break;
4952 case '<':
4953 case ',':
4954 case 'K':
4955 up = 1;
4956 /* FALL THROUGH */
4957 case '>':
4958 case '.':
4959 case 'J':
4960 if (s->parent_view == NULL) {
4961 view->count = 0;
4962 break;
4964 s->parent_view->count = view->count;
4966 if (s->parent_view->type == TOG_VIEW_LOG) {
4967 ls = &s->parent_view->state.log;
4968 old_selected_entry = ls->selected_entry;
4970 err = input_log_view(NULL, s->parent_view,
4971 up ? KEY_UP : KEY_DOWN);
4972 if (err)
4973 break;
4974 view->count = s->parent_view->count;
4976 if (old_selected_entry == ls->selected_entry)
4977 break;
4979 err = set_selected_commit(s, ls->selected_entry);
4980 if (err)
4981 break;
4982 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4983 struct tog_blame_view_state *bs;
4984 struct got_object_id *id, *prev_id;
4986 bs = &s->parent_view->state.blame;
4987 prev_id = get_annotation_for_line(bs->blame.lines,
4988 bs->blame.nlines, bs->last_diffed_line);
4990 err = input_blame_view(&view, s->parent_view,
4991 up ? KEY_UP : KEY_DOWN);
4992 if (err)
4993 break;
4994 view->count = s->parent_view->count;
4996 if (prev_id == NULL)
4997 break;
4998 id = get_selected_commit_id(bs->blame.lines,
4999 bs->blame.nlines, bs->first_displayed_line,
5000 bs->selected_line);
5001 if (id == NULL)
5002 break;
5004 if (!got_object_id_cmp(prev_id, id))
5005 break;
5007 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5008 if (err)
5009 break;
5011 s->first_displayed_line = 1;
5012 s->last_displayed_line = view->nlines;
5013 s->matched_line = 0;
5014 view->x = 0;
5016 diff_view_indicate_progress(view);
5017 err = create_diff(s);
5018 break;
5019 default:
5020 view->count = 0;
5021 break;
5024 return err;
5027 static const struct got_error *
5028 cmd_diff(int argc, char *argv[])
5030 const struct got_error *error = NULL;
5031 struct got_repository *repo = NULL;
5032 struct got_worktree *worktree = NULL;
5033 struct got_object_id *id1 = NULL, *id2 = NULL;
5034 char *repo_path = NULL, *cwd = NULL;
5035 char *id_str1 = NULL, *id_str2 = NULL;
5036 char *label1 = NULL, *label2 = NULL;
5037 int diff_context = 3, ignore_whitespace = 0;
5038 int ch, force_text_diff = 0;
5039 const char *errstr;
5040 struct tog_view *view;
5041 int *pack_fds = NULL;
5043 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5044 switch (ch) {
5045 case 'a':
5046 force_text_diff = 1;
5047 break;
5048 case 'C':
5049 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5050 &errstr);
5051 if (errstr != NULL)
5052 errx(1, "number of context lines is %s: %s",
5053 errstr, errstr);
5054 break;
5055 case 'r':
5056 repo_path = realpath(optarg, NULL);
5057 if (repo_path == NULL)
5058 return got_error_from_errno2("realpath",
5059 optarg);
5060 got_path_strip_trailing_slashes(repo_path);
5061 break;
5062 case 'w':
5063 ignore_whitespace = 1;
5064 break;
5065 default:
5066 usage_diff();
5067 /* NOTREACHED */
5071 argc -= optind;
5072 argv += optind;
5074 if (argc == 0) {
5075 usage_diff(); /* TODO show local worktree changes */
5076 } else if (argc == 2) {
5077 id_str1 = argv[0];
5078 id_str2 = argv[1];
5079 } else
5080 usage_diff();
5082 error = got_repo_pack_fds_open(&pack_fds);
5083 if (error)
5084 goto done;
5086 if (repo_path == NULL) {
5087 cwd = getcwd(NULL, 0);
5088 if (cwd == NULL)
5089 return got_error_from_errno("getcwd");
5090 error = got_worktree_open(&worktree, cwd);
5091 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5092 goto done;
5093 if (worktree)
5094 repo_path =
5095 strdup(got_worktree_get_repo_path(worktree));
5096 else
5097 repo_path = strdup(cwd);
5098 if (repo_path == NULL) {
5099 error = got_error_from_errno("strdup");
5100 goto done;
5104 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5105 if (error)
5106 goto done;
5108 init_curses();
5110 error = apply_unveil(got_repo_get_path(repo), NULL);
5111 if (error)
5112 goto done;
5114 error = tog_load_refs(repo, 0);
5115 if (error)
5116 goto done;
5118 error = got_repo_match_object_id(&id1, &label1, id_str1,
5119 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5120 if (error)
5121 goto done;
5123 error = got_repo_match_object_id(&id2, &label2, id_str2,
5124 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5125 if (error)
5126 goto done;
5128 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5129 if (view == NULL) {
5130 error = got_error_from_errno("view_open");
5131 goto done;
5133 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5134 ignore_whitespace, force_text_diff, NULL, repo);
5135 if (error)
5136 goto done;
5137 error = view_loop(view);
5138 done:
5139 free(label1);
5140 free(label2);
5141 free(repo_path);
5142 free(cwd);
5143 if (repo) {
5144 const struct got_error *close_err = got_repo_close(repo);
5145 if (error == NULL)
5146 error = close_err;
5148 if (worktree)
5149 got_worktree_close(worktree);
5150 if (pack_fds) {
5151 const struct got_error *pack_err =
5152 got_repo_pack_fds_close(pack_fds);
5153 if (error == NULL)
5154 error = pack_err;
5156 tog_free_refs();
5157 return error;
5160 __dead static void
5161 usage_blame(void)
5163 endwin();
5164 fprintf(stderr,
5165 "usage: %s blame [-c commit] [-r repository-path] path\n",
5166 getprogname());
5167 exit(1);
5170 struct tog_blame_line {
5171 int annotated;
5172 struct got_object_id *id;
5175 static const struct got_error *
5176 draw_blame(struct tog_view *view)
5178 struct tog_blame_view_state *s = &view->state.blame;
5179 struct tog_blame *blame = &s->blame;
5180 regmatch_t *regmatch = &view->regmatch;
5181 const struct got_error *err;
5182 int lineno = 0, nprinted = 0;
5183 char *line = NULL;
5184 size_t linesize = 0;
5185 ssize_t linelen;
5186 wchar_t *wline;
5187 int width;
5188 struct tog_blame_line *blame_line;
5189 struct got_object_id *prev_id = NULL;
5190 char *id_str;
5191 struct tog_color *tc;
5193 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5194 if (err)
5195 return err;
5197 rewind(blame->f);
5198 werase(view->window);
5200 if (asprintf(&line, "commit %s", id_str) == -1) {
5201 err = got_error_from_errno("asprintf");
5202 free(id_str);
5203 return err;
5206 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5207 free(line);
5208 line = NULL;
5209 if (err)
5210 return err;
5211 if (view_needs_focus_indication(view))
5212 wstandout(view->window);
5213 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5214 if (tc)
5215 wattr_on(view->window,
5216 COLOR_PAIR(tc->colorpair), NULL);
5217 waddwstr(view->window, wline);
5218 if (tc)
5219 wattr_off(view->window,
5220 COLOR_PAIR(tc->colorpair), NULL);
5221 if (view_needs_focus_indication(view))
5222 wstandend(view->window);
5223 free(wline);
5224 wline = NULL;
5225 if (width < view->ncols - 1)
5226 waddch(view->window, '\n');
5228 if (view->gline > blame->nlines)
5229 view->gline = blame->nlines;
5231 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5232 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5233 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5234 free(id_str);
5235 return got_error_from_errno("asprintf");
5237 free(id_str);
5238 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5239 free(line);
5240 line = NULL;
5241 if (err)
5242 return err;
5243 waddwstr(view->window, wline);
5244 free(wline);
5245 wline = NULL;
5246 if (width < view->ncols - 1)
5247 waddch(view->window, '\n');
5249 s->eof = 0;
5250 view->maxx = 0;
5251 while (nprinted < view->nlines - 2) {
5252 linelen = getline(&line, &linesize, blame->f);
5253 if (linelen == -1) {
5254 if (feof(blame->f)) {
5255 s->eof = 1;
5256 break;
5258 free(line);
5259 return got_ferror(blame->f, GOT_ERR_IO);
5261 if (++lineno < s->first_displayed_line)
5262 continue;
5263 if (view->gline && !gotoline(view, &lineno, &nprinted))
5264 continue;
5266 /* Set view->maxx based on full line length. */
5267 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5268 if (err) {
5269 free(line);
5270 return err;
5272 free(wline);
5273 wline = NULL;
5274 view->maxx = MAX(view->maxx, width);
5276 if (nprinted == s->selected_line - 1)
5277 wstandout(view->window);
5279 if (blame->nlines > 0) {
5280 blame_line = &blame->lines[lineno - 1];
5281 if (blame_line->annotated && prev_id &&
5282 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5283 !(nprinted == s->selected_line - 1)) {
5284 waddstr(view->window, " ");
5285 } else if (blame_line->annotated) {
5286 char *id_str;
5287 err = got_object_id_str(&id_str,
5288 blame_line->id);
5289 if (err) {
5290 free(line);
5291 return err;
5293 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5294 if (tc)
5295 wattr_on(view->window,
5296 COLOR_PAIR(tc->colorpair), NULL);
5297 wprintw(view->window, "%.8s", id_str);
5298 if (tc)
5299 wattr_off(view->window,
5300 COLOR_PAIR(tc->colorpair), NULL);
5301 free(id_str);
5302 prev_id = blame_line->id;
5303 } else {
5304 waddstr(view->window, "........");
5305 prev_id = NULL;
5307 } else {
5308 waddstr(view->window, "........");
5309 prev_id = NULL;
5312 if (nprinted == s->selected_line - 1)
5313 wstandend(view->window);
5314 waddstr(view->window, " ");
5316 if (view->ncols <= 9) {
5317 width = 9;
5318 } else if (s->first_displayed_line + nprinted ==
5319 s->matched_line &&
5320 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5321 err = add_matched_line(&width, line, view->ncols - 9, 9,
5322 view->window, view->x, regmatch);
5323 if (err) {
5324 free(line);
5325 return err;
5327 width += 9;
5328 } else {
5329 int skip;
5330 err = format_line(&wline, &width, &skip, line,
5331 view->x, view->ncols - 9, 9, 1);
5332 if (err) {
5333 free(line);
5334 return err;
5336 waddwstr(view->window, &wline[skip]);
5337 width += 9;
5338 free(wline);
5339 wline = NULL;
5342 if (width <= view->ncols - 1)
5343 waddch(view->window, '\n');
5344 if (++nprinted == 1)
5345 s->first_displayed_line = lineno;
5347 free(line);
5348 s->last_displayed_line = lineno;
5350 view_border(view);
5352 return NULL;
5355 static const struct got_error *
5356 blame_cb(void *arg, int nlines, int lineno,
5357 struct got_commit_object *commit, struct got_object_id *id)
5359 const struct got_error *err = NULL;
5360 struct tog_blame_cb_args *a = arg;
5361 struct tog_blame_line *line;
5362 int errcode;
5364 if (nlines != a->nlines ||
5365 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5366 return got_error(GOT_ERR_RANGE);
5368 errcode = pthread_mutex_lock(&tog_mutex);
5369 if (errcode)
5370 return got_error_set_errno(errcode, "pthread_mutex_lock");
5372 if (*a->quit) { /* user has quit the blame view */
5373 err = got_error(GOT_ERR_ITER_COMPLETED);
5374 goto done;
5377 if (lineno == -1)
5378 goto done; /* no change in this commit */
5380 line = &a->lines[lineno - 1];
5381 if (line->annotated)
5382 goto done;
5384 line->id = got_object_id_dup(id);
5385 if (line->id == NULL) {
5386 err = got_error_from_errno("got_object_id_dup");
5387 goto done;
5389 line->annotated = 1;
5390 done:
5391 errcode = pthread_mutex_unlock(&tog_mutex);
5392 if (errcode)
5393 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5394 return err;
5397 static void *
5398 blame_thread(void *arg)
5400 const struct got_error *err, *close_err;
5401 struct tog_blame_thread_args *ta = arg;
5402 struct tog_blame_cb_args *a = ta->cb_args;
5403 int errcode, fd1 = -1, fd2 = -1;
5404 FILE *f1 = NULL, *f2 = NULL;
5406 fd1 = got_opentempfd();
5407 if (fd1 == -1)
5408 return (void *)got_error_from_errno("got_opentempfd");
5410 fd2 = got_opentempfd();
5411 if (fd2 == -1) {
5412 err = got_error_from_errno("got_opentempfd");
5413 goto done;
5416 f1 = got_opentemp();
5417 if (f1 == NULL) {
5418 err = (void *)got_error_from_errno("got_opentemp");
5419 goto done;
5421 f2 = got_opentemp();
5422 if (f2 == NULL) {
5423 err = (void *)got_error_from_errno("got_opentemp");
5424 goto done;
5427 err = block_signals_used_by_main_thread();
5428 if (err)
5429 goto done;
5431 err = got_blame(ta->path, a->commit_id, ta->repo,
5432 tog_diff_algo, blame_cb, ta->cb_args,
5433 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5434 if (err && err->code == GOT_ERR_CANCELLED)
5435 err = NULL;
5437 errcode = pthread_mutex_lock(&tog_mutex);
5438 if (errcode) {
5439 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5440 goto done;
5443 close_err = got_repo_close(ta->repo);
5444 if (err == NULL)
5445 err = close_err;
5446 ta->repo = NULL;
5447 *ta->complete = 1;
5449 errcode = pthread_mutex_unlock(&tog_mutex);
5450 if (errcode && err == NULL)
5451 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5453 done:
5454 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5455 err = got_error_from_errno("close");
5456 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5457 err = got_error_from_errno("close");
5458 if (f1 && fclose(f1) == EOF && err == NULL)
5459 err = got_error_from_errno("fclose");
5460 if (f2 && fclose(f2) == EOF && err == NULL)
5461 err = got_error_from_errno("fclose");
5463 return (void *)err;
5466 static struct got_object_id *
5467 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5468 int first_displayed_line, int selected_line)
5470 struct tog_blame_line *line;
5472 if (nlines <= 0)
5473 return NULL;
5475 line = &lines[first_displayed_line - 1 + selected_line - 1];
5476 if (!line->annotated)
5477 return NULL;
5479 return line->id;
5482 static struct got_object_id *
5483 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5484 int lineno)
5486 struct tog_blame_line *line;
5488 if (nlines <= 0 || lineno >= nlines)
5489 return NULL;
5491 line = &lines[lineno - 1];
5492 if (!line->annotated)
5493 return NULL;
5495 return line->id;
5498 static const struct got_error *
5499 stop_blame(struct tog_blame *blame)
5501 const struct got_error *err = NULL;
5502 int i;
5504 if (blame->thread) {
5505 int errcode;
5506 errcode = pthread_mutex_unlock(&tog_mutex);
5507 if (errcode)
5508 return got_error_set_errno(errcode,
5509 "pthread_mutex_unlock");
5510 errcode = pthread_join(blame->thread, (void **)&err);
5511 if (errcode)
5512 return got_error_set_errno(errcode, "pthread_join");
5513 errcode = pthread_mutex_lock(&tog_mutex);
5514 if (errcode)
5515 return got_error_set_errno(errcode,
5516 "pthread_mutex_lock");
5517 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5518 err = NULL;
5519 blame->thread = 0; //NULL;
5521 if (blame->thread_args.repo) {
5522 const struct got_error *close_err;
5523 close_err = got_repo_close(blame->thread_args.repo);
5524 if (err == NULL)
5525 err = close_err;
5526 blame->thread_args.repo = NULL;
5528 if (blame->f) {
5529 if (fclose(blame->f) == EOF && err == NULL)
5530 err = got_error_from_errno("fclose");
5531 blame->f = NULL;
5533 if (blame->lines) {
5534 for (i = 0; i < blame->nlines; i++)
5535 free(blame->lines[i].id);
5536 free(blame->lines);
5537 blame->lines = NULL;
5539 free(blame->cb_args.commit_id);
5540 blame->cb_args.commit_id = NULL;
5541 if (blame->pack_fds) {
5542 const struct got_error *pack_err =
5543 got_repo_pack_fds_close(blame->pack_fds);
5544 if (err == NULL)
5545 err = pack_err;
5546 blame->pack_fds = NULL;
5548 return err;
5551 static const struct got_error *
5552 cancel_blame_view(void *arg)
5554 const struct got_error *err = NULL;
5555 int *done = arg;
5556 int errcode;
5558 errcode = pthread_mutex_lock(&tog_mutex);
5559 if (errcode)
5560 return got_error_set_errno(errcode,
5561 "pthread_mutex_unlock");
5563 if (*done)
5564 err = got_error(GOT_ERR_CANCELLED);
5566 errcode = pthread_mutex_unlock(&tog_mutex);
5567 if (errcode)
5568 return got_error_set_errno(errcode,
5569 "pthread_mutex_lock");
5571 return err;
5574 static const struct got_error *
5575 run_blame(struct tog_view *view)
5577 struct tog_blame_view_state *s = &view->state.blame;
5578 struct tog_blame *blame = &s->blame;
5579 const struct got_error *err = NULL;
5580 struct got_commit_object *commit = NULL;
5581 struct got_blob_object *blob = NULL;
5582 struct got_repository *thread_repo = NULL;
5583 struct got_object_id *obj_id = NULL;
5584 int obj_type, fd = -1;
5585 int *pack_fds = NULL;
5587 err = got_object_open_as_commit(&commit, s->repo,
5588 &s->blamed_commit->id);
5589 if (err)
5590 return err;
5592 fd = got_opentempfd();
5593 if (fd == -1) {
5594 err = got_error_from_errno("got_opentempfd");
5595 goto done;
5598 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5599 if (err)
5600 goto done;
5602 err = got_object_get_type(&obj_type, s->repo, obj_id);
5603 if (err)
5604 goto done;
5606 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5607 err = got_error(GOT_ERR_OBJ_TYPE);
5608 goto done;
5611 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5612 if (err)
5613 goto done;
5614 blame->f = got_opentemp();
5615 if (blame->f == NULL) {
5616 err = got_error_from_errno("got_opentemp");
5617 goto done;
5619 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5620 &blame->line_offsets, blame->f, blob);
5621 if (err)
5622 goto done;
5623 if (blame->nlines == 0) {
5624 s->blame_complete = 1;
5625 goto done;
5628 /* Don't include \n at EOF in the blame line count. */
5629 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5630 blame->nlines--;
5632 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5633 if (blame->lines == NULL) {
5634 err = got_error_from_errno("calloc");
5635 goto done;
5638 err = got_repo_pack_fds_open(&pack_fds);
5639 if (err)
5640 goto done;
5641 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5642 pack_fds);
5643 if (err)
5644 goto done;
5646 blame->pack_fds = pack_fds;
5647 blame->cb_args.view = view;
5648 blame->cb_args.lines = blame->lines;
5649 blame->cb_args.nlines = blame->nlines;
5650 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5651 if (blame->cb_args.commit_id == NULL) {
5652 err = got_error_from_errno("got_object_id_dup");
5653 goto done;
5655 blame->cb_args.quit = &s->done;
5657 blame->thread_args.path = s->path;
5658 blame->thread_args.repo = thread_repo;
5659 blame->thread_args.cb_args = &blame->cb_args;
5660 blame->thread_args.complete = &s->blame_complete;
5661 blame->thread_args.cancel_cb = cancel_blame_view;
5662 blame->thread_args.cancel_arg = &s->done;
5663 s->blame_complete = 0;
5665 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5666 s->first_displayed_line = 1;
5667 s->last_displayed_line = view->nlines;
5668 s->selected_line = 1;
5670 s->matched_line = 0;
5672 done:
5673 if (commit)
5674 got_object_commit_close(commit);
5675 if (fd != -1 && close(fd) == -1 && err == NULL)
5676 err = got_error_from_errno("close");
5677 if (blob)
5678 got_object_blob_close(blob);
5679 free(obj_id);
5680 if (err)
5681 stop_blame(blame);
5682 return err;
5685 static const struct got_error *
5686 open_blame_view(struct tog_view *view, char *path,
5687 struct got_object_id *commit_id, struct got_repository *repo)
5689 const struct got_error *err = NULL;
5690 struct tog_blame_view_state *s = &view->state.blame;
5692 STAILQ_INIT(&s->blamed_commits);
5694 s->path = strdup(path);
5695 if (s->path == NULL)
5696 return got_error_from_errno("strdup");
5698 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5699 if (err) {
5700 free(s->path);
5701 return err;
5704 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5705 s->first_displayed_line = 1;
5706 s->last_displayed_line = view->nlines;
5707 s->selected_line = 1;
5708 s->blame_complete = 0;
5709 s->repo = repo;
5710 s->commit_id = commit_id;
5711 memset(&s->blame, 0, sizeof(s->blame));
5713 STAILQ_INIT(&s->colors);
5714 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5715 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5716 get_color_value("TOG_COLOR_COMMIT"));
5717 if (err)
5718 return err;
5721 view->show = show_blame_view;
5722 view->input = input_blame_view;
5723 view->reset = reset_blame_view;
5724 view->close = close_blame_view;
5725 view->search_start = search_start_blame_view;
5726 view->search_next = search_next_blame_view;
5728 return run_blame(view);
5731 static const struct got_error *
5732 close_blame_view(struct tog_view *view)
5734 const struct got_error *err = NULL;
5735 struct tog_blame_view_state *s = &view->state.blame;
5737 if (s->blame.thread)
5738 err = stop_blame(&s->blame);
5740 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5741 struct got_object_qid *blamed_commit;
5742 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5743 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5744 got_object_qid_free(blamed_commit);
5747 free(s->path);
5748 free_colors(&s->colors);
5749 return err;
5752 static const struct got_error *
5753 search_start_blame_view(struct tog_view *view)
5755 struct tog_blame_view_state *s = &view->state.blame;
5757 s->matched_line = 0;
5758 return NULL;
5761 static const struct got_error *
5762 search_next_blame_view(struct tog_view *view)
5764 struct tog_blame_view_state *s = &view->state.blame;
5765 const struct got_error *err = NULL;
5766 int lineno;
5767 char *line = NULL;
5768 size_t linesize = 0;
5769 ssize_t linelen;
5771 if (!view->searching) {
5772 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5773 return NULL;
5776 if (s->matched_line) {
5777 if (view->searching == TOG_SEARCH_FORWARD)
5778 lineno = s->matched_line + 1;
5779 else
5780 lineno = s->matched_line - 1;
5781 } else
5782 lineno = s->first_displayed_line - 1 + s->selected_line;
5784 while (1) {
5785 off_t offset;
5787 if (lineno <= 0 || lineno > s->blame.nlines) {
5788 if (s->matched_line == 0) {
5789 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5790 break;
5793 if (view->searching == TOG_SEARCH_FORWARD)
5794 lineno = 1;
5795 else
5796 lineno = s->blame.nlines;
5799 offset = s->blame.line_offsets[lineno - 1];
5800 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5801 free(line);
5802 return got_error_from_errno("fseeko");
5804 linelen = getline(&line, &linesize, s->blame.f);
5805 if (linelen != -1) {
5806 char *exstr;
5807 err = expand_tab(&exstr, line);
5808 if (err)
5809 break;
5810 if (match_line(exstr, &view->regex, 1,
5811 &view->regmatch)) {
5812 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5813 s->matched_line = lineno;
5814 free(exstr);
5815 break;
5817 free(exstr);
5819 if (view->searching == TOG_SEARCH_FORWARD)
5820 lineno++;
5821 else
5822 lineno--;
5824 free(line);
5826 if (s->matched_line) {
5827 s->first_displayed_line = s->matched_line;
5828 s->selected_line = 1;
5831 return err;
5834 static const struct got_error *
5835 show_blame_view(struct tog_view *view)
5837 const struct got_error *err = NULL;
5838 struct tog_blame_view_state *s = &view->state.blame;
5839 int errcode;
5841 if (s->blame.thread == 0 && !s->blame_complete) {
5842 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5843 &s->blame.thread_args);
5844 if (errcode)
5845 return got_error_set_errno(errcode, "pthread_create");
5847 halfdelay(1); /* fast refresh while annotating */
5850 if (s->blame_complete)
5851 halfdelay(10); /* disable fast refresh */
5853 err = draw_blame(view);
5855 view_border(view);
5856 return err;
5859 static const struct got_error *
5860 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5861 struct got_repository *repo, struct got_object_id *id)
5863 struct tog_view *log_view;
5864 const struct got_error *err = NULL;
5866 *new_view = NULL;
5868 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5869 if (log_view == NULL)
5870 return got_error_from_errno("view_open");
5872 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5873 if (err)
5874 view_close(log_view);
5875 else
5876 *new_view = log_view;
5878 return err;
5881 static const struct got_error *
5882 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5884 const struct got_error *err = NULL, *thread_err = NULL;
5885 struct tog_view *diff_view;
5886 struct tog_blame_view_state *s = &view->state.blame;
5887 int eos, nscroll, begin_y = 0, begin_x = 0;
5889 eos = nscroll = view->nlines - 2;
5890 if (view_is_hsplit_top(view))
5891 --eos; /* border */
5893 switch (ch) {
5894 case '0':
5895 view->x = 0;
5896 break;
5897 case '$':
5898 view->x = MAX(view->maxx - view->ncols / 3, 0);
5899 view->count = 0;
5900 break;
5901 case KEY_RIGHT:
5902 case 'l':
5903 if (view->x + view->ncols / 3 < view->maxx)
5904 view->x += 2; /* move two columns right */
5905 else
5906 view->count = 0;
5907 break;
5908 case KEY_LEFT:
5909 case 'h':
5910 view->x -= MIN(view->x, 2); /* move two columns back */
5911 if (view->x <= 0)
5912 view->count = 0;
5913 break;
5914 case 'q':
5915 s->done = 1;
5916 break;
5917 case 'g':
5918 case KEY_HOME:
5919 s->selected_line = 1;
5920 s->first_displayed_line = 1;
5921 view->count = 0;
5922 break;
5923 case 'G':
5924 case KEY_END:
5925 if (s->blame.nlines < eos) {
5926 s->selected_line = s->blame.nlines;
5927 s->first_displayed_line = 1;
5928 } else {
5929 s->selected_line = eos;
5930 s->first_displayed_line = s->blame.nlines - (eos - 1);
5932 view->count = 0;
5933 break;
5934 case 'k':
5935 case KEY_UP:
5936 case CTRL('p'):
5937 if (s->selected_line > 1)
5938 s->selected_line--;
5939 else if (s->selected_line == 1 &&
5940 s->first_displayed_line > 1)
5941 s->first_displayed_line--;
5942 else
5943 view->count = 0;
5944 break;
5945 case CTRL('u'):
5946 case 'u':
5947 nscroll /= 2;
5948 /* FALL THROUGH */
5949 case KEY_PPAGE:
5950 case CTRL('b'):
5951 case 'b':
5952 if (s->first_displayed_line == 1) {
5953 if (view->count > 1)
5954 nscroll += nscroll;
5955 s->selected_line = MAX(1, s->selected_line - nscroll);
5956 view->count = 0;
5957 break;
5959 if (s->first_displayed_line > nscroll)
5960 s->first_displayed_line -= nscroll;
5961 else
5962 s->first_displayed_line = 1;
5963 break;
5964 case 'j':
5965 case KEY_DOWN:
5966 case CTRL('n'):
5967 if (s->selected_line < eos && s->first_displayed_line +
5968 s->selected_line <= s->blame.nlines)
5969 s->selected_line++;
5970 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5971 s->first_displayed_line++;
5972 else
5973 view->count = 0;
5974 break;
5975 case 'c':
5976 case 'p': {
5977 struct got_object_id *id = NULL;
5979 view->count = 0;
5980 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5981 s->first_displayed_line, s->selected_line);
5982 if (id == NULL)
5983 break;
5984 if (ch == 'p') {
5985 struct got_commit_object *commit, *pcommit;
5986 struct got_object_qid *pid;
5987 struct got_object_id *blob_id = NULL;
5988 int obj_type;
5989 err = got_object_open_as_commit(&commit,
5990 s->repo, id);
5991 if (err)
5992 break;
5993 pid = STAILQ_FIRST(
5994 got_object_commit_get_parent_ids(commit));
5995 if (pid == NULL) {
5996 got_object_commit_close(commit);
5997 break;
5999 /* Check if path history ends here. */
6000 err = got_object_open_as_commit(&pcommit,
6001 s->repo, &pid->id);
6002 if (err)
6003 break;
6004 err = got_object_id_by_path(&blob_id, s->repo,
6005 pcommit, s->path);
6006 got_object_commit_close(pcommit);
6007 if (err) {
6008 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6009 err = NULL;
6010 got_object_commit_close(commit);
6011 break;
6013 err = got_object_get_type(&obj_type, s->repo,
6014 blob_id);
6015 free(blob_id);
6016 /* Can't blame non-blob type objects. */
6017 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6018 got_object_commit_close(commit);
6019 break;
6021 err = got_object_qid_alloc(&s->blamed_commit,
6022 &pid->id);
6023 got_object_commit_close(commit);
6024 } else {
6025 if (got_object_id_cmp(id,
6026 &s->blamed_commit->id) == 0)
6027 break;
6028 err = got_object_qid_alloc(&s->blamed_commit,
6029 id);
6031 if (err)
6032 break;
6033 s->done = 1;
6034 thread_err = stop_blame(&s->blame);
6035 s->done = 0;
6036 if (thread_err)
6037 break;
6038 STAILQ_INSERT_HEAD(&s->blamed_commits,
6039 s->blamed_commit, entry);
6040 err = run_blame(view);
6041 if (err)
6042 break;
6043 break;
6045 case 'C': {
6046 struct got_object_qid *first;
6048 view->count = 0;
6049 first = STAILQ_FIRST(&s->blamed_commits);
6050 if (!got_object_id_cmp(&first->id, s->commit_id))
6051 break;
6052 s->done = 1;
6053 thread_err = stop_blame(&s->blame);
6054 s->done = 0;
6055 if (thread_err)
6056 break;
6057 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6058 got_object_qid_free(s->blamed_commit);
6059 s->blamed_commit =
6060 STAILQ_FIRST(&s->blamed_commits);
6061 err = run_blame(view);
6062 if (err)
6063 break;
6064 break;
6066 case 'L':
6067 view->count = 0;
6068 s->id_to_log = get_selected_commit_id(s->blame.lines,
6069 s->blame.nlines, s->first_displayed_line, s->selected_line);
6070 if (s->id_to_log)
6071 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6072 break;
6073 case KEY_ENTER:
6074 case '\r': {
6075 struct got_object_id *id = NULL;
6076 struct got_object_qid *pid;
6077 struct got_commit_object *commit = NULL;
6079 view->count = 0;
6080 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6081 s->first_displayed_line, s->selected_line);
6082 if (id == NULL)
6083 break;
6084 err = got_object_open_as_commit(&commit, s->repo, id);
6085 if (err)
6086 break;
6087 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6088 if (*new_view) {
6089 /* traversed from diff view, release diff resources */
6090 err = close_diff_view(*new_view);
6091 if (err)
6092 break;
6093 diff_view = *new_view;
6094 } else {
6095 if (view_is_parent_view(view))
6096 view_get_split(view, &begin_y, &begin_x);
6098 diff_view = view_open(0, 0, begin_y, begin_x,
6099 TOG_VIEW_DIFF);
6100 if (diff_view == NULL) {
6101 got_object_commit_close(commit);
6102 err = got_error_from_errno("view_open");
6103 break;
6106 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6107 id, NULL, NULL, 3, 0, 0, view, s->repo);
6108 got_object_commit_close(commit);
6109 if (err) {
6110 view_close(diff_view);
6111 break;
6113 s->last_diffed_line = s->first_displayed_line - 1 +
6114 s->selected_line;
6115 if (*new_view)
6116 break; /* still open from active diff view */
6117 if (view_is_parent_view(view) &&
6118 view->mode == TOG_VIEW_SPLIT_HRZN) {
6119 err = view_init_hsplit(view, begin_y);
6120 if (err)
6121 break;
6124 view->focussed = 0;
6125 diff_view->focussed = 1;
6126 diff_view->mode = view->mode;
6127 diff_view->nlines = view->lines - begin_y;
6128 if (view_is_parent_view(view)) {
6129 view_transfer_size(diff_view, view);
6130 err = view_close_child(view);
6131 if (err)
6132 break;
6133 err = view_set_child(view, diff_view);
6134 if (err)
6135 break;
6136 view->focus_child = 1;
6137 } else
6138 *new_view = diff_view;
6139 if (err)
6140 break;
6141 break;
6143 case CTRL('d'):
6144 case 'd':
6145 nscroll /= 2;
6146 /* FALL THROUGH */
6147 case KEY_NPAGE:
6148 case CTRL('f'):
6149 case 'f':
6150 case ' ':
6151 if (s->last_displayed_line >= s->blame.nlines &&
6152 s->selected_line >= MIN(s->blame.nlines,
6153 view->nlines - 2)) {
6154 view->count = 0;
6155 break;
6157 if (s->last_displayed_line >= s->blame.nlines &&
6158 s->selected_line < view->nlines - 2) {
6159 s->selected_line +=
6160 MIN(nscroll, s->last_displayed_line -
6161 s->first_displayed_line - s->selected_line + 1);
6163 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6164 s->first_displayed_line += nscroll;
6165 else
6166 s->first_displayed_line =
6167 s->blame.nlines - (view->nlines - 3);
6168 break;
6169 case KEY_RESIZE:
6170 if (s->selected_line > view->nlines - 2) {
6171 s->selected_line = MIN(s->blame.nlines,
6172 view->nlines - 2);
6174 break;
6175 default:
6176 view->count = 0;
6177 break;
6179 return thread_err ? thread_err : err;
6182 static const struct got_error *
6183 reset_blame_view(struct tog_view *view)
6185 const struct got_error *err;
6186 struct tog_blame_view_state *s = &view->state.blame;
6188 view->count = 0;
6189 s->done = 1;
6190 err = stop_blame(&s->blame);
6191 s->done = 0;
6192 if (err)
6193 return err;
6194 return run_blame(view);
6197 static const struct got_error *
6198 cmd_blame(int argc, char *argv[])
6200 const struct got_error *error;
6201 struct got_repository *repo = NULL;
6202 struct got_worktree *worktree = NULL;
6203 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6204 char *link_target = NULL;
6205 struct got_object_id *commit_id = NULL;
6206 struct got_commit_object *commit = NULL;
6207 char *commit_id_str = NULL;
6208 int ch;
6209 struct tog_view *view;
6210 int *pack_fds = NULL;
6212 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6213 switch (ch) {
6214 case 'c':
6215 commit_id_str = optarg;
6216 break;
6217 case 'r':
6218 repo_path = realpath(optarg, NULL);
6219 if (repo_path == NULL)
6220 return got_error_from_errno2("realpath",
6221 optarg);
6222 break;
6223 default:
6224 usage_blame();
6225 /* NOTREACHED */
6229 argc -= optind;
6230 argv += optind;
6232 if (argc != 1)
6233 usage_blame();
6235 error = got_repo_pack_fds_open(&pack_fds);
6236 if (error != NULL)
6237 goto done;
6239 if (repo_path == NULL) {
6240 cwd = getcwd(NULL, 0);
6241 if (cwd == NULL)
6242 return got_error_from_errno("getcwd");
6243 error = got_worktree_open(&worktree, cwd);
6244 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6245 goto done;
6246 if (worktree)
6247 repo_path =
6248 strdup(got_worktree_get_repo_path(worktree));
6249 else
6250 repo_path = strdup(cwd);
6251 if (repo_path == NULL) {
6252 error = got_error_from_errno("strdup");
6253 goto done;
6257 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6258 if (error != NULL)
6259 goto done;
6261 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6262 worktree);
6263 if (error)
6264 goto done;
6266 init_curses();
6268 error = apply_unveil(got_repo_get_path(repo), NULL);
6269 if (error)
6270 goto done;
6272 error = tog_load_refs(repo, 0);
6273 if (error)
6274 goto done;
6276 if (commit_id_str == NULL) {
6277 struct got_reference *head_ref;
6278 error = got_ref_open(&head_ref, repo, worktree ?
6279 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6280 if (error != NULL)
6281 goto done;
6282 error = got_ref_resolve(&commit_id, repo, head_ref);
6283 got_ref_close(head_ref);
6284 } else {
6285 error = got_repo_match_object_id(&commit_id, NULL,
6286 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6288 if (error != NULL)
6289 goto done;
6291 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6292 if (view == NULL) {
6293 error = got_error_from_errno("view_open");
6294 goto done;
6297 error = got_object_open_as_commit(&commit, repo, commit_id);
6298 if (error)
6299 goto done;
6301 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6302 commit, repo);
6303 if (error)
6304 goto done;
6306 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6307 commit_id, repo);
6308 if (error)
6309 goto done;
6310 if (worktree) {
6311 /* Release work tree lock. */
6312 got_worktree_close(worktree);
6313 worktree = NULL;
6315 error = view_loop(view);
6316 done:
6317 free(repo_path);
6318 free(in_repo_path);
6319 free(link_target);
6320 free(cwd);
6321 free(commit_id);
6322 if (commit)
6323 got_object_commit_close(commit);
6324 if (worktree)
6325 got_worktree_close(worktree);
6326 if (repo) {
6327 const struct got_error *close_err = got_repo_close(repo);
6328 if (error == NULL)
6329 error = close_err;
6331 if (pack_fds) {
6332 const struct got_error *pack_err =
6333 got_repo_pack_fds_close(pack_fds);
6334 if (error == NULL)
6335 error = pack_err;
6337 tog_free_refs();
6338 return error;
6341 static const struct got_error *
6342 draw_tree_entries(struct tog_view *view, const char *parent_path)
6344 struct tog_tree_view_state *s = &view->state.tree;
6345 const struct got_error *err = NULL;
6346 struct got_tree_entry *te;
6347 wchar_t *wline;
6348 struct tog_color *tc;
6349 int width, n, nentries, i = 1;
6350 int limit = view->nlines;
6352 s->ndisplayed = 0;
6353 if (view_is_hsplit_top(view))
6354 --limit; /* border */
6356 werase(view->window);
6358 if (limit == 0)
6359 return NULL;
6361 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6362 0, 0);
6363 if (err)
6364 return err;
6365 if (view_needs_focus_indication(view))
6366 wstandout(view->window);
6367 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6368 if (tc)
6369 wattr_on(view->window,
6370 COLOR_PAIR(tc->colorpair), NULL);
6371 waddwstr(view->window, wline);
6372 if (tc)
6373 wattr_off(view->window,
6374 COLOR_PAIR(tc->colorpair), NULL);
6375 if (view_needs_focus_indication(view))
6376 wstandend(view->window);
6377 free(wline);
6378 wline = NULL;
6380 i += s->selected;
6381 if (s->first_displayed_entry) {
6382 i += got_tree_entry_get_index(s->first_displayed_entry);
6383 if (s->tree != s->root)
6384 ++i; /* account for ".." entry */
6386 nentries = got_object_tree_get_nentries(s->tree);
6387 wprintw(view->window, " [%d/%d]", i,
6388 nentries + (s->tree == s->root ? 0 : 1)); /* ".." in !root tree */
6390 if (width < view->ncols - 1)
6391 waddch(view->window, '\n');
6392 if (--limit <= 0)
6393 return NULL;
6394 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6395 0, 0);
6396 if (err)
6397 return err;
6398 waddwstr(view->window, wline);
6399 free(wline);
6400 wline = NULL;
6401 if (width < view->ncols - 1)
6402 waddch(view->window, '\n');
6403 if (--limit <= 0)
6404 return NULL;
6405 waddch(view->window, '\n');
6406 if (--limit <= 0)
6407 return NULL;
6409 if (s->first_displayed_entry == NULL) {
6410 te = got_object_tree_get_first_entry(s->tree);
6411 if (s->selected == 0) {
6412 if (view->focussed)
6413 wstandout(view->window);
6414 s->selected_entry = NULL;
6416 waddstr(view->window, " ..\n"); /* parent directory */
6417 if (s->selected == 0 && view->focussed)
6418 wstandend(view->window);
6419 s->ndisplayed++;
6420 if (--limit <= 0)
6421 return NULL;
6422 n = 1;
6423 } else {
6424 n = 0;
6425 te = s->first_displayed_entry;
6428 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6429 char *line = NULL, *id_str = NULL, *link_target = NULL;
6430 const char *modestr = "";
6431 mode_t mode;
6433 te = got_object_tree_get_entry(s->tree, i);
6434 mode = got_tree_entry_get_mode(te);
6436 if (s->show_ids) {
6437 err = got_object_id_str(&id_str,
6438 got_tree_entry_get_id(te));
6439 if (err)
6440 return got_error_from_errno(
6441 "got_object_id_str");
6443 if (got_object_tree_entry_is_submodule(te))
6444 modestr = "$";
6445 else if (S_ISLNK(mode)) {
6446 int i;
6448 err = got_tree_entry_get_symlink_target(&link_target,
6449 te, s->repo);
6450 if (err) {
6451 free(id_str);
6452 return err;
6454 for (i = 0; i < strlen(link_target); i++) {
6455 if (!isprint((unsigned char)link_target[i]))
6456 link_target[i] = '?';
6458 modestr = "@";
6460 else if (S_ISDIR(mode))
6461 modestr = "/";
6462 else if (mode & S_IXUSR)
6463 modestr = "*";
6464 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6465 got_tree_entry_get_name(te), modestr,
6466 link_target ? " -> ": "",
6467 link_target ? link_target : "") == -1) {
6468 free(id_str);
6469 free(link_target);
6470 return got_error_from_errno("asprintf");
6472 free(id_str);
6473 free(link_target);
6474 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6475 0, 0);
6476 if (err) {
6477 free(line);
6478 break;
6480 if (n == s->selected) {
6481 if (view->focussed)
6482 wstandout(view->window);
6483 s->selected_entry = te;
6485 tc = match_color(&s->colors, line);
6486 if (tc)
6487 wattr_on(view->window,
6488 COLOR_PAIR(tc->colorpair), NULL);
6489 waddwstr(view->window, wline);
6490 if (tc)
6491 wattr_off(view->window,
6492 COLOR_PAIR(tc->colorpair), NULL);
6493 if (width < view->ncols - 1)
6494 waddch(view->window, '\n');
6495 if (n == s->selected && view->focussed)
6496 wstandend(view->window);
6497 free(line);
6498 free(wline);
6499 wline = NULL;
6500 n++;
6501 s->ndisplayed++;
6502 s->last_displayed_entry = te;
6503 if (--limit <= 0)
6504 break;
6507 return err;
6510 static void
6511 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6513 struct got_tree_entry *te;
6514 int isroot = s->tree == s->root;
6515 int i = 0;
6517 if (s->first_displayed_entry == NULL)
6518 return;
6520 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6521 while (i++ < maxscroll) {
6522 if (te == NULL) {
6523 if (!isroot)
6524 s->first_displayed_entry = NULL;
6525 break;
6527 s->first_displayed_entry = te;
6528 te = got_tree_entry_get_prev(s->tree, te);
6532 static const struct got_error *
6533 tree_scroll_down(struct tog_view *view, int maxscroll)
6535 struct tog_tree_view_state *s = &view->state.tree;
6536 struct got_tree_entry *next, *last;
6537 int n = 0;
6539 if (s->first_displayed_entry)
6540 next = got_tree_entry_get_next(s->tree,
6541 s->first_displayed_entry);
6542 else
6543 next = got_object_tree_get_first_entry(s->tree);
6545 last = s->last_displayed_entry;
6546 while (next && n++ < maxscroll) {
6547 if (last) {
6548 s->last_displayed_entry = last;
6549 last = got_tree_entry_get_next(s->tree, last);
6551 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6552 s->first_displayed_entry = next;
6553 next = got_tree_entry_get_next(s->tree, next);
6557 return NULL;
6560 static const struct got_error *
6561 tree_entry_path(char **path, struct tog_parent_trees *parents,
6562 struct got_tree_entry *te)
6564 const struct got_error *err = NULL;
6565 struct tog_parent_tree *pt;
6566 size_t len = 2; /* for leading slash and NUL */
6568 TAILQ_FOREACH(pt, parents, entry)
6569 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6570 + 1 /* slash */;
6571 if (te)
6572 len += strlen(got_tree_entry_get_name(te));
6574 *path = calloc(1, len);
6575 if (path == NULL)
6576 return got_error_from_errno("calloc");
6578 (*path)[0] = '/';
6579 pt = TAILQ_LAST(parents, tog_parent_trees);
6580 while (pt) {
6581 const char *name = got_tree_entry_get_name(pt->selected_entry);
6582 if (strlcat(*path, name, len) >= len) {
6583 err = got_error(GOT_ERR_NO_SPACE);
6584 goto done;
6586 if (strlcat(*path, "/", len) >= len) {
6587 err = got_error(GOT_ERR_NO_SPACE);
6588 goto done;
6590 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6592 if (te) {
6593 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6594 err = got_error(GOT_ERR_NO_SPACE);
6595 goto done;
6598 done:
6599 if (err) {
6600 free(*path);
6601 *path = NULL;
6603 return err;
6606 static const struct got_error *
6607 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6608 struct got_tree_entry *te, struct tog_parent_trees *parents,
6609 struct got_object_id *commit_id, struct got_repository *repo)
6611 const struct got_error *err = NULL;
6612 char *path;
6613 struct tog_view *blame_view;
6615 *new_view = NULL;
6617 err = tree_entry_path(&path, parents, te);
6618 if (err)
6619 return err;
6621 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6622 if (blame_view == NULL) {
6623 err = got_error_from_errno("view_open");
6624 goto done;
6627 err = open_blame_view(blame_view, path, commit_id, repo);
6628 if (err) {
6629 if (err->code == GOT_ERR_CANCELLED)
6630 err = NULL;
6631 view_close(blame_view);
6632 } else
6633 *new_view = blame_view;
6634 done:
6635 free(path);
6636 return err;
6639 static const struct got_error *
6640 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6641 struct tog_tree_view_state *s)
6643 struct tog_view *log_view;
6644 const struct got_error *err = NULL;
6645 char *path;
6647 *new_view = NULL;
6649 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6650 if (log_view == NULL)
6651 return got_error_from_errno("view_open");
6653 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6654 if (err)
6655 return err;
6657 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6658 path, 0);
6659 if (err)
6660 view_close(log_view);
6661 else
6662 *new_view = log_view;
6663 free(path);
6664 return err;
6667 static const struct got_error *
6668 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6669 const char *head_ref_name, struct got_repository *repo)
6671 const struct got_error *err = NULL;
6672 char *commit_id_str = NULL;
6673 struct tog_tree_view_state *s = &view->state.tree;
6674 struct got_commit_object *commit = NULL;
6676 TAILQ_INIT(&s->parents);
6677 STAILQ_INIT(&s->colors);
6679 s->commit_id = got_object_id_dup(commit_id);
6680 if (s->commit_id == NULL)
6681 return got_error_from_errno("got_object_id_dup");
6683 err = got_object_open_as_commit(&commit, repo, commit_id);
6684 if (err)
6685 goto done;
6688 * The root is opened here and will be closed when the view is closed.
6689 * Any visited subtrees and their path-wise parents are opened and
6690 * closed on demand.
6692 err = got_object_open_as_tree(&s->root, repo,
6693 got_object_commit_get_tree_id(commit));
6694 if (err)
6695 goto done;
6696 s->tree = s->root;
6698 err = got_object_id_str(&commit_id_str, commit_id);
6699 if (err != NULL)
6700 goto done;
6702 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6703 err = got_error_from_errno("asprintf");
6704 goto done;
6707 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6708 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6709 if (head_ref_name) {
6710 s->head_ref_name = strdup(head_ref_name);
6711 if (s->head_ref_name == NULL) {
6712 err = got_error_from_errno("strdup");
6713 goto done;
6716 s->repo = repo;
6718 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6719 err = add_color(&s->colors, "\\$$",
6720 TOG_COLOR_TREE_SUBMODULE,
6721 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6722 if (err)
6723 goto done;
6724 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6725 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6726 if (err)
6727 goto done;
6728 err = add_color(&s->colors, "/$",
6729 TOG_COLOR_TREE_DIRECTORY,
6730 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6731 if (err)
6732 goto done;
6734 err = add_color(&s->colors, "\\*$",
6735 TOG_COLOR_TREE_EXECUTABLE,
6736 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6737 if (err)
6738 goto done;
6740 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6741 get_color_value("TOG_COLOR_COMMIT"));
6742 if (err)
6743 goto done;
6746 view->show = show_tree_view;
6747 view->input = input_tree_view;
6748 view->close = close_tree_view;
6749 view->search_start = search_start_tree_view;
6750 view->search_next = search_next_tree_view;
6751 done:
6752 free(commit_id_str);
6753 if (commit)
6754 got_object_commit_close(commit);
6755 if (err)
6756 close_tree_view(view);
6757 return err;
6760 static const struct got_error *
6761 close_tree_view(struct tog_view *view)
6763 struct tog_tree_view_state *s = &view->state.tree;
6765 free_colors(&s->colors);
6766 free(s->tree_label);
6767 s->tree_label = NULL;
6768 free(s->commit_id);
6769 s->commit_id = NULL;
6770 free(s->head_ref_name);
6771 s->head_ref_name = NULL;
6772 while (!TAILQ_EMPTY(&s->parents)) {
6773 struct tog_parent_tree *parent;
6774 parent = TAILQ_FIRST(&s->parents);
6775 TAILQ_REMOVE(&s->parents, parent, entry);
6776 if (parent->tree != s->root)
6777 got_object_tree_close(parent->tree);
6778 free(parent);
6781 if (s->tree != NULL && s->tree != s->root)
6782 got_object_tree_close(s->tree);
6783 if (s->root)
6784 got_object_tree_close(s->root);
6785 return NULL;
6788 static const struct got_error *
6789 search_start_tree_view(struct tog_view *view)
6791 struct tog_tree_view_state *s = &view->state.tree;
6793 s->matched_entry = NULL;
6794 return NULL;
6797 static int
6798 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6800 regmatch_t regmatch;
6802 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6803 0) == 0;
6806 static const struct got_error *
6807 search_next_tree_view(struct tog_view *view)
6809 struct tog_tree_view_state *s = &view->state.tree;
6810 struct got_tree_entry *te = NULL;
6812 if (!view->searching) {
6813 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6814 return NULL;
6817 if (s->matched_entry) {
6818 if (view->searching == TOG_SEARCH_FORWARD) {
6819 if (s->selected_entry)
6820 te = got_tree_entry_get_next(s->tree,
6821 s->selected_entry);
6822 else
6823 te = got_object_tree_get_first_entry(s->tree);
6824 } else {
6825 if (s->selected_entry == NULL)
6826 te = got_object_tree_get_last_entry(s->tree);
6827 else
6828 te = got_tree_entry_get_prev(s->tree,
6829 s->selected_entry);
6831 } else {
6832 if (s->selected_entry)
6833 te = s->selected_entry;
6834 else if (view->searching == TOG_SEARCH_FORWARD)
6835 te = got_object_tree_get_first_entry(s->tree);
6836 else
6837 te = got_object_tree_get_last_entry(s->tree);
6840 while (1) {
6841 if (te == NULL) {
6842 if (s->matched_entry == NULL) {
6843 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6844 return NULL;
6846 if (view->searching == TOG_SEARCH_FORWARD)
6847 te = got_object_tree_get_first_entry(s->tree);
6848 else
6849 te = got_object_tree_get_last_entry(s->tree);
6852 if (match_tree_entry(te, &view->regex)) {
6853 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6854 s->matched_entry = te;
6855 break;
6858 if (view->searching == TOG_SEARCH_FORWARD)
6859 te = got_tree_entry_get_next(s->tree, te);
6860 else
6861 te = got_tree_entry_get_prev(s->tree, te);
6864 if (s->matched_entry) {
6865 s->first_displayed_entry = s->matched_entry;
6866 s->selected = 0;
6869 return NULL;
6872 static const struct got_error *
6873 show_tree_view(struct tog_view *view)
6875 const struct got_error *err = NULL;
6876 struct tog_tree_view_state *s = &view->state.tree;
6877 char *parent_path;
6879 err = tree_entry_path(&parent_path, &s->parents, NULL);
6880 if (err)
6881 return err;
6883 err = draw_tree_entries(view, parent_path);
6884 free(parent_path);
6886 view_border(view);
6887 return err;
6890 static const struct got_error *
6891 tree_goto_line(struct tog_view *view, int nlines)
6893 const struct got_error *err = NULL;
6894 struct tog_tree_view_state *s = &view->state.tree;
6895 struct got_tree_entry **fte, **lte, **ste;
6896 int g, last, first = 1, i = 1;
6897 int root = s->tree == s->root;
6898 int off = root ? 1 : 2;
6900 g = view->gline;
6901 view->gline = 0;
6903 if (g == 0)
6904 g = 1;
6905 else if (g > got_object_tree_get_nentries(s->tree))
6906 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
6908 fte = &s->first_displayed_entry;
6909 lte = &s->last_displayed_entry;
6910 ste = &s->selected_entry;
6912 if (*fte != NULL) {
6913 first = got_tree_entry_get_index(*fte);
6914 first += off; /* account for ".." */
6916 last = got_tree_entry_get_index(*lte);
6917 last += off;
6919 if (g >= first && g <= last && g - first < nlines) {
6920 s->selected = g - first;
6921 return NULL; /* gline is on the current page */
6924 if (*ste != NULL) {
6925 i = got_tree_entry_get_index(*ste);
6926 i += off;
6929 if (i < g) {
6930 err = tree_scroll_down(view, g - i);
6931 if (err)
6932 return err;
6933 if (got_tree_entry_get_index(*lte) >=
6934 got_object_tree_get_nentries(s->tree) - 1 &&
6935 first + s->selected < g &&
6936 s->selected < s->ndisplayed - 1) {
6937 first = got_tree_entry_get_index(*fte);
6938 first += off;
6939 s->selected = g - first;
6941 } else if (i > g)
6942 tree_scroll_up(s, i - g);
6944 if (g < nlines &&
6945 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
6946 s->selected = g - 1;
6948 return NULL;
6951 static const struct got_error *
6952 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6954 const struct got_error *err = NULL;
6955 struct tog_tree_view_state *s = &view->state.tree;
6956 struct got_tree_entry *te;
6957 int n, nscroll = view->nlines - 3;
6959 if (view->gline)
6960 return tree_goto_line(view, nscroll);
6962 switch (ch) {
6963 case 'i':
6964 s->show_ids = !s->show_ids;
6965 view->count = 0;
6966 break;
6967 case 'L':
6968 view->count = 0;
6969 if (!s->selected_entry)
6970 break;
6971 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6972 break;
6973 case 'R':
6974 view->count = 0;
6975 err = view_request_new(new_view, view, TOG_VIEW_REF);
6976 break;
6977 case 'g':
6978 case KEY_HOME:
6979 s->selected = 0;
6980 view->count = 0;
6981 if (s->tree == s->root)
6982 s->first_displayed_entry =
6983 got_object_tree_get_first_entry(s->tree);
6984 else
6985 s->first_displayed_entry = NULL;
6986 break;
6987 case 'G':
6988 case KEY_END: {
6989 int eos = view->nlines - 3;
6991 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6992 --eos; /* border */
6993 s->selected = 0;
6994 view->count = 0;
6995 te = got_object_tree_get_last_entry(s->tree);
6996 for (n = 0; n < eos; n++) {
6997 if (te == NULL) {
6998 if (s->tree != s->root) {
6999 s->first_displayed_entry = NULL;
7000 n++;
7002 break;
7004 s->first_displayed_entry = te;
7005 te = got_tree_entry_get_prev(s->tree, te);
7007 if (n > 0)
7008 s->selected = n - 1;
7009 break;
7011 case 'k':
7012 case KEY_UP:
7013 case CTRL('p'):
7014 if (s->selected > 0) {
7015 s->selected--;
7016 break;
7018 tree_scroll_up(s, 1);
7019 if (s->selected_entry == NULL ||
7020 (s->tree == s->root && s->selected_entry ==
7021 got_object_tree_get_first_entry(s->tree)))
7022 view->count = 0;
7023 break;
7024 case CTRL('u'):
7025 case 'u':
7026 nscroll /= 2;
7027 /* FALL THROUGH */
7028 case KEY_PPAGE:
7029 case CTRL('b'):
7030 case 'b':
7031 if (s->tree == s->root) {
7032 if (got_object_tree_get_first_entry(s->tree) ==
7033 s->first_displayed_entry)
7034 s->selected -= MIN(s->selected, nscroll);
7035 } else {
7036 if (s->first_displayed_entry == NULL)
7037 s->selected -= MIN(s->selected, nscroll);
7039 tree_scroll_up(s, MAX(0, nscroll));
7040 if (s->selected_entry == NULL ||
7041 (s->tree == s->root && s->selected_entry ==
7042 got_object_tree_get_first_entry(s->tree)))
7043 view->count = 0;
7044 break;
7045 case 'j':
7046 case KEY_DOWN:
7047 case CTRL('n'):
7048 if (s->selected < s->ndisplayed - 1) {
7049 s->selected++;
7050 break;
7052 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7053 == NULL) {
7054 /* can't scroll any further */
7055 view->count = 0;
7056 break;
7058 tree_scroll_down(view, 1);
7059 break;
7060 case CTRL('d'):
7061 case 'd':
7062 nscroll /= 2;
7063 /* FALL THROUGH */
7064 case KEY_NPAGE:
7065 case CTRL('f'):
7066 case 'f':
7067 case ' ':
7068 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7069 == NULL) {
7070 /* can't scroll any further; move cursor down */
7071 if (s->selected < s->ndisplayed - 1)
7072 s->selected += MIN(nscroll,
7073 s->ndisplayed - s->selected - 1);
7074 else
7075 view->count = 0;
7076 break;
7078 tree_scroll_down(view, nscroll);
7079 break;
7080 case KEY_ENTER:
7081 case '\r':
7082 case KEY_BACKSPACE:
7083 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7084 struct tog_parent_tree *parent;
7085 /* user selected '..' */
7086 if (s->tree == s->root) {
7087 view->count = 0;
7088 break;
7090 parent = TAILQ_FIRST(&s->parents);
7091 TAILQ_REMOVE(&s->parents, parent,
7092 entry);
7093 got_object_tree_close(s->tree);
7094 s->tree = parent->tree;
7095 s->first_displayed_entry =
7096 parent->first_displayed_entry;
7097 s->selected_entry =
7098 parent->selected_entry;
7099 s->selected = parent->selected;
7100 if (s->selected > view->nlines - 3) {
7101 err = offset_selection_down(view);
7102 if (err)
7103 break;
7105 free(parent);
7106 } else if (S_ISDIR(got_tree_entry_get_mode(
7107 s->selected_entry))) {
7108 struct got_tree_object *subtree;
7109 view->count = 0;
7110 err = got_object_open_as_tree(&subtree, s->repo,
7111 got_tree_entry_get_id(s->selected_entry));
7112 if (err)
7113 break;
7114 err = tree_view_visit_subtree(s, subtree);
7115 if (err) {
7116 got_object_tree_close(subtree);
7117 break;
7119 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7120 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7121 break;
7122 case KEY_RESIZE:
7123 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7124 s->selected = view->nlines - 4;
7125 view->count = 0;
7126 break;
7127 default:
7128 view->count = 0;
7129 break;
7132 return err;
7135 __dead static void
7136 usage_tree(void)
7138 endwin();
7139 fprintf(stderr,
7140 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7141 getprogname());
7142 exit(1);
7145 static const struct got_error *
7146 cmd_tree(int argc, char *argv[])
7148 const struct got_error *error;
7149 struct got_repository *repo = NULL;
7150 struct got_worktree *worktree = NULL;
7151 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7152 struct got_object_id *commit_id = NULL;
7153 struct got_commit_object *commit = NULL;
7154 const char *commit_id_arg = NULL;
7155 char *label = NULL;
7156 struct got_reference *ref = NULL;
7157 const char *head_ref_name = NULL;
7158 int ch;
7159 struct tog_view *view;
7160 int *pack_fds = NULL;
7162 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7163 switch (ch) {
7164 case 'c':
7165 commit_id_arg = optarg;
7166 break;
7167 case 'r':
7168 repo_path = realpath(optarg, NULL);
7169 if (repo_path == NULL)
7170 return got_error_from_errno2("realpath",
7171 optarg);
7172 break;
7173 default:
7174 usage_tree();
7175 /* NOTREACHED */
7179 argc -= optind;
7180 argv += optind;
7182 if (argc > 1)
7183 usage_tree();
7185 error = got_repo_pack_fds_open(&pack_fds);
7186 if (error != NULL)
7187 goto done;
7189 if (repo_path == NULL) {
7190 cwd = getcwd(NULL, 0);
7191 if (cwd == NULL)
7192 return got_error_from_errno("getcwd");
7193 error = got_worktree_open(&worktree, cwd);
7194 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7195 goto done;
7196 if (worktree)
7197 repo_path =
7198 strdup(got_worktree_get_repo_path(worktree));
7199 else
7200 repo_path = strdup(cwd);
7201 if (repo_path == NULL) {
7202 error = got_error_from_errno("strdup");
7203 goto done;
7207 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7208 if (error != NULL)
7209 goto done;
7211 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7212 repo, worktree);
7213 if (error)
7214 goto done;
7216 init_curses();
7218 error = apply_unveil(got_repo_get_path(repo), NULL);
7219 if (error)
7220 goto done;
7222 error = tog_load_refs(repo, 0);
7223 if (error)
7224 goto done;
7226 if (commit_id_arg == NULL) {
7227 error = got_repo_match_object_id(&commit_id, &label,
7228 worktree ? got_worktree_get_head_ref_name(worktree) :
7229 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7230 if (error)
7231 goto done;
7232 head_ref_name = label;
7233 } else {
7234 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7235 if (error == NULL)
7236 head_ref_name = got_ref_get_name(ref);
7237 else if (error->code != GOT_ERR_NOT_REF)
7238 goto done;
7239 error = got_repo_match_object_id(&commit_id, NULL,
7240 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7241 if (error)
7242 goto done;
7245 error = got_object_open_as_commit(&commit, repo, commit_id);
7246 if (error)
7247 goto done;
7249 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7250 if (view == NULL) {
7251 error = got_error_from_errno("view_open");
7252 goto done;
7254 error = open_tree_view(view, commit_id, head_ref_name, repo);
7255 if (error)
7256 goto done;
7257 if (!got_path_is_root_dir(in_repo_path)) {
7258 error = tree_view_walk_path(&view->state.tree, commit,
7259 in_repo_path);
7260 if (error)
7261 goto done;
7264 if (worktree) {
7265 /* Release work tree lock. */
7266 got_worktree_close(worktree);
7267 worktree = NULL;
7269 error = view_loop(view);
7270 done:
7271 free(repo_path);
7272 free(cwd);
7273 free(commit_id);
7274 free(label);
7275 if (ref)
7276 got_ref_close(ref);
7277 if (repo) {
7278 const struct got_error *close_err = got_repo_close(repo);
7279 if (error == NULL)
7280 error = close_err;
7282 if (pack_fds) {
7283 const struct got_error *pack_err =
7284 got_repo_pack_fds_close(pack_fds);
7285 if (error == NULL)
7286 error = pack_err;
7288 tog_free_refs();
7289 return error;
7292 static const struct got_error *
7293 ref_view_load_refs(struct tog_ref_view_state *s)
7295 struct got_reflist_entry *sre;
7296 struct tog_reflist_entry *re;
7298 s->nrefs = 0;
7299 TAILQ_FOREACH(sre, &tog_refs, entry) {
7300 if (strncmp(got_ref_get_name(sre->ref),
7301 "refs/got/", 9) == 0 &&
7302 strncmp(got_ref_get_name(sre->ref),
7303 "refs/got/backup/", 16) != 0)
7304 continue;
7306 re = malloc(sizeof(*re));
7307 if (re == NULL)
7308 return got_error_from_errno("malloc");
7310 re->ref = got_ref_dup(sre->ref);
7311 if (re->ref == NULL)
7312 return got_error_from_errno("got_ref_dup");
7313 re->idx = s->nrefs++;
7314 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7317 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7318 return NULL;
7321 static void
7322 ref_view_free_refs(struct tog_ref_view_state *s)
7324 struct tog_reflist_entry *re;
7326 while (!TAILQ_EMPTY(&s->refs)) {
7327 re = TAILQ_FIRST(&s->refs);
7328 TAILQ_REMOVE(&s->refs, re, entry);
7329 got_ref_close(re->ref);
7330 free(re);
7334 static const struct got_error *
7335 open_ref_view(struct tog_view *view, struct got_repository *repo)
7337 const struct got_error *err = NULL;
7338 struct tog_ref_view_state *s = &view->state.ref;
7340 s->selected_entry = 0;
7341 s->repo = repo;
7343 TAILQ_INIT(&s->refs);
7344 STAILQ_INIT(&s->colors);
7346 err = ref_view_load_refs(s);
7347 if (err)
7348 return err;
7350 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7351 err = add_color(&s->colors, "^refs/heads/",
7352 TOG_COLOR_REFS_HEADS,
7353 get_color_value("TOG_COLOR_REFS_HEADS"));
7354 if (err)
7355 goto done;
7357 err = add_color(&s->colors, "^refs/tags/",
7358 TOG_COLOR_REFS_TAGS,
7359 get_color_value("TOG_COLOR_REFS_TAGS"));
7360 if (err)
7361 goto done;
7363 err = add_color(&s->colors, "^refs/remotes/",
7364 TOG_COLOR_REFS_REMOTES,
7365 get_color_value("TOG_COLOR_REFS_REMOTES"));
7366 if (err)
7367 goto done;
7369 err = add_color(&s->colors, "^refs/got/backup/",
7370 TOG_COLOR_REFS_BACKUP,
7371 get_color_value("TOG_COLOR_REFS_BACKUP"));
7372 if (err)
7373 goto done;
7376 view->show = show_ref_view;
7377 view->input = input_ref_view;
7378 view->close = close_ref_view;
7379 view->search_start = search_start_ref_view;
7380 view->search_next = search_next_ref_view;
7381 done:
7382 if (err)
7383 free_colors(&s->colors);
7384 return err;
7387 static const struct got_error *
7388 close_ref_view(struct tog_view *view)
7390 struct tog_ref_view_state *s = &view->state.ref;
7392 ref_view_free_refs(s);
7393 free_colors(&s->colors);
7395 return NULL;
7398 static const struct got_error *
7399 resolve_reflist_entry(struct got_object_id **commit_id,
7400 struct tog_reflist_entry *re, struct got_repository *repo)
7402 const struct got_error *err = NULL;
7403 struct got_object_id *obj_id;
7404 struct got_tag_object *tag = NULL;
7405 int obj_type;
7407 *commit_id = NULL;
7409 err = got_ref_resolve(&obj_id, repo, re->ref);
7410 if (err)
7411 return err;
7413 err = got_object_get_type(&obj_type, repo, obj_id);
7414 if (err)
7415 goto done;
7417 switch (obj_type) {
7418 case GOT_OBJ_TYPE_COMMIT:
7419 *commit_id = obj_id;
7420 break;
7421 case GOT_OBJ_TYPE_TAG:
7422 err = got_object_open_as_tag(&tag, repo, obj_id);
7423 if (err)
7424 goto done;
7425 free(obj_id);
7426 err = got_object_get_type(&obj_type, repo,
7427 got_object_tag_get_object_id(tag));
7428 if (err)
7429 goto done;
7430 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7431 err = got_error(GOT_ERR_OBJ_TYPE);
7432 goto done;
7434 *commit_id = got_object_id_dup(
7435 got_object_tag_get_object_id(tag));
7436 if (*commit_id == NULL) {
7437 err = got_error_from_errno("got_object_id_dup");
7438 goto done;
7440 break;
7441 default:
7442 err = got_error(GOT_ERR_OBJ_TYPE);
7443 break;
7446 done:
7447 if (tag)
7448 got_object_tag_close(tag);
7449 if (err) {
7450 free(*commit_id);
7451 *commit_id = NULL;
7453 return err;
7456 static const struct got_error *
7457 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7458 struct tog_reflist_entry *re, struct got_repository *repo)
7460 struct tog_view *log_view;
7461 const struct got_error *err = NULL;
7462 struct got_object_id *commit_id = NULL;
7464 *new_view = NULL;
7466 err = resolve_reflist_entry(&commit_id, re, repo);
7467 if (err) {
7468 if (err->code != GOT_ERR_OBJ_TYPE)
7469 return err;
7470 else
7471 return NULL;
7474 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7475 if (log_view == NULL) {
7476 err = got_error_from_errno("view_open");
7477 goto done;
7480 err = open_log_view(log_view, commit_id, repo,
7481 got_ref_get_name(re->ref), "", 0);
7482 done:
7483 if (err)
7484 view_close(log_view);
7485 else
7486 *new_view = log_view;
7487 free(commit_id);
7488 return err;
7491 static void
7492 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7494 struct tog_reflist_entry *re;
7495 int i = 0;
7497 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7498 return;
7500 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7501 while (i++ < maxscroll) {
7502 if (re == NULL)
7503 break;
7504 s->first_displayed_entry = re;
7505 re = TAILQ_PREV(re, tog_reflist_head, entry);
7509 static const struct got_error *
7510 ref_scroll_down(struct tog_view *view, int maxscroll)
7512 struct tog_ref_view_state *s = &view->state.ref;
7513 struct tog_reflist_entry *next, *last;
7514 int n = 0;
7516 if (s->first_displayed_entry)
7517 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7518 else
7519 next = TAILQ_FIRST(&s->refs);
7521 last = s->last_displayed_entry;
7522 while (next && n++ < maxscroll) {
7523 if (last) {
7524 s->last_displayed_entry = last;
7525 last = TAILQ_NEXT(last, entry);
7527 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7528 s->first_displayed_entry = next;
7529 next = TAILQ_NEXT(next, entry);
7533 return NULL;
7536 static const struct got_error *
7537 search_start_ref_view(struct tog_view *view)
7539 struct tog_ref_view_state *s = &view->state.ref;
7541 s->matched_entry = NULL;
7542 return NULL;
7545 static int
7546 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7548 regmatch_t regmatch;
7550 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7551 0) == 0;
7554 static const struct got_error *
7555 search_next_ref_view(struct tog_view *view)
7557 struct tog_ref_view_state *s = &view->state.ref;
7558 struct tog_reflist_entry *re = NULL;
7560 if (!view->searching) {
7561 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7562 return NULL;
7565 if (s->matched_entry) {
7566 if (view->searching == TOG_SEARCH_FORWARD) {
7567 if (s->selected_entry)
7568 re = TAILQ_NEXT(s->selected_entry, entry);
7569 else
7570 re = TAILQ_PREV(s->selected_entry,
7571 tog_reflist_head, entry);
7572 } else {
7573 if (s->selected_entry == NULL)
7574 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7575 else
7576 re = TAILQ_PREV(s->selected_entry,
7577 tog_reflist_head, entry);
7579 } else {
7580 if (s->selected_entry)
7581 re = s->selected_entry;
7582 else if (view->searching == TOG_SEARCH_FORWARD)
7583 re = TAILQ_FIRST(&s->refs);
7584 else
7585 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7588 while (1) {
7589 if (re == NULL) {
7590 if (s->matched_entry == NULL) {
7591 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7592 return NULL;
7594 if (view->searching == TOG_SEARCH_FORWARD)
7595 re = TAILQ_FIRST(&s->refs);
7596 else
7597 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7600 if (match_reflist_entry(re, &view->regex)) {
7601 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7602 s->matched_entry = re;
7603 break;
7606 if (view->searching == TOG_SEARCH_FORWARD)
7607 re = TAILQ_NEXT(re, entry);
7608 else
7609 re = TAILQ_PREV(re, tog_reflist_head, entry);
7612 if (s->matched_entry) {
7613 s->first_displayed_entry = s->matched_entry;
7614 s->selected = 0;
7617 return NULL;
7620 static const struct got_error *
7621 show_ref_view(struct tog_view *view)
7623 const struct got_error *err = NULL;
7624 struct tog_ref_view_state *s = &view->state.ref;
7625 struct tog_reflist_entry *re;
7626 char *line = NULL;
7627 wchar_t *wline;
7628 struct tog_color *tc;
7629 int width, n;
7630 int limit = view->nlines;
7632 werase(view->window);
7634 s->ndisplayed = 0;
7635 if (view_is_hsplit_top(view))
7636 --limit; /* border */
7638 if (limit == 0)
7639 return NULL;
7641 re = s->first_displayed_entry;
7643 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7644 s->nrefs) == -1)
7645 return got_error_from_errno("asprintf");
7647 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7648 if (err) {
7649 free(line);
7650 return err;
7652 if (view_needs_focus_indication(view))
7653 wstandout(view->window);
7654 waddwstr(view->window, wline);
7655 if (view_needs_focus_indication(view))
7656 wstandend(view->window);
7657 free(wline);
7658 wline = NULL;
7659 free(line);
7660 line = NULL;
7661 if (width < view->ncols - 1)
7662 waddch(view->window, '\n');
7663 if (--limit <= 0)
7664 return NULL;
7666 n = 0;
7667 while (re && limit > 0) {
7668 char *line = NULL;
7669 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7671 if (s->show_date) {
7672 struct got_commit_object *ci;
7673 struct got_tag_object *tag;
7674 struct got_object_id *id;
7675 struct tm tm;
7676 time_t t;
7678 err = got_ref_resolve(&id, s->repo, re->ref);
7679 if (err)
7680 return err;
7681 err = got_object_open_as_tag(&tag, s->repo, id);
7682 if (err) {
7683 if (err->code != GOT_ERR_OBJ_TYPE) {
7684 free(id);
7685 return err;
7687 err = got_object_open_as_commit(&ci, s->repo,
7688 id);
7689 if (err) {
7690 free(id);
7691 return err;
7693 t = got_object_commit_get_committer_time(ci);
7694 got_object_commit_close(ci);
7695 } else {
7696 t = got_object_tag_get_tagger_time(tag);
7697 got_object_tag_close(tag);
7699 free(id);
7700 if (gmtime_r(&t, &tm) == NULL)
7701 return got_error_from_errno("gmtime_r");
7702 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7703 return got_error(GOT_ERR_NO_SPACE);
7705 if (got_ref_is_symbolic(re->ref)) {
7706 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7707 ymd : "", got_ref_get_name(re->ref),
7708 got_ref_get_symref_target(re->ref)) == -1)
7709 return got_error_from_errno("asprintf");
7710 } else if (s->show_ids) {
7711 struct got_object_id *id;
7712 char *id_str;
7713 err = got_ref_resolve(&id, s->repo, re->ref);
7714 if (err)
7715 return err;
7716 err = got_object_id_str(&id_str, id);
7717 if (err) {
7718 free(id);
7719 return err;
7721 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7722 got_ref_get_name(re->ref), id_str) == -1) {
7723 err = got_error_from_errno("asprintf");
7724 free(id);
7725 free(id_str);
7726 return err;
7728 free(id);
7729 free(id_str);
7730 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7731 got_ref_get_name(re->ref)) == -1)
7732 return got_error_from_errno("asprintf");
7734 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7735 0, 0);
7736 if (err) {
7737 free(line);
7738 return err;
7740 if (n == s->selected) {
7741 if (view->focussed)
7742 wstandout(view->window);
7743 s->selected_entry = re;
7745 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7746 if (tc)
7747 wattr_on(view->window,
7748 COLOR_PAIR(tc->colorpair), NULL);
7749 waddwstr(view->window, wline);
7750 if (tc)
7751 wattr_off(view->window,
7752 COLOR_PAIR(tc->colorpair), NULL);
7753 if (width < view->ncols - 1)
7754 waddch(view->window, '\n');
7755 if (n == s->selected && view->focussed)
7756 wstandend(view->window);
7757 free(line);
7758 free(wline);
7759 wline = NULL;
7760 n++;
7761 s->ndisplayed++;
7762 s->last_displayed_entry = re;
7764 limit--;
7765 re = TAILQ_NEXT(re, entry);
7768 view_border(view);
7769 return err;
7772 static const struct got_error *
7773 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7774 struct tog_reflist_entry *re, struct got_repository *repo)
7776 const struct got_error *err = NULL;
7777 struct got_object_id *commit_id = NULL;
7778 struct tog_view *tree_view;
7780 *new_view = NULL;
7782 err = resolve_reflist_entry(&commit_id, re, repo);
7783 if (err) {
7784 if (err->code != GOT_ERR_OBJ_TYPE)
7785 return err;
7786 else
7787 return NULL;
7791 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7792 if (tree_view == NULL) {
7793 err = got_error_from_errno("view_open");
7794 goto done;
7797 err = open_tree_view(tree_view, commit_id,
7798 got_ref_get_name(re->ref), repo);
7799 if (err)
7800 goto done;
7802 *new_view = tree_view;
7803 done:
7804 free(commit_id);
7805 return err;
7808 static const struct got_error *
7809 ref_goto_line(struct tog_view *view, int nlines)
7811 const struct got_error *err = NULL;
7812 struct tog_ref_view_state *s = &view->state.ref;
7813 int g, idx = s->selected_entry->idx;
7815 g = view->gline;
7816 view->gline = 0;
7818 if (g == 0)
7819 g = 1;
7820 else if (g > s->nrefs)
7821 g = s->nrefs;
7823 if (g >= s->first_displayed_entry->idx + 1 &&
7824 g <= s->last_displayed_entry->idx + 1 &&
7825 g - s->first_displayed_entry->idx - 1 < nlines) {
7826 s->selected = g - s->first_displayed_entry->idx - 1;
7827 return NULL;
7830 if (idx + 1 < g) {
7831 err = ref_scroll_down(view, g - idx - 1);
7832 if (err)
7833 return err;
7834 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
7835 s->first_displayed_entry->idx + s->selected < g &&
7836 s->selected < s->ndisplayed - 1)
7837 s->selected = g - s->first_displayed_entry->idx - 1;
7838 } else if (idx + 1 > g)
7839 ref_scroll_up(s, idx - g + 1);
7841 if (g < nlines && s->first_displayed_entry->idx == 0)
7842 s->selected = g - 1;
7844 return NULL;
7848 static const struct got_error *
7849 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7851 const struct got_error *err = NULL;
7852 struct tog_ref_view_state *s = &view->state.ref;
7853 struct tog_reflist_entry *re;
7854 int n, nscroll = view->nlines - 1;
7856 if (view->gline)
7857 return ref_goto_line(view, nscroll);
7859 switch (ch) {
7860 case 'i':
7861 s->show_ids = !s->show_ids;
7862 view->count = 0;
7863 break;
7864 case 'm':
7865 s->show_date = !s->show_date;
7866 view->count = 0;
7867 break;
7868 case 'o':
7869 s->sort_by_date = !s->sort_by_date;
7870 view->count = 0;
7871 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7872 got_ref_cmp_by_commit_timestamp_descending :
7873 tog_ref_cmp_by_name, s->repo);
7874 if (err)
7875 break;
7876 got_reflist_object_id_map_free(tog_refs_idmap);
7877 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7878 &tog_refs, s->repo);
7879 if (err)
7880 break;
7881 ref_view_free_refs(s);
7882 err = ref_view_load_refs(s);
7883 break;
7884 case KEY_ENTER:
7885 case '\r':
7886 view->count = 0;
7887 if (!s->selected_entry)
7888 break;
7889 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7890 break;
7891 case 'T':
7892 view->count = 0;
7893 if (!s->selected_entry)
7894 break;
7895 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7896 break;
7897 case 'g':
7898 case KEY_HOME:
7899 s->selected = 0;
7900 view->count = 0;
7901 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7902 break;
7903 case 'G':
7904 case KEY_END: {
7905 int eos = view->nlines - 1;
7907 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7908 --eos; /* border */
7909 s->selected = 0;
7910 view->count = 0;
7911 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7912 for (n = 0; n < eos; n++) {
7913 if (re == NULL)
7914 break;
7915 s->first_displayed_entry = re;
7916 re = TAILQ_PREV(re, tog_reflist_head, entry);
7918 if (n > 0)
7919 s->selected = n - 1;
7920 break;
7922 case 'k':
7923 case KEY_UP:
7924 case CTRL('p'):
7925 if (s->selected > 0) {
7926 s->selected--;
7927 break;
7929 ref_scroll_up(s, 1);
7930 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7931 view->count = 0;
7932 break;
7933 case CTRL('u'):
7934 case 'u':
7935 nscroll /= 2;
7936 /* FALL THROUGH */
7937 case KEY_PPAGE:
7938 case CTRL('b'):
7939 case 'b':
7940 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7941 s->selected -= MIN(nscroll, s->selected);
7942 ref_scroll_up(s, MAX(0, nscroll));
7943 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7944 view->count = 0;
7945 break;
7946 case 'j':
7947 case KEY_DOWN:
7948 case CTRL('n'):
7949 if (s->selected < s->ndisplayed - 1) {
7950 s->selected++;
7951 break;
7953 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7954 /* can't scroll any further */
7955 view->count = 0;
7956 break;
7958 ref_scroll_down(view, 1);
7959 break;
7960 case CTRL('d'):
7961 case 'd':
7962 nscroll /= 2;
7963 /* FALL THROUGH */
7964 case KEY_NPAGE:
7965 case CTRL('f'):
7966 case 'f':
7967 case ' ':
7968 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7969 /* can't scroll any further; move cursor down */
7970 if (s->selected < s->ndisplayed - 1)
7971 s->selected += MIN(nscroll,
7972 s->ndisplayed - s->selected - 1);
7973 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7974 s->selected += s->ndisplayed - s->selected - 1;
7975 view->count = 0;
7976 break;
7978 ref_scroll_down(view, nscroll);
7979 break;
7980 case CTRL('l'):
7981 view->count = 0;
7982 tog_free_refs();
7983 err = tog_load_refs(s->repo, s->sort_by_date);
7984 if (err)
7985 break;
7986 ref_view_free_refs(s);
7987 err = ref_view_load_refs(s);
7988 break;
7989 case KEY_RESIZE:
7990 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7991 s->selected = view->nlines - 2;
7992 break;
7993 default:
7994 view->count = 0;
7995 break;
7998 return err;
8001 __dead static void
8002 usage_ref(void)
8004 endwin();
8005 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8006 getprogname());
8007 exit(1);
8010 static const struct got_error *
8011 cmd_ref(int argc, char *argv[])
8013 const struct got_error *error;
8014 struct got_repository *repo = NULL;
8015 struct got_worktree *worktree = NULL;
8016 char *cwd = NULL, *repo_path = NULL;
8017 int ch;
8018 struct tog_view *view;
8019 int *pack_fds = NULL;
8021 while ((ch = getopt(argc, argv, "r:")) != -1) {
8022 switch (ch) {
8023 case 'r':
8024 repo_path = realpath(optarg, NULL);
8025 if (repo_path == NULL)
8026 return got_error_from_errno2("realpath",
8027 optarg);
8028 break;
8029 default:
8030 usage_ref();
8031 /* NOTREACHED */
8035 argc -= optind;
8036 argv += optind;
8038 if (argc > 1)
8039 usage_ref();
8041 error = got_repo_pack_fds_open(&pack_fds);
8042 if (error != NULL)
8043 goto done;
8045 if (repo_path == NULL) {
8046 cwd = getcwd(NULL, 0);
8047 if (cwd == NULL)
8048 return got_error_from_errno("getcwd");
8049 error = got_worktree_open(&worktree, cwd);
8050 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8051 goto done;
8052 if (worktree)
8053 repo_path =
8054 strdup(got_worktree_get_repo_path(worktree));
8055 else
8056 repo_path = strdup(cwd);
8057 if (repo_path == NULL) {
8058 error = got_error_from_errno("strdup");
8059 goto done;
8063 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8064 if (error != NULL)
8065 goto done;
8067 init_curses();
8069 error = apply_unveil(got_repo_get_path(repo), NULL);
8070 if (error)
8071 goto done;
8073 error = tog_load_refs(repo, 0);
8074 if (error)
8075 goto done;
8077 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8078 if (view == NULL) {
8079 error = got_error_from_errno("view_open");
8080 goto done;
8083 error = open_ref_view(view, repo);
8084 if (error)
8085 goto done;
8087 if (worktree) {
8088 /* Release work tree lock. */
8089 got_worktree_close(worktree);
8090 worktree = NULL;
8092 error = view_loop(view);
8093 done:
8094 free(repo_path);
8095 free(cwd);
8096 if (repo) {
8097 const struct got_error *close_err = got_repo_close(repo);
8098 if (close_err)
8099 error = close_err;
8101 if (pack_fds) {
8102 const struct got_error *pack_err =
8103 got_repo_pack_fds_close(pack_fds);
8104 if (error == NULL)
8105 error = pack_err;
8107 tog_free_refs();
8108 return error;
8111 static const struct got_error *
8112 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8113 enum tog_view_type request, int y, int x)
8115 const struct got_error *err = NULL;
8117 *new_view = NULL;
8119 switch (request) {
8120 case TOG_VIEW_DIFF:
8121 if (view->type == TOG_VIEW_LOG) {
8122 struct tog_log_view_state *s = &view->state.log;
8124 err = open_diff_view_for_commit(new_view, y, x,
8125 s->selected_entry->commit, s->selected_entry->id,
8126 view, s->repo);
8127 } else
8128 return got_error_msg(GOT_ERR_NOT_IMPL,
8129 "parent/child view pair not supported");
8130 break;
8131 case TOG_VIEW_BLAME:
8132 if (view->type == TOG_VIEW_TREE) {
8133 struct tog_tree_view_state *s = &view->state.tree;
8135 err = blame_tree_entry(new_view, y, x,
8136 s->selected_entry, &s->parents, s->commit_id,
8137 s->repo);
8138 } else
8139 return got_error_msg(GOT_ERR_NOT_IMPL,
8140 "parent/child view pair not supported");
8141 break;
8142 case TOG_VIEW_LOG:
8143 if (view->type == TOG_VIEW_BLAME)
8144 err = log_annotated_line(new_view, y, x,
8145 view->state.blame.repo, view->state.blame.id_to_log);
8146 else if (view->type == TOG_VIEW_TREE)
8147 err = log_selected_tree_entry(new_view, y, x,
8148 &view->state.tree);
8149 else if (view->type == TOG_VIEW_REF)
8150 err = log_ref_entry(new_view, y, x,
8151 view->state.ref.selected_entry,
8152 view->state.ref.repo);
8153 else
8154 return got_error_msg(GOT_ERR_NOT_IMPL,
8155 "parent/child view pair not supported");
8156 break;
8157 case TOG_VIEW_TREE:
8158 if (view->type == TOG_VIEW_LOG)
8159 err = browse_commit_tree(new_view, y, x,
8160 view->state.log.selected_entry,
8161 view->state.log.in_repo_path,
8162 view->state.log.head_ref_name,
8163 view->state.log.repo);
8164 else if (view->type == TOG_VIEW_REF)
8165 err = browse_ref_tree(new_view, y, x,
8166 view->state.ref.selected_entry,
8167 view->state.ref.repo);
8168 else
8169 return got_error_msg(GOT_ERR_NOT_IMPL,
8170 "parent/child view pair not supported");
8171 break;
8172 case TOG_VIEW_REF:
8173 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8174 if (*new_view == NULL)
8175 return got_error_from_errno("view_open");
8176 if (view->type == TOG_VIEW_LOG)
8177 err = open_ref_view(*new_view, view->state.log.repo);
8178 else if (view->type == TOG_VIEW_TREE)
8179 err = open_ref_view(*new_view, view->state.tree.repo);
8180 else
8181 err = got_error_msg(GOT_ERR_NOT_IMPL,
8182 "parent/child view pair not supported");
8183 if (err)
8184 view_close(*new_view);
8185 break;
8186 default:
8187 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8190 return err;
8194 * If view was scrolled down to move the selected line into view when opening a
8195 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8197 static void
8198 offset_selection_up(struct tog_view *view)
8200 switch (view->type) {
8201 case TOG_VIEW_BLAME: {
8202 struct tog_blame_view_state *s = &view->state.blame;
8203 if (s->first_displayed_line == 1) {
8204 s->selected_line = MAX(s->selected_line - view->offset,
8205 1);
8206 break;
8208 if (s->first_displayed_line > view->offset)
8209 s->first_displayed_line -= view->offset;
8210 else
8211 s->first_displayed_line = 1;
8212 s->selected_line += view->offset;
8213 break;
8215 case TOG_VIEW_LOG:
8216 log_scroll_up(&view->state.log, view->offset);
8217 view->state.log.selected += view->offset;
8218 break;
8219 case TOG_VIEW_REF:
8220 ref_scroll_up(&view->state.ref, view->offset);
8221 view->state.ref.selected += view->offset;
8222 break;
8223 case TOG_VIEW_TREE:
8224 tree_scroll_up(&view->state.tree, view->offset);
8225 view->state.tree.selected += view->offset;
8226 break;
8227 default:
8228 break;
8231 view->offset = 0;
8235 * If the selected line is in the section of screen covered by the bottom split,
8236 * scroll down offset lines to move it into view and index its new position.
8238 static const struct got_error *
8239 offset_selection_down(struct tog_view *view)
8241 const struct got_error *err = NULL;
8242 const struct got_error *(*scrolld)(struct tog_view *, int);
8243 int *selected = NULL;
8244 int header, offset;
8246 switch (view->type) {
8247 case TOG_VIEW_BLAME: {
8248 struct tog_blame_view_state *s = &view->state.blame;
8249 header = 3;
8250 scrolld = NULL;
8251 if (s->selected_line > view->nlines - header) {
8252 offset = abs(view->nlines - s->selected_line - header);
8253 s->first_displayed_line += offset;
8254 s->selected_line -= offset;
8255 view->offset = offset;
8257 break;
8259 case TOG_VIEW_LOG: {
8260 struct tog_log_view_state *s = &view->state.log;
8261 scrolld = &log_scroll_down;
8262 header = view_is_parent_view(view) ? 3 : 2;
8263 selected = &s->selected;
8264 break;
8266 case TOG_VIEW_REF: {
8267 struct tog_ref_view_state *s = &view->state.ref;
8268 scrolld = &ref_scroll_down;
8269 header = 3;
8270 selected = &s->selected;
8271 break;
8273 case TOG_VIEW_TREE: {
8274 struct tog_tree_view_state *s = &view->state.tree;
8275 scrolld = &tree_scroll_down;
8276 header = 5;
8277 selected = &s->selected;
8278 break;
8280 default:
8281 selected = NULL;
8282 scrolld = NULL;
8283 header = 0;
8284 break;
8287 if (selected && *selected > view->nlines - header) {
8288 offset = abs(view->nlines - *selected - header);
8289 view->offset = offset;
8290 if (scrolld && offset) {
8291 err = scrolld(view, offset);
8292 *selected -= offset;
8296 return err;
8299 static void
8300 list_commands(FILE *fp)
8302 size_t i;
8304 fprintf(fp, "commands:");
8305 for (i = 0; i < nitems(tog_commands); i++) {
8306 const struct tog_cmd *cmd = &tog_commands[i];
8307 fprintf(fp, " %s", cmd->name);
8309 fputc('\n', fp);
8312 __dead static void
8313 usage(int hflag, int status)
8315 FILE *fp = (status == 0) ? stdout : stderr;
8317 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8318 getprogname());
8319 if (hflag) {
8320 fprintf(fp, "lazy usage: %s path\n", getprogname());
8321 list_commands(fp);
8323 exit(status);
8326 static char **
8327 make_argv(int argc, ...)
8329 va_list ap;
8330 char **argv;
8331 int i;
8333 va_start(ap, argc);
8335 argv = calloc(argc, sizeof(char *));
8336 if (argv == NULL)
8337 err(1, "calloc");
8338 for (i = 0; i < argc; i++) {
8339 argv[i] = strdup(va_arg(ap, char *));
8340 if (argv[i] == NULL)
8341 err(1, "strdup");
8344 va_end(ap);
8345 return argv;
8349 * Try to convert 'tog path' into a 'tog log path' command.
8350 * The user could simply have mistyped the command rather than knowingly
8351 * provided a path. So check whether argv[0] can in fact be resolved
8352 * to a path in the HEAD commit and print a special error if not.
8353 * This hack is for mpi@ <3
8355 static const struct got_error *
8356 tog_log_with_path(int argc, char *argv[])
8358 const struct got_error *error = NULL, *close_err;
8359 const struct tog_cmd *cmd = NULL;
8360 struct got_repository *repo = NULL;
8361 struct got_worktree *worktree = NULL;
8362 struct got_object_id *commit_id = NULL, *id = NULL;
8363 struct got_commit_object *commit = NULL;
8364 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8365 char *commit_id_str = NULL, **cmd_argv = NULL;
8366 int *pack_fds = NULL;
8368 cwd = getcwd(NULL, 0);
8369 if (cwd == NULL)
8370 return got_error_from_errno("getcwd");
8372 error = got_repo_pack_fds_open(&pack_fds);
8373 if (error != NULL)
8374 goto done;
8376 error = got_worktree_open(&worktree, cwd);
8377 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8378 goto done;
8380 if (worktree)
8381 repo_path = strdup(got_worktree_get_repo_path(worktree));
8382 else
8383 repo_path = strdup(cwd);
8384 if (repo_path == NULL) {
8385 error = got_error_from_errno("strdup");
8386 goto done;
8389 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8390 if (error != NULL)
8391 goto done;
8393 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8394 repo, worktree);
8395 if (error)
8396 goto done;
8398 error = tog_load_refs(repo, 0);
8399 if (error)
8400 goto done;
8401 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8402 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8403 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8404 if (error)
8405 goto done;
8407 if (worktree) {
8408 got_worktree_close(worktree);
8409 worktree = NULL;
8412 error = got_object_open_as_commit(&commit, repo, commit_id);
8413 if (error)
8414 goto done;
8416 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8417 if (error) {
8418 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8419 goto done;
8420 fprintf(stderr, "%s: '%s' is no known command or path\n",
8421 getprogname(), argv[0]);
8422 usage(1, 1);
8423 /* not reached */
8426 error = got_object_id_str(&commit_id_str, commit_id);
8427 if (error)
8428 goto done;
8430 cmd = &tog_commands[0]; /* log */
8431 argc = 4;
8432 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8433 error = cmd->cmd_main(argc, cmd_argv);
8434 done:
8435 if (repo) {
8436 close_err = got_repo_close(repo);
8437 if (error == NULL)
8438 error = close_err;
8440 if (commit)
8441 got_object_commit_close(commit);
8442 if (worktree)
8443 got_worktree_close(worktree);
8444 if (pack_fds) {
8445 const struct got_error *pack_err =
8446 got_repo_pack_fds_close(pack_fds);
8447 if (error == NULL)
8448 error = pack_err;
8450 free(id);
8451 free(commit_id_str);
8452 free(commit_id);
8453 free(cwd);
8454 free(repo_path);
8455 free(in_repo_path);
8456 if (cmd_argv) {
8457 int i;
8458 for (i = 0; i < argc; i++)
8459 free(cmd_argv[i]);
8460 free(cmd_argv);
8462 tog_free_refs();
8463 return error;
8466 int
8467 main(int argc, char *argv[])
8469 const struct got_error *error = NULL;
8470 const struct tog_cmd *cmd = NULL;
8471 int ch, hflag = 0, Vflag = 0;
8472 char **cmd_argv = NULL;
8473 static const struct option longopts[] = {
8474 { "version", no_argument, NULL, 'V' },
8475 { NULL, 0, NULL, 0}
8477 char *diff_algo_str = NULL;
8479 setlocale(LC_CTYPE, "");
8481 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8482 switch (ch) {
8483 case 'h':
8484 hflag = 1;
8485 break;
8486 case 'V':
8487 Vflag = 1;
8488 break;
8489 default:
8490 usage(hflag, 1);
8491 /* NOTREACHED */
8495 argc -= optind;
8496 argv += optind;
8497 optind = 1;
8498 optreset = 1;
8500 if (Vflag) {
8501 got_version_print_str();
8502 return 0;
8505 #ifndef PROFILE
8506 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8507 NULL) == -1)
8508 err(1, "pledge");
8509 #endif
8511 if (argc == 0) {
8512 if (hflag)
8513 usage(hflag, 0);
8514 /* Build an argument vector which runs a default command. */
8515 cmd = &tog_commands[0];
8516 argc = 1;
8517 cmd_argv = make_argv(argc, cmd->name);
8518 } else {
8519 size_t i;
8521 /* Did the user specify a command? */
8522 for (i = 0; i < nitems(tog_commands); i++) {
8523 if (strncmp(tog_commands[i].name, argv[0],
8524 strlen(argv[0])) == 0) {
8525 cmd = &tog_commands[i];
8526 break;
8531 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8532 if (diff_algo_str) {
8533 if (strcasecmp(diff_algo_str, "patience") == 0)
8534 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8535 if (strcasecmp(diff_algo_str, "myers") == 0)
8536 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8539 if (cmd == NULL) {
8540 if (argc != 1)
8541 usage(0, 1);
8542 /* No command specified; try log with a path */
8543 error = tog_log_with_path(argc, argv);
8544 } else {
8545 if (hflag)
8546 cmd->cmd_usage();
8547 else
8548 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8551 endwin();
8552 putchar('\n');
8553 if (cmd_argv) {
8554 int i;
8555 for (i = 0; i < argc; i++)
8556 free(cmd_argv[i]);
8557 free(cmd_argv);
8560 if (error && error->code != GOT_ERR_CANCELLED)
8561 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8562 return 0;