Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 };
108 enum tog_view_mode {
109 TOG_VIEW_SPLIT_NONE,
110 TOG_VIEW_SPLIT_VERT,
111 TOG_VIEW_SPLIT_HRZN
112 };
114 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
116 #define TOG_EOF_STRING "(END)"
118 struct commit_queue_entry {
119 TAILQ_ENTRY(commit_queue_entry) entry;
120 struct got_object_id *id;
121 struct got_commit_object *commit;
122 int idx;
123 };
124 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
125 struct commit_queue {
126 int ncommits;
127 struct commit_queue_head head;
128 };
130 struct tog_color {
131 STAILQ_ENTRY(tog_color) entry;
132 regex_t regex;
133 short colorpair;
134 };
135 STAILQ_HEAD(tog_colors, tog_color);
137 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
138 static struct got_reflist_object_id_map *tog_refs_idmap;
139 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
141 static const struct got_error *
142 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
143 struct got_reference* re2)
145 const char *name1 = got_ref_get_name(re1);
146 const char *name2 = got_ref_get_name(re2);
147 int isbackup1, isbackup2;
149 /* Sort backup refs towards the bottom of the list. */
150 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
151 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
152 if (!isbackup1 && isbackup2) {
153 *cmp = -1;
154 return NULL;
155 } else if (isbackup1 && !isbackup2) {
156 *cmp = 1;
157 return NULL;
160 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
161 return NULL;
164 static const struct got_error *
165 tog_load_refs(struct got_repository *repo, int sort_by_date)
167 const struct got_error *err;
169 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
170 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
171 repo);
172 if (err)
173 return err;
175 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
176 repo);
179 static void
180 tog_free_refs(void)
182 if (tog_refs_idmap) {
183 got_reflist_object_id_map_free(tog_refs_idmap);
184 tog_refs_idmap = NULL;
186 got_ref_list_free(&tog_refs);
189 static const struct got_error *
190 add_color(struct tog_colors *colors, const char *pattern,
191 int idx, short color)
193 const struct got_error *err = NULL;
194 struct tog_color *tc;
195 int regerr = 0;
197 if (idx < 1 || idx > COLOR_PAIRS - 1)
198 return NULL;
200 init_pair(idx, color, -1);
202 tc = calloc(1, sizeof(*tc));
203 if (tc == NULL)
204 return got_error_from_errno("calloc");
205 regerr = regcomp(&tc->regex, pattern,
206 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
207 if (regerr) {
208 static char regerr_msg[512];
209 static char err_msg[512];
210 regerror(regerr, &tc->regex, regerr_msg,
211 sizeof(regerr_msg));
212 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
213 regerr_msg);
214 err = got_error_msg(GOT_ERR_REGEX, err_msg);
215 free(tc);
216 return err;
218 tc->colorpair = idx;
219 STAILQ_INSERT_HEAD(colors, tc, entry);
220 return NULL;
223 static void
224 free_colors(struct tog_colors *colors)
226 struct tog_color *tc;
228 while (!STAILQ_EMPTY(colors)) {
229 tc = STAILQ_FIRST(colors);
230 STAILQ_REMOVE_HEAD(colors, entry);
231 regfree(&tc->regex);
232 free(tc);
236 static struct tog_color *
237 get_color(struct tog_colors *colors, int colorpair)
239 struct tog_color *tc = NULL;
241 STAILQ_FOREACH(tc, colors, entry) {
242 if (tc->colorpair == colorpair)
243 return tc;
246 return NULL;
249 static int
250 default_color_value(const char *envvar)
252 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
253 return COLOR_MAGENTA;
254 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
255 return COLOR_CYAN;
256 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
257 return COLOR_YELLOW;
258 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
259 return COLOR_GREEN;
260 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
261 return COLOR_MAGENTA;
262 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
263 return COLOR_MAGENTA;
264 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
265 return COLOR_CYAN;
266 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
267 return COLOR_GREEN;
268 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
269 return COLOR_GREEN;
270 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
271 return COLOR_CYAN;
272 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
273 return COLOR_YELLOW;
274 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
275 return COLOR_GREEN;
276 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
279 return COLOR_YELLOW;
280 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
281 return COLOR_CYAN;
283 return -1;
286 static int
287 get_color_value(const char *envvar)
289 const char *val = getenv(envvar);
291 if (val == NULL)
292 return default_color_value(envvar);
294 if (strcasecmp(val, "black") == 0)
295 return COLOR_BLACK;
296 if (strcasecmp(val, "red") == 0)
297 return COLOR_RED;
298 if (strcasecmp(val, "green") == 0)
299 return COLOR_GREEN;
300 if (strcasecmp(val, "yellow") == 0)
301 return COLOR_YELLOW;
302 if (strcasecmp(val, "blue") == 0)
303 return COLOR_BLUE;
304 if (strcasecmp(val, "magenta") == 0)
305 return COLOR_MAGENTA;
306 if (strcasecmp(val, "cyan") == 0)
307 return COLOR_CYAN;
308 if (strcasecmp(val, "white") == 0)
309 return COLOR_WHITE;
310 if (strcasecmp(val, "default") == 0)
311 return -1;
313 return default_color_value(envvar);
316 struct tog_diff_view_state {
317 struct got_object_id *id1, *id2;
318 const char *label1, *label2;
319 FILE *f, *f1, *f2;
320 int fd1, fd2;
321 int lineno;
322 int first_displayed_line;
323 int last_displayed_line;
324 int eof;
325 int diff_context;
326 int ignore_whitespace;
327 int force_text_diff;
328 struct got_repository *repo;
329 struct tog_colors colors;
330 struct got_diff_line *lines;
331 size_t nlines;
332 int matched_line;
333 int selected_line;
335 /* passed from log or blame view; may be NULL */
336 struct tog_view *parent_view;
337 };
339 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
340 static volatile sig_atomic_t tog_thread_error;
342 struct tog_log_thread_args {
343 pthread_cond_t need_commits;
344 pthread_cond_t commit_loaded;
345 int commits_needed;
346 int load_all;
347 struct got_commit_graph *graph;
348 struct commit_queue *commits;
349 const char *in_repo_path;
350 struct got_object_id *start_id;
351 struct got_repository *repo;
352 int *pack_fds;
353 int log_complete;
354 sig_atomic_t *quit;
355 struct commit_queue_entry **first_displayed_entry;
356 struct commit_queue_entry **selected_entry;
357 int *searching;
358 int *search_next_done;
359 regex_t *regex;
360 };
362 struct tog_log_view_state {
363 struct commit_queue commits;
364 struct commit_queue_entry *first_displayed_entry;
365 struct commit_queue_entry *last_displayed_entry;
366 struct commit_queue_entry *selected_entry;
367 int selected;
368 char *in_repo_path;
369 char *head_ref_name;
370 int log_branches;
371 struct got_repository *repo;
372 struct got_object_id *start_id;
373 sig_atomic_t quit;
374 pthread_t thread;
375 struct tog_log_thread_args thread_args;
376 struct commit_queue_entry *matched_entry;
377 struct commit_queue_entry *search_entry;
378 struct tog_colors colors;
379 int use_committer;
380 };
382 #define TOG_COLOR_DIFF_MINUS 1
383 #define TOG_COLOR_DIFF_PLUS 2
384 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
385 #define TOG_COLOR_DIFF_META 4
386 #define TOG_COLOR_TREE_SUBMODULE 5
387 #define TOG_COLOR_TREE_SYMLINK 6
388 #define TOG_COLOR_TREE_DIRECTORY 7
389 #define TOG_COLOR_TREE_EXECUTABLE 8
390 #define TOG_COLOR_COMMIT 9
391 #define TOG_COLOR_AUTHOR 10
392 #define TOG_COLOR_DATE 11
393 #define TOG_COLOR_REFS_HEADS 12
394 #define TOG_COLOR_REFS_TAGS 13
395 #define TOG_COLOR_REFS_REMOTES 14
396 #define TOG_COLOR_REFS_BACKUP 15
398 struct tog_blame_cb_args {
399 struct tog_blame_line *lines; /* one per line */
400 int nlines;
402 struct tog_view *view;
403 struct got_object_id *commit_id;
404 int *quit;
405 };
407 struct tog_blame_thread_args {
408 const char *path;
409 struct got_repository *repo;
410 struct tog_blame_cb_args *cb_args;
411 int *complete;
412 got_cancel_cb cancel_cb;
413 void *cancel_arg;
414 };
416 struct tog_blame {
417 FILE *f;
418 off_t filesize;
419 struct tog_blame_line *lines;
420 int nlines;
421 off_t *line_offsets;
422 pthread_t thread;
423 struct tog_blame_thread_args thread_args;
424 struct tog_blame_cb_args cb_args;
425 const char *path;
426 int *pack_fds;
427 };
429 struct tog_blame_view_state {
430 int first_displayed_line;
431 int last_displayed_line;
432 int selected_line;
433 int last_diffed_line;
434 int blame_complete;
435 int eof;
436 int done;
437 struct got_object_id_queue blamed_commits;
438 struct got_object_qid *blamed_commit;
439 char *path;
440 struct got_repository *repo;
441 struct got_object_id *commit_id;
442 struct got_object_id *id_to_log;
443 struct tog_blame blame;
444 int matched_line;
445 struct tog_colors colors;
446 };
448 struct tog_parent_tree {
449 TAILQ_ENTRY(tog_parent_tree) entry;
450 struct got_tree_object *tree;
451 struct got_tree_entry *first_displayed_entry;
452 struct got_tree_entry *selected_entry;
453 int selected;
454 };
456 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
458 struct tog_tree_view_state {
459 char *tree_label;
460 struct got_object_id *commit_id;/* commit which this tree belongs to */
461 struct got_tree_object *root; /* the commit's root tree entry */
462 struct got_tree_object *tree; /* currently displayed (sub-)tree */
463 struct got_tree_entry *first_displayed_entry;
464 struct got_tree_entry *last_displayed_entry;
465 struct got_tree_entry *selected_entry;
466 int ndisplayed, selected, show_ids;
467 struct tog_parent_trees parents; /* parent trees of current sub-tree */
468 char *head_ref_name;
469 struct got_repository *repo;
470 struct got_tree_entry *matched_entry;
471 struct tog_colors colors;
472 };
474 struct tog_reflist_entry {
475 TAILQ_ENTRY(tog_reflist_entry) entry;
476 struct got_reference *ref;
477 int idx;
478 };
480 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
482 struct tog_ref_view_state {
483 struct tog_reflist_head refs;
484 struct tog_reflist_entry *first_displayed_entry;
485 struct tog_reflist_entry *last_displayed_entry;
486 struct tog_reflist_entry *selected_entry;
487 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
488 struct got_repository *repo;
489 struct tog_reflist_entry *matched_entry;
490 struct tog_colors colors;
491 };
493 /*
494 * We implement two types of views: parent views and child views.
496 * The 'Tab' key switches focus between a parent view and its child view.
497 * Child views are shown side-by-side to their parent view, provided
498 * there is enough screen estate.
500 * When a new view is opened from within a parent view, this new view
501 * becomes a child view of the parent view, replacing any existing child.
503 * When a new view is opened from within a child view, this new view
504 * becomes a parent view which will obscure the views below until the
505 * user quits the new parent view by typing 'q'.
507 * This list of views contains parent views only.
508 * Child views are only pointed to by their parent view.
509 */
510 TAILQ_HEAD(tog_view_list_head, tog_view);
512 struct tog_view {
513 TAILQ_ENTRY(tog_view) entry;
514 WINDOW *window;
515 PANEL *panel;
516 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
517 int resized_y, resized_x; /* begin_y/x based on user resizing */
518 int maxx, x; /* max column and current start column */
519 int lines, cols; /* copies of LINES and COLS */
520 int nscrolled, offset; /* lines scrolled and hsplit line offset */
521 int gline, hiline; /* navigate to and highlight this nG line */
522 int ch, count; /* current keymap and count prefix */
523 int resized; /* set when in a resize event */
524 int focussed; /* Only set on one parent or child view at a time. */
525 int dying;
526 struct tog_view *parent;
527 struct tog_view *child;
529 /*
530 * This flag is initially set on parent views when a new child view
531 * is created. It gets toggled when the 'Tab' key switches focus
532 * between parent and child.
533 * The flag indicates whether focus should be passed on to our child
534 * view if this parent view gets picked for focus after another parent
535 * view was closed. This prevents child views from losing focus in such
536 * situations.
537 */
538 int focus_child;
540 enum tog_view_mode mode;
541 /* type-specific state */
542 enum tog_view_type type;
543 union {
544 struct tog_diff_view_state diff;
545 struct tog_log_view_state log;
546 struct tog_blame_view_state blame;
547 struct tog_tree_view_state tree;
548 struct tog_ref_view_state ref;
549 } state;
551 const struct got_error *(*show)(struct tog_view *);
552 const struct got_error *(*input)(struct tog_view **,
553 struct tog_view *, int);
554 const struct got_error *(*reset)(struct tog_view *);
555 const struct got_error *(*resize)(struct tog_view *, int);
556 const struct got_error *(*close)(struct tog_view *);
558 const struct got_error *(*search_start)(struct tog_view *);
559 const struct got_error *(*search_next)(struct tog_view *);
560 int search_started;
561 int searching;
562 #define TOG_SEARCH_FORWARD 1
563 #define TOG_SEARCH_BACKWARD 2
564 int search_next_done;
565 #define TOG_SEARCH_HAVE_MORE 1
566 #define TOG_SEARCH_NO_MORE 2
567 #define TOG_SEARCH_HAVE_NONE 3
568 regex_t regex;
569 regmatch_t regmatch;
570 };
572 static const struct got_error *open_diff_view(struct tog_view *,
573 struct got_object_id *, struct got_object_id *,
574 const char *, const char *, int, int, int, struct tog_view *,
575 struct got_repository *);
576 static const struct got_error *show_diff_view(struct tog_view *);
577 static const struct got_error *input_diff_view(struct tog_view **,
578 struct tog_view *, int);
579 static const struct got_error *reset_diff_view(struct tog_view *);
580 static const struct got_error* close_diff_view(struct tog_view *);
581 static const struct got_error *search_start_diff_view(struct tog_view *);
582 static const struct got_error *search_next_diff_view(struct tog_view *);
584 static const struct got_error *open_log_view(struct tog_view *,
585 struct got_object_id *, struct got_repository *,
586 const char *, const char *, int);
587 static const struct got_error * show_log_view(struct tog_view *);
588 static const struct got_error *input_log_view(struct tog_view **,
589 struct tog_view *, int);
590 static const struct got_error *resize_log_view(struct tog_view *, int);
591 static const struct got_error *close_log_view(struct tog_view *);
592 static const struct got_error *search_start_log_view(struct tog_view *);
593 static const struct got_error *search_next_log_view(struct tog_view *);
595 static const struct got_error *open_blame_view(struct tog_view *, char *,
596 struct got_object_id *, struct got_repository *);
597 static const struct got_error *show_blame_view(struct tog_view *);
598 static const struct got_error *input_blame_view(struct tog_view **,
599 struct tog_view *, int);
600 static const struct got_error *reset_blame_view(struct tog_view *);
601 static const struct got_error *close_blame_view(struct tog_view *);
602 static const struct got_error *search_start_blame_view(struct tog_view *);
603 static const struct got_error *search_next_blame_view(struct tog_view *);
605 static const struct got_error *open_tree_view(struct tog_view *,
606 struct got_object_id *, const char *, struct got_repository *);
607 static const struct got_error *show_tree_view(struct tog_view *);
608 static const struct got_error *input_tree_view(struct tog_view **,
609 struct tog_view *, int);
610 static const struct got_error *close_tree_view(struct tog_view *);
611 static const struct got_error *search_start_tree_view(struct tog_view *);
612 static const struct got_error *search_next_tree_view(struct tog_view *);
614 static const struct got_error *open_ref_view(struct tog_view *,
615 struct got_repository *);
616 static const struct got_error *show_ref_view(struct tog_view *);
617 static const struct got_error *input_ref_view(struct tog_view **,
618 struct tog_view *, int);
619 static const struct got_error *close_ref_view(struct tog_view *);
620 static const struct got_error *search_start_ref_view(struct tog_view *);
621 static const struct got_error *search_next_ref_view(struct tog_view *);
623 static volatile sig_atomic_t tog_sigwinch_received;
624 static volatile sig_atomic_t tog_sigpipe_received;
625 static volatile sig_atomic_t tog_sigcont_received;
626 static volatile sig_atomic_t tog_sigint_received;
627 static volatile sig_atomic_t tog_sigterm_received;
629 static void
630 tog_sigwinch(int signo)
632 tog_sigwinch_received = 1;
635 static void
636 tog_sigpipe(int signo)
638 tog_sigpipe_received = 1;
641 static void
642 tog_sigcont(int signo)
644 tog_sigcont_received = 1;
647 static void
648 tog_sigint(int signo)
650 tog_sigint_received = 1;
653 static void
654 tog_sigterm(int signo)
656 tog_sigterm_received = 1;
659 static int
660 tog_fatal_signal_received(void)
662 return (tog_sigpipe_received ||
663 tog_sigint_received || tog_sigint_received);
666 static const struct got_error *
667 view_close(struct tog_view *view)
669 const struct got_error *err = NULL, *child_err = NULL;
671 if (view->child) {
672 child_err = view_close(view->child);
673 view->child = NULL;
675 if (view->close)
676 err = view->close(view);
677 if (view->panel)
678 del_panel(view->panel);
679 if (view->window)
680 delwin(view->window);
681 free(view);
682 return err ? err : child_err;
685 static struct tog_view *
686 view_open(int nlines, int ncols, int begin_y, int begin_x,
687 enum tog_view_type type)
689 struct tog_view *view = calloc(1, sizeof(*view));
691 if (view == NULL)
692 return NULL;
694 view->type = type;
695 view->lines = LINES;
696 view->cols = COLS;
697 view->nlines = nlines ? nlines : LINES - begin_y;
698 view->ncols = ncols ? ncols : COLS - begin_x;
699 view->begin_y = begin_y;
700 view->begin_x = begin_x;
701 view->window = newwin(nlines, ncols, begin_y, begin_x);
702 if (view->window == NULL) {
703 view_close(view);
704 return NULL;
706 view->panel = new_panel(view->window);
707 if (view->panel == NULL ||
708 set_panel_userptr(view->panel, view) != OK) {
709 view_close(view);
710 return NULL;
713 keypad(view->window, TRUE);
714 return view;
717 static int
718 view_split_begin_x(int begin_x)
720 if (begin_x > 0 || COLS < 120)
721 return 0;
722 return (COLS - MAX(COLS / 2, 80));
725 /* XXX Stub till we decide what to do. */
726 static int
727 view_split_begin_y(int lines)
729 return lines * HSPLIT_SCALE;
732 static const struct got_error *view_resize(struct tog_view *);
734 static const struct got_error *
735 view_splitscreen(struct tog_view *view)
737 const struct got_error *err = NULL;
739 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
740 if (view->resized_y && view->resized_y < view->lines)
741 view->begin_y = view->resized_y;
742 else
743 view->begin_y = view_split_begin_y(view->nlines);
744 view->begin_x = 0;
745 } else if (!view->resized) {
746 if (view->resized_x && view->resized_x < view->cols - 1 &&
747 view->cols > 119)
748 view->begin_x = view->resized_x;
749 else
750 view->begin_x = view_split_begin_x(0);
751 view->begin_y = 0;
753 view->nlines = LINES - view->begin_y;
754 view->ncols = COLS - view->begin_x;
755 view->lines = LINES;
756 view->cols = COLS;
757 err = view_resize(view);
758 if (err)
759 return err;
761 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
762 view->parent->nlines = view->begin_y;
764 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
765 return got_error_from_errno("mvwin");
767 return NULL;
770 static const struct got_error *
771 view_fullscreen(struct tog_view *view)
773 const struct got_error *err = NULL;
775 view->begin_x = 0;
776 view->begin_y = view->resized ? view->begin_y : 0;
777 view->nlines = view->resized ? view->nlines : LINES;
778 view->ncols = COLS;
779 view->lines = LINES;
780 view->cols = COLS;
781 err = view_resize(view);
782 if (err)
783 return err;
785 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
786 return got_error_from_errno("mvwin");
788 return NULL;
791 static int
792 view_is_parent_view(struct tog_view *view)
794 return view->parent == NULL;
797 static int
798 view_is_splitscreen(struct tog_view *view)
800 return view->begin_x > 0 || view->begin_y > 0;
803 static int
804 view_is_fullscreen(struct tog_view *view)
806 return view->nlines == LINES && view->ncols == COLS;
809 static int
810 view_is_hsplit_top(struct tog_view *view)
812 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
813 view_is_splitscreen(view->child);
816 static void
817 view_border(struct tog_view *view)
819 PANEL *panel;
820 const struct tog_view *view_above;
822 if (view->parent)
823 return view_border(view->parent);
825 panel = panel_above(view->panel);
826 if (panel == NULL)
827 return;
829 view_above = panel_userptr(panel);
830 if (view->mode == TOG_VIEW_SPLIT_HRZN)
831 mvwhline(view->window, view_above->begin_y - 1,
832 view->begin_x, got_locale_is_utf8() ?
833 ACS_HLINE : '-', view->ncols);
834 else
835 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
836 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
839 static const struct got_error *view_init_hsplit(struct tog_view *, int);
840 static const struct got_error *request_log_commits(struct tog_view *);
841 static const struct got_error *offset_selection_down(struct tog_view *);
842 static void offset_selection_up(struct tog_view *);
843 static void view_get_split(struct tog_view *, int *, int *);
845 static const struct got_error *
846 view_resize(struct tog_view *view)
848 const struct got_error *err = NULL;
849 int dif, nlines, ncols;
851 dif = LINES - view->lines; /* line difference */
853 if (view->lines > LINES)
854 nlines = view->nlines - (view->lines - LINES);
855 else
856 nlines = view->nlines + (LINES - view->lines);
857 if (view->cols > COLS)
858 ncols = view->ncols - (view->cols - COLS);
859 else
860 ncols = view->ncols + (COLS - view->cols);
862 if (view->child) {
863 int hs = view->child->begin_y;
865 if (!view_is_fullscreen(view))
866 view->child->begin_x = view_split_begin_x(view->begin_x);
867 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
868 view->child->begin_x == 0) {
869 ncols = COLS;
871 view_fullscreen(view->child);
872 if (view->child->focussed)
873 show_panel(view->child->panel);
874 else
875 show_panel(view->panel);
876 } else {
877 ncols = view->child->begin_x;
879 view_splitscreen(view->child);
880 show_panel(view->child->panel);
882 /*
883 * XXX This is ugly and needs to be moved into the above
884 * logic but "works" for now and my attempts at moving it
885 * break either 'tab' or 'F' key maps in horizontal splits.
886 */
887 if (hs) {
888 err = view_splitscreen(view->child);
889 if (err)
890 return err;
891 if (dif < 0) { /* top split decreased */
892 err = offset_selection_down(view);
893 if (err)
894 return err;
896 view_border(view);
897 update_panels();
898 doupdate();
899 show_panel(view->child->panel);
900 nlines = view->nlines;
902 } else if (view->parent == NULL)
903 ncols = COLS;
905 if (view->resize && dif > 0) {
906 err = view->resize(view, dif);
907 if (err)
908 return err;
911 if (wresize(view->window, nlines, ncols) == ERR)
912 return got_error_from_errno("wresize");
913 if (replace_panel(view->panel, view->window) == ERR)
914 return got_error_from_errno("replace_panel");
915 wclear(view->window);
917 view->nlines = nlines;
918 view->ncols = ncols;
919 view->lines = LINES;
920 view->cols = COLS;
922 return NULL;
925 static const struct got_error *
926 resize_log_view(struct tog_view *view, int increase)
928 struct tog_log_view_state *s = &view->state.log;
929 const struct got_error *err = NULL;
930 int n = 0;
932 if (s->selected_entry)
933 n = s->selected_entry->idx + view->lines - s->selected;
935 /*
936 * Request commits to account for the increased
937 * height so we have enough to populate the view.
938 */
939 if (s->commits.ncommits < n) {
940 view->nscrolled = n - s->commits.ncommits + increase + 1;
941 err = request_log_commits(view);
944 return err;
947 static void
948 view_adjust_offset(struct tog_view *view, int n)
950 if (n == 0)
951 return;
953 if (view->parent && view->parent->offset) {
954 if (view->parent->offset + n >= 0)
955 view->parent->offset += n;
956 else
957 view->parent->offset = 0;
958 } else if (view->offset) {
959 if (view->offset - n >= 0)
960 view->offset -= n;
961 else
962 view->offset = 0;
966 static const struct got_error *
967 view_resize_split(struct tog_view *view, int resize)
969 const struct got_error *err = NULL;
970 struct tog_view *v = NULL;
972 if (view->parent)
973 v = view->parent;
974 else
975 v = view;
977 if (!v->child || !view_is_splitscreen(v->child))
978 return NULL;
980 v->resized = v->child->resized = resize; /* lock for resize event */
982 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
983 if (v->child->resized_y)
984 v->child->begin_y = v->child->resized_y;
985 if (view->parent)
986 v->child->begin_y -= resize;
987 else
988 v->child->begin_y += resize;
989 if (v->child->begin_y < 3) {
990 view->count = 0;
991 v->child->begin_y = 3;
992 } else if (v->child->begin_y > LINES - 1) {
993 view->count = 0;
994 v->child->begin_y = LINES - 1;
996 v->ncols = COLS;
997 v->child->ncols = COLS;
998 view_adjust_offset(view, resize);
999 err = view_init_hsplit(v, v->child->begin_y);
1000 if (err)
1001 return err;
1002 v->child->resized_y = v->child->begin_y;
1003 } else {
1004 if (v->child->resized_x)
1005 v->child->begin_x = v->child->resized_x;
1006 if (view->parent)
1007 v->child->begin_x -= resize;
1008 else
1009 v->child->begin_x += resize;
1010 if (v->child->begin_x < 11) {
1011 view->count = 0;
1012 v->child->begin_x = 11;
1013 } else if (v->child->begin_x > COLS - 1) {
1014 view->count = 0;
1015 v->child->begin_x = COLS - 1;
1017 v->child->resized_x = v->child->begin_x;
1020 v->child->mode = v->mode;
1021 v->child->nlines = v->lines - v->child->begin_y;
1022 v->child->ncols = v->cols - v->child->begin_x;
1023 v->focus_child = 1;
1025 err = view_fullscreen(v);
1026 if (err)
1027 return err;
1028 err = view_splitscreen(v->child);
1029 if (err)
1030 return err;
1032 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1033 err = offset_selection_down(v->child);
1034 if (err)
1035 return err;
1038 if (v->resize)
1039 err = v->resize(v, 0);
1040 else if (v->child->resize)
1041 err = v->child->resize(v->child, 0);
1043 v->resized = v->child->resized = 0;
1045 return err;
1048 static void
1049 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1051 struct tog_view *v = src->child ? src->child : src;
1053 dst->resized_x = v->resized_x;
1054 dst->resized_y = v->resized_y;
1057 static const struct got_error *
1058 view_close_child(struct tog_view *view)
1060 const struct got_error *err = NULL;
1062 if (view->child == NULL)
1063 return NULL;
1065 err = view_close(view->child);
1066 view->child = NULL;
1067 return err;
1070 static const struct got_error *
1071 view_set_child(struct tog_view *view, struct tog_view *child)
1073 const struct got_error *err = NULL;
1075 view->child = child;
1076 child->parent = view;
1078 err = view_resize(view);
1079 if (err)
1080 return err;
1082 if (view->child->resized_x || view->child->resized_y)
1083 err = view_resize_split(view, 0);
1085 return err;
1088 static const struct got_error *view_dispatch_request(struct tog_view **,
1089 struct tog_view *, enum tog_view_type, int, int);
1091 static const struct got_error *
1092 view_request_new(struct tog_view **requested, struct tog_view *view,
1093 enum tog_view_type request)
1095 struct tog_view *new_view = NULL;
1096 const struct got_error *err;
1097 int y = 0, x = 0;
1099 *requested = NULL;
1101 if (view_is_parent_view(view))
1102 view_get_split(view, &y, &x);
1104 err = view_dispatch_request(&new_view, view, request, y, x);
1105 if (err)
1106 return err;
1108 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN) {
1109 err = view_init_hsplit(view, y);
1110 if (err)
1111 return err;
1114 view->focussed = 0;
1115 new_view->focussed = 1;
1116 new_view->mode = view->mode;
1117 new_view->nlines = view->lines - y;
1119 if (view_is_parent_view(view)) {
1120 view_transfer_size(new_view, view);
1121 err = view_close_child(view);
1122 if (err)
1123 return err;
1124 err = view_set_child(view, new_view);
1125 if (err)
1126 return err;
1127 view->focus_child = 1;
1128 } else
1129 *requested = new_view;
1131 return NULL;
1134 static void
1135 tog_resizeterm(void)
1137 int cols, lines;
1138 struct winsize size;
1140 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1141 cols = 80; /* Default */
1142 lines = 24;
1143 } else {
1144 cols = size.ws_col;
1145 lines = size.ws_row;
1147 resize_term(lines, cols);
1150 static const struct got_error *
1151 view_search_start(struct tog_view *view)
1153 const struct got_error *err = NULL;
1154 struct tog_view *v = view;
1155 char pattern[1024];
1156 int ret;
1158 if (view->search_started) {
1159 regfree(&view->regex);
1160 view->searching = 0;
1161 memset(&view->regmatch, 0, sizeof(view->regmatch));
1163 view->search_started = 0;
1165 if (view->nlines < 1)
1166 return NULL;
1168 if (view_is_hsplit_top(view))
1169 v = view->child;
1171 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1172 wclrtoeol(v->window);
1174 nodelay(view->window, FALSE); /* block for search term input */
1175 nocbreak();
1176 echo();
1177 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1178 wrefresh(v->window);
1179 cbreak();
1180 noecho();
1181 nodelay(view->window, TRUE);
1182 if (ret == ERR)
1183 return NULL;
1185 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1186 err = view->search_start(view);
1187 if (err) {
1188 regfree(&view->regex);
1189 return err;
1191 view->search_started = 1;
1192 view->searching = TOG_SEARCH_FORWARD;
1193 view->search_next_done = 0;
1194 view->search_next(view);
1197 return NULL;
1200 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1201 static const struct got_error *
1202 switch_split(struct tog_view *view)
1204 const struct got_error *err = NULL;
1205 struct tog_view *v = NULL;
1207 if (view->parent)
1208 v = view->parent;
1209 else
1210 v = view;
1212 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1213 v->mode = TOG_VIEW_SPLIT_VERT;
1214 else
1215 v->mode = TOG_VIEW_SPLIT_HRZN;
1217 if (!v->child)
1218 return NULL;
1219 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1220 v->mode = TOG_VIEW_SPLIT_NONE;
1222 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1223 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1224 v->child->begin_y = v->child->resized_y;
1225 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1226 v->child->begin_x = v->child->resized_x;
1229 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1230 v->ncols = COLS;
1231 v->child->ncols = COLS;
1232 v->child->nscrolled = LINES - v->child->nlines;
1234 err = view_init_hsplit(v, v->child->begin_y);
1235 if (err)
1236 return err;
1238 v->child->mode = v->mode;
1239 v->child->nlines = v->lines - v->child->begin_y;
1240 v->focus_child = 1;
1242 err = view_fullscreen(v);
1243 if (err)
1244 return err;
1245 err = view_splitscreen(v->child);
1246 if (err)
1247 return err;
1249 if (v->mode == TOG_VIEW_SPLIT_NONE)
1250 v->mode = TOG_VIEW_SPLIT_VERT;
1251 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1252 err = offset_selection_down(v);
1253 if (err)
1254 return err;
1255 err = offset_selection_down(v->child);
1256 if (err)
1257 return err;
1258 } else {
1259 offset_selection_up(v);
1260 offset_selection_up(v->child);
1262 if (v->resize)
1263 err = v->resize(v, 0);
1264 else if (v->child->resize)
1265 err = v->child->resize(v->child, 0);
1267 return err;
1271 * Compute view->count from numeric input. Assign total to view->count and
1272 * return first non-numeric key entered.
1274 static int
1275 get_compound_key(struct tog_view *view, int c)
1277 struct tog_view *v = view;
1278 int x, n = 0;
1280 if (view_is_hsplit_top(view))
1281 v = view->child;
1282 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1283 v = view->parent;
1285 view->count = 0;
1286 cbreak(); /* block for input */
1287 nodelay(view->window, FALSE);
1288 wmove(v->window, v->nlines - 1, 0);
1289 wclrtoeol(v->window);
1290 waddch(v->window, ':');
1292 do {
1293 x = getcurx(v->window);
1294 if (x != ERR && x < view->ncols) {
1295 waddch(v->window, c);
1296 wrefresh(v->window);
1300 * Don't overflow. Max valid request should be the greatest
1301 * between the longest and total lines; cap at 10 million.
1303 if (n >= 9999999)
1304 n = 9999999;
1305 else
1306 n = n * 10 + (c - '0');
1307 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1309 if (c == 'G' || c == 'g') { /* nG key map */
1310 view->gline = view->hiline = n;
1311 n = 0;
1312 c = 0;
1315 /* Massage excessive or inapplicable values at the input handler. */
1316 view->count = n;
1318 return c;
1321 static const struct got_error *
1322 view_input(struct tog_view **new, int *done, struct tog_view *view,
1323 struct tog_view_list_head *views)
1325 const struct got_error *err = NULL;
1326 struct tog_view *v;
1327 int ch, errcode;
1329 *new = NULL;
1331 /* Clear "no matches" indicator. */
1332 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1333 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1334 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1335 view->count = 0;
1338 if (view->searching && !view->search_next_done) {
1339 errcode = pthread_mutex_unlock(&tog_mutex);
1340 if (errcode)
1341 return got_error_set_errno(errcode,
1342 "pthread_mutex_unlock");
1343 sched_yield();
1344 errcode = pthread_mutex_lock(&tog_mutex);
1345 if (errcode)
1346 return got_error_set_errno(errcode,
1347 "pthread_mutex_lock");
1348 view->search_next(view);
1349 return NULL;
1352 /* Allow threads to make progress while we are waiting for input. */
1353 errcode = pthread_mutex_unlock(&tog_mutex);
1354 if (errcode)
1355 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1356 /* If we have an unfinished count, let C-g or backspace abort. */
1357 if (view->count && --view->count) {
1358 cbreak();
1359 nodelay(view->window, TRUE);
1360 ch = wgetch(view->window);
1361 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1362 view->count = 0;
1363 else
1364 ch = view->ch;
1365 } else {
1366 ch = wgetch(view->window);
1367 if (ch >= '1' && ch <= '9')
1368 view->ch = ch = get_compound_key(view, ch);
1370 if (view->hiline && ch != ERR && ch != 0)
1371 view->hiline = 0; /* key pressed, clear line highlight */
1372 nodelay(view->window, TRUE);
1373 errcode = pthread_mutex_lock(&tog_mutex);
1374 if (errcode)
1375 return got_error_set_errno(errcode, "pthread_mutex_lock");
1377 if (tog_sigwinch_received || tog_sigcont_received) {
1378 tog_resizeterm();
1379 tog_sigwinch_received = 0;
1380 tog_sigcont_received = 0;
1381 TAILQ_FOREACH(v, views, entry) {
1382 err = view_resize(v);
1383 if (err)
1384 return err;
1385 err = v->input(new, v, KEY_RESIZE);
1386 if (err)
1387 return err;
1388 if (v->child) {
1389 err = view_resize(v->child);
1390 if (err)
1391 return err;
1392 err = v->child->input(new, v->child,
1393 KEY_RESIZE);
1394 if (err)
1395 return err;
1396 if (v->child->resized_x || v->child->resized_y) {
1397 err = view_resize_split(v, 0);
1398 if (err)
1399 return err;
1405 switch (ch) {
1406 case '\t':
1407 view->count = 0;
1408 if (view->child) {
1409 view->focussed = 0;
1410 view->child->focussed = 1;
1411 view->focus_child = 1;
1412 } else if (view->parent) {
1413 view->focussed = 0;
1414 view->parent->focussed = 1;
1415 view->parent->focus_child = 0;
1416 if (!view_is_splitscreen(view)) {
1417 if (view->parent->resize) {
1418 err = view->parent->resize(view->parent,
1419 0);
1420 if (err)
1421 return err;
1423 offset_selection_up(view->parent);
1424 err = view_fullscreen(view->parent);
1425 if (err)
1426 return err;
1429 break;
1430 case 'q':
1431 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1432 if (view->parent->resize) {
1433 /* might need more commits to fill fullscreen */
1434 err = view->parent->resize(view->parent, 0);
1435 if (err)
1436 break;
1438 offset_selection_up(view->parent);
1440 err = view->input(new, view, ch);
1441 view->dying = 1;
1442 break;
1443 case 'Q':
1444 *done = 1;
1445 break;
1446 case 'F':
1447 view->count = 0;
1448 if (view_is_parent_view(view)) {
1449 if (view->child == NULL)
1450 break;
1451 if (view_is_splitscreen(view->child)) {
1452 view->focussed = 0;
1453 view->child->focussed = 1;
1454 err = view_fullscreen(view->child);
1455 } else {
1456 err = view_splitscreen(view->child);
1457 if (!err)
1458 err = view_resize_split(view, 0);
1460 if (err)
1461 break;
1462 err = view->child->input(new, view->child,
1463 KEY_RESIZE);
1464 } else {
1465 if (view_is_splitscreen(view)) {
1466 view->parent->focussed = 0;
1467 view->focussed = 1;
1468 err = view_fullscreen(view);
1469 } else {
1470 err = view_splitscreen(view);
1471 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1472 err = view_resize(view->parent);
1473 if (!err)
1474 err = view_resize_split(view, 0);
1476 if (err)
1477 break;
1478 err = view->input(new, view, KEY_RESIZE);
1480 if (err)
1481 break;
1482 if (view->resize) {
1483 err = view->resize(view, 0);
1484 if (err)
1485 break;
1487 if (view->parent)
1488 err = offset_selection_down(view->parent);
1489 if (!err)
1490 err = offset_selection_down(view);
1491 break;
1492 case 'S':
1493 view->count = 0;
1494 err = switch_split(view);
1495 break;
1496 case '-':
1497 err = view_resize_split(view, -1);
1498 break;
1499 case '+':
1500 err = view_resize_split(view, 1);
1501 break;
1502 case KEY_RESIZE:
1503 break;
1504 case '/':
1505 view->count = 0;
1506 if (view->search_start)
1507 view_search_start(view);
1508 else
1509 err = view->input(new, view, ch);
1510 break;
1511 case 'N':
1512 case 'n':
1513 if (view->search_started && view->search_next) {
1514 view->searching = (ch == 'n' ?
1515 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1516 view->search_next_done = 0;
1517 view->search_next(view);
1518 } else
1519 err = view->input(new, view, ch);
1520 break;
1521 case 'A':
1522 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1523 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1524 else
1525 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1526 TAILQ_FOREACH(v, views, entry) {
1527 if (v->reset) {
1528 err = v->reset(v);
1529 if (err)
1530 return err;
1532 if (v->child && v->child->reset) {
1533 err = v->child->reset(v->child);
1534 if (err)
1535 return err;
1538 break;
1539 default:
1540 err = view->input(new, view, ch);
1541 break;
1544 return err;
1547 static int
1548 view_needs_focus_indication(struct tog_view *view)
1550 if (view_is_parent_view(view)) {
1551 if (view->child == NULL || view->child->focussed)
1552 return 0;
1553 if (!view_is_splitscreen(view->child))
1554 return 0;
1555 } else if (!view_is_splitscreen(view))
1556 return 0;
1558 return view->focussed;
1561 static const struct got_error *
1562 view_loop(struct tog_view *view)
1564 const struct got_error *err = NULL;
1565 struct tog_view_list_head views;
1566 struct tog_view *new_view;
1567 char *mode;
1568 int fast_refresh = 10;
1569 int done = 0, errcode;
1571 mode = getenv("TOG_VIEW_SPLIT_MODE");
1572 if (!mode || !(*mode == 'h' || *mode == 'H'))
1573 view->mode = TOG_VIEW_SPLIT_VERT;
1574 else
1575 view->mode = TOG_VIEW_SPLIT_HRZN;
1577 errcode = pthread_mutex_lock(&tog_mutex);
1578 if (errcode)
1579 return got_error_set_errno(errcode, "pthread_mutex_lock");
1581 TAILQ_INIT(&views);
1582 TAILQ_INSERT_HEAD(&views, view, entry);
1584 view->focussed = 1;
1585 err = view->show(view);
1586 if (err)
1587 return err;
1588 update_panels();
1589 doupdate();
1590 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1591 !tog_fatal_signal_received()) {
1592 /* Refresh fast during initialization, then become slower. */
1593 if (fast_refresh && fast_refresh-- == 0)
1594 halfdelay(10); /* switch to once per second */
1596 err = view_input(&new_view, &done, view, &views);
1597 if (err)
1598 break;
1599 if (view->dying) {
1600 struct tog_view *v, *prev = NULL;
1602 if (view_is_parent_view(view))
1603 prev = TAILQ_PREV(view, tog_view_list_head,
1604 entry);
1605 else if (view->parent)
1606 prev = view->parent;
1608 if (view->parent) {
1609 view->parent->child = NULL;
1610 view->parent->focus_child = 0;
1611 /* Restore fullscreen line height. */
1612 view->parent->nlines = view->parent->lines;
1613 err = view_resize(view->parent);
1614 if (err)
1615 break;
1616 /* Make resized splits persist. */
1617 view_transfer_size(view->parent, view);
1618 } else
1619 TAILQ_REMOVE(&views, view, entry);
1621 err = view_close(view);
1622 if (err)
1623 goto done;
1625 view = NULL;
1626 TAILQ_FOREACH(v, &views, entry) {
1627 if (v->focussed)
1628 break;
1630 if (view == NULL && new_view == NULL) {
1631 /* No view has focus. Try to pick one. */
1632 if (prev)
1633 view = prev;
1634 else if (!TAILQ_EMPTY(&views)) {
1635 view = TAILQ_LAST(&views,
1636 tog_view_list_head);
1638 if (view) {
1639 if (view->focus_child) {
1640 view->child->focussed = 1;
1641 view = view->child;
1642 } else
1643 view->focussed = 1;
1647 if (new_view) {
1648 struct tog_view *v, *t;
1649 /* Only allow one parent view per type. */
1650 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1651 if (v->type != new_view->type)
1652 continue;
1653 TAILQ_REMOVE(&views, v, entry);
1654 err = view_close(v);
1655 if (err)
1656 goto done;
1657 break;
1659 TAILQ_INSERT_TAIL(&views, new_view, entry);
1660 view = new_view;
1662 if (view) {
1663 if (view_is_parent_view(view)) {
1664 if (view->child && view->child->focussed)
1665 view = view->child;
1666 } else {
1667 if (view->parent && view->parent->focussed)
1668 view = view->parent;
1670 show_panel(view->panel);
1671 if (view->child && view_is_splitscreen(view->child))
1672 show_panel(view->child->panel);
1673 if (view->parent && view_is_splitscreen(view)) {
1674 err = view->parent->show(view->parent);
1675 if (err)
1676 goto done;
1678 err = view->show(view);
1679 if (err)
1680 goto done;
1681 if (view->child) {
1682 err = view->child->show(view->child);
1683 if (err)
1684 goto done;
1686 update_panels();
1687 doupdate();
1690 done:
1691 while (!TAILQ_EMPTY(&views)) {
1692 const struct got_error *close_err;
1693 view = TAILQ_FIRST(&views);
1694 TAILQ_REMOVE(&views, view, entry);
1695 close_err = view_close(view);
1696 if (close_err && err == NULL)
1697 err = close_err;
1700 errcode = pthread_mutex_unlock(&tog_mutex);
1701 if (errcode && err == NULL)
1702 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1704 return err;
1707 __dead static void
1708 usage_log(void)
1710 endwin();
1711 fprintf(stderr,
1712 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1713 getprogname());
1714 exit(1);
1717 /* Create newly allocated wide-character string equivalent to a byte string. */
1718 static const struct got_error *
1719 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1721 char *vis = NULL;
1722 const struct got_error *err = NULL;
1724 *ws = NULL;
1725 *wlen = mbstowcs(NULL, s, 0);
1726 if (*wlen == (size_t)-1) {
1727 int vislen;
1728 if (errno != EILSEQ)
1729 return got_error_from_errno("mbstowcs");
1731 /* byte string invalid in current encoding; try to "fix" it */
1732 err = got_mbsavis(&vis, &vislen, s);
1733 if (err)
1734 return err;
1735 *wlen = mbstowcs(NULL, vis, 0);
1736 if (*wlen == (size_t)-1) {
1737 err = got_error_from_errno("mbstowcs"); /* give up */
1738 goto done;
1742 *ws = calloc(*wlen + 1, sizeof(**ws));
1743 if (*ws == NULL) {
1744 err = got_error_from_errno("calloc");
1745 goto done;
1748 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1749 err = got_error_from_errno("mbstowcs");
1750 done:
1751 free(vis);
1752 if (err) {
1753 free(*ws);
1754 *ws = NULL;
1755 *wlen = 0;
1757 return err;
1760 static const struct got_error *
1761 expand_tab(char **ptr, const char *src)
1763 char *dst;
1764 size_t len, n, idx = 0, sz = 0;
1766 *ptr = NULL;
1767 n = len = strlen(src);
1768 dst = malloc(n + 1);
1769 if (dst == NULL)
1770 return got_error_from_errno("malloc");
1772 while (idx < len && src[idx]) {
1773 const char c = src[idx];
1775 if (c == '\t') {
1776 size_t nb = TABSIZE - sz % TABSIZE;
1777 char *p;
1779 p = realloc(dst, n + nb);
1780 if (p == NULL) {
1781 free(dst);
1782 return got_error_from_errno("realloc");
1785 dst = p;
1786 n += nb;
1787 memset(dst + sz, ' ', nb);
1788 sz += nb;
1789 } else
1790 dst[sz++] = src[idx];
1791 ++idx;
1794 dst[sz] = '\0';
1795 *ptr = dst;
1796 return NULL;
1800 * Advance at most n columns from wline starting at offset off.
1801 * Return the index to the first character after the span operation.
1802 * Return the combined column width of all spanned wide character in
1803 * *rcol.
1805 static int
1806 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1808 int width, i, cols = 0;
1810 if (n == 0) {
1811 *rcol = cols;
1812 return off;
1815 for (i = off; wline[i] != L'\0'; ++i) {
1816 if (wline[i] == L'\t')
1817 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1818 else
1819 width = wcwidth(wline[i]);
1821 if (width == -1) {
1822 width = 1;
1823 wline[i] = L'.';
1826 if (cols + width > n)
1827 break;
1828 cols += width;
1831 *rcol = cols;
1832 return i;
1836 * Format a line for display, ensuring that it won't overflow a width limit.
1837 * With scrolling, the width returned refers to the scrolled version of the
1838 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1840 static const struct got_error *
1841 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1842 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1844 const struct got_error *err = NULL;
1845 int cols;
1846 wchar_t *wline = NULL;
1847 char *exstr = NULL;
1848 size_t wlen;
1849 int i, scrollx;
1851 *wlinep = NULL;
1852 *widthp = 0;
1854 if (expand) {
1855 err = expand_tab(&exstr, line);
1856 if (err)
1857 return err;
1860 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1861 free(exstr);
1862 if (err)
1863 return err;
1865 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1867 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1868 wline[wlen - 1] = L'\0';
1869 wlen--;
1871 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1872 wline[wlen - 1] = L'\0';
1873 wlen--;
1876 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1877 wline[i] = L'\0';
1879 if (widthp)
1880 *widthp = cols;
1881 if (scrollxp)
1882 *scrollxp = scrollx;
1883 if (err)
1884 free(wline);
1885 else
1886 *wlinep = wline;
1887 return err;
1890 static const struct got_error*
1891 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1892 struct got_object_id *id, struct got_repository *repo)
1894 static const struct got_error *err = NULL;
1895 struct got_reflist_entry *re;
1896 char *s;
1897 const char *name;
1899 *refs_str = NULL;
1901 TAILQ_FOREACH(re, refs, entry) {
1902 struct got_tag_object *tag = NULL;
1903 struct got_object_id *ref_id;
1904 int cmp;
1906 name = got_ref_get_name(re->ref);
1907 if (strcmp(name, GOT_REF_HEAD) == 0)
1908 continue;
1909 if (strncmp(name, "refs/", 5) == 0)
1910 name += 5;
1911 if (strncmp(name, "got/", 4) == 0 &&
1912 strncmp(name, "got/backup/", 11) != 0)
1913 continue;
1914 if (strncmp(name, "heads/", 6) == 0)
1915 name += 6;
1916 if (strncmp(name, "remotes/", 8) == 0) {
1917 name += 8;
1918 s = strstr(name, "/" GOT_REF_HEAD);
1919 if (s != NULL && s[strlen(s)] == '\0')
1920 continue;
1922 err = got_ref_resolve(&ref_id, repo, re->ref);
1923 if (err)
1924 break;
1925 if (strncmp(name, "tags/", 5) == 0) {
1926 err = got_object_open_as_tag(&tag, repo, ref_id);
1927 if (err) {
1928 if (err->code != GOT_ERR_OBJ_TYPE) {
1929 free(ref_id);
1930 break;
1932 /* Ref points at something other than a tag. */
1933 err = NULL;
1934 tag = NULL;
1937 cmp = got_object_id_cmp(tag ?
1938 got_object_tag_get_object_id(tag) : ref_id, id);
1939 free(ref_id);
1940 if (tag)
1941 got_object_tag_close(tag);
1942 if (cmp != 0)
1943 continue;
1944 s = *refs_str;
1945 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1946 s ? ", " : "", name) == -1) {
1947 err = got_error_from_errno("asprintf");
1948 free(s);
1949 *refs_str = NULL;
1950 break;
1952 free(s);
1955 return err;
1958 static const struct got_error *
1959 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1960 int col_tab_align)
1962 char *smallerthan;
1964 smallerthan = strchr(author, '<');
1965 if (smallerthan && smallerthan[1] != '\0')
1966 author = smallerthan + 1;
1967 author[strcspn(author, "@>")] = '\0';
1968 return format_line(wauthor, author_width, NULL, author, 0, limit,
1969 col_tab_align, 0);
1972 static const struct got_error *
1973 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1974 struct got_object_id *id, const size_t date_display_cols,
1975 int author_display_cols)
1977 struct tog_log_view_state *s = &view->state.log;
1978 const struct got_error *err = NULL;
1979 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1980 char *logmsg0 = NULL, *logmsg = NULL;
1981 char *author = NULL;
1982 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1983 int author_width, logmsg_width;
1984 char *newline, *line = NULL;
1985 int col, limit, scrollx;
1986 const int avail = view->ncols;
1987 struct tm tm;
1988 time_t committer_time;
1989 struct tog_color *tc;
1991 committer_time = got_object_commit_get_committer_time(commit);
1992 if (gmtime_r(&committer_time, &tm) == NULL)
1993 return got_error_from_errno("gmtime_r");
1994 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1995 return got_error(GOT_ERR_NO_SPACE);
1997 if (avail <= date_display_cols)
1998 limit = MIN(sizeof(datebuf) - 1, avail);
1999 else
2000 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2001 tc = get_color(&s->colors, TOG_COLOR_DATE);
2002 if (tc)
2003 wattr_on(view->window,
2004 COLOR_PAIR(tc->colorpair), NULL);
2005 waddnstr(view->window, datebuf, limit);
2006 if (tc)
2007 wattr_off(view->window,
2008 COLOR_PAIR(tc->colorpair), NULL);
2009 col = limit;
2010 if (col > avail)
2011 goto done;
2013 if (avail >= 120) {
2014 char *id_str;
2015 err = got_object_id_str(&id_str, id);
2016 if (err)
2017 goto done;
2018 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2019 if (tc)
2020 wattr_on(view->window,
2021 COLOR_PAIR(tc->colorpair), NULL);
2022 wprintw(view->window, "%.8s ", id_str);
2023 if (tc)
2024 wattr_off(view->window,
2025 COLOR_PAIR(tc->colorpair), NULL);
2026 free(id_str);
2027 col += 9;
2028 if (col > avail)
2029 goto done;
2032 if (s->use_committer)
2033 author = strdup(got_object_commit_get_committer(commit));
2034 else
2035 author = strdup(got_object_commit_get_author(commit));
2036 if (author == NULL) {
2037 err = got_error_from_errno("strdup");
2038 goto done;
2040 err = format_author(&wauthor, &author_width, author, avail - col, col);
2041 if (err)
2042 goto done;
2043 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2044 if (tc)
2045 wattr_on(view->window,
2046 COLOR_PAIR(tc->colorpair), NULL);
2047 waddwstr(view->window, wauthor);
2048 if (tc)
2049 wattr_off(view->window,
2050 COLOR_PAIR(tc->colorpair), NULL);
2051 col += author_width;
2052 while (col < avail && author_width < author_display_cols + 2) {
2053 waddch(view->window, ' ');
2054 col++;
2055 author_width++;
2057 if (col > avail)
2058 goto done;
2060 err = got_object_commit_get_logmsg(&logmsg0, commit);
2061 if (err)
2062 goto done;
2063 logmsg = logmsg0;
2064 while (*logmsg == '\n')
2065 logmsg++;
2066 newline = strchr(logmsg, '\n');
2067 if (newline)
2068 *newline = '\0';
2069 limit = avail - col;
2070 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2071 limit--; /* for the border */
2072 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2073 limit, col, 1);
2074 if (err)
2075 goto done;
2076 waddwstr(view->window, &wlogmsg[scrollx]);
2077 col += MAX(logmsg_width, 0);
2078 while (col < avail) {
2079 waddch(view->window, ' ');
2080 col++;
2082 done:
2083 free(logmsg0);
2084 free(wlogmsg);
2085 free(author);
2086 free(wauthor);
2087 free(line);
2088 return err;
2091 static struct commit_queue_entry *
2092 alloc_commit_queue_entry(struct got_commit_object *commit,
2093 struct got_object_id *id)
2095 struct commit_queue_entry *entry;
2097 entry = calloc(1, sizeof(*entry));
2098 if (entry == NULL)
2099 return NULL;
2101 entry->id = id;
2102 entry->commit = commit;
2103 return entry;
2106 static void
2107 pop_commit(struct commit_queue *commits)
2109 struct commit_queue_entry *entry;
2111 entry = TAILQ_FIRST(&commits->head);
2112 TAILQ_REMOVE(&commits->head, entry, entry);
2113 got_object_commit_close(entry->commit);
2114 commits->ncommits--;
2115 /* Don't free entry->id! It is owned by the commit graph. */
2116 free(entry);
2119 static void
2120 free_commits(struct commit_queue *commits)
2122 while (!TAILQ_EMPTY(&commits->head))
2123 pop_commit(commits);
2126 static const struct got_error *
2127 match_commit(int *have_match, struct got_object_id *id,
2128 struct got_commit_object *commit, regex_t *regex)
2130 const struct got_error *err = NULL;
2131 regmatch_t regmatch;
2132 char *id_str = NULL, *logmsg = NULL;
2134 *have_match = 0;
2136 err = got_object_id_str(&id_str, id);
2137 if (err)
2138 return err;
2140 err = got_object_commit_get_logmsg(&logmsg, commit);
2141 if (err)
2142 goto done;
2144 if (regexec(regex, got_object_commit_get_author(commit), 1,
2145 &regmatch, 0) == 0 ||
2146 regexec(regex, got_object_commit_get_committer(commit), 1,
2147 &regmatch, 0) == 0 ||
2148 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2149 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2150 *have_match = 1;
2151 done:
2152 free(id_str);
2153 free(logmsg);
2154 return err;
2157 static const struct got_error *
2158 queue_commits(struct tog_log_thread_args *a)
2160 const struct got_error *err = NULL;
2163 * We keep all commits open throughout the lifetime of the log
2164 * view in order to avoid having to re-fetch commits from disk
2165 * while updating the display.
2167 do {
2168 struct got_object_id *id;
2169 struct got_commit_object *commit;
2170 struct commit_queue_entry *entry;
2171 int errcode;
2173 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2174 NULL, NULL);
2175 if (err || id == NULL)
2176 break;
2178 err = got_object_open_as_commit(&commit, a->repo, id);
2179 if (err)
2180 break;
2181 entry = alloc_commit_queue_entry(commit, id);
2182 if (entry == NULL) {
2183 err = got_error_from_errno("alloc_commit_queue_entry");
2184 break;
2187 errcode = pthread_mutex_lock(&tog_mutex);
2188 if (errcode) {
2189 err = got_error_set_errno(errcode,
2190 "pthread_mutex_lock");
2191 break;
2194 entry->idx = a->commits->ncommits;
2195 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2196 a->commits->ncommits++;
2198 if (*a->searching == TOG_SEARCH_FORWARD &&
2199 !*a->search_next_done) {
2200 int have_match;
2201 err = match_commit(&have_match, id, commit, a->regex);
2202 if (err)
2203 break;
2204 if (have_match)
2205 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2208 errcode = pthread_mutex_unlock(&tog_mutex);
2209 if (errcode && err == NULL)
2210 err = got_error_set_errno(errcode,
2211 "pthread_mutex_unlock");
2212 if (err)
2213 break;
2214 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2216 return err;
2219 static void
2220 select_commit(struct tog_log_view_state *s)
2222 struct commit_queue_entry *entry;
2223 int ncommits = 0;
2225 entry = s->first_displayed_entry;
2226 while (entry) {
2227 if (ncommits == s->selected) {
2228 s->selected_entry = entry;
2229 break;
2231 entry = TAILQ_NEXT(entry, entry);
2232 ncommits++;
2236 static const struct got_error *
2237 draw_commits(struct tog_view *view)
2239 const struct got_error *err = NULL;
2240 struct tog_log_view_state *s = &view->state.log;
2241 struct commit_queue_entry *entry = s->selected_entry;
2242 const int limit = view->nlines;
2243 int width;
2244 int ncommits, author_cols = 4;
2245 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2246 char *refs_str = NULL;
2247 wchar_t *wline;
2248 struct tog_color *tc;
2249 static const size_t date_display_cols = 12;
2251 if (s->selected_entry &&
2252 !(view->searching && view->search_next_done == 0)) {
2253 struct got_reflist_head *refs;
2254 err = got_object_id_str(&id_str, s->selected_entry->id);
2255 if (err)
2256 return err;
2257 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2258 s->selected_entry->id);
2259 if (refs) {
2260 err = build_refs_str(&refs_str, refs,
2261 s->selected_entry->id, s->repo);
2262 if (err)
2263 goto done;
2267 if (s->thread_args.commits_needed == 0)
2268 halfdelay(10); /* disable fast refresh */
2270 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2271 if (asprintf(&ncommits_str, " [%d/%d] %s",
2272 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2273 (view->searching && !view->search_next_done) ?
2274 "searching..." : "loading...") == -1) {
2275 err = got_error_from_errno("asprintf");
2276 goto done;
2278 } else {
2279 const char *search_str = NULL;
2281 if (view->searching) {
2282 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2283 search_str = "no more matches";
2284 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2285 search_str = "no matches found";
2286 else if (!view->search_next_done)
2287 search_str = "searching...";
2290 if (asprintf(&ncommits_str, " [%d/%d] %s",
2291 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2292 search_str ? search_str :
2293 (refs_str ? refs_str : "")) == -1) {
2294 err = got_error_from_errno("asprintf");
2295 goto done;
2299 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2300 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2301 "........................................",
2302 s->in_repo_path, ncommits_str) == -1) {
2303 err = got_error_from_errno("asprintf");
2304 header = NULL;
2305 goto done;
2307 } else if (asprintf(&header, "commit %s%s",
2308 id_str ? id_str : "........................................",
2309 ncommits_str) == -1) {
2310 err = got_error_from_errno("asprintf");
2311 header = NULL;
2312 goto done;
2314 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2315 if (err)
2316 goto done;
2318 werase(view->window);
2320 if (view_needs_focus_indication(view))
2321 wstandout(view->window);
2322 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2323 if (tc)
2324 wattr_on(view->window,
2325 COLOR_PAIR(tc->colorpair), NULL);
2326 waddwstr(view->window, wline);
2327 if (tc)
2328 wattr_off(view->window,
2329 COLOR_PAIR(tc->colorpair), NULL);
2330 while (width < view->ncols) {
2331 waddch(view->window, ' ');
2332 width++;
2334 if (view_needs_focus_indication(view))
2335 wstandend(view->window);
2336 free(wline);
2337 if (limit <= 1)
2338 goto done;
2340 /* Grow author column size if necessary, and set view->maxx. */
2341 entry = s->first_displayed_entry;
2342 ncommits = 0;
2343 view->maxx = 0;
2344 while (entry) {
2345 struct got_commit_object *c = entry->commit;
2346 char *author, *eol, *msg, *msg0;
2347 wchar_t *wauthor, *wmsg;
2348 int width;
2349 if (ncommits >= limit - 1)
2350 break;
2351 if (s->use_committer)
2352 author = strdup(got_object_commit_get_committer(c));
2353 else
2354 author = strdup(got_object_commit_get_author(c));
2355 if (author == NULL) {
2356 err = got_error_from_errno("strdup");
2357 goto done;
2359 err = format_author(&wauthor, &width, author, COLS,
2360 date_display_cols);
2361 if (author_cols < width)
2362 author_cols = width;
2363 free(wauthor);
2364 free(author);
2365 if (err)
2366 goto done;
2367 err = got_object_commit_get_logmsg(&msg0, c);
2368 if (err)
2369 goto done;
2370 msg = msg0;
2371 while (*msg == '\n')
2372 ++msg;
2373 if ((eol = strchr(msg, '\n')))
2374 *eol = '\0';
2375 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2376 date_display_cols + author_cols, 0);
2377 if (err)
2378 goto done;
2379 view->maxx = MAX(view->maxx, width);
2380 free(msg0);
2381 free(wmsg);
2382 ncommits++;
2383 entry = TAILQ_NEXT(entry, entry);
2386 entry = s->first_displayed_entry;
2387 s->last_displayed_entry = s->first_displayed_entry;
2388 ncommits = 0;
2389 while (entry) {
2390 if (ncommits >= limit - 1)
2391 break;
2392 if (ncommits == s->selected)
2393 wstandout(view->window);
2394 err = draw_commit(view, entry->commit, entry->id,
2395 date_display_cols, author_cols);
2396 if (ncommits == s->selected)
2397 wstandend(view->window);
2398 if (err)
2399 goto done;
2400 ncommits++;
2401 s->last_displayed_entry = entry;
2402 entry = TAILQ_NEXT(entry, entry);
2405 view_border(view);
2406 done:
2407 free(id_str);
2408 free(refs_str);
2409 free(ncommits_str);
2410 free(header);
2411 return err;
2414 static void
2415 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2417 struct commit_queue_entry *entry;
2418 int nscrolled = 0;
2420 entry = TAILQ_FIRST(&s->commits.head);
2421 if (s->first_displayed_entry == entry)
2422 return;
2424 entry = s->first_displayed_entry;
2425 while (entry && nscrolled < maxscroll) {
2426 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2427 if (entry) {
2428 s->first_displayed_entry = entry;
2429 nscrolled++;
2434 static const struct got_error *
2435 trigger_log_thread(struct tog_view *view, int wait)
2437 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2438 int errcode;
2440 halfdelay(1); /* fast refresh while loading commits */
2442 while (!ta->log_complete && !tog_thread_error &&
2443 (ta->commits_needed > 0 || ta->load_all)) {
2444 /* Wake the log thread. */
2445 errcode = pthread_cond_signal(&ta->need_commits);
2446 if (errcode)
2447 return got_error_set_errno(errcode,
2448 "pthread_cond_signal");
2451 * The mutex will be released while the view loop waits
2452 * in wgetch(), at which time the log thread will run.
2454 if (!wait)
2455 break;
2457 /* Display progress update in log view. */
2458 show_log_view(view);
2459 update_panels();
2460 doupdate();
2462 /* Wait right here while next commit is being loaded. */
2463 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2464 if (errcode)
2465 return got_error_set_errno(errcode,
2466 "pthread_cond_wait");
2468 /* Display progress update in log view. */
2469 show_log_view(view);
2470 update_panels();
2471 doupdate();
2474 return NULL;
2477 static const struct got_error *
2478 request_log_commits(struct tog_view *view)
2480 struct tog_log_view_state *state = &view->state.log;
2481 const struct got_error *err = NULL;
2483 if (state->thread_args.log_complete)
2484 return NULL;
2486 state->thread_args.commits_needed += view->nscrolled;
2487 err = trigger_log_thread(view, 1);
2488 view->nscrolled = 0;
2490 return err;
2493 static const struct got_error *
2494 log_scroll_down(struct tog_view *view, int maxscroll)
2496 struct tog_log_view_state *s = &view->state.log;
2497 const struct got_error *err = NULL;
2498 struct commit_queue_entry *pentry;
2499 int nscrolled = 0, ncommits_needed;
2501 if (s->last_displayed_entry == NULL)
2502 return NULL;
2504 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2505 if (s->commits.ncommits < ncommits_needed &&
2506 !s->thread_args.log_complete) {
2508 * Ask the log thread for required amount of commits.
2510 s->thread_args.commits_needed +=
2511 ncommits_needed - s->commits.ncommits;
2512 err = trigger_log_thread(view, 1);
2513 if (err)
2514 return err;
2517 do {
2518 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2519 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2520 break;
2522 s->last_displayed_entry = pentry ?
2523 pentry : s->last_displayed_entry;;
2525 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2526 if (pentry == NULL)
2527 break;
2528 s->first_displayed_entry = pentry;
2529 } while (++nscrolled < maxscroll);
2531 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2532 view->nscrolled += nscrolled;
2533 else
2534 view->nscrolled = 0;
2536 return err;
2539 static const struct got_error *
2540 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2541 struct got_commit_object *commit, struct got_object_id *commit_id,
2542 struct tog_view *log_view, struct got_repository *repo)
2544 const struct got_error *err;
2545 struct got_object_qid *parent_id;
2546 struct tog_view *diff_view;
2548 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2549 if (diff_view == NULL)
2550 return got_error_from_errno("view_open");
2552 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2553 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2554 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2555 if (err == NULL)
2556 *new_view = diff_view;
2557 return err;
2560 static const struct got_error *
2561 tree_view_visit_subtree(struct tog_tree_view_state *s,
2562 struct got_tree_object *subtree)
2564 struct tog_parent_tree *parent;
2566 parent = calloc(1, sizeof(*parent));
2567 if (parent == NULL)
2568 return got_error_from_errno("calloc");
2570 parent->tree = s->tree;
2571 parent->first_displayed_entry = s->first_displayed_entry;
2572 parent->selected_entry = s->selected_entry;
2573 parent->selected = s->selected;
2574 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2575 s->tree = subtree;
2576 s->selected = 0;
2577 s->first_displayed_entry = NULL;
2578 return NULL;
2581 static const struct got_error *
2582 tree_view_walk_path(struct tog_tree_view_state *s,
2583 struct got_commit_object *commit, const char *path)
2585 const struct got_error *err = NULL;
2586 struct got_tree_object *tree = NULL;
2587 const char *p;
2588 char *slash, *subpath = NULL;
2590 /* Walk the path and open corresponding tree objects. */
2591 p = path;
2592 while (*p) {
2593 struct got_tree_entry *te;
2594 struct got_object_id *tree_id;
2595 char *te_name;
2597 while (p[0] == '/')
2598 p++;
2600 /* Ensure the correct subtree entry is selected. */
2601 slash = strchr(p, '/');
2602 if (slash == NULL)
2603 te_name = strdup(p);
2604 else
2605 te_name = strndup(p, slash - p);
2606 if (te_name == NULL) {
2607 err = got_error_from_errno("strndup");
2608 break;
2610 te = got_object_tree_find_entry(s->tree, te_name);
2611 if (te == NULL) {
2612 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2613 free(te_name);
2614 break;
2616 free(te_name);
2617 s->first_displayed_entry = s->selected_entry = te;
2619 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2620 break; /* jump to this file's entry */
2622 slash = strchr(p, '/');
2623 if (slash)
2624 subpath = strndup(path, slash - path);
2625 else
2626 subpath = strdup(path);
2627 if (subpath == NULL) {
2628 err = got_error_from_errno("strdup");
2629 break;
2632 err = got_object_id_by_path(&tree_id, s->repo, commit,
2633 subpath);
2634 if (err)
2635 break;
2637 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2638 free(tree_id);
2639 if (err)
2640 break;
2642 err = tree_view_visit_subtree(s, tree);
2643 if (err) {
2644 got_object_tree_close(tree);
2645 break;
2647 if (slash == NULL)
2648 break;
2649 free(subpath);
2650 subpath = NULL;
2651 p = slash;
2654 free(subpath);
2655 return err;
2658 static const struct got_error *
2659 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2660 struct commit_queue_entry *entry, const char *path,
2661 const char *head_ref_name, struct got_repository *repo)
2663 const struct got_error *err = NULL;
2664 struct tog_tree_view_state *s;
2665 struct tog_view *tree_view;
2667 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2668 if (tree_view == NULL)
2669 return got_error_from_errno("view_open");
2671 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2672 if (err)
2673 return err;
2674 s = &tree_view->state.tree;
2676 *new_view = tree_view;
2678 if (got_path_is_root_dir(path))
2679 return NULL;
2681 return tree_view_walk_path(s, entry->commit, path);
2684 static const struct got_error *
2685 block_signals_used_by_main_thread(void)
2687 sigset_t sigset;
2688 int errcode;
2690 if (sigemptyset(&sigset) == -1)
2691 return got_error_from_errno("sigemptyset");
2693 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2694 if (sigaddset(&sigset, SIGWINCH) == -1)
2695 return got_error_from_errno("sigaddset");
2696 if (sigaddset(&sigset, SIGCONT) == -1)
2697 return got_error_from_errno("sigaddset");
2698 if (sigaddset(&sigset, SIGINT) == -1)
2699 return got_error_from_errno("sigaddset");
2700 if (sigaddset(&sigset, SIGTERM) == -1)
2701 return got_error_from_errno("sigaddset");
2703 /* ncurses handles SIGTSTP */
2704 if (sigaddset(&sigset, SIGTSTP) == -1)
2705 return got_error_from_errno("sigaddset");
2707 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2708 if (errcode)
2709 return got_error_set_errno(errcode, "pthread_sigmask");
2711 return NULL;
2714 static void *
2715 log_thread(void *arg)
2717 const struct got_error *err = NULL;
2718 int errcode = 0;
2719 struct tog_log_thread_args *a = arg;
2720 int done = 0;
2723 * Sync startup with main thread such that we begin our
2724 * work once view_input() has released the mutex.
2726 errcode = pthread_mutex_lock(&tog_mutex);
2727 if (errcode) {
2728 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2729 return (void *)err;
2732 err = block_signals_used_by_main_thread();
2733 if (err) {
2734 pthread_mutex_unlock(&tog_mutex);
2735 goto done;
2738 while (!done && !err && !tog_fatal_signal_received()) {
2739 errcode = pthread_mutex_unlock(&tog_mutex);
2740 if (errcode) {
2741 err = got_error_set_errno(errcode,
2742 "pthread_mutex_unlock");
2743 goto done;
2745 err = queue_commits(a);
2746 if (err) {
2747 if (err->code != GOT_ERR_ITER_COMPLETED)
2748 goto done;
2749 err = NULL;
2750 done = 1;
2751 } else if (a->commits_needed > 0 && !a->load_all)
2752 a->commits_needed--;
2754 errcode = pthread_mutex_lock(&tog_mutex);
2755 if (errcode) {
2756 err = got_error_set_errno(errcode,
2757 "pthread_mutex_lock");
2758 goto done;
2759 } else if (*a->quit)
2760 done = 1;
2761 else if (*a->first_displayed_entry == NULL) {
2762 *a->first_displayed_entry =
2763 TAILQ_FIRST(&a->commits->head);
2764 *a->selected_entry = *a->first_displayed_entry;
2767 errcode = pthread_cond_signal(&a->commit_loaded);
2768 if (errcode) {
2769 err = got_error_set_errno(errcode,
2770 "pthread_cond_signal");
2771 pthread_mutex_unlock(&tog_mutex);
2772 goto done;
2775 if (done)
2776 a->commits_needed = 0;
2777 else {
2778 if (a->commits_needed == 0 && !a->load_all) {
2779 errcode = pthread_cond_wait(&a->need_commits,
2780 &tog_mutex);
2781 if (errcode) {
2782 err = got_error_set_errno(errcode,
2783 "pthread_cond_wait");
2784 pthread_mutex_unlock(&tog_mutex);
2785 goto done;
2787 if (*a->quit)
2788 done = 1;
2792 a->log_complete = 1;
2793 errcode = pthread_mutex_unlock(&tog_mutex);
2794 if (errcode)
2795 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2796 done:
2797 if (err) {
2798 tog_thread_error = 1;
2799 pthread_cond_signal(&a->commit_loaded);
2801 return (void *)err;
2804 static const struct got_error *
2805 stop_log_thread(struct tog_log_view_state *s)
2807 const struct got_error *err = NULL, *thread_err = NULL;
2808 int errcode;
2810 if (s->thread) {
2811 s->quit = 1;
2812 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2813 if (errcode)
2814 return got_error_set_errno(errcode,
2815 "pthread_cond_signal");
2816 errcode = pthread_mutex_unlock(&tog_mutex);
2817 if (errcode)
2818 return got_error_set_errno(errcode,
2819 "pthread_mutex_unlock");
2820 errcode = pthread_join(s->thread, (void **)&thread_err);
2821 if (errcode)
2822 return got_error_set_errno(errcode, "pthread_join");
2823 errcode = pthread_mutex_lock(&tog_mutex);
2824 if (errcode)
2825 return got_error_set_errno(errcode,
2826 "pthread_mutex_lock");
2827 s->thread = NULL;
2830 if (s->thread_args.repo) {
2831 err = got_repo_close(s->thread_args.repo);
2832 s->thread_args.repo = NULL;
2835 if (s->thread_args.pack_fds) {
2836 const struct got_error *pack_err =
2837 got_repo_pack_fds_close(s->thread_args.pack_fds);
2838 if (err == NULL)
2839 err = pack_err;
2840 s->thread_args.pack_fds = NULL;
2843 if (s->thread_args.graph) {
2844 got_commit_graph_close(s->thread_args.graph);
2845 s->thread_args.graph = NULL;
2848 return err ? err : thread_err;
2851 static const struct got_error *
2852 close_log_view(struct tog_view *view)
2854 const struct got_error *err = NULL;
2855 struct tog_log_view_state *s = &view->state.log;
2856 int errcode;
2858 err = stop_log_thread(s);
2860 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2861 if (errcode && err == NULL)
2862 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2864 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2865 if (errcode && err == NULL)
2866 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2868 free_commits(&s->commits);
2869 free(s->in_repo_path);
2870 s->in_repo_path = NULL;
2871 free(s->start_id);
2872 s->start_id = NULL;
2873 free(s->head_ref_name);
2874 s->head_ref_name = NULL;
2875 return err;
2878 static const struct got_error *
2879 search_start_log_view(struct tog_view *view)
2881 struct tog_log_view_state *s = &view->state.log;
2883 s->matched_entry = NULL;
2884 s->search_entry = NULL;
2885 return NULL;
2888 static const struct got_error *
2889 search_next_log_view(struct tog_view *view)
2891 const struct got_error *err = NULL;
2892 struct tog_log_view_state *s = &view->state.log;
2893 struct commit_queue_entry *entry;
2895 /* Display progress update in log view. */
2896 show_log_view(view);
2897 update_panels();
2898 doupdate();
2900 if (s->search_entry) {
2901 int errcode, ch;
2902 errcode = pthread_mutex_unlock(&tog_mutex);
2903 if (errcode)
2904 return got_error_set_errno(errcode,
2905 "pthread_mutex_unlock");
2906 ch = wgetch(view->window);
2907 errcode = pthread_mutex_lock(&tog_mutex);
2908 if (errcode)
2909 return got_error_set_errno(errcode,
2910 "pthread_mutex_lock");
2911 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2912 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2913 return NULL;
2915 if (view->searching == TOG_SEARCH_FORWARD)
2916 entry = TAILQ_NEXT(s->search_entry, entry);
2917 else
2918 entry = TAILQ_PREV(s->search_entry,
2919 commit_queue_head, entry);
2920 } else if (s->matched_entry) {
2921 int matched_idx = s->matched_entry->idx;
2922 int selected_idx = s->selected_entry->idx;
2925 * If the user has moved the cursor after we hit a match,
2926 * the position from where we should continue searching
2927 * might have changed.
2929 if (view->searching == TOG_SEARCH_FORWARD) {
2930 if (matched_idx > selected_idx)
2931 entry = TAILQ_NEXT(s->selected_entry, entry);
2932 else
2933 entry = TAILQ_NEXT(s->matched_entry, entry);
2934 } else {
2935 if (matched_idx < selected_idx)
2936 entry = TAILQ_PREV(s->selected_entry,
2937 commit_queue_head, entry);
2938 else
2939 entry = TAILQ_PREV(s->matched_entry,
2940 commit_queue_head, entry);
2942 } else {
2943 entry = s->selected_entry;
2946 while (1) {
2947 int have_match = 0;
2949 if (entry == NULL) {
2950 if (s->thread_args.log_complete ||
2951 view->searching == TOG_SEARCH_BACKWARD) {
2952 view->search_next_done =
2953 (s->matched_entry == NULL ?
2954 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2955 s->search_entry = NULL;
2956 return NULL;
2959 * Poke the log thread for more commits and return,
2960 * allowing the main loop to make progress. Search
2961 * will resume at s->search_entry once we come back.
2963 s->thread_args.commits_needed++;
2964 return trigger_log_thread(view, 0);
2967 err = match_commit(&have_match, entry->id, entry->commit,
2968 &view->regex);
2969 if (err)
2970 break;
2971 if (have_match) {
2972 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2973 s->matched_entry = entry;
2974 break;
2977 s->search_entry = entry;
2978 if (view->searching == TOG_SEARCH_FORWARD)
2979 entry = TAILQ_NEXT(entry, entry);
2980 else
2981 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2984 if (s->matched_entry) {
2985 int cur = s->selected_entry->idx;
2986 while (cur < s->matched_entry->idx) {
2987 err = input_log_view(NULL, view, KEY_DOWN);
2988 if (err)
2989 return err;
2990 cur++;
2992 while (cur > s->matched_entry->idx) {
2993 err = input_log_view(NULL, view, KEY_UP);
2994 if (err)
2995 return err;
2996 cur--;
3000 s->search_entry = NULL;
3002 return NULL;
3005 static const struct got_error *
3006 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3007 struct got_repository *repo, const char *head_ref_name,
3008 const char *in_repo_path, int log_branches)
3010 const struct got_error *err = NULL;
3011 struct tog_log_view_state *s = &view->state.log;
3012 struct got_repository *thread_repo = NULL;
3013 struct got_commit_graph *thread_graph = NULL;
3014 int errcode;
3016 if (in_repo_path != s->in_repo_path) {
3017 free(s->in_repo_path);
3018 s->in_repo_path = strdup(in_repo_path);
3019 if (s->in_repo_path == NULL)
3020 return got_error_from_errno("strdup");
3023 /* The commit queue only contains commits being displayed. */
3024 TAILQ_INIT(&s->commits.head);
3025 s->commits.ncommits = 0;
3027 s->repo = repo;
3028 if (head_ref_name) {
3029 s->head_ref_name = strdup(head_ref_name);
3030 if (s->head_ref_name == NULL) {
3031 err = got_error_from_errno("strdup");
3032 goto done;
3035 s->start_id = got_object_id_dup(start_id);
3036 if (s->start_id == NULL) {
3037 err = got_error_from_errno("got_object_id_dup");
3038 goto done;
3040 s->log_branches = log_branches;
3042 STAILQ_INIT(&s->colors);
3043 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3044 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3045 get_color_value("TOG_COLOR_COMMIT"));
3046 if (err)
3047 goto done;
3048 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3049 get_color_value("TOG_COLOR_AUTHOR"));
3050 if (err) {
3051 free_colors(&s->colors);
3052 goto done;
3054 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3055 get_color_value("TOG_COLOR_DATE"));
3056 if (err) {
3057 free_colors(&s->colors);
3058 goto done;
3062 view->show = show_log_view;
3063 view->input = input_log_view;
3064 view->resize = resize_log_view;
3065 view->close = close_log_view;
3066 view->search_start = search_start_log_view;
3067 view->search_next = search_next_log_view;
3069 if (s->thread_args.pack_fds == NULL) {
3070 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3071 if (err)
3072 goto done;
3074 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3075 s->thread_args.pack_fds);
3076 if (err)
3077 goto done;
3078 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3079 !s->log_branches);
3080 if (err)
3081 goto done;
3082 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3083 s->repo, NULL, NULL);
3084 if (err)
3085 goto done;
3087 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3088 if (errcode) {
3089 err = got_error_set_errno(errcode, "pthread_cond_init");
3090 goto done;
3092 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3093 if (errcode) {
3094 err = got_error_set_errno(errcode, "pthread_cond_init");
3095 goto done;
3098 s->thread_args.commits_needed = view->nlines;
3099 s->thread_args.graph = thread_graph;
3100 s->thread_args.commits = &s->commits;
3101 s->thread_args.in_repo_path = s->in_repo_path;
3102 s->thread_args.start_id = s->start_id;
3103 s->thread_args.repo = thread_repo;
3104 s->thread_args.log_complete = 0;
3105 s->thread_args.quit = &s->quit;
3106 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3107 s->thread_args.selected_entry = &s->selected_entry;
3108 s->thread_args.searching = &view->searching;
3109 s->thread_args.search_next_done = &view->search_next_done;
3110 s->thread_args.regex = &view->regex;
3111 done:
3112 if (err)
3113 close_log_view(view);
3114 return err;
3117 static const struct got_error *
3118 show_log_view(struct tog_view *view)
3120 const struct got_error *err;
3121 struct tog_log_view_state *s = &view->state.log;
3123 if (s->thread == NULL) {
3124 int errcode = pthread_create(&s->thread, NULL, log_thread,
3125 &s->thread_args);
3126 if (errcode)
3127 return got_error_set_errno(errcode, "pthread_create");
3128 if (s->thread_args.commits_needed > 0) {
3129 err = trigger_log_thread(view, 1);
3130 if (err)
3131 return err;
3135 return draw_commits(view);
3138 static void
3139 log_move_cursor_up(struct tog_view *view, int page, int home)
3141 struct tog_log_view_state *s = &view->state.log;
3143 if (s->selected_entry->idx == 0)
3144 view->count = 0;
3145 if (s->first_displayed_entry == NULL)
3146 return;
3148 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3149 || home)
3150 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3152 if (!page && !home && s->selected > 0)
3153 --s->selected;
3154 else
3155 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3157 select_commit(s);
3158 return;
3161 static const struct got_error *
3162 log_move_cursor_down(struct tog_view *view, int page)
3164 struct tog_log_view_state *s = &view->state.log;
3165 struct commit_queue_entry *first;
3166 const struct got_error *err = NULL;
3168 first = s->first_displayed_entry;
3169 if (first == NULL) {
3170 view->count = 0;
3171 return NULL;
3174 if (s->thread_args.log_complete &&
3175 s->selected_entry->idx >= s->commits.ncommits - 1)
3176 return NULL;
3178 if (!page) {
3179 int eos = view->nlines - 2;
3181 if (view_is_hsplit_top(view))
3182 --eos; /* border consumes the last line */
3183 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3184 ++s->selected;
3185 else
3186 err = log_scroll_down(view, 1);
3187 } else if (s->thread_args.load_all) {
3188 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3189 s->selected += MIN(s->last_displayed_entry->idx -
3190 s->selected_entry->idx, page + 1);
3191 else
3192 err = log_scroll_down(view, MIN(page,
3193 s->commits.ncommits - s->selected_entry->idx - 1));
3194 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3195 } else {
3196 err = log_scroll_down(view, page);
3197 if (err)
3198 return err;
3199 if (first == s->first_displayed_entry && s->selected <
3200 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
3201 s->selected = MIN(s->commits.ncommits - 1, page);
3204 if (err)
3205 return err;
3208 * We might necessarily overshoot in horizontal
3209 * splits; if so, select the last displayed commit.
3211 s->selected = MIN(s->selected,
3212 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3214 select_commit(s);
3216 if (s->thread_args.log_complete &&
3217 s->selected_entry->idx == s->commits.ncommits - 1)
3218 view->count = 0;
3220 return NULL;
3223 static void
3224 view_get_split(struct tog_view *view, int *y, int *x)
3226 *x = 0;
3227 *y = 0;
3229 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3230 if (view->child && view->child->resized_y)
3231 *y = view->child->resized_y;
3232 else if (view->resized_y)
3233 *y = view->resized_y;
3234 else
3235 *y = view_split_begin_y(view->lines);
3236 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3237 if (view->child && view->child->resized_x)
3238 *x = view->child->resized_x;
3239 else if (view->resized_x)
3240 *x = view->resized_x;
3241 else
3242 *x = view_split_begin_x(view->begin_x);
3246 /* Split view horizontally at y and offset view->state->selected line. */
3247 static const struct got_error *
3248 view_init_hsplit(struct tog_view *view, int y)
3250 const struct got_error *err = NULL;
3252 view->nlines = y;
3253 view->ncols = COLS;
3254 err = view_resize(view);
3255 if (err)
3256 return err;
3258 err = offset_selection_down(view);
3260 return err;
3263 static const struct got_error *
3264 log_goto_line(struct tog_view *view, int nlines)
3266 const struct got_error *err = NULL;
3267 struct tog_log_view_state *s = &view->state.log;
3268 int g, idx = s->selected_entry->idx;
3270 g = view->gline;
3271 view->gline = 0;
3273 if (g >= s->first_displayed_entry->idx + 1 &&
3274 g <= s->last_displayed_entry->idx + 1 &&
3275 g - s->first_displayed_entry->idx - 1 < nlines) {
3276 s->selected = g - s->first_displayed_entry->idx - 1;
3277 select_commit(s);
3278 return NULL;
3281 if (idx + 1 < g) {
3282 err = log_move_cursor_down(view, g - idx - 1);
3283 if (!err && g > s->selected_entry->idx + 1)
3284 err = log_move_cursor_down(view,
3285 g - s->first_displayed_entry->idx - 1);
3286 if (err)
3287 return err;
3288 } else if (idx + 1 > g)
3289 log_move_cursor_up(view, idx - g + 1, 0);
3291 if (g < nlines && s->first_displayed_entry->idx == 0)
3292 s->selected = g - 1;
3294 select_commit(s);
3295 return NULL;
3299 static const struct got_error *
3300 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3302 const struct got_error *err = NULL;
3303 struct tog_log_view_state *s = &view->state.log;
3304 struct commit_queue_entry *entry;
3305 int eos, n, nscroll;
3307 if (s->thread_args.load_all) {
3308 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3309 s->thread_args.load_all = 0;
3310 else if (s->thread_args.log_complete) {
3311 err = log_move_cursor_down(view, s->commits.ncommits);
3312 s->thread_args.load_all = 0;
3314 return err;
3317 eos = nscroll = view->nlines - 1;
3318 if (view_is_hsplit_top(view))
3319 --eos; /* border */
3321 if (view->gline)
3322 return log_goto_line(view, eos);
3324 switch (ch) {
3325 case 'q':
3326 s->quit = 1;
3327 break;
3328 case '0':
3329 view->x = 0;
3330 break;
3331 case '$':
3332 view->x = MAX(view->maxx - view->ncols / 2, 0);
3333 view->count = 0;
3334 break;
3335 case KEY_RIGHT:
3336 case 'l':
3337 if (view->x + view->ncols / 2 < view->maxx)
3338 view->x += 2; /* move two columns right */
3339 else
3340 view->count = 0;
3341 break;
3342 case KEY_LEFT:
3343 case 'h':
3344 view->x -= MIN(view->x, 2); /* move two columns back */
3345 if (view->x <= 0)
3346 view->count = 0;
3347 break;
3348 case 'k':
3349 case KEY_UP:
3350 case '<':
3351 case ',':
3352 case CTRL('p'):
3353 log_move_cursor_up(view, 0, 0);
3354 break;
3355 case 'g':
3356 case KEY_HOME:
3357 log_move_cursor_up(view, 0, 1);
3358 view->count = 0;
3359 break;
3360 case CTRL('u'):
3361 case 'u':
3362 nscroll /= 2;
3363 /* FALL THROUGH */
3364 case KEY_PPAGE:
3365 case CTRL('b'):
3366 case 'b':
3367 log_move_cursor_up(view, nscroll, 0);
3368 break;
3369 case 'j':
3370 case KEY_DOWN:
3371 case '>':
3372 case '.':
3373 case CTRL('n'):
3374 err = log_move_cursor_down(view, 0);
3375 break;
3376 case '@':
3377 s->use_committer = !s->use_committer;
3378 break;
3379 case 'G':
3380 case KEY_END: {
3381 /* We don't know yet how many commits, so we're forced to
3382 * traverse them all. */
3383 view->count = 0;
3384 if (!s->thread_args.log_complete) {
3385 s->thread_args.load_all = 1;
3386 return trigger_log_thread(view, 0);
3389 s->selected = 0;
3390 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3391 for (n = 0; n < eos; n++) {
3392 if (entry == NULL)
3393 break;
3394 s->first_displayed_entry = entry;
3395 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3397 if (n > 0)
3398 s->selected = n - 1;
3399 select_commit(s);
3400 break;
3402 case CTRL('d'):
3403 case 'd':
3404 nscroll /= 2;
3405 /* FALL THROUGH */
3406 case KEY_NPAGE:
3407 case CTRL('f'):
3408 case 'f':
3409 case ' ':
3410 err = log_move_cursor_down(view, nscroll);
3411 break;
3412 case KEY_RESIZE:
3413 if (s->selected > view->nlines - 2)
3414 s->selected = view->nlines - 2;
3415 if (s->selected > s->commits.ncommits - 1)
3416 s->selected = s->commits.ncommits - 1;
3417 select_commit(s);
3418 if (s->commits.ncommits < view->nlines - 1 &&
3419 !s->thread_args.log_complete) {
3420 s->thread_args.commits_needed += (view->nlines - 1) -
3421 s->commits.ncommits;
3422 err = trigger_log_thread(view, 1);
3424 break;
3425 case KEY_ENTER:
3426 case '\r':
3427 view->count = 0;
3428 if (s->selected_entry == NULL)
3429 break;
3430 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3431 break;
3432 case 'T':
3433 view->count = 0;
3434 if (s->selected_entry == NULL)
3435 break;
3436 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3437 break;
3438 case KEY_BACKSPACE:
3439 case CTRL('l'):
3440 case 'B':
3441 view->count = 0;
3442 if (ch == KEY_BACKSPACE &&
3443 got_path_is_root_dir(s->in_repo_path))
3444 break;
3445 err = stop_log_thread(s);
3446 if (err)
3447 return err;
3448 if (ch == KEY_BACKSPACE) {
3449 char *parent_path;
3450 err = got_path_dirname(&parent_path, s->in_repo_path);
3451 if (err)
3452 return err;
3453 free(s->in_repo_path);
3454 s->in_repo_path = parent_path;
3455 s->thread_args.in_repo_path = s->in_repo_path;
3456 } else if (ch == CTRL('l')) {
3457 struct got_object_id *start_id;
3458 err = got_repo_match_object_id(&start_id, NULL,
3459 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3460 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3461 if (err)
3462 return err;
3463 free(s->start_id);
3464 s->start_id = start_id;
3465 s->thread_args.start_id = s->start_id;
3466 } else /* 'B' */
3467 s->log_branches = !s->log_branches;
3469 if (s->thread_args.pack_fds == NULL) {
3470 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3471 if (err)
3472 return err;
3474 err = got_repo_open(&s->thread_args.repo,
3475 got_repo_get_path(s->repo), NULL,
3476 s->thread_args.pack_fds);
3477 if (err)
3478 return err;
3479 tog_free_refs();
3480 err = tog_load_refs(s->repo, 0);
3481 if (err)
3482 return err;
3483 err = got_commit_graph_open(&s->thread_args.graph,
3484 s->in_repo_path, !s->log_branches);
3485 if (err)
3486 return err;
3487 err = got_commit_graph_iter_start(s->thread_args.graph,
3488 s->start_id, s->repo, NULL, NULL);
3489 if (err)
3490 return err;
3491 free_commits(&s->commits);
3492 s->first_displayed_entry = NULL;
3493 s->last_displayed_entry = NULL;
3494 s->selected_entry = NULL;
3495 s->selected = 0;
3496 s->thread_args.log_complete = 0;
3497 s->quit = 0;
3498 s->thread_args.commits_needed = view->lines;
3499 s->matched_entry = NULL;
3500 s->search_entry = NULL;
3501 view->offset = 0;
3502 break;
3503 case 'R':
3504 view->count = 0;
3505 err = view_request_new(new_view, view, TOG_VIEW_REF);
3506 break;
3507 default:
3508 view->count = 0;
3509 break;
3512 return err;
3515 static const struct got_error *
3516 apply_unveil(const char *repo_path, const char *worktree_path)
3518 const struct got_error *error;
3520 #ifdef PROFILE
3521 if (unveil("gmon.out", "rwc") != 0)
3522 return got_error_from_errno2("unveil", "gmon.out");
3523 #endif
3524 if (repo_path && unveil(repo_path, "r") != 0)
3525 return got_error_from_errno2("unveil", repo_path);
3527 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3528 return got_error_from_errno2("unveil", worktree_path);
3530 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3531 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3533 error = got_privsep_unveil_exec_helpers();
3534 if (error != NULL)
3535 return error;
3537 if (unveil(NULL, NULL) != 0)
3538 return got_error_from_errno("unveil");
3540 return NULL;
3543 static void
3544 init_curses(void)
3547 * Override default signal handlers before starting ncurses.
3548 * This should prevent ncurses from installing its own
3549 * broken cleanup() signal handler.
3551 signal(SIGWINCH, tog_sigwinch);
3552 signal(SIGPIPE, tog_sigpipe);
3553 signal(SIGCONT, tog_sigcont);
3554 signal(SIGINT, tog_sigint);
3555 signal(SIGTERM, tog_sigterm);
3557 initscr();
3558 cbreak();
3559 halfdelay(1); /* Do fast refresh while initial view is loading. */
3560 noecho();
3561 nonl();
3562 intrflush(stdscr, FALSE);
3563 keypad(stdscr, TRUE);
3564 curs_set(0);
3565 if (getenv("TOG_COLORS") != NULL) {
3566 start_color();
3567 use_default_colors();
3571 static const struct got_error *
3572 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3573 struct got_repository *repo, struct got_worktree *worktree)
3575 const struct got_error *err = NULL;
3577 if (argc == 0) {
3578 *in_repo_path = strdup("/");
3579 if (*in_repo_path == NULL)
3580 return got_error_from_errno("strdup");
3581 return NULL;
3584 if (worktree) {
3585 const char *prefix = got_worktree_get_path_prefix(worktree);
3586 char *p;
3588 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3589 if (err)
3590 return err;
3591 if (asprintf(in_repo_path, "%s%s%s", prefix,
3592 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3593 p) == -1) {
3594 err = got_error_from_errno("asprintf");
3595 *in_repo_path = NULL;
3597 free(p);
3598 } else
3599 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3601 return err;
3604 static const struct got_error *
3605 cmd_log(int argc, char *argv[])
3607 const struct got_error *error;
3608 struct got_repository *repo = NULL;
3609 struct got_worktree *worktree = NULL;
3610 struct got_object_id *start_id = NULL;
3611 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3612 char *start_commit = NULL, *label = NULL;
3613 struct got_reference *ref = NULL;
3614 const char *head_ref_name = NULL;
3615 int ch, log_branches = 0;
3616 struct tog_view *view;
3617 int *pack_fds = NULL;
3619 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3620 switch (ch) {
3621 case 'b':
3622 log_branches = 1;
3623 break;
3624 case 'c':
3625 start_commit = optarg;
3626 break;
3627 case 'r':
3628 repo_path = realpath(optarg, NULL);
3629 if (repo_path == NULL)
3630 return got_error_from_errno2("realpath",
3631 optarg);
3632 break;
3633 default:
3634 usage_log();
3635 /* NOTREACHED */
3639 argc -= optind;
3640 argv += optind;
3642 if (argc > 1)
3643 usage_log();
3645 error = got_repo_pack_fds_open(&pack_fds);
3646 if (error != NULL)
3647 goto done;
3649 if (repo_path == NULL) {
3650 cwd = getcwd(NULL, 0);
3651 if (cwd == NULL)
3652 return got_error_from_errno("getcwd");
3653 error = got_worktree_open(&worktree, cwd);
3654 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3655 goto done;
3656 if (worktree)
3657 repo_path =
3658 strdup(got_worktree_get_repo_path(worktree));
3659 else
3660 repo_path = strdup(cwd);
3661 if (repo_path == NULL) {
3662 error = got_error_from_errno("strdup");
3663 goto done;
3667 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3668 if (error != NULL)
3669 goto done;
3671 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3672 repo, worktree);
3673 if (error)
3674 goto done;
3676 init_curses();
3678 error = apply_unveil(got_repo_get_path(repo),
3679 worktree ? got_worktree_get_root_path(worktree) : NULL);
3680 if (error)
3681 goto done;
3683 /* already loaded by tog_log_with_path()? */
3684 if (TAILQ_EMPTY(&tog_refs)) {
3685 error = tog_load_refs(repo, 0);
3686 if (error)
3687 goto done;
3690 if (start_commit == NULL) {
3691 error = got_repo_match_object_id(&start_id, &label,
3692 worktree ? got_worktree_get_head_ref_name(worktree) :
3693 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3694 if (error)
3695 goto done;
3696 head_ref_name = label;
3697 } else {
3698 error = got_ref_open(&ref, repo, start_commit, 0);
3699 if (error == NULL)
3700 head_ref_name = got_ref_get_name(ref);
3701 else if (error->code != GOT_ERR_NOT_REF)
3702 goto done;
3703 error = got_repo_match_object_id(&start_id, NULL,
3704 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3705 if (error)
3706 goto done;
3709 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3710 if (view == NULL) {
3711 error = got_error_from_errno("view_open");
3712 goto done;
3714 error = open_log_view(view, start_id, repo, head_ref_name,
3715 in_repo_path, log_branches);
3716 if (error)
3717 goto done;
3718 if (worktree) {
3719 /* Release work tree lock. */
3720 got_worktree_close(worktree);
3721 worktree = NULL;
3723 error = view_loop(view);
3724 done:
3725 free(in_repo_path);
3726 free(repo_path);
3727 free(cwd);
3728 free(start_id);
3729 free(label);
3730 if (ref)
3731 got_ref_close(ref);
3732 if (repo) {
3733 const struct got_error *close_err = got_repo_close(repo);
3734 if (error == NULL)
3735 error = close_err;
3737 if (worktree)
3738 got_worktree_close(worktree);
3739 if (pack_fds) {
3740 const struct got_error *pack_err =
3741 got_repo_pack_fds_close(pack_fds);
3742 if (error == NULL)
3743 error = pack_err;
3745 tog_free_refs();
3746 return error;
3749 __dead static void
3750 usage_diff(void)
3752 endwin();
3753 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3754 "[-w] object1 object2\n", getprogname());
3755 exit(1);
3758 static int
3759 match_line(const char *line, regex_t *regex, size_t nmatch,
3760 regmatch_t *regmatch)
3762 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3765 static struct tog_color *
3766 match_color(struct tog_colors *colors, const char *line)
3768 struct tog_color *tc = NULL;
3770 STAILQ_FOREACH(tc, colors, entry) {
3771 if (match_line(line, &tc->regex, 0, NULL))
3772 return tc;
3775 return NULL;
3778 static const struct got_error *
3779 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3780 WINDOW *window, int skipcol, regmatch_t *regmatch)
3782 const struct got_error *err = NULL;
3783 char *exstr = NULL;
3784 wchar_t *wline = NULL;
3785 int rme, rms, n, width, scrollx;
3786 int width0 = 0, width1 = 0, width2 = 0;
3787 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3789 *wtotal = 0;
3791 rms = regmatch->rm_so;
3792 rme = regmatch->rm_eo;
3794 err = expand_tab(&exstr, line);
3795 if (err)
3796 return err;
3798 /* Split the line into 3 segments, according to match offsets. */
3799 seg0 = strndup(exstr, rms);
3800 if (seg0 == NULL) {
3801 err = got_error_from_errno("strndup");
3802 goto done;
3804 seg1 = strndup(exstr + rms, rme - rms);
3805 if (seg1 == NULL) {
3806 err = got_error_from_errno("strndup");
3807 goto done;
3809 seg2 = strdup(exstr + rme);
3810 if (seg2 == NULL) {
3811 err = got_error_from_errno("strndup");
3812 goto done;
3815 /* draw up to matched token if we haven't scrolled past it */
3816 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3817 col_tab_align, 1);
3818 if (err)
3819 goto done;
3820 n = MAX(width0 - skipcol, 0);
3821 if (n) {
3822 free(wline);
3823 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3824 wlimit, col_tab_align, 1);
3825 if (err)
3826 goto done;
3827 waddwstr(window, &wline[scrollx]);
3828 wlimit -= width;
3829 *wtotal += width;
3832 if (wlimit > 0) {
3833 int i = 0, w = 0;
3834 size_t wlen;
3836 free(wline);
3837 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3838 col_tab_align, 1);
3839 if (err)
3840 goto done;
3841 wlen = wcslen(wline);
3842 while (i < wlen) {
3843 width = wcwidth(wline[i]);
3844 if (width == -1) {
3845 /* should not happen, tabs are expanded */
3846 err = got_error(GOT_ERR_RANGE);
3847 goto done;
3849 if (width0 + w + width > skipcol)
3850 break;
3851 w += width;
3852 i++;
3854 /* draw (visible part of) matched token (if scrolled into it) */
3855 if (width1 - w > 0) {
3856 wattron(window, A_STANDOUT);
3857 waddwstr(window, &wline[i]);
3858 wattroff(window, A_STANDOUT);
3859 wlimit -= (width1 - w);
3860 *wtotal += (width1 - w);
3864 if (wlimit > 0) { /* draw rest of line */
3865 free(wline);
3866 if (skipcol > width0 + width1) {
3867 err = format_line(&wline, &width2, &scrollx, seg2,
3868 skipcol - (width0 + width1), wlimit,
3869 col_tab_align, 1);
3870 if (err)
3871 goto done;
3872 waddwstr(window, &wline[scrollx]);
3873 } else {
3874 err = format_line(&wline, &width2, NULL, seg2, 0,
3875 wlimit, col_tab_align, 1);
3876 if (err)
3877 goto done;
3878 waddwstr(window, wline);
3880 *wtotal += width2;
3882 done:
3883 free(wline);
3884 free(exstr);
3885 free(seg0);
3886 free(seg1);
3887 free(seg2);
3888 return err;
3891 static int
3892 gotoline(struct tog_view *view, int *lineno, int *nprinted)
3894 FILE *f = NULL;
3895 int *eof, *first, *selected;
3897 if (view->type == TOG_VIEW_DIFF) {
3898 struct tog_diff_view_state *s = &view->state.diff;
3900 first = &s->first_displayed_line;
3901 selected = first;
3902 eof = &s->eof;
3903 f = s->f;
3904 } else if (view->type == TOG_VIEW_BLAME) {
3905 struct tog_blame_view_state *s = &view->state.blame;
3907 first = &s->first_displayed_line;
3908 selected = &s->selected_line;
3909 eof = &s->eof;
3910 f = s->blame.f;
3911 } else
3912 return 0;
3914 /* Center gline in the middle of the page like vi(1). */
3915 if (*lineno < view->gline - (view->nlines - 3) / 2)
3916 return 0;
3917 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
3918 rewind(f);
3919 *eof = 0;
3920 *first = 1;
3921 *lineno = 0;
3922 *nprinted = 0;
3923 return 0;
3926 *selected = view->gline <= (view->nlines - 3) / 2 ?
3927 view->gline : (view->nlines - 3) / 2 + 1;
3928 view->gline = 0;
3930 return 1;
3933 static const struct got_error *
3934 draw_file(struct tog_view *view, const char *header)
3936 struct tog_diff_view_state *s = &view->state.diff;
3937 regmatch_t *regmatch = &view->regmatch;
3938 const struct got_error *err;
3939 int nprinted = 0;
3940 char *line;
3941 size_t linesize = 0;
3942 ssize_t linelen;
3943 struct tog_color *tc;
3944 wchar_t *wline;
3945 int width;
3946 int max_lines = view->nlines;
3947 int nlines = s->nlines;
3948 off_t line_offset;
3949 attr_t attr;
3951 s->lineno = s->first_displayed_line - 1;
3952 line_offset = s->lines[s->first_displayed_line - 1].offset;
3953 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3954 return got_error_from_errno("fseek");
3956 werase(view->window);
3958 if (view->gline > s->nlines - 1)
3959 view->gline = s->nlines - 1;
3961 if (header) {
3962 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
3963 1 : view->gline - (view->nlines - 3) / 2 :
3964 s->lineno + s->selected_line;
3966 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
3967 return got_error_from_errno("asprintf");
3968 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3969 0, 0);
3970 free(line);
3971 if (err)
3972 return err;
3974 if (view_needs_focus_indication(view))
3975 wstandout(view->window);
3976 waddwstr(view->window, wline);
3977 free(wline);
3978 wline = NULL;
3979 if (view_needs_focus_indication(view))
3980 wstandend(view->window);
3981 if (width <= view->ncols - 1)
3982 waddch(view->window, '\n');
3984 if (max_lines <= 1)
3985 return NULL;
3986 max_lines--;
3989 s->eof = 0;
3990 view->maxx = 0;
3991 line = NULL;
3992 while (max_lines > 0 && nprinted < max_lines) {
3993 linelen = getline(&line, &linesize, s->f);
3994 if (linelen == -1) {
3995 if (feof(s->f)) {
3996 s->eof = 1;
3997 break;
3999 free(line);
4000 return got_ferror(s->f, GOT_ERR_IO);
4003 attr = 0;
4004 if (++s->lineno < s->first_displayed_line)
4005 continue;
4006 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4007 continue;
4008 if (s->lineno == view->hiline)
4009 attr = A_STANDOUT;
4011 /* Set view->maxx based on full line length. */
4012 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4013 view->x ? 1 : 0);
4014 if (err) {
4015 free(line);
4016 return err;
4018 view->maxx = MAX(view->maxx, width);
4019 free(wline);
4020 wline = NULL;
4022 tc = match_color(&s->colors, line);
4023 if (tc)
4024 attr |= COLOR_PAIR(tc->colorpair);
4025 if (attr)
4026 wattron(view->window, attr);
4027 if (s->first_displayed_line + nprinted == s->matched_line &&
4028 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4029 err = add_matched_line(&width, line, view->ncols, 0,
4030 view->window, view->x, regmatch);
4031 if (err) {
4032 free(line);
4033 return err;
4035 } else {
4036 int skip;
4037 err = format_line(&wline, &width, &skip, line,
4038 view->x, view->ncols, 0, view->x ? 1 : 0);
4039 if (err) {
4040 free(line);
4041 return err;
4043 waddwstr(view->window, &wline[skip]);
4044 free(wline);
4045 wline = NULL;
4047 if (s->lineno == view->hiline) {
4048 /* highlight full gline length */
4049 while (width++ < view->ncols)
4050 waddch(view->window, ' ');
4051 } else {
4052 if (width <= view->ncols - 1)
4053 waddch(view->window, '\n');
4055 if (attr)
4056 wattroff(view->window, attr);
4057 if (++nprinted == 1)
4058 s->first_displayed_line = s->lineno;
4060 free(line);
4061 if (nprinted >= 1)
4062 s->last_displayed_line = s->first_displayed_line +
4063 (nprinted - 1);
4064 else
4065 s->last_displayed_line = s->first_displayed_line;
4067 view_border(view);
4069 if (s->eof) {
4070 while (nprinted < view->nlines) {
4071 waddch(view->window, '\n');
4072 nprinted++;
4075 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4076 view->ncols, 0, 0);
4077 if (err) {
4078 return err;
4081 wstandout(view->window);
4082 waddwstr(view->window, wline);
4083 free(wline);
4084 wline = NULL;
4085 wstandend(view->window);
4088 return NULL;
4091 static char *
4092 get_datestr(time_t *time, char *datebuf)
4094 struct tm mytm, *tm;
4095 char *p, *s;
4097 tm = gmtime_r(time, &mytm);
4098 if (tm == NULL)
4099 return NULL;
4100 s = asctime_r(tm, datebuf);
4101 if (s == NULL)
4102 return NULL;
4103 p = strchr(s, '\n');
4104 if (p)
4105 *p = '\0';
4106 return s;
4109 static const struct got_error *
4110 get_changed_paths(struct got_pathlist_head *paths,
4111 struct got_commit_object *commit, struct got_repository *repo)
4113 const struct got_error *err = NULL;
4114 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4115 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4116 struct got_object_qid *qid;
4118 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4119 if (qid != NULL) {
4120 struct got_commit_object *pcommit;
4121 err = got_object_open_as_commit(&pcommit, repo,
4122 &qid->id);
4123 if (err)
4124 return err;
4126 tree_id1 = got_object_id_dup(
4127 got_object_commit_get_tree_id(pcommit));
4128 if (tree_id1 == NULL) {
4129 got_object_commit_close(pcommit);
4130 return got_error_from_errno("got_object_id_dup");
4132 got_object_commit_close(pcommit);
4136 if (tree_id1) {
4137 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4138 if (err)
4139 goto done;
4142 tree_id2 = got_object_commit_get_tree_id(commit);
4143 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4144 if (err)
4145 goto done;
4147 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4148 got_diff_tree_collect_changed_paths, paths, 0);
4149 done:
4150 if (tree1)
4151 got_object_tree_close(tree1);
4152 if (tree2)
4153 got_object_tree_close(tree2);
4154 free(tree_id1);
4155 return err;
4158 static const struct got_error *
4159 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4160 off_t off, uint8_t type)
4162 struct got_diff_line *p;
4164 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4165 if (p == NULL)
4166 return got_error_from_errno("reallocarray");
4167 *lines = p;
4168 (*lines)[*nlines].offset = off;
4169 (*lines)[*nlines].type = type;
4170 (*nlines)++;
4172 return NULL;
4175 static const struct got_error *
4176 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4177 struct got_object_id *commit_id, struct got_reflist_head *refs,
4178 struct got_repository *repo, FILE *outfile)
4180 const struct got_error *err = NULL;
4181 char datebuf[26], *datestr;
4182 struct got_commit_object *commit;
4183 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4184 time_t committer_time;
4185 const char *author, *committer;
4186 char *refs_str = NULL;
4187 struct got_pathlist_head changed_paths;
4188 struct got_pathlist_entry *pe;
4189 off_t outoff = 0;
4190 int n;
4192 TAILQ_INIT(&changed_paths);
4194 if (refs) {
4195 err = build_refs_str(&refs_str, refs, commit_id, repo);
4196 if (err)
4197 return err;
4200 err = got_object_open_as_commit(&commit, repo, commit_id);
4201 if (err)
4202 return err;
4204 err = got_object_id_str(&id_str, commit_id);
4205 if (err) {
4206 err = got_error_from_errno("got_object_id_str");
4207 goto done;
4210 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4211 if (err)
4212 goto done;
4214 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4215 refs_str ? refs_str : "", refs_str ? ")" : "");
4216 if (n < 0) {
4217 err = got_error_from_errno("fprintf");
4218 goto done;
4220 outoff += n;
4221 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4222 if (err)
4223 goto done;
4225 n = fprintf(outfile, "from: %s\n",
4226 got_object_commit_get_author(commit));
4227 if (n < 0) {
4228 err = got_error_from_errno("fprintf");
4229 goto done;
4231 outoff += n;
4232 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4233 if (err)
4234 goto done;
4236 committer_time = got_object_commit_get_committer_time(commit);
4237 datestr = get_datestr(&committer_time, datebuf);
4238 if (datestr) {
4239 n = fprintf(outfile, "date: %s UTC\n", datestr);
4240 if (n < 0) {
4241 err = got_error_from_errno("fprintf");
4242 goto done;
4244 outoff += n;
4245 err = add_line_metadata(lines, nlines, outoff,
4246 GOT_DIFF_LINE_DATE);
4247 if (err)
4248 goto done;
4250 author = got_object_commit_get_author(commit);
4251 committer = got_object_commit_get_committer(commit);
4252 if (strcmp(author, committer) != 0) {
4253 n = fprintf(outfile, "via: %s\n", committer);
4254 if (n < 0) {
4255 err = got_error_from_errno("fprintf");
4256 goto done;
4258 outoff += n;
4259 err = add_line_metadata(lines, nlines, outoff,
4260 GOT_DIFF_LINE_AUTHOR);
4261 if (err)
4262 goto done;
4264 if (got_object_commit_get_nparents(commit) > 1) {
4265 const struct got_object_id_queue *parent_ids;
4266 struct got_object_qid *qid;
4267 int pn = 1;
4268 parent_ids = got_object_commit_get_parent_ids(commit);
4269 STAILQ_FOREACH(qid, parent_ids, entry) {
4270 err = got_object_id_str(&id_str, &qid->id);
4271 if (err)
4272 goto done;
4273 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4274 if (n < 0) {
4275 err = got_error_from_errno("fprintf");
4276 goto done;
4278 outoff += n;
4279 err = add_line_metadata(lines, nlines, outoff,
4280 GOT_DIFF_LINE_META);
4281 if (err)
4282 goto done;
4283 free(id_str);
4284 id_str = NULL;
4288 err = got_object_commit_get_logmsg(&logmsg, commit);
4289 if (err)
4290 goto done;
4291 s = logmsg;
4292 while ((line = strsep(&s, "\n")) != NULL) {
4293 n = fprintf(outfile, "%s\n", line);
4294 if (n < 0) {
4295 err = got_error_from_errno("fprintf");
4296 goto done;
4298 outoff += n;
4299 err = add_line_metadata(lines, nlines, outoff,
4300 GOT_DIFF_LINE_LOGMSG);
4301 if (err)
4302 goto done;
4305 err = get_changed_paths(&changed_paths, commit, repo);
4306 if (err)
4307 goto done;
4308 TAILQ_FOREACH(pe, &changed_paths, entry) {
4309 struct got_diff_changed_path *cp = pe->data;
4310 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4311 if (n < 0) {
4312 err = got_error_from_errno("fprintf");
4313 goto done;
4315 outoff += n;
4316 err = add_line_metadata(lines, nlines, outoff,
4317 GOT_DIFF_LINE_CHANGES);
4318 if (err)
4319 goto done;
4320 free((char *)pe->path);
4321 free(pe->data);
4324 fputc('\n', outfile);
4325 outoff++;
4326 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4327 done:
4328 got_pathlist_free(&changed_paths);
4329 free(id_str);
4330 free(logmsg);
4331 free(refs_str);
4332 got_object_commit_close(commit);
4333 if (err) {
4334 free(*lines);
4335 *lines = NULL;
4336 *nlines = 0;
4338 return err;
4341 static const struct got_error *
4342 create_diff(struct tog_diff_view_state *s)
4344 const struct got_error *err = NULL;
4345 FILE *f = NULL;
4346 int obj_type;
4348 free(s->lines);
4349 s->lines = malloc(sizeof(*s->lines));
4350 if (s->lines == NULL)
4351 return got_error_from_errno("malloc");
4352 s->nlines = 0;
4354 f = got_opentemp();
4355 if (f == NULL) {
4356 err = got_error_from_errno("got_opentemp");
4357 goto done;
4359 if (s->f && fclose(s->f) == EOF) {
4360 err = got_error_from_errno("fclose");
4361 goto done;
4363 s->f = f;
4365 if (s->id1)
4366 err = got_object_get_type(&obj_type, s->repo, s->id1);
4367 else
4368 err = got_object_get_type(&obj_type, s->repo, s->id2);
4369 if (err)
4370 goto done;
4372 switch (obj_type) {
4373 case GOT_OBJ_TYPE_BLOB:
4374 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4375 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4376 s->label1, s->label2, tog_diff_algo, s->diff_context,
4377 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4378 break;
4379 case GOT_OBJ_TYPE_TREE:
4380 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4381 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4382 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4383 s->force_text_diff, s->repo, s->f);
4384 break;
4385 case GOT_OBJ_TYPE_COMMIT: {
4386 const struct got_object_id_queue *parent_ids;
4387 struct got_object_qid *pid;
4388 struct got_commit_object *commit2;
4389 struct got_reflist_head *refs;
4391 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4392 if (err)
4393 goto done;
4394 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4395 /* Show commit info if we're diffing to a parent/root commit. */
4396 if (s->id1 == NULL) {
4397 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4398 refs, s->repo, s->f);
4399 if (err)
4400 goto done;
4401 } else {
4402 parent_ids = got_object_commit_get_parent_ids(commit2);
4403 STAILQ_FOREACH(pid, parent_ids, entry) {
4404 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4405 err = write_commit_info(&s->lines,
4406 &s->nlines, s->id2, refs, s->repo,
4407 s->f);
4408 if (err)
4409 goto done;
4410 break;
4414 got_object_commit_close(commit2);
4416 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4417 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4418 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4419 s->force_text_diff, s->repo, s->f);
4420 break;
4422 default:
4423 err = got_error(GOT_ERR_OBJ_TYPE);
4424 break;
4426 done:
4427 if (s->f && fflush(s->f) != 0 && err == NULL)
4428 err = got_error_from_errno("fflush");
4429 return err;
4432 static void
4433 diff_view_indicate_progress(struct tog_view *view)
4435 mvwaddstr(view->window, 0, 0, "diffing...");
4436 update_panels();
4437 doupdate();
4440 static const struct got_error *
4441 search_start_diff_view(struct tog_view *view)
4443 struct tog_diff_view_state *s = &view->state.diff;
4445 s->matched_line = 0;
4446 return NULL;
4449 static const struct got_error *
4450 search_next_diff_view(struct tog_view *view)
4452 struct tog_diff_view_state *s = &view->state.diff;
4453 const struct got_error *err = NULL;
4454 int lineno;
4455 char *line = NULL;
4456 size_t linesize = 0;
4457 ssize_t linelen;
4459 if (!view->searching) {
4460 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4461 return NULL;
4464 if (s->matched_line) {
4465 if (view->searching == TOG_SEARCH_FORWARD)
4466 lineno = s->matched_line + 1;
4467 else
4468 lineno = s->matched_line - 1;
4469 } else
4470 lineno = s->first_displayed_line;
4472 while (1) {
4473 off_t offset;
4475 if (lineno <= 0 || lineno > s->nlines) {
4476 if (s->matched_line == 0) {
4477 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4478 break;
4481 if (view->searching == TOG_SEARCH_FORWARD)
4482 lineno = 1;
4483 else
4484 lineno = s->nlines;
4487 offset = s->lines[lineno - 1].offset;
4488 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4489 free(line);
4490 return got_error_from_errno("fseeko");
4492 linelen = getline(&line, &linesize, s->f);
4493 if (linelen != -1) {
4494 char *exstr;
4495 err = expand_tab(&exstr, line);
4496 if (err)
4497 break;
4498 if (match_line(exstr, &view->regex, 1,
4499 &view->regmatch)) {
4500 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4501 s->matched_line = lineno;
4502 free(exstr);
4503 break;
4505 free(exstr);
4507 if (view->searching == TOG_SEARCH_FORWARD)
4508 lineno++;
4509 else
4510 lineno--;
4512 free(line);
4514 if (s->matched_line) {
4515 s->first_displayed_line = s->matched_line;
4516 s->selected_line = 1;
4519 return err;
4522 static const struct got_error *
4523 close_diff_view(struct tog_view *view)
4525 const struct got_error *err = NULL;
4526 struct tog_diff_view_state *s = &view->state.diff;
4528 free(s->id1);
4529 s->id1 = NULL;
4530 free(s->id2);
4531 s->id2 = NULL;
4532 if (s->f && fclose(s->f) == EOF)
4533 err = got_error_from_errno("fclose");
4534 s->f = NULL;
4535 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4536 err = got_error_from_errno("fclose");
4537 s->f1 = NULL;
4538 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4539 err = got_error_from_errno("fclose");
4540 s->f2 = NULL;
4541 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4542 err = got_error_from_errno("close");
4543 s->fd1 = -1;
4544 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4545 err = got_error_from_errno("close");
4546 s->fd2 = -1;
4547 free_colors(&s->colors);
4548 free(s->lines);
4549 s->lines = NULL;
4550 s->nlines = 0;
4551 return err;
4554 static const struct got_error *
4555 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4556 struct got_object_id *id2, const char *label1, const char *label2,
4557 int diff_context, int ignore_whitespace, int force_text_diff,
4558 struct tog_view *parent_view, struct got_repository *repo)
4560 const struct got_error *err;
4561 struct tog_diff_view_state *s = &view->state.diff;
4563 memset(s, 0, sizeof(*s));
4564 s->fd1 = -1;
4565 s->fd2 = -1;
4567 if (id1 != NULL && id2 != NULL) {
4568 int type1, type2;
4569 err = got_object_get_type(&type1, repo, id1);
4570 if (err)
4571 return err;
4572 err = got_object_get_type(&type2, repo, id2);
4573 if (err)
4574 return err;
4576 if (type1 != type2)
4577 return got_error(GOT_ERR_OBJ_TYPE);
4579 s->first_displayed_line = 1;
4580 s->last_displayed_line = view->nlines;
4581 s->selected_line = 1;
4582 s->repo = repo;
4583 s->id1 = id1;
4584 s->id2 = id2;
4585 s->label1 = label1;
4586 s->label2 = label2;
4588 if (id1) {
4589 s->id1 = got_object_id_dup(id1);
4590 if (s->id1 == NULL)
4591 return got_error_from_errno("got_object_id_dup");
4592 } else
4593 s->id1 = NULL;
4595 s->id2 = got_object_id_dup(id2);
4596 if (s->id2 == NULL) {
4597 err = got_error_from_errno("got_object_id_dup");
4598 goto done;
4601 s->f1 = got_opentemp();
4602 if (s->f1 == NULL) {
4603 err = got_error_from_errno("got_opentemp");
4604 goto done;
4607 s->f2 = got_opentemp();
4608 if (s->f2 == NULL) {
4609 err = got_error_from_errno("got_opentemp");
4610 goto done;
4613 s->fd1 = got_opentempfd();
4614 if (s->fd1 == -1) {
4615 err = got_error_from_errno("got_opentempfd");
4616 goto done;
4619 s->fd2 = got_opentempfd();
4620 if (s->fd2 == -1) {
4621 err = got_error_from_errno("got_opentempfd");
4622 goto done;
4625 s->first_displayed_line = 1;
4626 s->last_displayed_line = view->nlines;
4627 s->diff_context = diff_context;
4628 s->ignore_whitespace = ignore_whitespace;
4629 s->force_text_diff = force_text_diff;
4630 s->parent_view = parent_view;
4631 s->repo = repo;
4633 STAILQ_INIT(&s->colors);
4634 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4635 err = add_color(&s->colors,
4636 "^-", TOG_COLOR_DIFF_MINUS,
4637 get_color_value("TOG_COLOR_DIFF_MINUS"));
4638 if (err)
4639 goto done;
4640 err = add_color(&s->colors, "^\\+",
4641 TOG_COLOR_DIFF_PLUS,
4642 get_color_value("TOG_COLOR_DIFF_PLUS"));
4643 if (err)
4644 goto done;
4645 err = add_color(&s->colors,
4646 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4647 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4648 if (err)
4649 goto done;
4651 err = add_color(&s->colors,
4652 "^(commit [0-9a-f]|parent [0-9]|"
4653 "(blob|file|tree|commit) [-+] |"
4654 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4655 get_color_value("TOG_COLOR_DIFF_META"));
4656 if (err)
4657 goto done;
4659 err = add_color(&s->colors,
4660 "^(from|via): ", TOG_COLOR_AUTHOR,
4661 get_color_value("TOG_COLOR_AUTHOR"));
4662 if (err)
4663 goto done;
4665 err = add_color(&s->colors,
4666 "^date: ", TOG_COLOR_DATE,
4667 get_color_value("TOG_COLOR_DATE"));
4668 if (err)
4669 goto done;
4672 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4673 view_is_splitscreen(view))
4674 show_log_view(parent_view); /* draw border */
4675 diff_view_indicate_progress(view);
4677 err = create_diff(s);
4679 view->show = show_diff_view;
4680 view->input = input_diff_view;
4681 view->reset = reset_diff_view;
4682 view->close = close_diff_view;
4683 view->search_start = search_start_diff_view;
4684 view->search_next = search_next_diff_view;
4685 done:
4686 if (err)
4687 close_diff_view(view);
4688 return err;
4691 static const struct got_error *
4692 show_diff_view(struct tog_view *view)
4694 const struct got_error *err;
4695 struct tog_diff_view_state *s = &view->state.diff;
4696 char *id_str1 = NULL, *id_str2, *header;
4697 const char *label1, *label2;
4699 if (s->id1) {
4700 err = got_object_id_str(&id_str1, s->id1);
4701 if (err)
4702 return err;
4703 label1 = s->label1 ? : id_str1;
4704 } else
4705 label1 = "/dev/null";
4707 err = got_object_id_str(&id_str2, s->id2);
4708 if (err)
4709 return err;
4710 label2 = s->label2 ? : id_str2;
4712 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4713 err = got_error_from_errno("asprintf");
4714 free(id_str1);
4715 free(id_str2);
4716 return err;
4718 free(id_str1);
4719 free(id_str2);
4721 err = draw_file(view, header);
4722 free(header);
4723 return err;
4726 static const struct got_error *
4727 set_selected_commit(struct tog_diff_view_state *s,
4728 struct commit_queue_entry *entry)
4730 const struct got_error *err;
4731 const struct got_object_id_queue *parent_ids;
4732 struct got_commit_object *selected_commit;
4733 struct got_object_qid *pid;
4735 free(s->id2);
4736 s->id2 = got_object_id_dup(entry->id);
4737 if (s->id2 == NULL)
4738 return got_error_from_errno("got_object_id_dup");
4740 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4741 if (err)
4742 return err;
4743 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4744 free(s->id1);
4745 pid = STAILQ_FIRST(parent_ids);
4746 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4747 got_object_commit_close(selected_commit);
4748 return NULL;
4751 static const struct got_error *
4752 reset_diff_view(struct tog_view *view)
4754 struct tog_diff_view_state *s = &view->state.diff;
4756 view->count = 0;
4757 wclear(view->window);
4758 s->first_displayed_line = 1;
4759 s->last_displayed_line = view->nlines;
4760 s->matched_line = 0;
4761 diff_view_indicate_progress(view);
4762 return create_diff(s);
4765 static void
4766 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4768 int start, i;
4770 i = start = s->first_displayed_line - 1;
4772 while (s->lines[i].type != type) {
4773 if (i == 0)
4774 i = s->nlines - 1;
4775 if (--i == start)
4776 return; /* do nothing, requested type not in file */
4779 s->selected_line = 1;
4780 s->first_displayed_line = i;
4783 static void
4784 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4786 int start, i;
4788 i = start = s->first_displayed_line + 1;
4790 while (s->lines[i].type != type) {
4791 if (i == s->nlines - 1)
4792 i = 0;
4793 if (++i == start)
4794 return; /* do nothing, requested type not in file */
4797 s->selected_line = 1;
4798 s->first_displayed_line = i;
4801 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4802 int, int, int);
4803 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4804 int, int);
4806 static const struct got_error *
4807 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4809 const struct got_error *err = NULL;
4810 struct tog_diff_view_state *s = &view->state.diff;
4811 struct tog_log_view_state *ls;
4812 struct commit_queue_entry *old_selected_entry;
4813 char *line = NULL;
4814 size_t linesize = 0;
4815 ssize_t linelen;
4816 int i, nscroll = view->nlines - 1, up = 0;
4818 s->lineno = s->first_displayed_line - 1 + s->selected_line;
4820 switch (ch) {
4821 case '0':
4822 view->x = 0;
4823 break;
4824 case '$':
4825 view->x = MAX(view->maxx - view->ncols / 3, 0);
4826 view->count = 0;
4827 break;
4828 case KEY_RIGHT:
4829 case 'l':
4830 if (view->x + view->ncols / 3 < view->maxx)
4831 view->x += 2; /* move two columns right */
4832 else
4833 view->count = 0;
4834 break;
4835 case KEY_LEFT:
4836 case 'h':
4837 view->x -= MIN(view->x, 2); /* move two columns back */
4838 if (view->x <= 0)
4839 view->count = 0;
4840 break;
4841 case 'a':
4842 case 'w':
4843 if (ch == 'a')
4844 s->force_text_diff = !s->force_text_diff;
4845 if (ch == 'w')
4846 s->ignore_whitespace = !s->ignore_whitespace;
4847 err = reset_diff_view(view);
4848 break;
4849 case 'g':
4850 case KEY_HOME:
4851 s->first_displayed_line = 1;
4852 view->count = 0;
4853 break;
4854 case 'G':
4855 case KEY_END:
4856 view->count = 0;
4857 if (s->eof)
4858 break;
4860 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4861 s->eof = 1;
4862 break;
4863 case 'k':
4864 case KEY_UP:
4865 case CTRL('p'):
4866 if (s->first_displayed_line > 1)
4867 s->first_displayed_line--;
4868 else
4869 view->count = 0;
4870 break;
4871 case CTRL('u'):
4872 case 'u':
4873 nscroll /= 2;
4874 /* FALL THROUGH */
4875 case KEY_PPAGE:
4876 case CTRL('b'):
4877 case 'b':
4878 if (s->first_displayed_line == 1) {
4879 view->count = 0;
4880 break;
4882 i = 0;
4883 while (i++ < nscroll && s->first_displayed_line > 1)
4884 s->first_displayed_line--;
4885 break;
4886 case 'j':
4887 case KEY_DOWN:
4888 case CTRL('n'):
4889 if (!s->eof)
4890 s->first_displayed_line++;
4891 else
4892 view->count = 0;
4893 break;
4894 case CTRL('d'):
4895 case 'd':
4896 nscroll /= 2;
4897 /* FALL THROUGH */
4898 case KEY_NPAGE:
4899 case CTRL('f'):
4900 case 'f':
4901 case ' ':
4902 if (s->eof) {
4903 view->count = 0;
4904 break;
4906 i = 0;
4907 while (!s->eof && i++ < nscroll) {
4908 linelen = getline(&line, &linesize, s->f);
4909 s->first_displayed_line++;
4910 if (linelen == -1) {
4911 if (feof(s->f)) {
4912 s->eof = 1;
4913 } else
4914 err = got_ferror(s->f, GOT_ERR_IO);
4915 break;
4918 free(line);
4919 break;
4920 case '(':
4921 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
4922 break;
4923 case ')':
4924 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
4925 break;
4926 case '{':
4927 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
4928 break;
4929 case '}':
4930 diff_next_index(s, GOT_DIFF_LINE_HUNK);
4931 break;
4932 case '[':
4933 if (s->diff_context > 0) {
4934 s->diff_context--;
4935 s->matched_line = 0;
4936 diff_view_indicate_progress(view);
4937 err = create_diff(s);
4938 if (s->first_displayed_line + view->nlines - 1 >
4939 s->nlines) {
4940 s->first_displayed_line = 1;
4941 s->last_displayed_line = view->nlines;
4943 } else
4944 view->count = 0;
4945 break;
4946 case ']':
4947 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4948 s->diff_context++;
4949 s->matched_line = 0;
4950 diff_view_indicate_progress(view);
4951 err = create_diff(s);
4952 } else
4953 view->count = 0;
4954 break;
4955 case '<':
4956 case ',':
4957 case 'K':
4958 up = 1;
4959 /* FALL THROUGH */
4960 case '>':
4961 case '.':
4962 case 'J':
4963 if (s->parent_view == NULL) {
4964 view->count = 0;
4965 break;
4967 s->parent_view->count = view->count;
4969 if (s->parent_view->type == TOG_VIEW_LOG) {
4970 ls = &s->parent_view->state.log;
4971 old_selected_entry = ls->selected_entry;
4973 err = input_log_view(NULL, s->parent_view,
4974 up ? KEY_UP : KEY_DOWN);
4975 if (err)
4976 break;
4977 view->count = s->parent_view->count;
4979 if (old_selected_entry == ls->selected_entry)
4980 break;
4982 err = set_selected_commit(s, ls->selected_entry);
4983 if (err)
4984 break;
4985 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4986 struct tog_blame_view_state *bs;
4987 struct got_object_id *id, *prev_id;
4989 bs = &s->parent_view->state.blame;
4990 prev_id = get_annotation_for_line(bs->blame.lines,
4991 bs->blame.nlines, bs->last_diffed_line);
4993 err = input_blame_view(&view, s->parent_view,
4994 up ? KEY_UP : KEY_DOWN);
4995 if (err)
4996 break;
4997 view->count = s->parent_view->count;
4999 if (prev_id == NULL)
5000 break;
5001 id = get_selected_commit_id(bs->blame.lines,
5002 bs->blame.nlines, bs->first_displayed_line,
5003 bs->selected_line);
5004 if (id == NULL)
5005 break;
5007 if (!got_object_id_cmp(prev_id, id))
5008 break;
5010 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5011 if (err)
5012 break;
5014 s->first_displayed_line = 1;
5015 s->last_displayed_line = view->nlines;
5016 s->matched_line = 0;
5017 view->x = 0;
5019 diff_view_indicate_progress(view);
5020 err = create_diff(s);
5021 break;
5022 default:
5023 view->count = 0;
5024 break;
5027 return err;
5030 static const struct got_error *
5031 cmd_diff(int argc, char *argv[])
5033 const struct got_error *error = NULL;
5034 struct got_repository *repo = NULL;
5035 struct got_worktree *worktree = NULL;
5036 struct got_object_id *id1 = NULL, *id2 = NULL;
5037 char *repo_path = NULL, *cwd = NULL;
5038 char *id_str1 = NULL, *id_str2 = NULL;
5039 char *label1 = NULL, *label2 = NULL;
5040 int diff_context = 3, ignore_whitespace = 0;
5041 int ch, force_text_diff = 0;
5042 const char *errstr;
5043 struct tog_view *view;
5044 int *pack_fds = NULL;
5046 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5047 switch (ch) {
5048 case 'a':
5049 force_text_diff = 1;
5050 break;
5051 case 'C':
5052 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5053 &errstr);
5054 if (errstr != NULL)
5055 errx(1, "number of context lines is %s: %s",
5056 errstr, errstr);
5057 break;
5058 case 'r':
5059 repo_path = realpath(optarg, NULL);
5060 if (repo_path == NULL)
5061 return got_error_from_errno2("realpath",
5062 optarg);
5063 got_path_strip_trailing_slashes(repo_path);
5064 break;
5065 case 'w':
5066 ignore_whitespace = 1;
5067 break;
5068 default:
5069 usage_diff();
5070 /* NOTREACHED */
5074 argc -= optind;
5075 argv += optind;
5077 if (argc == 0) {
5078 usage_diff(); /* TODO show local worktree changes */
5079 } else if (argc == 2) {
5080 id_str1 = argv[0];
5081 id_str2 = argv[1];
5082 } else
5083 usage_diff();
5085 error = got_repo_pack_fds_open(&pack_fds);
5086 if (error)
5087 goto done;
5089 if (repo_path == NULL) {
5090 cwd = getcwd(NULL, 0);
5091 if (cwd == NULL)
5092 return got_error_from_errno("getcwd");
5093 error = got_worktree_open(&worktree, cwd);
5094 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5095 goto done;
5096 if (worktree)
5097 repo_path =
5098 strdup(got_worktree_get_repo_path(worktree));
5099 else
5100 repo_path = strdup(cwd);
5101 if (repo_path == NULL) {
5102 error = got_error_from_errno("strdup");
5103 goto done;
5107 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5108 if (error)
5109 goto done;
5111 init_curses();
5113 error = apply_unveil(got_repo_get_path(repo), NULL);
5114 if (error)
5115 goto done;
5117 error = tog_load_refs(repo, 0);
5118 if (error)
5119 goto done;
5121 error = got_repo_match_object_id(&id1, &label1, id_str1,
5122 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5123 if (error)
5124 goto done;
5126 error = got_repo_match_object_id(&id2, &label2, id_str2,
5127 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5128 if (error)
5129 goto done;
5131 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5132 if (view == NULL) {
5133 error = got_error_from_errno("view_open");
5134 goto done;
5136 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5137 ignore_whitespace, force_text_diff, NULL, repo);
5138 if (error)
5139 goto done;
5140 error = view_loop(view);
5141 done:
5142 free(label1);
5143 free(label2);
5144 free(repo_path);
5145 free(cwd);
5146 if (repo) {
5147 const struct got_error *close_err = got_repo_close(repo);
5148 if (error == NULL)
5149 error = close_err;
5151 if (worktree)
5152 got_worktree_close(worktree);
5153 if (pack_fds) {
5154 const struct got_error *pack_err =
5155 got_repo_pack_fds_close(pack_fds);
5156 if (error == NULL)
5157 error = pack_err;
5159 tog_free_refs();
5160 return error;
5163 __dead static void
5164 usage_blame(void)
5166 endwin();
5167 fprintf(stderr,
5168 "usage: %s blame [-c commit] [-r repository-path] path\n",
5169 getprogname());
5170 exit(1);
5173 struct tog_blame_line {
5174 int annotated;
5175 struct got_object_id *id;
5178 static const struct got_error *
5179 draw_blame(struct tog_view *view)
5181 struct tog_blame_view_state *s = &view->state.blame;
5182 struct tog_blame *blame = &s->blame;
5183 regmatch_t *regmatch = &view->regmatch;
5184 const struct got_error *err;
5185 int lineno = 0, nprinted = 0;
5186 char *line = NULL;
5187 size_t linesize = 0;
5188 ssize_t linelen;
5189 wchar_t *wline;
5190 int width;
5191 struct tog_blame_line *blame_line;
5192 struct got_object_id *prev_id = NULL;
5193 char *id_str;
5194 struct tog_color *tc;
5196 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5197 if (err)
5198 return err;
5200 rewind(blame->f);
5201 werase(view->window);
5203 if (asprintf(&line, "commit %s", id_str) == -1) {
5204 err = got_error_from_errno("asprintf");
5205 free(id_str);
5206 return err;
5209 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5210 free(line);
5211 line = NULL;
5212 if (err)
5213 return err;
5214 if (view_needs_focus_indication(view))
5215 wstandout(view->window);
5216 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5217 if (tc)
5218 wattr_on(view->window,
5219 COLOR_PAIR(tc->colorpair), NULL);
5220 waddwstr(view->window, wline);
5221 if (tc)
5222 wattr_off(view->window,
5223 COLOR_PAIR(tc->colorpair), NULL);
5224 if (view_needs_focus_indication(view))
5225 wstandend(view->window);
5226 free(wline);
5227 wline = NULL;
5228 if (width < view->ncols - 1)
5229 waddch(view->window, '\n');
5231 if (view->gline > blame->nlines)
5232 view->gline = blame->nlines;
5234 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5235 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5236 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5237 free(id_str);
5238 return got_error_from_errno("asprintf");
5240 free(id_str);
5241 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5242 free(line);
5243 line = NULL;
5244 if (err)
5245 return err;
5246 waddwstr(view->window, wline);
5247 free(wline);
5248 wline = NULL;
5249 if (width < view->ncols - 1)
5250 waddch(view->window, '\n');
5252 s->eof = 0;
5253 view->maxx = 0;
5254 while (nprinted < view->nlines - 2) {
5255 linelen = getline(&line, &linesize, blame->f);
5256 if (linelen == -1) {
5257 if (feof(blame->f)) {
5258 s->eof = 1;
5259 break;
5261 free(line);
5262 return got_ferror(blame->f, GOT_ERR_IO);
5264 if (++lineno < s->first_displayed_line)
5265 continue;
5266 if (view->gline && !gotoline(view, &lineno, &nprinted))
5267 continue;
5269 /* Set view->maxx based on full line length. */
5270 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5271 if (err) {
5272 free(line);
5273 return err;
5275 free(wline);
5276 wline = NULL;
5277 view->maxx = MAX(view->maxx, width);
5279 if (nprinted == s->selected_line - 1)
5280 wstandout(view->window);
5282 if (blame->nlines > 0) {
5283 blame_line = &blame->lines[lineno - 1];
5284 if (blame_line->annotated && prev_id &&
5285 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5286 !(nprinted == s->selected_line - 1)) {
5287 waddstr(view->window, " ");
5288 } else if (blame_line->annotated) {
5289 char *id_str;
5290 err = got_object_id_str(&id_str,
5291 blame_line->id);
5292 if (err) {
5293 free(line);
5294 return err;
5296 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5297 if (tc)
5298 wattr_on(view->window,
5299 COLOR_PAIR(tc->colorpair), NULL);
5300 wprintw(view->window, "%.8s", id_str);
5301 if (tc)
5302 wattr_off(view->window,
5303 COLOR_PAIR(tc->colorpair), NULL);
5304 free(id_str);
5305 prev_id = blame_line->id;
5306 } else {
5307 waddstr(view->window, "........");
5308 prev_id = NULL;
5310 } else {
5311 waddstr(view->window, "........");
5312 prev_id = NULL;
5315 if (nprinted == s->selected_line - 1)
5316 wstandend(view->window);
5317 waddstr(view->window, " ");
5319 if (view->ncols <= 9) {
5320 width = 9;
5321 } else if (s->first_displayed_line + nprinted ==
5322 s->matched_line &&
5323 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5324 err = add_matched_line(&width, line, view->ncols - 9, 9,
5325 view->window, view->x, regmatch);
5326 if (err) {
5327 free(line);
5328 return err;
5330 width += 9;
5331 } else {
5332 int skip;
5333 err = format_line(&wline, &width, &skip, line,
5334 view->x, view->ncols - 9, 9, 1);
5335 if (err) {
5336 free(line);
5337 return err;
5339 waddwstr(view->window, &wline[skip]);
5340 width += 9;
5341 free(wline);
5342 wline = NULL;
5345 if (width <= view->ncols - 1)
5346 waddch(view->window, '\n');
5347 if (++nprinted == 1)
5348 s->first_displayed_line = lineno;
5350 free(line);
5351 s->last_displayed_line = lineno;
5353 view_border(view);
5355 return NULL;
5358 static const struct got_error *
5359 blame_cb(void *arg, int nlines, int lineno,
5360 struct got_commit_object *commit, struct got_object_id *id)
5362 const struct got_error *err = NULL;
5363 struct tog_blame_cb_args *a = arg;
5364 struct tog_blame_line *line;
5365 int errcode;
5367 if (nlines != a->nlines ||
5368 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5369 return got_error(GOT_ERR_RANGE);
5371 errcode = pthread_mutex_lock(&tog_mutex);
5372 if (errcode)
5373 return got_error_set_errno(errcode, "pthread_mutex_lock");
5375 if (*a->quit) { /* user has quit the blame view */
5376 err = got_error(GOT_ERR_ITER_COMPLETED);
5377 goto done;
5380 if (lineno == -1)
5381 goto done; /* no change in this commit */
5383 line = &a->lines[lineno - 1];
5384 if (line->annotated)
5385 goto done;
5387 line->id = got_object_id_dup(id);
5388 if (line->id == NULL) {
5389 err = got_error_from_errno("got_object_id_dup");
5390 goto done;
5392 line->annotated = 1;
5393 done:
5394 errcode = pthread_mutex_unlock(&tog_mutex);
5395 if (errcode)
5396 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5397 return err;
5400 static void *
5401 blame_thread(void *arg)
5403 const struct got_error *err, *close_err;
5404 struct tog_blame_thread_args *ta = arg;
5405 struct tog_blame_cb_args *a = ta->cb_args;
5406 int errcode, fd1 = -1, fd2 = -1;
5407 FILE *f1 = NULL, *f2 = NULL;
5409 fd1 = got_opentempfd();
5410 if (fd1 == -1)
5411 return (void *)got_error_from_errno("got_opentempfd");
5413 fd2 = got_opentempfd();
5414 if (fd2 == -1) {
5415 err = got_error_from_errno("got_opentempfd");
5416 goto done;
5419 f1 = got_opentemp();
5420 if (f1 == NULL) {
5421 err = (void *)got_error_from_errno("got_opentemp");
5422 goto done;
5424 f2 = got_opentemp();
5425 if (f2 == NULL) {
5426 err = (void *)got_error_from_errno("got_opentemp");
5427 goto done;
5430 err = block_signals_used_by_main_thread();
5431 if (err)
5432 goto done;
5434 err = got_blame(ta->path, a->commit_id, ta->repo,
5435 tog_diff_algo, blame_cb, ta->cb_args,
5436 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5437 if (err && err->code == GOT_ERR_CANCELLED)
5438 err = NULL;
5440 errcode = pthread_mutex_lock(&tog_mutex);
5441 if (errcode) {
5442 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5443 goto done;
5446 close_err = got_repo_close(ta->repo);
5447 if (err == NULL)
5448 err = close_err;
5449 ta->repo = NULL;
5450 *ta->complete = 1;
5452 errcode = pthread_mutex_unlock(&tog_mutex);
5453 if (errcode && err == NULL)
5454 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5456 done:
5457 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5458 err = got_error_from_errno("close");
5459 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5460 err = got_error_from_errno("close");
5461 if (f1 && fclose(f1) == EOF && err == NULL)
5462 err = got_error_from_errno("fclose");
5463 if (f2 && fclose(f2) == EOF && err == NULL)
5464 err = got_error_from_errno("fclose");
5466 return (void *)err;
5469 static struct got_object_id *
5470 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5471 int first_displayed_line, int selected_line)
5473 struct tog_blame_line *line;
5475 if (nlines <= 0)
5476 return NULL;
5478 line = &lines[first_displayed_line - 1 + selected_line - 1];
5479 if (!line->annotated)
5480 return NULL;
5482 return line->id;
5485 static struct got_object_id *
5486 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5487 int lineno)
5489 struct tog_blame_line *line;
5491 if (nlines <= 0 || lineno >= nlines)
5492 return NULL;
5494 line = &lines[lineno - 1];
5495 if (!line->annotated)
5496 return NULL;
5498 return line->id;
5501 static const struct got_error *
5502 stop_blame(struct tog_blame *blame)
5504 const struct got_error *err = NULL;
5505 int i;
5507 if (blame->thread) {
5508 int errcode;
5509 errcode = pthread_mutex_unlock(&tog_mutex);
5510 if (errcode)
5511 return got_error_set_errno(errcode,
5512 "pthread_mutex_unlock");
5513 errcode = pthread_join(blame->thread, (void **)&err);
5514 if (errcode)
5515 return got_error_set_errno(errcode, "pthread_join");
5516 errcode = pthread_mutex_lock(&tog_mutex);
5517 if (errcode)
5518 return got_error_set_errno(errcode,
5519 "pthread_mutex_lock");
5520 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5521 err = NULL;
5522 blame->thread = NULL;
5524 if (blame->thread_args.repo) {
5525 const struct got_error *close_err;
5526 close_err = got_repo_close(blame->thread_args.repo);
5527 if (err == NULL)
5528 err = close_err;
5529 blame->thread_args.repo = NULL;
5531 if (blame->f) {
5532 if (fclose(blame->f) == EOF && err == NULL)
5533 err = got_error_from_errno("fclose");
5534 blame->f = NULL;
5536 if (blame->lines) {
5537 for (i = 0; i < blame->nlines; i++)
5538 free(blame->lines[i].id);
5539 free(blame->lines);
5540 blame->lines = NULL;
5542 free(blame->cb_args.commit_id);
5543 blame->cb_args.commit_id = NULL;
5544 if (blame->pack_fds) {
5545 const struct got_error *pack_err =
5546 got_repo_pack_fds_close(blame->pack_fds);
5547 if (err == NULL)
5548 err = pack_err;
5549 blame->pack_fds = NULL;
5551 return err;
5554 static const struct got_error *
5555 cancel_blame_view(void *arg)
5557 const struct got_error *err = NULL;
5558 int *done = arg;
5559 int errcode;
5561 errcode = pthread_mutex_lock(&tog_mutex);
5562 if (errcode)
5563 return got_error_set_errno(errcode,
5564 "pthread_mutex_unlock");
5566 if (*done)
5567 err = got_error(GOT_ERR_CANCELLED);
5569 errcode = pthread_mutex_unlock(&tog_mutex);
5570 if (errcode)
5571 return got_error_set_errno(errcode,
5572 "pthread_mutex_lock");
5574 return err;
5577 static const struct got_error *
5578 run_blame(struct tog_view *view)
5580 struct tog_blame_view_state *s = &view->state.blame;
5581 struct tog_blame *blame = &s->blame;
5582 const struct got_error *err = NULL;
5583 struct got_commit_object *commit = NULL;
5584 struct got_blob_object *blob = NULL;
5585 struct got_repository *thread_repo = NULL;
5586 struct got_object_id *obj_id = NULL;
5587 int obj_type, fd = -1;
5588 int *pack_fds = NULL;
5590 err = got_object_open_as_commit(&commit, s->repo,
5591 &s->blamed_commit->id);
5592 if (err)
5593 return err;
5595 fd = got_opentempfd();
5596 if (fd == -1) {
5597 err = got_error_from_errno("got_opentempfd");
5598 goto done;
5601 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5602 if (err)
5603 goto done;
5605 err = got_object_get_type(&obj_type, s->repo, obj_id);
5606 if (err)
5607 goto done;
5609 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5610 err = got_error(GOT_ERR_OBJ_TYPE);
5611 goto done;
5614 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5615 if (err)
5616 goto done;
5617 blame->f = got_opentemp();
5618 if (blame->f == NULL) {
5619 err = got_error_from_errno("got_opentemp");
5620 goto done;
5622 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5623 &blame->line_offsets, blame->f, blob);
5624 if (err)
5625 goto done;
5626 if (blame->nlines == 0) {
5627 s->blame_complete = 1;
5628 goto done;
5631 /* Don't include \n at EOF in the blame line count. */
5632 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5633 blame->nlines--;
5635 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5636 if (blame->lines == NULL) {
5637 err = got_error_from_errno("calloc");
5638 goto done;
5641 err = got_repo_pack_fds_open(&pack_fds);
5642 if (err)
5643 goto done;
5644 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5645 pack_fds);
5646 if (err)
5647 goto done;
5649 blame->pack_fds = pack_fds;
5650 blame->cb_args.view = view;
5651 blame->cb_args.lines = blame->lines;
5652 blame->cb_args.nlines = blame->nlines;
5653 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5654 if (blame->cb_args.commit_id == NULL) {
5655 err = got_error_from_errno("got_object_id_dup");
5656 goto done;
5658 blame->cb_args.quit = &s->done;
5660 blame->thread_args.path = s->path;
5661 blame->thread_args.repo = thread_repo;
5662 blame->thread_args.cb_args = &blame->cb_args;
5663 blame->thread_args.complete = &s->blame_complete;
5664 blame->thread_args.cancel_cb = cancel_blame_view;
5665 blame->thread_args.cancel_arg = &s->done;
5666 s->blame_complete = 0;
5668 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5669 s->first_displayed_line = 1;
5670 s->last_displayed_line = view->nlines;
5671 s->selected_line = 1;
5673 s->matched_line = 0;
5675 done:
5676 if (commit)
5677 got_object_commit_close(commit);
5678 if (fd != -1 && close(fd) == -1 && err == NULL)
5679 err = got_error_from_errno("close");
5680 if (blob)
5681 got_object_blob_close(blob);
5682 free(obj_id);
5683 if (err)
5684 stop_blame(blame);
5685 return err;
5688 static const struct got_error *
5689 open_blame_view(struct tog_view *view, char *path,
5690 struct got_object_id *commit_id, struct got_repository *repo)
5692 const struct got_error *err = NULL;
5693 struct tog_blame_view_state *s = &view->state.blame;
5695 STAILQ_INIT(&s->blamed_commits);
5697 s->path = strdup(path);
5698 if (s->path == NULL)
5699 return got_error_from_errno("strdup");
5701 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5702 if (err) {
5703 free(s->path);
5704 return err;
5707 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5708 s->first_displayed_line = 1;
5709 s->last_displayed_line = view->nlines;
5710 s->selected_line = 1;
5711 s->blame_complete = 0;
5712 s->repo = repo;
5713 s->commit_id = commit_id;
5714 memset(&s->blame, 0, sizeof(s->blame));
5716 STAILQ_INIT(&s->colors);
5717 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5718 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5719 get_color_value("TOG_COLOR_COMMIT"));
5720 if (err)
5721 return err;
5724 view->show = show_blame_view;
5725 view->input = input_blame_view;
5726 view->reset = reset_blame_view;
5727 view->close = close_blame_view;
5728 view->search_start = search_start_blame_view;
5729 view->search_next = search_next_blame_view;
5731 return run_blame(view);
5734 static const struct got_error *
5735 close_blame_view(struct tog_view *view)
5737 const struct got_error *err = NULL;
5738 struct tog_blame_view_state *s = &view->state.blame;
5740 if (s->blame.thread)
5741 err = stop_blame(&s->blame);
5743 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5744 struct got_object_qid *blamed_commit;
5745 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5746 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5747 got_object_qid_free(blamed_commit);
5750 free(s->path);
5751 free_colors(&s->colors);
5752 return err;
5755 static const struct got_error *
5756 search_start_blame_view(struct tog_view *view)
5758 struct tog_blame_view_state *s = &view->state.blame;
5760 s->matched_line = 0;
5761 return NULL;
5764 static const struct got_error *
5765 search_next_blame_view(struct tog_view *view)
5767 struct tog_blame_view_state *s = &view->state.blame;
5768 const struct got_error *err = NULL;
5769 int lineno;
5770 char *line = NULL;
5771 size_t linesize = 0;
5772 ssize_t linelen;
5774 if (!view->searching) {
5775 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5776 return NULL;
5779 if (s->matched_line) {
5780 if (view->searching == TOG_SEARCH_FORWARD)
5781 lineno = s->matched_line + 1;
5782 else
5783 lineno = s->matched_line - 1;
5784 } else
5785 lineno = s->first_displayed_line - 1 + s->selected_line;
5787 while (1) {
5788 off_t offset;
5790 if (lineno <= 0 || lineno > s->blame.nlines) {
5791 if (s->matched_line == 0) {
5792 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5793 break;
5796 if (view->searching == TOG_SEARCH_FORWARD)
5797 lineno = 1;
5798 else
5799 lineno = s->blame.nlines;
5802 offset = s->blame.line_offsets[lineno - 1];
5803 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5804 free(line);
5805 return got_error_from_errno("fseeko");
5807 linelen = getline(&line, &linesize, s->blame.f);
5808 if (linelen != -1) {
5809 char *exstr;
5810 err = expand_tab(&exstr, line);
5811 if (err)
5812 break;
5813 if (match_line(exstr, &view->regex, 1,
5814 &view->regmatch)) {
5815 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5816 s->matched_line = lineno;
5817 free(exstr);
5818 break;
5820 free(exstr);
5822 if (view->searching == TOG_SEARCH_FORWARD)
5823 lineno++;
5824 else
5825 lineno--;
5827 free(line);
5829 if (s->matched_line) {
5830 s->first_displayed_line = s->matched_line;
5831 s->selected_line = 1;
5834 return err;
5837 static const struct got_error *
5838 show_blame_view(struct tog_view *view)
5840 const struct got_error *err = NULL;
5841 struct tog_blame_view_state *s = &view->state.blame;
5842 int errcode;
5844 if (s->blame.thread == NULL && !s->blame_complete) {
5845 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5846 &s->blame.thread_args);
5847 if (errcode)
5848 return got_error_set_errno(errcode, "pthread_create");
5850 halfdelay(1); /* fast refresh while annotating */
5853 if (s->blame_complete)
5854 halfdelay(10); /* disable fast refresh */
5856 err = draw_blame(view);
5858 view_border(view);
5859 return err;
5862 static const struct got_error *
5863 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5864 struct got_repository *repo, struct got_object_id *id)
5866 struct tog_view *log_view;
5867 const struct got_error *err = NULL;
5869 *new_view = NULL;
5871 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5872 if (log_view == NULL)
5873 return got_error_from_errno("view_open");
5875 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5876 if (err)
5877 view_close(log_view);
5878 else
5879 *new_view = log_view;
5881 return err;
5884 static const struct got_error *
5885 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5887 const struct got_error *err = NULL, *thread_err = NULL;
5888 struct tog_view *diff_view;
5889 struct tog_blame_view_state *s = &view->state.blame;
5890 int eos, nscroll, begin_y = 0, begin_x = 0;
5892 eos = nscroll = view->nlines - 2;
5893 if (view_is_hsplit_top(view))
5894 --eos; /* border */
5896 switch (ch) {
5897 case '0':
5898 view->x = 0;
5899 break;
5900 case '$':
5901 view->x = MAX(view->maxx - view->ncols / 3, 0);
5902 view->count = 0;
5903 break;
5904 case KEY_RIGHT:
5905 case 'l':
5906 if (view->x + view->ncols / 3 < view->maxx)
5907 view->x += 2; /* move two columns right */
5908 else
5909 view->count = 0;
5910 break;
5911 case KEY_LEFT:
5912 case 'h':
5913 view->x -= MIN(view->x, 2); /* move two columns back */
5914 if (view->x <= 0)
5915 view->count = 0;
5916 break;
5917 case 'q':
5918 s->done = 1;
5919 break;
5920 case 'g':
5921 case KEY_HOME:
5922 s->selected_line = 1;
5923 s->first_displayed_line = 1;
5924 view->count = 0;
5925 break;
5926 case 'G':
5927 case KEY_END:
5928 if (s->blame.nlines < eos) {
5929 s->selected_line = s->blame.nlines;
5930 s->first_displayed_line = 1;
5931 } else {
5932 s->selected_line = eos;
5933 s->first_displayed_line = s->blame.nlines - (eos - 1);
5935 view->count = 0;
5936 break;
5937 case 'k':
5938 case KEY_UP:
5939 case CTRL('p'):
5940 if (s->selected_line > 1)
5941 s->selected_line--;
5942 else if (s->selected_line == 1 &&
5943 s->first_displayed_line > 1)
5944 s->first_displayed_line--;
5945 else
5946 view->count = 0;
5947 break;
5948 case CTRL('u'):
5949 case 'u':
5950 nscroll /= 2;
5951 /* FALL THROUGH */
5952 case KEY_PPAGE:
5953 case CTRL('b'):
5954 case 'b':
5955 if (s->first_displayed_line == 1) {
5956 if (view->count > 1)
5957 nscroll += nscroll;
5958 s->selected_line = MAX(1, s->selected_line - nscroll);
5959 view->count = 0;
5960 break;
5962 if (s->first_displayed_line > nscroll)
5963 s->first_displayed_line -= nscroll;
5964 else
5965 s->first_displayed_line = 1;
5966 break;
5967 case 'j':
5968 case KEY_DOWN:
5969 case CTRL('n'):
5970 if (s->selected_line < eos && s->first_displayed_line +
5971 s->selected_line <= s->blame.nlines)
5972 s->selected_line++;
5973 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5974 s->first_displayed_line++;
5975 else
5976 view->count = 0;
5977 break;
5978 case 'c':
5979 case 'p': {
5980 struct got_object_id *id = NULL;
5982 view->count = 0;
5983 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5984 s->first_displayed_line, s->selected_line);
5985 if (id == NULL)
5986 break;
5987 if (ch == 'p') {
5988 struct got_commit_object *commit, *pcommit;
5989 struct got_object_qid *pid;
5990 struct got_object_id *blob_id = NULL;
5991 int obj_type;
5992 err = got_object_open_as_commit(&commit,
5993 s->repo, id);
5994 if (err)
5995 break;
5996 pid = STAILQ_FIRST(
5997 got_object_commit_get_parent_ids(commit));
5998 if (pid == NULL) {
5999 got_object_commit_close(commit);
6000 break;
6002 /* Check if path history ends here. */
6003 err = got_object_open_as_commit(&pcommit,
6004 s->repo, &pid->id);
6005 if (err)
6006 break;
6007 err = got_object_id_by_path(&blob_id, s->repo,
6008 pcommit, s->path);
6009 got_object_commit_close(pcommit);
6010 if (err) {
6011 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6012 err = NULL;
6013 got_object_commit_close(commit);
6014 break;
6016 err = got_object_get_type(&obj_type, s->repo,
6017 blob_id);
6018 free(blob_id);
6019 /* Can't blame non-blob type objects. */
6020 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6021 got_object_commit_close(commit);
6022 break;
6024 err = got_object_qid_alloc(&s->blamed_commit,
6025 &pid->id);
6026 got_object_commit_close(commit);
6027 } else {
6028 if (got_object_id_cmp(id,
6029 &s->blamed_commit->id) == 0)
6030 break;
6031 err = got_object_qid_alloc(&s->blamed_commit,
6032 id);
6034 if (err)
6035 break;
6036 s->done = 1;
6037 thread_err = stop_blame(&s->blame);
6038 s->done = 0;
6039 if (thread_err)
6040 break;
6041 STAILQ_INSERT_HEAD(&s->blamed_commits,
6042 s->blamed_commit, entry);
6043 err = run_blame(view);
6044 if (err)
6045 break;
6046 break;
6048 case 'C': {
6049 struct got_object_qid *first;
6051 view->count = 0;
6052 first = STAILQ_FIRST(&s->blamed_commits);
6053 if (!got_object_id_cmp(&first->id, s->commit_id))
6054 break;
6055 s->done = 1;
6056 thread_err = stop_blame(&s->blame);
6057 s->done = 0;
6058 if (thread_err)
6059 break;
6060 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6061 got_object_qid_free(s->blamed_commit);
6062 s->blamed_commit =
6063 STAILQ_FIRST(&s->blamed_commits);
6064 err = run_blame(view);
6065 if (err)
6066 break;
6067 break;
6069 case 'L':
6070 view->count = 0;
6071 s->id_to_log = get_selected_commit_id(s->blame.lines,
6072 s->blame.nlines, s->first_displayed_line, s->selected_line);
6073 if (s->id_to_log)
6074 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6075 break;
6076 case KEY_ENTER:
6077 case '\r': {
6078 struct got_object_id *id = NULL;
6079 struct got_object_qid *pid;
6080 struct got_commit_object *commit = NULL;
6082 view->count = 0;
6083 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6084 s->first_displayed_line, s->selected_line);
6085 if (id == NULL)
6086 break;
6087 err = got_object_open_as_commit(&commit, s->repo, id);
6088 if (err)
6089 break;
6090 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6091 if (*new_view) {
6092 /* traversed from diff view, release diff resources */
6093 err = close_diff_view(*new_view);
6094 if (err)
6095 break;
6096 diff_view = *new_view;
6097 } else {
6098 if (view_is_parent_view(view))
6099 view_get_split(view, &begin_y, &begin_x);
6101 diff_view = view_open(0, 0, begin_y, begin_x,
6102 TOG_VIEW_DIFF);
6103 if (diff_view == NULL) {
6104 got_object_commit_close(commit);
6105 err = got_error_from_errno("view_open");
6106 break;
6109 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6110 id, NULL, NULL, 3, 0, 0, view, s->repo);
6111 got_object_commit_close(commit);
6112 if (err) {
6113 view_close(diff_view);
6114 break;
6116 s->last_diffed_line = s->first_displayed_line - 1 +
6117 s->selected_line;
6118 if (*new_view)
6119 break; /* still open from active diff view */
6120 if (view_is_parent_view(view) &&
6121 view->mode == TOG_VIEW_SPLIT_HRZN) {
6122 err = view_init_hsplit(view, begin_y);
6123 if (err)
6124 break;
6127 view->focussed = 0;
6128 diff_view->focussed = 1;
6129 diff_view->mode = view->mode;
6130 diff_view->nlines = view->lines - begin_y;
6131 if (view_is_parent_view(view)) {
6132 view_transfer_size(diff_view, view);
6133 err = view_close_child(view);
6134 if (err)
6135 break;
6136 err = view_set_child(view, diff_view);
6137 if (err)
6138 break;
6139 view->focus_child = 1;
6140 } else
6141 *new_view = diff_view;
6142 if (err)
6143 break;
6144 break;
6146 case CTRL('d'):
6147 case 'd':
6148 nscroll /= 2;
6149 /* FALL THROUGH */
6150 case KEY_NPAGE:
6151 case CTRL('f'):
6152 case 'f':
6153 case ' ':
6154 if (s->last_displayed_line >= s->blame.nlines &&
6155 s->selected_line >= MIN(s->blame.nlines,
6156 view->nlines - 2)) {
6157 view->count = 0;
6158 break;
6160 if (s->last_displayed_line >= s->blame.nlines &&
6161 s->selected_line < view->nlines - 2) {
6162 s->selected_line +=
6163 MIN(nscroll, s->last_displayed_line -
6164 s->first_displayed_line - s->selected_line + 1);
6166 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6167 s->first_displayed_line += nscroll;
6168 else
6169 s->first_displayed_line =
6170 s->blame.nlines - (view->nlines - 3);
6171 break;
6172 case KEY_RESIZE:
6173 if (s->selected_line > view->nlines - 2) {
6174 s->selected_line = MIN(s->blame.nlines,
6175 view->nlines - 2);
6177 break;
6178 default:
6179 view->count = 0;
6180 break;
6182 return thread_err ? thread_err : err;
6185 static const struct got_error *
6186 reset_blame_view(struct tog_view *view)
6188 const struct got_error *err;
6189 struct tog_blame_view_state *s = &view->state.blame;
6191 view->count = 0;
6192 s->done = 1;
6193 err = stop_blame(&s->blame);
6194 s->done = 0;
6195 if (err)
6196 return err;
6197 return run_blame(view);
6200 static const struct got_error *
6201 cmd_blame(int argc, char *argv[])
6203 const struct got_error *error;
6204 struct got_repository *repo = NULL;
6205 struct got_worktree *worktree = NULL;
6206 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6207 char *link_target = NULL;
6208 struct got_object_id *commit_id = NULL;
6209 struct got_commit_object *commit = NULL;
6210 char *commit_id_str = NULL;
6211 int ch;
6212 struct tog_view *view;
6213 int *pack_fds = NULL;
6215 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6216 switch (ch) {
6217 case 'c':
6218 commit_id_str = optarg;
6219 break;
6220 case 'r':
6221 repo_path = realpath(optarg, NULL);
6222 if (repo_path == NULL)
6223 return got_error_from_errno2("realpath",
6224 optarg);
6225 break;
6226 default:
6227 usage_blame();
6228 /* NOTREACHED */
6232 argc -= optind;
6233 argv += optind;
6235 if (argc != 1)
6236 usage_blame();
6238 error = got_repo_pack_fds_open(&pack_fds);
6239 if (error != NULL)
6240 goto done;
6242 if (repo_path == NULL) {
6243 cwd = getcwd(NULL, 0);
6244 if (cwd == NULL)
6245 return got_error_from_errno("getcwd");
6246 error = got_worktree_open(&worktree, cwd);
6247 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6248 goto done;
6249 if (worktree)
6250 repo_path =
6251 strdup(got_worktree_get_repo_path(worktree));
6252 else
6253 repo_path = strdup(cwd);
6254 if (repo_path == NULL) {
6255 error = got_error_from_errno("strdup");
6256 goto done;
6260 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6261 if (error != NULL)
6262 goto done;
6264 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6265 worktree);
6266 if (error)
6267 goto done;
6269 init_curses();
6271 error = apply_unveil(got_repo_get_path(repo), NULL);
6272 if (error)
6273 goto done;
6275 error = tog_load_refs(repo, 0);
6276 if (error)
6277 goto done;
6279 if (commit_id_str == NULL) {
6280 struct got_reference *head_ref;
6281 error = got_ref_open(&head_ref, repo, worktree ?
6282 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6283 if (error != NULL)
6284 goto done;
6285 error = got_ref_resolve(&commit_id, repo, head_ref);
6286 got_ref_close(head_ref);
6287 } else {
6288 error = got_repo_match_object_id(&commit_id, NULL,
6289 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6291 if (error != NULL)
6292 goto done;
6294 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6295 if (view == NULL) {
6296 error = got_error_from_errno("view_open");
6297 goto done;
6300 error = got_object_open_as_commit(&commit, repo, commit_id);
6301 if (error)
6302 goto done;
6304 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6305 commit, repo);
6306 if (error)
6307 goto done;
6309 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6310 commit_id, repo);
6311 if (error)
6312 goto done;
6313 if (worktree) {
6314 /* Release work tree lock. */
6315 got_worktree_close(worktree);
6316 worktree = NULL;
6318 error = view_loop(view);
6319 done:
6320 free(repo_path);
6321 free(in_repo_path);
6322 free(link_target);
6323 free(cwd);
6324 free(commit_id);
6325 if (commit)
6326 got_object_commit_close(commit);
6327 if (worktree)
6328 got_worktree_close(worktree);
6329 if (repo) {
6330 const struct got_error *close_err = got_repo_close(repo);
6331 if (error == NULL)
6332 error = close_err;
6334 if (pack_fds) {
6335 const struct got_error *pack_err =
6336 got_repo_pack_fds_close(pack_fds);
6337 if (error == NULL)
6338 error = pack_err;
6340 tog_free_refs();
6341 return error;
6344 static const struct got_error *
6345 draw_tree_entries(struct tog_view *view, const char *parent_path)
6347 struct tog_tree_view_state *s = &view->state.tree;
6348 const struct got_error *err = NULL;
6349 struct got_tree_entry *te;
6350 wchar_t *wline;
6351 struct tog_color *tc;
6352 int width, n, nentries, i = 1;
6353 int limit = view->nlines;
6355 s->ndisplayed = 0;
6356 if (view_is_hsplit_top(view))
6357 --limit; /* border */
6359 werase(view->window);
6361 if (limit == 0)
6362 return NULL;
6364 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6365 0, 0);
6366 if (err)
6367 return err;
6368 if (view_needs_focus_indication(view))
6369 wstandout(view->window);
6370 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6371 if (tc)
6372 wattr_on(view->window,
6373 COLOR_PAIR(tc->colorpair), NULL);
6374 waddwstr(view->window, wline);
6375 if (tc)
6376 wattr_off(view->window,
6377 COLOR_PAIR(tc->colorpair), NULL);
6378 if (view_needs_focus_indication(view))
6379 wstandend(view->window);
6380 free(wline);
6381 wline = NULL;
6383 if (s->selected_entry) {
6384 i = got_tree_entry_get_index(s->selected_entry);
6385 i += s->tree == s->root ? 1 : 2; /* account for ".." entry */
6387 nentries = got_object_tree_get_nentries(s->tree);
6388 wprintw(view->window, " [%d/%d]", i,
6389 nentries + (s->tree == s->root ? 0 : 1)); /* ".." in !root tree */
6391 if (width < view->ncols - 1)
6392 waddch(view->window, '\n');
6393 if (--limit <= 0)
6394 return NULL;
6395 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6396 0, 0);
6397 if (err)
6398 return err;
6399 waddwstr(view->window, wline);
6400 free(wline);
6401 wline = NULL;
6402 if (width < view->ncols - 1)
6403 waddch(view->window, '\n');
6404 if (--limit <= 0)
6405 return NULL;
6406 waddch(view->window, '\n');
6407 if (--limit <= 0)
6408 return NULL;
6410 if (s->first_displayed_entry == NULL) {
6411 te = got_object_tree_get_first_entry(s->tree);
6412 if (s->selected == 0) {
6413 if (view->focussed)
6414 wstandout(view->window);
6415 s->selected_entry = NULL;
6417 waddstr(view->window, " ..\n"); /* parent directory */
6418 if (s->selected == 0 && view->focussed)
6419 wstandend(view->window);
6420 s->ndisplayed++;
6421 if (--limit <= 0)
6422 return NULL;
6423 n = 1;
6424 } else {
6425 n = 0;
6426 te = s->first_displayed_entry;
6429 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6430 char *line = NULL, *id_str = NULL, *link_target = NULL;
6431 const char *modestr = "";
6432 mode_t mode;
6434 te = got_object_tree_get_entry(s->tree, i);
6435 mode = got_tree_entry_get_mode(te);
6437 if (s->show_ids) {
6438 err = got_object_id_str(&id_str,
6439 got_tree_entry_get_id(te));
6440 if (err)
6441 return got_error_from_errno(
6442 "got_object_id_str");
6444 if (got_object_tree_entry_is_submodule(te))
6445 modestr = "$";
6446 else if (S_ISLNK(mode)) {
6447 int i;
6449 err = got_tree_entry_get_symlink_target(&link_target,
6450 te, s->repo);
6451 if (err) {
6452 free(id_str);
6453 return err;
6455 for (i = 0; i < strlen(link_target); i++) {
6456 if (!isprint((unsigned char)link_target[i]))
6457 link_target[i] = '?';
6459 modestr = "@";
6461 else if (S_ISDIR(mode))
6462 modestr = "/";
6463 else if (mode & S_IXUSR)
6464 modestr = "*";
6465 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6466 got_tree_entry_get_name(te), modestr,
6467 link_target ? " -> ": "",
6468 link_target ? link_target : "") == -1) {
6469 free(id_str);
6470 free(link_target);
6471 return got_error_from_errno("asprintf");
6473 free(id_str);
6474 free(link_target);
6475 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6476 0, 0);
6477 if (err) {
6478 free(line);
6479 break;
6481 if (n == s->selected) {
6482 if (view->focussed)
6483 wstandout(view->window);
6484 s->selected_entry = te;
6486 tc = match_color(&s->colors, line);
6487 if (tc)
6488 wattr_on(view->window,
6489 COLOR_PAIR(tc->colorpair), NULL);
6490 waddwstr(view->window, wline);
6491 if (tc)
6492 wattr_off(view->window,
6493 COLOR_PAIR(tc->colorpair), NULL);
6494 if (width < view->ncols - 1)
6495 waddch(view->window, '\n');
6496 if (n == s->selected && view->focussed)
6497 wstandend(view->window);
6498 free(line);
6499 free(wline);
6500 wline = NULL;
6501 n++;
6502 s->ndisplayed++;
6503 s->last_displayed_entry = te;
6504 if (--limit <= 0)
6505 break;
6508 return err;
6511 static void
6512 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6514 struct got_tree_entry *te;
6515 int isroot = s->tree == s->root;
6516 int i = 0;
6518 if (s->first_displayed_entry == NULL)
6519 return;
6521 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6522 while (i++ < maxscroll) {
6523 if (te == NULL) {
6524 if (!isroot)
6525 s->first_displayed_entry = NULL;
6526 break;
6528 s->first_displayed_entry = te;
6529 te = got_tree_entry_get_prev(s->tree, te);
6533 static const struct got_error *
6534 tree_scroll_down(struct tog_view *view, int maxscroll)
6536 struct tog_tree_view_state *s = &view->state.tree;
6537 struct got_tree_entry *next, *last;
6538 int n = 0;
6540 if (s->first_displayed_entry)
6541 next = got_tree_entry_get_next(s->tree,
6542 s->first_displayed_entry);
6543 else
6544 next = got_object_tree_get_first_entry(s->tree);
6546 last = s->last_displayed_entry;
6547 while (next && n++ < maxscroll) {
6548 if (last) {
6549 s->last_displayed_entry = last;
6550 last = got_tree_entry_get_next(s->tree, last);
6552 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6553 s->first_displayed_entry = next;
6554 next = got_tree_entry_get_next(s->tree, next);
6558 return NULL;
6561 static const struct got_error *
6562 tree_entry_path(char **path, struct tog_parent_trees *parents,
6563 struct got_tree_entry *te)
6565 const struct got_error *err = NULL;
6566 struct tog_parent_tree *pt;
6567 size_t len = 2; /* for leading slash and NUL */
6569 TAILQ_FOREACH(pt, parents, entry)
6570 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6571 + 1 /* slash */;
6572 if (te)
6573 len += strlen(got_tree_entry_get_name(te));
6575 *path = calloc(1, len);
6576 if (path == NULL)
6577 return got_error_from_errno("calloc");
6579 (*path)[0] = '/';
6580 pt = TAILQ_LAST(parents, tog_parent_trees);
6581 while (pt) {
6582 const char *name = got_tree_entry_get_name(pt->selected_entry);
6583 if (strlcat(*path, name, len) >= len) {
6584 err = got_error(GOT_ERR_NO_SPACE);
6585 goto done;
6587 if (strlcat(*path, "/", len) >= len) {
6588 err = got_error(GOT_ERR_NO_SPACE);
6589 goto done;
6591 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6593 if (te) {
6594 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6595 err = got_error(GOT_ERR_NO_SPACE);
6596 goto done;
6599 done:
6600 if (err) {
6601 free(*path);
6602 *path = NULL;
6604 return err;
6607 static const struct got_error *
6608 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6609 struct got_tree_entry *te, struct tog_parent_trees *parents,
6610 struct got_object_id *commit_id, struct got_repository *repo)
6612 const struct got_error *err = NULL;
6613 char *path;
6614 struct tog_view *blame_view;
6616 *new_view = NULL;
6618 err = tree_entry_path(&path, parents, te);
6619 if (err)
6620 return err;
6622 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6623 if (blame_view == NULL) {
6624 err = got_error_from_errno("view_open");
6625 goto done;
6628 err = open_blame_view(blame_view, path, commit_id, repo);
6629 if (err) {
6630 if (err->code == GOT_ERR_CANCELLED)
6631 err = NULL;
6632 view_close(blame_view);
6633 } else
6634 *new_view = blame_view;
6635 done:
6636 free(path);
6637 return err;
6640 static const struct got_error *
6641 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6642 struct tog_tree_view_state *s)
6644 struct tog_view *log_view;
6645 const struct got_error *err = NULL;
6646 char *path;
6648 *new_view = NULL;
6650 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6651 if (log_view == NULL)
6652 return got_error_from_errno("view_open");
6654 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6655 if (err)
6656 return err;
6658 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6659 path, 0);
6660 if (err)
6661 view_close(log_view);
6662 else
6663 *new_view = log_view;
6664 free(path);
6665 return err;
6668 static const struct got_error *
6669 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6670 const char *head_ref_name, struct got_repository *repo)
6672 const struct got_error *err = NULL;
6673 char *commit_id_str = NULL;
6674 struct tog_tree_view_state *s = &view->state.tree;
6675 struct got_commit_object *commit = NULL;
6677 TAILQ_INIT(&s->parents);
6678 STAILQ_INIT(&s->colors);
6680 s->commit_id = got_object_id_dup(commit_id);
6681 if (s->commit_id == NULL)
6682 return got_error_from_errno("got_object_id_dup");
6684 err = got_object_open_as_commit(&commit, repo, commit_id);
6685 if (err)
6686 goto done;
6689 * The root is opened here and will be closed when the view is closed.
6690 * Any visited subtrees and their path-wise parents are opened and
6691 * closed on demand.
6693 err = got_object_open_as_tree(&s->root, repo,
6694 got_object_commit_get_tree_id(commit));
6695 if (err)
6696 goto done;
6697 s->tree = s->root;
6699 err = got_object_id_str(&commit_id_str, commit_id);
6700 if (err != NULL)
6701 goto done;
6703 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6704 err = got_error_from_errno("asprintf");
6705 goto done;
6708 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6709 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6710 if (head_ref_name) {
6711 s->head_ref_name = strdup(head_ref_name);
6712 if (s->head_ref_name == NULL) {
6713 err = got_error_from_errno("strdup");
6714 goto done;
6717 s->repo = repo;
6719 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6720 err = add_color(&s->colors, "\\$$",
6721 TOG_COLOR_TREE_SUBMODULE,
6722 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6723 if (err)
6724 goto done;
6725 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6726 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6727 if (err)
6728 goto done;
6729 err = add_color(&s->colors, "/$",
6730 TOG_COLOR_TREE_DIRECTORY,
6731 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6732 if (err)
6733 goto done;
6735 err = add_color(&s->colors, "\\*$",
6736 TOG_COLOR_TREE_EXECUTABLE,
6737 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6738 if (err)
6739 goto done;
6741 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6742 get_color_value("TOG_COLOR_COMMIT"));
6743 if (err)
6744 goto done;
6747 view->show = show_tree_view;
6748 view->input = input_tree_view;
6749 view->close = close_tree_view;
6750 view->search_start = search_start_tree_view;
6751 view->search_next = search_next_tree_view;
6752 done:
6753 free(commit_id_str);
6754 if (commit)
6755 got_object_commit_close(commit);
6756 if (err)
6757 close_tree_view(view);
6758 return err;
6761 static const struct got_error *
6762 close_tree_view(struct tog_view *view)
6764 struct tog_tree_view_state *s = &view->state.tree;
6766 free_colors(&s->colors);
6767 free(s->tree_label);
6768 s->tree_label = NULL;
6769 free(s->commit_id);
6770 s->commit_id = NULL;
6771 free(s->head_ref_name);
6772 s->head_ref_name = NULL;
6773 while (!TAILQ_EMPTY(&s->parents)) {
6774 struct tog_parent_tree *parent;
6775 parent = TAILQ_FIRST(&s->parents);
6776 TAILQ_REMOVE(&s->parents, parent, entry);
6777 if (parent->tree != s->root)
6778 got_object_tree_close(parent->tree);
6779 free(parent);
6782 if (s->tree != NULL && s->tree != s->root)
6783 got_object_tree_close(s->tree);
6784 if (s->root)
6785 got_object_tree_close(s->root);
6786 return NULL;
6789 static const struct got_error *
6790 search_start_tree_view(struct tog_view *view)
6792 struct tog_tree_view_state *s = &view->state.tree;
6794 s->matched_entry = NULL;
6795 return NULL;
6798 static int
6799 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6801 regmatch_t regmatch;
6803 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6804 0) == 0;
6807 static const struct got_error *
6808 search_next_tree_view(struct tog_view *view)
6810 struct tog_tree_view_state *s = &view->state.tree;
6811 struct got_tree_entry *te = NULL;
6813 if (!view->searching) {
6814 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6815 return NULL;
6818 if (s->matched_entry) {
6819 if (view->searching == TOG_SEARCH_FORWARD) {
6820 if (s->selected_entry)
6821 te = got_tree_entry_get_next(s->tree,
6822 s->selected_entry);
6823 else
6824 te = got_object_tree_get_first_entry(s->tree);
6825 } else {
6826 if (s->selected_entry == NULL)
6827 te = got_object_tree_get_last_entry(s->tree);
6828 else
6829 te = got_tree_entry_get_prev(s->tree,
6830 s->selected_entry);
6832 } else {
6833 if (s->selected_entry)
6834 te = s->selected_entry;
6835 else if (view->searching == TOG_SEARCH_FORWARD)
6836 te = got_object_tree_get_first_entry(s->tree);
6837 else
6838 te = got_object_tree_get_last_entry(s->tree);
6841 while (1) {
6842 if (te == NULL) {
6843 if (s->matched_entry == NULL) {
6844 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6845 return NULL;
6847 if (view->searching == TOG_SEARCH_FORWARD)
6848 te = got_object_tree_get_first_entry(s->tree);
6849 else
6850 te = got_object_tree_get_last_entry(s->tree);
6853 if (match_tree_entry(te, &view->regex)) {
6854 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6855 s->matched_entry = te;
6856 break;
6859 if (view->searching == TOG_SEARCH_FORWARD)
6860 te = got_tree_entry_get_next(s->tree, te);
6861 else
6862 te = got_tree_entry_get_prev(s->tree, te);
6865 if (s->matched_entry) {
6866 s->first_displayed_entry = s->matched_entry;
6867 s->selected = 0;
6870 return NULL;
6873 static const struct got_error *
6874 show_tree_view(struct tog_view *view)
6876 const struct got_error *err = NULL;
6877 struct tog_tree_view_state *s = &view->state.tree;
6878 char *parent_path;
6880 err = tree_entry_path(&parent_path, &s->parents, NULL);
6881 if (err)
6882 return err;
6884 err = draw_tree_entries(view, parent_path);
6885 free(parent_path);
6887 view_border(view);
6888 return err;
6891 static const struct got_error *
6892 tree_goto_line(struct tog_view *view, int nlines)
6894 const struct got_error *err = NULL;
6895 struct tog_tree_view_state *s = &view->state.tree;
6896 struct got_tree_entry **fte, **lte, **ste;
6897 int g, last, first = 1, i = 1;
6898 int root = s->tree == s->root;
6899 int off = root ? 1 : 2;
6901 g = view->gline;
6902 view->gline = 0;
6904 if (g == 0)
6905 g = 1;
6906 else if (g > got_object_tree_get_nentries(s->tree))
6907 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
6909 fte = &s->first_displayed_entry;
6910 lte = &s->last_displayed_entry;
6911 ste = &s->selected_entry;
6913 if (*fte != NULL) {
6914 first = got_tree_entry_get_index(*fte);
6915 first += off; /* account for ".." */
6917 last = got_tree_entry_get_index(*lte);
6918 last += off;
6920 if (g >= first && g <= last && g - first < nlines) {
6921 s->selected = g - first;
6922 return NULL; /* gline is on the current page */
6925 if (*ste != NULL) {
6926 i = got_tree_entry_get_index(*ste);
6927 i += off;
6930 if (i < g) {
6931 err = tree_scroll_down(view, g - i);
6932 if (err)
6933 return err;
6934 if (got_tree_entry_get_index(*lte) >=
6935 got_object_tree_get_nentries(s->tree) - 1 &&
6936 first + s->selected < g &&
6937 s->selected < s->ndisplayed - 1) {
6938 first = got_tree_entry_get_index(*fte);
6939 first += off;
6940 s->selected = g - first;
6942 } else if (i > g)
6943 tree_scroll_up(s, i - g);
6945 if (g < nlines &&
6946 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
6947 s->selected = g - 1;
6949 return NULL;
6952 static const struct got_error *
6953 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6955 const struct got_error *err = NULL;
6956 struct tog_tree_view_state *s = &view->state.tree;
6957 struct got_tree_entry *te;
6958 int n, nscroll = view->nlines - 3;
6960 if (view->gline)
6961 return tree_goto_line(view, nscroll);
6963 switch (ch) {
6964 case 'i':
6965 s->show_ids = !s->show_ids;
6966 view->count = 0;
6967 break;
6968 case 'L':
6969 view->count = 0;
6970 if (!s->selected_entry)
6971 break;
6972 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6973 break;
6974 case 'R':
6975 view->count = 0;
6976 err = view_request_new(new_view, view, TOG_VIEW_REF);
6977 break;
6978 case 'g':
6979 case KEY_HOME:
6980 s->selected = 0;
6981 view->count = 0;
6982 if (s->tree == s->root)
6983 s->first_displayed_entry =
6984 got_object_tree_get_first_entry(s->tree);
6985 else
6986 s->first_displayed_entry = NULL;
6987 break;
6988 case 'G':
6989 case KEY_END: {
6990 int eos = view->nlines - 3;
6992 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6993 --eos; /* border */
6994 s->selected = 0;
6995 view->count = 0;
6996 te = got_object_tree_get_last_entry(s->tree);
6997 for (n = 0; n < eos; n++) {
6998 if (te == NULL) {
6999 if (s->tree != s->root) {
7000 s->first_displayed_entry = NULL;
7001 n++;
7003 break;
7005 s->first_displayed_entry = te;
7006 te = got_tree_entry_get_prev(s->tree, te);
7008 if (n > 0)
7009 s->selected = n - 1;
7010 break;
7012 case 'k':
7013 case KEY_UP:
7014 case CTRL('p'):
7015 if (s->selected > 0) {
7016 s->selected--;
7017 break;
7019 tree_scroll_up(s, 1);
7020 if (s->selected_entry == NULL ||
7021 (s->tree == s->root && s->selected_entry ==
7022 got_object_tree_get_first_entry(s->tree)))
7023 view->count = 0;
7024 break;
7025 case CTRL('u'):
7026 case 'u':
7027 nscroll /= 2;
7028 /* FALL THROUGH */
7029 case KEY_PPAGE:
7030 case CTRL('b'):
7031 case 'b':
7032 if (s->tree == s->root) {
7033 if (got_object_tree_get_first_entry(s->tree) ==
7034 s->first_displayed_entry)
7035 s->selected -= MIN(s->selected, nscroll);
7036 } else {
7037 if (s->first_displayed_entry == NULL)
7038 s->selected -= MIN(s->selected, nscroll);
7040 tree_scroll_up(s, MAX(0, nscroll));
7041 if (s->selected_entry == NULL ||
7042 (s->tree == s->root && s->selected_entry ==
7043 got_object_tree_get_first_entry(s->tree)))
7044 view->count = 0;
7045 break;
7046 case 'j':
7047 case KEY_DOWN:
7048 case CTRL('n'):
7049 if (s->selected < s->ndisplayed - 1) {
7050 s->selected++;
7051 break;
7053 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7054 == NULL) {
7055 /* can't scroll any further */
7056 view->count = 0;
7057 break;
7059 tree_scroll_down(view, 1);
7060 break;
7061 case CTRL('d'):
7062 case 'd':
7063 nscroll /= 2;
7064 /* FALL THROUGH */
7065 case KEY_NPAGE:
7066 case CTRL('f'):
7067 case 'f':
7068 case ' ':
7069 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7070 == NULL) {
7071 /* can't scroll any further; move cursor down */
7072 if (s->selected < s->ndisplayed - 1)
7073 s->selected += MIN(nscroll,
7074 s->ndisplayed - s->selected - 1);
7075 else
7076 view->count = 0;
7077 break;
7079 tree_scroll_down(view, nscroll);
7080 break;
7081 case KEY_ENTER:
7082 case '\r':
7083 case KEY_BACKSPACE:
7084 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7085 struct tog_parent_tree *parent;
7086 /* user selected '..' */
7087 if (s->tree == s->root) {
7088 view->count = 0;
7089 break;
7091 parent = TAILQ_FIRST(&s->parents);
7092 TAILQ_REMOVE(&s->parents, parent,
7093 entry);
7094 got_object_tree_close(s->tree);
7095 s->tree = parent->tree;
7096 s->first_displayed_entry =
7097 parent->first_displayed_entry;
7098 s->selected_entry =
7099 parent->selected_entry;
7100 s->selected = parent->selected;
7101 if (s->selected > view->nlines - 3) {
7102 err = offset_selection_down(view);
7103 if (err)
7104 break;
7106 free(parent);
7107 } else if (S_ISDIR(got_tree_entry_get_mode(
7108 s->selected_entry))) {
7109 struct got_tree_object *subtree;
7110 view->count = 0;
7111 err = got_object_open_as_tree(&subtree, s->repo,
7112 got_tree_entry_get_id(s->selected_entry));
7113 if (err)
7114 break;
7115 err = tree_view_visit_subtree(s, subtree);
7116 if (err) {
7117 got_object_tree_close(subtree);
7118 break;
7120 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7121 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7122 break;
7123 case KEY_RESIZE:
7124 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7125 s->selected = view->nlines - 4;
7126 view->count = 0;
7127 break;
7128 default:
7129 view->count = 0;
7130 break;
7133 return err;
7136 __dead static void
7137 usage_tree(void)
7139 endwin();
7140 fprintf(stderr,
7141 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7142 getprogname());
7143 exit(1);
7146 static const struct got_error *
7147 cmd_tree(int argc, char *argv[])
7149 const struct got_error *error;
7150 struct got_repository *repo = NULL;
7151 struct got_worktree *worktree = NULL;
7152 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7153 struct got_object_id *commit_id = NULL;
7154 struct got_commit_object *commit = NULL;
7155 const char *commit_id_arg = NULL;
7156 char *label = NULL;
7157 struct got_reference *ref = NULL;
7158 const char *head_ref_name = NULL;
7159 int ch;
7160 struct tog_view *view;
7161 int *pack_fds = NULL;
7163 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7164 switch (ch) {
7165 case 'c':
7166 commit_id_arg = optarg;
7167 break;
7168 case 'r':
7169 repo_path = realpath(optarg, NULL);
7170 if (repo_path == NULL)
7171 return got_error_from_errno2("realpath",
7172 optarg);
7173 break;
7174 default:
7175 usage_tree();
7176 /* NOTREACHED */
7180 argc -= optind;
7181 argv += optind;
7183 if (argc > 1)
7184 usage_tree();
7186 error = got_repo_pack_fds_open(&pack_fds);
7187 if (error != NULL)
7188 goto done;
7190 if (repo_path == NULL) {
7191 cwd = getcwd(NULL, 0);
7192 if (cwd == NULL)
7193 return got_error_from_errno("getcwd");
7194 error = got_worktree_open(&worktree, cwd);
7195 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7196 goto done;
7197 if (worktree)
7198 repo_path =
7199 strdup(got_worktree_get_repo_path(worktree));
7200 else
7201 repo_path = strdup(cwd);
7202 if (repo_path == NULL) {
7203 error = got_error_from_errno("strdup");
7204 goto done;
7208 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7209 if (error != NULL)
7210 goto done;
7212 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7213 repo, worktree);
7214 if (error)
7215 goto done;
7217 init_curses();
7219 error = apply_unveil(got_repo_get_path(repo), NULL);
7220 if (error)
7221 goto done;
7223 error = tog_load_refs(repo, 0);
7224 if (error)
7225 goto done;
7227 if (commit_id_arg == NULL) {
7228 error = got_repo_match_object_id(&commit_id, &label,
7229 worktree ? got_worktree_get_head_ref_name(worktree) :
7230 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7231 if (error)
7232 goto done;
7233 head_ref_name = label;
7234 } else {
7235 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7236 if (error == NULL)
7237 head_ref_name = got_ref_get_name(ref);
7238 else if (error->code != GOT_ERR_NOT_REF)
7239 goto done;
7240 error = got_repo_match_object_id(&commit_id, NULL,
7241 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7242 if (error)
7243 goto done;
7246 error = got_object_open_as_commit(&commit, repo, commit_id);
7247 if (error)
7248 goto done;
7250 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7251 if (view == NULL) {
7252 error = got_error_from_errno("view_open");
7253 goto done;
7255 error = open_tree_view(view, commit_id, head_ref_name, repo);
7256 if (error)
7257 goto done;
7258 if (!got_path_is_root_dir(in_repo_path)) {
7259 error = tree_view_walk_path(&view->state.tree, commit,
7260 in_repo_path);
7261 if (error)
7262 goto done;
7265 if (worktree) {
7266 /* Release work tree lock. */
7267 got_worktree_close(worktree);
7268 worktree = NULL;
7270 error = view_loop(view);
7271 done:
7272 free(repo_path);
7273 free(cwd);
7274 free(commit_id);
7275 free(label);
7276 if (ref)
7277 got_ref_close(ref);
7278 if (repo) {
7279 const struct got_error *close_err = got_repo_close(repo);
7280 if (error == NULL)
7281 error = close_err;
7283 if (pack_fds) {
7284 const struct got_error *pack_err =
7285 got_repo_pack_fds_close(pack_fds);
7286 if (error == NULL)
7287 error = pack_err;
7289 tog_free_refs();
7290 return error;
7293 static const struct got_error *
7294 ref_view_load_refs(struct tog_ref_view_state *s)
7296 struct got_reflist_entry *sre;
7297 struct tog_reflist_entry *re;
7299 s->nrefs = 0;
7300 TAILQ_FOREACH(sre, &tog_refs, entry) {
7301 if (strncmp(got_ref_get_name(sre->ref),
7302 "refs/got/", 9) == 0 &&
7303 strncmp(got_ref_get_name(sre->ref),
7304 "refs/got/backup/", 16) != 0)
7305 continue;
7307 re = malloc(sizeof(*re));
7308 if (re == NULL)
7309 return got_error_from_errno("malloc");
7311 re->ref = got_ref_dup(sre->ref);
7312 if (re->ref == NULL)
7313 return got_error_from_errno("got_ref_dup");
7314 re->idx = s->nrefs++;
7315 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7318 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7319 return NULL;
7322 static void
7323 ref_view_free_refs(struct tog_ref_view_state *s)
7325 struct tog_reflist_entry *re;
7327 while (!TAILQ_EMPTY(&s->refs)) {
7328 re = TAILQ_FIRST(&s->refs);
7329 TAILQ_REMOVE(&s->refs, re, entry);
7330 got_ref_close(re->ref);
7331 free(re);
7335 static const struct got_error *
7336 open_ref_view(struct tog_view *view, struct got_repository *repo)
7338 const struct got_error *err = NULL;
7339 struct tog_ref_view_state *s = &view->state.ref;
7341 s->selected_entry = 0;
7342 s->repo = repo;
7344 TAILQ_INIT(&s->refs);
7345 STAILQ_INIT(&s->colors);
7347 err = ref_view_load_refs(s);
7348 if (err)
7349 return err;
7351 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7352 err = add_color(&s->colors, "^refs/heads/",
7353 TOG_COLOR_REFS_HEADS,
7354 get_color_value("TOG_COLOR_REFS_HEADS"));
7355 if (err)
7356 goto done;
7358 err = add_color(&s->colors, "^refs/tags/",
7359 TOG_COLOR_REFS_TAGS,
7360 get_color_value("TOG_COLOR_REFS_TAGS"));
7361 if (err)
7362 goto done;
7364 err = add_color(&s->colors, "^refs/remotes/",
7365 TOG_COLOR_REFS_REMOTES,
7366 get_color_value("TOG_COLOR_REFS_REMOTES"));
7367 if (err)
7368 goto done;
7370 err = add_color(&s->colors, "^refs/got/backup/",
7371 TOG_COLOR_REFS_BACKUP,
7372 get_color_value("TOG_COLOR_REFS_BACKUP"));
7373 if (err)
7374 goto done;
7377 view->show = show_ref_view;
7378 view->input = input_ref_view;
7379 view->close = close_ref_view;
7380 view->search_start = search_start_ref_view;
7381 view->search_next = search_next_ref_view;
7382 done:
7383 if (err)
7384 free_colors(&s->colors);
7385 return err;
7388 static const struct got_error *
7389 close_ref_view(struct tog_view *view)
7391 struct tog_ref_view_state *s = &view->state.ref;
7393 ref_view_free_refs(s);
7394 free_colors(&s->colors);
7396 return NULL;
7399 static const struct got_error *
7400 resolve_reflist_entry(struct got_object_id **commit_id,
7401 struct tog_reflist_entry *re, struct got_repository *repo)
7403 const struct got_error *err = NULL;
7404 struct got_object_id *obj_id;
7405 struct got_tag_object *tag = NULL;
7406 int obj_type;
7408 *commit_id = NULL;
7410 err = got_ref_resolve(&obj_id, repo, re->ref);
7411 if (err)
7412 return err;
7414 err = got_object_get_type(&obj_type, repo, obj_id);
7415 if (err)
7416 goto done;
7418 switch (obj_type) {
7419 case GOT_OBJ_TYPE_COMMIT:
7420 *commit_id = obj_id;
7421 break;
7422 case GOT_OBJ_TYPE_TAG:
7423 err = got_object_open_as_tag(&tag, repo, obj_id);
7424 if (err)
7425 goto done;
7426 free(obj_id);
7427 err = got_object_get_type(&obj_type, repo,
7428 got_object_tag_get_object_id(tag));
7429 if (err)
7430 goto done;
7431 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7432 err = got_error(GOT_ERR_OBJ_TYPE);
7433 goto done;
7435 *commit_id = got_object_id_dup(
7436 got_object_tag_get_object_id(tag));
7437 if (*commit_id == NULL) {
7438 err = got_error_from_errno("got_object_id_dup");
7439 goto done;
7441 break;
7442 default:
7443 err = got_error(GOT_ERR_OBJ_TYPE);
7444 break;
7447 done:
7448 if (tag)
7449 got_object_tag_close(tag);
7450 if (err) {
7451 free(*commit_id);
7452 *commit_id = NULL;
7454 return err;
7457 static const struct got_error *
7458 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7459 struct tog_reflist_entry *re, struct got_repository *repo)
7461 struct tog_view *log_view;
7462 const struct got_error *err = NULL;
7463 struct got_object_id *commit_id = NULL;
7465 *new_view = NULL;
7467 err = resolve_reflist_entry(&commit_id, re, repo);
7468 if (err) {
7469 if (err->code != GOT_ERR_OBJ_TYPE)
7470 return err;
7471 else
7472 return NULL;
7475 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7476 if (log_view == NULL) {
7477 err = got_error_from_errno("view_open");
7478 goto done;
7481 err = open_log_view(log_view, commit_id, repo,
7482 got_ref_get_name(re->ref), "", 0);
7483 done:
7484 if (err)
7485 view_close(log_view);
7486 else
7487 *new_view = log_view;
7488 free(commit_id);
7489 return err;
7492 static void
7493 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7495 struct tog_reflist_entry *re;
7496 int i = 0;
7498 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7499 return;
7501 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7502 while (i++ < maxscroll) {
7503 if (re == NULL)
7504 break;
7505 s->first_displayed_entry = re;
7506 re = TAILQ_PREV(re, tog_reflist_head, entry);
7510 static const struct got_error *
7511 ref_scroll_down(struct tog_view *view, int maxscroll)
7513 struct tog_ref_view_state *s = &view->state.ref;
7514 struct tog_reflist_entry *next, *last;
7515 int n = 0;
7517 if (s->first_displayed_entry)
7518 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7519 else
7520 next = TAILQ_FIRST(&s->refs);
7522 last = s->last_displayed_entry;
7523 while (next && n++ < maxscroll) {
7524 if (last) {
7525 s->last_displayed_entry = last;
7526 last = TAILQ_NEXT(last, entry);
7528 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7529 s->first_displayed_entry = next;
7530 next = TAILQ_NEXT(next, entry);
7534 return NULL;
7537 static const struct got_error *
7538 search_start_ref_view(struct tog_view *view)
7540 struct tog_ref_view_state *s = &view->state.ref;
7542 s->matched_entry = NULL;
7543 return NULL;
7546 static int
7547 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7549 regmatch_t regmatch;
7551 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7552 0) == 0;
7555 static const struct got_error *
7556 search_next_ref_view(struct tog_view *view)
7558 struct tog_ref_view_state *s = &view->state.ref;
7559 struct tog_reflist_entry *re = NULL;
7561 if (!view->searching) {
7562 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7563 return NULL;
7566 if (s->matched_entry) {
7567 if (view->searching == TOG_SEARCH_FORWARD) {
7568 if (s->selected_entry)
7569 re = TAILQ_NEXT(s->selected_entry, entry);
7570 else
7571 re = TAILQ_PREV(s->selected_entry,
7572 tog_reflist_head, entry);
7573 } else {
7574 if (s->selected_entry == NULL)
7575 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7576 else
7577 re = TAILQ_PREV(s->selected_entry,
7578 tog_reflist_head, entry);
7580 } else {
7581 if (s->selected_entry)
7582 re = s->selected_entry;
7583 else if (view->searching == TOG_SEARCH_FORWARD)
7584 re = TAILQ_FIRST(&s->refs);
7585 else
7586 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7589 while (1) {
7590 if (re == NULL) {
7591 if (s->matched_entry == NULL) {
7592 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7593 return NULL;
7595 if (view->searching == TOG_SEARCH_FORWARD)
7596 re = TAILQ_FIRST(&s->refs);
7597 else
7598 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7601 if (match_reflist_entry(re, &view->regex)) {
7602 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7603 s->matched_entry = re;
7604 break;
7607 if (view->searching == TOG_SEARCH_FORWARD)
7608 re = TAILQ_NEXT(re, entry);
7609 else
7610 re = TAILQ_PREV(re, tog_reflist_head, entry);
7613 if (s->matched_entry) {
7614 s->first_displayed_entry = s->matched_entry;
7615 s->selected = 0;
7618 return NULL;
7621 static const struct got_error *
7622 show_ref_view(struct tog_view *view)
7624 const struct got_error *err = NULL;
7625 struct tog_ref_view_state *s = &view->state.ref;
7626 struct tog_reflist_entry *re;
7627 char *line = NULL;
7628 wchar_t *wline;
7629 struct tog_color *tc;
7630 int width, n;
7631 int limit = view->nlines;
7633 werase(view->window);
7635 s->ndisplayed = 0;
7636 if (view_is_hsplit_top(view))
7637 --limit; /* border */
7639 if (limit == 0)
7640 return NULL;
7642 re = s->first_displayed_entry;
7644 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7645 s->nrefs) == -1)
7646 return got_error_from_errno("asprintf");
7648 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7649 if (err) {
7650 free(line);
7651 return err;
7653 if (view_needs_focus_indication(view))
7654 wstandout(view->window);
7655 waddwstr(view->window, wline);
7656 if (view_needs_focus_indication(view))
7657 wstandend(view->window);
7658 free(wline);
7659 wline = NULL;
7660 free(line);
7661 line = NULL;
7662 if (width < view->ncols - 1)
7663 waddch(view->window, '\n');
7664 if (--limit <= 0)
7665 return NULL;
7667 n = 0;
7668 while (re && limit > 0) {
7669 char *line = NULL;
7670 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7672 if (s->show_date) {
7673 struct got_commit_object *ci;
7674 struct got_tag_object *tag;
7675 struct got_object_id *id;
7676 struct tm tm;
7677 time_t t;
7679 err = got_ref_resolve(&id, s->repo, re->ref);
7680 if (err)
7681 return err;
7682 err = got_object_open_as_tag(&tag, s->repo, id);
7683 if (err) {
7684 if (err->code != GOT_ERR_OBJ_TYPE) {
7685 free(id);
7686 return err;
7688 err = got_object_open_as_commit(&ci, s->repo,
7689 id);
7690 if (err) {
7691 free(id);
7692 return err;
7694 t = got_object_commit_get_committer_time(ci);
7695 got_object_commit_close(ci);
7696 } else {
7697 t = got_object_tag_get_tagger_time(tag);
7698 got_object_tag_close(tag);
7700 free(id);
7701 if (gmtime_r(&t, &tm) == NULL)
7702 return got_error_from_errno("gmtime_r");
7703 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7704 return got_error(GOT_ERR_NO_SPACE);
7706 if (got_ref_is_symbolic(re->ref)) {
7707 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7708 ymd : "", got_ref_get_name(re->ref),
7709 got_ref_get_symref_target(re->ref)) == -1)
7710 return got_error_from_errno("asprintf");
7711 } else if (s->show_ids) {
7712 struct got_object_id *id;
7713 char *id_str;
7714 err = got_ref_resolve(&id, s->repo, re->ref);
7715 if (err)
7716 return err;
7717 err = got_object_id_str(&id_str, id);
7718 if (err) {
7719 free(id);
7720 return err;
7722 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7723 got_ref_get_name(re->ref), id_str) == -1) {
7724 err = got_error_from_errno("asprintf");
7725 free(id);
7726 free(id_str);
7727 return err;
7729 free(id);
7730 free(id_str);
7731 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7732 got_ref_get_name(re->ref)) == -1)
7733 return got_error_from_errno("asprintf");
7735 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7736 0, 0);
7737 if (err) {
7738 free(line);
7739 return err;
7741 if (n == s->selected) {
7742 if (view->focussed)
7743 wstandout(view->window);
7744 s->selected_entry = re;
7746 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7747 if (tc)
7748 wattr_on(view->window,
7749 COLOR_PAIR(tc->colorpair), NULL);
7750 waddwstr(view->window, wline);
7751 if (tc)
7752 wattr_off(view->window,
7753 COLOR_PAIR(tc->colorpair), NULL);
7754 if (width < view->ncols - 1)
7755 waddch(view->window, '\n');
7756 if (n == s->selected && view->focussed)
7757 wstandend(view->window);
7758 free(line);
7759 free(wline);
7760 wline = NULL;
7761 n++;
7762 s->ndisplayed++;
7763 s->last_displayed_entry = re;
7765 limit--;
7766 re = TAILQ_NEXT(re, entry);
7769 view_border(view);
7770 return err;
7773 static const struct got_error *
7774 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7775 struct tog_reflist_entry *re, struct got_repository *repo)
7777 const struct got_error *err = NULL;
7778 struct got_object_id *commit_id = NULL;
7779 struct tog_view *tree_view;
7781 *new_view = NULL;
7783 err = resolve_reflist_entry(&commit_id, re, repo);
7784 if (err) {
7785 if (err->code != GOT_ERR_OBJ_TYPE)
7786 return err;
7787 else
7788 return NULL;
7792 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7793 if (tree_view == NULL) {
7794 err = got_error_from_errno("view_open");
7795 goto done;
7798 err = open_tree_view(tree_view, commit_id,
7799 got_ref_get_name(re->ref), repo);
7800 if (err)
7801 goto done;
7803 *new_view = tree_view;
7804 done:
7805 free(commit_id);
7806 return err;
7809 static const struct got_error *
7810 ref_goto_line(struct tog_view *view, int nlines)
7812 const struct got_error *err = NULL;
7813 struct tog_ref_view_state *s = &view->state.ref;
7814 int g, idx = s->selected_entry->idx;
7816 g = view->gline;
7817 view->gline = 0;
7819 if (g == 0)
7820 g = 1;
7821 else if (g > s->nrefs)
7822 g = s->nrefs;
7824 if (g >= s->first_displayed_entry->idx + 1 &&
7825 g <= s->last_displayed_entry->idx + 1 &&
7826 g - s->first_displayed_entry->idx - 1 < nlines) {
7827 s->selected = g - s->first_displayed_entry->idx - 1;
7828 return NULL;
7831 if (idx + 1 < g) {
7832 err = ref_scroll_down(view, g - idx - 1);
7833 if (err)
7834 return err;
7835 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
7836 s->first_displayed_entry->idx + s->selected < g &&
7837 s->selected < s->ndisplayed - 1)
7838 s->selected = g - s->first_displayed_entry->idx - 1;
7839 } else if (idx + 1 > g)
7840 ref_scroll_up(s, idx - g + 1);
7842 if (g < nlines && s->first_displayed_entry->idx == 0)
7843 s->selected = g - 1;
7845 return NULL;
7849 static const struct got_error *
7850 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7852 const struct got_error *err = NULL;
7853 struct tog_ref_view_state *s = &view->state.ref;
7854 struct tog_reflist_entry *re;
7855 int n, nscroll = view->nlines - 1;
7857 if (view->gline)
7858 return ref_goto_line(view, nscroll);
7860 switch (ch) {
7861 case 'i':
7862 s->show_ids = !s->show_ids;
7863 view->count = 0;
7864 break;
7865 case 'm':
7866 s->show_date = !s->show_date;
7867 view->count = 0;
7868 break;
7869 case 'o':
7870 s->sort_by_date = !s->sort_by_date;
7871 view->count = 0;
7872 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7873 got_ref_cmp_by_commit_timestamp_descending :
7874 tog_ref_cmp_by_name, s->repo);
7875 if (err)
7876 break;
7877 got_reflist_object_id_map_free(tog_refs_idmap);
7878 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7879 &tog_refs, s->repo);
7880 if (err)
7881 break;
7882 ref_view_free_refs(s);
7883 err = ref_view_load_refs(s);
7884 break;
7885 case KEY_ENTER:
7886 case '\r':
7887 view->count = 0;
7888 if (!s->selected_entry)
7889 break;
7890 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7891 break;
7892 case 'T':
7893 view->count = 0;
7894 if (!s->selected_entry)
7895 break;
7896 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7897 break;
7898 case 'g':
7899 case KEY_HOME:
7900 s->selected = 0;
7901 view->count = 0;
7902 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7903 break;
7904 case 'G':
7905 case KEY_END: {
7906 int eos = view->nlines - 1;
7908 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7909 --eos; /* border */
7910 s->selected = 0;
7911 view->count = 0;
7912 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7913 for (n = 0; n < eos; n++) {
7914 if (re == NULL)
7915 break;
7916 s->first_displayed_entry = re;
7917 re = TAILQ_PREV(re, tog_reflist_head, entry);
7919 if (n > 0)
7920 s->selected = n - 1;
7921 break;
7923 case 'k':
7924 case KEY_UP:
7925 case CTRL('p'):
7926 if (s->selected > 0) {
7927 s->selected--;
7928 break;
7930 ref_scroll_up(s, 1);
7931 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7932 view->count = 0;
7933 break;
7934 case CTRL('u'):
7935 case 'u':
7936 nscroll /= 2;
7937 /* FALL THROUGH */
7938 case KEY_PPAGE:
7939 case CTRL('b'):
7940 case 'b':
7941 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7942 s->selected -= MIN(nscroll, s->selected);
7943 ref_scroll_up(s, MAX(0, nscroll));
7944 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7945 view->count = 0;
7946 break;
7947 case 'j':
7948 case KEY_DOWN:
7949 case CTRL('n'):
7950 if (s->selected < s->ndisplayed - 1) {
7951 s->selected++;
7952 break;
7954 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7955 /* can't scroll any further */
7956 view->count = 0;
7957 break;
7959 ref_scroll_down(view, 1);
7960 break;
7961 case CTRL('d'):
7962 case 'd':
7963 nscroll /= 2;
7964 /* FALL THROUGH */
7965 case KEY_NPAGE:
7966 case CTRL('f'):
7967 case 'f':
7968 case ' ':
7969 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7970 /* can't scroll any further; move cursor down */
7971 if (s->selected < s->ndisplayed - 1)
7972 s->selected += MIN(nscroll,
7973 s->ndisplayed - s->selected - 1);
7974 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7975 s->selected += s->ndisplayed - s->selected - 1;
7976 view->count = 0;
7977 break;
7979 ref_scroll_down(view, nscroll);
7980 break;
7981 case CTRL('l'):
7982 view->count = 0;
7983 tog_free_refs();
7984 err = tog_load_refs(s->repo, s->sort_by_date);
7985 if (err)
7986 break;
7987 ref_view_free_refs(s);
7988 err = ref_view_load_refs(s);
7989 break;
7990 case KEY_RESIZE:
7991 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7992 s->selected = view->nlines - 2;
7993 break;
7994 default:
7995 view->count = 0;
7996 break;
7999 return err;
8002 __dead static void
8003 usage_ref(void)
8005 endwin();
8006 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8007 getprogname());
8008 exit(1);
8011 static const struct got_error *
8012 cmd_ref(int argc, char *argv[])
8014 const struct got_error *error;
8015 struct got_repository *repo = NULL;
8016 struct got_worktree *worktree = NULL;
8017 char *cwd = NULL, *repo_path = NULL;
8018 int ch;
8019 struct tog_view *view;
8020 int *pack_fds = NULL;
8022 while ((ch = getopt(argc, argv, "r:")) != -1) {
8023 switch (ch) {
8024 case 'r':
8025 repo_path = realpath(optarg, NULL);
8026 if (repo_path == NULL)
8027 return got_error_from_errno2("realpath",
8028 optarg);
8029 break;
8030 default:
8031 usage_ref();
8032 /* NOTREACHED */
8036 argc -= optind;
8037 argv += optind;
8039 if (argc > 1)
8040 usage_ref();
8042 error = got_repo_pack_fds_open(&pack_fds);
8043 if (error != NULL)
8044 goto done;
8046 if (repo_path == NULL) {
8047 cwd = getcwd(NULL, 0);
8048 if (cwd == NULL)
8049 return got_error_from_errno("getcwd");
8050 error = got_worktree_open(&worktree, cwd);
8051 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8052 goto done;
8053 if (worktree)
8054 repo_path =
8055 strdup(got_worktree_get_repo_path(worktree));
8056 else
8057 repo_path = strdup(cwd);
8058 if (repo_path == NULL) {
8059 error = got_error_from_errno("strdup");
8060 goto done;
8064 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8065 if (error != NULL)
8066 goto done;
8068 init_curses();
8070 error = apply_unveil(got_repo_get_path(repo), NULL);
8071 if (error)
8072 goto done;
8074 error = tog_load_refs(repo, 0);
8075 if (error)
8076 goto done;
8078 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8079 if (view == NULL) {
8080 error = got_error_from_errno("view_open");
8081 goto done;
8084 error = open_ref_view(view, repo);
8085 if (error)
8086 goto done;
8088 if (worktree) {
8089 /* Release work tree lock. */
8090 got_worktree_close(worktree);
8091 worktree = NULL;
8093 error = view_loop(view);
8094 done:
8095 free(repo_path);
8096 free(cwd);
8097 if (repo) {
8098 const struct got_error *close_err = got_repo_close(repo);
8099 if (close_err)
8100 error = close_err;
8102 if (pack_fds) {
8103 const struct got_error *pack_err =
8104 got_repo_pack_fds_close(pack_fds);
8105 if (error == NULL)
8106 error = pack_err;
8108 tog_free_refs();
8109 return error;
8112 static const struct got_error *
8113 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8114 enum tog_view_type request, int y, int x)
8116 const struct got_error *err = NULL;
8118 *new_view = NULL;
8120 switch (request) {
8121 case TOG_VIEW_DIFF:
8122 if (view->type == TOG_VIEW_LOG) {
8123 struct tog_log_view_state *s = &view->state.log;
8125 err = open_diff_view_for_commit(new_view, y, x,
8126 s->selected_entry->commit, s->selected_entry->id,
8127 view, s->repo);
8128 } else
8129 return got_error_msg(GOT_ERR_NOT_IMPL,
8130 "parent/child view pair not supported");
8131 break;
8132 case TOG_VIEW_BLAME:
8133 if (view->type == TOG_VIEW_TREE) {
8134 struct tog_tree_view_state *s = &view->state.tree;
8136 err = blame_tree_entry(new_view, y, x,
8137 s->selected_entry, &s->parents, s->commit_id,
8138 s->repo);
8139 } else
8140 return got_error_msg(GOT_ERR_NOT_IMPL,
8141 "parent/child view pair not supported");
8142 break;
8143 case TOG_VIEW_LOG:
8144 if (view->type == TOG_VIEW_BLAME)
8145 err = log_annotated_line(new_view, y, x,
8146 view->state.blame.repo, view->state.blame.id_to_log);
8147 else if (view->type == TOG_VIEW_TREE)
8148 err = log_selected_tree_entry(new_view, y, x,
8149 &view->state.tree);
8150 else if (view->type == TOG_VIEW_REF)
8151 err = log_ref_entry(new_view, y, x,
8152 view->state.ref.selected_entry,
8153 view->state.ref.repo);
8154 else
8155 return got_error_msg(GOT_ERR_NOT_IMPL,
8156 "parent/child view pair not supported");
8157 break;
8158 case TOG_VIEW_TREE:
8159 if (view->type == TOG_VIEW_LOG)
8160 err = browse_commit_tree(new_view, y, x,
8161 view->state.log.selected_entry,
8162 view->state.log.in_repo_path,
8163 view->state.log.head_ref_name,
8164 view->state.log.repo);
8165 else if (view->type == TOG_VIEW_REF)
8166 err = browse_ref_tree(new_view, y, x,
8167 view->state.ref.selected_entry,
8168 view->state.ref.repo);
8169 else
8170 return got_error_msg(GOT_ERR_NOT_IMPL,
8171 "parent/child view pair not supported");
8172 break;
8173 case TOG_VIEW_REF:
8174 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8175 if (*new_view == NULL)
8176 return got_error_from_errno("view_open");
8177 if (view->type == TOG_VIEW_LOG)
8178 err = open_ref_view(*new_view, view->state.log.repo);
8179 else if (view->type == TOG_VIEW_TREE)
8180 err = open_ref_view(*new_view, view->state.tree.repo);
8181 else
8182 err = got_error_msg(GOT_ERR_NOT_IMPL,
8183 "parent/child view pair not supported");
8184 if (err)
8185 view_close(*new_view);
8186 break;
8187 default:
8188 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8191 return err;
8195 * If view was scrolled down to move the selected line into view when opening a
8196 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8198 static void
8199 offset_selection_up(struct tog_view *view)
8201 switch (view->type) {
8202 case TOG_VIEW_BLAME: {
8203 struct tog_blame_view_state *s = &view->state.blame;
8204 if (s->first_displayed_line == 1) {
8205 s->selected_line = MAX(s->selected_line - view->offset,
8206 1);
8207 break;
8209 if (s->first_displayed_line > view->offset)
8210 s->first_displayed_line -= view->offset;
8211 else
8212 s->first_displayed_line = 1;
8213 s->selected_line += view->offset;
8214 break;
8216 case TOG_VIEW_LOG:
8217 log_scroll_up(&view->state.log, view->offset);
8218 view->state.log.selected += view->offset;
8219 break;
8220 case TOG_VIEW_REF:
8221 ref_scroll_up(&view->state.ref, view->offset);
8222 view->state.ref.selected += view->offset;
8223 break;
8224 case TOG_VIEW_TREE:
8225 tree_scroll_up(&view->state.tree, view->offset);
8226 view->state.tree.selected += view->offset;
8227 break;
8228 default:
8229 break;
8232 view->offset = 0;
8236 * If the selected line is in the section of screen covered by the bottom split,
8237 * scroll down offset lines to move it into view and index its new position.
8239 static const struct got_error *
8240 offset_selection_down(struct tog_view *view)
8242 const struct got_error *err = NULL;
8243 const struct got_error *(*scrolld)(struct tog_view *, int);
8244 int *selected = NULL;
8245 int header, offset;
8247 switch (view->type) {
8248 case TOG_VIEW_BLAME: {
8249 struct tog_blame_view_state *s = &view->state.blame;
8250 header = 3;
8251 scrolld = NULL;
8252 if (s->selected_line > view->nlines - header) {
8253 offset = abs(view->nlines - s->selected_line - header);
8254 s->first_displayed_line += offset;
8255 s->selected_line -= offset;
8256 view->offset = offset;
8258 break;
8260 case TOG_VIEW_LOG: {
8261 struct tog_log_view_state *s = &view->state.log;
8262 scrolld = &log_scroll_down;
8263 header = view_is_parent_view(view) ? 3 : 2;
8264 selected = &s->selected;
8265 break;
8267 case TOG_VIEW_REF: {
8268 struct tog_ref_view_state *s = &view->state.ref;
8269 scrolld = &ref_scroll_down;
8270 header = 3;
8271 selected = &s->selected;
8272 break;
8274 case TOG_VIEW_TREE: {
8275 struct tog_tree_view_state *s = &view->state.tree;
8276 scrolld = &tree_scroll_down;
8277 header = 5;
8278 selected = &s->selected;
8279 break;
8281 default:
8282 selected = NULL;
8283 scrolld = NULL;
8284 header = 0;
8285 break;
8288 if (selected && *selected > view->nlines - header) {
8289 offset = abs(view->nlines - *selected - header);
8290 view->offset = offset;
8291 if (scrolld && offset) {
8292 err = scrolld(view, offset);
8293 *selected -= offset;
8297 return err;
8300 static void
8301 list_commands(FILE *fp)
8303 size_t i;
8305 fprintf(fp, "commands:");
8306 for (i = 0; i < nitems(tog_commands); i++) {
8307 const struct tog_cmd *cmd = &tog_commands[i];
8308 fprintf(fp, " %s", cmd->name);
8310 fputc('\n', fp);
8313 __dead static void
8314 usage(int hflag, int status)
8316 FILE *fp = (status == 0) ? stdout : stderr;
8318 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8319 getprogname());
8320 if (hflag) {
8321 fprintf(fp, "lazy usage: %s path\n", getprogname());
8322 list_commands(fp);
8324 exit(status);
8327 static char **
8328 make_argv(int argc, ...)
8330 va_list ap;
8331 char **argv;
8332 int i;
8334 va_start(ap, argc);
8336 argv = calloc(argc, sizeof(char *));
8337 if (argv == NULL)
8338 err(1, "calloc");
8339 for (i = 0; i < argc; i++) {
8340 argv[i] = strdup(va_arg(ap, char *));
8341 if (argv[i] == NULL)
8342 err(1, "strdup");
8345 va_end(ap);
8346 return argv;
8350 * Try to convert 'tog path' into a 'tog log path' command.
8351 * The user could simply have mistyped the command rather than knowingly
8352 * provided a path. So check whether argv[0] can in fact be resolved
8353 * to a path in the HEAD commit and print a special error if not.
8354 * This hack is for mpi@ <3
8356 static const struct got_error *
8357 tog_log_with_path(int argc, char *argv[])
8359 const struct got_error *error = NULL, *close_err;
8360 const struct tog_cmd *cmd = NULL;
8361 struct got_repository *repo = NULL;
8362 struct got_worktree *worktree = NULL;
8363 struct got_object_id *commit_id = NULL, *id = NULL;
8364 struct got_commit_object *commit = NULL;
8365 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8366 char *commit_id_str = NULL, **cmd_argv = NULL;
8367 int *pack_fds = NULL;
8369 cwd = getcwd(NULL, 0);
8370 if (cwd == NULL)
8371 return got_error_from_errno("getcwd");
8373 error = got_repo_pack_fds_open(&pack_fds);
8374 if (error != NULL)
8375 goto done;
8377 error = got_worktree_open(&worktree, cwd);
8378 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8379 goto done;
8381 if (worktree)
8382 repo_path = strdup(got_worktree_get_repo_path(worktree));
8383 else
8384 repo_path = strdup(cwd);
8385 if (repo_path == NULL) {
8386 error = got_error_from_errno("strdup");
8387 goto done;
8390 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8391 if (error != NULL)
8392 goto done;
8394 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8395 repo, worktree);
8396 if (error)
8397 goto done;
8399 error = tog_load_refs(repo, 0);
8400 if (error)
8401 goto done;
8402 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8403 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8404 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8405 if (error)
8406 goto done;
8408 if (worktree) {
8409 got_worktree_close(worktree);
8410 worktree = NULL;
8413 error = got_object_open_as_commit(&commit, repo, commit_id);
8414 if (error)
8415 goto done;
8417 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8418 if (error) {
8419 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8420 goto done;
8421 fprintf(stderr, "%s: '%s' is no known command or path\n",
8422 getprogname(), argv[0]);
8423 usage(1, 1);
8424 /* not reached */
8427 error = got_object_id_str(&commit_id_str, commit_id);
8428 if (error)
8429 goto done;
8431 cmd = &tog_commands[0]; /* log */
8432 argc = 4;
8433 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8434 error = cmd->cmd_main(argc, cmd_argv);
8435 done:
8436 if (repo) {
8437 close_err = got_repo_close(repo);
8438 if (error == NULL)
8439 error = close_err;
8441 if (commit)
8442 got_object_commit_close(commit);
8443 if (worktree)
8444 got_worktree_close(worktree);
8445 if (pack_fds) {
8446 const struct got_error *pack_err =
8447 got_repo_pack_fds_close(pack_fds);
8448 if (error == NULL)
8449 error = pack_err;
8451 free(id);
8452 free(commit_id_str);
8453 free(commit_id);
8454 free(cwd);
8455 free(repo_path);
8456 free(in_repo_path);
8457 if (cmd_argv) {
8458 int i;
8459 for (i = 0; i < argc; i++)
8460 free(cmd_argv[i]);
8461 free(cmd_argv);
8463 tog_free_refs();
8464 return error;
8467 int
8468 main(int argc, char *argv[])
8470 const struct got_error *error = NULL;
8471 const struct tog_cmd *cmd = NULL;
8472 int ch, hflag = 0, Vflag = 0;
8473 char **cmd_argv = NULL;
8474 static const struct option longopts[] = {
8475 { "version", no_argument, NULL, 'V' },
8476 { NULL, 0, NULL, 0}
8478 char *diff_algo_str = NULL;
8480 setlocale(LC_CTYPE, "");
8482 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8483 switch (ch) {
8484 case 'h':
8485 hflag = 1;
8486 break;
8487 case 'V':
8488 Vflag = 1;
8489 break;
8490 default:
8491 usage(hflag, 1);
8492 /* NOTREACHED */
8496 argc -= optind;
8497 argv += optind;
8498 optind = 1;
8499 optreset = 1;
8501 if (Vflag) {
8502 got_version_print_str();
8503 return 0;
8506 #ifndef PROFILE
8507 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8508 NULL) == -1)
8509 err(1, "pledge");
8510 #endif
8512 if (argc == 0) {
8513 if (hflag)
8514 usage(hflag, 0);
8515 /* Build an argument vector which runs a default command. */
8516 cmd = &tog_commands[0];
8517 argc = 1;
8518 cmd_argv = make_argv(argc, cmd->name);
8519 } else {
8520 size_t i;
8522 /* Did the user specify a command? */
8523 for (i = 0; i < nitems(tog_commands); i++) {
8524 if (strncmp(tog_commands[i].name, argv[0],
8525 strlen(argv[0])) == 0) {
8526 cmd = &tog_commands[i];
8527 break;
8532 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8533 if (diff_algo_str) {
8534 if (strcasecmp(diff_algo_str, "patience") == 0)
8535 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8536 if (strcasecmp(diff_algo_str, "myers") == 0)
8537 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8540 if (cmd == NULL) {
8541 if (argc != 1)
8542 usage(0, 1);
8543 /* No command specified; try log with a path */
8544 error = tog_log_with_path(argc, argv);
8545 } else {
8546 if (hflag)
8547 cmd->cmd_usage();
8548 else
8549 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8552 endwin();
8553 putchar('\n');
8554 if (cmd_argv) {
8555 int i;
8556 for (i = 0; i < argc; i++)
8557 free(cmd_argv[i]);
8558 free(cmd_argv);
8561 if (error && error->code != GOT_ERR_CANCELLED)
8562 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8563 return 0;