Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 };
108 enum tog_view_mode {
109 TOG_VIEW_SPLIT_NONE,
110 TOG_VIEW_SPLIT_VERT,
111 TOG_VIEW_SPLIT_HRZN
112 };
114 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
116 #define TOG_EOF_STRING "(END)"
118 struct commit_queue_entry {
119 TAILQ_ENTRY(commit_queue_entry) entry;
120 struct got_object_id *id;
121 struct got_commit_object *commit;
122 int idx;
123 };
124 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
125 struct commit_queue {
126 int ncommits;
127 struct commit_queue_head head;
128 };
130 struct tog_color {
131 STAILQ_ENTRY(tog_color) entry;
132 regex_t regex;
133 short colorpair;
134 };
135 STAILQ_HEAD(tog_colors, tog_color);
137 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
138 static struct got_reflist_object_id_map *tog_refs_idmap;
139 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
141 static const struct got_error *
142 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
143 struct got_reference* re2)
145 const char *name1 = got_ref_get_name(re1);
146 const char *name2 = got_ref_get_name(re2);
147 int isbackup1, isbackup2;
149 /* Sort backup refs towards the bottom of the list. */
150 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
151 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
152 if (!isbackup1 && isbackup2) {
153 *cmp = -1;
154 return NULL;
155 } else if (isbackup1 && !isbackup2) {
156 *cmp = 1;
157 return NULL;
160 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
161 return NULL;
164 static const struct got_error *
165 tog_load_refs(struct got_repository *repo, int sort_by_date)
167 const struct got_error *err;
169 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
170 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
171 repo);
172 if (err)
173 return err;
175 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
176 repo);
179 static void
180 tog_free_refs(void)
182 if (tog_refs_idmap) {
183 got_reflist_object_id_map_free(tog_refs_idmap);
184 tog_refs_idmap = NULL;
186 got_ref_list_free(&tog_refs);
189 static const struct got_error *
190 add_color(struct tog_colors *colors, const char *pattern,
191 int idx, short color)
193 const struct got_error *err = NULL;
194 struct tog_color *tc;
195 int regerr = 0;
197 if (idx < 1 || idx > COLOR_PAIRS - 1)
198 return NULL;
200 init_pair(idx, color, -1);
202 tc = calloc(1, sizeof(*tc));
203 if (tc == NULL)
204 return got_error_from_errno("calloc");
205 regerr = regcomp(&tc->regex, pattern,
206 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
207 if (regerr) {
208 static char regerr_msg[512];
209 static char err_msg[512];
210 regerror(regerr, &tc->regex, regerr_msg,
211 sizeof(regerr_msg));
212 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
213 regerr_msg);
214 err = got_error_msg(GOT_ERR_REGEX, err_msg);
215 free(tc);
216 return err;
218 tc->colorpair = idx;
219 STAILQ_INSERT_HEAD(colors, tc, entry);
220 return NULL;
223 static void
224 free_colors(struct tog_colors *colors)
226 struct tog_color *tc;
228 while (!STAILQ_EMPTY(colors)) {
229 tc = STAILQ_FIRST(colors);
230 STAILQ_REMOVE_HEAD(colors, entry);
231 regfree(&tc->regex);
232 free(tc);
236 static struct tog_color *
237 get_color(struct tog_colors *colors, int colorpair)
239 struct tog_color *tc = NULL;
241 STAILQ_FOREACH(tc, colors, entry) {
242 if (tc->colorpair == colorpair)
243 return tc;
246 return NULL;
249 static int
250 default_color_value(const char *envvar)
252 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
253 return COLOR_MAGENTA;
254 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
255 return COLOR_CYAN;
256 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
257 return COLOR_YELLOW;
258 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
259 return COLOR_GREEN;
260 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
261 return COLOR_MAGENTA;
262 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
263 return COLOR_MAGENTA;
264 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
265 return COLOR_CYAN;
266 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
267 return COLOR_GREEN;
268 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
269 return COLOR_GREEN;
270 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
271 return COLOR_CYAN;
272 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
273 return COLOR_YELLOW;
274 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
275 return COLOR_GREEN;
276 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
279 return COLOR_YELLOW;
280 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
281 return COLOR_CYAN;
283 return -1;
286 static int
287 get_color_value(const char *envvar)
289 const char *val = getenv(envvar);
291 if (val == NULL)
292 return default_color_value(envvar);
294 if (strcasecmp(val, "black") == 0)
295 return COLOR_BLACK;
296 if (strcasecmp(val, "red") == 0)
297 return COLOR_RED;
298 if (strcasecmp(val, "green") == 0)
299 return COLOR_GREEN;
300 if (strcasecmp(val, "yellow") == 0)
301 return COLOR_YELLOW;
302 if (strcasecmp(val, "blue") == 0)
303 return COLOR_BLUE;
304 if (strcasecmp(val, "magenta") == 0)
305 return COLOR_MAGENTA;
306 if (strcasecmp(val, "cyan") == 0)
307 return COLOR_CYAN;
308 if (strcasecmp(val, "white") == 0)
309 return COLOR_WHITE;
310 if (strcasecmp(val, "default") == 0)
311 return -1;
313 return default_color_value(envvar);
317 struct tog_diff_view_state {
318 struct got_object_id *id1, *id2;
319 const char *label1, *label2;
320 FILE *f, *f1, *f2;
321 int fd1, fd2;
322 int first_displayed_line;
323 int last_displayed_line;
324 int eof;
325 int diff_context;
326 int ignore_whitespace;
327 int force_text_diff;
328 struct got_repository *repo;
329 struct tog_colors colors;
330 size_t nlines;
331 off_t *line_offsets;
332 int matched_line;
333 int selected_line;
335 /* passed from log or blame view; may be NULL */
336 struct tog_view *parent_view;
337 };
339 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
340 static volatile sig_atomic_t tog_thread_error;
342 struct tog_log_thread_args {
343 pthread_cond_t need_commits;
344 pthread_cond_t commit_loaded;
345 int commits_needed;
346 int load_all;
347 struct got_commit_graph *graph;
348 struct commit_queue *commits;
349 const char *in_repo_path;
350 struct got_object_id *start_id;
351 struct got_repository *repo;
352 int *pack_fds;
353 int log_complete;
354 sig_atomic_t *quit;
355 struct commit_queue_entry **first_displayed_entry;
356 struct commit_queue_entry **selected_entry;
357 int *searching;
358 int *search_next_done;
359 regex_t *regex;
360 };
362 struct tog_log_view_state {
363 struct commit_queue commits;
364 struct commit_queue_entry *first_displayed_entry;
365 struct commit_queue_entry *last_displayed_entry;
366 struct commit_queue_entry *selected_entry;
367 int selected;
368 char *in_repo_path;
369 char *head_ref_name;
370 int log_branches;
371 struct got_repository *repo;
372 struct got_object_id *start_id;
373 sig_atomic_t quit;
374 pthread_t thread;
375 struct tog_log_thread_args thread_args;
376 struct commit_queue_entry *matched_entry;
377 struct commit_queue_entry *search_entry;
378 struct tog_colors colors;
379 int use_committer;
380 };
382 #define TOG_COLOR_DIFF_MINUS 1
383 #define TOG_COLOR_DIFF_PLUS 2
384 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
385 #define TOG_COLOR_DIFF_META 4
386 #define TOG_COLOR_TREE_SUBMODULE 5
387 #define TOG_COLOR_TREE_SYMLINK 6
388 #define TOG_COLOR_TREE_DIRECTORY 7
389 #define TOG_COLOR_TREE_EXECUTABLE 8
390 #define TOG_COLOR_COMMIT 9
391 #define TOG_COLOR_AUTHOR 10
392 #define TOG_COLOR_DATE 11
393 #define TOG_COLOR_REFS_HEADS 12
394 #define TOG_COLOR_REFS_TAGS 13
395 #define TOG_COLOR_REFS_REMOTES 14
396 #define TOG_COLOR_REFS_BACKUP 15
398 struct tog_blame_cb_args {
399 struct tog_blame_line *lines; /* one per line */
400 int nlines;
402 struct tog_view *view;
403 struct got_object_id *commit_id;
404 int *quit;
405 };
407 struct tog_blame_thread_args {
408 const char *path;
409 struct got_repository *repo;
410 struct tog_blame_cb_args *cb_args;
411 int *complete;
412 got_cancel_cb cancel_cb;
413 void *cancel_arg;
414 };
416 struct tog_blame {
417 FILE *f;
418 off_t filesize;
419 struct tog_blame_line *lines;
420 int nlines;
421 off_t *line_offsets;
422 pthread_t thread;
423 struct tog_blame_thread_args thread_args;
424 struct tog_blame_cb_args cb_args;
425 const char *path;
426 int *pack_fds;
427 };
429 struct tog_blame_view_state {
430 int first_displayed_line;
431 int last_displayed_line;
432 int selected_line;
433 int last_diffed_line;
434 int blame_complete;
435 int eof;
436 int done;
437 struct got_object_id_queue blamed_commits;
438 struct got_object_qid *blamed_commit;
439 char *path;
440 struct got_repository *repo;
441 struct got_object_id *commit_id;
442 struct got_object_id *id_to_log;
443 struct tog_blame blame;
444 int matched_line;
445 struct tog_colors colors;
446 };
448 struct tog_parent_tree {
449 TAILQ_ENTRY(tog_parent_tree) entry;
450 struct got_tree_object *tree;
451 struct got_tree_entry *first_displayed_entry;
452 struct got_tree_entry *selected_entry;
453 int selected;
454 };
456 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
458 struct tog_tree_view_state {
459 char *tree_label;
460 struct got_object_id *commit_id;/* commit which this tree belongs to */
461 struct got_tree_object *root; /* the commit's root tree entry */
462 struct got_tree_object *tree; /* currently displayed (sub-)tree */
463 struct got_tree_entry *first_displayed_entry;
464 struct got_tree_entry *last_displayed_entry;
465 struct got_tree_entry *selected_entry;
466 int ndisplayed, selected, show_ids;
467 struct tog_parent_trees parents; /* parent trees of current sub-tree */
468 char *head_ref_name;
469 struct got_repository *repo;
470 struct got_tree_entry *matched_entry;
471 struct tog_colors colors;
472 };
474 struct tog_reflist_entry {
475 TAILQ_ENTRY(tog_reflist_entry) entry;
476 struct got_reference *ref;
477 int idx;
478 };
480 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
482 struct tog_ref_view_state {
483 struct tog_reflist_head refs;
484 struct tog_reflist_entry *first_displayed_entry;
485 struct tog_reflist_entry *last_displayed_entry;
486 struct tog_reflist_entry *selected_entry;
487 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
488 struct got_repository *repo;
489 struct tog_reflist_entry *matched_entry;
490 struct tog_colors colors;
491 };
493 /*
494 * We implement two types of views: parent views and child views.
496 * The 'Tab' key switches focus between a parent view and its child view.
497 * Child views are shown side-by-side to their parent view, provided
498 * there is enough screen estate.
500 * When a new view is opened from within a parent view, this new view
501 * becomes a child view of the parent view, replacing any existing child.
503 * When a new view is opened from within a child view, this new view
504 * becomes a parent view which will obscure the views below until the
505 * user quits the new parent view by typing 'q'.
507 * This list of views contains parent views only.
508 * Child views are only pointed to by their parent view.
509 */
510 TAILQ_HEAD(tog_view_list_head, tog_view);
512 struct tog_view {
513 TAILQ_ENTRY(tog_view) entry;
514 WINDOW *window;
515 PANEL *panel;
516 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
517 int resized_y, resized_x; /* begin_y/x based on user resizing */
518 int maxx, x; /* max column and current start column */
519 int lines, cols; /* copies of LINES and COLS */
520 int nscrolled, offset; /* lines scrolled and hsplit line offset */
521 int 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 lineno, 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 lineno = s->first_displayed_line - 1;
3952 line_offset = s->line_offsets[s->first_displayed_line - 1];
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 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 (++lineno < s->first_displayed_line)
4005 continue;
4006 if (view->gline && !gotoline(view, &lineno, &nprinted))
4007 continue;
4008 if (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 (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 = 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_offset(off_t **line_offsets, size_t *nlines, off_t off)
4161 off_t *p;
4163 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
4164 if (p == NULL)
4165 return got_error_from_errno("reallocarray");
4166 *line_offsets = p;
4167 (*line_offsets)[*nlines] = off;
4168 (*nlines)++;
4169 return NULL;
4172 static const struct got_error *
4173 write_commit_info(off_t **line_offsets, size_t *nlines,
4174 struct got_object_id *commit_id, struct got_reflist_head *refs,
4175 struct got_repository *repo, FILE *outfile)
4177 const struct got_error *err = NULL;
4178 char datebuf[26], *datestr;
4179 struct got_commit_object *commit;
4180 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4181 time_t committer_time;
4182 const char *author, *committer;
4183 char *refs_str = NULL;
4184 struct got_pathlist_head changed_paths;
4185 struct got_pathlist_entry *pe;
4186 off_t outoff = 0;
4187 int n;
4189 TAILQ_INIT(&changed_paths);
4191 if (refs) {
4192 err = build_refs_str(&refs_str, refs, commit_id, repo);
4193 if (err)
4194 return err;
4197 err = got_object_open_as_commit(&commit, repo, commit_id);
4198 if (err)
4199 return err;
4201 err = got_object_id_str(&id_str, commit_id);
4202 if (err) {
4203 err = got_error_from_errno("got_object_id_str");
4204 goto done;
4207 err = add_line_offset(line_offsets, nlines, 0);
4208 if (err)
4209 goto done;
4211 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4212 refs_str ? refs_str : "", refs_str ? ")" : "");
4213 if (n < 0) {
4214 err = got_error_from_errno("fprintf");
4215 goto done;
4217 outoff += n;
4218 err = add_line_offset(line_offsets, nlines, outoff);
4219 if (err)
4220 goto done;
4222 n = fprintf(outfile, "from: %s\n",
4223 got_object_commit_get_author(commit));
4224 if (n < 0) {
4225 err = got_error_from_errno("fprintf");
4226 goto done;
4228 outoff += n;
4229 err = add_line_offset(line_offsets, nlines, outoff);
4230 if (err)
4231 goto done;
4233 committer_time = got_object_commit_get_committer_time(commit);
4234 datestr = get_datestr(&committer_time, datebuf);
4235 if (datestr) {
4236 n = fprintf(outfile, "date: %s UTC\n", datestr);
4237 if (n < 0) {
4238 err = got_error_from_errno("fprintf");
4239 goto done;
4241 outoff += n;
4242 err = add_line_offset(line_offsets, nlines, outoff);
4243 if (err)
4244 goto done;
4246 author = got_object_commit_get_author(commit);
4247 committer = got_object_commit_get_committer(commit);
4248 if (strcmp(author, committer) != 0) {
4249 n = fprintf(outfile, "via: %s\n", committer);
4250 if (n < 0) {
4251 err = got_error_from_errno("fprintf");
4252 goto done;
4254 outoff += n;
4255 err = add_line_offset(line_offsets, nlines, outoff);
4256 if (err)
4257 goto done;
4259 if (got_object_commit_get_nparents(commit) > 1) {
4260 const struct got_object_id_queue *parent_ids;
4261 struct got_object_qid *qid;
4262 int pn = 1;
4263 parent_ids = got_object_commit_get_parent_ids(commit);
4264 STAILQ_FOREACH(qid, parent_ids, entry) {
4265 err = got_object_id_str(&id_str, &qid->id);
4266 if (err)
4267 goto done;
4268 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4269 if (n < 0) {
4270 err = got_error_from_errno("fprintf");
4271 goto done;
4273 outoff += n;
4274 err = add_line_offset(line_offsets, nlines, outoff);
4275 if (err)
4276 goto done;
4277 free(id_str);
4278 id_str = NULL;
4282 err = got_object_commit_get_logmsg(&logmsg, commit);
4283 if (err)
4284 goto done;
4285 s = logmsg;
4286 while ((line = strsep(&s, "\n")) != NULL) {
4287 n = fprintf(outfile, "%s\n", line);
4288 if (n < 0) {
4289 err = got_error_from_errno("fprintf");
4290 goto done;
4292 outoff += n;
4293 err = add_line_offset(line_offsets, nlines, outoff);
4294 if (err)
4295 goto done;
4298 err = get_changed_paths(&changed_paths, commit, repo);
4299 if (err)
4300 goto done;
4301 TAILQ_FOREACH(pe, &changed_paths, entry) {
4302 struct got_diff_changed_path *cp = pe->data;
4303 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4304 if (n < 0) {
4305 err = got_error_from_errno("fprintf");
4306 goto done;
4308 outoff += n;
4309 err = add_line_offset(line_offsets, nlines, outoff);
4310 if (err)
4311 goto done;
4312 free((char *)pe->path);
4313 free(pe->data);
4316 fputc('\n', outfile);
4317 outoff++;
4318 err = add_line_offset(line_offsets, nlines, outoff);
4319 done:
4320 got_pathlist_free(&changed_paths);
4321 free(id_str);
4322 free(logmsg);
4323 free(refs_str);
4324 got_object_commit_close(commit);
4325 if (err) {
4326 free(*line_offsets);
4327 *line_offsets = NULL;
4328 *nlines = 0;
4330 return err;
4333 static const struct got_error *
4334 create_diff(struct tog_diff_view_state *s)
4336 const struct got_error *err = NULL;
4337 FILE *f = NULL;
4338 int obj_type;
4340 free(s->line_offsets);
4341 s->line_offsets = malloc(sizeof(off_t));
4342 if (s->line_offsets == NULL)
4343 return got_error_from_errno("malloc");
4344 s->nlines = 0;
4346 f = got_opentemp();
4347 if (f == NULL) {
4348 err = got_error_from_errno("got_opentemp");
4349 goto done;
4351 if (s->f && fclose(s->f) == EOF) {
4352 err = got_error_from_errno("fclose");
4353 goto done;
4355 s->f = f;
4357 if (s->id1)
4358 err = got_object_get_type(&obj_type, s->repo, s->id1);
4359 else
4360 err = got_object_get_type(&obj_type, s->repo, s->id2);
4361 if (err)
4362 goto done;
4364 switch (obj_type) {
4365 case GOT_OBJ_TYPE_BLOB:
4366 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
4367 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4368 s->label1, s->label2, tog_diff_algo, s->diff_context,
4369 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4370 break;
4371 case GOT_OBJ_TYPE_TREE:
4372 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
4373 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4374 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4375 s->force_text_diff, s->repo, s->f);
4376 break;
4377 case GOT_OBJ_TYPE_COMMIT: {
4378 const struct got_object_id_queue *parent_ids;
4379 struct got_object_qid *pid;
4380 struct got_commit_object *commit2;
4381 struct got_reflist_head *refs;
4383 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4384 if (err)
4385 goto done;
4386 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4387 /* Show commit info if we're diffing to a parent/root commit. */
4388 if (s->id1 == NULL) {
4389 err = write_commit_info(&s->line_offsets, &s->nlines,
4390 s->id2, refs, s->repo, s->f);
4391 if (err)
4392 goto done;
4393 } else {
4394 parent_ids = got_object_commit_get_parent_ids(commit2);
4395 STAILQ_FOREACH(pid, parent_ids, entry) {
4396 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4397 err = write_commit_info(
4398 &s->line_offsets, &s->nlines,
4399 s->id2, refs, s->repo, s->f);
4400 if (err)
4401 goto done;
4402 break;
4406 got_object_commit_close(commit2);
4408 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4409 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4410 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4411 s->force_text_diff, s->repo, s->f);
4412 break;
4414 default:
4415 err = got_error(GOT_ERR_OBJ_TYPE);
4416 break;
4418 if (err)
4419 goto done;
4420 done:
4421 if (s->f && fflush(s->f) != 0 && err == NULL)
4422 err = got_error_from_errno("fflush");
4423 return err;
4426 static void
4427 diff_view_indicate_progress(struct tog_view *view)
4429 mvwaddstr(view->window, 0, 0, "diffing...");
4430 update_panels();
4431 doupdate();
4434 static const struct got_error *
4435 search_start_diff_view(struct tog_view *view)
4437 struct tog_diff_view_state *s = &view->state.diff;
4439 s->matched_line = 0;
4440 return NULL;
4443 static const struct got_error *
4444 search_next_diff_view(struct tog_view *view)
4446 struct tog_diff_view_state *s = &view->state.diff;
4447 const struct got_error *err = NULL;
4448 int lineno;
4449 char *line = NULL;
4450 size_t linesize = 0;
4451 ssize_t linelen;
4453 if (!view->searching) {
4454 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4455 return NULL;
4458 if (s->matched_line) {
4459 if (view->searching == TOG_SEARCH_FORWARD)
4460 lineno = s->matched_line + 1;
4461 else
4462 lineno = s->matched_line - 1;
4463 } else
4464 lineno = s->first_displayed_line;
4466 while (1) {
4467 off_t offset;
4469 if (lineno <= 0 || lineno > s->nlines) {
4470 if (s->matched_line == 0) {
4471 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4472 break;
4475 if (view->searching == TOG_SEARCH_FORWARD)
4476 lineno = 1;
4477 else
4478 lineno = s->nlines;
4481 offset = s->line_offsets[lineno - 1];
4482 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4483 free(line);
4484 return got_error_from_errno("fseeko");
4486 linelen = getline(&line, &linesize, s->f);
4487 if (linelen != -1) {
4488 char *exstr;
4489 err = expand_tab(&exstr, line);
4490 if (err)
4491 break;
4492 if (match_line(exstr, &view->regex, 1,
4493 &view->regmatch)) {
4494 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4495 s->matched_line = lineno;
4496 free(exstr);
4497 break;
4499 free(exstr);
4501 if (view->searching == TOG_SEARCH_FORWARD)
4502 lineno++;
4503 else
4504 lineno--;
4506 free(line);
4508 if (s->matched_line) {
4509 s->first_displayed_line = s->matched_line;
4510 s->selected_line = 1;
4513 return err;
4516 static const struct got_error *
4517 close_diff_view(struct tog_view *view)
4519 const struct got_error *err = NULL;
4520 struct tog_diff_view_state *s = &view->state.diff;
4522 free(s->id1);
4523 s->id1 = NULL;
4524 free(s->id2);
4525 s->id2 = NULL;
4526 if (s->f && fclose(s->f) == EOF)
4527 err = got_error_from_errno("fclose");
4528 s->f = NULL;
4529 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4530 err = got_error_from_errno("fclose");
4531 s->f1 = NULL;
4532 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4533 err = got_error_from_errno("fclose");
4534 s->f2 = NULL;
4535 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4536 err = got_error_from_errno("close");
4537 s->fd1 = -1;
4538 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4539 err = got_error_from_errno("close");
4540 s->fd2 = -1;
4541 free_colors(&s->colors);
4542 free(s->line_offsets);
4543 s->line_offsets = NULL;
4544 s->nlines = 0;
4545 return err;
4548 static const struct got_error *
4549 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4550 struct got_object_id *id2, const char *label1, const char *label2,
4551 int diff_context, int ignore_whitespace, int force_text_diff,
4552 struct tog_view *parent_view, struct got_repository *repo)
4554 const struct got_error *err;
4555 struct tog_diff_view_state *s = &view->state.diff;
4557 memset(s, 0, sizeof(*s));
4558 s->fd1 = -1;
4559 s->fd2 = -1;
4561 if (id1 != NULL && id2 != NULL) {
4562 int type1, type2;
4563 err = got_object_get_type(&type1, repo, id1);
4564 if (err)
4565 return err;
4566 err = got_object_get_type(&type2, repo, id2);
4567 if (err)
4568 return err;
4570 if (type1 != type2)
4571 return got_error(GOT_ERR_OBJ_TYPE);
4573 s->first_displayed_line = 1;
4574 s->last_displayed_line = view->nlines;
4575 s->selected_line = 1;
4576 s->repo = repo;
4577 s->id1 = id1;
4578 s->id2 = id2;
4579 s->label1 = label1;
4580 s->label2 = label2;
4582 if (id1) {
4583 s->id1 = got_object_id_dup(id1);
4584 if (s->id1 == NULL)
4585 return got_error_from_errno("got_object_id_dup");
4586 } else
4587 s->id1 = NULL;
4589 s->id2 = got_object_id_dup(id2);
4590 if (s->id2 == NULL) {
4591 err = got_error_from_errno("got_object_id_dup");
4592 goto done;
4595 s->f1 = got_opentemp();
4596 if (s->f1 == NULL) {
4597 err = got_error_from_errno("got_opentemp");
4598 goto done;
4601 s->f2 = got_opentemp();
4602 if (s->f2 == NULL) {
4603 err = got_error_from_errno("got_opentemp");
4604 goto done;
4607 s->fd1 = got_opentempfd();
4608 if (s->fd1 == -1) {
4609 err = got_error_from_errno("got_opentempfd");
4610 goto done;
4613 s->fd2 = got_opentempfd();
4614 if (s->fd2 == -1) {
4615 err = got_error_from_errno("got_opentempfd");
4616 goto done;
4619 s->first_displayed_line = 1;
4620 s->last_displayed_line = view->nlines;
4621 s->diff_context = diff_context;
4622 s->ignore_whitespace = ignore_whitespace;
4623 s->force_text_diff = force_text_diff;
4624 s->parent_view = parent_view;
4625 s->repo = repo;
4627 STAILQ_INIT(&s->colors);
4628 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4629 err = add_color(&s->colors,
4630 "^-", TOG_COLOR_DIFF_MINUS,
4631 get_color_value("TOG_COLOR_DIFF_MINUS"));
4632 if (err)
4633 goto done;
4634 err = add_color(&s->colors, "^\\+",
4635 TOG_COLOR_DIFF_PLUS,
4636 get_color_value("TOG_COLOR_DIFF_PLUS"));
4637 if (err)
4638 goto done;
4639 err = add_color(&s->colors,
4640 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4641 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4642 if (err)
4643 goto done;
4645 err = add_color(&s->colors,
4646 "^(commit [0-9a-f]|parent [0-9]|"
4647 "(blob|file|tree|commit) [-+] |"
4648 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4649 get_color_value("TOG_COLOR_DIFF_META"));
4650 if (err)
4651 goto done;
4653 err = add_color(&s->colors,
4654 "^(from|via): ", TOG_COLOR_AUTHOR,
4655 get_color_value("TOG_COLOR_AUTHOR"));
4656 if (err)
4657 goto done;
4659 err = add_color(&s->colors,
4660 "^date: ", TOG_COLOR_DATE,
4661 get_color_value("TOG_COLOR_DATE"));
4662 if (err)
4663 goto done;
4666 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4667 view_is_splitscreen(view))
4668 show_log_view(parent_view); /* draw border */
4669 diff_view_indicate_progress(view);
4671 err = create_diff(s);
4673 view->show = show_diff_view;
4674 view->input = input_diff_view;
4675 view->reset = reset_diff_view;
4676 view->close = close_diff_view;
4677 view->search_start = search_start_diff_view;
4678 view->search_next = search_next_diff_view;
4679 done:
4680 if (err)
4681 close_diff_view(view);
4682 return err;
4685 static const struct got_error *
4686 show_diff_view(struct tog_view *view)
4688 const struct got_error *err;
4689 struct tog_diff_view_state *s = &view->state.diff;
4690 char *id_str1 = NULL, *id_str2, *header;
4691 const char *label1, *label2;
4693 if (s->id1) {
4694 err = got_object_id_str(&id_str1, s->id1);
4695 if (err)
4696 return err;
4697 label1 = s->label1 ? : id_str1;
4698 } else
4699 label1 = "/dev/null";
4701 err = got_object_id_str(&id_str2, s->id2);
4702 if (err)
4703 return err;
4704 label2 = s->label2 ? : id_str2;
4706 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4707 err = got_error_from_errno("asprintf");
4708 free(id_str1);
4709 free(id_str2);
4710 return err;
4712 free(id_str1);
4713 free(id_str2);
4715 err = draw_file(view, header);
4716 free(header);
4717 return err;
4720 static const struct got_error *
4721 set_selected_commit(struct tog_diff_view_state *s,
4722 struct commit_queue_entry *entry)
4724 const struct got_error *err;
4725 const struct got_object_id_queue *parent_ids;
4726 struct got_commit_object *selected_commit;
4727 struct got_object_qid *pid;
4729 free(s->id2);
4730 s->id2 = got_object_id_dup(entry->id);
4731 if (s->id2 == NULL)
4732 return got_error_from_errno("got_object_id_dup");
4734 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4735 if (err)
4736 return err;
4737 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4738 free(s->id1);
4739 pid = STAILQ_FIRST(parent_ids);
4740 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4741 got_object_commit_close(selected_commit);
4742 return NULL;
4745 static const struct got_error *
4746 reset_diff_view(struct tog_view *view)
4748 struct tog_diff_view_state *s = &view->state.diff;
4750 view->count = 0;
4751 wclear(view->window);
4752 s->first_displayed_line = 1;
4753 s->last_displayed_line = view->nlines;
4754 s->matched_line = 0;
4755 diff_view_indicate_progress(view);
4756 return create_diff(s);
4759 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4760 int, int, int);
4761 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4762 int, int);
4764 static const struct got_error *
4765 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4767 const struct got_error *err = NULL;
4768 struct tog_diff_view_state *s = &view->state.diff;
4769 struct tog_log_view_state *ls;
4770 struct commit_queue_entry *old_selected_entry;
4771 char *line = NULL;
4772 size_t linesize = 0;
4773 ssize_t linelen;
4774 int i, nscroll = view->nlines - 1, up = 0;
4776 switch (ch) {
4777 case '0':
4778 view->x = 0;
4779 break;
4780 case '$':
4781 view->x = MAX(view->maxx - view->ncols / 3, 0);
4782 view->count = 0;
4783 break;
4784 case KEY_RIGHT:
4785 case 'l':
4786 if (view->x + view->ncols / 3 < view->maxx)
4787 view->x += 2; /* move two columns right */
4788 else
4789 view->count = 0;
4790 break;
4791 case KEY_LEFT:
4792 case 'h':
4793 view->x -= MIN(view->x, 2); /* move two columns back */
4794 if (view->x <= 0)
4795 view->count = 0;
4796 break;
4797 case 'a':
4798 case 'w':
4799 if (ch == 'a')
4800 s->force_text_diff = !s->force_text_diff;
4801 if (ch == 'w')
4802 s->ignore_whitespace = !s->ignore_whitespace;
4803 err = reset_diff_view(view);
4804 break;
4805 case 'g':
4806 case KEY_HOME:
4807 s->first_displayed_line = 1;
4808 view->count = 0;
4809 break;
4810 case 'G':
4811 case KEY_END:
4812 view->count = 0;
4813 if (s->eof)
4814 break;
4816 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4817 s->eof = 1;
4818 break;
4819 case 'k':
4820 case KEY_UP:
4821 case CTRL('p'):
4822 if (s->first_displayed_line > 1)
4823 s->first_displayed_line--;
4824 else
4825 view->count = 0;
4826 break;
4827 case CTRL('u'):
4828 case 'u':
4829 nscroll /= 2;
4830 /* FALL THROUGH */
4831 case KEY_PPAGE:
4832 case CTRL('b'):
4833 case 'b':
4834 if (s->first_displayed_line == 1) {
4835 view->count = 0;
4836 break;
4838 i = 0;
4839 while (i++ < nscroll && s->first_displayed_line > 1)
4840 s->first_displayed_line--;
4841 break;
4842 case 'j':
4843 case KEY_DOWN:
4844 case CTRL('n'):
4845 if (!s->eof)
4846 s->first_displayed_line++;
4847 else
4848 view->count = 0;
4849 break;
4850 case CTRL('d'):
4851 case 'd':
4852 nscroll /= 2;
4853 /* FALL THROUGH */
4854 case KEY_NPAGE:
4855 case CTRL('f'):
4856 case 'f':
4857 case ' ':
4858 if (s->eof) {
4859 view->count = 0;
4860 break;
4862 i = 0;
4863 while (!s->eof && i++ < nscroll) {
4864 linelen = getline(&line, &linesize, s->f);
4865 s->first_displayed_line++;
4866 if (linelen == -1) {
4867 if (feof(s->f)) {
4868 s->eof = 1;
4869 } else
4870 err = got_ferror(s->f, GOT_ERR_IO);
4871 break;
4874 free(line);
4875 break;
4876 case '[':
4877 if (s->diff_context > 0) {
4878 s->diff_context--;
4879 s->matched_line = 0;
4880 diff_view_indicate_progress(view);
4881 err = create_diff(s);
4882 if (s->first_displayed_line + view->nlines - 1 >
4883 s->nlines) {
4884 s->first_displayed_line = 1;
4885 s->last_displayed_line = view->nlines;
4887 } else
4888 view->count = 0;
4889 break;
4890 case ']':
4891 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4892 s->diff_context++;
4893 s->matched_line = 0;
4894 diff_view_indicate_progress(view);
4895 err = create_diff(s);
4896 } else
4897 view->count = 0;
4898 break;
4899 case '<':
4900 case ',':
4901 case 'K':
4902 up = 1;
4903 /* FALL THROUGH */
4904 case '>':
4905 case '.':
4906 case 'J':
4907 if (s->parent_view == NULL) {
4908 view->count = 0;
4909 break;
4911 s->parent_view->count = view->count;
4913 if (s->parent_view->type == TOG_VIEW_LOG) {
4914 ls = &s->parent_view->state.log;
4915 old_selected_entry = ls->selected_entry;
4917 err = input_log_view(NULL, s->parent_view,
4918 up ? KEY_UP : KEY_DOWN);
4919 if (err)
4920 break;
4921 view->count = s->parent_view->count;
4923 if (old_selected_entry == ls->selected_entry)
4924 break;
4926 err = set_selected_commit(s, ls->selected_entry);
4927 if (err)
4928 break;
4929 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4930 struct tog_blame_view_state *bs;
4931 struct got_object_id *id, *prev_id;
4933 bs = &s->parent_view->state.blame;
4934 prev_id = get_annotation_for_line(bs->blame.lines,
4935 bs->blame.nlines, bs->last_diffed_line);
4937 err = input_blame_view(&view, s->parent_view,
4938 up ? KEY_UP : KEY_DOWN);
4939 if (err)
4940 break;
4941 view->count = s->parent_view->count;
4943 if (prev_id == NULL)
4944 break;
4945 id = get_selected_commit_id(bs->blame.lines,
4946 bs->blame.nlines, bs->first_displayed_line,
4947 bs->selected_line);
4948 if (id == NULL)
4949 break;
4951 if (!got_object_id_cmp(prev_id, id))
4952 break;
4954 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
4955 if (err)
4956 break;
4958 s->first_displayed_line = 1;
4959 s->last_displayed_line = view->nlines;
4960 s->matched_line = 0;
4961 view->x = 0;
4963 diff_view_indicate_progress(view);
4964 err = create_diff(s);
4965 break;
4966 default:
4967 view->count = 0;
4968 break;
4971 return err;
4974 static const struct got_error *
4975 cmd_diff(int argc, char *argv[])
4977 const struct got_error *error = NULL;
4978 struct got_repository *repo = NULL;
4979 struct got_worktree *worktree = NULL;
4980 struct got_object_id *id1 = NULL, *id2 = NULL;
4981 char *repo_path = NULL, *cwd = NULL;
4982 char *id_str1 = NULL, *id_str2 = NULL;
4983 char *label1 = NULL, *label2 = NULL;
4984 int diff_context = 3, ignore_whitespace = 0;
4985 int ch, force_text_diff = 0;
4986 const char *errstr;
4987 struct tog_view *view;
4988 int *pack_fds = NULL;
4990 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4991 switch (ch) {
4992 case 'a':
4993 force_text_diff = 1;
4994 break;
4995 case 'C':
4996 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4997 &errstr);
4998 if (errstr != NULL)
4999 errx(1, "number of context lines is %s: %s",
5000 errstr, errstr);
5001 break;
5002 case 'r':
5003 repo_path = realpath(optarg, NULL);
5004 if (repo_path == NULL)
5005 return got_error_from_errno2("realpath",
5006 optarg);
5007 got_path_strip_trailing_slashes(repo_path);
5008 break;
5009 case 'w':
5010 ignore_whitespace = 1;
5011 break;
5012 default:
5013 usage_diff();
5014 /* NOTREACHED */
5018 argc -= optind;
5019 argv += optind;
5021 if (argc == 0) {
5022 usage_diff(); /* TODO show local worktree changes */
5023 } else if (argc == 2) {
5024 id_str1 = argv[0];
5025 id_str2 = argv[1];
5026 } else
5027 usage_diff();
5029 error = got_repo_pack_fds_open(&pack_fds);
5030 if (error)
5031 goto done;
5033 if (repo_path == NULL) {
5034 cwd = getcwd(NULL, 0);
5035 if (cwd == NULL)
5036 return got_error_from_errno("getcwd");
5037 error = got_worktree_open(&worktree, cwd);
5038 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5039 goto done;
5040 if (worktree)
5041 repo_path =
5042 strdup(got_worktree_get_repo_path(worktree));
5043 else
5044 repo_path = strdup(cwd);
5045 if (repo_path == NULL) {
5046 error = got_error_from_errno("strdup");
5047 goto done;
5051 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5052 if (error)
5053 goto done;
5055 init_curses();
5057 error = apply_unveil(got_repo_get_path(repo), NULL);
5058 if (error)
5059 goto done;
5061 error = tog_load_refs(repo, 0);
5062 if (error)
5063 goto done;
5065 error = got_repo_match_object_id(&id1, &label1, id_str1,
5066 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5067 if (error)
5068 goto done;
5070 error = got_repo_match_object_id(&id2, &label2, id_str2,
5071 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5072 if (error)
5073 goto done;
5075 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5076 if (view == NULL) {
5077 error = got_error_from_errno("view_open");
5078 goto done;
5080 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5081 ignore_whitespace, force_text_diff, NULL, repo);
5082 if (error)
5083 goto done;
5084 error = view_loop(view);
5085 done:
5086 free(label1);
5087 free(label2);
5088 free(repo_path);
5089 free(cwd);
5090 if (repo) {
5091 const struct got_error *close_err = got_repo_close(repo);
5092 if (error == NULL)
5093 error = close_err;
5095 if (worktree)
5096 got_worktree_close(worktree);
5097 if (pack_fds) {
5098 const struct got_error *pack_err =
5099 got_repo_pack_fds_close(pack_fds);
5100 if (error == NULL)
5101 error = pack_err;
5103 tog_free_refs();
5104 return error;
5107 __dead static void
5108 usage_blame(void)
5110 endwin();
5111 fprintf(stderr,
5112 "usage: %s blame [-c commit] [-r repository-path] path\n",
5113 getprogname());
5114 exit(1);
5117 struct tog_blame_line {
5118 int annotated;
5119 struct got_object_id *id;
5122 static const struct got_error *
5123 draw_blame(struct tog_view *view)
5125 struct tog_blame_view_state *s = &view->state.blame;
5126 struct tog_blame *blame = &s->blame;
5127 regmatch_t *regmatch = &view->regmatch;
5128 const struct got_error *err;
5129 int lineno = 0, nprinted = 0;
5130 char *line = NULL;
5131 size_t linesize = 0;
5132 ssize_t linelen;
5133 wchar_t *wline;
5134 int width;
5135 struct tog_blame_line *blame_line;
5136 struct got_object_id *prev_id = NULL;
5137 char *id_str;
5138 struct tog_color *tc;
5140 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5141 if (err)
5142 return err;
5144 rewind(blame->f);
5145 werase(view->window);
5147 if (asprintf(&line, "commit %s", id_str) == -1) {
5148 err = got_error_from_errno("asprintf");
5149 free(id_str);
5150 return err;
5153 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5154 free(line);
5155 line = NULL;
5156 if (err)
5157 return err;
5158 if (view_needs_focus_indication(view))
5159 wstandout(view->window);
5160 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5161 if (tc)
5162 wattr_on(view->window,
5163 COLOR_PAIR(tc->colorpair), NULL);
5164 waddwstr(view->window, wline);
5165 if (tc)
5166 wattr_off(view->window,
5167 COLOR_PAIR(tc->colorpair), NULL);
5168 if (view_needs_focus_indication(view))
5169 wstandend(view->window);
5170 free(wline);
5171 wline = NULL;
5172 if (width < view->ncols - 1)
5173 waddch(view->window, '\n');
5175 if (view->gline > blame->nlines)
5176 view->gline = blame->nlines;
5178 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5179 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5180 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5181 free(id_str);
5182 return got_error_from_errno("asprintf");
5184 free(id_str);
5185 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5186 free(line);
5187 line = NULL;
5188 if (err)
5189 return err;
5190 waddwstr(view->window, wline);
5191 free(wline);
5192 wline = NULL;
5193 if (width < view->ncols - 1)
5194 waddch(view->window, '\n');
5196 s->eof = 0;
5197 view->maxx = 0;
5198 while (nprinted < view->nlines - 2) {
5199 linelen = getline(&line, &linesize, blame->f);
5200 if (linelen == -1) {
5201 if (feof(blame->f)) {
5202 s->eof = 1;
5203 break;
5205 free(line);
5206 return got_ferror(blame->f, GOT_ERR_IO);
5208 if (++lineno < s->first_displayed_line)
5209 continue;
5210 if (view->gline && !gotoline(view, &lineno, &nprinted))
5211 continue;
5213 /* Set view->maxx based on full line length. */
5214 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5215 if (err) {
5216 free(line);
5217 return err;
5219 free(wline);
5220 wline = NULL;
5221 view->maxx = MAX(view->maxx, width);
5223 if (nprinted == s->selected_line - 1)
5224 wstandout(view->window);
5226 if (blame->nlines > 0) {
5227 blame_line = &blame->lines[lineno - 1];
5228 if (blame_line->annotated && prev_id &&
5229 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5230 !(nprinted == s->selected_line - 1)) {
5231 waddstr(view->window, " ");
5232 } else if (blame_line->annotated) {
5233 char *id_str;
5234 err = got_object_id_str(&id_str,
5235 blame_line->id);
5236 if (err) {
5237 free(line);
5238 return err;
5240 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5241 if (tc)
5242 wattr_on(view->window,
5243 COLOR_PAIR(tc->colorpair), NULL);
5244 wprintw(view->window, "%.8s", id_str);
5245 if (tc)
5246 wattr_off(view->window,
5247 COLOR_PAIR(tc->colorpair), NULL);
5248 free(id_str);
5249 prev_id = blame_line->id;
5250 } else {
5251 waddstr(view->window, "........");
5252 prev_id = NULL;
5254 } else {
5255 waddstr(view->window, "........");
5256 prev_id = NULL;
5259 if (nprinted == s->selected_line - 1)
5260 wstandend(view->window);
5261 waddstr(view->window, " ");
5263 if (view->ncols <= 9) {
5264 width = 9;
5265 } else if (s->first_displayed_line + nprinted ==
5266 s->matched_line &&
5267 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5268 err = add_matched_line(&width, line, view->ncols - 9, 9,
5269 view->window, view->x, regmatch);
5270 if (err) {
5271 free(line);
5272 return err;
5274 width += 9;
5275 } else {
5276 int skip;
5277 err = format_line(&wline, &width, &skip, line,
5278 view->x, view->ncols - 9, 9, 1);
5279 if (err) {
5280 free(line);
5281 return err;
5283 waddwstr(view->window, &wline[skip]);
5284 width += 9;
5285 free(wline);
5286 wline = NULL;
5289 if (width <= view->ncols - 1)
5290 waddch(view->window, '\n');
5291 if (++nprinted == 1)
5292 s->first_displayed_line = lineno;
5294 free(line);
5295 s->last_displayed_line = lineno;
5297 view_border(view);
5299 return NULL;
5302 static const struct got_error *
5303 blame_cb(void *arg, int nlines, int lineno,
5304 struct got_commit_object *commit, struct got_object_id *id)
5306 const struct got_error *err = NULL;
5307 struct tog_blame_cb_args *a = arg;
5308 struct tog_blame_line *line;
5309 int errcode;
5311 if (nlines != a->nlines ||
5312 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5313 return got_error(GOT_ERR_RANGE);
5315 errcode = pthread_mutex_lock(&tog_mutex);
5316 if (errcode)
5317 return got_error_set_errno(errcode, "pthread_mutex_lock");
5319 if (*a->quit) { /* user has quit the blame view */
5320 err = got_error(GOT_ERR_ITER_COMPLETED);
5321 goto done;
5324 if (lineno == -1)
5325 goto done; /* no change in this commit */
5327 line = &a->lines[lineno - 1];
5328 if (line->annotated)
5329 goto done;
5331 line->id = got_object_id_dup(id);
5332 if (line->id == NULL) {
5333 err = got_error_from_errno("got_object_id_dup");
5334 goto done;
5336 line->annotated = 1;
5337 done:
5338 errcode = pthread_mutex_unlock(&tog_mutex);
5339 if (errcode)
5340 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5341 return err;
5344 static void *
5345 blame_thread(void *arg)
5347 const struct got_error *err, *close_err;
5348 struct tog_blame_thread_args *ta = arg;
5349 struct tog_blame_cb_args *a = ta->cb_args;
5350 int errcode, fd1 = -1, fd2 = -1;
5351 FILE *f1 = NULL, *f2 = NULL;
5353 fd1 = got_opentempfd();
5354 if (fd1 == -1)
5355 return (void *)got_error_from_errno("got_opentempfd");
5357 fd2 = got_opentempfd();
5358 if (fd2 == -1) {
5359 err = got_error_from_errno("got_opentempfd");
5360 goto done;
5363 f1 = got_opentemp();
5364 if (f1 == NULL) {
5365 err = (void *)got_error_from_errno("got_opentemp");
5366 goto done;
5368 f2 = got_opentemp();
5369 if (f2 == NULL) {
5370 err = (void *)got_error_from_errno("got_opentemp");
5371 goto done;
5374 err = block_signals_used_by_main_thread();
5375 if (err)
5376 goto done;
5378 err = got_blame(ta->path, a->commit_id, ta->repo,
5379 tog_diff_algo, blame_cb, ta->cb_args,
5380 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5381 if (err && err->code == GOT_ERR_CANCELLED)
5382 err = NULL;
5384 errcode = pthread_mutex_lock(&tog_mutex);
5385 if (errcode) {
5386 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5387 goto done;
5390 close_err = got_repo_close(ta->repo);
5391 if (err == NULL)
5392 err = close_err;
5393 ta->repo = NULL;
5394 *ta->complete = 1;
5396 errcode = pthread_mutex_unlock(&tog_mutex);
5397 if (errcode && err == NULL)
5398 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5400 done:
5401 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5402 err = got_error_from_errno("close");
5403 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5404 err = got_error_from_errno("close");
5405 if (f1 && fclose(f1) == EOF && err == NULL)
5406 err = got_error_from_errno("fclose");
5407 if (f2 && fclose(f2) == EOF && err == NULL)
5408 err = got_error_from_errno("fclose");
5410 return (void *)err;
5413 static struct got_object_id *
5414 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5415 int first_displayed_line, int selected_line)
5417 struct tog_blame_line *line;
5419 if (nlines <= 0)
5420 return NULL;
5422 line = &lines[first_displayed_line - 1 + selected_line - 1];
5423 if (!line->annotated)
5424 return NULL;
5426 return line->id;
5429 static struct got_object_id *
5430 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5431 int lineno)
5433 struct tog_blame_line *line;
5435 if (nlines <= 0 || lineno >= nlines)
5436 return NULL;
5438 line = &lines[lineno - 1];
5439 if (!line->annotated)
5440 return NULL;
5442 return line->id;
5445 static const struct got_error *
5446 stop_blame(struct tog_blame *blame)
5448 const struct got_error *err = NULL;
5449 int i;
5451 if (blame->thread) {
5452 int errcode;
5453 errcode = pthread_mutex_unlock(&tog_mutex);
5454 if (errcode)
5455 return got_error_set_errno(errcode,
5456 "pthread_mutex_unlock");
5457 errcode = pthread_join(blame->thread, (void **)&err);
5458 if (errcode)
5459 return got_error_set_errno(errcode, "pthread_join");
5460 errcode = pthread_mutex_lock(&tog_mutex);
5461 if (errcode)
5462 return got_error_set_errno(errcode,
5463 "pthread_mutex_lock");
5464 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5465 err = NULL;
5466 blame->thread = NULL;
5468 if (blame->thread_args.repo) {
5469 const struct got_error *close_err;
5470 close_err = got_repo_close(blame->thread_args.repo);
5471 if (err == NULL)
5472 err = close_err;
5473 blame->thread_args.repo = NULL;
5475 if (blame->f) {
5476 if (fclose(blame->f) == EOF && err == NULL)
5477 err = got_error_from_errno("fclose");
5478 blame->f = NULL;
5480 if (blame->lines) {
5481 for (i = 0; i < blame->nlines; i++)
5482 free(blame->lines[i].id);
5483 free(blame->lines);
5484 blame->lines = NULL;
5486 free(blame->cb_args.commit_id);
5487 blame->cb_args.commit_id = NULL;
5488 if (blame->pack_fds) {
5489 const struct got_error *pack_err =
5490 got_repo_pack_fds_close(blame->pack_fds);
5491 if (err == NULL)
5492 err = pack_err;
5493 blame->pack_fds = NULL;
5495 return err;
5498 static const struct got_error *
5499 cancel_blame_view(void *arg)
5501 const struct got_error *err = NULL;
5502 int *done = arg;
5503 int errcode;
5505 errcode = pthread_mutex_lock(&tog_mutex);
5506 if (errcode)
5507 return got_error_set_errno(errcode,
5508 "pthread_mutex_unlock");
5510 if (*done)
5511 err = got_error(GOT_ERR_CANCELLED);
5513 errcode = pthread_mutex_unlock(&tog_mutex);
5514 if (errcode)
5515 return got_error_set_errno(errcode,
5516 "pthread_mutex_lock");
5518 return err;
5521 static const struct got_error *
5522 run_blame(struct tog_view *view)
5524 struct tog_blame_view_state *s = &view->state.blame;
5525 struct tog_blame *blame = &s->blame;
5526 const struct got_error *err = NULL;
5527 struct got_commit_object *commit = NULL;
5528 struct got_blob_object *blob = NULL;
5529 struct got_repository *thread_repo = NULL;
5530 struct got_object_id *obj_id = NULL;
5531 int obj_type, fd = -1;
5532 int *pack_fds = NULL;
5534 err = got_object_open_as_commit(&commit, s->repo,
5535 &s->blamed_commit->id);
5536 if (err)
5537 return err;
5539 fd = got_opentempfd();
5540 if (fd == -1) {
5541 err = got_error_from_errno("got_opentempfd");
5542 goto done;
5545 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5546 if (err)
5547 goto done;
5549 err = got_object_get_type(&obj_type, s->repo, obj_id);
5550 if (err)
5551 goto done;
5553 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5554 err = got_error(GOT_ERR_OBJ_TYPE);
5555 goto done;
5558 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5559 if (err)
5560 goto done;
5561 blame->f = got_opentemp();
5562 if (blame->f == NULL) {
5563 err = got_error_from_errno("got_opentemp");
5564 goto done;
5566 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5567 &blame->line_offsets, blame->f, blob);
5568 if (err)
5569 goto done;
5570 if (blame->nlines == 0) {
5571 s->blame_complete = 1;
5572 goto done;
5575 /* Don't include \n at EOF in the blame line count. */
5576 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5577 blame->nlines--;
5579 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5580 if (blame->lines == NULL) {
5581 err = got_error_from_errno("calloc");
5582 goto done;
5585 err = got_repo_pack_fds_open(&pack_fds);
5586 if (err)
5587 goto done;
5588 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5589 pack_fds);
5590 if (err)
5591 goto done;
5593 blame->pack_fds = pack_fds;
5594 blame->cb_args.view = view;
5595 blame->cb_args.lines = blame->lines;
5596 blame->cb_args.nlines = blame->nlines;
5597 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5598 if (blame->cb_args.commit_id == NULL) {
5599 err = got_error_from_errno("got_object_id_dup");
5600 goto done;
5602 blame->cb_args.quit = &s->done;
5604 blame->thread_args.path = s->path;
5605 blame->thread_args.repo = thread_repo;
5606 blame->thread_args.cb_args = &blame->cb_args;
5607 blame->thread_args.complete = &s->blame_complete;
5608 blame->thread_args.cancel_cb = cancel_blame_view;
5609 blame->thread_args.cancel_arg = &s->done;
5610 s->blame_complete = 0;
5612 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5613 s->first_displayed_line = 1;
5614 s->last_displayed_line = view->nlines;
5615 s->selected_line = 1;
5617 s->matched_line = 0;
5619 done:
5620 if (commit)
5621 got_object_commit_close(commit);
5622 if (fd != -1 && close(fd) == -1 && err == NULL)
5623 err = got_error_from_errno("close");
5624 if (blob)
5625 got_object_blob_close(blob);
5626 free(obj_id);
5627 if (err)
5628 stop_blame(blame);
5629 return err;
5632 static const struct got_error *
5633 open_blame_view(struct tog_view *view, char *path,
5634 struct got_object_id *commit_id, struct got_repository *repo)
5636 const struct got_error *err = NULL;
5637 struct tog_blame_view_state *s = &view->state.blame;
5639 STAILQ_INIT(&s->blamed_commits);
5641 s->path = strdup(path);
5642 if (s->path == NULL)
5643 return got_error_from_errno("strdup");
5645 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5646 if (err) {
5647 free(s->path);
5648 return err;
5651 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5652 s->first_displayed_line = 1;
5653 s->last_displayed_line = view->nlines;
5654 s->selected_line = 1;
5655 s->blame_complete = 0;
5656 s->repo = repo;
5657 s->commit_id = commit_id;
5658 memset(&s->blame, 0, sizeof(s->blame));
5660 STAILQ_INIT(&s->colors);
5661 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5662 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5663 get_color_value("TOG_COLOR_COMMIT"));
5664 if (err)
5665 return err;
5668 view->show = show_blame_view;
5669 view->input = input_blame_view;
5670 view->reset = reset_blame_view;
5671 view->close = close_blame_view;
5672 view->search_start = search_start_blame_view;
5673 view->search_next = search_next_blame_view;
5675 return run_blame(view);
5678 static const struct got_error *
5679 close_blame_view(struct tog_view *view)
5681 const struct got_error *err = NULL;
5682 struct tog_blame_view_state *s = &view->state.blame;
5684 if (s->blame.thread)
5685 err = stop_blame(&s->blame);
5687 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5688 struct got_object_qid *blamed_commit;
5689 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5690 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5691 got_object_qid_free(blamed_commit);
5694 free(s->path);
5695 free_colors(&s->colors);
5696 return err;
5699 static const struct got_error *
5700 search_start_blame_view(struct tog_view *view)
5702 struct tog_blame_view_state *s = &view->state.blame;
5704 s->matched_line = 0;
5705 return NULL;
5708 static const struct got_error *
5709 search_next_blame_view(struct tog_view *view)
5711 struct tog_blame_view_state *s = &view->state.blame;
5712 const struct got_error *err = NULL;
5713 int lineno;
5714 char *line = NULL;
5715 size_t linesize = 0;
5716 ssize_t linelen;
5718 if (!view->searching) {
5719 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5720 return NULL;
5723 if (s->matched_line) {
5724 if (view->searching == TOG_SEARCH_FORWARD)
5725 lineno = s->matched_line + 1;
5726 else
5727 lineno = s->matched_line - 1;
5728 } else
5729 lineno = s->first_displayed_line - 1 + s->selected_line;
5731 while (1) {
5732 off_t offset;
5734 if (lineno <= 0 || lineno > s->blame.nlines) {
5735 if (s->matched_line == 0) {
5736 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5737 break;
5740 if (view->searching == TOG_SEARCH_FORWARD)
5741 lineno = 1;
5742 else
5743 lineno = s->blame.nlines;
5746 offset = s->blame.line_offsets[lineno - 1];
5747 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5748 free(line);
5749 return got_error_from_errno("fseeko");
5751 linelen = getline(&line, &linesize, s->blame.f);
5752 if (linelen != -1) {
5753 char *exstr;
5754 err = expand_tab(&exstr, line);
5755 if (err)
5756 break;
5757 if (match_line(exstr, &view->regex, 1,
5758 &view->regmatch)) {
5759 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5760 s->matched_line = lineno;
5761 free(exstr);
5762 break;
5764 free(exstr);
5766 if (view->searching == TOG_SEARCH_FORWARD)
5767 lineno++;
5768 else
5769 lineno--;
5771 free(line);
5773 if (s->matched_line) {
5774 s->first_displayed_line = s->matched_line;
5775 s->selected_line = 1;
5778 return err;
5781 static const struct got_error *
5782 show_blame_view(struct tog_view *view)
5784 const struct got_error *err = NULL;
5785 struct tog_blame_view_state *s = &view->state.blame;
5786 int errcode;
5788 if (s->blame.thread == NULL && !s->blame_complete) {
5789 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5790 &s->blame.thread_args);
5791 if (errcode)
5792 return got_error_set_errno(errcode, "pthread_create");
5794 halfdelay(1); /* fast refresh while annotating */
5797 if (s->blame_complete)
5798 halfdelay(10); /* disable fast refresh */
5800 err = draw_blame(view);
5802 view_border(view);
5803 return err;
5806 static const struct got_error *
5807 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5808 struct got_repository *repo, struct got_object_id *id)
5810 struct tog_view *log_view;
5811 const struct got_error *err = NULL;
5813 *new_view = NULL;
5815 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5816 if (log_view == NULL)
5817 return got_error_from_errno("view_open");
5819 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5820 if (err)
5821 view_close(log_view);
5822 else
5823 *new_view = log_view;
5825 return err;
5828 static const struct got_error *
5829 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5831 const struct got_error *err = NULL, *thread_err = NULL;
5832 struct tog_view *diff_view;
5833 struct tog_blame_view_state *s = &view->state.blame;
5834 int eos, nscroll, begin_y = 0, begin_x = 0;
5836 eos = nscroll = view->nlines - 2;
5837 if (view_is_hsplit_top(view))
5838 --eos; /* border */
5840 switch (ch) {
5841 case '0':
5842 view->x = 0;
5843 break;
5844 case '$':
5845 view->x = MAX(view->maxx - view->ncols / 3, 0);
5846 view->count = 0;
5847 break;
5848 case KEY_RIGHT:
5849 case 'l':
5850 if (view->x + view->ncols / 3 < view->maxx)
5851 view->x += 2; /* move two columns right */
5852 else
5853 view->count = 0;
5854 break;
5855 case KEY_LEFT:
5856 case 'h':
5857 view->x -= MIN(view->x, 2); /* move two columns back */
5858 if (view->x <= 0)
5859 view->count = 0;
5860 break;
5861 case 'q':
5862 s->done = 1;
5863 break;
5864 case 'g':
5865 case KEY_HOME:
5866 s->selected_line = 1;
5867 s->first_displayed_line = 1;
5868 view->count = 0;
5869 break;
5870 case 'G':
5871 case KEY_END:
5872 if (s->blame.nlines < eos) {
5873 s->selected_line = s->blame.nlines;
5874 s->first_displayed_line = 1;
5875 } else {
5876 s->selected_line = eos;
5877 s->first_displayed_line = s->blame.nlines - (eos - 1);
5879 view->count = 0;
5880 break;
5881 case 'k':
5882 case KEY_UP:
5883 case CTRL('p'):
5884 if (s->selected_line > 1)
5885 s->selected_line--;
5886 else if (s->selected_line == 1 &&
5887 s->first_displayed_line > 1)
5888 s->first_displayed_line--;
5889 else
5890 view->count = 0;
5891 break;
5892 case CTRL('u'):
5893 case 'u':
5894 nscroll /= 2;
5895 /* FALL THROUGH */
5896 case KEY_PPAGE:
5897 case CTRL('b'):
5898 case 'b':
5899 if (s->first_displayed_line == 1) {
5900 if (view->count > 1)
5901 nscroll += nscroll;
5902 s->selected_line = MAX(1, s->selected_line - nscroll);
5903 view->count = 0;
5904 break;
5906 if (s->first_displayed_line > nscroll)
5907 s->first_displayed_line -= nscroll;
5908 else
5909 s->first_displayed_line = 1;
5910 break;
5911 case 'j':
5912 case KEY_DOWN:
5913 case CTRL('n'):
5914 if (s->selected_line < eos && s->first_displayed_line +
5915 s->selected_line <= s->blame.nlines)
5916 s->selected_line++;
5917 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5918 s->first_displayed_line++;
5919 else
5920 view->count = 0;
5921 break;
5922 case 'c':
5923 case 'p': {
5924 struct got_object_id *id = NULL;
5926 view->count = 0;
5927 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5928 s->first_displayed_line, s->selected_line);
5929 if (id == NULL)
5930 break;
5931 if (ch == 'p') {
5932 struct got_commit_object *commit, *pcommit;
5933 struct got_object_qid *pid;
5934 struct got_object_id *blob_id = NULL;
5935 int obj_type;
5936 err = got_object_open_as_commit(&commit,
5937 s->repo, id);
5938 if (err)
5939 break;
5940 pid = STAILQ_FIRST(
5941 got_object_commit_get_parent_ids(commit));
5942 if (pid == NULL) {
5943 got_object_commit_close(commit);
5944 break;
5946 /* Check if path history ends here. */
5947 err = got_object_open_as_commit(&pcommit,
5948 s->repo, &pid->id);
5949 if (err)
5950 break;
5951 err = got_object_id_by_path(&blob_id, s->repo,
5952 pcommit, s->path);
5953 got_object_commit_close(pcommit);
5954 if (err) {
5955 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5956 err = NULL;
5957 got_object_commit_close(commit);
5958 break;
5960 err = got_object_get_type(&obj_type, s->repo,
5961 blob_id);
5962 free(blob_id);
5963 /* Can't blame non-blob type objects. */
5964 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5965 got_object_commit_close(commit);
5966 break;
5968 err = got_object_qid_alloc(&s->blamed_commit,
5969 &pid->id);
5970 got_object_commit_close(commit);
5971 } else {
5972 if (got_object_id_cmp(id,
5973 &s->blamed_commit->id) == 0)
5974 break;
5975 err = got_object_qid_alloc(&s->blamed_commit,
5976 id);
5978 if (err)
5979 break;
5980 s->done = 1;
5981 thread_err = stop_blame(&s->blame);
5982 s->done = 0;
5983 if (thread_err)
5984 break;
5985 STAILQ_INSERT_HEAD(&s->blamed_commits,
5986 s->blamed_commit, entry);
5987 err = run_blame(view);
5988 if (err)
5989 break;
5990 break;
5992 case 'C': {
5993 struct got_object_qid *first;
5995 view->count = 0;
5996 first = STAILQ_FIRST(&s->blamed_commits);
5997 if (!got_object_id_cmp(&first->id, s->commit_id))
5998 break;
5999 s->done = 1;
6000 thread_err = stop_blame(&s->blame);
6001 s->done = 0;
6002 if (thread_err)
6003 break;
6004 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6005 got_object_qid_free(s->blamed_commit);
6006 s->blamed_commit =
6007 STAILQ_FIRST(&s->blamed_commits);
6008 err = run_blame(view);
6009 if (err)
6010 break;
6011 break;
6013 case 'L':
6014 view->count = 0;
6015 s->id_to_log = get_selected_commit_id(s->blame.lines,
6016 s->blame.nlines, s->first_displayed_line, s->selected_line);
6017 if (s->id_to_log)
6018 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6019 break;
6020 case KEY_ENTER:
6021 case '\r': {
6022 struct got_object_id *id = NULL;
6023 struct got_object_qid *pid;
6024 struct got_commit_object *commit = NULL;
6026 view->count = 0;
6027 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6028 s->first_displayed_line, s->selected_line);
6029 if (id == NULL)
6030 break;
6031 err = got_object_open_as_commit(&commit, s->repo, id);
6032 if (err)
6033 break;
6034 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6035 if (*new_view) {
6036 /* traversed from diff view, release diff resources */
6037 err = close_diff_view(*new_view);
6038 if (err)
6039 break;
6040 diff_view = *new_view;
6041 } else {
6042 if (view_is_parent_view(view))
6043 view_get_split(view, &begin_y, &begin_x);
6045 diff_view = view_open(0, 0, begin_y, begin_x,
6046 TOG_VIEW_DIFF);
6047 if (diff_view == NULL) {
6048 got_object_commit_close(commit);
6049 err = got_error_from_errno("view_open");
6050 break;
6053 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6054 id, NULL, NULL, 3, 0, 0, view, s->repo);
6055 got_object_commit_close(commit);
6056 if (err) {
6057 view_close(diff_view);
6058 break;
6060 s->last_diffed_line = s->first_displayed_line - 1 +
6061 s->selected_line;
6062 if (*new_view)
6063 break; /* still open from active diff view */
6064 if (view_is_parent_view(view) &&
6065 view->mode == TOG_VIEW_SPLIT_HRZN) {
6066 err = view_init_hsplit(view, begin_y);
6067 if (err)
6068 break;
6071 view->focussed = 0;
6072 diff_view->focussed = 1;
6073 diff_view->mode = view->mode;
6074 diff_view->nlines = view->lines - begin_y;
6075 if (view_is_parent_view(view)) {
6076 view_transfer_size(diff_view, view);
6077 err = view_close_child(view);
6078 if (err)
6079 break;
6080 err = view_set_child(view, diff_view);
6081 if (err)
6082 break;
6083 view->focus_child = 1;
6084 } else
6085 *new_view = diff_view;
6086 if (err)
6087 break;
6088 break;
6090 case CTRL('d'):
6091 case 'd':
6092 nscroll /= 2;
6093 /* FALL THROUGH */
6094 case KEY_NPAGE:
6095 case CTRL('f'):
6096 case 'f':
6097 case ' ':
6098 if (s->last_displayed_line >= s->blame.nlines &&
6099 s->selected_line >= MIN(s->blame.nlines,
6100 view->nlines - 2)) {
6101 view->count = 0;
6102 break;
6104 if (s->last_displayed_line >= s->blame.nlines &&
6105 s->selected_line < view->nlines - 2) {
6106 s->selected_line +=
6107 MIN(nscroll, s->last_displayed_line -
6108 s->first_displayed_line - s->selected_line + 1);
6110 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6111 s->first_displayed_line += nscroll;
6112 else
6113 s->first_displayed_line =
6114 s->blame.nlines - (view->nlines - 3);
6115 break;
6116 case KEY_RESIZE:
6117 if (s->selected_line > view->nlines - 2) {
6118 s->selected_line = MIN(s->blame.nlines,
6119 view->nlines - 2);
6121 break;
6122 default:
6123 view->count = 0;
6124 break;
6126 return thread_err ? thread_err : err;
6129 static const struct got_error *
6130 reset_blame_view(struct tog_view *view)
6132 const struct got_error *err;
6133 struct tog_blame_view_state *s = &view->state.blame;
6135 view->count = 0;
6136 s->done = 1;
6137 err = stop_blame(&s->blame);
6138 s->done = 0;
6139 if (err)
6140 return err;
6141 return run_blame(view);
6144 static const struct got_error *
6145 cmd_blame(int argc, char *argv[])
6147 const struct got_error *error;
6148 struct got_repository *repo = NULL;
6149 struct got_worktree *worktree = NULL;
6150 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6151 char *link_target = NULL;
6152 struct got_object_id *commit_id = NULL;
6153 struct got_commit_object *commit = NULL;
6154 char *commit_id_str = NULL;
6155 int ch;
6156 struct tog_view *view;
6157 int *pack_fds = NULL;
6159 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6160 switch (ch) {
6161 case 'c':
6162 commit_id_str = optarg;
6163 break;
6164 case 'r':
6165 repo_path = realpath(optarg, NULL);
6166 if (repo_path == NULL)
6167 return got_error_from_errno2("realpath",
6168 optarg);
6169 break;
6170 default:
6171 usage_blame();
6172 /* NOTREACHED */
6176 argc -= optind;
6177 argv += optind;
6179 if (argc != 1)
6180 usage_blame();
6182 error = got_repo_pack_fds_open(&pack_fds);
6183 if (error != NULL)
6184 goto done;
6186 if (repo_path == NULL) {
6187 cwd = getcwd(NULL, 0);
6188 if (cwd == NULL)
6189 return got_error_from_errno("getcwd");
6190 error = got_worktree_open(&worktree, cwd);
6191 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6192 goto done;
6193 if (worktree)
6194 repo_path =
6195 strdup(got_worktree_get_repo_path(worktree));
6196 else
6197 repo_path = strdup(cwd);
6198 if (repo_path == NULL) {
6199 error = got_error_from_errno("strdup");
6200 goto done;
6204 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6205 if (error != NULL)
6206 goto done;
6208 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6209 worktree);
6210 if (error)
6211 goto done;
6213 init_curses();
6215 error = apply_unveil(got_repo_get_path(repo), NULL);
6216 if (error)
6217 goto done;
6219 error = tog_load_refs(repo, 0);
6220 if (error)
6221 goto done;
6223 if (commit_id_str == NULL) {
6224 struct got_reference *head_ref;
6225 error = got_ref_open(&head_ref, repo, worktree ?
6226 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6227 if (error != NULL)
6228 goto done;
6229 error = got_ref_resolve(&commit_id, repo, head_ref);
6230 got_ref_close(head_ref);
6231 } else {
6232 error = got_repo_match_object_id(&commit_id, NULL,
6233 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6235 if (error != NULL)
6236 goto done;
6238 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6239 if (view == NULL) {
6240 error = got_error_from_errno("view_open");
6241 goto done;
6244 error = got_object_open_as_commit(&commit, repo, commit_id);
6245 if (error)
6246 goto done;
6248 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6249 commit, repo);
6250 if (error)
6251 goto done;
6253 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6254 commit_id, repo);
6255 if (error)
6256 goto done;
6257 if (worktree) {
6258 /* Release work tree lock. */
6259 got_worktree_close(worktree);
6260 worktree = NULL;
6262 error = view_loop(view);
6263 done:
6264 free(repo_path);
6265 free(in_repo_path);
6266 free(link_target);
6267 free(cwd);
6268 free(commit_id);
6269 if (commit)
6270 got_object_commit_close(commit);
6271 if (worktree)
6272 got_worktree_close(worktree);
6273 if (repo) {
6274 const struct got_error *close_err = got_repo_close(repo);
6275 if (error == NULL)
6276 error = close_err;
6278 if (pack_fds) {
6279 const struct got_error *pack_err =
6280 got_repo_pack_fds_close(pack_fds);
6281 if (error == NULL)
6282 error = pack_err;
6284 tog_free_refs();
6285 return error;
6288 static const struct got_error *
6289 draw_tree_entries(struct tog_view *view, const char *parent_path)
6291 struct tog_tree_view_state *s = &view->state.tree;
6292 const struct got_error *err = NULL;
6293 struct got_tree_entry *te;
6294 wchar_t *wline;
6295 struct tog_color *tc;
6296 int width, n, nentries, i = 1;
6297 int limit = view->nlines;
6299 s->ndisplayed = 0;
6300 if (view_is_hsplit_top(view))
6301 --limit; /* border */
6303 werase(view->window);
6305 if (limit == 0)
6306 return NULL;
6308 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6309 0, 0);
6310 if (err)
6311 return err;
6312 if (view_needs_focus_indication(view))
6313 wstandout(view->window);
6314 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6315 if (tc)
6316 wattr_on(view->window,
6317 COLOR_PAIR(tc->colorpair), NULL);
6318 waddwstr(view->window, wline);
6319 if (tc)
6320 wattr_off(view->window,
6321 COLOR_PAIR(tc->colorpair), NULL);
6322 if (view_needs_focus_indication(view))
6323 wstandend(view->window);
6324 free(wline);
6325 wline = NULL;
6327 if (s->selected_entry) {
6328 i = got_tree_entry_get_index(s->selected_entry);
6329 i += s->tree == s->root ? 1 : 2; /* account for ".." entry */
6331 nentries = got_object_tree_get_nentries(s->tree);
6332 wprintw(view->window, " [%d/%d]", i,
6333 nentries + (s->tree == s->root ? 0 : 1)); /* ".." in !root tree */
6335 if (width < view->ncols - 1)
6336 waddch(view->window, '\n');
6337 if (--limit <= 0)
6338 return NULL;
6339 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6340 0, 0);
6341 if (err)
6342 return err;
6343 waddwstr(view->window, wline);
6344 free(wline);
6345 wline = NULL;
6346 if (width < view->ncols - 1)
6347 waddch(view->window, '\n');
6348 if (--limit <= 0)
6349 return NULL;
6350 waddch(view->window, '\n');
6351 if (--limit <= 0)
6352 return NULL;
6354 if (s->first_displayed_entry == NULL) {
6355 te = got_object_tree_get_first_entry(s->tree);
6356 if (s->selected == 0) {
6357 if (view->focussed)
6358 wstandout(view->window);
6359 s->selected_entry = NULL;
6361 waddstr(view->window, " ..\n"); /* parent directory */
6362 if (s->selected == 0 && view->focussed)
6363 wstandend(view->window);
6364 s->ndisplayed++;
6365 if (--limit <= 0)
6366 return NULL;
6367 n = 1;
6368 } else {
6369 n = 0;
6370 te = s->first_displayed_entry;
6373 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6374 char *line = NULL, *id_str = NULL, *link_target = NULL;
6375 const char *modestr = "";
6376 mode_t mode;
6378 te = got_object_tree_get_entry(s->tree, i);
6379 mode = got_tree_entry_get_mode(te);
6381 if (s->show_ids) {
6382 err = got_object_id_str(&id_str,
6383 got_tree_entry_get_id(te));
6384 if (err)
6385 return got_error_from_errno(
6386 "got_object_id_str");
6388 if (got_object_tree_entry_is_submodule(te))
6389 modestr = "$";
6390 else if (S_ISLNK(mode)) {
6391 int i;
6393 err = got_tree_entry_get_symlink_target(&link_target,
6394 te, s->repo);
6395 if (err) {
6396 free(id_str);
6397 return err;
6399 for (i = 0; i < strlen(link_target); i++) {
6400 if (!isprint((unsigned char)link_target[i]))
6401 link_target[i] = '?';
6403 modestr = "@";
6405 else if (S_ISDIR(mode))
6406 modestr = "/";
6407 else if (mode & S_IXUSR)
6408 modestr = "*";
6409 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6410 got_tree_entry_get_name(te), modestr,
6411 link_target ? " -> ": "",
6412 link_target ? link_target : "") == -1) {
6413 free(id_str);
6414 free(link_target);
6415 return got_error_from_errno("asprintf");
6417 free(id_str);
6418 free(link_target);
6419 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6420 0, 0);
6421 if (err) {
6422 free(line);
6423 break;
6425 if (n == s->selected) {
6426 if (view->focussed)
6427 wstandout(view->window);
6428 s->selected_entry = te;
6430 tc = match_color(&s->colors, line);
6431 if (tc)
6432 wattr_on(view->window,
6433 COLOR_PAIR(tc->colorpair), NULL);
6434 waddwstr(view->window, wline);
6435 if (tc)
6436 wattr_off(view->window,
6437 COLOR_PAIR(tc->colorpair), NULL);
6438 if (width < view->ncols - 1)
6439 waddch(view->window, '\n');
6440 if (n == s->selected && view->focussed)
6441 wstandend(view->window);
6442 free(line);
6443 free(wline);
6444 wline = NULL;
6445 n++;
6446 s->ndisplayed++;
6447 s->last_displayed_entry = te;
6448 if (--limit <= 0)
6449 break;
6452 return err;
6455 static void
6456 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6458 struct got_tree_entry *te;
6459 int isroot = s->tree == s->root;
6460 int i = 0;
6462 if (s->first_displayed_entry == NULL)
6463 return;
6465 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6466 while (i++ < maxscroll) {
6467 if (te == NULL) {
6468 if (!isroot)
6469 s->first_displayed_entry = NULL;
6470 break;
6472 s->first_displayed_entry = te;
6473 te = got_tree_entry_get_prev(s->tree, te);
6477 static const struct got_error *
6478 tree_scroll_down(struct tog_view *view, int maxscroll)
6480 struct tog_tree_view_state *s = &view->state.tree;
6481 struct got_tree_entry *next, *last;
6482 int n = 0;
6484 if (s->first_displayed_entry)
6485 next = got_tree_entry_get_next(s->tree,
6486 s->first_displayed_entry);
6487 else
6488 next = got_object_tree_get_first_entry(s->tree);
6490 last = s->last_displayed_entry;
6491 while (next && n++ < maxscroll) {
6492 if (last) {
6493 s->last_displayed_entry = last;
6494 last = got_tree_entry_get_next(s->tree, last);
6496 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6497 s->first_displayed_entry = next;
6498 next = got_tree_entry_get_next(s->tree, next);
6502 return NULL;
6505 static const struct got_error *
6506 tree_entry_path(char **path, struct tog_parent_trees *parents,
6507 struct got_tree_entry *te)
6509 const struct got_error *err = NULL;
6510 struct tog_parent_tree *pt;
6511 size_t len = 2; /* for leading slash and NUL */
6513 TAILQ_FOREACH(pt, parents, entry)
6514 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6515 + 1 /* slash */;
6516 if (te)
6517 len += strlen(got_tree_entry_get_name(te));
6519 *path = calloc(1, len);
6520 if (path == NULL)
6521 return got_error_from_errno("calloc");
6523 (*path)[0] = '/';
6524 pt = TAILQ_LAST(parents, tog_parent_trees);
6525 while (pt) {
6526 const char *name = got_tree_entry_get_name(pt->selected_entry);
6527 if (strlcat(*path, name, len) >= len) {
6528 err = got_error(GOT_ERR_NO_SPACE);
6529 goto done;
6531 if (strlcat(*path, "/", len) >= len) {
6532 err = got_error(GOT_ERR_NO_SPACE);
6533 goto done;
6535 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6537 if (te) {
6538 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6539 err = got_error(GOT_ERR_NO_SPACE);
6540 goto done;
6543 done:
6544 if (err) {
6545 free(*path);
6546 *path = NULL;
6548 return err;
6551 static const struct got_error *
6552 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6553 struct got_tree_entry *te, struct tog_parent_trees *parents,
6554 struct got_object_id *commit_id, struct got_repository *repo)
6556 const struct got_error *err = NULL;
6557 char *path;
6558 struct tog_view *blame_view;
6560 *new_view = NULL;
6562 err = tree_entry_path(&path, parents, te);
6563 if (err)
6564 return err;
6566 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6567 if (blame_view == NULL) {
6568 err = got_error_from_errno("view_open");
6569 goto done;
6572 err = open_blame_view(blame_view, path, commit_id, repo);
6573 if (err) {
6574 if (err->code == GOT_ERR_CANCELLED)
6575 err = NULL;
6576 view_close(blame_view);
6577 } else
6578 *new_view = blame_view;
6579 done:
6580 free(path);
6581 return err;
6584 static const struct got_error *
6585 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6586 struct tog_tree_view_state *s)
6588 struct tog_view *log_view;
6589 const struct got_error *err = NULL;
6590 char *path;
6592 *new_view = NULL;
6594 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6595 if (log_view == NULL)
6596 return got_error_from_errno("view_open");
6598 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6599 if (err)
6600 return err;
6602 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6603 path, 0);
6604 if (err)
6605 view_close(log_view);
6606 else
6607 *new_view = log_view;
6608 free(path);
6609 return err;
6612 static const struct got_error *
6613 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6614 const char *head_ref_name, struct got_repository *repo)
6616 const struct got_error *err = NULL;
6617 char *commit_id_str = NULL;
6618 struct tog_tree_view_state *s = &view->state.tree;
6619 struct got_commit_object *commit = NULL;
6621 TAILQ_INIT(&s->parents);
6622 STAILQ_INIT(&s->colors);
6624 s->commit_id = got_object_id_dup(commit_id);
6625 if (s->commit_id == NULL)
6626 return got_error_from_errno("got_object_id_dup");
6628 err = got_object_open_as_commit(&commit, repo, commit_id);
6629 if (err)
6630 goto done;
6633 * The root is opened here and will be closed when the view is closed.
6634 * Any visited subtrees and their path-wise parents are opened and
6635 * closed on demand.
6637 err = got_object_open_as_tree(&s->root, repo,
6638 got_object_commit_get_tree_id(commit));
6639 if (err)
6640 goto done;
6641 s->tree = s->root;
6643 err = got_object_id_str(&commit_id_str, commit_id);
6644 if (err != NULL)
6645 goto done;
6647 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6648 err = got_error_from_errno("asprintf");
6649 goto done;
6652 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6653 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6654 if (head_ref_name) {
6655 s->head_ref_name = strdup(head_ref_name);
6656 if (s->head_ref_name == NULL) {
6657 err = got_error_from_errno("strdup");
6658 goto done;
6661 s->repo = repo;
6663 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6664 err = add_color(&s->colors, "\\$$",
6665 TOG_COLOR_TREE_SUBMODULE,
6666 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6667 if (err)
6668 goto done;
6669 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6670 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6671 if (err)
6672 goto done;
6673 err = add_color(&s->colors, "/$",
6674 TOG_COLOR_TREE_DIRECTORY,
6675 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6676 if (err)
6677 goto done;
6679 err = add_color(&s->colors, "\\*$",
6680 TOG_COLOR_TREE_EXECUTABLE,
6681 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6682 if (err)
6683 goto done;
6685 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6686 get_color_value("TOG_COLOR_COMMIT"));
6687 if (err)
6688 goto done;
6691 view->show = show_tree_view;
6692 view->input = input_tree_view;
6693 view->close = close_tree_view;
6694 view->search_start = search_start_tree_view;
6695 view->search_next = search_next_tree_view;
6696 done:
6697 free(commit_id_str);
6698 if (commit)
6699 got_object_commit_close(commit);
6700 if (err)
6701 close_tree_view(view);
6702 return err;
6705 static const struct got_error *
6706 close_tree_view(struct tog_view *view)
6708 struct tog_tree_view_state *s = &view->state.tree;
6710 free_colors(&s->colors);
6711 free(s->tree_label);
6712 s->tree_label = NULL;
6713 free(s->commit_id);
6714 s->commit_id = NULL;
6715 free(s->head_ref_name);
6716 s->head_ref_name = NULL;
6717 while (!TAILQ_EMPTY(&s->parents)) {
6718 struct tog_parent_tree *parent;
6719 parent = TAILQ_FIRST(&s->parents);
6720 TAILQ_REMOVE(&s->parents, parent, entry);
6721 if (parent->tree != s->root)
6722 got_object_tree_close(parent->tree);
6723 free(parent);
6726 if (s->tree != NULL && s->tree != s->root)
6727 got_object_tree_close(s->tree);
6728 if (s->root)
6729 got_object_tree_close(s->root);
6730 return NULL;
6733 static const struct got_error *
6734 search_start_tree_view(struct tog_view *view)
6736 struct tog_tree_view_state *s = &view->state.tree;
6738 s->matched_entry = NULL;
6739 return NULL;
6742 static int
6743 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6745 regmatch_t regmatch;
6747 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6748 0) == 0;
6751 static const struct got_error *
6752 search_next_tree_view(struct tog_view *view)
6754 struct tog_tree_view_state *s = &view->state.tree;
6755 struct got_tree_entry *te = NULL;
6757 if (!view->searching) {
6758 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6759 return NULL;
6762 if (s->matched_entry) {
6763 if (view->searching == TOG_SEARCH_FORWARD) {
6764 if (s->selected_entry)
6765 te = got_tree_entry_get_next(s->tree,
6766 s->selected_entry);
6767 else
6768 te = got_object_tree_get_first_entry(s->tree);
6769 } else {
6770 if (s->selected_entry == NULL)
6771 te = got_object_tree_get_last_entry(s->tree);
6772 else
6773 te = got_tree_entry_get_prev(s->tree,
6774 s->selected_entry);
6776 } else {
6777 if (s->selected_entry)
6778 te = s->selected_entry;
6779 else if (view->searching == TOG_SEARCH_FORWARD)
6780 te = got_object_tree_get_first_entry(s->tree);
6781 else
6782 te = got_object_tree_get_last_entry(s->tree);
6785 while (1) {
6786 if (te == NULL) {
6787 if (s->matched_entry == NULL) {
6788 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6789 return NULL;
6791 if (view->searching == TOG_SEARCH_FORWARD)
6792 te = got_object_tree_get_first_entry(s->tree);
6793 else
6794 te = got_object_tree_get_last_entry(s->tree);
6797 if (match_tree_entry(te, &view->regex)) {
6798 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6799 s->matched_entry = te;
6800 break;
6803 if (view->searching == TOG_SEARCH_FORWARD)
6804 te = got_tree_entry_get_next(s->tree, te);
6805 else
6806 te = got_tree_entry_get_prev(s->tree, te);
6809 if (s->matched_entry) {
6810 s->first_displayed_entry = s->matched_entry;
6811 s->selected = 0;
6814 return NULL;
6817 static const struct got_error *
6818 show_tree_view(struct tog_view *view)
6820 const struct got_error *err = NULL;
6821 struct tog_tree_view_state *s = &view->state.tree;
6822 char *parent_path;
6824 err = tree_entry_path(&parent_path, &s->parents, NULL);
6825 if (err)
6826 return err;
6828 err = draw_tree_entries(view, parent_path);
6829 free(parent_path);
6831 view_border(view);
6832 return err;
6835 static const struct got_error *
6836 tree_goto_line(struct tog_view *view, int nlines)
6838 const struct got_error *err = NULL;
6839 struct tog_tree_view_state *s = &view->state.tree;
6840 struct got_tree_entry **fte, **lte, **ste;
6841 int g, last, first = 1, i = 1;
6842 int root = s->tree == s->root;
6843 int off = root ? 1 : 2;
6845 g = view->gline;
6846 view->gline = 0;
6848 if (g == 0)
6849 g = 1;
6850 else if (g > got_object_tree_get_nentries(s->tree))
6851 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
6853 fte = &s->first_displayed_entry;
6854 lte = &s->last_displayed_entry;
6855 ste = &s->selected_entry;
6857 if (*fte != NULL) {
6858 first = got_tree_entry_get_index(*fte);
6859 first += off; /* account for ".." */
6861 last = got_tree_entry_get_index(*lte);
6862 last += off;
6864 if (g >= first && g <= last && g - first < nlines) {
6865 s->selected = g - first;
6866 return NULL; /* gline is on the current page */
6869 if (*ste != NULL) {
6870 i = got_tree_entry_get_index(*ste);
6871 i += off;
6874 if (i < g) {
6875 err = tree_scroll_down(view, g - i);
6876 if (err)
6877 return err;
6878 if (got_tree_entry_get_index(*lte) >=
6879 got_object_tree_get_nentries(s->tree) - 1 &&
6880 first + s->selected < g &&
6881 s->selected < s->ndisplayed - 1) {
6882 first = got_tree_entry_get_index(*fte);
6883 first += off;
6884 s->selected = g - first;
6886 } else if (i > g)
6887 tree_scroll_up(s, i - g);
6889 if (g < nlines &&
6890 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
6891 s->selected = g - 1;
6893 return NULL;
6896 static const struct got_error *
6897 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6899 const struct got_error *err = NULL;
6900 struct tog_tree_view_state *s = &view->state.tree;
6901 struct got_tree_entry *te;
6902 int n, nscroll = view->nlines - 3;
6904 if (view->gline)
6905 return tree_goto_line(view, nscroll);
6907 switch (ch) {
6908 case 'i':
6909 s->show_ids = !s->show_ids;
6910 view->count = 0;
6911 break;
6912 case 'L':
6913 view->count = 0;
6914 if (!s->selected_entry)
6915 break;
6916 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6917 break;
6918 case 'R':
6919 view->count = 0;
6920 err = view_request_new(new_view, view, TOG_VIEW_REF);
6921 break;
6922 case 'g':
6923 case KEY_HOME:
6924 s->selected = 0;
6925 view->count = 0;
6926 if (s->tree == s->root)
6927 s->first_displayed_entry =
6928 got_object_tree_get_first_entry(s->tree);
6929 else
6930 s->first_displayed_entry = NULL;
6931 break;
6932 case 'G':
6933 case KEY_END: {
6934 int eos = view->nlines - 3;
6936 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6937 --eos; /* border */
6938 s->selected = 0;
6939 view->count = 0;
6940 te = got_object_tree_get_last_entry(s->tree);
6941 for (n = 0; n < eos; n++) {
6942 if (te == NULL) {
6943 if (s->tree != s->root) {
6944 s->first_displayed_entry = NULL;
6945 n++;
6947 break;
6949 s->first_displayed_entry = te;
6950 te = got_tree_entry_get_prev(s->tree, te);
6952 if (n > 0)
6953 s->selected = n - 1;
6954 break;
6956 case 'k':
6957 case KEY_UP:
6958 case CTRL('p'):
6959 if (s->selected > 0) {
6960 s->selected--;
6961 break;
6963 tree_scroll_up(s, 1);
6964 if (s->selected_entry == NULL ||
6965 (s->tree == s->root && s->selected_entry ==
6966 got_object_tree_get_first_entry(s->tree)))
6967 view->count = 0;
6968 break;
6969 case CTRL('u'):
6970 case 'u':
6971 nscroll /= 2;
6972 /* FALL THROUGH */
6973 case KEY_PPAGE:
6974 case CTRL('b'):
6975 case 'b':
6976 if (s->tree == s->root) {
6977 if (got_object_tree_get_first_entry(s->tree) ==
6978 s->first_displayed_entry)
6979 s->selected -= MIN(s->selected, nscroll);
6980 } else {
6981 if (s->first_displayed_entry == NULL)
6982 s->selected -= MIN(s->selected, nscroll);
6984 tree_scroll_up(s, MAX(0, nscroll));
6985 if (s->selected_entry == NULL ||
6986 (s->tree == s->root && s->selected_entry ==
6987 got_object_tree_get_first_entry(s->tree)))
6988 view->count = 0;
6989 break;
6990 case 'j':
6991 case KEY_DOWN:
6992 case CTRL('n'):
6993 if (s->selected < s->ndisplayed - 1) {
6994 s->selected++;
6995 break;
6997 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6998 == NULL) {
6999 /* can't scroll any further */
7000 view->count = 0;
7001 break;
7003 tree_scroll_down(view, 1);
7004 break;
7005 case CTRL('d'):
7006 case 'd':
7007 nscroll /= 2;
7008 /* FALL THROUGH */
7009 case KEY_NPAGE:
7010 case CTRL('f'):
7011 case 'f':
7012 case ' ':
7013 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7014 == NULL) {
7015 /* can't scroll any further; move cursor down */
7016 if (s->selected < s->ndisplayed - 1)
7017 s->selected += MIN(nscroll,
7018 s->ndisplayed - s->selected - 1);
7019 else
7020 view->count = 0;
7021 break;
7023 tree_scroll_down(view, nscroll);
7024 break;
7025 case KEY_ENTER:
7026 case '\r':
7027 case KEY_BACKSPACE:
7028 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7029 struct tog_parent_tree *parent;
7030 /* user selected '..' */
7031 if (s->tree == s->root) {
7032 view->count = 0;
7033 break;
7035 parent = TAILQ_FIRST(&s->parents);
7036 TAILQ_REMOVE(&s->parents, parent,
7037 entry);
7038 got_object_tree_close(s->tree);
7039 s->tree = parent->tree;
7040 s->first_displayed_entry =
7041 parent->first_displayed_entry;
7042 s->selected_entry =
7043 parent->selected_entry;
7044 s->selected = parent->selected;
7045 if (s->selected > view->nlines - 3) {
7046 err = offset_selection_down(view);
7047 if (err)
7048 break;
7050 free(parent);
7051 } else if (S_ISDIR(got_tree_entry_get_mode(
7052 s->selected_entry))) {
7053 struct got_tree_object *subtree;
7054 view->count = 0;
7055 err = got_object_open_as_tree(&subtree, s->repo,
7056 got_tree_entry_get_id(s->selected_entry));
7057 if (err)
7058 break;
7059 err = tree_view_visit_subtree(s, subtree);
7060 if (err) {
7061 got_object_tree_close(subtree);
7062 break;
7064 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7065 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7066 break;
7067 case KEY_RESIZE:
7068 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7069 s->selected = view->nlines - 4;
7070 view->count = 0;
7071 break;
7072 default:
7073 view->count = 0;
7074 break;
7077 return err;
7080 __dead static void
7081 usage_tree(void)
7083 endwin();
7084 fprintf(stderr,
7085 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7086 getprogname());
7087 exit(1);
7090 static const struct got_error *
7091 cmd_tree(int argc, char *argv[])
7093 const struct got_error *error;
7094 struct got_repository *repo = NULL;
7095 struct got_worktree *worktree = NULL;
7096 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7097 struct got_object_id *commit_id = NULL;
7098 struct got_commit_object *commit = NULL;
7099 const char *commit_id_arg = NULL;
7100 char *label = NULL;
7101 struct got_reference *ref = NULL;
7102 const char *head_ref_name = NULL;
7103 int ch;
7104 struct tog_view *view;
7105 int *pack_fds = NULL;
7107 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7108 switch (ch) {
7109 case 'c':
7110 commit_id_arg = optarg;
7111 break;
7112 case 'r':
7113 repo_path = realpath(optarg, NULL);
7114 if (repo_path == NULL)
7115 return got_error_from_errno2("realpath",
7116 optarg);
7117 break;
7118 default:
7119 usage_tree();
7120 /* NOTREACHED */
7124 argc -= optind;
7125 argv += optind;
7127 if (argc > 1)
7128 usage_tree();
7130 error = got_repo_pack_fds_open(&pack_fds);
7131 if (error != NULL)
7132 goto done;
7134 if (repo_path == NULL) {
7135 cwd = getcwd(NULL, 0);
7136 if (cwd == NULL)
7137 return got_error_from_errno("getcwd");
7138 error = got_worktree_open(&worktree, cwd);
7139 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7140 goto done;
7141 if (worktree)
7142 repo_path =
7143 strdup(got_worktree_get_repo_path(worktree));
7144 else
7145 repo_path = strdup(cwd);
7146 if (repo_path == NULL) {
7147 error = got_error_from_errno("strdup");
7148 goto done;
7152 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7153 if (error != NULL)
7154 goto done;
7156 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7157 repo, worktree);
7158 if (error)
7159 goto done;
7161 init_curses();
7163 error = apply_unveil(got_repo_get_path(repo), NULL);
7164 if (error)
7165 goto done;
7167 error = tog_load_refs(repo, 0);
7168 if (error)
7169 goto done;
7171 if (commit_id_arg == NULL) {
7172 error = got_repo_match_object_id(&commit_id, &label,
7173 worktree ? got_worktree_get_head_ref_name(worktree) :
7174 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7175 if (error)
7176 goto done;
7177 head_ref_name = label;
7178 } else {
7179 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7180 if (error == NULL)
7181 head_ref_name = got_ref_get_name(ref);
7182 else if (error->code != GOT_ERR_NOT_REF)
7183 goto done;
7184 error = got_repo_match_object_id(&commit_id, NULL,
7185 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7186 if (error)
7187 goto done;
7190 error = got_object_open_as_commit(&commit, repo, commit_id);
7191 if (error)
7192 goto done;
7194 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7195 if (view == NULL) {
7196 error = got_error_from_errno("view_open");
7197 goto done;
7199 error = open_tree_view(view, commit_id, head_ref_name, repo);
7200 if (error)
7201 goto done;
7202 if (!got_path_is_root_dir(in_repo_path)) {
7203 error = tree_view_walk_path(&view->state.tree, commit,
7204 in_repo_path);
7205 if (error)
7206 goto done;
7209 if (worktree) {
7210 /* Release work tree lock. */
7211 got_worktree_close(worktree);
7212 worktree = NULL;
7214 error = view_loop(view);
7215 done:
7216 free(repo_path);
7217 free(cwd);
7218 free(commit_id);
7219 free(label);
7220 if (ref)
7221 got_ref_close(ref);
7222 if (repo) {
7223 const struct got_error *close_err = got_repo_close(repo);
7224 if (error == NULL)
7225 error = close_err;
7227 if (pack_fds) {
7228 const struct got_error *pack_err =
7229 got_repo_pack_fds_close(pack_fds);
7230 if (error == NULL)
7231 error = pack_err;
7233 tog_free_refs();
7234 return error;
7237 static const struct got_error *
7238 ref_view_load_refs(struct tog_ref_view_state *s)
7240 struct got_reflist_entry *sre;
7241 struct tog_reflist_entry *re;
7243 s->nrefs = 0;
7244 TAILQ_FOREACH(sre, &tog_refs, entry) {
7245 if (strncmp(got_ref_get_name(sre->ref),
7246 "refs/got/", 9) == 0 &&
7247 strncmp(got_ref_get_name(sre->ref),
7248 "refs/got/backup/", 16) != 0)
7249 continue;
7251 re = malloc(sizeof(*re));
7252 if (re == NULL)
7253 return got_error_from_errno("malloc");
7255 re->ref = got_ref_dup(sre->ref);
7256 if (re->ref == NULL)
7257 return got_error_from_errno("got_ref_dup");
7258 re->idx = s->nrefs++;
7259 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7262 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7263 return NULL;
7266 static void
7267 ref_view_free_refs(struct tog_ref_view_state *s)
7269 struct tog_reflist_entry *re;
7271 while (!TAILQ_EMPTY(&s->refs)) {
7272 re = TAILQ_FIRST(&s->refs);
7273 TAILQ_REMOVE(&s->refs, re, entry);
7274 got_ref_close(re->ref);
7275 free(re);
7279 static const struct got_error *
7280 open_ref_view(struct tog_view *view, struct got_repository *repo)
7282 const struct got_error *err = NULL;
7283 struct tog_ref_view_state *s = &view->state.ref;
7285 s->selected_entry = 0;
7286 s->repo = repo;
7288 TAILQ_INIT(&s->refs);
7289 STAILQ_INIT(&s->colors);
7291 err = ref_view_load_refs(s);
7292 if (err)
7293 return err;
7295 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7296 err = add_color(&s->colors, "^refs/heads/",
7297 TOG_COLOR_REFS_HEADS,
7298 get_color_value("TOG_COLOR_REFS_HEADS"));
7299 if (err)
7300 goto done;
7302 err = add_color(&s->colors, "^refs/tags/",
7303 TOG_COLOR_REFS_TAGS,
7304 get_color_value("TOG_COLOR_REFS_TAGS"));
7305 if (err)
7306 goto done;
7308 err = add_color(&s->colors, "^refs/remotes/",
7309 TOG_COLOR_REFS_REMOTES,
7310 get_color_value("TOG_COLOR_REFS_REMOTES"));
7311 if (err)
7312 goto done;
7314 err = add_color(&s->colors, "^refs/got/backup/",
7315 TOG_COLOR_REFS_BACKUP,
7316 get_color_value("TOG_COLOR_REFS_BACKUP"));
7317 if (err)
7318 goto done;
7321 view->show = show_ref_view;
7322 view->input = input_ref_view;
7323 view->close = close_ref_view;
7324 view->search_start = search_start_ref_view;
7325 view->search_next = search_next_ref_view;
7326 done:
7327 if (err)
7328 free_colors(&s->colors);
7329 return err;
7332 static const struct got_error *
7333 close_ref_view(struct tog_view *view)
7335 struct tog_ref_view_state *s = &view->state.ref;
7337 ref_view_free_refs(s);
7338 free_colors(&s->colors);
7340 return NULL;
7343 static const struct got_error *
7344 resolve_reflist_entry(struct got_object_id **commit_id,
7345 struct tog_reflist_entry *re, struct got_repository *repo)
7347 const struct got_error *err = NULL;
7348 struct got_object_id *obj_id;
7349 struct got_tag_object *tag = NULL;
7350 int obj_type;
7352 *commit_id = NULL;
7354 err = got_ref_resolve(&obj_id, repo, re->ref);
7355 if (err)
7356 return err;
7358 err = got_object_get_type(&obj_type, repo, obj_id);
7359 if (err)
7360 goto done;
7362 switch (obj_type) {
7363 case GOT_OBJ_TYPE_COMMIT:
7364 *commit_id = obj_id;
7365 break;
7366 case GOT_OBJ_TYPE_TAG:
7367 err = got_object_open_as_tag(&tag, repo, obj_id);
7368 if (err)
7369 goto done;
7370 free(obj_id);
7371 err = got_object_get_type(&obj_type, repo,
7372 got_object_tag_get_object_id(tag));
7373 if (err)
7374 goto done;
7375 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7376 err = got_error(GOT_ERR_OBJ_TYPE);
7377 goto done;
7379 *commit_id = got_object_id_dup(
7380 got_object_tag_get_object_id(tag));
7381 if (*commit_id == NULL) {
7382 err = got_error_from_errno("got_object_id_dup");
7383 goto done;
7385 break;
7386 default:
7387 err = got_error(GOT_ERR_OBJ_TYPE);
7388 break;
7391 done:
7392 if (tag)
7393 got_object_tag_close(tag);
7394 if (err) {
7395 free(*commit_id);
7396 *commit_id = NULL;
7398 return err;
7401 static const struct got_error *
7402 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7403 struct tog_reflist_entry *re, struct got_repository *repo)
7405 struct tog_view *log_view;
7406 const struct got_error *err = NULL;
7407 struct got_object_id *commit_id = NULL;
7409 *new_view = NULL;
7411 err = resolve_reflist_entry(&commit_id, re, repo);
7412 if (err) {
7413 if (err->code != GOT_ERR_OBJ_TYPE)
7414 return err;
7415 else
7416 return NULL;
7419 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7420 if (log_view == NULL) {
7421 err = got_error_from_errno("view_open");
7422 goto done;
7425 err = open_log_view(log_view, commit_id, repo,
7426 got_ref_get_name(re->ref), "", 0);
7427 done:
7428 if (err)
7429 view_close(log_view);
7430 else
7431 *new_view = log_view;
7432 free(commit_id);
7433 return err;
7436 static void
7437 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7439 struct tog_reflist_entry *re;
7440 int i = 0;
7442 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7443 return;
7445 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7446 while (i++ < maxscroll) {
7447 if (re == NULL)
7448 break;
7449 s->first_displayed_entry = re;
7450 re = TAILQ_PREV(re, tog_reflist_head, entry);
7454 static const struct got_error *
7455 ref_scroll_down(struct tog_view *view, int maxscroll)
7457 struct tog_ref_view_state *s = &view->state.ref;
7458 struct tog_reflist_entry *next, *last;
7459 int n = 0;
7461 if (s->first_displayed_entry)
7462 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7463 else
7464 next = TAILQ_FIRST(&s->refs);
7466 last = s->last_displayed_entry;
7467 while (next && n++ < maxscroll) {
7468 if (last) {
7469 s->last_displayed_entry = last;
7470 last = TAILQ_NEXT(last, entry);
7472 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7473 s->first_displayed_entry = next;
7474 next = TAILQ_NEXT(next, entry);
7478 return NULL;
7481 static const struct got_error *
7482 search_start_ref_view(struct tog_view *view)
7484 struct tog_ref_view_state *s = &view->state.ref;
7486 s->matched_entry = NULL;
7487 return NULL;
7490 static int
7491 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7493 regmatch_t regmatch;
7495 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7496 0) == 0;
7499 static const struct got_error *
7500 search_next_ref_view(struct tog_view *view)
7502 struct tog_ref_view_state *s = &view->state.ref;
7503 struct tog_reflist_entry *re = NULL;
7505 if (!view->searching) {
7506 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7507 return NULL;
7510 if (s->matched_entry) {
7511 if (view->searching == TOG_SEARCH_FORWARD) {
7512 if (s->selected_entry)
7513 re = TAILQ_NEXT(s->selected_entry, entry);
7514 else
7515 re = TAILQ_PREV(s->selected_entry,
7516 tog_reflist_head, entry);
7517 } else {
7518 if (s->selected_entry == NULL)
7519 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7520 else
7521 re = TAILQ_PREV(s->selected_entry,
7522 tog_reflist_head, entry);
7524 } else {
7525 if (s->selected_entry)
7526 re = s->selected_entry;
7527 else if (view->searching == TOG_SEARCH_FORWARD)
7528 re = TAILQ_FIRST(&s->refs);
7529 else
7530 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7533 while (1) {
7534 if (re == NULL) {
7535 if (s->matched_entry == NULL) {
7536 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7537 return NULL;
7539 if (view->searching == TOG_SEARCH_FORWARD)
7540 re = TAILQ_FIRST(&s->refs);
7541 else
7542 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7545 if (match_reflist_entry(re, &view->regex)) {
7546 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7547 s->matched_entry = re;
7548 break;
7551 if (view->searching == TOG_SEARCH_FORWARD)
7552 re = TAILQ_NEXT(re, entry);
7553 else
7554 re = TAILQ_PREV(re, tog_reflist_head, entry);
7557 if (s->matched_entry) {
7558 s->first_displayed_entry = s->matched_entry;
7559 s->selected = 0;
7562 return NULL;
7565 static const struct got_error *
7566 show_ref_view(struct tog_view *view)
7568 const struct got_error *err = NULL;
7569 struct tog_ref_view_state *s = &view->state.ref;
7570 struct tog_reflist_entry *re;
7571 char *line = NULL;
7572 wchar_t *wline;
7573 struct tog_color *tc;
7574 int width, n;
7575 int limit = view->nlines;
7577 werase(view->window);
7579 s->ndisplayed = 0;
7580 if (view_is_hsplit_top(view))
7581 --limit; /* border */
7583 if (limit == 0)
7584 return NULL;
7586 re = s->first_displayed_entry;
7588 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7589 s->nrefs) == -1)
7590 return got_error_from_errno("asprintf");
7592 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7593 if (err) {
7594 free(line);
7595 return err;
7597 if (view_needs_focus_indication(view))
7598 wstandout(view->window);
7599 waddwstr(view->window, wline);
7600 if (view_needs_focus_indication(view))
7601 wstandend(view->window);
7602 free(wline);
7603 wline = NULL;
7604 free(line);
7605 line = NULL;
7606 if (width < view->ncols - 1)
7607 waddch(view->window, '\n');
7608 if (--limit <= 0)
7609 return NULL;
7611 n = 0;
7612 while (re && limit > 0) {
7613 char *line = NULL;
7614 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7616 if (s->show_date) {
7617 struct got_commit_object *ci;
7618 struct got_tag_object *tag;
7619 struct got_object_id *id;
7620 struct tm tm;
7621 time_t t;
7623 err = got_ref_resolve(&id, s->repo, re->ref);
7624 if (err)
7625 return err;
7626 err = got_object_open_as_tag(&tag, s->repo, id);
7627 if (err) {
7628 if (err->code != GOT_ERR_OBJ_TYPE) {
7629 free(id);
7630 return err;
7632 err = got_object_open_as_commit(&ci, s->repo,
7633 id);
7634 if (err) {
7635 free(id);
7636 return err;
7638 t = got_object_commit_get_committer_time(ci);
7639 got_object_commit_close(ci);
7640 } else {
7641 t = got_object_tag_get_tagger_time(tag);
7642 got_object_tag_close(tag);
7644 free(id);
7645 if (gmtime_r(&t, &tm) == NULL)
7646 return got_error_from_errno("gmtime_r");
7647 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7648 return got_error(GOT_ERR_NO_SPACE);
7650 if (got_ref_is_symbolic(re->ref)) {
7651 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7652 ymd : "", got_ref_get_name(re->ref),
7653 got_ref_get_symref_target(re->ref)) == -1)
7654 return got_error_from_errno("asprintf");
7655 } else if (s->show_ids) {
7656 struct got_object_id *id;
7657 char *id_str;
7658 err = got_ref_resolve(&id, s->repo, re->ref);
7659 if (err)
7660 return err;
7661 err = got_object_id_str(&id_str, id);
7662 if (err) {
7663 free(id);
7664 return err;
7666 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7667 got_ref_get_name(re->ref), id_str) == -1) {
7668 err = got_error_from_errno("asprintf");
7669 free(id);
7670 free(id_str);
7671 return err;
7673 free(id);
7674 free(id_str);
7675 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7676 got_ref_get_name(re->ref)) == -1)
7677 return got_error_from_errno("asprintf");
7679 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7680 0, 0);
7681 if (err) {
7682 free(line);
7683 return err;
7685 if (n == s->selected) {
7686 if (view->focussed)
7687 wstandout(view->window);
7688 s->selected_entry = re;
7690 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7691 if (tc)
7692 wattr_on(view->window,
7693 COLOR_PAIR(tc->colorpair), NULL);
7694 waddwstr(view->window, wline);
7695 if (tc)
7696 wattr_off(view->window,
7697 COLOR_PAIR(tc->colorpair), NULL);
7698 if (width < view->ncols - 1)
7699 waddch(view->window, '\n');
7700 if (n == s->selected && view->focussed)
7701 wstandend(view->window);
7702 free(line);
7703 free(wline);
7704 wline = NULL;
7705 n++;
7706 s->ndisplayed++;
7707 s->last_displayed_entry = re;
7709 limit--;
7710 re = TAILQ_NEXT(re, entry);
7713 view_border(view);
7714 return err;
7717 static const struct got_error *
7718 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7719 struct tog_reflist_entry *re, struct got_repository *repo)
7721 const struct got_error *err = NULL;
7722 struct got_object_id *commit_id = NULL;
7723 struct tog_view *tree_view;
7725 *new_view = NULL;
7727 err = resolve_reflist_entry(&commit_id, re, repo);
7728 if (err) {
7729 if (err->code != GOT_ERR_OBJ_TYPE)
7730 return err;
7731 else
7732 return NULL;
7736 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7737 if (tree_view == NULL) {
7738 err = got_error_from_errno("view_open");
7739 goto done;
7742 err = open_tree_view(tree_view, commit_id,
7743 got_ref_get_name(re->ref), repo);
7744 if (err)
7745 goto done;
7747 *new_view = tree_view;
7748 done:
7749 free(commit_id);
7750 return err;
7753 static const struct got_error *
7754 ref_goto_line(struct tog_view *view, int nlines)
7756 const struct got_error *err = NULL;
7757 struct tog_ref_view_state *s = &view->state.ref;
7758 int g, idx = s->selected_entry->idx;
7760 g = view->gline;
7761 view->gline = 0;
7763 if (g == 0)
7764 g = 1;
7765 else if (g > s->nrefs)
7766 g = s->nrefs;
7768 if (g >= s->first_displayed_entry->idx + 1 &&
7769 g <= s->last_displayed_entry->idx + 1 &&
7770 g - s->first_displayed_entry->idx - 1 < nlines) {
7771 s->selected = g - s->first_displayed_entry->idx - 1;
7772 return NULL;
7775 if (idx + 1 < g) {
7776 err = ref_scroll_down(view, g - idx - 1);
7777 if (err)
7778 return err;
7779 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
7780 s->first_displayed_entry->idx + s->selected < g &&
7781 s->selected < s->ndisplayed - 1)
7782 s->selected = g - s->first_displayed_entry->idx - 1;
7783 } else if (idx + 1 > g)
7784 ref_scroll_up(s, idx - g + 1);
7786 if (g < nlines && s->first_displayed_entry->idx == 0)
7787 s->selected = g - 1;
7789 return NULL;
7793 static const struct got_error *
7794 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7796 const struct got_error *err = NULL;
7797 struct tog_ref_view_state *s = &view->state.ref;
7798 struct tog_reflist_entry *re;
7799 int n, nscroll = view->nlines - 1;
7801 if (view->gline)
7802 return ref_goto_line(view, nscroll);
7804 switch (ch) {
7805 case 'i':
7806 s->show_ids = !s->show_ids;
7807 view->count = 0;
7808 break;
7809 case 'm':
7810 s->show_date = !s->show_date;
7811 view->count = 0;
7812 break;
7813 case 'o':
7814 s->sort_by_date = !s->sort_by_date;
7815 view->count = 0;
7816 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7817 got_ref_cmp_by_commit_timestamp_descending :
7818 tog_ref_cmp_by_name, s->repo);
7819 if (err)
7820 break;
7821 got_reflist_object_id_map_free(tog_refs_idmap);
7822 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7823 &tog_refs, s->repo);
7824 if (err)
7825 break;
7826 ref_view_free_refs(s);
7827 err = ref_view_load_refs(s);
7828 break;
7829 case KEY_ENTER:
7830 case '\r':
7831 view->count = 0;
7832 if (!s->selected_entry)
7833 break;
7834 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7835 break;
7836 case 'T':
7837 view->count = 0;
7838 if (!s->selected_entry)
7839 break;
7840 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7841 break;
7842 case 'g':
7843 case KEY_HOME:
7844 s->selected = 0;
7845 view->count = 0;
7846 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7847 break;
7848 case 'G':
7849 case KEY_END: {
7850 int eos = view->nlines - 1;
7852 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7853 --eos; /* border */
7854 s->selected = 0;
7855 view->count = 0;
7856 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7857 for (n = 0; n < eos; n++) {
7858 if (re == NULL)
7859 break;
7860 s->first_displayed_entry = re;
7861 re = TAILQ_PREV(re, tog_reflist_head, entry);
7863 if (n > 0)
7864 s->selected = n - 1;
7865 break;
7867 case 'k':
7868 case KEY_UP:
7869 case CTRL('p'):
7870 if (s->selected > 0) {
7871 s->selected--;
7872 break;
7874 ref_scroll_up(s, 1);
7875 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7876 view->count = 0;
7877 break;
7878 case CTRL('u'):
7879 case 'u':
7880 nscroll /= 2;
7881 /* FALL THROUGH */
7882 case KEY_PPAGE:
7883 case CTRL('b'):
7884 case 'b':
7885 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7886 s->selected -= MIN(nscroll, s->selected);
7887 ref_scroll_up(s, MAX(0, nscroll));
7888 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7889 view->count = 0;
7890 break;
7891 case 'j':
7892 case KEY_DOWN:
7893 case CTRL('n'):
7894 if (s->selected < s->ndisplayed - 1) {
7895 s->selected++;
7896 break;
7898 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7899 /* can't scroll any further */
7900 view->count = 0;
7901 break;
7903 ref_scroll_down(view, 1);
7904 break;
7905 case CTRL('d'):
7906 case 'd':
7907 nscroll /= 2;
7908 /* FALL THROUGH */
7909 case KEY_NPAGE:
7910 case CTRL('f'):
7911 case 'f':
7912 case ' ':
7913 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7914 /* can't scroll any further; move cursor down */
7915 if (s->selected < s->ndisplayed - 1)
7916 s->selected += MIN(nscroll,
7917 s->ndisplayed - s->selected - 1);
7918 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7919 s->selected += s->ndisplayed - s->selected - 1;
7920 view->count = 0;
7921 break;
7923 ref_scroll_down(view, nscroll);
7924 break;
7925 case CTRL('l'):
7926 view->count = 0;
7927 tog_free_refs();
7928 err = tog_load_refs(s->repo, s->sort_by_date);
7929 if (err)
7930 break;
7931 ref_view_free_refs(s);
7932 err = ref_view_load_refs(s);
7933 break;
7934 case KEY_RESIZE:
7935 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7936 s->selected = view->nlines - 2;
7937 break;
7938 default:
7939 view->count = 0;
7940 break;
7943 return err;
7946 __dead static void
7947 usage_ref(void)
7949 endwin();
7950 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7951 getprogname());
7952 exit(1);
7955 static const struct got_error *
7956 cmd_ref(int argc, char *argv[])
7958 const struct got_error *error;
7959 struct got_repository *repo = NULL;
7960 struct got_worktree *worktree = NULL;
7961 char *cwd = NULL, *repo_path = NULL;
7962 int ch;
7963 struct tog_view *view;
7964 int *pack_fds = NULL;
7966 while ((ch = getopt(argc, argv, "r:")) != -1) {
7967 switch (ch) {
7968 case 'r':
7969 repo_path = realpath(optarg, NULL);
7970 if (repo_path == NULL)
7971 return got_error_from_errno2("realpath",
7972 optarg);
7973 break;
7974 default:
7975 usage_ref();
7976 /* NOTREACHED */
7980 argc -= optind;
7981 argv += optind;
7983 if (argc > 1)
7984 usage_ref();
7986 error = got_repo_pack_fds_open(&pack_fds);
7987 if (error != NULL)
7988 goto done;
7990 if (repo_path == NULL) {
7991 cwd = getcwd(NULL, 0);
7992 if (cwd == NULL)
7993 return got_error_from_errno("getcwd");
7994 error = got_worktree_open(&worktree, cwd);
7995 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7996 goto done;
7997 if (worktree)
7998 repo_path =
7999 strdup(got_worktree_get_repo_path(worktree));
8000 else
8001 repo_path = strdup(cwd);
8002 if (repo_path == NULL) {
8003 error = got_error_from_errno("strdup");
8004 goto done;
8008 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8009 if (error != NULL)
8010 goto done;
8012 init_curses();
8014 error = apply_unveil(got_repo_get_path(repo), NULL);
8015 if (error)
8016 goto done;
8018 error = tog_load_refs(repo, 0);
8019 if (error)
8020 goto done;
8022 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8023 if (view == NULL) {
8024 error = got_error_from_errno("view_open");
8025 goto done;
8028 error = open_ref_view(view, repo);
8029 if (error)
8030 goto done;
8032 if (worktree) {
8033 /* Release work tree lock. */
8034 got_worktree_close(worktree);
8035 worktree = NULL;
8037 error = view_loop(view);
8038 done:
8039 free(repo_path);
8040 free(cwd);
8041 if (repo) {
8042 const struct got_error *close_err = got_repo_close(repo);
8043 if (close_err)
8044 error = close_err;
8046 if (pack_fds) {
8047 const struct got_error *pack_err =
8048 got_repo_pack_fds_close(pack_fds);
8049 if (error == NULL)
8050 error = pack_err;
8052 tog_free_refs();
8053 return error;
8056 static const struct got_error *
8057 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8058 enum tog_view_type request, int y, int x)
8060 const struct got_error *err = NULL;
8062 *new_view = NULL;
8064 switch (request) {
8065 case TOG_VIEW_DIFF:
8066 if (view->type == TOG_VIEW_LOG) {
8067 struct tog_log_view_state *s = &view->state.log;
8069 err = open_diff_view_for_commit(new_view, y, x,
8070 s->selected_entry->commit, s->selected_entry->id,
8071 view, s->repo);
8072 } else
8073 return got_error_msg(GOT_ERR_NOT_IMPL,
8074 "parent/child view pair not supported");
8075 break;
8076 case TOG_VIEW_BLAME:
8077 if (view->type == TOG_VIEW_TREE) {
8078 struct tog_tree_view_state *s = &view->state.tree;
8080 err = blame_tree_entry(new_view, y, x,
8081 s->selected_entry, &s->parents, s->commit_id,
8082 s->repo);
8083 } else
8084 return got_error_msg(GOT_ERR_NOT_IMPL,
8085 "parent/child view pair not supported");
8086 break;
8087 case TOG_VIEW_LOG:
8088 if (view->type == TOG_VIEW_BLAME)
8089 err = log_annotated_line(new_view, y, x,
8090 view->state.blame.repo, view->state.blame.id_to_log);
8091 else if (view->type == TOG_VIEW_TREE)
8092 err = log_selected_tree_entry(new_view, y, x,
8093 &view->state.tree);
8094 else if (view->type == TOG_VIEW_REF)
8095 err = log_ref_entry(new_view, y, x,
8096 view->state.ref.selected_entry,
8097 view->state.ref.repo);
8098 else
8099 return got_error_msg(GOT_ERR_NOT_IMPL,
8100 "parent/child view pair not supported");
8101 break;
8102 case TOG_VIEW_TREE:
8103 if (view->type == TOG_VIEW_LOG)
8104 err = browse_commit_tree(new_view, y, x,
8105 view->state.log.selected_entry,
8106 view->state.log.in_repo_path,
8107 view->state.log.head_ref_name,
8108 view->state.log.repo);
8109 else if (view->type == TOG_VIEW_REF)
8110 err = browse_ref_tree(new_view, y, x,
8111 view->state.ref.selected_entry,
8112 view->state.ref.repo);
8113 else
8114 return got_error_msg(GOT_ERR_NOT_IMPL,
8115 "parent/child view pair not supported");
8116 break;
8117 case TOG_VIEW_REF:
8118 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8119 if (*new_view == NULL)
8120 return got_error_from_errno("view_open");
8121 if (view->type == TOG_VIEW_LOG)
8122 err = open_ref_view(*new_view, view->state.log.repo);
8123 else if (view->type == TOG_VIEW_TREE)
8124 err = open_ref_view(*new_view, view->state.tree.repo);
8125 else
8126 err = got_error_msg(GOT_ERR_NOT_IMPL,
8127 "parent/child view pair not supported");
8128 if (err)
8129 view_close(*new_view);
8130 break;
8131 default:
8132 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8135 return err;
8139 * If view was scrolled down to move the selected line into view when opening a
8140 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8142 static void
8143 offset_selection_up(struct tog_view *view)
8145 switch (view->type) {
8146 case TOG_VIEW_BLAME: {
8147 struct tog_blame_view_state *s = &view->state.blame;
8148 if (s->first_displayed_line == 1) {
8149 s->selected_line = MAX(s->selected_line - view->offset,
8150 1);
8151 break;
8153 if (s->first_displayed_line > view->offset)
8154 s->first_displayed_line -= view->offset;
8155 else
8156 s->first_displayed_line = 1;
8157 s->selected_line += view->offset;
8158 break;
8160 case TOG_VIEW_LOG:
8161 log_scroll_up(&view->state.log, view->offset);
8162 view->state.log.selected += view->offset;
8163 break;
8164 case TOG_VIEW_REF:
8165 ref_scroll_up(&view->state.ref, view->offset);
8166 view->state.ref.selected += view->offset;
8167 break;
8168 case TOG_VIEW_TREE:
8169 tree_scroll_up(&view->state.tree, view->offset);
8170 view->state.tree.selected += view->offset;
8171 break;
8172 default:
8173 break;
8176 view->offset = 0;
8180 * If the selected line is in the section of screen covered by the bottom split,
8181 * scroll down offset lines to move it into view and index its new position.
8183 static const struct got_error *
8184 offset_selection_down(struct tog_view *view)
8186 const struct got_error *err = NULL;
8187 const struct got_error *(*scrolld)(struct tog_view *, int);
8188 int *selected = NULL;
8189 int header, offset;
8191 switch (view->type) {
8192 case TOG_VIEW_BLAME: {
8193 struct tog_blame_view_state *s = &view->state.blame;
8194 header = 3;
8195 scrolld = NULL;
8196 if (s->selected_line > view->nlines - header) {
8197 offset = abs(view->nlines - s->selected_line - header);
8198 s->first_displayed_line += offset;
8199 s->selected_line -= offset;
8200 view->offset = offset;
8202 break;
8204 case TOG_VIEW_LOG: {
8205 struct tog_log_view_state *s = &view->state.log;
8206 scrolld = &log_scroll_down;
8207 header = view_is_parent_view(view) ? 3 : 2;
8208 selected = &s->selected;
8209 break;
8211 case TOG_VIEW_REF: {
8212 struct tog_ref_view_state *s = &view->state.ref;
8213 scrolld = &ref_scroll_down;
8214 header = 3;
8215 selected = &s->selected;
8216 break;
8218 case TOG_VIEW_TREE: {
8219 struct tog_tree_view_state *s = &view->state.tree;
8220 scrolld = &tree_scroll_down;
8221 header = 5;
8222 selected = &s->selected;
8223 break;
8225 default:
8226 selected = NULL;
8227 scrolld = NULL;
8228 header = 0;
8229 break;
8232 if (selected && *selected > view->nlines - header) {
8233 offset = abs(view->nlines - *selected - header);
8234 view->offset = offset;
8235 if (scrolld && offset) {
8236 err = scrolld(view, offset);
8237 *selected -= offset;
8241 return err;
8244 static void
8245 list_commands(FILE *fp)
8247 size_t i;
8249 fprintf(fp, "commands:");
8250 for (i = 0; i < nitems(tog_commands); i++) {
8251 const struct tog_cmd *cmd = &tog_commands[i];
8252 fprintf(fp, " %s", cmd->name);
8254 fputc('\n', fp);
8257 __dead static void
8258 usage(int hflag, int status)
8260 FILE *fp = (status == 0) ? stdout : stderr;
8262 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8263 getprogname());
8264 if (hflag) {
8265 fprintf(fp, "lazy usage: %s path\n", getprogname());
8266 list_commands(fp);
8268 exit(status);
8271 static char **
8272 make_argv(int argc, ...)
8274 va_list ap;
8275 char **argv;
8276 int i;
8278 va_start(ap, argc);
8280 argv = calloc(argc, sizeof(char *));
8281 if (argv == NULL)
8282 err(1, "calloc");
8283 for (i = 0; i < argc; i++) {
8284 argv[i] = strdup(va_arg(ap, char *));
8285 if (argv[i] == NULL)
8286 err(1, "strdup");
8289 va_end(ap);
8290 return argv;
8294 * Try to convert 'tog path' into a 'tog log path' command.
8295 * The user could simply have mistyped the command rather than knowingly
8296 * provided a path. So check whether argv[0] can in fact be resolved
8297 * to a path in the HEAD commit and print a special error if not.
8298 * This hack is for mpi@ <3
8300 static const struct got_error *
8301 tog_log_with_path(int argc, char *argv[])
8303 const struct got_error *error = NULL, *close_err;
8304 const struct tog_cmd *cmd = NULL;
8305 struct got_repository *repo = NULL;
8306 struct got_worktree *worktree = NULL;
8307 struct got_object_id *commit_id = NULL, *id = NULL;
8308 struct got_commit_object *commit = NULL;
8309 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8310 char *commit_id_str = NULL, **cmd_argv = NULL;
8311 int *pack_fds = NULL;
8313 cwd = getcwd(NULL, 0);
8314 if (cwd == NULL)
8315 return got_error_from_errno("getcwd");
8317 error = got_repo_pack_fds_open(&pack_fds);
8318 if (error != NULL)
8319 goto done;
8321 error = got_worktree_open(&worktree, cwd);
8322 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8323 goto done;
8325 if (worktree)
8326 repo_path = strdup(got_worktree_get_repo_path(worktree));
8327 else
8328 repo_path = strdup(cwd);
8329 if (repo_path == NULL) {
8330 error = got_error_from_errno("strdup");
8331 goto done;
8334 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8335 if (error != NULL)
8336 goto done;
8338 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8339 repo, worktree);
8340 if (error)
8341 goto done;
8343 error = tog_load_refs(repo, 0);
8344 if (error)
8345 goto done;
8346 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8347 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8348 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8349 if (error)
8350 goto done;
8352 if (worktree) {
8353 got_worktree_close(worktree);
8354 worktree = NULL;
8357 error = got_object_open_as_commit(&commit, repo, commit_id);
8358 if (error)
8359 goto done;
8361 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8362 if (error) {
8363 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8364 goto done;
8365 fprintf(stderr, "%s: '%s' is no known command or path\n",
8366 getprogname(), argv[0]);
8367 usage(1, 1);
8368 /* not reached */
8371 error = got_object_id_str(&commit_id_str, commit_id);
8372 if (error)
8373 goto done;
8375 cmd = &tog_commands[0]; /* log */
8376 argc = 4;
8377 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8378 error = cmd->cmd_main(argc, cmd_argv);
8379 done:
8380 if (repo) {
8381 close_err = got_repo_close(repo);
8382 if (error == NULL)
8383 error = close_err;
8385 if (commit)
8386 got_object_commit_close(commit);
8387 if (worktree)
8388 got_worktree_close(worktree);
8389 if (pack_fds) {
8390 const struct got_error *pack_err =
8391 got_repo_pack_fds_close(pack_fds);
8392 if (error == NULL)
8393 error = pack_err;
8395 free(id);
8396 free(commit_id_str);
8397 free(commit_id);
8398 free(cwd);
8399 free(repo_path);
8400 free(in_repo_path);
8401 if (cmd_argv) {
8402 int i;
8403 for (i = 0; i < argc; i++)
8404 free(cmd_argv[i]);
8405 free(cmd_argv);
8407 tog_free_refs();
8408 return error;
8411 int
8412 main(int argc, char *argv[])
8414 const struct got_error *error = NULL;
8415 const struct tog_cmd *cmd = NULL;
8416 int ch, hflag = 0, Vflag = 0;
8417 char **cmd_argv = NULL;
8418 static const struct option longopts[] = {
8419 { "version", no_argument, NULL, 'V' },
8420 { NULL, 0, NULL, 0}
8422 char *diff_algo_str = NULL;
8424 setlocale(LC_CTYPE, "");
8426 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8427 switch (ch) {
8428 case 'h':
8429 hflag = 1;
8430 break;
8431 case 'V':
8432 Vflag = 1;
8433 break;
8434 default:
8435 usage(hflag, 1);
8436 /* NOTREACHED */
8440 argc -= optind;
8441 argv += optind;
8442 optind = 1;
8443 optreset = 1;
8445 if (Vflag) {
8446 got_version_print_str();
8447 return 0;
8450 #ifndef PROFILE
8451 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8452 NULL) == -1)
8453 err(1, "pledge");
8454 #endif
8456 if (argc == 0) {
8457 if (hflag)
8458 usage(hflag, 0);
8459 /* Build an argument vector which runs a default command. */
8460 cmd = &tog_commands[0];
8461 argc = 1;
8462 cmd_argv = make_argv(argc, cmd->name);
8463 } else {
8464 size_t i;
8466 /* Did the user specify a command? */
8467 for (i = 0; i < nitems(tog_commands); i++) {
8468 if (strncmp(tog_commands[i].name, argv[0],
8469 strlen(argv[0])) == 0) {
8470 cmd = &tog_commands[i];
8471 break;
8476 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8477 if (diff_algo_str) {
8478 if (strcasecmp(diff_algo_str, "patience") == 0)
8479 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8480 if (strcasecmp(diff_algo_str, "myers") == 0)
8481 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8484 if (cmd == NULL) {
8485 if (argc != 1)
8486 usage(0, 1);
8487 /* No command specified; try log with a path */
8488 error = tog_log_with_path(argc, argv);
8489 } else {
8490 if (hflag)
8491 cmd->cmd_usage();
8492 else
8493 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8496 endwin();
8497 putchar('\n');
8498 if (cmd_argv) {
8499 int i;
8500 for (i = 0; i < argc; i++)
8501 free(cmd_argv[i]);
8502 free(cmd_argv);
8505 if (error && error->code != GOT_ERR_CANCELLED)
8506 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8507 return 0;