Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #if defined(__FreeBSD__) || defined(__APPLE__)
24 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
25 #endif
26 #include <curses.h>
27 #include <panel.h>
28 #include <locale.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_compat.h"
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
159 static const struct got_error *
160 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
161 struct got_reference* re2)
163 const char *name1 = got_ref_get_name(re1);
164 const char *name2 = got_ref_get_name(re2);
165 int isbackup1, isbackup2;
167 /* Sort backup refs towards the bottom of the list. */
168 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
169 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
170 if (!isbackup1 && isbackup2) {
171 *cmp = -1;
172 return NULL;
173 } else if (isbackup1 && !isbackup2) {
174 *cmp = 1;
175 return NULL;
178 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
179 return NULL;
182 static const struct got_error *
183 tog_load_refs(struct got_repository *repo, int sort_by_date)
185 const struct got_error *err;
187 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
188 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
189 repo);
190 if (err)
191 return err;
193 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
194 repo);
197 static void
198 tog_free_refs(void)
200 if (tog_refs_idmap) {
201 got_reflist_object_id_map_free(tog_refs_idmap);
202 tog_refs_idmap = NULL;
204 got_ref_list_free(&tog_refs);
207 static const struct got_error *
208 add_color(struct tog_colors *colors, const char *pattern,
209 int idx, short color)
211 const struct got_error *err = NULL;
212 struct tog_color *tc;
213 int regerr = 0;
215 if (idx < 1 || idx > COLOR_PAIRS - 1)
216 return NULL;
218 init_pair(idx, color, -1);
220 tc = calloc(1, sizeof(*tc));
221 if (tc == NULL)
222 return got_error_from_errno("calloc");
223 regerr = regcomp(&tc->regex, pattern,
224 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
225 if (regerr) {
226 static char regerr_msg[512];
227 static char err_msg[512];
228 regerror(regerr, &tc->regex, regerr_msg,
229 sizeof(regerr_msg));
230 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
231 regerr_msg);
232 err = got_error_msg(GOT_ERR_REGEX, err_msg);
233 free(tc);
234 return err;
236 tc->colorpair = idx;
237 STAILQ_INSERT_HEAD(colors, tc, entry);
238 return NULL;
241 static void
242 free_colors(struct tog_colors *colors)
244 struct tog_color *tc;
246 while (!STAILQ_EMPTY(colors)) {
247 tc = STAILQ_FIRST(colors);
248 STAILQ_REMOVE_HEAD(colors, entry);
249 regfree(&tc->regex);
250 free(tc);
254 static struct tog_color *
255 get_color(struct tog_colors *colors, int colorpair)
257 struct tog_color *tc = NULL;
259 STAILQ_FOREACH(tc, colors, entry) {
260 if (tc->colorpair == colorpair)
261 return tc;
264 return NULL;
267 static int
268 default_color_value(const char *envvar)
270 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
271 return COLOR_MAGENTA;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
273 return COLOR_CYAN;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
275 return COLOR_YELLOW;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
277 return COLOR_GREEN;
278 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
279 return COLOR_MAGENTA;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
283 return COLOR_CYAN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
285 return COLOR_GREEN;
286 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
291 return COLOR_YELLOW;
292 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
295 return COLOR_MAGENTA;
296 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
299 return COLOR_CYAN;
301 return -1;
304 static int
305 get_color_value(const char *envvar)
307 const char *val = getenv(envvar);
309 if (val == NULL)
310 return default_color_value(envvar);
312 if (strcasecmp(val, "black") == 0)
313 return COLOR_BLACK;
314 if (strcasecmp(val, "red") == 0)
315 return COLOR_RED;
316 if (strcasecmp(val, "green") == 0)
317 return COLOR_GREEN;
318 if (strcasecmp(val, "yellow") == 0)
319 return COLOR_YELLOW;
320 if (strcasecmp(val, "blue") == 0)
321 return COLOR_BLUE;
322 if (strcasecmp(val, "magenta") == 0)
323 return COLOR_MAGENTA;
324 if (strcasecmp(val, "cyan") == 0)
325 return COLOR_CYAN;
326 if (strcasecmp(val, "white") == 0)
327 return COLOR_WHITE;
328 if (strcasecmp(val, "default") == 0)
329 return -1;
331 return default_color_value(envvar);
334 struct tog_diff_view_state {
335 struct got_object_id *id1, *id2;
336 const char *label1, *label2;
337 FILE *f, *f1, *f2;
338 int fd1, fd2;
339 int lineno;
340 int first_displayed_line;
341 int last_displayed_line;
342 int eof;
343 int diff_context;
344 int ignore_whitespace;
345 int force_text_diff;
346 struct got_repository *repo;
347 struct got_diff_line *lines;
348 size_t nlines;
349 int matched_line;
350 int selected_line;
352 /* passed from log or blame view; may be NULL */
353 struct tog_view *parent_view;
354 };
356 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
357 static volatile sig_atomic_t tog_thread_error;
359 struct tog_log_thread_args {
360 pthread_cond_t need_commits;
361 pthread_cond_t commit_loaded;
362 int commits_needed;
363 int load_all;
364 struct got_commit_graph *graph;
365 struct commit_queue *real_commits;
366 const char *in_repo_path;
367 struct got_object_id *start_id;
368 struct got_repository *repo;
369 int *pack_fds;
370 int log_complete;
371 sig_atomic_t *quit;
372 struct commit_queue_entry **first_displayed_entry;
373 struct commit_queue_entry **selected_entry;
374 int *searching;
375 int *search_next_done;
376 regex_t *regex;
377 int *limiting;
378 int limit_match;
379 regex_t *limit_regex;
380 struct commit_queue *limit_commits;
381 };
383 struct tog_log_view_state {
384 struct commit_queue *commits;
385 struct commit_queue_entry *first_displayed_entry;
386 struct commit_queue_entry *last_displayed_entry;
387 struct commit_queue_entry *selected_entry;
388 struct commit_queue real_commits;
389 int selected;
390 char *in_repo_path;
391 char *head_ref_name;
392 int log_branches;
393 struct got_repository *repo;
394 struct got_object_id *start_id;
395 sig_atomic_t quit;
396 pthread_t thread;
397 struct tog_log_thread_args thread_args;
398 struct commit_queue_entry *matched_entry;
399 struct commit_queue_entry *search_entry;
400 struct tog_colors colors;
401 int use_committer;
402 int limit_view;
403 regex_t limit_regex;
404 struct commit_queue limit_commits;
405 };
407 #define TOG_COLOR_DIFF_MINUS 1
408 #define TOG_COLOR_DIFF_PLUS 2
409 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
410 #define TOG_COLOR_DIFF_META 4
411 #define TOG_COLOR_TREE_SUBMODULE 5
412 #define TOG_COLOR_TREE_SYMLINK 6
413 #define TOG_COLOR_TREE_DIRECTORY 7
414 #define TOG_COLOR_TREE_EXECUTABLE 8
415 #define TOG_COLOR_COMMIT 9
416 #define TOG_COLOR_AUTHOR 10
417 #define TOG_COLOR_DATE 11
418 #define TOG_COLOR_REFS_HEADS 12
419 #define TOG_COLOR_REFS_TAGS 13
420 #define TOG_COLOR_REFS_REMOTES 14
421 #define TOG_COLOR_REFS_BACKUP 15
423 struct tog_blame_cb_args {
424 struct tog_blame_line *lines; /* one per line */
425 int nlines;
427 struct tog_view *view;
428 struct got_object_id *commit_id;
429 int *quit;
430 };
432 struct tog_blame_thread_args {
433 const char *path;
434 struct got_repository *repo;
435 struct tog_blame_cb_args *cb_args;
436 int *complete;
437 got_cancel_cb cancel_cb;
438 void *cancel_arg;
439 };
441 struct tog_blame {
442 FILE *f;
443 off_t filesize;
444 struct tog_blame_line *lines;
445 int nlines;
446 off_t *line_offsets;
447 pthread_t thread;
448 struct tog_blame_thread_args thread_args;
449 struct tog_blame_cb_args cb_args;
450 const char *path;
451 int *pack_fds;
452 };
454 struct tog_blame_view_state {
455 int first_displayed_line;
456 int last_displayed_line;
457 int selected_line;
458 int last_diffed_line;
459 int blame_complete;
460 int eof;
461 int done;
462 struct got_object_id_queue blamed_commits;
463 struct got_object_qid *blamed_commit;
464 char *path;
465 struct got_repository *repo;
466 struct got_object_id *commit_id;
467 struct got_object_id *id_to_log;
468 struct tog_blame blame;
469 int matched_line;
470 struct tog_colors colors;
471 };
473 struct tog_parent_tree {
474 TAILQ_ENTRY(tog_parent_tree) entry;
475 struct got_tree_object *tree;
476 struct got_tree_entry *first_displayed_entry;
477 struct got_tree_entry *selected_entry;
478 int selected;
479 };
481 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
483 struct tog_tree_view_state {
484 char *tree_label;
485 struct got_object_id *commit_id;/* commit which this tree belongs to */
486 struct got_tree_object *root; /* the commit's root tree entry */
487 struct got_tree_object *tree; /* currently displayed (sub-)tree */
488 struct got_tree_entry *first_displayed_entry;
489 struct got_tree_entry *last_displayed_entry;
490 struct got_tree_entry *selected_entry;
491 int ndisplayed, selected, show_ids;
492 struct tog_parent_trees parents; /* parent trees of current sub-tree */
493 char *head_ref_name;
494 struct got_repository *repo;
495 struct got_tree_entry *matched_entry;
496 struct tog_colors colors;
497 };
499 struct tog_reflist_entry {
500 TAILQ_ENTRY(tog_reflist_entry) entry;
501 struct got_reference *ref;
502 int idx;
503 };
505 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
507 struct tog_ref_view_state {
508 struct tog_reflist_head refs;
509 struct tog_reflist_entry *first_displayed_entry;
510 struct tog_reflist_entry *last_displayed_entry;
511 struct tog_reflist_entry *selected_entry;
512 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
513 struct got_repository *repo;
514 struct tog_reflist_entry *matched_entry;
515 struct tog_colors colors;
516 };
518 struct tog_help_view_state {
519 FILE *f;
520 off_t *line_offsets;
521 size_t nlines;
522 int lineno;
523 int first_displayed_line;
524 int last_displayed_line;
525 int eof;
526 int matched_line;
527 int selected_line;
528 int all;
529 enum tog_keymap_type type;
530 };
532 #define GENERATE_HELP \
533 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
534 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
535 KEY_("k C-p Up", "Move cursor or page up one line"), \
536 KEY_("j C-n Down", "Move cursor or page down one line"), \
537 KEY_("C-b b PgUp", "Scroll the view up one page"), \
538 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
539 KEY_("C-u u", "Scroll the view up one half page"), \
540 KEY_("C-d d", "Scroll the view down one half page"), \
541 KEY_("g Home", "Go to line N (default: first line)"), \
542 KEY_("G End", "Go to line N (default: last line)"), \
543 KEY_("l Right", "Scroll the view right"), \
544 KEY_("h Left", "Scroll the view left"), \
545 KEY_("$", "Scroll view to the rightmost position"), \
546 KEY_("0", "Scroll view to the leftmost position"), \
547 KEY_("-", "Decrease size of the focussed split"), \
548 KEY_("+", "Increase size of the focussed split"), \
549 KEY_("Tab", "Switch focus between views"), \
550 KEY_("F", "Toggle fullscreen mode"), \
551 KEY_("/", "Open prompt to enter search term"), \
552 KEY_("n", "Find next line/token matching the current search term"), \
553 KEY_("N", "Find previous line/token matching the current search term"),\
554 KEY_("q", "Quit the focussed view"), \
555 KEY_("Q", "Quit tog"), \
557 KEYMAP_("Log", TOG_KEYMAP_LOG), \
558 KEY_("< ,", "Move cursor up one commit"), \
559 KEY_("> .", "Move cursor down one commit"), \
560 KEY_("Enter", "Open diff view of the selected commit"), \
561 KEY_("B", "Reload the log view and toggle display of merged commits"), \
562 KEY_("R", "Open ref view of all repository references"), \
563 KEY_("T", "Display tree view of the repository from the selected" \
564 " commit"), \
565 KEY_("@", "Toggle between displaying author and committer name"), \
566 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
567 KEY_("C-g Backspace", "Cancel current search or log operation"), \
568 KEY_("C-l", "Reload the log view with new commits in the repository"), \
570 KEYMAP_("Diff", TOG_KEYMAP_DIFF), \
571 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
572 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
573 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
574 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
575 " data"), \
576 KEY_("(", "Go to the previous file in the diff"), \
577 KEY_(")", "Go to the next file in the diff"), \
578 KEY_("{", "Go to the previous hunk in the diff"), \
579 KEY_("}", "Go to the next hunk in the diff"), \
580 KEY_("[", "Decrease the number of context lines"), \
581 KEY_("]", "Increase the number of context lines"), \
582 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
584 KEYMAP_("Blame", TOG_KEYMAP_BLAME), \
585 KEY_("Enter", "Display diff view of the selected line's commit"), \
586 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
587 KEY_("L", "Open log view for the currently selected annotated line"), \
588 KEY_("C", "Reload view with the previously blamed commit"), \
589 KEY_("c", "Reload view with the version of the file found in the" \
590 " selected line's commit"), \
591 KEY_("p", "Reload view with the version of the file found in the" \
592 " selected line's parent commit"), \
594 KEYMAP_("Tree", TOG_KEYMAP_TREE), \
595 KEY_("Enter", "Enter selected directory or open blame view of the" \
596 " selected file"), \
597 KEY_("L", "Open log view for the selected entry"), \
598 KEY_("R", "Open ref view of all repository references"), \
599 KEY_("i", "Show object IDs for all tree entries"), \
600 KEY_("Backspace", "Return to the parent directory"), \
602 KEYMAP_("Ref", TOG_KEYMAP_REF), \
603 KEY_("Enter", "Display log view of the selected reference"), \
604 KEY_("T", "Display tree view of the selected reference"), \
605 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
606 KEY_("m", "Toggle display of last modified date for each reference"), \
607 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
608 KEY_("C-l", "Reload view with all repository references")
610 struct tog_key_map {
611 const char *keys;
612 const char *info;
613 enum tog_keymap_type type;
614 };
616 /*
617 * We implement two types of views: parent views and child views.
619 * The 'Tab' key switches focus between a parent view and its child view.
620 * Child views are shown side-by-side to their parent view, provided
621 * there is enough screen estate.
623 * When a new view is opened from within a parent view, this new view
624 * becomes a child view of the parent view, replacing any existing child.
626 * When a new view is opened from within a child view, this new view
627 * becomes a parent view which will obscure the views below until the
628 * user quits the new parent view by typing 'q'.
630 * This list of views contains parent views only.
631 * Child views are only pointed to by their parent view.
632 */
633 TAILQ_HEAD(tog_view_list_head, tog_view);
635 struct tog_view {
636 TAILQ_ENTRY(tog_view) entry;
637 WINDOW *window;
638 PANEL *panel;
639 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
640 int resized_y, resized_x; /* begin_y/x based on user resizing */
641 int maxx, x; /* max column and current start column */
642 int lines, cols; /* copies of LINES and COLS */
643 int nscrolled, offset; /* lines scrolled and hsplit line offset */
644 int gline, hiline; /* navigate to and highlight this nG line */
645 int ch, count; /* current keymap and count prefix */
646 int resized; /* set when in a resize event */
647 int focussed; /* Only set on one parent or child view at a time. */
648 int dying;
649 struct tog_view *parent;
650 struct tog_view *child;
652 /*
653 * This flag is initially set on parent views when a new child view
654 * is created. It gets toggled when the 'Tab' key switches focus
655 * between parent and child.
656 * The flag indicates whether focus should be passed on to our child
657 * view if this parent view gets picked for focus after another parent
658 * view was closed. This prevents child views from losing focus in such
659 * situations.
660 */
661 int focus_child;
663 enum tog_view_mode mode;
664 /* type-specific state */
665 enum tog_view_type type;
666 union {
667 struct tog_diff_view_state diff;
668 struct tog_log_view_state log;
669 struct tog_blame_view_state blame;
670 struct tog_tree_view_state tree;
671 struct tog_ref_view_state ref;
672 struct tog_help_view_state help;
673 } state;
675 const struct got_error *(*show)(struct tog_view *);
676 const struct got_error *(*input)(struct tog_view **,
677 struct tog_view *, int);
678 const struct got_error *(*reset)(struct tog_view *);
679 const struct got_error *(*resize)(struct tog_view *, int);
680 const struct got_error *(*close)(struct tog_view *);
682 const struct got_error *(*search_start)(struct tog_view *);
683 const struct got_error *(*search_next)(struct tog_view *);
684 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
685 int **, int **, int **, int **);
686 int search_started;
687 int searching;
688 #define TOG_SEARCH_FORWARD 1
689 #define TOG_SEARCH_BACKWARD 2
690 int search_next_done;
691 #define TOG_SEARCH_HAVE_MORE 1
692 #define TOG_SEARCH_NO_MORE 2
693 #define TOG_SEARCH_HAVE_NONE 3
694 regex_t regex;
695 regmatch_t regmatch;
696 };
698 static const struct got_error *open_diff_view(struct tog_view *,
699 struct got_object_id *, struct got_object_id *,
700 const char *, const char *, int, int, int, struct tog_view *,
701 struct got_repository *);
702 static const struct got_error *show_diff_view(struct tog_view *);
703 static const struct got_error *input_diff_view(struct tog_view **,
704 struct tog_view *, int);
705 static const struct got_error *reset_diff_view(struct tog_view *);
706 static const struct got_error* close_diff_view(struct tog_view *);
707 static const struct got_error *search_start_diff_view(struct tog_view *);
708 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
709 size_t *, int **, int **, int **, int **);
710 static const struct got_error *search_next_view_match(struct tog_view *);
712 static const struct got_error *open_log_view(struct tog_view *,
713 struct got_object_id *, struct got_repository *,
714 const char *, const char *, int);
715 static const struct got_error * show_log_view(struct tog_view *);
716 static const struct got_error *input_log_view(struct tog_view **,
717 struct tog_view *, int);
718 static const struct got_error *resize_log_view(struct tog_view *, int);
719 static const struct got_error *close_log_view(struct tog_view *);
720 static const struct got_error *search_start_log_view(struct tog_view *);
721 static const struct got_error *search_next_log_view(struct tog_view *);
723 static const struct got_error *open_blame_view(struct tog_view *, char *,
724 struct got_object_id *, struct got_repository *);
725 static const struct got_error *show_blame_view(struct tog_view *);
726 static const struct got_error *input_blame_view(struct tog_view **,
727 struct tog_view *, int);
728 static const struct got_error *reset_blame_view(struct tog_view *);
729 static const struct got_error *close_blame_view(struct tog_view *);
730 static const struct got_error *search_start_blame_view(struct tog_view *);
731 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
732 size_t *, int **, int **, int **, int **);
734 static const struct got_error *open_tree_view(struct tog_view *,
735 struct got_object_id *, const char *, struct got_repository *);
736 static const struct got_error *show_tree_view(struct tog_view *);
737 static const struct got_error *input_tree_view(struct tog_view **,
738 struct tog_view *, int);
739 static const struct got_error *close_tree_view(struct tog_view *);
740 static const struct got_error *search_start_tree_view(struct tog_view *);
741 static const struct got_error *search_next_tree_view(struct tog_view *);
743 static const struct got_error *open_ref_view(struct tog_view *,
744 struct got_repository *);
745 static const struct got_error *show_ref_view(struct tog_view *);
746 static const struct got_error *input_ref_view(struct tog_view **,
747 struct tog_view *, int);
748 static const struct got_error *close_ref_view(struct tog_view *);
749 static const struct got_error *search_start_ref_view(struct tog_view *);
750 static const struct got_error *search_next_ref_view(struct tog_view *);
752 static const struct got_error *open_help_view(struct tog_view *,
753 struct tog_view *);
754 static const struct got_error *show_help_view(struct tog_view *);
755 static const struct got_error *input_help_view(struct tog_view **,
756 struct tog_view *, int);
757 static const struct got_error *reset_help_view(struct tog_view *);
758 static const struct got_error* close_help_view(struct tog_view *);
759 static const struct got_error *search_start_help_view(struct tog_view *);
760 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
761 size_t *, int **, int **, int **, int **);
763 static volatile sig_atomic_t tog_sigwinch_received;
764 static volatile sig_atomic_t tog_sigpipe_received;
765 static volatile sig_atomic_t tog_sigcont_received;
766 static volatile sig_atomic_t tog_sigint_received;
767 static volatile sig_atomic_t tog_sigterm_received;
769 static void
770 tog_sigwinch(int signo)
772 tog_sigwinch_received = 1;
775 static void
776 tog_sigpipe(int signo)
778 tog_sigpipe_received = 1;
781 static void
782 tog_sigcont(int signo)
784 tog_sigcont_received = 1;
787 static void
788 tog_sigint(int signo)
790 tog_sigint_received = 1;
793 static void
794 tog_sigterm(int signo)
796 tog_sigterm_received = 1;
799 static int
800 tog_fatal_signal_received(void)
802 return (tog_sigpipe_received ||
803 tog_sigint_received || tog_sigint_received);
806 static const struct got_error *
807 view_close(struct tog_view *view)
809 const struct got_error *err = NULL, *child_err = NULL;
811 if (view->child) {
812 child_err = view_close(view->child);
813 view->child = NULL;
815 if (view->close)
816 err = view->close(view);
817 if (view->panel)
818 del_panel(view->panel);
819 if (view->window)
820 delwin(view->window);
821 free(view);
822 return err ? err : child_err;
825 static struct tog_view *
826 view_open(int nlines, int ncols, int begin_y, int begin_x,
827 enum tog_view_type type)
829 struct tog_view *view = calloc(1, sizeof(*view));
831 if (view == NULL)
832 return NULL;
834 view->type = type;
835 view->lines = LINES;
836 view->cols = COLS;
837 view->nlines = nlines ? nlines : LINES - begin_y;
838 view->ncols = ncols ? ncols : COLS - begin_x;
839 view->begin_y = begin_y;
840 view->begin_x = begin_x;
841 view->window = newwin(nlines, ncols, begin_y, begin_x);
842 if (view->window == NULL) {
843 view_close(view);
844 return NULL;
846 view->panel = new_panel(view->window);
847 if (view->panel == NULL ||
848 set_panel_userptr(view->panel, view) != OK) {
849 view_close(view);
850 return NULL;
853 keypad(view->window, TRUE);
854 return view;
857 static int
858 view_split_begin_x(int begin_x)
860 if (begin_x > 0 || COLS < 120)
861 return 0;
862 return (COLS - MAX(COLS / 2, 80));
865 /* XXX Stub till we decide what to do. */
866 static int
867 view_split_begin_y(int lines)
869 return lines * HSPLIT_SCALE;
872 static const struct got_error *view_resize(struct tog_view *);
874 static const struct got_error *
875 view_splitscreen(struct tog_view *view)
877 const struct got_error *err = NULL;
879 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
880 if (view->resized_y && view->resized_y < view->lines)
881 view->begin_y = view->resized_y;
882 else
883 view->begin_y = view_split_begin_y(view->nlines);
884 view->begin_x = 0;
885 } else if (!view->resized) {
886 if (view->resized_x && view->resized_x < view->cols - 1 &&
887 view->cols > 119)
888 view->begin_x = view->resized_x;
889 else
890 view->begin_x = view_split_begin_x(0);
891 view->begin_y = 0;
893 view->nlines = LINES - view->begin_y;
894 view->ncols = COLS - view->begin_x;
895 view->lines = LINES;
896 view->cols = COLS;
897 err = view_resize(view);
898 if (err)
899 return err;
901 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
902 view->parent->nlines = view->begin_y;
904 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
905 return got_error_from_errno("mvwin");
907 return NULL;
910 static const struct got_error *
911 view_fullscreen(struct tog_view *view)
913 const struct got_error *err = NULL;
915 view->begin_x = 0;
916 view->begin_y = view->resized ? view->begin_y : 0;
917 view->nlines = view->resized ? view->nlines : LINES;
918 view->ncols = COLS;
919 view->lines = LINES;
920 view->cols = COLS;
921 err = view_resize(view);
922 if (err)
923 return err;
925 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
926 return got_error_from_errno("mvwin");
928 return NULL;
931 static int
932 view_is_parent_view(struct tog_view *view)
934 return view->parent == NULL;
937 static int
938 view_is_splitscreen(struct tog_view *view)
940 return view->begin_x > 0 || view->begin_y > 0;
943 static int
944 view_is_fullscreen(struct tog_view *view)
946 return view->nlines == LINES && view->ncols == COLS;
949 static int
950 view_is_hsplit_top(struct tog_view *view)
952 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
953 view_is_splitscreen(view->child);
956 static void
957 view_border(struct tog_view *view)
959 PANEL *panel;
960 const struct tog_view *view_above;
962 if (view->parent)
963 return view_border(view->parent);
965 panel = panel_above(view->panel);
966 if (panel == NULL)
967 return;
969 view_above = panel_userptr(panel);
970 if (view->mode == TOG_VIEW_SPLIT_HRZN)
971 mvwhline(view->window, view_above->begin_y - 1,
972 view->begin_x, got_locale_is_utf8() ?
973 ACS_HLINE : '-', view->ncols);
974 else
975 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
976 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
979 static const struct got_error *view_init_hsplit(struct tog_view *, int);
980 static const struct got_error *request_log_commits(struct tog_view *);
981 static const struct got_error *offset_selection_down(struct tog_view *);
982 static void offset_selection_up(struct tog_view *);
983 static void view_get_split(struct tog_view *, int *, int *);
985 static const struct got_error *
986 view_resize(struct tog_view *view)
988 const struct got_error *err = NULL;
989 int dif, nlines, ncols;
991 dif = LINES - view->lines; /* line difference */
993 if (view->lines > LINES)
994 nlines = view->nlines - (view->lines - LINES);
995 else
996 nlines = view->nlines + (LINES - view->lines);
997 if (view->cols > COLS)
998 ncols = view->ncols - (view->cols - COLS);
999 else
1000 ncols = view->ncols + (COLS - view->cols);
1002 if (view->child) {
1003 int hs = view->child->begin_y;
1005 if (!view_is_fullscreen(view))
1006 view->child->begin_x = view_split_begin_x(view->begin_x);
1007 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1008 view->child->begin_x == 0) {
1009 ncols = COLS;
1011 view_fullscreen(view->child);
1012 if (view->child->focussed)
1013 show_panel(view->child->panel);
1014 else
1015 show_panel(view->panel);
1016 } else {
1017 ncols = view->child->begin_x;
1019 view_splitscreen(view->child);
1020 show_panel(view->child->panel);
1023 * XXX This is ugly and needs to be moved into the above
1024 * logic but "works" for now and my attempts at moving it
1025 * break either 'tab' or 'F' key maps in horizontal splits.
1027 if (hs) {
1028 err = view_splitscreen(view->child);
1029 if (err)
1030 return err;
1031 if (dif < 0) { /* top split decreased */
1032 err = offset_selection_down(view);
1033 if (err)
1034 return err;
1036 view_border(view);
1037 update_panels();
1038 doupdate();
1039 show_panel(view->child->panel);
1040 nlines = view->nlines;
1042 } else if (view->parent == NULL)
1043 ncols = COLS;
1045 if (view->resize && dif > 0) {
1046 err = view->resize(view, dif);
1047 if (err)
1048 return err;
1051 if (wresize(view->window, nlines, ncols) == ERR)
1052 return got_error_from_errno("wresize");
1053 if (replace_panel(view->panel, view->window) == ERR)
1054 return got_error_from_errno("replace_panel");
1055 wclear(view->window);
1057 view->nlines = nlines;
1058 view->ncols = ncols;
1059 view->lines = LINES;
1060 view->cols = COLS;
1062 return NULL;
1065 static const struct got_error *
1066 resize_log_view(struct tog_view *view, int increase)
1068 struct tog_log_view_state *s = &view->state.log;
1069 const struct got_error *err = NULL;
1070 int n = 0;
1072 if (s->selected_entry)
1073 n = s->selected_entry->idx + view->lines - s->selected;
1076 * Request commits to account for the increased
1077 * height so we have enough to populate the view.
1079 if (s->commits->ncommits < n) {
1080 view->nscrolled = n - s->commits->ncommits + increase + 1;
1081 err = request_log_commits(view);
1084 return err;
1087 static void
1088 view_adjust_offset(struct tog_view *view, int n)
1090 if (n == 0)
1091 return;
1093 if (view->parent && view->parent->offset) {
1094 if (view->parent->offset + n >= 0)
1095 view->parent->offset += n;
1096 else
1097 view->parent->offset = 0;
1098 } else if (view->offset) {
1099 if (view->offset - n >= 0)
1100 view->offset -= n;
1101 else
1102 view->offset = 0;
1106 static const struct got_error *
1107 view_resize_split(struct tog_view *view, int resize)
1109 const struct got_error *err = NULL;
1110 struct tog_view *v = NULL;
1112 if (view->parent)
1113 v = view->parent;
1114 else
1115 v = view;
1117 if (!v->child || !view_is_splitscreen(v->child))
1118 return NULL;
1120 v->resized = v->child->resized = resize; /* lock for resize event */
1122 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1123 if (v->child->resized_y)
1124 v->child->begin_y = v->child->resized_y;
1125 if (view->parent)
1126 v->child->begin_y -= resize;
1127 else
1128 v->child->begin_y += resize;
1129 if (v->child->begin_y < 3) {
1130 view->count = 0;
1131 v->child->begin_y = 3;
1132 } else if (v->child->begin_y > LINES - 1) {
1133 view->count = 0;
1134 v->child->begin_y = LINES - 1;
1136 v->ncols = COLS;
1137 v->child->ncols = COLS;
1138 view_adjust_offset(view, resize);
1139 err = view_init_hsplit(v, v->child->begin_y);
1140 if (err)
1141 return err;
1142 v->child->resized_y = v->child->begin_y;
1143 } else {
1144 if (v->child->resized_x)
1145 v->child->begin_x = v->child->resized_x;
1146 if (view->parent)
1147 v->child->begin_x -= resize;
1148 else
1149 v->child->begin_x += resize;
1150 if (v->child->begin_x < 11) {
1151 view->count = 0;
1152 v->child->begin_x = 11;
1153 } else if (v->child->begin_x > COLS - 1) {
1154 view->count = 0;
1155 v->child->begin_x = COLS - 1;
1157 v->child->resized_x = v->child->begin_x;
1160 v->child->mode = v->mode;
1161 v->child->nlines = v->lines - v->child->begin_y;
1162 v->child->ncols = v->cols - v->child->begin_x;
1163 v->focus_child = 1;
1165 err = view_fullscreen(v);
1166 if (err)
1167 return err;
1168 err = view_splitscreen(v->child);
1169 if (err)
1170 return err;
1172 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1173 err = offset_selection_down(v->child);
1174 if (err)
1175 return err;
1178 if (v->resize)
1179 err = v->resize(v, 0);
1180 else if (v->child->resize)
1181 err = v->child->resize(v->child, 0);
1183 v->resized = v->child->resized = 0;
1185 return err;
1188 static void
1189 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1191 struct tog_view *v = src->child ? src->child : src;
1193 dst->resized_x = v->resized_x;
1194 dst->resized_y = v->resized_y;
1197 static const struct got_error *
1198 view_close_child(struct tog_view *view)
1200 const struct got_error *err = NULL;
1202 if (view->child == NULL)
1203 return NULL;
1205 err = view_close(view->child);
1206 view->child = NULL;
1207 return err;
1210 static const struct got_error *
1211 view_set_child(struct tog_view *view, struct tog_view *child)
1213 const struct got_error *err = NULL;
1215 view->child = child;
1216 child->parent = view;
1218 err = view_resize(view);
1219 if (err)
1220 return err;
1222 if (view->child->resized_x || view->child->resized_y)
1223 err = view_resize_split(view, 0);
1225 return err;
1228 static const struct got_error *view_dispatch_request(struct tog_view **,
1229 struct tog_view *, enum tog_view_type, int, int);
1231 static const struct got_error *
1232 view_request_new(struct tog_view **requested, struct tog_view *view,
1233 enum tog_view_type request)
1235 struct tog_view *new_view = NULL;
1236 const struct got_error *err;
1237 int y = 0, x = 0;
1239 *requested = NULL;
1241 if (view_is_parent_view(view))
1242 view_get_split(view, &y, &x);
1244 err = view_dispatch_request(&new_view, view, request, y, x);
1245 if (err)
1246 return err;
1248 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN) {
1249 err = view_init_hsplit(view, y);
1250 if (err)
1251 return err;
1254 view->focussed = 0;
1255 new_view->focussed = 1;
1256 new_view->mode = view->mode;
1257 new_view->nlines = view->lines - y;
1259 if (view_is_parent_view(view)) {
1260 view_transfer_size(new_view, view);
1261 err = view_close_child(view);
1262 if (err)
1263 return err;
1264 err = view_set_child(view, new_view);
1265 if (err)
1266 return err;
1267 view->focus_child = 1;
1268 } else
1269 *requested = new_view;
1271 return NULL;
1274 static void
1275 tog_resizeterm(void)
1277 int cols, lines;
1278 struct winsize size;
1280 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1281 cols = 80; /* Default */
1282 lines = 24;
1283 } else {
1284 cols = size.ws_col;
1285 lines = size.ws_row;
1287 resize_term(lines, cols);
1290 static const struct got_error *
1291 view_search_start(struct tog_view *view)
1293 const struct got_error *err = NULL;
1294 struct tog_view *v = view;
1295 char pattern[1024];
1296 int ret;
1298 if (view->search_started) {
1299 regfree(&view->regex);
1300 view->searching = 0;
1301 memset(&view->regmatch, 0, sizeof(view->regmatch));
1303 view->search_started = 0;
1305 if (view->nlines < 1)
1306 return NULL;
1308 if (view_is_hsplit_top(view))
1309 v = view->child;
1311 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1312 wclrtoeol(v->window);
1314 nodelay(view->window, FALSE); /* block for search term input */
1315 nocbreak();
1316 echo();
1317 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1318 wrefresh(v->window);
1319 cbreak();
1320 noecho();
1321 nodelay(view->window, TRUE);
1322 if (ret == ERR)
1323 return NULL;
1325 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1326 err = view->search_start(view);
1327 if (err) {
1328 regfree(&view->regex);
1329 return err;
1331 view->search_started = 1;
1332 view->searching = TOG_SEARCH_FORWARD;
1333 view->search_next_done = 0;
1334 view->search_next(view);
1337 return NULL;
1340 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1341 static const struct got_error *
1342 switch_split(struct tog_view *view)
1344 const struct got_error *err = NULL;
1345 struct tog_view *v = NULL;
1347 if (view->parent)
1348 v = view->parent;
1349 else
1350 v = view;
1352 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1353 v->mode = TOG_VIEW_SPLIT_VERT;
1354 else
1355 v->mode = TOG_VIEW_SPLIT_HRZN;
1357 if (!v->child)
1358 return NULL;
1359 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1360 v->mode = TOG_VIEW_SPLIT_NONE;
1362 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1363 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1364 v->child->begin_y = v->child->resized_y;
1365 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1366 v->child->begin_x = v->child->resized_x;
1369 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1370 v->ncols = COLS;
1371 v->child->ncols = COLS;
1372 v->child->nscrolled = LINES - v->child->nlines;
1374 err = view_init_hsplit(v, v->child->begin_y);
1375 if (err)
1376 return err;
1378 v->child->mode = v->mode;
1379 v->child->nlines = v->lines - v->child->begin_y;
1380 v->focus_child = 1;
1382 err = view_fullscreen(v);
1383 if (err)
1384 return err;
1385 err = view_splitscreen(v->child);
1386 if (err)
1387 return err;
1389 if (v->mode == TOG_VIEW_SPLIT_NONE)
1390 v->mode = TOG_VIEW_SPLIT_VERT;
1391 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1392 err = offset_selection_down(v);
1393 if (err)
1394 return err;
1395 err = offset_selection_down(v->child);
1396 if (err)
1397 return err;
1398 } else {
1399 offset_selection_up(v);
1400 offset_selection_up(v->child);
1402 if (v->resize)
1403 err = v->resize(v, 0);
1404 else if (v->child->resize)
1405 err = v->child->resize(v->child, 0);
1407 return err;
1411 * Compute view->count from numeric input. Assign total to view->count and
1412 * return first non-numeric key entered.
1414 static int
1415 get_compound_key(struct tog_view *view, int c)
1417 struct tog_view *v = view;
1418 int x, n = 0;
1420 if (view_is_hsplit_top(view))
1421 v = view->child;
1422 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1423 v = view->parent;
1425 view->count = 0;
1426 cbreak(); /* block for input */
1427 nodelay(view->window, FALSE);
1428 wmove(v->window, v->nlines - 1, 0);
1429 wclrtoeol(v->window);
1430 waddch(v->window, ':');
1432 do {
1433 x = getcurx(v->window);
1434 if (x != ERR && x < view->ncols) {
1435 waddch(v->window, c);
1436 wrefresh(v->window);
1440 * Don't overflow. Max valid request should be the greatest
1441 * between the longest and total lines; cap at 10 million.
1443 if (n >= 9999999)
1444 n = 9999999;
1445 else
1446 n = n * 10 + (c - '0');
1447 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1449 if (c == 'G' || c == 'g') { /* nG key map */
1450 view->gline = view->hiline = n;
1451 n = 0;
1452 c = 0;
1455 /* Massage excessive or inapplicable values at the input handler. */
1456 view->count = n;
1458 return c;
1461 static const struct got_error *
1462 view_input(struct tog_view **new, int *done, struct tog_view *view,
1463 struct tog_view_list_head *views)
1465 const struct got_error *err = NULL;
1466 struct tog_view *v;
1467 int ch, errcode;
1469 *new = NULL;
1471 /* Clear "no matches" indicator. */
1472 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1473 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1474 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1475 view->count = 0;
1478 if (view->searching && !view->search_next_done) {
1479 errcode = pthread_mutex_unlock(&tog_mutex);
1480 if (errcode)
1481 return got_error_set_errno(errcode,
1482 "pthread_mutex_unlock");
1483 sched_yield();
1484 errcode = pthread_mutex_lock(&tog_mutex);
1485 if (errcode)
1486 return got_error_set_errno(errcode,
1487 "pthread_mutex_lock");
1488 view->search_next(view);
1489 return NULL;
1492 /* Allow threads to make progress while we are waiting for input. */
1493 errcode = pthread_mutex_unlock(&tog_mutex);
1494 if (errcode)
1495 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1496 /* If we have an unfinished count, let C-g or backspace abort. */
1497 if (view->count && --view->count) {
1498 cbreak();
1499 nodelay(view->window, TRUE);
1500 ch = wgetch(view->window);
1501 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1502 view->count = 0;
1503 else
1504 ch = view->ch;
1505 } else {
1506 ch = wgetch(view->window);
1507 if (ch >= '1' && ch <= '9')
1508 view->ch = ch = get_compound_key(view, ch);
1510 if (view->hiline && ch != ERR && ch != 0)
1511 view->hiline = 0; /* key pressed, clear line highlight */
1512 nodelay(view->window, TRUE);
1513 errcode = pthread_mutex_lock(&tog_mutex);
1514 if (errcode)
1515 return got_error_set_errno(errcode, "pthread_mutex_lock");
1517 if (tog_sigwinch_received || tog_sigcont_received) {
1518 tog_resizeterm();
1519 tog_sigwinch_received = 0;
1520 tog_sigcont_received = 0;
1521 TAILQ_FOREACH(v, views, entry) {
1522 err = view_resize(v);
1523 if (err)
1524 return err;
1525 err = v->input(new, v, KEY_RESIZE);
1526 if (err)
1527 return err;
1528 if (v->child) {
1529 err = view_resize(v->child);
1530 if (err)
1531 return err;
1532 err = v->child->input(new, v->child,
1533 KEY_RESIZE);
1534 if (err)
1535 return err;
1536 if (v->child->resized_x || v->child->resized_y) {
1537 err = view_resize_split(v, 0);
1538 if (err)
1539 return err;
1545 switch (ch) {
1546 case '?':
1547 case 'H':
1548 case KEY_F(1):
1549 if (view->type == TOG_VIEW_HELP)
1550 err = view->reset(view);
1551 else
1552 err = view_request_new(new, view, TOG_VIEW_HELP);
1553 break;
1554 case '\t':
1555 view->count = 0;
1556 if (view->child) {
1557 view->focussed = 0;
1558 view->child->focussed = 1;
1559 view->focus_child = 1;
1560 } else if (view->parent) {
1561 view->focussed = 0;
1562 view->parent->focussed = 1;
1563 view->parent->focus_child = 0;
1564 if (!view_is_splitscreen(view)) {
1565 if (view->parent->resize) {
1566 err = view->parent->resize(view->parent,
1567 0);
1568 if (err)
1569 return err;
1571 offset_selection_up(view->parent);
1572 err = view_fullscreen(view->parent);
1573 if (err)
1574 return err;
1577 break;
1578 case 'q':
1579 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1580 if (view->parent->resize) {
1581 /* might need more commits to fill fullscreen */
1582 err = view->parent->resize(view->parent, 0);
1583 if (err)
1584 break;
1586 offset_selection_up(view->parent);
1588 err = view->input(new, view, ch);
1589 view->dying = 1;
1590 break;
1591 case 'Q':
1592 *done = 1;
1593 break;
1594 case 'F':
1595 view->count = 0;
1596 if (view_is_parent_view(view)) {
1597 if (view->child == NULL)
1598 break;
1599 if (view_is_splitscreen(view->child)) {
1600 view->focussed = 0;
1601 view->child->focussed = 1;
1602 err = view_fullscreen(view->child);
1603 } else {
1604 err = view_splitscreen(view->child);
1605 if (!err)
1606 err = view_resize_split(view, 0);
1608 if (err)
1609 break;
1610 err = view->child->input(new, view->child,
1611 KEY_RESIZE);
1612 } else {
1613 if (view_is_splitscreen(view)) {
1614 view->parent->focussed = 0;
1615 view->focussed = 1;
1616 err = view_fullscreen(view);
1617 } else {
1618 err = view_splitscreen(view);
1619 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1620 err = view_resize(view->parent);
1621 if (!err)
1622 err = view_resize_split(view, 0);
1624 if (err)
1625 break;
1626 err = view->input(new, view, KEY_RESIZE);
1628 if (err)
1629 break;
1630 if (view->resize) {
1631 err = view->resize(view, 0);
1632 if (err)
1633 break;
1635 if (view->parent)
1636 err = offset_selection_down(view->parent);
1637 if (!err)
1638 err = offset_selection_down(view);
1639 break;
1640 case 'S':
1641 view->count = 0;
1642 err = switch_split(view);
1643 break;
1644 case '-':
1645 err = view_resize_split(view, -1);
1646 break;
1647 case '+':
1648 err = view_resize_split(view, 1);
1649 break;
1650 case KEY_RESIZE:
1651 break;
1652 case '/':
1653 view->count = 0;
1654 if (view->search_start)
1655 view_search_start(view);
1656 else
1657 err = view->input(new, view, ch);
1658 break;
1659 case 'N':
1660 case 'n':
1661 if (view->search_started && view->search_next) {
1662 view->searching = (ch == 'n' ?
1663 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1664 view->search_next_done = 0;
1665 view->search_next(view);
1666 } else
1667 err = view->input(new, view, ch);
1668 break;
1669 case 'A':
1670 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1671 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1672 else
1673 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1674 TAILQ_FOREACH(v, views, entry) {
1675 if (v->reset) {
1676 err = v->reset(v);
1677 if (err)
1678 return err;
1680 if (v->child && v->child->reset) {
1681 err = v->child->reset(v->child);
1682 if (err)
1683 return err;
1686 break;
1687 default:
1688 err = view->input(new, view, ch);
1689 break;
1692 return err;
1695 static int
1696 view_needs_focus_indication(struct tog_view *view)
1698 if (view_is_parent_view(view)) {
1699 if (view->child == NULL || view->child->focussed)
1700 return 0;
1701 if (!view_is_splitscreen(view->child))
1702 return 0;
1703 } else if (!view_is_splitscreen(view))
1704 return 0;
1706 return view->focussed;
1709 static const struct got_error *
1710 view_loop(struct tog_view *view)
1712 const struct got_error *err = NULL;
1713 struct tog_view_list_head views;
1714 struct tog_view *new_view;
1715 char *mode;
1716 int fast_refresh = 10;
1717 int done = 0, errcode;
1719 mode = getenv("TOG_VIEW_SPLIT_MODE");
1720 if (!mode || !(*mode == 'h' || *mode == 'H'))
1721 view->mode = TOG_VIEW_SPLIT_VERT;
1722 else
1723 view->mode = TOG_VIEW_SPLIT_HRZN;
1725 errcode = pthread_mutex_lock(&tog_mutex);
1726 if (errcode)
1727 return got_error_set_errno(errcode, "pthread_mutex_lock");
1729 TAILQ_INIT(&views);
1730 TAILQ_INSERT_HEAD(&views, view, entry);
1732 view->focussed = 1;
1733 err = view->show(view);
1734 if (err)
1735 return err;
1736 update_panels();
1737 doupdate();
1738 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1739 !tog_fatal_signal_received()) {
1740 /* Refresh fast during initialization, then become slower. */
1741 if (fast_refresh && fast_refresh-- == 0)
1742 halfdelay(10); /* switch to once per second */
1744 err = view_input(&new_view, &done, view, &views);
1745 if (err)
1746 break;
1747 if (view->dying) {
1748 struct tog_view *v, *prev = NULL;
1750 if (view_is_parent_view(view))
1751 prev = TAILQ_PREV(view, tog_view_list_head,
1752 entry);
1753 else if (view->parent)
1754 prev = view->parent;
1756 if (view->parent) {
1757 view->parent->child = NULL;
1758 view->parent->focus_child = 0;
1759 /* Restore fullscreen line height. */
1760 view->parent->nlines = view->parent->lines;
1761 err = view_resize(view->parent);
1762 if (err)
1763 break;
1764 /* Make resized splits persist. */
1765 view_transfer_size(view->parent, view);
1766 } else
1767 TAILQ_REMOVE(&views, view, entry);
1769 err = view_close(view);
1770 if (err)
1771 goto done;
1773 view = NULL;
1774 TAILQ_FOREACH(v, &views, entry) {
1775 if (v->focussed)
1776 break;
1778 if (view == NULL && new_view == NULL) {
1779 /* No view has focus. Try to pick one. */
1780 if (prev)
1781 view = prev;
1782 else if (!TAILQ_EMPTY(&views)) {
1783 view = TAILQ_LAST(&views,
1784 tog_view_list_head);
1786 if (view) {
1787 if (view->focus_child) {
1788 view->child->focussed = 1;
1789 view = view->child;
1790 } else
1791 view->focussed = 1;
1795 if (new_view) {
1796 struct tog_view *v, *t;
1797 /* Only allow one parent view per type. */
1798 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1799 if (v->type != new_view->type)
1800 continue;
1801 TAILQ_REMOVE(&views, v, entry);
1802 err = view_close(v);
1803 if (err)
1804 goto done;
1805 break;
1807 TAILQ_INSERT_TAIL(&views, new_view, entry);
1808 view = new_view;
1810 if (view) {
1811 if (view_is_parent_view(view)) {
1812 if (view->child && view->child->focussed)
1813 view = view->child;
1814 } else {
1815 if (view->parent && view->parent->focussed)
1816 view = view->parent;
1818 show_panel(view->panel);
1819 if (view->child && view_is_splitscreen(view->child))
1820 show_panel(view->child->panel);
1821 if (view->parent && view_is_splitscreen(view)) {
1822 err = view->parent->show(view->parent);
1823 if (err)
1824 goto done;
1826 err = view->show(view);
1827 if (err)
1828 goto done;
1829 if (view->child) {
1830 err = view->child->show(view->child);
1831 if (err)
1832 goto done;
1834 update_panels();
1835 doupdate();
1838 done:
1839 while (!TAILQ_EMPTY(&views)) {
1840 const struct got_error *close_err;
1841 view = TAILQ_FIRST(&views);
1842 TAILQ_REMOVE(&views, view, entry);
1843 close_err = view_close(view);
1844 if (close_err && err == NULL)
1845 err = close_err;
1848 errcode = pthread_mutex_unlock(&tog_mutex);
1849 if (errcode && err == NULL)
1850 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1852 return err;
1855 __dead static void
1856 usage_log(void)
1858 endwin();
1859 fprintf(stderr,
1860 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1861 getprogname());
1862 exit(1);
1865 /* Create newly allocated wide-character string equivalent to a byte string. */
1866 static const struct got_error *
1867 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1869 char *vis = NULL;
1870 const struct got_error *err = NULL;
1872 *ws = NULL;
1873 *wlen = mbstowcs(NULL, s, 0);
1874 if (*wlen == (size_t)-1) {
1875 int vislen;
1876 if (errno != EILSEQ)
1877 return got_error_from_errno("mbstowcs");
1879 /* byte string invalid in current encoding; try to "fix" it */
1880 err = got_mbsavis(&vis, &vislen, s);
1881 if (err)
1882 return err;
1883 *wlen = mbstowcs(NULL, vis, 0);
1884 if (*wlen == (size_t)-1) {
1885 err = got_error_from_errno("mbstowcs"); /* give up */
1886 goto done;
1890 *ws = calloc(*wlen + 1, sizeof(**ws));
1891 if (*ws == NULL) {
1892 err = got_error_from_errno("calloc");
1893 goto done;
1896 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1897 err = got_error_from_errno("mbstowcs");
1898 done:
1899 free(vis);
1900 if (err) {
1901 free(*ws);
1902 *ws = NULL;
1903 *wlen = 0;
1905 return err;
1908 static const struct got_error *
1909 expand_tab(char **ptr, const char *src)
1911 char *dst;
1912 size_t len, n, idx = 0, sz = 0;
1914 *ptr = NULL;
1915 n = len = strlen(src);
1916 dst = malloc(n + 1);
1917 if (dst == NULL)
1918 return got_error_from_errno("malloc");
1920 while (idx < len && src[idx]) {
1921 const char c = src[idx];
1923 if (c == '\t') {
1924 size_t nb = TABSIZE - sz % TABSIZE;
1925 char *p;
1927 p = realloc(dst, n + nb);
1928 if (p == NULL) {
1929 free(dst);
1930 return got_error_from_errno("realloc");
1933 dst = p;
1934 n += nb;
1935 memset(dst + sz, ' ', nb);
1936 sz += nb;
1937 } else
1938 dst[sz++] = src[idx];
1939 ++idx;
1942 dst[sz] = '\0';
1943 *ptr = dst;
1944 return NULL;
1948 * Advance at most n columns from wline starting at offset off.
1949 * Return the index to the first character after the span operation.
1950 * Return the combined column width of all spanned wide character in
1951 * *rcol.
1953 static int
1954 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1956 int width, i, cols = 0;
1958 if (n == 0) {
1959 *rcol = cols;
1960 return off;
1963 for (i = off; wline[i] != L'\0'; ++i) {
1964 if (wline[i] == L'\t')
1965 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1966 else
1967 width = wcwidth(wline[i]);
1969 if (width == -1) {
1970 width = 1;
1971 wline[i] = L'.';
1974 if (cols + width > n)
1975 break;
1976 cols += width;
1979 *rcol = cols;
1980 return i;
1984 * Format a line for display, ensuring that it won't overflow a width limit.
1985 * With scrolling, the width returned refers to the scrolled version of the
1986 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1988 static const struct got_error *
1989 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1990 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1992 const struct got_error *err = NULL;
1993 int cols;
1994 wchar_t *wline = NULL;
1995 char *exstr = NULL;
1996 size_t wlen;
1997 int i, scrollx;
1999 *wlinep = NULL;
2000 *widthp = 0;
2002 if (expand) {
2003 err = expand_tab(&exstr, line);
2004 if (err)
2005 return err;
2008 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2009 free(exstr);
2010 if (err)
2011 return err;
2013 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2015 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2016 wline[wlen - 1] = L'\0';
2017 wlen--;
2019 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2020 wline[wlen - 1] = L'\0';
2021 wlen--;
2024 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2025 wline[i] = L'\0';
2027 if (widthp)
2028 *widthp = cols;
2029 if (scrollxp)
2030 *scrollxp = scrollx;
2031 if (err)
2032 free(wline);
2033 else
2034 *wlinep = wline;
2035 return err;
2038 static const struct got_error*
2039 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2040 struct got_object_id *id, struct got_repository *repo)
2042 static const struct got_error *err = NULL;
2043 struct got_reflist_entry *re;
2044 char *s;
2045 const char *name;
2047 *refs_str = NULL;
2049 TAILQ_FOREACH(re, refs, entry) {
2050 struct got_tag_object *tag = NULL;
2051 struct got_object_id *ref_id;
2052 int cmp;
2054 name = got_ref_get_name(re->ref);
2055 if (strcmp(name, GOT_REF_HEAD) == 0)
2056 continue;
2057 if (strncmp(name, "refs/", 5) == 0)
2058 name += 5;
2059 if (strncmp(name, "got/", 4) == 0 &&
2060 strncmp(name, "got/backup/", 11) != 0)
2061 continue;
2062 if (strncmp(name, "heads/", 6) == 0)
2063 name += 6;
2064 if (strncmp(name, "remotes/", 8) == 0) {
2065 name += 8;
2066 s = strstr(name, "/" GOT_REF_HEAD);
2067 if (s != NULL && s[strlen(s)] == '\0')
2068 continue;
2070 err = got_ref_resolve(&ref_id, repo, re->ref);
2071 if (err)
2072 break;
2073 if (strncmp(name, "tags/", 5) == 0) {
2074 err = got_object_open_as_tag(&tag, repo, ref_id);
2075 if (err) {
2076 if (err->code != GOT_ERR_OBJ_TYPE) {
2077 free(ref_id);
2078 break;
2080 /* Ref points at something other than a tag. */
2081 err = NULL;
2082 tag = NULL;
2085 cmp = got_object_id_cmp(tag ?
2086 got_object_tag_get_object_id(tag) : ref_id, id);
2087 free(ref_id);
2088 if (tag)
2089 got_object_tag_close(tag);
2090 if (cmp != 0)
2091 continue;
2092 s = *refs_str;
2093 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2094 s ? ", " : "", name) == -1) {
2095 err = got_error_from_errno("asprintf");
2096 free(s);
2097 *refs_str = NULL;
2098 break;
2100 free(s);
2103 return err;
2106 static const struct got_error *
2107 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2108 int col_tab_align)
2110 char *smallerthan;
2112 smallerthan = strchr(author, '<');
2113 if (smallerthan && smallerthan[1] != '\0')
2114 author = smallerthan + 1;
2115 author[strcspn(author, "@>")] = '\0';
2116 return format_line(wauthor, author_width, NULL, author, 0, limit,
2117 col_tab_align, 0);
2120 static const struct got_error *
2121 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2122 struct got_object_id *id, const size_t date_display_cols,
2123 int author_display_cols)
2125 struct tog_log_view_state *s = &view->state.log;
2126 const struct got_error *err = NULL;
2127 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2128 char *logmsg0 = NULL, *logmsg = NULL;
2129 char *author = NULL;
2130 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2131 int author_width, logmsg_width;
2132 char *newline, *line = NULL;
2133 int col, limit, scrollx;
2134 const int avail = view->ncols;
2135 struct tm tm;
2136 time_t committer_time;
2137 struct tog_color *tc;
2139 committer_time = got_object_commit_get_committer_time(commit);
2140 if (gmtime_r(&committer_time, &tm) == NULL)
2141 return got_error_from_errno("gmtime_r");
2142 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2143 return got_error(GOT_ERR_NO_SPACE);
2145 if (avail <= date_display_cols)
2146 limit = MIN(sizeof(datebuf) - 1, avail);
2147 else
2148 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2149 tc = get_color(&s->colors, TOG_COLOR_DATE);
2150 if (tc)
2151 wattr_on(view->window,
2152 COLOR_PAIR(tc->colorpair), NULL);
2153 waddnstr(view->window, datebuf, limit);
2154 if (tc)
2155 wattr_off(view->window,
2156 COLOR_PAIR(tc->colorpair), NULL);
2157 col = limit;
2158 if (col > avail)
2159 goto done;
2161 if (avail >= 120) {
2162 char *id_str;
2163 err = got_object_id_str(&id_str, id);
2164 if (err)
2165 goto done;
2166 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2167 if (tc)
2168 wattr_on(view->window,
2169 COLOR_PAIR(tc->colorpair), NULL);
2170 wprintw(view->window, "%.8s ", id_str);
2171 if (tc)
2172 wattr_off(view->window,
2173 COLOR_PAIR(tc->colorpair), NULL);
2174 free(id_str);
2175 col += 9;
2176 if (col > avail)
2177 goto done;
2180 if (s->use_committer)
2181 author = strdup(got_object_commit_get_committer(commit));
2182 else
2183 author = strdup(got_object_commit_get_author(commit));
2184 if (author == NULL) {
2185 err = got_error_from_errno("strdup");
2186 goto done;
2188 err = format_author(&wauthor, &author_width, author, avail - col, col);
2189 if (err)
2190 goto done;
2191 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2192 if (tc)
2193 wattr_on(view->window,
2194 COLOR_PAIR(tc->colorpair), NULL);
2195 waddwstr(view->window, wauthor);
2196 col += author_width;
2197 while (col < avail && author_width < author_display_cols + 2) {
2198 waddch(view->window, ' ');
2199 col++;
2200 author_width++;
2202 if (tc)
2203 wattr_off(view->window,
2204 COLOR_PAIR(tc->colorpair), NULL);
2205 if (col > avail)
2206 goto done;
2208 err = got_object_commit_get_logmsg(&logmsg0, commit);
2209 if (err)
2210 goto done;
2211 logmsg = logmsg0;
2212 while (*logmsg == '\n')
2213 logmsg++;
2214 newline = strchr(logmsg, '\n');
2215 if (newline)
2216 *newline = '\0';
2217 limit = avail - col;
2218 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2219 limit--; /* for the border */
2220 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2221 limit, col, 1);
2222 if (err)
2223 goto done;
2224 waddwstr(view->window, &wlogmsg[scrollx]);
2225 col += MAX(logmsg_width, 0);
2226 while (col < avail) {
2227 waddch(view->window, ' ');
2228 col++;
2230 done:
2231 free(logmsg0);
2232 free(wlogmsg);
2233 free(author);
2234 free(wauthor);
2235 free(line);
2236 return err;
2239 static struct commit_queue_entry *
2240 alloc_commit_queue_entry(struct got_commit_object *commit,
2241 struct got_object_id *id)
2243 struct commit_queue_entry *entry;
2244 struct got_object_id *dup;
2246 entry = calloc(1, sizeof(*entry));
2247 if (entry == NULL)
2248 return NULL;
2250 dup = got_object_id_dup(id);
2251 if (dup == NULL) {
2252 free(entry);
2253 return NULL;
2256 entry->id = dup;
2257 entry->commit = commit;
2258 return entry;
2261 static void
2262 pop_commit(struct commit_queue *commits)
2264 struct commit_queue_entry *entry;
2266 entry = TAILQ_FIRST(&commits->head);
2267 TAILQ_REMOVE(&commits->head, entry, entry);
2268 got_object_commit_close(entry->commit);
2269 commits->ncommits--;
2270 free(entry->id);
2271 free(entry);
2274 static void
2275 free_commits(struct commit_queue *commits)
2277 while (!TAILQ_EMPTY(&commits->head))
2278 pop_commit(commits);
2281 static const struct got_error *
2282 match_commit(int *have_match, struct got_object_id *id,
2283 struct got_commit_object *commit, regex_t *regex)
2285 const struct got_error *err = NULL;
2286 regmatch_t regmatch;
2287 char *id_str = NULL, *logmsg = NULL;
2289 *have_match = 0;
2291 err = got_object_id_str(&id_str, id);
2292 if (err)
2293 return err;
2295 err = got_object_commit_get_logmsg(&logmsg, commit);
2296 if (err)
2297 goto done;
2299 if (regexec(regex, got_object_commit_get_author(commit), 1,
2300 &regmatch, 0) == 0 ||
2301 regexec(regex, got_object_commit_get_committer(commit), 1,
2302 &regmatch, 0) == 0 ||
2303 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2304 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2305 *have_match = 1;
2306 done:
2307 free(id_str);
2308 free(logmsg);
2309 return err;
2312 static const struct got_error *
2313 queue_commits(struct tog_log_thread_args *a)
2315 const struct got_error *err = NULL;
2318 * We keep all commits open throughout the lifetime of the log
2319 * view in order to avoid having to re-fetch commits from disk
2320 * while updating the display.
2322 do {
2323 struct got_object_id id;
2324 struct got_commit_object *commit;
2325 struct commit_queue_entry *entry;
2326 int limit_match = 0;
2327 int errcode;
2329 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2330 NULL, NULL);
2331 if (err)
2332 break;
2334 err = got_object_open_as_commit(&commit, a->repo, &id);
2335 if (err)
2336 break;
2337 entry = alloc_commit_queue_entry(commit, &id);
2338 if (entry == NULL) {
2339 err = got_error_from_errno("alloc_commit_queue_entry");
2340 break;
2343 errcode = pthread_mutex_lock(&tog_mutex);
2344 if (errcode) {
2345 err = got_error_set_errno(errcode,
2346 "pthread_mutex_lock");
2347 break;
2350 entry->idx = a->real_commits->ncommits;
2351 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2352 a->real_commits->ncommits++;
2354 if (*a->limiting) {
2355 err = match_commit(&limit_match, &id, commit,
2356 a->limit_regex);
2357 if (err)
2358 break;
2360 if (limit_match) {
2361 struct commit_queue_entry *matched;
2363 matched = alloc_commit_queue_entry(
2364 entry->commit, entry->id);
2365 if (matched == NULL) {
2366 err = got_error_from_errno(
2367 "alloc_commit_queue_entry");
2368 break;
2370 matched->commit = entry->commit;
2371 got_object_commit_retain(entry->commit);
2373 matched->idx = a->limit_commits->ncommits;
2374 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2375 matched, entry);
2376 a->limit_commits->ncommits++;
2380 * This is how we signal log_thread() that we
2381 * have found a match, and that it should be
2382 * counted as a new entry for the view.
2384 a->limit_match = limit_match;
2387 if (*a->searching == TOG_SEARCH_FORWARD &&
2388 !*a->search_next_done) {
2389 int have_match;
2390 err = match_commit(&have_match, &id, commit, a->regex);
2391 if (err)
2392 break;
2394 if (*a->limiting) {
2395 if (limit_match && have_match)
2396 *a->search_next_done =
2397 TOG_SEARCH_HAVE_MORE;
2398 } else if (have_match)
2399 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2402 errcode = pthread_mutex_unlock(&tog_mutex);
2403 if (errcode && err == NULL)
2404 err = got_error_set_errno(errcode,
2405 "pthread_mutex_unlock");
2406 if (err)
2407 break;
2408 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2410 return err;
2413 static void
2414 select_commit(struct tog_log_view_state *s)
2416 struct commit_queue_entry *entry;
2417 int ncommits = 0;
2419 entry = s->first_displayed_entry;
2420 while (entry) {
2421 if (ncommits == s->selected) {
2422 s->selected_entry = entry;
2423 break;
2425 entry = TAILQ_NEXT(entry, entry);
2426 ncommits++;
2430 static const struct got_error *
2431 draw_commits(struct tog_view *view)
2433 const struct got_error *err = NULL;
2434 struct tog_log_view_state *s = &view->state.log;
2435 struct commit_queue_entry *entry = s->selected_entry;
2436 int limit = view->nlines;
2437 int width;
2438 int ncommits, author_cols = 4;
2439 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2440 char *refs_str = NULL;
2441 wchar_t *wline;
2442 struct tog_color *tc;
2443 static const size_t date_display_cols = 12;
2445 if (view_is_hsplit_top(view))
2446 --limit; /* account for border */
2448 if (s->selected_entry &&
2449 !(view->searching && view->search_next_done == 0)) {
2450 struct got_reflist_head *refs;
2451 err = got_object_id_str(&id_str, s->selected_entry->id);
2452 if (err)
2453 return err;
2454 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2455 s->selected_entry->id);
2456 if (refs) {
2457 err = build_refs_str(&refs_str, refs,
2458 s->selected_entry->id, s->repo);
2459 if (err)
2460 goto done;
2464 if (s->thread_args.commits_needed == 0)
2465 halfdelay(10); /* disable fast refresh */
2467 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2468 if (asprintf(&ncommits_str, " [%d/%d] %s",
2469 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2470 (view->searching && !view->search_next_done) ?
2471 "searching..." : "loading...") == -1) {
2472 err = got_error_from_errno("asprintf");
2473 goto done;
2475 } else {
2476 const char *search_str = NULL;
2477 const char *limit_str = NULL;
2479 if (view->searching) {
2480 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2481 search_str = "no more matches";
2482 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2483 search_str = "no matches found";
2484 else if (!view->search_next_done)
2485 search_str = "searching...";
2488 if (s->limit_view && s->commits->ncommits == 0)
2489 limit_str = "no matches found";
2491 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2492 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2493 search_str ? search_str : (refs_str ? refs_str : ""),
2494 limit_str ? limit_str : "") == -1) {
2495 err = got_error_from_errno("asprintf");
2496 goto done;
2500 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2501 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2502 "........................................",
2503 s->in_repo_path, ncommits_str) == -1) {
2504 err = got_error_from_errno("asprintf");
2505 header = NULL;
2506 goto done;
2508 } else if (asprintf(&header, "commit %s%s",
2509 id_str ? id_str : "........................................",
2510 ncommits_str) == -1) {
2511 err = got_error_from_errno("asprintf");
2512 header = NULL;
2513 goto done;
2515 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2516 if (err)
2517 goto done;
2519 werase(view->window);
2521 if (view_needs_focus_indication(view))
2522 wstandout(view->window);
2523 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2524 if (tc)
2525 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2526 waddwstr(view->window, wline);
2527 while (width < view->ncols) {
2528 waddch(view->window, ' ');
2529 width++;
2531 if (tc)
2532 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2533 if (view_needs_focus_indication(view))
2534 wstandend(view->window);
2535 free(wline);
2536 if (limit <= 1)
2537 goto done;
2539 /* Grow author column size if necessary, and set view->maxx. */
2540 entry = s->first_displayed_entry;
2541 ncommits = 0;
2542 view->maxx = 0;
2543 while (entry) {
2544 struct got_commit_object *c = entry->commit;
2545 char *author, *eol, *msg, *msg0;
2546 wchar_t *wauthor, *wmsg;
2547 int width;
2548 if (ncommits >= limit - 1)
2549 break;
2550 if (s->use_committer)
2551 author = strdup(got_object_commit_get_committer(c));
2552 else
2553 author = strdup(got_object_commit_get_author(c));
2554 if (author == NULL) {
2555 err = got_error_from_errno("strdup");
2556 goto done;
2558 err = format_author(&wauthor, &width, author, COLS,
2559 date_display_cols);
2560 if (author_cols < width)
2561 author_cols = width;
2562 free(wauthor);
2563 free(author);
2564 if (err)
2565 goto done;
2566 err = got_object_commit_get_logmsg(&msg0, c);
2567 if (err)
2568 goto done;
2569 msg = msg0;
2570 while (*msg == '\n')
2571 ++msg;
2572 if ((eol = strchr(msg, '\n')))
2573 *eol = '\0';
2574 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2575 date_display_cols + author_cols, 0);
2576 if (err)
2577 goto done;
2578 view->maxx = MAX(view->maxx, width);
2579 free(msg0);
2580 free(wmsg);
2581 ncommits++;
2582 entry = TAILQ_NEXT(entry, entry);
2585 entry = s->first_displayed_entry;
2586 s->last_displayed_entry = s->first_displayed_entry;
2587 ncommits = 0;
2588 while (entry) {
2589 if (ncommits >= limit - 1)
2590 break;
2591 if (ncommits == s->selected)
2592 wstandout(view->window);
2593 err = draw_commit(view, entry->commit, entry->id,
2594 date_display_cols, author_cols);
2595 if (ncommits == s->selected)
2596 wstandend(view->window);
2597 if (err)
2598 goto done;
2599 ncommits++;
2600 s->last_displayed_entry = entry;
2601 entry = TAILQ_NEXT(entry, entry);
2604 view_border(view);
2605 done:
2606 free(id_str);
2607 free(refs_str);
2608 free(ncommits_str);
2609 free(header);
2610 return err;
2613 static void
2614 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2616 struct commit_queue_entry *entry;
2617 int nscrolled = 0;
2619 entry = TAILQ_FIRST(&s->commits->head);
2620 if (s->first_displayed_entry == entry)
2621 return;
2623 entry = s->first_displayed_entry;
2624 while (entry && nscrolled < maxscroll) {
2625 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2626 if (entry) {
2627 s->first_displayed_entry = entry;
2628 nscrolled++;
2633 static const struct got_error *
2634 trigger_log_thread(struct tog_view *view, int wait)
2636 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2637 int errcode;
2639 halfdelay(1); /* fast refresh while loading commits */
2641 while (!ta->log_complete && !tog_thread_error &&
2642 (ta->commits_needed > 0 || ta->load_all)) {
2643 /* Wake the log thread. */
2644 errcode = pthread_cond_signal(&ta->need_commits);
2645 if (errcode)
2646 return got_error_set_errno(errcode,
2647 "pthread_cond_signal");
2650 * The mutex will be released while the view loop waits
2651 * in wgetch(), at which time the log thread will run.
2653 if (!wait)
2654 break;
2656 /* Display progress update in log view. */
2657 show_log_view(view);
2658 update_panels();
2659 doupdate();
2661 /* Wait right here while next commit is being loaded. */
2662 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2663 if (errcode)
2664 return got_error_set_errno(errcode,
2665 "pthread_cond_wait");
2667 /* Display progress update in log view. */
2668 show_log_view(view);
2669 update_panels();
2670 doupdate();
2673 return NULL;
2676 static const struct got_error *
2677 request_log_commits(struct tog_view *view)
2679 struct tog_log_view_state *state = &view->state.log;
2680 const struct got_error *err = NULL;
2682 if (state->thread_args.log_complete)
2683 return NULL;
2685 state->thread_args.commits_needed += view->nscrolled;
2686 err = trigger_log_thread(view, 1);
2687 view->nscrolled = 0;
2689 return err;
2692 static const struct got_error *
2693 log_scroll_down(struct tog_view *view, int maxscroll)
2695 struct tog_log_view_state *s = &view->state.log;
2696 const struct got_error *err = NULL;
2697 struct commit_queue_entry *pentry;
2698 int nscrolled = 0, ncommits_needed;
2700 if (s->last_displayed_entry == NULL)
2701 return NULL;
2703 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2704 if (s->commits->ncommits < ncommits_needed &&
2705 !s->thread_args.log_complete) {
2707 * Ask the log thread for required amount of commits.
2709 s->thread_args.commits_needed +=
2710 ncommits_needed - s->commits->ncommits;
2711 err = trigger_log_thread(view, 1);
2712 if (err)
2713 return err;
2716 do {
2717 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2718 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2719 break;
2721 s->last_displayed_entry = pentry ?
2722 pentry : s->last_displayed_entry;;
2724 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2725 if (pentry == NULL)
2726 break;
2727 s->first_displayed_entry = pentry;
2728 } while (++nscrolled < maxscroll);
2730 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2731 view->nscrolled += nscrolled;
2732 else
2733 view->nscrolled = 0;
2735 return err;
2738 static const struct got_error *
2739 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2740 struct got_commit_object *commit, struct got_object_id *commit_id,
2741 struct tog_view *log_view, struct got_repository *repo)
2743 const struct got_error *err;
2744 struct got_object_qid *parent_id;
2745 struct tog_view *diff_view;
2747 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2748 if (diff_view == NULL)
2749 return got_error_from_errno("view_open");
2751 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2752 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2753 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2754 if (err == NULL)
2755 *new_view = diff_view;
2756 return err;
2759 static const struct got_error *
2760 tree_view_visit_subtree(struct tog_tree_view_state *s,
2761 struct got_tree_object *subtree)
2763 struct tog_parent_tree *parent;
2765 parent = calloc(1, sizeof(*parent));
2766 if (parent == NULL)
2767 return got_error_from_errno("calloc");
2769 parent->tree = s->tree;
2770 parent->first_displayed_entry = s->first_displayed_entry;
2771 parent->selected_entry = s->selected_entry;
2772 parent->selected = s->selected;
2773 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2774 s->tree = subtree;
2775 s->selected = 0;
2776 s->first_displayed_entry = NULL;
2777 return NULL;
2780 static const struct got_error *
2781 tree_view_walk_path(struct tog_tree_view_state *s,
2782 struct got_commit_object *commit, const char *path)
2784 const struct got_error *err = NULL;
2785 struct got_tree_object *tree = NULL;
2786 const char *p;
2787 char *slash, *subpath = NULL;
2789 /* Walk the path and open corresponding tree objects. */
2790 p = path;
2791 while (*p) {
2792 struct got_tree_entry *te;
2793 struct got_object_id *tree_id;
2794 char *te_name;
2796 while (p[0] == '/')
2797 p++;
2799 /* Ensure the correct subtree entry is selected. */
2800 slash = strchr(p, '/');
2801 if (slash == NULL)
2802 te_name = strdup(p);
2803 else
2804 te_name = strndup(p, slash - p);
2805 if (te_name == NULL) {
2806 err = got_error_from_errno("strndup");
2807 break;
2809 te = got_object_tree_find_entry(s->tree, te_name);
2810 if (te == NULL) {
2811 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2812 free(te_name);
2813 break;
2815 free(te_name);
2816 s->first_displayed_entry = s->selected_entry = te;
2818 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2819 break; /* jump to this file's entry */
2821 slash = strchr(p, '/');
2822 if (slash)
2823 subpath = strndup(path, slash - path);
2824 else
2825 subpath = strdup(path);
2826 if (subpath == NULL) {
2827 err = got_error_from_errno("strdup");
2828 break;
2831 err = got_object_id_by_path(&tree_id, s->repo, commit,
2832 subpath);
2833 if (err)
2834 break;
2836 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2837 free(tree_id);
2838 if (err)
2839 break;
2841 err = tree_view_visit_subtree(s, tree);
2842 if (err) {
2843 got_object_tree_close(tree);
2844 break;
2846 if (slash == NULL)
2847 break;
2848 free(subpath);
2849 subpath = NULL;
2850 p = slash;
2853 free(subpath);
2854 return err;
2857 static const struct got_error *
2858 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2859 struct commit_queue_entry *entry, const char *path,
2860 const char *head_ref_name, struct got_repository *repo)
2862 const struct got_error *err = NULL;
2863 struct tog_tree_view_state *s;
2864 struct tog_view *tree_view;
2866 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2867 if (tree_view == NULL)
2868 return got_error_from_errno("view_open");
2870 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2871 if (err)
2872 return err;
2873 s = &tree_view->state.tree;
2875 *new_view = tree_view;
2877 if (got_path_is_root_dir(path))
2878 return NULL;
2880 return tree_view_walk_path(s, entry->commit, path);
2883 static const struct got_error *
2884 block_signals_used_by_main_thread(void)
2886 sigset_t sigset;
2887 int errcode;
2889 if (sigemptyset(&sigset) == -1)
2890 return got_error_from_errno("sigemptyset");
2892 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2893 if (sigaddset(&sigset, SIGWINCH) == -1)
2894 return got_error_from_errno("sigaddset");
2895 if (sigaddset(&sigset, SIGCONT) == -1)
2896 return got_error_from_errno("sigaddset");
2897 if (sigaddset(&sigset, SIGINT) == -1)
2898 return got_error_from_errno("sigaddset");
2899 if (sigaddset(&sigset, SIGTERM) == -1)
2900 return got_error_from_errno("sigaddset");
2902 /* ncurses handles SIGTSTP */
2903 if (sigaddset(&sigset, SIGTSTP) == -1)
2904 return got_error_from_errno("sigaddset");
2906 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2907 if (errcode)
2908 return got_error_set_errno(errcode, "pthread_sigmask");
2910 return NULL;
2913 static void *
2914 log_thread(void *arg)
2916 const struct got_error *err = NULL;
2917 int errcode = 0;
2918 struct tog_log_thread_args *a = arg;
2919 int done = 0;
2922 * Sync startup with main thread such that we begin our
2923 * work once view_input() has released the mutex.
2925 errcode = pthread_mutex_lock(&tog_mutex);
2926 if (errcode) {
2927 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2928 return (void *)err;
2931 err = block_signals_used_by_main_thread();
2932 if (err) {
2933 pthread_mutex_unlock(&tog_mutex);
2934 goto done;
2937 while (!done && !err && !tog_fatal_signal_received()) {
2938 errcode = pthread_mutex_unlock(&tog_mutex);
2939 if (errcode) {
2940 err = got_error_set_errno(errcode,
2941 "pthread_mutex_unlock");
2942 goto done;
2944 err = queue_commits(a);
2945 if (err) {
2946 if (err->code != GOT_ERR_ITER_COMPLETED)
2947 goto done;
2948 err = NULL;
2949 done = 1;
2950 } else if (a->commits_needed > 0 && !a->load_all) {
2951 if (*a->limiting) {
2952 if (a->limit_match)
2953 a->commits_needed--;
2954 } else
2955 a->commits_needed--;
2958 errcode = pthread_mutex_lock(&tog_mutex);
2959 if (errcode) {
2960 err = got_error_set_errno(errcode,
2961 "pthread_mutex_lock");
2962 goto done;
2963 } else if (*a->quit)
2964 done = 1;
2965 else if (*a->limiting && *a->first_displayed_entry == NULL) {
2966 *a->first_displayed_entry =
2967 TAILQ_FIRST(&a->limit_commits->head);
2968 *a->selected_entry = *a->first_displayed_entry;
2969 } else if (*a->first_displayed_entry == NULL) {
2970 *a->first_displayed_entry =
2971 TAILQ_FIRST(&a->real_commits->head);
2972 *a->selected_entry = *a->first_displayed_entry;
2975 errcode = pthread_cond_signal(&a->commit_loaded);
2976 if (errcode) {
2977 err = got_error_set_errno(errcode,
2978 "pthread_cond_signal");
2979 pthread_mutex_unlock(&tog_mutex);
2980 goto done;
2983 if (done)
2984 a->commits_needed = 0;
2985 else {
2986 if (a->commits_needed == 0 && !a->load_all) {
2987 errcode = pthread_cond_wait(&a->need_commits,
2988 &tog_mutex);
2989 if (errcode) {
2990 err = got_error_set_errno(errcode,
2991 "pthread_cond_wait");
2992 pthread_mutex_unlock(&tog_mutex);
2993 goto done;
2995 if (*a->quit)
2996 done = 1;
3000 a->log_complete = 1;
3001 errcode = pthread_mutex_unlock(&tog_mutex);
3002 if (errcode)
3003 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3004 done:
3005 if (err) {
3006 tog_thread_error = 1;
3007 pthread_cond_signal(&a->commit_loaded);
3009 return (void *)err;
3012 static const struct got_error *
3013 stop_log_thread(struct tog_log_view_state *s)
3015 const struct got_error *err = NULL, *thread_err = NULL;
3016 int errcode;
3018 if (s->thread) {
3019 s->quit = 1;
3020 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3021 if (errcode)
3022 return got_error_set_errno(errcode,
3023 "pthread_cond_signal");
3024 errcode = pthread_mutex_unlock(&tog_mutex);
3025 if (errcode)
3026 return got_error_set_errno(errcode,
3027 "pthread_mutex_unlock");
3028 errcode = pthread_join(s->thread, (void **)&thread_err);
3029 if (errcode)
3030 return got_error_set_errno(errcode, "pthread_join");
3031 errcode = pthread_mutex_lock(&tog_mutex);
3032 if (errcode)
3033 return got_error_set_errno(errcode,
3034 "pthread_mutex_lock");
3035 s->thread = 0; //NULL;
3038 if (s->thread_args.repo) {
3039 err = got_repo_close(s->thread_args.repo);
3040 s->thread_args.repo = NULL;
3043 if (s->thread_args.pack_fds) {
3044 const struct got_error *pack_err =
3045 got_repo_pack_fds_close(s->thread_args.pack_fds);
3046 if (err == NULL)
3047 err = pack_err;
3048 s->thread_args.pack_fds = NULL;
3051 if (s->thread_args.graph) {
3052 got_commit_graph_close(s->thread_args.graph);
3053 s->thread_args.graph = NULL;
3056 return err ? err : thread_err;
3059 static const struct got_error *
3060 close_log_view(struct tog_view *view)
3062 const struct got_error *err = NULL;
3063 struct tog_log_view_state *s = &view->state.log;
3064 int errcode;
3066 err = stop_log_thread(s);
3068 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3069 if (errcode && err == NULL)
3070 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3072 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3073 if (errcode && err == NULL)
3074 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3076 free_commits(&s->limit_commits);
3077 free_commits(&s->real_commits);
3078 free(s->in_repo_path);
3079 s->in_repo_path = NULL;
3080 free(s->start_id);
3081 s->start_id = NULL;
3082 free(s->head_ref_name);
3083 s->head_ref_name = NULL;
3084 return err;
3088 * We use two queues to implement the limit feature: first consists of
3089 * commits matching the current limit_regex; second is the real queue
3090 * of all known commits (real_commits). When the user starts limiting,
3091 * we swap queues such that all movement and displaying functionality
3092 * works with very slight change.
3094 static const struct got_error *
3095 limit_log_view(struct tog_view *view)
3097 struct tog_log_view_state *s = &view->state.log;
3098 struct commit_queue_entry *entry;
3099 struct tog_view *v = view;
3100 const struct got_error *err = NULL;
3101 char pattern[1024];
3102 int ret;
3104 if (view_is_hsplit_top(view))
3105 v = view->child;
3106 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3107 v = view->parent;
3109 /* Get the pattern */
3110 wmove(v->window, v->nlines - 1, 0);
3111 wclrtoeol(v->window);
3112 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3113 nodelay(v->window, FALSE);
3114 nocbreak();
3115 echo();
3116 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3117 cbreak();
3118 noecho();
3119 nodelay(v->window, TRUE);
3120 if (ret == ERR)
3121 return NULL;
3123 if (*pattern == '\0') {
3125 * Safety measure for the situation where the user
3126 * resets limit without previously limiting anything.
3128 if (!s->limit_view)
3129 return NULL;
3132 * User could have pressed Ctrl+L, which refreshed the
3133 * commit queues, it means we can't save previously
3134 * (before limit took place) displayed entries,
3135 * because they would point to already free'ed memory,
3136 * so we are forced to always select first entry of
3137 * the queue.
3139 s->commits = &s->real_commits;
3140 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3141 s->selected_entry = s->first_displayed_entry;
3142 s->selected = 0;
3143 s->limit_view = 0;
3145 return NULL;
3148 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3149 return NULL;
3151 s->limit_view = 1;
3153 /* Clear the screen while loading limit view */
3154 s->first_displayed_entry = NULL;
3155 s->last_displayed_entry = NULL;
3156 s->selected_entry = NULL;
3157 s->commits = &s->limit_commits;
3159 /* Prepare limit queue for new search */
3160 free_commits(&s->limit_commits);
3161 s->limit_commits.ncommits = 0;
3163 /* First process commits, which are in queue already */
3164 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3165 int have_match = 0;
3167 err = match_commit(&have_match, entry->id,
3168 entry->commit, &s->limit_regex);
3169 if (err)
3170 return err;
3172 if (have_match) {
3173 struct commit_queue_entry *matched;
3175 matched = alloc_commit_queue_entry(entry->commit,
3176 entry->id);
3177 if (matched == NULL) {
3178 err = got_error_from_errno(
3179 "alloc_commit_queue_entry");
3180 break;
3182 matched->commit = entry->commit;
3183 got_object_commit_retain(entry->commit);
3185 matched->idx = s->limit_commits.ncommits;
3186 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3187 matched, entry);
3188 s->limit_commits.ncommits++;
3192 /* Second process all the commits, until we fill the screen */
3193 if (s->limit_commits.ncommits < view->nlines - 1 &&
3194 !s->thread_args.log_complete) {
3195 s->thread_args.commits_needed +=
3196 view->nlines - s->limit_commits.ncommits - 1;
3197 err = trigger_log_thread(view, 1);
3198 if (err)
3199 return err;
3202 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3203 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3204 s->selected = 0;
3206 return NULL;
3209 static const struct got_error *
3210 search_start_log_view(struct tog_view *view)
3212 struct tog_log_view_state *s = &view->state.log;
3214 s->matched_entry = NULL;
3215 s->search_entry = NULL;
3216 return NULL;
3219 static const struct got_error *
3220 search_next_log_view(struct tog_view *view)
3222 const struct got_error *err = NULL;
3223 struct tog_log_view_state *s = &view->state.log;
3224 struct commit_queue_entry *entry;
3226 /* Display progress update in log view. */
3227 show_log_view(view);
3228 update_panels();
3229 doupdate();
3231 if (s->search_entry) {
3232 int errcode, ch;
3233 errcode = pthread_mutex_unlock(&tog_mutex);
3234 if (errcode)
3235 return got_error_set_errno(errcode,
3236 "pthread_mutex_unlock");
3237 ch = wgetch(view->window);
3238 errcode = pthread_mutex_lock(&tog_mutex);
3239 if (errcode)
3240 return got_error_set_errno(errcode,
3241 "pthread_mutex_lock");
3242 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3243 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3244 return NULL;
3246 if (view->searching == TOG_SEARCH_FORWARD)
3247 entry = TAILQ_NEXT(s->search_entry, entry);
3248 else
3249 entry = TAILQ_PREV(s->search_entry,
3250 commit_queue_head, entry);
3251 } else if (s->matched_entry) {
3253 * If the user has moved the cursor after we hit a match,
3254 * the position from where we should continue searching
3255 * might have changed.
3257 if (view->searching == TOG_SEARCH_FORWARD)
3258 entry = TAILQ_NEXT(s->selected_entry, entry);
3259 else
3260 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3261 entry);
3262 } else {
3263 entry = s->selected_entry;
3266 while (1) {
3267 int have_match = 0;
3269 if (entry == NULL) {
3270 if (s->thread_args.log_complete ||
3271 view->searching == TOG_SEARCH_BACKWARD) {
3272 view->search_next_done =
3273 (s->matched_entry == NULL ?
3274 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3275 s->search_entry = NULL;
3276 return NULL;
3279 * Poke the log thread for more commits and return,
3280 * allowing the main loop to make progress. Search
3281 * will resume at s->search_entry once we come back.
3283 s->thread_args.commits_needed++;
3284 return trigger_log_thread(view, 0);
3287 err = match_commit(&have_match, entry->id, entry->commit,
3288 &view->regex);
3289 if (err)
3290 break;
3291 if (have_match) {
3292 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3293 s->matched_entry = entry;
3294 break;
3297 s->search_entry = entry;
3298 if (view->searching == TOG_SEARCH_FORWARD)
3299 entry = TAILQ_NEXT(entry, entry);
3300 else
3301 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3304 if (s->matched_entry) {
3305 int cur = s->selected_entry->idx;
3306 while (cur < s->matched_entry->idx) {
3307 err = input_log_view(NULL, view, KEY_DOWN);
3308 if (err)
3309 return err;
3310 cur++;
3312 while (cur > s->matched_entry->idx) {
3313 err = input_log_view(NULL, view, KEY_UP);
3314 if (err)
3315 return err;
3316 cur--;
3320 s->search_entry = NULL;
3322 return NULL;
3325 static const struct got_error *
3326 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3327 struct got_repository *repo, const char *head_ref_name,
3328 const char *in_repo_path, int log_branches)
3330 const struct got_error *err = NULL;
3331 struct tog_log_view_state *s = &view->state.log;
3332 struct got_repository *thread_repo = NULL;
3333 struct got_commit_graph *thread_graph = NULL;
3334 int errcode;
3336 if (in_repo_path != s->in_repo_path) {
3337 free(s->in_repo_path);
3338 s->in_repo_path = strdup(in_repo_path);
3339 if (s->in_repo_path == NULL)
3340 return got_error_from_errno("strdup");
3343 /* The commit queue only contains commits being displayed. */
3344 TAILQ_INIT(&s->real_commits.head);
3345 s->real_commits.ncommits = 0;
3346 s->commits = &s->real_commits;
3348 TAILQ_INIT(&s->limit_commits.head);
3349 s->limit_view = 0;
3350 s->limit_commits.ncommits = 0;
3352 s->repo = repo;
3353 if (head_ref_name) {
3354 s->head_ref_name = strdup(head_ref_name);
3355 if (s->head_ref_name == NULL) {
3356 err = got_error_from_errno("strdup");
3357 goto done;
3360 s->start_id = got_object_id_dup(start_id);
3361 if (s->start_id == NULL) {
3362 err = got_error_from_errno("got_object_id_dup");
3363 goto done;
3365 s->log_branches = log_branches;
3367 STAILQ_INIT(&s->colors);
3368 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3369 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3370 get_color_value("TOG_COLOR_COMMIT"));
3371 if (err)
3372 goto done;
3373 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3374 get_color_value("TOG_COLOR_AUTHOR"));
3375 if (err) {
3376 free_colors(&s->colors);
3377 goto done;
3379 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3380 get_color_value("TOG_COLOR_DATE"));
3381 if (err) {
3382 free_colors(&s->colors);
3383 goto done;
3387 view->show = show_log_view;
3388 view->input = input_log_view;
3389 view->resize = resize_log_view;
3390 view->close = close_log_view;
3391 view->search_start = search_start_log_view;
3392 view->search_next = search_next_log_view;
3394 if (s->thread_args.pack_fds == NULL) {
3395 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3396 if (err)
3397 goto done;
3399 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3400 s->thread_args.pack_fds);
3401 if (err)
3402 goto done;
3403 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3404 !s->log_branches);
3405 if (err)
3406 goto done;
3407 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3408 s->repo, NULL, NULL);
3409 if (err)
3410 goto done;
3412 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3413 if (errcode) {
3414 err = got_error_set_errno(errcode, "pthread_cond_init");
3415 goto done;
3417 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3418 if (errcode) {
3419 err = got_error_set_errno(errcode, "pthread_cond_init");
3420 goto done;
3423 s->thread_args.commits_needed = view->nlines;
3424 s->thread_args.graph = thread_graph;
3425 s->thread_args.real_commits = &s->real_commits;
3426 s->thread_args.limit_commits = &s->limit_commits;
3427 s->thread_args.in_repo_path = s->in_repo_path;
3428 s->thread_args.start_id = s->start_id;
3429 s->thread_args.repo = thread_repo;
3430 s->thread_args.log_complete = 0;
3431 s->thread_args.quit = &s->quit;
3432 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3433 s->thread_args.selected_entry = &s->selected_entry;
3434 s->thread_args.searching = &view->searching;
3435 s->thread_args.search_next_done = &view->search_next_done;
3436 s->thread_args.regex = &view->regex;
3437 s->thread_args.limiting = &s->limit_view;
3438 s->thread_args.limit_regex = &s->limit_regex;
3439 s->thread_args.limit_commits = &s->limit_commits;
3440 done:
3441 if (err)
3442 close_log_view(view);
3443 return err;
3446 static const struct got_error *
3447 show_log_view(struct tog_view *view)
3449 const struct got_error *err;
3450 struct tog_log_view_state *s = &view->state.log;
3452 if (s->thread == 0) { //NULL) {
3453 int errcode = pthread_create(&s->thread, NULL, log_thread,
3454 &s->thread_args);
3455 if (errcode)
3456 return got_error_set_errno(errcode, "pthread_create");
3457 if (s->thread_args.commits_needed > 0) {
3458 err = trigger_log_thread(view, 1);
3459 if (err)
3460 return err;
3464 return draw_commits(view);
3467 static void
3468 log_move_cursor_up(struct tog_view *view, int page, int home)
3470 struct tog_log_view_state *s = &view->state.log;
3472 if (s->first_displayed_entry == NULL)
3473 return;
3474 if (s->selected_entry->idx == 0)
3475 view->count = 0;
3477 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3478 || home)
3479 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3481 if (!page && !home && s->selected > 0)
3482 --s->selected;
3483 else
3484 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3486 select_commit(s);
3487 return;
3490 static const struct got_error *
3491 log_move_cursor_down(struct tog_view *view, int page)
3493 struct tog_log_view_state *s = &view->state.log;
3494 const struct got_error *err = NULL;
3495 int eos = view->nlines - 2;
3497 if (s->first_displayed_entry == NULL)
3498 return NULL;
3500 if (s->thread_args.log_complete &&
3501 s->selected_entry->idx >= s->commits->ncommits - 1)
3502 return NULL;
3504 if (view_is_hsplit_top(view))
3505 --eos; /* border consumes the last line */
3507 if (!page) {
3508 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3509 ++s->selected;
3510 else
3511 err = log_scroll_down(view, 1);
3512 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3513 struct commit_queue_entry *entry;
3514 int n;
3516 s->selected = 0;
3517 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3518 s->last_displayed_entry = entry;
3519 for (n = 0; n <= eos; n++) {
3520 if (entry == NULL)
3521 break;
3522 s->first_displayed_entry = entry;
3523 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3525 if (n > 0)
3526 s->selected = n - 1;
3527 } else {
3528 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3529 s->thread_args.log_complete)
3530 s->selected += MIN(page,
3531 s->commits->ncommits - s->selected_entry->idx - 1);
3532 else
3533 err = log_scroll_down(view, page);
3535 if (err)
3536 return err;
3539 * We might necessarily overshoot in horizontal
3540 * splits; if so, select the last displayed commit.
3542 if (s->first_displayed_entry && s->last_displayed_entry) {
3543 s->selected = MIN(s->selected,
3544 s->last_displayed_entry->idx -
3545 s->first_displayed_entry->idx);
3548 select_commit(s);
3550 if (s->thread_args.log_complete &&
3551 s->selected_entry->idx == s->commits->ncommits - 1)
3552 view->count = 0;
3554 return NULL;
3557 static void
3558 view_get_split(struct tog_view *view, int *y, int *x)
3560 *x = 0;
3561 *y = 0;
3563 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3564 if (view->child && view->child->resized_y)
3565 *y = view->child->resized_y;
3566 else if (view->resized_y)
3567 *y = view->resized_y;
3568 else
3569 *y = view_split_begin_y(view->lines);
3570 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3571 if (view->child && view->child->resized_x)
3572 *x = view->child->resized_x;
3573 else if (view->resized_x)
3574 *x = view->resized_x;
3575 else
3576 *x = view_split_begin_x(view->begin_x);
3580 /* Split view horizontally at y and offset view->state->selected line. */
3581 static const struct got_error *
3582 view_init_hsplit(struct tog_view *view, int y)
3584 const struct got_error *err = NULL;
3586 view->nlines = y;
3587 view->ncols = COLS;
3588 err = view_resize(view);
3589 if (err)
3590 return err;
3592 err = offset_selection_down(view);
3594 return err;
3597 static const struct got_error *
3598 log_goto_line(struct tog_view *view, int nlines)
3600 const struct got_error *err = NULL;
3601 struct tog_log_view_state *s = &view->state.log;
3602 int g, idx = s->selected_entry->idx;
3604 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3605 return NULL;
3607 g = view->gline;
3608 view->gline = 0;
3610 if (g >= s->first_displayed_entry->idx + 1 &&
3611 g <= s->last_displayed_entry->idx + 1 &&
3612 g - s->first_displayed_entry->idx - 1 < nlines) {
3613 s->selected = g - s->first_displayed_entry->idx - 1;
3614 select_commit(s);
3615 return NULL;
3618 if (idx + 1 < g) {
3619 err = log_move_cursor_down(view, g - idx - 1);
3620 if (!err && g > s->selected_entry->idx + 1)
3621 err = log_move_cursor_down(view,
3622 g - s->first_displayed_entry->idx - 1);
3623 if (err)
3624 return err;
3625 } else if (idx + 1 > g)
3626 log_move_cursor_up(view, idx - g + 1, 0);
3628 if (g < nlines && s->first_displayed_entry->idx == 0)
3629 s->selected = g - 1;
3631 select_commit(s);
3632 return NULL;
3636 static const struct got_error *
3637 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3639 const struct got_error *err = NULL;
3640 struct tog_log_view_state *s = &view->state.log;
3641 int eos, nscroll;
3643 if (s->thread_args.load_all) {
3644 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3645 s->thread_args.load_all = 0;
3646 else if (s->thread_args.log_complete) {
3647 err = log_move_cursor_down(view, s->commits->ncommits);
3648 s->thread_args.load_all = 0;
3650 if (err)
3651 return err;
3654 eos = nscroll = view->nlines - 1;
3655 if (view_is_hsplit_top(view))
3656 --eos; /* border */
3658 if (view->gline)
3659 return log_goto_line(view, eos);
3661 switch (ch) {
3662 case '&':
3663 err = limit_log_view(view);
3664 break;
3665 case 'q':
3666 s->quit = 1;
3667 break;
3668 case '0':
3669 view->x = 0;
3670 break;
3671 case '$':
3672 view->x = MAX(view->maxx - view->ncols / 2, 0);
3673 view->count = 0;
3674 break;
3675 case KEY_RIGHT:
3676 case 'l':
3677 if (view->x + view->ncols / 2 < view->maxx)
3678 view->x += 2; /* move two columns right */
3679 else
3680 view->count = 0;
3681 break;
3682 case KEY_LEFT:
3683 case 'h':
3684 view->x -= MIN(view->x, 2); /* move two columns back */
3685 if (view->x <= 0)
3686 view->count = 0;
3687 break;
3688 case 'k':
3689 case KEY_UP:
3690 case '<':
3691 case ',':
3692 case CTRL('p'):
3693 log_move_cursor_up(view, 0, 0);
3694 break;
3695 case 'g':
3696 case KEY_HOME:
3697 log_move_cursor_up(view, 0, 1);
3698 view->count = 0;
3699 break;
3700 case CTRL('u'):
3701 case 'u':
3702 nscroll /= 2;
3703 /* FALL THROUGH */
3704 case KEY_PPAGE:
3705 case CTRL('b'):
3706 case 'b':
3707 log_move_cursor_up(view, nscroll, 0);
3708 break;
3709 case 'j':
3710 case KEY_DOWN:
3711 case '>':
3712 case '.':
3713 case CTRL('n'):
3714 err = log_move_cursor_down(view, 0);
3715 break;
3716 case '@':
3717 s->use_committer = !s->use_committer;
3718 break;
3719 case 'G':
3720 case KEY_END: {
3721 /* We don't know yet how many commits, so we're forced to
3722 * traverse them all. */
3723 view->count = 0;
3724 s->thread_args.load_all = 1;
3725 if (!s->thread_args.log_complete)
3726 return trigger_log_thread(view, 0);
3727 err = log_move_cursor_down(view, s->commits->ncommits);
3728 s->thread_args.load_all = 0;
3729 break;
3731 case CTRL('d'):
3732 case 'd':
3733 nscroll /= 2;
3734 /* FALL THROUGH */
3735 case KEY_NPAGE:
3736 case CTRL('f'):
3737 case 'f':
3738 case ' ':
3739 err = log_move_cursor_down(view, nscroll);
3740 break;
3741 case KEY_RESIZE:
3742 if (s->selected > view->nlines - 2)
3743 s->selected = view->nlines - 2;
3744 if (s->selected > s->commits->ncommits - 1)
3745 s->selected = s->commits->ncommits - 1;
3746 select_commit(s);
3747 if (s->commits->ncommits < view->nlines - 1 &&
3748 !s->thread_args.log_complete) {
3749 s->thread_args.commits_needed += (view->nlines - 1) -
3750 s->commits->ncommits;
3751 err = trigger_log_thread(view, 1);
3753 break;
3754 case KEY_ENTER:
3755 case '\r':
3756 view->count = 0;
3757 if (s->selected_entry == NULL)
3758 break;
3759 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3760 break;
3761 case 'T':
3762 view->count = 0;
3763 if (s->selected_entry == NULL)
3764 break;
3765 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3766 break;
3767 case KEY_BACKSPACE:
3768 case CTRL('l'):
3769 case 'B':
3770 view->count = 0;
3771 if (ch == KEY_BACKSPACE &&
3772 got_path_is_root_dir(s->in_repo_path))
3773 break;
3774 err = stop_log_thread(s);
3775 if (err)
3776 return err;
3777 if (ch == KEY_BACKSPACE) {
3778 char *parent_path;
3779 err = got_path_dirname(&parent_path, s->in_repo_path);
3780 if (err)
3781 return err;
3782 free(s->in_repo_path);
3783 s->in_repo_path = parent_path;
3784 s->thread_args.in_repo_path = s->in_repo_path;
3785 } else if (ch == CTRL('l')) {
3786 struct got_object_id *start_id;
3787 err = got_repo_match_object_id(&start_id, NULL,
3788 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3789 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3790 if (err)
3791 return err;
3792 free(s->start_id);
3793 s->start_id = start_id;
3794 s->thread_args.start_id = s->start_id;
3795 } else /* 'B' */
3796 s->log_branches = !s->log_branches;
3798 if (s->thread_args.pack_fds == NULL) {
3799 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3800 if (err)
3801 return err;
3803 err = got_repo_open(&s->thread_args.repo,
3804 got_repo_get_path(s->repo), NULL,
3805 s->thread_args.pack_fds);
3806 if (err)
3807 return err;
3808 tog_free_refs();
3809 err = tog_load_refs(s->repo, 0);
3810 if (err)
3811 return err;
3812 err = got_commit_graph_open(&s->thread_args.graph,
3813 s->in_repo_path, !s->log_branches);
3814 if (err)
3815 return err;
3816 err = got_commit_graph_iter_start(s->thread_args.graph,
3817 s->start_id, s->repo, NULL, NULL);
3818 if (err)
3819 return err;
3820 free_commits(&s->real_commits);
3821 free_commits(&s->limit_commits);
3822 s->first_displayed_entry = NULL;
3823 s->last_displayed_entry = NULL;
3824 s->selected_entry = NULL;
3825 s->selected = 0;
3826 s->thread_args.log_complete = 0;
3827 s->quit = 0;
3828 s->thread_args.commits_needed = view->lines;
3829 s->matched_entry = NULL;
3830 s->search_entry = NULL;
3831 view->offset = 0;
3832 break;
3833 case 'R':
3834 view->count = 0;
3835 err = view_request_new(new_view, view, TOG_VIEW_REF);
3836 break;
3837 default:
3838 view->count = 0;
3839 break;
3842 return err;
3845 static const struct got_error *
3846 apply_unveil(const char *repo_path, const char *worktree_path)
3848 const struct got_error *error;
3850 #ifdef PROFILE
3851 if (unveil("gmon.out", "rwc") != 0)
3852 return got_error_from_errno2("unveil", "gmon.out");
3853 #endif
3854 if (repo_path && unveil(repo_path, "r") != 0)
3855 return got_error_from_errno2("unveil", repo_path);
3857 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3858 return got_error_from_errno2("unveil", worktree_path);
3860 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3861 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3863 error = got_privsep_unveil_exec_helpers();
3864 if (error != NULL)
3865 return error;
3867 if (unveil(NULL, NULL) != 0)
3868 return got_error_from_errno("unveil");
3870 return NULL;
3873 static void
3874 init_curses(void)
3877 * Override default signal handlers before starting ncurses.
3878 * This should prevent ncurses from installing its own
3879 * broken cleanup() signal handler.
3881 signal(SIGWINCH, tog_sigwinch);
3882 signal(SIGPIPE, tog_sigpipe);
3883 signal(SIGCONT, tog_sigcont);
3884 signal(SIGINT, tog_sigint);
3885 signal(SIGTERM, tog_sigterm);
3887 initscr();
3888 cbreak();
3889 halfdelay(1); /* Do fast refresh while initial view is loading. */
3890 noecho();
3891 nonl();
3892 intrflush(stdscr, FALSE);
3893 keypad(stdscr, TRUE);
3894 curs_set(0);
3895 if (getenv("TOG_COLORS") != NULL) {
3896 start_color();
3897 use_default_colors();
3901 static const struct got_error *
3902 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3903 struct got_repository *repo, struct got_worktree *worktree)
3905 const struct got_error *err = NULL;
3907 if (argc == 0) {
3908 *in_repo_path = strdup("/");
3909 if (*in_repo_path == NULL)
3910 return got_error_from_errno("strdup");
3911 return NULL;
3914 if (worktree) {
3915 const char *prefix = got_worktree_get_path_prefix(worktree);
3916 char *p;
3918 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3919 if (err)
3920 return err;
3921 if (asprintf(in_repo_path, "%s%s%s", prefix,
3922 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3923 p) == -1) {
3924 err = got_error_from_errno("asprintf");
3925 *in_repo_path = NULL;
3927 free(p);
3928 } else
3929 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3931 return err;
3934 static const struct got_error *
3935 cmd_log(int argc, char *argv[])
3937 const struct got_error *error;
3938 struct got_repository *repo = NULL;
3939 struct got_worktree *worktree = NULL;
3940 struct got_object_id *start_id = NULL;
3941 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3942 char *start_commit = NULL, *label = NULL;
3943 struct got_reference *ref = NULL;
3944 const char *head_ref_name = NULL;
3945 int ch, log_branches = 0;
3946 struct tog_view *view;
3947 int *pack_fds = NULL;
3949 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3950 switch (ch) {
3951 case 'b':
3952 log_branches = 1;
3953 break;
3954 case 'c':
3955 start_commit = optarg;
3956 break;
3957 case 'r':
3958 repo_path = realpath(optarg, NULL);
3959 if (repo_path == NULL)
3960 return got_error_from_errno2("realpath",
3961 optarg);
3962 break;
3963 default:
3964 usage_log();
3965 /* NOTREACHED */
3969 argc -= optind;
3970 argv += optind;
3972 if (argc > 1)
3973 usage_log();
3975 error = got_repo_pack_fds_open(&pack_fds);
3976 if (error != NULL)
3977 goto done;
3979 if (repo_path == NULL) {
3980 cwd = getcwd(NULL, 0);
3981 if (cwd == NULL)
3982 return got_error_from_errno("getcwd");
3983 error = got_worktree_open(&worktree, cwd);
3984 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3985 goto done;
3986 if (worktree)
3987 repo_path =
3988 strdup(got_worktree_get_repo_path(worktree));
3989 else
3990 repo_path = strdup(cwd);
3991 if (repo_path == NULL) {
3992 error = got_error_from_errno("strdup");
3993 goto done;
3997 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3998 if (error != NULL)
3999 goto done;
4001 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4002 repo, worktree);
4003 if (error)
4004 goto done;
4006 init_curses();
4008 error = apply_unveil(got_repo_get_path(repo),
4009 worktree ? got_worktree_get_root_path(worktree) : NULL);
4010 if (error)
4011 goto done;
4013 /* already loaded by tog_log_with_path()? */
4014 if (TAILQ_EMPTY(&tog_refs)) {
4015 error = tog_load_refs(repo, 0);
4016 if (error)
4017 goto done;
4020 if (start_commit == NULL) {
4021 error = got_repo_match_object_id(&start_id, &label,
4022 worktree ? got_worktree_get_head_ref_name(worktree) :
4023 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4024 if (error)
4025 goto done;
4026 head_ref_name = label;
4027 } else {
4028 error = got_ref_open(&ref, repo, start_commit, 0);
4029 if (error == NULL)
4030 head_ref_name = got_ref_get_name(ref);
4031 else if (error->code != GOT_ERR_NOT_REF)
4032 goto done;
4033 error = got_repo_match_object_id(&start_id, NULL,
4034 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4035 if (error)
4036 goto done;
4039 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4040 if (view == NULL) {
4041 error = got_error_from_errno("view_open");
4042 goto done;
4044 error = open_log_view(view, start_id, repo, head_ref_name,
4045 in_repo_path, log_branches);
4046 if (error)
4047 goto done;
4048 if (worktree) {
4049 /* Release work tree lock. */
4050 got_worktree_close(worktree);
4051 worktree = NULL;
4053 error = view_loop(view);
4054 done:
4055 free(in_repo_path);
4056 free(repo_path);
4057 free(cwd);
4058 free(start_id);
4059 free(label);
4060 if (ref)
4061 got_ref_close(ref);
4062 if (repo) {
4063 const struct got_error *close_err = got_repo_close(repo);
4064 if (error == NULL)
4065 error = close_err;
4067 if (worktree)
4068 got_worktree_close(worktree);
4069 if (pack_fds) {
4070 const struct got_error *pack_err =
4071 got_repo_pack_fds_close(pack_fds);
4072 if (error == NULL)
4073 error = pack_err;
4075 tog_free_refs();
4076 return error;
4079 __dead static void
4080 usage_diff(void)
4082 endwin();
4083 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4084 "object1 object2\n", getprogname());
4085 exit(1);
4088 static int
4089 match_line(const char *line, regex_t *regex, size_t nmatch,
4090 regmatch_t *regmatch)
4092 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4095 static struct tog_color *
4096 match_color(struct tog_colors *colors, const char *line)
4098 struct tog_color *tc = NULL;
4100 STAILQ_FOREACH(tc, colors, entry) {
4101 if (match_line(line, &tc->regex, 0, NULL))
4102 return tc;
4105 return NULL;
4108 static const struct got_error *
4109 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4110 WINDOW *window, int skipcol, regmatch_t *regmatch)
4112 const struct got_error *err = NULL;
4113 char *exstr = NULL;
4114 wchar_t *wline = NULL;
4115 int rme, rms, n, width, scrollx;
4116 int width0 = 0, width1 = 0, width2 = 0;
4117 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4119 *wtotal = 0;
4121 rms = regmatch->rm_so;
4122 rme = regmatch->rm_eo;
4124 err = expand_tab(&exstr, line);
4125 if (err)
4126 return err;
4128 /* Split the line into 3 segments, according to match offsets. */
4129 seg0 = strndup(exstr, rms);
4130 if (seg0 == NULL) {
4131 err = got_error_from_errno("strndup");
4132 goto done;
4134 seg1 = strndup(exstr + rms, rme - rms);
4135 if (seg1 == NULL) {
4136 err = got_error_from_errno("strndup");
4137 goto done;
4139 seg2 = strdup(exstr + rme);
4140 if (seg2 == NULL) {
4141 err = got_error_from_errno("strndup");
4142 goto done;
4145 /* draw up to matched token if we haven't scrolled past it */
4146 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4147 col_tab_align, 1);
4148 if (err)
4149 goto done;
4150 n = MAX(width0 - skipcol, 0);
4151 if (n) {
4152 free(wline);
4153 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4154 wlimit, col_tab_align, 1);
4155 if (err)
4156 goto done;
4157 waddwstr(window, &wline[scrollx]);
4158 wlimit -= width;
4159 *wtotal += width;
4162 if (wlimit > 0) {
4163 int i = 0, w = 0;
4164 size_t wlen;
4166 free(wline);
4167 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4168 col_tab_align, 1);
4169 if (err)
4170 goto done;
4171 wlen = wcslen(wline);
4172 while (i < wlen) {
4173 width = wcwidth(wline[i]);
4174 if (width == -1) {
4175 /* should not happen, tabs are expanded */
4176 err = got_error(GOT_ERR_RANGE);
4177 goto done;
4179 if (width0 + w + width > skipcol)
4180 break;
4181 w += width;
4182 i++;
4184 /* draw (visible part of) matched token (if scrolled into it) */
4185 if (width1 - w > 0) {
4186 wattron(window, A_STANDOUT);
4187 waddwstr(window, &wline[i]);
4188 wattroff(window, A_STANDOUT);
4189 wlimit -= (width1 - w);
4190 *wtotal += (width1 - w);
4194 if (wlimit > 0) { /* draw rest of line */
4195 free(wline);
4196 if (skipcol > width0 + width1) {
4197 err = format_line(&wline, &width2, &scrollx, seg2,
4198 skipcol - (width0 + width1), wlimit,
4199 col_tab_align, 1);
4200 if (err)
4201 goto done;
4202 waddwstr(window, &wline[scrollx]);
4203 } else {
4204 err = format_line(&wline, &width2, NULL, seg2, 0,
4205 wlimit, col_tab_align, 1);
4206 if (err)
4207 goto done;
4208 waddwstr(window, wline);
4210 *wtotal += width2;
4212 done:
4213 free(wline);
4214 free(exstr);
4215 free(seg0);
4216 free(seg1);
4217 free(seg2);
4218 return err;
4221 static int
4222 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4224 FILE *f = NULL;
4225 int *eof, *first, *selected;
4227 if (view->type == TOG_VIEW_DIFF) {
4228 struct tog_diff_view_state *s = &view->state.diff;
4230 first = &s->first_displayed_line;
4231 selected = first;
4232 eof = &s->eof;
4233 f = s->f;
4234 } else if (view->type == TOG_VIEW_HELP) {
4235 struct tog_help_view_state *s = &view->state.help;
4237 first = &s->first_displayed_line;
4238 selected = first;
4239 eof = &s->eof;
4240 f = s->f;
4241 } else if (view->type == TOG_VIEW_BLAME) {
4242 struct tog_blame_view_state *s = &view->state.blame;
4244 first = &s->first_displayed_line;
4245 selected = &s->selected_line;
4246 eof = &s->eof;
4247 f = s->blame.f;
4248 } else
4249 return 0;
4251 /* Center gline in the middle of the page like vi(1). */
4252 if (*lineno < view->gline - (view->nlines - 3) / 2)
4253 return 0;
4254 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4255 rewind(f);
4256 *eof = 0;
4257 *first = 1;
4258 *lineno = 0;
4259 *nprinted = 0;
4260 return 0;
4263 *selected = view->gline <= (view->nlines - 3) / 2 ?
4264 view->gline : (view->nlines - 3) / 2 + 1;
4265 view->gline = 0;
4267 return 1;
4270 static const struct got_error *
4271 draw_file(struct tog_view *view, const char *header)
4273 struct tog_diff_view_state *s = &view->state.diff;
4274 regmatch_t *regmatch = &view->regmatch;
4275 const struct got_error *err;
4276 int nprinted = 0;
4277 char *line;
4278 size_t linesize = 0;
4279 ssize_t linelen;
4280 wchar_t *wline;
4281 int width;
4282 int max_lines = view->nlines;
4283 int nlines = s->nlines;
4284 off_t line_offset;
4286 s->lineno = s->first_displayed_line - 1;
4287 line_offset = s->lines[s->first_displayed_line - 1].offset;
4288 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4289 return got_error_from_errno("fseek");
4291 werase(view->window);
4293 if (view->gline > s->nlines - 1)
4294 view->gline = s->nlines - 1;
4296 if (header) {
4297 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4298 1 : view->gline - (view->nlines - 3) / 2 :
4299 s->lineno + s->selected_line;
4301 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4302 return got_error_from_errno("asprintf");
4303 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4304 0, 0);
4305 free(line);
4306 if (err)
4307 return err;
4309 if (view_needs_focus_indication(view))
4310 wstandout(view->window);
4311 waddwstr(view->window, wline);
4312 free(wline);
4313 wline = NULL;
4314 while (width++ < view->ncols)
4315 waddch(view->window, ' ');
4316 if (view_needs_focus_indication(view))
4317 wstandend(view->window);
4319 if (max_lines <= 1)
4320 return NULL;
4321 max_lines--;
4324 s->eof = 0;
4325 view->maxx = 0;
4326 line = NULL;
4327 while (max_lines > 0 && nprinted < max_lines) {
4328 enum got_diff_line_type linetype;
4329 attr_t attr = 0;
4331 linelen = getline(&line, &linesize, s->f);
4332 if (linelen == -1) {
4333 if (feof(s->f)) {
4334 s->eof = 1;
4335 break;
4337 free(line);
4338 return got_ferror(s->f, GOT_ERR_IO);
4341 if (++s->lineno < s->first_displayed_line)
4342 continue;
4343 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4344 continue;
4345 if (s->lineno == view->hiline)
4346 attr = A_STANDOUT;
4348 /* Set view->maxx based on full line length. */
4349 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4350 view->x ? 1 : 0);
4351 if (err) {
4352 free(line);
4353 return err;
4355 view->maxx = MAX(view->maxx, width);
4356 free(wline);
4357 wline = NULL;
4359 linetype = s->lines[s->lineno].type;
4360 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4361 linetype < GOT_DIFF_LINE_CONTEXT)
4362 attr |= COLOR_PAIR(linetype);
4363 if (attr)
4364 wattron(view->window, attr);
4365 if (s->first_displayed_line + nprinted == s->matched_line &&
4366 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4367 err = add_matched_line(&width, line, view->ncols, 0,
4368 view->window, view->x, regmatch);
4369 if (err) {
4370 free(line);
4371 return err;
4373 } else {
4374 int skip;
4375 err = format_line(&wline, &width, &skip, line,
4376 view->x, view->ncols, 0, view->x ? 1 : 0);
4377 if (err) {
4378 free(line);
4379 return err;
4381 waddwstr(view->window, &wline[skip]);
4382 free(wline);
4383 wline = NULL;
4385 if (s->lineno == view->hiline) {
4386 /* highlight full gline length */
4387 while (width++ < view->ncols)
4388 waddch(view->window, ' ');
4389 } else {
4390 if (width <= view->ncols - 1)
4391 waddch(view->window, '\n');
4393 if (attr)
4394 wattroff(view->window, attr);
4395 if (++nprinted == 1)
4396 s->first_displayed_line = s->lineno;
4398 free(line);
4399 if (nprinted >= 1)
4400 s->last_displayed_line = s->first_displayed_line +
4401 (nprinted - 1);
4402 else
4403 s->last_displayed_line = s->first_displayed_line;
4405 view_border(view);
4407 if (s->eof) {
4408 while (nprinted < view->nlines) {
4409 waddch(view->window, '\n');
4410 nprinted++;
4413 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4414 view->ncols, 0, 0);
4415 if (err) {
4416 return err;
4419 wstandout(view->window);
4420 waddwstr(view->window, wline);
4421 free(wline);
4422 wline = NULL;
4423 wstandend(view->window);
4426 return NULL;
4429 static char *
4430 get_datestr(time_t *time, char *datebuf)
4432 struct tm mytm, *tm;
4433 char *p, *s;
4435 tm = gmtime_r(time, &mytm);
4436 if (tm == NULL)
4437 return NULL;
4438 s = asctime_r(tm, datebuf);
4439 if (s == NULL)
4440 return NULL;
4441 p = strchr(s, '\n');
4442 if (p)
4443 *p = '\0';
4444 return s;
4447 static const struct got_error *
4448 get_changed_paths(struct got_pathlist_head *paths,
4449 struct got_commit_object *commit, struct got_repository *repo)
4451 const struct got_error *err = NULL;
4452 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4453 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4454 struct got_object_qid *qid;
4456 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4457 if (qid != NULL) {
4458 struct got_commit_object *pcommit;
4459 err = got_object_open_as_commit(&pcommit, repo,
4460 &qid->id);
4461 if (err)
4462 return err;
4464 tree_id1 = got_object_id_dup(
4465 got_object_commit_get_tree_id(pcommit));
4466 if (tree_id1 == NULL) {
4467 got_object_commit_close(pcommit);
4468 return got_error_from_errno("got_object_id_dup");
4470 got_object_commit_close(pcommit);
4474 if (tree_id1) {
4475 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4476 if (err)
4477 goto done;
4480 tree_id2 = got_object_commit_get_tree_id(commit);
4481 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4482 if (err)
4483 goto done;
4485 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4486 got_diff_tree_collect_changed_paths, paths, 0);
4487 done:
4488 if (tree1)
4489 got_object_tree_close(tree1);
4490 if (tree2)
4491 got_object_tree_close(tree2);
4492 free(tree_id1);
4493 return err;
4496 static const struct got_error *
4497 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4498 off_t off, uint8_t type)
4500 struct got_diff_line *p;
4502 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4503 if (p == NULL)
4504 return got_error_from_errno("reallocarray");
4505 *lines = p;
4506 (*lines)[*nlines].offset = off;
4507 (*lines)[*nlines].type = type;
4508 (*nlines)++;
4510 return NULL;
4513 static const struct got_error *
4514 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4515 struct got_object_id *commit_id, struct got_reflist_head *refs,
4516 struct got_repository *repo, FILE *outfile)
4518 const struct got_error *err = NULL;
4519 char datebuf[26], *datestr;
4520 struct got_commit_object *commit;
4521 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4522 time_t committer_time;
4523 const char *author, *committer;
4524 char *refs_str = NULL;
4525 struct got_pathlist_head changed_paths;
4526 struct got_pathlist_entry *pe;
4527 off_t outoff = 0;
4528 int n;
4530 TAILQ_INIT(&changed_paths);
4532 if (refs) {
4533 err = build_refs_str(&refs_str, refs, commit_id, repo);
4534 if (err)
4535 return err;
4538 err = got_object_open_as_commit(&commit, repo, commit_id);
4539 if (err)
4540 return err;
4542 err = got_object_id_str(&id_str, commit_id);
4543 if (err) {
4544 err = got_error_from_errno("got_object_id_str");
4545 goto done;
4548 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4549 if (err)
4550 goto done;
4552 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4553 refs_str ? refs_str : "", refs_str ? ")" : "");
4554 if (n < 0) {
4555 err = got_error_from_errno("fprintf");
4556 goto done;
4558 outoff += n;
4559 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4560 if (err)
4561 goto done;
4563 n = fprintf(outfile, "from: %s\n",
4564 got_object_commit_get_author(commit));
4565 if (n < 0) {
4566 err = got_error_from_errno("fprintf");
4567 goto done;
4569 outoff += n;
4570 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4571 if (err)
4572 goto done;
4574 committer_time = got_object_commit_get_committer_time(commit);
4575 datestr = get_datestr(&committer_time, datebuf);
4576 if (datestr) {
4577 n = fprintf(outfile, "date: %s UTC\n", datestr);
4578 if (n < 0) {
4579 err = got_error_from_errno("fprintf");
4580 goto done;
4582 outoff += n;
4583 err = add_line_metadata(lines, nlines, outoff,
4584 GOT_DIFF_LINE_DATE);
4585 if (err)
4586 goto done;
4588 author = got_object_commit_get_author(commit);
4589 committer = got_object_commit_get_committer(commit);
4590 if (strcmp(author, committer) != 0) {
4591 n = fprintf(outfile, "via: %s\n", committer);
4592 if (n < 0) {
4593 err = got_error_from_errno("fprintf");
4594 goto done;
4596 outoff += n;
4597 err = add_line_metadata(lines, nlines, outoff,
4598 GOT_DIFF_LINE_AUTHOR);
4599 if (err)
4600 goto done;
4602 if (got_object_commit_get_nparents(commit) > 1) {
4603 const struct got_object_id_queue *parent_ids;
4604 struct got_object_qid *qid;
4605 int pn = 1;
4606 parent_ids = got_object_commit_get_parent_ids(commit);
4607 STAILQ_FOREACH(qid, parent_ids, entry) {
4608 err = got_object_id_str(&id_str, &qid->id);
4609 if (err)
4610 goto done;
4611 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4612 if (n < 0) {
4613 err = got_error_from_errno("fprintf");
4614 goto done;
4616 outoff += n;
4617 err = add_line_metadata(lines, nlines, outoff,
4618 GOT_DIFF_LINE_META);
4619 if (err)
4620 goto done;
4621 free(id_str);
4622 id_str = NULL;
4626 err = got_object_commit_get_logmsg(&logmsg, commit);
4627 if (err)
4628 goto done;
4629 s = logmsg;
4630 while ((line = strsep(&s, "\n")) != NULL) {
4631 n = fprintf(outfile, "%s\n", line);
4632 if (n < 0) {
4633 err = got_error_from_errno("fprintf");
4634 goto done;
4636 outoff += n;
4637 err = add_line_metadata(lines, nlines, outoff,
4638 GOT_DIFF_LINE_LOGMSG);
4639 if (err)
4640 goto done;
4643 err = get_changed_paths(&changed_paths, commit, repo);
4644 if (err)
4645 goto done;
4646 TAILQ_FOREACH(pe, &changed_paths, entry) {
4647 struct got_diff_changed_path *cp = pe->data;
4648 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4649 if (n < 0) {
4650 err = got_error_from_errno("fprintf");
4651 goto done;
4653 outoff += n;
4654 err = add_line_metadata(lines, nlines, outoff,
4655 GOT_DIFF_LINE_CHANGES);
4656 if (err)
4657 goto done;
4658 free((char *)pe->path);
4659 free(pe->data);
4662 fputc('\n', outfile);
4663 outoff++;
4664 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4665 done:
4666 got_pathlist_free(&changed_paths);
4667 free(id_str);
4668 free(logmsg);
4669 free(refs_str);
4670 got_object_commit_close(commit);
4671 if (err) {
4672 free(*lines);
4673 *lines = NULL;
4674 *nlines = 0;
4676 return err;
4679 static const struct got_error *
4680 create_diff(struct tog_diff_view_state *s)
4682 const struct got_error *err = NULL;
4683 FILE *f = NULL;
4684 int obj_type;
4686 free(s->lines);
4687 s->lines = malloc(sizeof(*s->lines));
4688 if (s->lines == NULL)
4689 return got_error_from_errno("malloc");
4690 s->nlines = 0;
4692 f = got_opentemp();
4693 if (f == NULL) {
4694 err = got_error_from_errno("got_opentemp");
4695 goto done;
4697 if (s->f && fclose(s->f) == EOF) {
4698 err = got_error_from_errno("fclose");
4699 goto done;
4701 s->f = f;
4703 if (s->id1)
4704 err = got_object_get_type(&obj_type, s->repo, s->id1);
4705 else
4706 err = got_object_get_type(&obj_type, s->repo, s->id2);
4707 if (err)
4708 goto done;
4710 switch (obj_type) {
4711 case GOT_OBJ_TYPE_BLOB:
4712 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4713 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4714 s->label1, s->label2, tog_diff_algo, s->diff_context,
4715 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4716 break;
4717 case GOT_OBJ_TYPE_TREE:
4718 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4719 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4720 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4721 s->force_text_diff, s->repo, s->f);
4722 break;
4723 case GOT_OBJ_TYPE_COMMIT: {
4724 const struct got_object_id_queue *parent_ids;
4725 struct got_object_qid *pid;
4726 struct got_commit_object *commit2;
4727 struct got_reflist_head *refs;
4729 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4730 if (err)
4731 goto done;
4732 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4733 /* Show commit info if we're diffing to a parent/root commit. */
4734 if (s->id1 == NULL) {
4735 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4736 refs, s->repo, s->f);
4737 if (err)
4738 goto done;
4739 } else {
4740 parent_ids = got_object_commit_get_parent_ids(commit2);
4741 STAILQ_FOREACH(pid, parent_ids, entry) {
4742 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4743 err = write_commit_info(&s->lines,
4744 &s->nlines, s->id2, refs, s->repo,
4745 s->f);
4746 if (err)
4747 goto done;
4748 break;
4752 got_object_commit_close(commit2);
4754 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4755 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4756 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4757 s->force_text_diff, s->repo, s->f);
4758 break;
4760 default:
4761 err = got_error(GOT_ERR_OBJ_TYPE);
4762 break;
4764 done:
4765 if (s->f && fflush(s->f) != 0 && err == NULL)
4766 err = got_error_from_errno("fflush");
4767 return err;
4770 static void
4771 diff_view_indicate_progress(struct tog_view *view)
4773 mvwaddstr(view->window, 0, 0, "diffing...");
4774 update_panels();
4775 doupdate();
4778 static const struct got_error *
4779 search_start_diff_view(struct tog_view *view)
4781 struct tog_diff_view_state *s = &view->state.diff;
4783 s->matched_line = 0;
4784 return NULL;
4787 static void
4788 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4789 size_t *nlines, int **first, int **last, int **match, int **selected)
4791 struct tog_diff_view_state *s = &view->state.diff;
4793 *f = s->f;
4794 *nlines = s->nlines;
4795 *line_offsets = NULL;
4796 *match = &s->matched_line;
4797 *first = &s->first_displayed_line;
4798 *last = &s->last_displayed_line;
4799 *selected = &s->selected_line;
4802 static const struct got_error *
4803 search_next_view_match(struct tog_view *view)
4805 const struct got_error *err = NULL;
4806 FILE *f;
4807 int lineno;
4808 char *line = NULL;
4809 size_t linesize = 0;
4810 ssize_t linelen;
4811 off_t *line_offsets;
4812 size_t nlines = 0;
4813 int *first, *last, *match, *selected;
4815 if (!view->search_setup)
4816 return got_error_msg(GOT_ERR_NOT_IMPL,
4817 "view search not supported");
4818 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4819 &match, &selected);
4821 if (!view->searching) {
4822 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4823 return NULL;
4826 if (*match) {
4827 if (view->searching == TOG_SEARCH_FORWARD)
4828 lineno = *match + 1;
4829 else
4830 lineno = *match - 1;
4831 } else
4832 lineno = *first - 1 + *selected;
4834 while (1) {
4835 off_t offset;
4837 if (lineno <= 0 || lineno > nlines) {
4838 if (*match == 0) {
4839 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4840 break;
4843 if (view->searching == TOG_SEARCH_FORWARD)
4844 lineno = 1;
4845 else
4846 lineno = nlines;
4849 offset = view->type == TOG_VIEW_DIFF ?
4850 view->state.diff.lines[lineno - 1].offset :
4851 line_offsets[lineno - 1];
4852 if (fseeko(f, offset, SEEK_SET) != 0) {
4853 free(line);
4854 return got_error_from_errno("fseeko");
4856 linelen = getline(&line, &linesize, f);
4857 if (linelen != -1) {
4858 char *exstr;
4859 err = expand_tab(&exstr, line);
4860 if (err)
4861 break;
4862 if (match_line(exstr, &view->regex, 1,
4863 &view->regmatch)) {
4864 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4865 *match = lineno;
4866 free(exstr);
4867 break;
4869 free(exstr);
4871 if (view->searching == TOG_SEARCH_FORWARD)
4872 lineno++;
4873 else
4874 lineno--;
4876 free(line);
4878 if (*match) {
4879 *first = *match;
4880 *selected = 1;
4883 return err;
4886 static const struct got_error *
4887 close_diff_view(struct tog_view *view)
4889 const struct got_error *err = NULL;
4890 struct tog_diff_view_state *s = &view->state.diff;
4892 free(s->id1);
4893 s->id1 = NULL;
4894 free(s->id2);
4895 s->id2 = NULL;
4896 if (s->f && fclose(s->f) == EOF)
4897 err = got_error_from_errno("fclose");
4898 s->f = NULL;
4899 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4900 err = got_error_from_errno("fclose");
4901 s->f1 = NULL;
4902 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4903 err = got_error_from_errno("fclose");
4904 s->f2 = NULL;
4905 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4906 err = got_error_from_errno("close");
4907 s->fd1 = -1;
4908 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4909 err = got_error_from_errno("close");
4910 s->fd2 = -1;
4911 free(s->lines);
4912 s->lines = NULL;
4913 s->nlines = 0;
4914 return err;
4917 static const struct got_error *
4918 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4919 struct got_object_id *id2, const char *label1, const char *label2,
4920 int diff_context, int ignore_whitespace, int force_text_diff,
4921 struct tog_view *parent_view, struct got_repository *repo)
4923 const struct got_error *err;
4924 struct tog_diff_view_state *s = &view->state.diff;
4926 memset(s, 0, sizeof(*s));
4927 s->fd1 = -1;
4928 s->fd2 = -1;
4930 if (id1 != NULL && id2 != NULL) {
4931 int type1, type2;
4932 err = got_object_get_type(&type1, repo, id1);
4933 if (err)
4934 return err;
4935 err = got_object_get_type(&type2, repo, id2);
4936 if (err)
4937 return err;
4939 if (type1 != type2)
4940 return got_error(GOT_ERR_OBJ_TYPE);
4942 s->first_displayed_line = 1;
4943 s->last_displayed_line = view->nlines;
4944 s->selected_line = 1;
4945 s->repo = repo;
4946 s->id1 = id1;
4947 s->id2 = id2;
4948 s->label1 = label1;
4949 s->label2 = label2;
4951 if (id1) {
4952 s->id1 = got_object_id_dup(id1);
4953 if (s->id1 == NULL)
4954 return got_error_from_errno("got_object_id_dup");
4955 } else
4956 s->id1 = NULL;
4958 s->id2 = got_object_id_dup(id2);
4959 if (s->id2 == NULL) {
4960 err = got_error_from_errno("got_object_id_dup");
4961 goto done;
4964 s->f1 = got_opentemp();
4965 if (s->f1 == NULL) {
4966 err = got_error_from_errno("got_opentemp");
4967 goto done;
4970 s->f2 = got_opentemp();
4971 if (s->f2 == NULL) {
4972 err = got_error_from_errno("got_opentemp");
4973 goto done;
4976 s->fd1 = got_opentempfd();
4977 if (s->fd1 == -1) {
4978 err = got_error_from_errno("got_opentempfd");
4979 goto done;
4982 s->fd2 = got_opentempfd();
4983 if (s->fd2 == -1) {
4984 err = got_error_from_errno("got_opentempfd");
4985 goto done;
4988 s->first_displayed_line = 1;
4989 s->last_displayed_line = view->nlines;
4990 s->diff_context = diff_context;
4991 s->ignore_whitespace = ignore_whitespace;
4992 s->force_text_diff = force_text_diff;
4993 s->parent_view = parent_view;
4994 s->repo = repo;
4996 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4997 int rc;
4999 rc = init_pair(GOT_DIFF_LINE_MINUS,
5000 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5001 if (rc != ERR)
5002 rc = init_pair(GOT_DIFF_LINE_PLUS,
5003 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5004 if (rc != ERR)
5005 rc = init_pair(GOT_DIFF_LINE_HUNK,
5006 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5007 if (rc != ERR)
5008 rc = init_pair(GOT_DIFF_LINE_META,
5009 get_color_value("TOG_COLOR_DIFF_META"), -1);
5010 if (rc != ERR)
5011 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5012 get_color_value("TOG_COLOR_DIFF_META"), -1);
5013 if (rc != ERR)
5014 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5015 get_color_value("TOG_COLOR_DIFF_META"), -1);
5016 if (rc != ERR)
5017 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5018 get_color_value("TOG_COLOR_DIFF_META"), -1);
5019 if (rc != ERR)
5020 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5021 get_color_value("TOG_COLOR_AUTHOR"), -1);
5022 if (rc != ERR)
5023 rc = init_pair(GOT_DIFF_LINE_DATE,
5024 get_color_value("TOG_COLOR_DATE"), -1);
5025 if (rc == ERR) {
5026 err = got_error(GOT_ERR_RANGE);
5027 goto done;
5031 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5032 view_is_splitscreen(view))
5033 show_log_view(parent_view); /* draw border */
5034 diff_view_indicate_progress(view);
5036 err = create_diff(s);
5038 view->show = show_diff_view;
5039 view->input = input_diff_view;
5040 view->reset = reset_diff_view;
5041 view->close = close_diff_view;
5042 view->search_start = search_start_diff_view;
5043 view->search_setup = search_setup_diff_view;
5044 view->search_next = search_next_view_match;
5045 done:
5046 if (err)
5047 close_diff_view(view);
5048 return err;
5051 static const struct got_error *
5052 show_diff_view(struct tog_view *view)
5054 const struct got_error *err;
5055 struct tog_diff_view_state *s = &view->state.diff;
5056 char *id_str1 = NULL, *id_str2, *header;
5057 const char *label1, *label2;
5059 if (s->id1) {
5060 err = got_object_id_str(&id_str1, s->id1);
5061 if (err)
5062 return err;
5063 label1 = s->label1 ? s->label1 : id_str1;
5064 } else
5065 label1 = "/dev/null";
5067 err = got_object_id_str(&id_str2, s->id2);
5068 if (err)
5069 return err;
5070 label2 = s->label2 ? s->label2 : id_str2;
5072 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5073 err = got_error_from_errno("asprintf");
5074 free(id_str1);
5075 free(id_str2);
5076 return err;
5078 free(id_str1);
5079 free(id_str2);
5081 err = draw_file(view, header);
5082 free(header);
5083 return err;
5086 static const struct got_error *
5087 set_selected_commit(struct tog_diff_view_state *s,
5088 struct commit_queue_entry *entry)
5090 const struct got_error *err;
5091 const struct got_object_id_queue *parent_ids;
5092 struct got_commit_object *selected_commit;
5093 struct got_object_qid *pid;
5095 free(s->id2);
5096 s->id2 = got_object_id_dup(entry->id);
5097 if (s->id2 == NULL)
5098 return got_error_from_errno("got_object_id_dup");
5100 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5101 if (err)
5102 return err;
5103 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5104 free(s->id1);
5105 pid = STAILQ_FIRST(parent_ids);
5106 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5107 got_object_commit_close(selected_commit);
5108 return NULL;
5111 static const struct got_error *
5112 reset_diff_view(struct tog_view *view)
5114 struct tog_diff_view_state *s = &view->state.diff;
5116 view->count = 0;
5117 wclear(view->window);
5118 s->first_displayed_line = 1;
5119 s->last_displayed_line = view->nlines;
5120 s->matched_line = 0;
5121 diff_view_indicate_progress(view);
5122 return create_diff(s);
5125 static void
5126 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5128 int start, i;
5130 i = start = s->first_displayed_line - 1;
5132 while (s->lines[i].type != type) {
5133 if (i == 0)
5134 i = s->nlines - 1;
5135 if (--i == start)
5136 return; /* do nothing, requested type not in file */
5139 s->selected_line = 1;
5140 s->first_displayed_line = i;
5143 static void
5144 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5146 int start, i;
5148 i = start = s->first_displayed_line + 1;
5150 while (s->lines[i].type != type) {
5151 if (i == s->nlines - 1)
5152 i = 0;
5153 if (++i == start)
5154 return; /* do nothing, requested type not in file */
5157 s->selected_line = 1;
5158 s->first_displayed_line = i;
5161 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5162 int, int, int);
5163 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5164 int, int);
5166 static const struct got_error *
5167 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5169 const struct got_error *err = NULL;
5170 struct tog_diff_view_state *s = &view->state.diff;
5171 struct tog_log_view_state *ls;
5172 struct commit_queue_entry *old_selected_entry;
5173 char *line = NULL;
5174 size_t linesize = 0;
5175 ssize_t linelen;
5176 int i, nscroll = view->nlines - 1, up = 0;
5178 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5180 switch (ch) {
5181 case '0':
5182 view->x = 0;
5183 break;
5184 case '$':
5185 view->x = MAX(view->maxx - view->ncols / 3, 0);
5186 view->count = 0;
5187 break;
5188 case KEY_RIGHT:
5189 case 'l':
5190 if (view->x + view->ncols / 3 < view->maxx)
5191 view->x += 2; /* move two columns right */
5192 else
5193 view->count = 0;
5194 break;
5195 case KEY_LEFT:
5196 case 'h':
5197 view->x -= MIN(view->x, 2); /* move two columns back */
5198 if (view->x <= 0)
5199 view->count = 0;
5200 break;
5201 case 'a':
5202 case 'w':
5203 if (ch == 'a')
5204 s->force_text_diff = !s->force_text_diff;
5205 if (ch == 'w')
5206 s->ignore_whitespace = !s->ignore_whitespace;
5207 err = reset_diff_view(view);
5208 break;
5209 case 'g':
5210 case KEY_HOME:
5211 s->first_displayed_line = 1;
5212 view->count = 0;
5213 break;
5214 case 'G':
5215 case KEY_END:
5216 view->count = 0;
5217 if (s->eof)
5218 break;
5220 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5221 s->eof = 1;
5222 break;
5223 case 'k':
5224 case KEY_UP:
5225 case CTRL('p'):
5226 if (s->first_displayed_line > 1)
5227 s->first_displayed_line--;
5228 else
5229 view->count = 0;
5230 break;
5231 case CTRL('u'):
5232 case 'u':
5233 nscroll /= 2;
5234 /* FALL THROUGH */
5235 case KEY_PPAGE:
5236 case CTRL('b'):
5237 case 'b':
5238 if (s->first_displayed_line == 1) {
5239 view->count = 0;
5240 break;
5242 i = 0;
5243 while (i++ < nscroll && s->first_displayed_line > 1)
5244 s->first_displayed_line--;
5245 break;
5246 case 'j':
5247 case KEY_DOWN:
5248 case CTRL('n'):
5249 if (!s->eof)
5250 s->first_displayed_line++;
5251 else
5252 view->count = 0;
5253 break;
5254 case CTRL('d'):
5255 case 'd':
5256 nscroll /= 2;
5257 /* FALL THROUGH */
5258 case KEY_NPAGE:
5259 case CTRL('f'):
5260 case 'f':
5261 case ' ':
5262 if (s->eof) {
5263 view->count = 0;
5264 break;
5266 i = 0;
5267 while (!s->eof && i++ < nscroll) {
5268 linelen = getline(&line, &linesize, s->f);
5269 s->first_displayed_line++;
5270 if (linelen == -1) {
5271 if (feof(s->f)) {
5272 s->eof = 1;
5273 } else
5274 err = got_ferror(s->f, GOT_ERR_IO);
5275 break;
5278 free(line);
5279 break;
5280 case '(':
5281 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5282 break;
5283 case ')':
5284 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5285 break;
5286 case '{':
5287 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5288 break;
5289 case '}':
5290 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5291 break;
5292 case '[':
5293 if (s->diff_context > 0) {
5294 s->diff_context--;
5295 s->matched_line = 0;
5296 diff_view_indicate_progress(view);
5297 err = create_diff(s);
5298 if (s->first_displayed_line + view->nlines - 1 >
5299 s->nlines) {
5300 s->first_displayed_line = 1;
5301 s->last_displayed_line = view->nlines;
5303 } else
5304 view->count = 0;
5305 break;
5306 case ']':
5307 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5308 s->diff_context++;
5309 s->matched_line = 0;
5310 diff_view_indicate_progress(view);
5311 err = create_diff(s);
5312 } else
5313 view->count = 0;
5314 break;
5315 case '<':
5316 case ',':
5317 case 'K':
5318 up = 1;
5319 /* FALL THROUGH */
5320 case '>':
5321 case '.':
5322 case 'J':
5323 if (s->parent_view == NULL) {
5324 view->count = 0;
5325 break;
5327 s->parent_view->count = view->count;
5329 if (s->parent_view->type == TOG_VIEW_LOG) {
5330 ls = &s->parent_view->state.log;
5331 old_selected_entry = ls->selected_entry;
5333 err = input_log_view(NULL, s->parent_view,
5334 up ? KEY_UP : KEY_DOWN);
5335 if (err)
5336 break;
5337 view->count = s->parent_view->count;
5339 if (old_selected_entry == ls->selected_entry)
5340 break;
5342 err = set_selected_commit(s, ls->selected_entry);
5343 if (err)
5344 break;
5345 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5346 struct tog_blame_view_state *bs;
5347 struct got_object_id *id, *prev_id;
5349 bs = &s->parent_view->state.blame;
5350 prev_id = get_annotation_for_line(bs->blame.lines,
5351 bs->blame.nlines, bs->last_diffed_line);
5353 err = input_blame_view(&view, s->parent_view,
5354 up ? KEY_UP : KEY_DOWN);
5355 if (err)
5356 break;
5357 view->count = s->parent_view->count;
5359 if (prev_id == NULL)
5360 break;
5361 id = get_selected_commit_id(bs->blame.lines,
5362 bs->blame.nlines, bs->first_displayed_line,
5363 bs->selected_line);
5364 if (id == NULL)
5365 break;
5367 if (!got_object_id_cmp(prev_id, id))
5368 break;
5370 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5371 if (err)
5372 break;
5374 s->first_displayed_line = 1;
5375 s->last_displayed_line = view->nlines;
5376 s->matched_line = 0;
5377 view->x = 0;
5379 diff_view_indicate_progress(view);
5380 err = create_diff(s);
5381 break;
5382 default:
5383 view->count = 0;
5384 break;
5387 return err;
5390 static const struct got_error *
5391 cmd_diff(int argc, char *argv[])
5393 const struct got_error *error = NULL;
5394 struct got_repository *repo = NULL;
5395 struct got_worktree *worktree = NULL;
5396 struct got_object_id *id1 = NULL, *id2 = NULL;
5397 char *repo_path = NULL, *cwd = NULL;
5398 char *id_str1 = NULL, *id_str2 = NULL;
5399 char *label1 = NULL, *label2 = NULL;
5400 int diff_context = 3, ignore_whitespace = 0;
5401 int ch, force_text_diff = 0;
5402 const char *errstr;
5403 struct tog_view *view;
5404 int *pack_fds = NULL;
5406 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5407 switch (ch) {
5408 case 'a':
5409 force_text_diff = 1;
5410 break;
5411 case 'C':
5412 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5413 &errstr);
5414 if (errstr != NULL)
5415 errx(1, "number of context lines is %s: %s",
5416 errstr, errstr);
5417 break;
5418 case 'r':
5419 repo_path = realpath(optarg, NULL);
5420 if (repo_path == NULL)
5421 return got_error_from_errno2("realpath",
5422 optarg);
5423 got_path_strip_trailing_slashes(repo_path);
5424 break;
5425 case 'w':
5426 ignore_whitespace = 1;
5427 break;
5428 default:
5429 usage_diff();
5430 /* NOTREACHED */
5434 argc -= optind;
5435 argv += optind;
5437 if (argc == 0) {
5438 usage_diff(); /* TODO show local worktree changes */
5439 } else if (argc == 2) {
5440 id_str1 = argv[0];
5441 id_str2 = argv[1];
5442 } else
5443 usage_diff();
5445 error = got_repo_pack_fds_open(&pack_fds);
5446 if (error)
5447 goto done;
5449 if (repo_path == NULL) {
5450 cwd = getcwd(NULL, 0);
5451 if (cwd == NULL)
5452 return got_error_from_errno("getcwd");
5453 error = got_worktree_open(&worktree, cwd);
5454 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5455 goto done;
5456 if (worktree)
5457 repo_path =
5458 strdup(got_worktree_get_repo_path(worktree));
5459 else
5460 repo_path = strdup(cwd);
5461 if (repo_path == NULL) {
5462 error = got_error_from_errno("strdup");
5463 goto done;
5467 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5468 if (error)
5469 goto done;
5471 init_curses();
5473 error = apply_unveil(got_repo_get_path(repo), NULL);
5474 if (error)
5475 goto done;
5477 error = tog_load_refs(repo, 0);
5478 if (error)
5479 goto done;
5481 error = got_repo_match_object_id(&id1, &label1, id_str1,
5482 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5483 if (error)
5484 goto done;
5486 error = got_repo_match_object_id(&id2, &label2, id_str2,
5487 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5488 if (error)
5489 goto done;
5491 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5492 if (view == NULL) {
5493 error = got_error_from_errno("view_open");
5494 goto done;
5496 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5497 ignore_whitespace, force_text_diff, NULL, repo);
5498 if (error)
5499 goto done;
5500 error = view_loop(view);
5501 done:
5502 free(label1);
5503 free(label2);
5504 free(repo_path);
5505 free(cwd);
5506 if (repo) {
5507 const struct got_error *close_err = got_repo_close(repo);
5508 if (error == NULL)
5509 error = close_err;
5511 if (worktree)
5512 got_worktree_close(worktree);
5513 if (pack_fds) {
5514 const struct got_error *pack_err =
5515 got_repo_pack_fds_close(pack_fds);
5516 if (error == NULL)
5517 error = pack_err;
5519 tog_free_refs();
5520 return error;
5523 __dead static void
5524 usage_blame(void)
5526 endwin();
5527 fprintf(stderr,
5528 "usage: %s blame [-c commit] [-r repository-path] path\n",
5529 getprogname());
5530 exit(1);
5533 struct tog_blame_line {
5534 int annotated;
5535 struct got_object_id *id;
5538 static const struct got_error *
5539 draw_blame(struct tog_view *view)
5541 struct tog_blame_view_state *s = &view->state.blame;
5542 struct tog_blame *blame = &s->blame;
5543 regmatch_t *regmatch = &view->regmatch;
5544 const struct got_error *err;
5545 int lineno = 0, nprinted = 0;
5546 char *line = NULL;
5547 size_t linesize = 0;
5548 ssize_t linelen;
5549 wchar_t *wline;
5550 int width;
5551 struct tog_blame_line *blame_line;
5552 struct got_object_id *prev_id = NULL;
5553 char *id_str;
5554 struct tog_color *tc;
5556 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5557 if (err)
5558 return err;
5560 rewind(blame->f);
5561 werase(view->window);
5563 if (asprintf(&line, "commit %s", id_str) == -1) {
5564 err = got_error_from_errno("asprintf");
5565 free(id_str);
5566 return err;
5569 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5570 free(line);
5571 line = NULL;
5572 if (err)
5573 return err;
5574 if (view_needs_focus_indication(view))
5575 wstandout(view->window);
5576 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5577 if (tc)
5578 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5579 waddwstr(view->window, wline);
5580 while (width++ < view->ncols)
5581 waddch(view->window, ' ');
5582 if (tc)
5583 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5584 if (view_needs_focus_indication(view))
5585 wstandend(view->window);
5586 free(wline);
5587 wline = NULL;
5589 if (view->gline > blame->nlines)
5590 view->gline = blame->nlines;
5592 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5593 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5594 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5595 free(id_str);
5596 return got_error_from_errno("asprintf");
5598 free(id_str);
5599 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5600 free(line);
5601 line = NULL;
5602 if (err)
5603 return err;
5604 waddwstr(view->window, wline);
5605 free(wline);
5606 wline = NULL;
5607 if (width < view->ncols - 1)
5608 waddch(view->window, '\n');
5610 s->eof = 0;
5611 view->maxx = 0;
5612 while (nprinted < view->nlines - 2) {
5613 linelen = getline(&line, &linesize, blame->f);
5614 if (linelen == -1) {
5615 if (feof(blame->f)) {
5616 s->eof = 1;
5617 break;
5619 free(line);
5620 return got_ferror(blame->f, GOT_ERR_IO);
5622 if (++lineno < s->first_displayed_line)
5623 continue;
5624 if (view->gline && !gotoline(view, &lineno, &nprinted))
5625 continue;
5627 /* Set view->maxx based on full line length. */
5628 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5629 if (err) {
5630 free(line);
5631 return err;
5633 free(wline);
5634 wline = NULL;
5635 view->maxx = MAX(view->maxx, width);
5637 if (nprinted == s->selected_line - 1)
5638 wstandout(view->window);
5640 if (blame->nlines > 0) {
5641 blame_line = &blame->lines[lineno - 1];
5642 if (blame_line->annotated && prev_id &&
5643 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5644 !(nprinted == s->selected_line - 1)) {
5645 waddstr(view->window, " ");
5646 } else if (blame_line->annotated) {
5647 char *id_str;
5648 err = got_object_id_str(&id_str,
5649 blame_line->id);
5650 if (err) {
5651 free(line);
5652 return err;
5654 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5655 if (tc)
5656 wattr_on(view->window,
5657 COLOR_PAIR(tc->colorpair), NULL);
5658 wprintw(view->window, "%.8s", id_str);
5659 if (tc)
5660 wattr_off(view->window,
5661 COLOR_PAIR(tc->colorpair), NULL);
5662 free(id_str);
5663 prev_id = blame_line->id;
5664 } else {
5665 waddstr(view->window, "........");
5666 prev_id = NULL;
5668 } else {
5669 waddstr(view->window, "........");
5670 prev_id = NULL;
5673 if (nprinted == s->selected_line - 1)
5674 wstandend(view->window);
5675 waddstr(view->window, " ");
5677 if (view->ncols <= 9) {
5678 width = 9;
5679 } else if (s->first_displayed_line + nprinted ==
5680 s->matched_line &&
5681 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5682 err = add_matched_line(&width, line, view->ncols - 9, 9,
5683 view->window, view->x, regmatch);
5684 if (err) {
5685 free(line);
5686 return err;
5688 width += 9;
5689 } else {
5690 int skip;
5691 err = format_line(&wline, &width, &skip, line,
5692 view->x, view->ncols - 9, 9, 1);
5693 if (err) {
5694 free(line);
5695 return err;
5697 waddwstr(view->window, &wline[skip]);
5698 width += 9;
5699 free(wline);
5700 wline = NULL;
5703 if (width <= view->ncols - 1)
5704 waddch(view->window, '\n');
5705 if (++nprinted == 1)
5706 s->first_displayed_line = lineno;
5708 free(line);
5709 s->last_displayed_line = lineno;
5711 view_border(view);
5713 return NULL;
5716 static const struct got_error *
5717 blame_cb(void *arg, int nlines, int lineno,
5718 struct got_commit_object *commit, struct got_object_id *id)
5720 const struct got_error *err = NULL;
5721 struct tog_blame_cb_args *a = arg;
5722 struct tog_blame_line *line;
5723 int errcode;
5725 if (nlines != a->nlines ||
5726 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5727 return got_error(GOT_ERR_RANGE);
5729 errcode = pthread_mutex_lock(&tog_mutex);
5730 if (errcode)
5731 return got_error_set_errno(errcode, "pthread_mutex_lock");
5733 if (*a->quit) { /* user has quit the blame view */
5734 err = got_error(GOT_ERR_ITER_COMPLETED);
5735 goto done;
5738 if (lineno == -1)
5739 goto done; /* no change in this commit */
5741 line = &a->lines[lineno - 1];
5742 if (line->annotated)
5743 goto done;
5745 line->id = got_object_id_dup(id);
5746 if (line->id == NULL) {
5747 err = got_error_from_errno("got_object_id_dup");
5748 goto done;
5750 line->annotated = 1;
5751 done:
5752 errcode = pthread_mutex_unlock(&tog_mutex);
5753 if (errcode)
5754 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5755 return err;
5758 static void *
5759 blame_thread(void *arg)
5761 const struct got_error *err, *close_err;
5762 struct tog_blame_thread_args *ta = arg;
5763 struct tog_blame_cb_args *a = ta->cb_args;
5764 int errcode, fd1 = -1, fd2 = -1;
5765 FILE *f1 = NULL, *f2 = NULL;
5767 fd1 = got_opentempfd();
5768 if (fd1 == -1)
5769 return (void *)got_error_from_errno("got_opentempfd");
5771 fd2 = got_opentempfd();
5772 if (fd2 == -1) {
5773 err = got_error_from_errno("got_opentempfd");
5774 goto done;
5777 f1 = got_opentemp();
5778 if (f1 == NULL) {
5779 err = (void *)got_error_from_errno("got_opentemp");
5780 goto done;
5782 f2 = got_opentemp();
5783 if (f2 == NULL) {
5784 err = (void *)got_error_from_errno("got_opentemp");
5785 goto done;
5788 err = block_signals_used_by_main_thread();
5789 if (err)
5790 goto done;
5792 err = got_blame(ta->path, a->commit_id, ta->repo,
5793 tog_diff_algo, blame_cb, ta->cb_args,
5794 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5795 if (err && err->code == GOT_ERR_CANCELLED)
5796 err = NULL;
5798 errcode = pthread_mutex_lock(&tog_mutex);
5799 if (errcode) {
5800 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5801 goto done;
5804 close_err = got_repo_close(ta->repo);
5805 if (err == NULL)
5806 err = close_err;
5807 ta->repo = NULL;
5808 *ta->complete = 1;
5810 errcode = pthread_mutex_unlock(&tog_mutex);
5811 if (errcode && err == NULL)
5812 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5814 done:
5815 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5816 err = got_error_from_errno("close");
5817 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5818 err = got_error_from_errno("close");
5819 if (f1 && fclose(f1) == EOF && err == NULL)
5820 err = got_error_from_errno("fclose");
5821 if (f2 && fclose(f2) == EOF && err == NULL)
5822 err = got_error_from_errno("fclose");
5824 return (void *)err;
5827 static struct got_object_id *
5828 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5829 int first_displayed_line, int selected_line)
5831 struct tog_blame_line *line;
5833 if (nlines <= 0)
5834 return NULL;
5836 line = &lines[first_displayed_line - 1 + selected_line - 1];
5837 if (!line->annotated)
5838 return NULL;
5840 return line->id;
5843 static struct got_object_id *
5844 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5845 int lineno)
5847 struct tog_blame_line *line;
5849 if (nlines <= 0 || lineno >= nlines)
5850 return NULL;
5852 line = &lines[lineno - 1];
5853 if (!line->annotated)
5854 return NULL;
5856 return line->id;
5859 static const struct got_error *
5860 stop_blame(struct tog_blame *blame)
5862 const struct got_error *err = NULL;
5863 int i;
5865 if (blame->thread) {
5866 int errcode;
5867 errcode = pthread_mutex_unlock(&tog_mutex);
5868 if (errcode)
5869 return got_error_set_errno(errcode,
5870 "pthread_mutex_unlock");
5871 errcode = pthread_join(blame->thread, (void **)&err);
5872 if (errcode)
5873 return got_error_set_errno(errcode, "pthread_join");
5874 errcode = pthread_mutex_lock(&tog_mutex);
5875 if (errcode)
5876 return got_error_set_errno(errcode,
5877 "pthread_mutex_lock");
5878 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5879 err = NULL;
5880 blame->thread = 0; //NULL;
5882 if (blame->thread_args.repo) {
5883 const struct got_error *close_err;
5884 close_err = got_repo_close(blame->thread_args.repo);
5885 if (err == NULL)
5886 err = close_err;
5887 blame->thread_args.repo = NULL;
5889 if (blame->f) {
5890 if (fclose(blame->f) == EOF && err == NULL)
5891 err = got_error_from_errno("fclose");
5892 blame->f = NULL;
5894 if (blame->lines) {
5895 for (i = 0; i < blame->nlines; i++)
5896 free(blame->lines[i].id);
5897 free(blame->lines);
5898 blame->lines = NULL;
5900 free(blame->cb_args.commit_id);
5901 blame->cb_args.commit_id = NULL;
5902 if (blame->pack_fds) {
5903 const struct got_error *pack_err =
5904 got_repo_pack_fds_close(blame->pack_fds);
5905 if (err == NULL)
5906 err = pack_err;
5907 blame->pack_fds = NULL;
5909 return err;
5912 static const struct got_error *
5913 cancel_blame_view(void *arg)
5915 const struct got_error *err = NULL;
5916 int *done = arg;
5917 int errcode;
5919 errcode = pthread_mutex_lock(&tog_mutex);
5920 if (errcode)
5921 return got_error_set_errno(errcode,
5922 "pthread_mutex_unlock");
5924 if (*done)
5925 err = got_error(GOT_ERR_CANCELLED);
5927 errcode = pthread_mutex_unlock(&tog_mutex);
5928 if (errcode)
5929 return got_error_set_errno(errcode,
5930 "pthread_mutex_lock");
5932 return err;
5935 static const struct got_error *
5936 run_blame(struct tog_view *view)
5938 struct tog_blame_view_state *s = &view->state.blame;
5939 struct tog_blame *blame = &s->blame;
5940 const struct got_error *err = NULL;
5941 struct got_commit_object *commit = NULL;
5942 struct got_blob_object *blob = NULL;
5943 struct got_repository *thread_repo = NULL;
5944 struct got_object_id *obj_id = NULL;
5945 int obj_type, fd = -1;
5946 int *pack_fds = NULL;
5948 err = got_object_open_as_commit(&commit, s->repo,
5949 &s->blamed_commit->id);
5950 if (err)
5951 return err;
5953 fd = got_opentempfd();
5954 if (fd == -1) {
5955 err = got_error_from_errno("got_opentempfd");
5956 goto done;
5959 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5960 if (err)
5961 goto done;
5963 err = got_object_get_type(&obj_type, s->repo, obj_id);
5964 if (err)
5965 goto done;
5967 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5968 err = got_error(GOT_ERR_OBJ_TYPE);
5969 goto done;
5972 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5973 if (err)
5974 goto done;
5975 blame->f = got_opentemp();
5976 if (blame->f == NULL) {
5977 err = got_error_from_errno("got_opentemp");
5978 goto done;
5980 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5981 &blame->line_offsets, blame->f, blob);
5982 if (err)
5983 goto done;
5984 if (blame->nlines == 0) {
5985 s->blame_complete = 1;
5986 goto done;
5989 /* Don't include \n at EOF in the blame line count. */
5990 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5991 blame->nlines--;
5993 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5994 if (blame->lines == NULL) {
5995 err = got_error_from_errno("calloc");
5996 goto done;
5999 err = got_repo_pack_fds_open(&pack_fds);
6000 if (err)
6001 goto done;
6002 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6003 pack_fds);
6004 if (err)
6005 goto done;
6007 blame->pack_fds = pack_fds;
6008 blame->cb_args.view = view;
6009 blame->cb_args.lines = blame->lines;
6010 blame->cb_args.nlines = blame->nlines;
6011 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6012 if (blame->cb_args.commit_id == NULL) {
6013 err = got_error_from_errno("got_object_id_dup");
6014 goto done;
6016 blame->cb_args.quit = &s->done;
6018 blame->thread_args.path = s->path;
6019 blame->thread_args.repo = thread_repo;
6020 blame->thread_args.cb_args = &blame->cb_args;
6021 blame->thread_args.complete = &s->blame_complete;
6022 blame->thread_args.cancel_cb = cancel_blame_view;
6023 blame->thread_args.cancel_arg = &s->done;
6024 s->blame_complete = 0;
6026 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6027 s->first_displayed_line = 1;
6028 s->last_displayed_line = view->nlines;
6029 s->selected_line = 1;
6031 s->matched_line = 0;
6033 done:
6034 if (commit)
6035 got_object_commit_close(commit);
6036 if (fd != -1 && close(fd) == -1 && err == NULL)
6037 err = got_error_from_errno("close");
6038 if (blob)
6039 got_object_blob_close(blob);
6040 free(obj_id);
6041 if (err)
6042 stop_blame(blame);
6043 return err;
6046 static const struct got_error *
6047 open_blame_view(struct tog_view *view, char *path,
6048 struct got_object_id *commit_id, struct got_repository *repo)
6050 const struct got_error *err = NULL;
6051 struct tog_blame_view_state *s = &view->state.blame;
6053 STAILQ_INIT(&s->blamed_commits);
6055 s->path = strdup(path);
6056 if (s->path == NULL)
6057 return got_error_from_errno("strdup");
6059 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6060 if (err) {
6061 free(s->path);
6062 return err;
6065 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6066 s->first_displayed_line = 1;
6067 s->last_displayed_line = view->nlines;
6068 s->selected_line = 1;
6069 s->blame_complete = 0;
6070 s->repo = repo;
6071 s->commit_id = commit_id;
6072 memset(&s->blame, 0, sizeof(s->blame));
6074 STAILQ_INIT(&s->colors);
6075 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6076 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6077 get_color_value("TOG_COLOR_COMMIT"));
6078 if (err)
6079 return err;
6082 view->show = show_blame_view;
6083 view->input = input_blame_view;
6084 view->reset = reset_blame_view;
6085 view->close = close_blame_view;
6086 view->search_start = search_start_blame_view;
6087 view->search_setup = search_setup_blame_view;
6088 view->search_next = search_next_view_match;
6090 return run_blame(view);
6093 static const struct got_error *
6094 close_blame_view(struct tog_view *view)
6096 const struct got_error *err = NULL;
6097 struct tog_blame_view_state *s = &view->state.blame;
6099 if (s->blame.thread)
6100 err = stop_blame(&s->blame);
6102 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6103 struct got_object_qid *blamed_commit;
6104 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6105 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6106 got_object_qid_free(blamed_commit);
6109 free(s->path);
6110 free_colors(&s->colors);
6111 return err;
6114 static const struct got_error *
6115 search_start_blame_view(struct tog_view *view)
6117 struct tog_blame_view_state *s = &view->state.blame;
6119 s->matched_line = 0;
6120 return NULL;
6123 static void
6124 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6125 size_t *nlines, int **first, int **last, int **match, int **selected)
6127 struct tog_blame_view_state *s = &view->state.blame;
6129 *f = s->blame.f;
6130 *nlines = s->blame.nlines;
6131 *line_offsets = s->blame.line_offsets;
6132 *match = &s->matched_line;
6133 *first = &s->first_displayed_line;
6134 *last = &s->last_displayed_line;
6135 *selected = &s->selected_line;
6138 static const struct got_error *
6139 show_blame_view(struct tog_view *view)
6141 const struct got_error *err = NULL;
6142 struct tog_blame_view_state *s = &view->state.blame;
6143 int errcode;
6145 if (s->blame.thread == 0 && !s->blame_complete) {
6146 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6147 &s->blame.thread_args);
6148 if (errcode)
6149 return got_error_set_errno(errcode, "pthread_create");
6151 halfdelay(1); /* fast refresh while annotating */
6154 if (s->blame_complete)
6155 halfdelay(10); /* disable fast refresh */
6157 err = draw_blame(view);
6159 view_border(view);
6160 return err;
6163 static const struct got_error *
6164 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6165 struct got_repository *repo, struct got_object_id *id)
6167 struct tog_view *log_view;
6168 const struct got_error *err = NULL;
6170 *new_view = NULL;
6172 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6173 if (log_view == NULL)
6174 return got_error_from_errno("view_open");
6176 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6177 if (err)
6178 view_close(log_view);
6179 else
6180 *new_view = log_view;
6182 return err;
6185 static const struct got_error *
6186 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6188 const struct got_error *err = NULL, *thread_err = NULL;
6189 struct tog_view *diff_view;
6190 struct tog_blame_view_state *s = &view->state.blame;
6191 int eos, nscroll, begin_y = 0, begin_x = 0;
6193 eos = nscroll = view->nlines - 2;
6194 if (view_is_hsplit_top(view))
6195 --eos; /* border */
6197 switch (ch) {
6198 case '0':
6199 view->x = 0;
6200 break;
6201 case '$':
6202 view->x = MAX(view->maxx - view->ncols / 3, 0);
6203 view->count = 0;
6204 break;
6205 case KEY_RIGHT:
6206 case 'l':
6207 if (view->x + view->ncols / 3 < view->maxx)
6208 view->x += 2; /* move two columns right */
6209 else
6210 view->count = 0;
6211 break;
6212 case KEY_LEFT:
6213 case 'h':
6214 view->x -= MIN(view->x, 2); /* move two columns back */
6215 if (view->x <= 0)
6216 view->count = 0;
6217 break;
6218 case 'q':
6219 s->done = 1;
6220 break;
6221 case 'g':
6222 case KEY_HOME:
6223 s->selected_line = 1;
6224 s->first_displayed_line = 1;
6225 view->count = 0;
6226 break;
6227 case 'G':
6228 case KEY_END:
6229 if (s->blame.nlines < eos) {
6230 s->selected_line = s->blame.nlines;
6231 s->first_displayed_line = 1;
6232 } else {
6233 s->selected_line = eos;
6234 s->first_displayed_line = s->blame.nlines - (eos - 1);
6236 view->count = 0;
6237 break;
6238 case 'k':
6239 case KEY_UP:
6240 case CTRL('p'):
6241 if (s->selected_line > 1)
6242 s->selected_line--;
6243 else if (s->selected_line == 1 &&
6244 s->first_displayed_line > 1)
6245 s->first_displayed_line--;
6246 else
6247 view->count = 0;
6248 break;
6249 case CTRL('u'):
6250 case 'u':
6251 nscroll /= 2;
6252 /* FALL THROUGH */
6253 case KEY_PPAGE:
6254 case CTRL('b'):
6255 case 'b':
6256 if (s->first_displayed_line == 1) {
6257 if (view->count > 1)
6258 nscroll += nscroll;
6259 s->selected_line = MAX(1, s->selected_line - nscroll);
6260 view->count = 0;
6261 break;
6263 if (s->first_displayed_line > nscroll)
6264 s->first_displayed_line -= nscroll;
6265 else
6266 s->first_displayed_line = 1;
6267 break;
6268 case 'j':
6269 case KEY_DOWN:
6270 case CTRL('n'):
6271 if (s->selected_line < eos && s->first_displayed_line +
6272 s->selected_line <= s->blame.nlines)
6273 s->selected_line++;
6274 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6275 s->first_displayed_line++;
6276 else
6277 view->count = 0;
6278 break;
6279 case 'c':
6280 case 'p': {
6281 struct got_object_id *id = NULL;
6283 view->count = 0;
6284 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6285 s->first_displayed_line, s->selected_line);
6286 if (id == NULL)
6287 break;
6288 if (ch == 'p') {
6289 struct got_commit_object *commit, *pcommit;
6290 struct got_object_qid *pid;
6291 struct got_object_id *blob_id = NULL;
6292 int obj_type;
6293 err = got_object_open_as_commit(&commit,
6294 s->repo, id);
6295 if (err)
6296 break;
6297 pid = STAILQ_FIRST(
6298 got_object_commit_get_parent_ids(commit));
6299 if (pid == NULL) {
6300 got_object_commit_close(commit);
6301 break;
6303 /* Check if path history ends here. */
6304 err = got_object_open_as_commit(&pcommit,
6305 s->repo, &pid->id);
6306 if (err)
6307 break;
6308 err = got_object_id_by_path(&blob_id, s->repo,
6309 pcommit, s->path);
6310 got_object_commit_close(pcommit);
6311 if (err) {
6312 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6313 err = NULL;
6314 got_object_commit_close(commit);
6315 break;
6317 err = got_object_get_type(&obj_type, s->repo,
6318 blob_id);
6319 free(blob_id);
6320 /* Can't blame non-blob type objects. */
6321 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6322 got_object_commit_close(commit);
6323 break;
6325 err = got_object_qid_alloc(&s->blamed_commit,
6326 &pid->id);
6327 got_object_commit_close(commit);
6328 } else {
6329 if (got_object_id_cmp(id,
6330 &s->blamed_commit->id) == 0)
6331 break;
6332 err = got_object_qid_alloc(&s->blamed_commit,
6333 id);
6335 if (err)
6336 break;
6337 s->done = 1;
6338 thread_err = stop_blame(&s->blame);
6339 s->done = 0;
6340 if (thread_err)
6341 break;
6342 STAILQ_INSERT_HEAD(&s->blamed_commits,
6343 s->blamed_commit, entry);
6344 err = run_blame(view);
6345 if (err)
6346 break;
6347 break;
6349 case 'C': {
6350 struct got_object_qid *first;
6352 view->count = 0;
6353 first = STAILQ_FIRST(&s->blamed_commits);
6354 if (!got_object_id_cmp(&first->id, s->commit_id))
6355 break;
6356 s->done = 1;
6357 thread_err = stop_blame(&s->blame);
6358 s->done = 0;
6359 if (thread_err)
6360 break;
6361 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6362 got_object_qid_free(s->blamed_commit);
6363 s->blamed_commit =
6364 STAILQ_FIRST(&s->blamed_commits);
6365 err = run_blame(view);
6366 if (err)
6367 break;
6368 break;
6370 case 'L':
6371 view->count = 0;
6372 s->id_to_log = get_selected_commit_id(s->blame.lines,
6373 s->blame.nlines, s->first_displayed_line, s->selected_line);
6374 if (s->id_to_log)
6375 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6376 break;
6377 case KEY_ENTER:
6378 case '\r': {
6379 struct got_object_id *id = NULL;
6380 struct got_object_qid *pid;
6381 struct got_commit_object *commit = NULL;
6383 view->count = 0;
6384 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6385 s->first_displayed_line, s->selected_line);
6386 if (id == NULL)
6387 break;
6388 err = got_object_open_as_commit(&commit, s->repo, id);
6389 if (err)
6390 break;
6391 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6392 if (*new_view) {
6393 /* traversed from diff view, release diff resources */
6394 err = close_diff_view(*new_view);
6395 if (err)
6396 break;
6397 diff_view = *new_view;
6398 } else {
6399 if (view_is_parent_view(view))
6400 view_get_split(view, &begin_y, &begin_x);
6402 diff_view = view_open(0, 0, begin_y, begin_x,
6403 TOG_VIEW_DIFF);
6404 if (diff_view == NULL) {
6405 got_object_commit_close(commit);
6406 err = got_error_from_errno("view_open");
6407 break;
6410 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6411 id, NULL, NULL, 3, 0, 0, view, s->repo);
6412 got_object_commit_close(commit);
6413 if (err) {
6414 view_close(diff_view);
6415 break;
6417 s->last_diffed_line = s->first_displayed_line - 1 +
6418 s->selected_line;
6419 if (*new_view)
6420 break; /* still open from active diff view */
6421 if (view_is_parent_view(view) &&
6422 view->mode == TOG_VIEW_SPLIT_HRZN) {
6423 err = view_init_hsplit(view, begin_y);
6424 if (err)
6425 break;
6428 view->focussed = 0;
6429 diff_view->focussed = 1;
6430 diff_view->mode = view->mode;
6431 diff_view->nlines = view->lines - begin_y;
6432 if (view_is_parent_view(view)) {
6433 view_transfer_size(diff_view, view);
6434 err = view_close_child(view);
6435 if (err)
6436 break;
6437 err = view_set_child(view, diff_view);
6438 if (err)
6439 break;
6440 view->focus_child = 1;
6441 } else
6442 *new_view = diff_view;
6443 if (err)
6444 break;
6445 break;
6447 case CTRL('d'):
6448 case 'd':
6449 nscroll /= 2;
6450 /* FALL THROUGH */
6451 case KEY_NPAGE:
6452 case CTRL('f'):
6453 case 'f':
6454 case ' ':
6455 if (s->last_displayed_line >= s->blame.nlines &&
6456 s->selected_line >= MIN(s->blame.nlines,
6457 view->nlines - 2)) {
6458 view->count = 0;
6459 break;
6461 if (s->last_displayed_line >= s->blame.nlines &&
6462 s->selected_line < view->nlines - 2) {
6463 s->selected_line +=
6464 MIN(nscroll, s->last_displayed_line -
6465 s->first_displayed_line - s->selected_line + 1);
6467 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6468 s->first_displayed_line += nscroll;
6469 else
6470 s->first_displayed_line =
6471 s->blame.nlines - (view->nlines - 3);
6472 break;
6473 case KEY_RESIZE:
6474 if (s->selected_line > view->nlines - 2) {
6475 s->selected_line = MIN(s->blame.nlines,
6476 view->nlines - 2);
6478 break;
6479 default:
6480 view->count = 0;
6481 break;
6483 return thread_err ? thread_err : err;
6486 static const struct got_error *
6487 reset_blame_view(struct tog_view *view)
6489 const struct got_error *err;
6490 struct tog_blame_view_state *s = &view->state.blame;
6492 view->count = 0;
6493 s->done = 1;
6494 err = stop_blame(&s->blame);
6495 s->done = 0;
6496 if (err)
6497 return err;
6498 return run_blame(view);
6501 static const struct got_error *
6502 cmd_blame(int argc, char *argv[])
6504 const struct got_error *error;
6505 struct got_repository *repo = NULL;
6506 struct got_worktree *worktree = NULL;
6507 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6508 char *link_target = NULL;
6509 struct got_object_id *commit_id = NULL;
6510 struct got_commit_object *commit = NULL;
6511 char *commit_id_str = NULL;
6512 int ch;
6513 struct tog_view *view;
6514 int *pack_fds = NULL;
6516 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6517 switch (ch) {
6518 case 'c':
6519 commit_id_str = optarg;
6520 break;
6521 case 'r':
6522 repo_path = realpath(optarg, NULL);
6523 if (repo_path == NULL)
6524 return got_error_from_errno2("realpath",
6525 optarg);
6526 break;
6527 default:
6528 usage_blame();
6529 /* NOTREACHED */
6533 argc -= optind;
6534 argv += optind;
6536 if (argc != 1)
6537 usage_blame();
6539 error = got_repo_pack_fds_open(&pack_fds);
6540 if (error != NULL)
6541 goto done;
6543 if (repo_path == NULL) {
6544 cwd = getcwd(NULL, 0);
6545 if (cwd == NULL)
6546 return got_error_from_errno("getcwd");
6547 error = got_worktree_open(&worktree, cwd);
6548 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6549 goto done;
6550 if (worktree)
6551 repo_path =
6552 strdup(got_worktree_get_repo_path(worktree));
6553 else
6554 repo_path = strdup(cwd);
6555 if (repo_path == NULL) {
6556 error = got_error_from_errno("strdup");
6557 goto done;
6561 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6562 if (error != NULL)
6563 goto done;
6565 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6566 worktree);
6567 if (error)
6568 goto done;
6570 init_curses();
6572 error = apply_unveil(got_repo_get_path(repo), NULL);
6573 if (error)
6574 goto done;
6576 error = tog_load_refs(repo, 0);
6577 if (error)
6578 goto done;
6580 if (commit_id_str == NULL) {
6581 struct got_reference *head_ref;
6582 error = got_ref_open(&head_ref, repo, worktree ?
6583 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6584 if (error != NULL)
6585 goto done;
6586 error = got_ref_resolve(&commit_id, repo, head_ref);
6587 got_ref_close(head_ref);
6588 } else {
6589 error = got_repo_match_object_id(&commit_id, NULL,
6590 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6592 if (error != NULL)
6593 goto done;
6595 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6596 if (view == NULL) {
6597 error = got_error_from_errno("view_open");
6598 goto done;
6601 error = got_object_open_as_commit(&commit, repo, commit_id);
6602 if (error)
6603 goto done;
6605 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6606 commit, repo);
6607 if (error)
6608 goto done;
6610 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6611 commit_id, repo);
6612 if (error)
6613 goto done;
6614 if (worktree) {
6615 /* Release work tree lock. */
6616 got_worktree_close(worktree);
6617 worktree = NULL;
6619 error = view_loop(view);
6620 done:
6621 free(repo_path);
6622 free(in_repo_path);
6623 free(link_target);
6624 free(cwd);
6625 free(commit_id);
6626 if (commit)
6627 got_object_commit_close(commit);
6628 if (worktree)
6629 got_worktree_close(worktree);
6630 if (repo) {
6631 const struct got_error *close_err = got_repo_close(repo);
6632 if (error == NULL)
6633 error = close_err;
6635 if (pack_fds) {
6636 const struct got_error *pack_err =
6637 got_repo_pack_fds_close(pack_fds);
6638 if (error == NULL)
6639 error = pack_err;
6641 tog_free_refs();
6642 return error;
6645 static const struct got_error *
6646 draw_tree_entries(struct tog_view *view, const char *parent_path)
6648 struct tog_tree_view_state *s = &view->state.tree;
6649 const struct got_error *err = NULL;
6650 struct got_tree_entry *te;
6651 wchar_t *wline;
6652 char *index = NULL;
6653 struct tog_color *tc;
6654 int width, n, nentries, i = 1;
6655 int limit = view->nlines;
6657 s->ndisplayed = 0;
6658 if (view_is_hsplit_top(view))
6659 --limit; /* border */
6661 werase(view->window);
6663 if (limit == 0)
6664 return NULL;
6666 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6667 0, 0);
6668 if (err)
6669 return err;
6670 if (view_needs_focus_indication(view))
6671 wstandout(view->window);
6672 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6673 if (tc)
6674 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6675 waddwstr(view->window, wline);
6676 free(wline);
6677 wline = NULL;
6678 while (width++ < view->ncols)
6679 waddch(view->window, ' ');
6680 if (tc)
6681 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6682 if (view_needs_focus_indication(view))
6683 wstandend(view->window);
6684 if (--limit <= 0)
6685 return NULL;
6687 i += s->selected;
6688 if (s->first_displayed_entry) {
6689 i += got_tree_entry_get_index(s->first_displayed_entry);
6690 if (s->tree != s->root)
6691 ++i; /* account for ".." entry */
6693 nentries = got_object_tree_get_nentries(s->tree);
6694 if (asprintf(&index, "[%d/%d] %s",
6695 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6696 return got_error_from_errno("asprintf");
6697 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6698 free(index);
6699 if (err)
6700 return err;
6701 waddwstr(view->window, wline);
6702 free(wline);
6703 wline = NULL;
6704 if (width < view->ncols - 1)
6705 waddch(view->window, '\n');
6706 if (--limit <= 0)
6707 return NULL;
6708 waddch(view->window, '\n');
6709 if (--limit <= 0)
6710 return NULL;
6712 if (s->first_displayed_entry == NULL) {
6713 te = got_object_tree_get_first_entry(s->tree);
6714 if (s->selected == 0) {
6715 if (view->focussed)
6716 wstandout(view->window);
6717 s->selected_entry = NULL;
6719 waddstr(view->window, " ..\n"); /* parent directory */
6720 if (s->selected == 0 && view->focussed)
6721 wstandend(view->window);
6722 s->ndisplayed++;
6723 if (--limit <= 0)
6724 return NULL;
6725 n = 1;
6726 } else {
6727 n = 0;
6728 te = s->first_displayed_entry;
6731 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6732 char *line = NULL, *id_str = NULL, *link_target = NULL;
6733 const char *modestr = "";
6734 mode_t mode;
6736 te = got_object_tree_get_entry(s->tree, i);
6737 mode = got_tree_entry_get_mode(te);
6739 if (s->show_ids) {
6740 err = got_object_id_str(&id_str,
6741 got_tree_entry_get_id(te));
6742 if (err)
6743 return got_error_from_errno(
6744 "got_object_id_str");
6746 if (got_object_tree_entry_is_submodule(te))
6747 modestr = "$";
6748 else if (S_ISLNK(mode)) {
6749 int i;
6751 err = got_tree_entry_get_symlink_target(&link_target,
6752 te, s->repo);
6753 if (err) {
6754 free(id_str);
6755 return err;
6757 for (i = 0; i < strlen(link_target); i++) {
6758 if (!isprint((unsigned char)link_target[i]))
6759 link_target[i] = '?';
6761 modestr = "@";
6763 else if (S_ISDIR(mode))
6764 modestr = "/";
6765 else if (mode & S_IXUSR)
6766 modestr = "*";
6767 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6768 got_tree_entry_get_name(te), modestr,
6769 link_target ? " -> ": "",
6770 link_target ? link_target : "") == -1) {
6771 free(id_str);
6772 free(link_target);
6773 return got_error_from_errno("asprintf");
6775 free(id_str);
6776 free(link_target);
6777 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6778 0, 0);
6779 if (err) {
6780 free(line);
6781 break;
6783 if (n == s->selected) {
6784 if (view->focussed)
6785 wstandout(view->window);
6786 s->selected_entry = te;
6788 tc = match_color(&s->colors, line);
6789 if (tc)
6790 wattr_on(view->window,
6791 COLOR_PAIR(tc->colorpair), NULL);
6792 waddwstr(view->window, wline);
6793 if (tc)
6794 wattr_off(view->window,
6795 COLOR_PAIR(tc->colorpair), NULL);
6796 if (width < view->ncols - 1)
6797 waddch(view->window, '\n');
6798 if (n == s->selected && view->focussed)
6799 wstandend(view->window);
6800 free(line);
6801 free(wline);
6802 wline = NULL;
6803 n++;
6804 s->ndisplayed++;
6805 s->last_displayed_entry = te;
6806 if (--limit <= 0)
6807 break;
6810 return err;
6813 static void
6814 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6816 struct got_tree_entry *te;
6817 int isroot = s->tree == s->root;
6818 int i = 0;
6820 if (s->first_displayed_entry == NULL)
6821 return;
6823 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6824 while (i++ < maxscroll) {
6825 if (te == NULL) {
6826 if (!isroot)
6827 s->first_displayed_entry = NULL;
6828 break;
6830 s->first_displayed_entry = te;
6831 te = got_tree_entry_get_prev(s->tree, te);
6835 static const struct got_error *
6836 tree_scroll_down(struct tog_view *view, int maxscroll)
6838 struct tog_tree_view_state *s = &view->state.tree;
6839 struct got_tree_entry *next, *last;
6840 int n = 0;
6842 if (s->first_displayed_entry)
6843 next = got_tree_entry_get_next(s->tree,
6844 s->first_displayed_entry);
6845 else
6846 next = got_object_tree_get_first_entry(s->tree);
6848 last = s->last_displayed_entry;
6849 while (next && n++ < maxscroll) {
6850 if (last) {
6851 s->last_displayed_entry = last;
6852 last = got_tree_entry_get_next(s->tree, last);
6854 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6855 s->first_displayed_entry = next;
6856 next = got_tree_entry_get_next(s->tree, next);
6860 return NULL;
6863 static const struct got_error *
6864 tree_entry_path(char **path, struct tog_parent_trees *parents,
6865 struct got_tree_entry *te)
6867 const struct got_error *err = NULL;
6868 struct tog_parent_tree *pt;
6869 size_t len = 2; /* for leading slash and NUL */
6871 TAILQ_FOREACH(pt, parents, entry)
6872 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6873 + 1 /* slash */;
6874 if (te)
6875 len += strlen(got_tree_entry_get_name(te));
6877 *path = calloc(1, len);
6878 if (path == NULL)
6879 return got_error_from_errno("calloc");
6881 (*path)[0] = '/';
6882 pt = TAILQ_LAST(parents, tog_parent_trees);
6883 while (pt) {
6884 const char *name = got_tree_entry_get_name(pt->selected_entry);
6885 if (strlcat(*path, name, len) >= len) {
6886 err = got_error(GOT_ERR_NO_SPACE);
6887 goto done;
6889 if (strlcat(*path, "/", len) >= len) {
6890 err = got_error(GOT_ERR_NO_SPACE);
6891 goto done;
6893 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6895 if (te) {
6896 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6897 err = got_error(GOT_ERR_NO_SPACE);
6898 goto done;
6901 done:
6902 if (err) {
6903 free(*path);
6904 *path = NULL;
6906 return err;
6909 static const struct got_error *
6910 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6911 struct got_tree_entry *te, struct tog_parent_trees *parents,
6912 struct got_object_id *commit_id, struct got_repository *repo)
6914 const struct got_error *err = NULL;
6915 char *path;
6916 struct tog_view *blame_view;
6918 *new_view = NULL;
6920 err = tree_entry_path(&path, parents, te);
6921 if (err)
6922 return err;
6924 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6925 if (blame_view == NULL) {
6926 err = got_error_from_errno("view_open");
6927 goto done;
6930 err = open_blame_view(blame_view, path, commit_id, repo);
6931 if (err) {
6932 if (err->code == GOT_ERR_CANCELLED)
6933 err = NULL;
6934 view_close(blame_view);
6935 } else
6936 *new_view = blame_view;
6937 done:
6938 free(path);
6939 return err;
6942 static const struct got_error *
6943 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6944 struct tog_tree_view_state *s)
6946 struct tog_view *log_view;
6947 const struct got_error *err = NULL;
6948 char *path;
6950 *new_view = NULL;
6952 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6953 if (log_view == NULL)
6954 return got_error_from_errno("view_open");
6956 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6957 if (err)
6958 return err;
6960 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6961 path, 0);
6962 if (err)
6963 view_close(log_view);
6964 else
6965 *new_view = log_view;
6966 free(path);
6967 return err;
6970 static const struct got_error *
6971 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6972 const char *head_ref_name, struct got_repository *repo)
6974 const struct got_error *err = NULL;
6975 char *commit_id_str = NULL;
6976 struct tog_tree_view_state *s = &view->state.tree;
6977 struct got_commit_object *commit = NULL;
6979 TAILQ_INIT(&s->parents);
6980 STAILQ_INIT(&s->colors);
6982 s->commit_id = got_object_id_dup(commit_id);
6983 if (s->commit_id == NULL)
6984 return got_error_from_errno("got_object_id_dup");
6986 err = got_object_open_as_commit(&commit, repo, commit_id);
6987 if (err)
6988 goto done;
6991 * The root is opened here and will be closed when the view is closed.
6992 * Any visited subtrees and their path-wise parents are opened and
6993 * closed on demand.
6995 err = got_object_open_as_tree(&s->root, repo,
6996 got_object_commit_get_tree_id(commit));
6997 if (err)
6998 goto done;
6999 s->tree = s->root;
7001 err = got_object_id_str(&commit_id_str, commit_id);
7002 if (err != NULL)
7003 goto done;
7005 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7006 err = got_error_from_errno("asprintf");
7007 goto done;
7010 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7011 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7012 if (head_ref_name) {
7013 s->head_ref_name = strdup(head_ref_name);
7014 if (s->head_ref_name == NULL) {
7015 err = got_error_from_errno("strdup");
7016 goto done;
7019 s->repo = repo;
7021 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7022 err = add_color(&s->colors, "\\$$",
7023 TOG_COLOR_TREE_SUBMODULE,
7024 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7025 if (err)
7026 goto done;
7027 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7028 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7029 if (err)
7030 goto done;
7031 err = add_color(&s->colors, "/$",
7032 TOG_COLOR_TREE_DIRECTORY,
7033 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7034 if (err)
7035 goto done;
7037 err = add_color(&s->colors, "\\*$",
7038 TOG_COLOR_TREE_EXECUTABLE,
7039 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7040 if (err)
7041 goto done;
7043 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7044 get_color_value("TOG_COLOR_COMMIT"));
7045 if (err)
7046 goto done;
7049 view->show = show_tree_view;
7050 view->input = input_tree_view;
7051 view->close = close_tree_view;
7052 view->search_start = search_start_tree_view;
7053 view->search_next = search_next_tree_view;
7054 done:
7055 free(commit_id_str);
7056 if (commit)
7057 got_object_commit_close(commit);
7058 if (err)
7059 close_tree_view(view);
7060 return err;
7063 static const struct got_error *
7064 close_tree_view(struct tog_view *view)
7066 struct tog_tree_view_state *s = &view->state.tree;
7068 free_colors(&s->colors);
7069 free(s->tree_label);
7070 s->tree_label = NULL;
7071 free(s->commit_id);
7072 s->commit_id = NULL;
7073 free(s->head_ref_name);
7074 s->head_ref_name = NULL;
7075 while (!TAILQ_EMPTY(&s->parents)) {
7076 struct tog_parent_tree *parent;
7077 parent = TAILQ_FIRST(&s->parents);
7078 TAILQ_REMOVE(&s->parents, parent, entry);
7079 if (parent->tree != s->root)
7080 got_object_tree_close(parent->tree);
7081 free(parent);
7084 if (s->tree != NULL && s->tree != s->root)
7085 got_object_tree_close(s->tree);
7086 if (s->root)
7087 got_object_tree_close(s->root);
7088 return NULL;
7091 static const struct got_error *
7092 search_start_tree_view(struct tog_view *view)
7094 struct tog_tree_view_state *s = &view->state.tree;
7096 s->matched_entry = NULL;
7097 return NULL;
7100 static int
7101 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7103 regmatch_t regmatch;
7105 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7106 0) == 0;
7109 static const struct got_error *
7110 search_next_tree_view(struct tog_view *view)
7112 struct tog_tree_view_state *s = &view->state.tree;
7113 struct got_tree_entry *te = NULL;
7115 if (!view->searching) {
7116 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7117 return NULL;
7120 if (s->matched_entry) {
7121 if (view->searching == TOG_SEARCH_FORWARD) {
7122 if (s->selected_entry)
7123 te = got_tree_entry_get_next(s->tree,
7124 s->selected_entry);
7125 else
7126 te = got_object_tree_get_first_entry(s->tree);
7127 } else {
7128 if (s->selected_entry == NULL)
7129 te = got_object_tree_get_last_entry(s->tree);
7130 else
7131 te = got_tree_entry_get_prev(s->tree,
7132 s->selected_entry);
7134 } else {
7135 if (s->selected_entry)
7136 te = s->selected_entry;
7137 else if (view->searching == TOG_SEARCH_FORWARD)
7138 te = got_object_tree_get_first_entry(s->tree);
7139 else
7140 te = got_object_tree_get_last_entry(s->tree);
7143 while (1) {
7144 if (te == NULL) {
7145 if (s->matched_entry == NULL) {
7146 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7147 return NULL;
7149 if (view->searching == TOG_SEARCH_FORWARD)
7150 te = got_object_tree_get_first_entry(s->tree);
7151 else
7152 te = got_object_tree_get_last_entry(s->tree);
7155 if (match_tree_entry(te, &view->regex)) {
7156 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7157 s->matched_entry = te;
7158 break;
7161 if (view->searching == TOG_SEARCH_FORWARD)
7162 te = got_tree_entry_get_next(s->tree, te);
7163 else
7164 te = got_tree_entry_get_prev(s->tree, te);
7167 if (s->matched_entry) {
7168 s->first_displayed_entry = s->matched_entry;
7169 s->selected = 0;
7172 return NULL;
7175 static const struct got_error *
7176 show_tree_view(struct tog_view *view)
7178 const struct got_error *err = NULL;
7179 struct tog_tree_view_state *s = &view->state.tree;
7180 char *parent_path;
7182 err = tree_entry_path(&parent_path, &s->parents, NULL);
7183 if (err)
7184 return err;
7186 err = draw_tree_entries(view, parent_path);
7187 free(parent_path);
7189 view_border(view);
7190 return err;
7193 static const struct got_error *
7194 tree_goto_line(struct tog_view *view, int nlines)
7196 const struct got_error *err = NULL;
7197 struct tog_tree_view_state *s = &view->state.tree;
7198 struct got_tree_entry **fte, **lte, **ste;
7199 int g, last, first = 1, i = 1;
7200 int root = s->tree == s->root;
7201 int off = root ? 1 : 2;
7203 g = view->gline;
7204 view->gline = 0;
7206 if (g == 0)
7207 g = 1;
7208 else if (g > got_object_tree_get_nentries(s->tree))
7209 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7211 fte = &s->first_displayed_entry;
7212 lte = &s->last_displayed_entry;
7213 ste = &s->selected_entry;
7215 if (*fte != NULL) {
7216 first = got_tree_entry_get_index(*fte);
7217 first += off; /* account for ".." */
7219 last = got_tree_entry_get_index(*lte);
7220 last += off;
7222 if (g >= first && g <= last && g - first < nlines) {
7223 s->selected = g - first;
7224 return NULL; /* gline is on the current page */
7227 if (*ste != NULL) {
7228 i = got_tree_entry_get_index(*ste);
7229 i += off;
7232 if (i < g) {
7233 err = tree_scroll_down(view, g - i);
7234 if (err)
7235 return err;
7236 if (got_tree_entry_get_index(*lte) >=
7237 got_object_tree_get_nentries(s->tree) - 1 &&
7238 first + s->selected < g &&
7239 s->selected < s->ndisplayed - 1) {
7240 first = got_tree_entry_get_index(*fte);
7241 first += off;
7242 s->selected = g - first;
7244 } else if (i > g)
7245 tree_scroll_up(s, i - g);
7247 if (g < nlines &&
7248 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7249 s->selected = g - 1;
7251 return NULL;
7254 static const struct got_error *
7255 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7257 const struct got_error *err = NULL;
7258 struct tog_tree_view_state *s = &view->state.tree;
7259 struct got_tree_entry *te;
7260 int n, nscroll = view->nlines - 3;
7262 if (view->gline)
7263 return tree_goto_line(view, nscroll);
7265 switch (ch) {
7266 case 'i':
7267 s->show_ids = !s->show_ids;
7268 view->count = 0;
7269 break;
7270 case 'L':
7271 view->count = 0;
7272 if (!s->selected_entry)
7273 break;
7274 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7275 break;
7276 case 'R':
7277 view->count = 0;
7278 err = view_request_new(new_view, view, TOG_VIEW_REF);
7279 break;
7280 case 'g':
7281 case KEY_HOME:
7282 s->selected = 0;
7283 view->count = 0;
7284 if (s->tree == s->root)
7285 s->first_displayed_entry =
7286 got_object_tree_get_first_entry(s->tree);
7287 else
7288 s->first_displayed_entry = NULL;
7289 break;
7290 case 'G':
7291 case KEY_END: {
7292 int eos = view->nlines - 3;
7294 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7295 --eos; /* border */
7296 s->selected = 0;
7297 view->count = 0;
7298 te = got_object_tree_get_last_entry(s->tree);
7299 for (n = 0; n < eos; n++) {
7300 if (te == NULL) {
7301 if (s->tree != s->root) {
7302 s->first_displayed_entry = NULL;
7303 n++;
7305 break;
7307 s->first_displayed_entry = te;
7308 te = got_tree_entry_get_prev(s->tree, te);
7310 if (n > 0)
7311 s->selected = n - 1;
7312 break;
7314 case 'k':
7315 case KEY_UP:
7316 case CTRL('p'):
7317 if (s->selected > 0) {
7318 s->selected--;
7319 break;
7321 tree_scroll_up(s, 1);
7322 if (s->selected_entry == NULL ||
7323 (s->tree == s->root && s->selected_entry ==
7324 got_object_tree_get_first_entry(s->tree)))
7325 view->count = 0;
7326 break;
7327 case CTRL('u'):
7328 case 'u':
7329 nscroll /= 2;
7330 /* FALL THROUGH */
7331 case KEY_PPAGE:
7332 case CTRL('b'):
7333 case 'b':
7334 if (s->tree == s->root) {
7335 if (got_object_tree_get_first_entry(s->tree) ==
7336 s->first_displayed_entry)
7337 s->selected -= MIN(s->selected, nscroll);
7338 } else {
7339 if (s->first_displayed_entry == NULL)
7340 s->selected -= MIN(s->selected, nscroll);
7342 tree_scroll_up(s, MAX(0, nscroll));
7343 if (s->selected_entry == NULL ||
7344 (s->tree == s->root && s->selected_entry ==
7345 got_object_tree_get_first_entry(s->tree)))
7346 view->count = 0;
7347 break;
7348 case 'j':
7349 case KEY_DOWN:
7350 case CTRL('n'):
7351 if (s->selected < s->ndisplayed - 1) {
7352 s->selected++;
7353 break;
7355 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7356 == NULL) {
7357 /* can't scroll any further */
7358 view->count = 0;
7359 break;
7361 tree_scroll_down(view, 1);
7362 break;
7363 case CTRL('d'):
7364 case 'd':
7365 nscroll /= 2;
7366 /* FALL THROUGH */
7367 case KEY_NPAGE:
7368 case CTRL('f'):
7369 case 'f':
7370 case ' ':
7371 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7372 == NULL) {
7373 /* can't scroll any further; move cursor down */
7374 if (s->selected < s->ndisplayed - 1)
7375 s->selected += MIN(nscroll,
7376 s->ndisplayed - s->selected - 1);
7377 else
7378 view->count = 0;
7379 break;
7381 tree_scroll_down(view, nscroll);
7382 break;
7383 case KEY_ENTER:
7384 case '\r':
7385 case KEY_BACKSPACE:
7386 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7387 struct tog_parent_tree *parent;
7388 /* user selected '..' */
7389 if (s->tree == s->root) {
7390 view->count = 0;
7391 break;
7393 parent = TAILQ_FIRST(&s->parents);
7394 TAILQ_REMOVE(&s->parents, parent,
7395 entry);
7396 got_object_tree_close(s->tree);
7397 s->tree = parent->tree;
7398 s->first_displayed_entry =
7399 parent->first_displayed_entry;
7400 s->selected_entry =
7401 parent->selected_entry;
7402 s->selected = parent->selected;
7403 if (s->selected > view->nlines - 3) {
7404 err = offset_selection_down(view);
7405 if (err)
7406 break;
7408 free(parent);
7409 } else if (S_ISDIR(got_tree_entry_get_mode(
7410 s->selected_entry))) {
7411 struct got_tree_object *subtree;
7412 view->count = 0;
7413 err = got_object_open_as_tree(&subtree, s->repo,
7414 got_tree_entry_get_id(s->selected_entry));
7415 if (err)
7416 break;
7417 err = tree_view_visit_subtree(s, subtree);
7418 if (err) {
7419 got_object_tree_close(subtree);
7420 break;
7422 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7423 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7424 break;
7425 case KEY_RESIZE:
7426 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7427 s->selected = view->nlines - 4;
7428 view->count = 0;
7429 break;
7430 default:
7431 view->count = 0;
7432 break;
7435 return err;
7438 __dead static void
7439 usage_tree(void)
7441 endwin();
7442 fprintf(stderr,
7443 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7444 getprogname());
7445 exit(1);
7448 static const struct got_error *
7449 cmd_tree(int argc, char *argv[])
7451 const struct got_error *error;
7452 struct got_repository *repo = NULL;
7453 struct got_worktree *worktree = NULL;
7454 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7455 struct got_object_id *commit_id = NULL;
7456 struct got_commit_object *commit = NULL;
7457 const char *commit_id_arg = NULL;
7458 char *label = NULL;
7459 struct got_reference *ref = NULL;
7460 const char *head_ref_name = NULL;
7461 int ch;
7462 struct tog_view *view;
7463 int *pack_fds = NULL;
7465 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7466 switch (ch) {
7467 case 'c':
7468 commit_id_arg = optarg;
7469 break;
7470 case 'r':
7471 repo_path = realpath(optarg, NULL);
7472 if (repo_path == NULL)
7473 return got_error_from_errno2("realpath",
7474 optarg);
7475 break;
7476 default:
7477 usage_tree();
7478 /* NOTREACHED */
7482 argc -= optind;
7483 argv += optind;
7485 if (argc > 1)
7486 usage_tree();
7488 error = got_repo_pack_fds_open(&pack_fds);
7489 if (error != NULL)
7490 goto done;
7492 if (repo_path == NULL) {
7493 cwd = getcwd(NULL, 0);
7494 if (cwd == NULL)
7495 return got_error_from_errno("getcwd");
7496 error = got_worktree_open(&worktree, cwd);
7497 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7498 goto done;
7499 if (worktree)
7500 repo_path =
7501 strdup(got_worktree_get_repo_path(worktree));
7502 else
7503 repo_path = strdup(cwd);
7504 if (repo_path == NULL) {
7505 error = got_error_from_errno("strdup");
7506 goto done;
7510 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7511 if (error != NULL)
7512 goto done;
7514 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7515 repo, worktree);
7516 if (error)
7517 goto done;
7519 init_curses();
7521 error = apply_unveil(got_repo_get_path(repo), NULL);
7522 if (error)
7523 goto done;
7525 error = tog_load_refs(repo, 0);
7526 if (error)
7527 goto done;
7529 if (commit_id_arg == NULL) {
7530 error = got_repo_match_object_id(&commit_id, &label,
7531 worktree ? got_worktree_get_head_ref_name(worktree) :
7532 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7533 if (error)
7534 goto done;
7535 head_ref_name = label;
7536 } else {
7537 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7538 if (error == NULL)
7539 head_ref_name = got_ref_get_name(ref);
7540 else if (error->code != GOT_ERR_NOT_REF)
7541 goto done;
7542 error = got_repo_match_object_id(&commit_id, NULL,
7543 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7544 if (error)
7545 goto done;
7548 error = got_object_open_as_commit(&commit, repo, commit_id);
7549 if (error)
7550 goto done;
7552 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7553 if (view == NULL) {
7554 error = got_error_from_errno("view_open");
7555 goto done;
7557 error = open_tree_view(view, commit_id, head_ref_name, repo);
7558 if (error)
7559 goto done;
7560 if (!got_path_is_root_dir(in_repo_path)) {
7561 error = tree_view_walk_path(&view->state.tree, commit,
7562 in_repo_path);
7563 if (error)
7564 goto done;
7567 if (worktree) {
7568 /* Release work tree lock. */
7569 got_worktree_close(worktree);
7570 worktree = NULL;
7572 error = view_loop(view);
7573 done:
7574 free(repo_path);
7575 free(cwd);
7576 free(commit_id);
7577 free(label);
7578 if (ref)
7579 got_ref_close(ref);
7580 if (repo) {
7581 const struct got_error *close_err = got_repo_close(repo);
7582 if (error == NULL)
7583 error = close_err;
7585 if (pack_fds) {
7586 const struct got_error *pack_err =
7587 got_repo_pack_fds_close(pack_fds);
7588 if (error == NULL)
7589 error = pack_err;
7591 tog_free_refs();
7592 return error;
7595 static const struct got_error *
7596 ref_view_load_refs(struct tog_ref_view_state *s)
7598 struct got_reflist_entry *sre;
7599 struct tog_reflist_entry *re;
7601 s->nrefs = 0;
7602 TAILQ_FOREACH(sre, &tog_refs, entry) {
7603 if (strncmp(got_ref_get_name(sre->ref),
7604 "refs/got/", 9) == 0 &&
7605 strncmp(got_ref_get_name(sre->ref),
7606 "refs/got/backup/", 16) != 0)
7607 continue;
7609 re = malloc(sizeof(*re));
7610 if (re == NULL)
7611 return got_error_from_errno("malloc");
7613 re->ref = got_ref_dup(sre->ref);
7614 if (re->ref == NULL)
7615 return got_error_from_errno("got_ref_dup");
7616 re->idx = s->nrefs++;
7617 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7620 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7621 return NULL;
7624 static void
7625 ref_view_free_refs(struct tog_ref_view_state *s)
7627 struct tog_reflist_entry *re;
7629 while (!TAILQ_EMPTY(&s->refs)) {
7630 re = TAILQ_FIRST(&s->refs);
7631 TAILQ_REMOVE(&s->refs, re, entry);
7632 got_ref_close(re->ref);
7633 free(re);
7637 static const struct got_error *
7638 open_ref_view(struct tog_view *view, struct got_repository *repo)
7640 const struct got_error *err = NULL;
7641 struct tog_ref_view_state *s = &view->state.ref;
7643 s->selected_entry = 0;
7644 s->repo = repo;
7646 TAILQ_INIT(&s->refs);
7647 STAILQ_INIT(&s->colors);
7649 err = ref_view_load_refs(s);
7650 if (err)
7651 return err;
7653 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7654 err = add_color(&s->colors, "^refs/heads/",
7655 TOG_COLOR_REFS_HEADS,
7656 get_color_value("TOG_COLOR_REFS_HEADS"));
7657 if (err)
7658 goto done;
7660 err = add_color(&s->colors, "^refs/tags/",
7661 TOG_COLOR_REFS_TAGS,
7662 get_color_value("TOG_COLOR_REFS_TAGS"));
7663 if (err)
7664 goto done;
7666 err = add_color(&s->colors, "^refs/remotes/",
7667 TOG_COLOR_REFS_REMOTES,
7668 get_color_value("TOG_COLOR_REFS_REMOTES"));
7669 if (err)
7670 goto done;
7672 err = add_color(&s->colors, "^refs/got/backup/",
7673 TOG_COLOR_REFS_BACKUP,
7674 get_color_value("TOG_COLOR_REFS_BACKUP"));
7675 if (err)
7676 goto done;
7679 view->show = show_ref_view;
7680 view->input = input_ref_view;
7681 view->close = close_ref_view;
7682 view->search_start = search_start_ref_view;
7683 view->search_next = search_next_ref_view;
7684 done:
7685 if (err)
7686 free_colors(&s->colors);
7687 return err;
7690 static const struct got_error *
7691 close_ref_view(struct tog_view *view)
7693 struct tog_ref_view_state *s = &view->state.ref;
7695 ref_view_free_refs(s);
7696 free_colors(&s->colors);
7698 return NULL;
7701 static const struct got_error *
7702 resolve_reflist_entry(struct got_object_id **commit_id,
7703 struct tog_reflist_entry *re, struct got_repository *repo)
7705 const struct got_error *err = NULL;
7706 struct got_object_id *obj_id;
7707 struct got_tag_object *tag = NULL;
7708 int obj_type;
7710 *commit_id = NULL;
7712 err = got_ref_resolve(&obj_id, repo, re->ref);
7713 if (err)
7714 return err;
7716 err = got_object_get_type(&obj_type, repo, obj_id);
7717 if (err)
7718 goto done;
7720 switch (obj_type) {
7721 case GOT_OBJ_TYPE_COMMIT:
7722 *commit_id = obj_id;
7723 break;
7724 case GOT_OBJ_TYPE_TAG:
7725 err = got_object_open_as_tag(&tag, repo, obj_id);
7726 if (err)
7727 goto done;
7728 free(obj_id);
7729 err = got_object_get_type(&obj_type, repo,
7730 got_object_tag_get_object_id(tag));
7731 if (err)
7732 goto done;
7733 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7734 err = got_error(GOT_ERR_OBJ_TYPE);
7735 goto done;
7737 *commit_id = got_object_id_dup(
7738 got_object_tag_get_object_id(tag));
7739 if (*commit_id == NULL) {
7740 err = got_error_from_errno("got_object_id_dup");
7741 goto done;
7743 break;
7744 default:
7745 err = got_error(GOT_ERR_OBJ_TYPE);
7746 break;
7749 done:
7750 if (tag)
7751 got_object_tag_close(tag);
7752 if (err) {
7753 free(*commit_id);
7754 *commit_id = NULL;
7756 return err;
7759 static const struct got_error *
7760 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7761 struct tog_reflist_entry *re, struct got_repository *repo)
7763 struct tog_view *log_view;
7764 const struct got_error *err = NULL;
7765 struct got_object_id *commit_id = NULL;
7767 *new_view = NULL;
7769 err = resolve_reflist_entry(&commit_id, re, repo);
7770 if (err) {
7771 if (err->code != GOT_ERR_OBJ_TYPE)
7772 return err;
7773 else
7774 return NULL;
7777 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7778 if (log_view == NULL) {
7779 err = got_error_from_errno("view_open");
7780 goto done;
7783 err = open_log_view(log_view, commit_id, repo,
7784 got_ref_get_name(re->ref), "", 0);
7785 done:
7786 if (err)
7787 view_close(log_view);
7788 else
7789 *new_view = log_view;
7790 free(commit_id);
7791 return err;
7794 static void
7795 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7797 struct tog_reflist_entry *re;
7798 int i = 0;
7800 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7801 return;
7803 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7804 while (i++ < maxscroll) {
7805 if (re == NULL)
7806 break;
7807 s->first_displayed_entry = re;
7808 re = TAILQ_PREV(re, tog_reflist_head, entry);
7812 static const struct got_error *
7813 ref_scroll_down(struct tog_view *view, int maxscroll)
7815 struct tog_ref_view_state *s = &view->state.ref;
7816 struct tog_reflist_entry *next, *last;
7817 int n = 0;
7819 if (s->first_displayed_entry)
7820 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7821 else
7822 next = TAILQ_FIRST(&s->refs);
7824 last = s->last_displayed_entry;
7825 while (next && n++ < maxscroll) {
7826 if (last) {
7827 s->last_displayed_entry = last;
7828 last = TAILQ_NEXT(last, entry);
7830 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7831 s->first_displayed_entry = next;
7832 next = TAILQ_NEXT(next, entry);
7836 return NULL;
7839 static const struct got_error *
7840 search_start_ref_view(struct tog_view *view)
7842 struct tog_ref_view_state *s = &view->state.ref;
7844 s->matched_entry = NULL;
7845 return NULL;
7848 static int
7849 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7851 regmatch_t regmatch;
7853 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7854 0) == 0;
7857 static const struct got_error *
7858 search_next_ref_view(struct tog_view *view)
7860 struct tog_ref_view_state *s = &view->state.ref;
7861 struct tog_reflist_entry *re = NULL;
7863 if (!view->searching) {
7864 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7865 return NULL;
7868 if (s->matched_entry) {
7869 if (view->searching == TOG_SEARCH_FORWARD) {
7870 if (s->selected_entry)
7871 re = TAILQ_NEXT(s->selected_entry, entry);
7872 else
7873 re = TAILQ_PREV(s->selected_entry,
7874 tog_reflist_head, entry);
7875 } else {
7876 if (s->selected_entry == NULL)
7877 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7878 else
7879 re = TAILQ_PREV(s->selected_entry,
7880 tog_reflist_head, entry);
7882 } else {
7883 if (s->selected_entry)
7884 re = s->selected_entry;
7885 else if (view->searching == TOG_SEARCH_FORWARD)
7886 re = TAILQ_FIRST(&s->refs);
7887 else
7888 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7891 while (1) {
7892 if (re == NULL) {
7893 if (s->matched_entry == NULL) {
7894 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7895 return NULL;
7897 if (view->searching == TOG_SEARCH_FORWARD)
7898 re = TAILQ_FIRST(&s->refs);
7899 else
7900 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7903 if (match_reflist_entry(re, &view->regex)) {
7904 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7905 s->matched_entry = re;
7906 break;
7909 if (view->searching == TOG_SEARCH_FORWARD)
7910 re = TAILQ_NEXT(re, entry);
7911 else
7912 re = TAILQ_PREV(re, tog_reflist_head, entry);
7915 if (s->matched_entry) {
7916 s->first_displayed_entry = s->matched_entry;
7917 s->selected = 0;
7920 return NULL;
7923 static const struct got_error *
7924 show_ref_view(struct tog_view *view)
7926 const struct got_error *err = NULL;
7927 struct tog_ref_view_state *s = &view->state.ref;
7928 struct tog_reflist_entry *re;
7929 char *line = NULL;
7930 wchar_t *wline;
7931 struct tog_color *tc;
7932 int width, n;
7933 int limit = view->nlines;
7935 werase(view->window);
7937 s->ndisplayed = 0;
7938 if (view_is_hsplit_top(view))
7939 --limit; /* border */
7941 if (limit == 0)
7942 return NULL;
7944 re = s->first_displayed_entry;
7946 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7947 s->nrefs) == -1)
7948 return got_error_from_errno("asprintf");
7950 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7951 if (err) {
7952 free(line);
7953 return err;
7955 if (view_needs_focus_indication(view))
7956 wstandout(view->window);
7957 waddwstr(view->window, wline);
7958 while (width++ < view->ncols)
7959 waddch(view->window, ' ');
7960 if (view_needs_focus_indication(view))
7961 wstandend(view->window);
7962 free(wline);
7963 wline = NULL;
7964 free(line);
7965 line = NULL;
7966 if (--limit <= 0)
7967 return NULL;
7969 n = 0;
7970 while (re && limit > 0) {
7971 char *line = NULL;
7972 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7974 if (s->show_date) {
7975 struct got_commit_object *ci;
7976 struct got_tag_object *tag;
7977 struct got_object_id *id;
7978 struct tm tm;
7979 time_t t;
7981 err = got_ref_resolve(&id, s->repo, re->ref);
7982 if (err)
7983 return err;
7984 err = got_object_open_as_tag(&tag, s->repo, id);
7985 if (err) {
7986 if (err->code != GOT_ERR_OBJ_TYPE) {
7987 free(id);
7988 return err;
7990 err = got_object_open_as_commit(&ci, s->repo,
7991 id);
7992 if (err) {
7993 free(id);
7994 return err;
7996 t = got_object_commit_get_committer_time(ci);
7997 got_object_commit_close(ci);
7998 } else {
7999 t = got_object_tag_get_tagger_time(tag);
8000 got_object_tag_close(tag);
8002 free(id);
8003 if (gmtime_r(&t, &tm) == NULL)
8004 return got_error_from_errno("gmtime_r");
8005 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8006 return got_error(GOT_ERR_NO_SPACE);
8008 if (got_ref_is_symbolic(re->ref)) {
8009 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8010 ymd : "", got_ref_get_name(re->ref),
8011 got_ref_get_symref_target(re->ref)) == -1)
8012 return got_error_from_errno("asprintf");
8013 } else if (s->show_ids) {
8014 struct got_object_id *id;
8015 char *id_str;
8016 err = got_ref_resolve(&id, s->repo, re->ref);
8017 if (err)
8018 return err;
8019 err = got_object_id_str(&id_str, id);
8020 if (err) {
8021 free(id);
8022 return err;
8024 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8025 got_ref_get_name(re->ref), id_str) == -1) {
8026 err = got_error_from_errno("asprintf");
8027 free(id);
8028 free(id_str);
8029 return err;
8031 free(id);
8032 free(id_str);
8033 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8034 got_ref_get_name(re->ref)) == -1)
8035 return got_error_from_errno("asprintf");
8037 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
8038 0, 0);
8039 if (err) {
8040 free(line);
8041 return err;
8043 if (n == s->selected) {
8044 if (view->focussed)
8045 wstandout(view->window);
8046 s->selected_entry = re;
8048 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8049 if (tc)
8050 wattr_on(view->window,
8051 COLOR_PAIR(tc->colorpair), NULL);
8052 waddwstr(view->window, wline);
8053 if (tc)
8054 wattr_off(view->window,
8055 COLOR_PAIR(tc->colorpair), NULL);
8056 if (width < view->ncols - 1)
8057 waddch(view->window, '\n');
8058 if (n == s->selected && view->focussed)
8059 wstandend(view->window);
8060 free(line);
8061 free(wline);
8062 wline = NULL;
8063 n++;
8064 s->ndisplayed++;
8065 s->last_displayed_entry = re;
8067 limit--;
8068 re = TAILQ_NEXT(re, entry);
8071 view_border(view);
8072 return err;
8075 static const struct got_error *
8076 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8077 struct tog_reflist_entry *re, struct got_repository *repo)
8079 const struct got_error *err = NULL;
8080 struct got_object_id *commit_id = NULL;
8081 struct tog_view *tree_view;
8083 *new_view = NULL;
8085 err = resolve_reflist_entry(&commit_id, re, repo);
8086 if (err) {
8087 if (err->code != GOT_ERR_OBJ_TYPE)
8088 return err;
8089 else
8090 return NULL;
8094 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8095 if (tree_view == NULL) {
8096 err = got_error_from_errno("view_open");
8097 goto done;
8100 err = open_tree_view(tree_view, commit_id,
8101 got_ref_get_name(re->ref), repo);
8102 if (err)
8103 goto done;
8105 *new_view = tree_view;
8106 done:
8107 free(commit_id);
8108 return err;
8111 static const struct got_error *
8112 ref_goto_line(struct tog_view *view, int nlines)
8114 const struct got_error *err = NULL;
8115 struct tog_ref_view_state *s = &view->state.ref;
8116 int g, idx = s->selected_entry->idx;
8118 g = view->gline;
8119 view->gline = 0;
8121 if (g == 0)
8122 g = 1;
8123 else if (g > s->nrefs)
8124 g = s->nrefs;
8126 if (g >= s->first_displayed_entry->idx + 1 &&
8127 g <= s->last_displayed_entry->idx + 1 &&
8128 g - s->first_displayed_entry->idx - 1 < nlines) {
8129 s->selected = g - s->first_displayed_entry->idx - 1;
8130 return NULL;
8133 if (idx + 1 < g) {
8134 err = ref_scroll_down(view, g - idx - 1);
8135 if (err)
8136 return err;
8137 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8138 s->first_displayed_entry->idx + s->selected < g &&
8139 s->selected < s->ndisplayed - 1)
8140 s->selected = g - s->first_displayed_entry->idx - 1;
8141 } else if (idx + 1 > g)
8142 ref_scroll_up(s, idx - g + 1);
8144 if (g < nlines && s->first_displayed_entry->idx == 0)
8145 s->selected = g - 1;
8147 return NULL;
8151 static const struct got_error *
8152 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8154 const struct got_error *err = NULL;
8155 struct tog_ref_view_state *s = &view->state.ref;
8156 struct tog_reflist_entry *re;
8157 int n, nscroll = view->nlines - 1;
8159 if (view->gline)
8160 return ref_goto_line(view, nscroll);
8162 switch (ch) {
8163 case 'i':
8164 s->show_ids = !s->show_ids;
8165 view->count = 0;
8166 break;
8167 case 'm':
8168 s->show_date = !s->show_date;
8169 view->count = 0;
8170 break;
8171 case 'o':
8172 s->sort_by_date = !s->sort_by_date;
8173 view->count = 0;
8174 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8175 got_ref_cmp_by_commit_timestamp_descending :
8176 tog_ref_cmp_by_name, s->repo);
8177 if (err)
8178 break;
8179 got_reflist_object_id_map_free(tog_refs_idmap);
8180 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8181 &tog_refs, s->repo);
8182 if (err)
8183 break;
8184 ref_view_free_refs(s);
8185 err = ref_view_load_refs(s);
8186 break;
8187 case KEY_ENTER:
8188 case '\r':
8189 view->count = 0;
8190 if (!s->selected_entry)
8191 break;
8192 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8193 break;
8194 case 'T':
8195 view->count = 0;
8196 if (!s->selected_entry)
8197 break;
8198 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8199 break;
8200 case 'g':
8201 case KEY_HOME:
8202 s->selected = 0;
8203 view->count = 0;
8204 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8205 break;
8206 case 'G':
8207 case KEY_END: {
8208 int eos = view->nlines - 1;
8210 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8211 --eos; /* border */
8212 s->selected = 0;
8213 view->count = 0;
8214 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8215 for (n = 0; n < eos; n++) {
8216 if (re == NULL)
8217 break;
8218 s->first_displayed_entry = re;
8219 re = TAILQ_PREV(re, tog_reflist_head, entry);
8221 if (n > 0)
8222 s->selected = n - 1;
8223 break;
8225 case 'k':
8226 case KEY_UP:
8227 case CTRL('p'):
8228 if (s->selected > 0) {
8229 s->selected--;
8230 break;
8232 ref_scroll_up(s, 1);
8233 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8234 view->count = 0;
8235 break;
8236 case CTRL('u'):
8237 case 'u':
8238 nscroll /= 2;
8239 /* FALL THROUGH */
8240 case KEY_PPAGE:
8241 case CTRL('b'):
8242 case 'b':
8243 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8244 s->selected -= MIN(nscroll, s->selected);
8245 ref_scroll_up(s, MAX(0, nscroll));
8246 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8247 view->count = 0;
8248 break;
8249 case 'j':
8250 case KEY_DOWN:
8251 case CTRL('n'):
8252 if (s->selected < s->ndisplayed - 1) {
8253 s->selected++;
8254 break;
8256 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8257 /* can't scroll any further */
8258 view->count = 0;
8259 break;
8261 ref_scroll_down(view, 1);
8262 break;
8263 case CTRL('d'):
8264 case 'd':
8265 nscroll /= 2;
8266 /* FALL THROUGH */
8267 case KEY_NPAGE:
8268 case CTRL('f'):
8269 case 'f':
8270 case ' ':
8271 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8272 /* can't scroll any further; move cursor down */
8273 if (s->selected < s->ndisplayed - 1)
8274 s->selected += MIN(nscroll,
8275 s->ndisplayed - s->selected - 1);
8276 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8277 s->selected += s->ndisplayed - s->selected - 1;
8278 view->count = 0;
8279 break;
8281 ref_scroll_down(view, nscroll);
8282 break;
8283 case CTRL('l'):
8284 view->count = 0;
8285 tog_free_refs();
8286 err = tog_load_refs(s->repo, s->sort_by_date);
8287 if (err)
8288 break;
8289 ref_view_free_refs(s);
8290 err = ref_view_load_refs(s);
8291 break;
8292 case KEY_RESIZE:
8293 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8294 s->selected = view->nlines - 2;
8295 break;
8296 default:
8297 view->count = 0;
8298 break;
8301 return err;
8304 __dead static void
8305 usage_ref(void)
8307 endwin();
8308 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8309 getprogname());
8310 exit(1);
8313 static const struct got_error *
8314 cmd_ref(int argc, char *argv[])
8316 const struct got_error *error;
8317 struct got_repository *repo = NULL;
8318 struct got_worktree *worktree = NULL;
8319 char *cwd = NULL, *repo_path = NULL;
8320 int ch;
8321 struct tog_view *view;
8322 int *pack_fds = NULL;
8324 while ((ch = getopt(argc, argv, "r:")) != -1) {
8325 switch (ch) {
8326 case 'r':
8327 repo_path = realpath(optarg, NULL);
8328 if (repo_path == NULL)
8329 return got_error_from_errno2("realpath",
8330 optarg);
8331 break;
8332 default:
8333 usage_ref();
8334 /* NOTREACHED */
8338 argc -= optind;
8339 argv += optind;
8341 if (argc > 1)
8342 usage_ref();
8344 error = got_repo_pack_fds_open(&pack_fds);
8345 if (error != NULL)
8346 goto done;
8348 if (repo_path == NULL) {
8349 cwd = getcwd(NULL, 0);
8350 if (cwd == NULL)
8351 return got_error_from_errno("getcwd");
8352 error = got_worktree_open(&worktree, cwd);
8353 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8354 goto done;
8355 if (worktree)
8356 repo_path =
8357 strdup(got_worktree_get_repo_path(worktree));
8358 else
8359 repo_path = strdup(cwd);
8360 if (repo_path == NULL) {
8361 error = got_error_from_errno("strdup");
8362 goto done;
8366 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8367 if (error != NULL)
8368 goto done;
8370 init_curses();
8372 error = apply_unveil(got_repo_get_path(repo), NULL);
8373 if (error)
8374 goto done;
8376 error = tog_load_refs(repo, 0);
8377 if (error)
8378 goto done;
8380 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8381 if (view == NULL) {
8382 error = got_error_from_errno("view_open");
8383 goto done;
8386 error = open_ref_view(view, repo);
8387 if (error)
8388 goto done;
8390 if (worktree) {
8391 /* Release work tree lock. */
8392 got_worktree_close(worktree);
8393 worktree = NULL;
8395 error = view_loop(view);
8396 done:
8397 free(repo_path);
8398 free(cwd);
8399 if (repo) {
8400 const struct got_error *close_err = got_repo_close(repo);
8401 if (close_err)
8402 error = close_err;
8404 if (pack_fds) {
8405 const struct got_error *pack_err =
8406 got_repo_pack_fds_close(pack_fds);
8407 if (error == NULL)
8408 error = pack_err;
8410 tog_free_refs();
8411 return error;
8414 static const struct got_error*
8415 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8416 const char *str)
8418 size_t len;
8420 if (win == NULL)
8421 win = stdscr;
8423 len = strlen(str);
8424 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8426 if (focus)
8427 wstandout(win);
8428 if (mvwprintw(win, y, x, "%s", str) == ERR)
8429 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8430 if (focus)
8431 wstandend(win);
8433 return NULL;
8436 static const struct got_error *
8437 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8439 off_t *p;
8441 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8442 if (p == NULL) {
8443 free(*line_offsets);
8444 *line_offsets = NULL;
8445 return got_error_from_errno("reallocarray");
8448 *line_offsets = p;
8449 (*line_offsets)[*nlines] = off;
8450 ++(*nlines);
8451 return NULL;
8454 static const struct got_error *
8455 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8457 *ret = 0;
8459 for (;n > 0; --n, ++km) {
8460 char *t0, *t, *k;
8461 size_t len = 1;
8463 if (km->keys == NULL)
8464 continue;
8466 t = t0 = strdup(km->keys);
8467 if (t0 == NULL)
8468 return got_error_from_errno("strdup");
8470 len += strlen(t);
8471 while ((k = strsep(&t, " ")) != NULL)
8472 len += strlen(k) > 1 ? 2 : 0;
8473 free(t0);
8474 *ret = MAX(*ret, len);
8477 return NULL;
8481 * Write keymap section headers, keys, and key info in km to f.
8482 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8483 * wrap control and symbolic keys in guillemets, else use <>.
8485 static const struct got_error *
8486 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8488 int n, len = width;
8490 if (km->keys) {
8491 static const char *u8_glyph[] = {
8492 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8493 "\xe2\x80\xba" /* U+203A (utf8 >) */
8495 char *t0, *t, *k;
8496 int cs, s, first = 1;
8498 cs = got_locale_is_utf8();
8500 t = t0 = strdup(km->keys);
8501 if (t0 == NULL)
8502 return got_error_from_errno("strdup");
8504 len = strlen(km->keys);
8505 while ((k = strsep(&t, " ")) != NULL) {
8506 s = strlen(k) > 1; /* control or symbolic key */
8507 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8508 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8509 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8510 if (n < 0) {
8511 free(t0);
8512 return got_error_from_errno("fprintf");
8514 first = 0;
8515 len += s ? 2 : 0;
8516 *off += n;
8518 free(t0);
8520 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8521 if (n < 0)
8522 return got_error_from_errno("fprintf");
8523 *off += n;
8525 return NULL;
8528 static const struct got_error *
8529 format_help(struct tog_help_view_state *s)
8531 const struct got_error *err = NULL;
8532 off_t off = 0;
8533 int i, max, n, show = s->all;
8534 static const struct tog_key_map km[] = {
8535 #define KEYMAP_(info, type) { NULL, (info), type }
8536 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8537 GENERATE_HELP
8538 #undef KEYMAP_
8539 #undef KEY_
8542 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8543 if (err)
8544 return err;
8546 n = nitems(km);
8547 err = max_key_str(&max, km, n);
8548 if (err)
8549 return err;
8551 for (i = 0; i < n; ++i) {
8552 if (km[i].keys == NULL) {
8553 show = s->all;
8554 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8555 km[i].type == s->type || s->all)
8556 show = 1;
8558 if (show) {
8559 err = format_help_line(&off, s->f, &km[i], max);
8560 if (err)
8561 return err;
8562 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8563 if (err)
8564 return err;
8567 fputc('\n', s->f);
8568 ++off;
8569 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8570 return err;
8573 static const struct got_error *
8574 create_help(struct tog_help_view_state *s)
8576 FILE *f;
8577 const struct got_error *err;
8579 free(s->line_offsets);
8580 s->line_offsets = NULL;
8581 s->nlines = 0;
8583 f = got_opentemp();
8584 if (f == NULL)
8585 return got_error_from_errno("got_opentemp");
8586 s->f = f;
8588 err = format_help(s);
8589 if (err)
8590 return err;
8592 if (s->f && fflush(s->f) != 0)
8593 return got_error_from_errno("fflush");
8595 return NULL;
8598 static const struct got_error *
8599 search_start_help_view(struct tog_view *view)
8601 view->state.help.matched_line = 0;
8602 return NULL;
8605 static void
8606 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8607 size_t *nlines, int **first, int **last, int **match, int **selected)
8609 struct tog_help_view_state *s = &view->state.help;
8611 *f = s->f;
8612 *nlines = s->nlines;
8613 *line_offsets = s->line_offsets;
8614 *match = &s->matched_line;
8615 *first = &s->first_displayed_line;
8616 *last = &s->last_displayed_line;
8617 *selected = &s->selected_line;
8620 static const struct got_error *
8621 show_help_view(struct tog_view *view)
8623 struct tog_help_view_state *s = &view->state.help;
8624 const struct got_error *err;
8625 regmatch_t *regmatch = &view->regmatch;
8626 wchar_t *wline;
8627 char *line;
8628 ssize_t linelen;
8629 size_t linesz = 0;
8630 int width, nprinted = 0, rc = 0;
8631 int eos = view->nlines;
8633 if (view_is_hsplit_top(view))
8634 --eos; /* account for border */
8636 s->lineno = 0;
8637 rewind(s->f);
8638 werase(view->window);
8640 if (view->gline > s->nlines - 1)
8641 view->gline = s->nlines - 1;
8643 err = win_draw_center(view->window, 0, 0, view->ncols,
8644 view_needs_focus_indication(view), "tog help");
8645 if (err)
8646 return err;
8647 if (eos <= 1)
8648 return NULL;
8649 waddstr(view->window, "\n\n");
8650 eos -= 2;
8652 s->eof = 0;
8653 view->maxx = 0;
8654 line = NULL;
8655 while (eos > 0 && nprinted < eos) {
8656 attr_t attr = 0;
8658 linelen = getline(&line, &linesz, s->f);
8659 if (linelen == -1) {
8660 if (!feof(s->f)) {
8661 free(line);
8662 return got_ferror(s->f, GOT_ERR_IO);
8664 s->eof = 1;
8665 break;
8667 if (++s->lineno < s->first_displayed_line)
8668 continue;
8669 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8670 continue;
8671 if (s->lineno == view->hiline)
8672 attr = A_STANDOUT;
8674 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8675 view->x ? 1 : 0);
8676 if (err) {
8677 free(line);
8678 return err;
8680 view->maxx = MAX(view->maxx, width);
8681 free(wline);
8682 wline = NULL;
8684 if (attr)
8685 wattron(view->window, attr);
8686 if (s->first_displayed_line + nprinted == s->matched_line &&
8687 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8688 err = add_matched_line(&width, line, view->ncols - 1, 0,
8689 view->window, view->x, regmatch);
8690 if (err) {
8691 free(line);
8692 return err;
8694 } else {
8695 int skip;
8697 err = format_line(&wline, &width, &skip, line,
8698 view->x, view->ncols - 1, 0, view->x ? 1 : 0);
8699 if (err) {
8700 free(line);
8701 return err;
8703 rc = waddwstr(view->window, &wline[skip]);
8704 free(wline);
8705 wline = NULL;
8706 if (rc == ERR)
8707 return got_error_msg(GOT_ERR_IO, "waddwstr");
8709 if (s->lineno == view->hiline) {
8710 while (width++ < view->ncols)
8711 waddch(view->window, ' ');
8712 } else {
8713 if (width <= view->ncols)
8714 waddch(view->window, '\n');
8716 if (attr)
8717 wattroff(view->window, attr);
8718 if (++nprinted == 1)
8719 s->first_displayed_line = s->lineno;
8721 free(line);
8722 if (nprinted > 0)
8723 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8724 else
8725 s->last_displayed_line = s->first_displayed_line;
8727 view_border(view);
8729 if (s->eof) {
8730 rc = waddnstr(view->window,
8731 "See the tog(1) manual page for full documentation",
8732 view->ncols - 1);
8733 if (rc == ERR)
8734 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8735 } else {
8736 wmove(view->window, view->nlines - 1, 0);
8737 wclrtoeol(view->window);
8738 wstandout(view->window);
8739 rc = waddnstr(view->window, "scroll down for more...",
8740 view->ncols - 1);
8741 if (rc == ERR)
8742 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8743 if (getcurx(view->window) < view->ncols - 6) {
8744 rc = wprintw(view->window, "[%.0f%%]",
8745 100.00 * s->last_displayed_line / s->nlines);
8746 if (rc == ERR)
8747 return got_error_msg(GOT_ERR_IO, "wprintw");
8749 wstandend(view->window);
8752 return NULL;
8755 static const struct got_error *
8756 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8758 struct tog_help_view_state *s = &view->state.help;
8759 const struct got_error *err = NULL;
8760 char *line = NULL;
8761 ssize_t linelen;
8762 size_t linesz = 0;
8763 int eos, nscroll;
8765 eos = nscroll = view->nlines;
8766 if (view_is_hsplit_top(view))
8767 --eos; /* border */
8769 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8771 switch (ch) {
8772 case '0':
8773 view->x = 0;
8774 break;
8775 case '$':
8776 view->x = MAX(view->maxx - view->ncols / 3, 0);
8777 view->count = 0;
8778 break;
8779 case KEY_RIGHT:
8780 case 'l':
8781 if (view->x + view->ncols / 3 < view->maxx)
8782 view->x += 2;
8783 else
8784 view->count = 0;
8785 break;
8786 case KEY_LEFT:
8787 case 'h':
8788 view->x -= MIN(view->x, 2);
8789 if (view->x <= 0)
8790 view->count = 0;
8791 break;
8792 case 'g':
8793 case KEY_HOME:
8794 s->first_displayed_line = 1;
8795 view->count = 0;
8796 break;
8797 case 'G':
8798 case KEY_END:
8799 view->count = 0;
8800 if (s->eof)
8801 break;
8802 s->first_displayed_line = (s->nlines - eos) + 3;
8803 s->eof = 1;
8804 break;
8805 case 'k':
8806 case KEY_UP:
8807 if (s->first_displayed_line > 1)
8808 --s->first_displayed_line;
8809 else
8810 view->count = 0;
8811 break;
8812 case CTRL('u'):
8813 case 'u':
8814 nscroll /= 2;
8815 /* FALL THROUGH */
8816 case KEY_PPAGE:
8817 case CTRL('b'):
8818 case 'b':
8819 if (s->first_displayed_line == 1) {
8820 view->count = 0;
8821 break;
8823 while (--nscroll > 0 && s->first_displayed_line > 1)
8824 s->first_displayed_line--;
8825 break;
8826 case 'j':
8827 case KEY_DOWN:
8828 case CTRL('n'):
8829 if (!s->eof)
8830 ++s->first_displayed_line;
8831 else
8832 view->count = 0;
8833 break;
8834 case CTRL('d'):
8835 case 'd':
8836 nscroll /= 2;
8837 /* FALL THROUGH */
8838 case KEY_NPAGE:
8839 case CTRL('f'):
8840 case 'f':
8841 case ' ':
8842 if (s->eof) {
8843 view->count = 0;
8844 break;
8846 while (!s->eof && --nscroll > 0) {
8847 linelen = getline(&line, &linesz, s->f);
8848 s->first_displayed_line++;
8849 if (linelen == -1) {
8850 if (feof(s->f))
8851 s->eof = 1;
8852 else
8853 err = got_ferror(s->f, GOT_ERR_IO);
8854 break;
8857 free(line);
8858 break;
8859 default:
8860 view->count = 0;
8861 break;
8864 return err;
8867 static const struct got_error *
8868 close_help_view(struct tog_view *view)
8870 struct tog_help_view_state *s = &view->state.help;
8872 free(s->line_offsets);
8873 s->line_offsets = NULL;
8874 if (fclose(s->f) == EOF)
8875 return got_error_from_errno("fclose");
8877 return NULL;
8880 static const struct got_error *
8881 reset_help_view(struct tog_view *view)
8883 struct tog_help_view_state *s = &view->state.help;
8886 if (s->f && fclose(s->f) == EOF)
8887 return got_error_from_errno("fclose");
8889 wclear(view->window);
8890 view->count = 0;
8891 view->x = 0;
8892 s->all = !s->all;
8893 s->first_displayed_line = 1;
8894 s->last_displayed_line = view->nlines;
8895 s->matched_line = 0;
8897 return create_help(s);
8900 static const struct got_error *
8901 open_help_view(struct tog_view *view, struct tog_view *parent)
8903 const struct got_error *err = NULL;
8904 struct tog_help_view_state *s = &view->state.help;
8906 s->type = (enum tog_keymap_type)parent->type;
8907 s->first_displayed_line = 1;
8908 s->last_displayed_line = view->nlines;
8909 s->selected_line = 1;
8911 view->show = show_help_view;
8912 view->input = input_help_view;
8913 view->reset = reset_help_view;
8914 view->close = close_help_view;
8915 view->search_start = search_start_help_view;
8916 view->search_setup = search_setup_help_view;
8917 view->search_next = search_next_view_match;
8919 err = create_help(s);
8920 return err;
8923 static const struct got_error *
8924 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8925 enum tog_view_type request, int y, int x)
8927 const struct got_error *err = NULL;
8929 *new_view = NULL;
8931 switch (request) {
8932 case TOG_VIEW_DIFF:
8933 if (view->type == TOG_VIEW_LOG) {
8934 struct tog_log_view_state *s = &view->state.log;
8936 err = open_diff_view_for_commit(new_view, y, x,
8937 s->selected_entry->commit, s->selected_entry->id,
8938 view, s->repo);
8939 } else
8940 return got_error_msg(GOT_ERR_NOT_IMPL,
8941 "parent/child view pair not supported");
8942 break;
8943 case TOG_VIEW_BLAME:
8944 if (view->type == TOG_VIEW_TREE) {
8945 struct tog_tree_view_state *s = &view->state.tree;
8947 err = blame_tree_entry(new_view, y, x,
8948 s->selected_entry, &s->parents, s->commit_id,
8949 s->repo);
8950 } else
8951 return got_error_msg(GOT_ERR_NOT_IMPL,
8952 "parent/child view pair not supported");
8953 break;
8954 case TOG_VIEW_LOG:
8955 if (view->type == TOG_VIEW_BLAME)
8956 err = log_annotated_line(new_view, y, x,
8957 view->state.blame.repo, view->state.blame.id_to_log);
8958 else if (view->type == TOG_VIEW_TREE)
8959 err = log_selected_tree_entry(new_view, y, x,
8960 &view->state.tree);
8961 else if (view->type == TOG_VIEW_REF)
8962 err = log_ref_entry(new_view, y, x,
8963 view->state.ref.selected_entry,
8964 view->state.ref.repo);
8965 else
8966 return got_error_msg(GOT_ERR_NOT_IMPL,
8967 "parent/child view pair not supported");
8968 break;
8969 case TOG_VIEW_TREE:
8970 if (view->type == TOG_VIEW_LOG)
8971 err = browse_commit_tree(new_view, y, x,
8972 view->state.log.selected_entry,
8973 view->state.log.in_repo_path,
8974 view->state.log.head_ref_name,
8975 view->state.log.repo);
8976 else if (view->type == TOG_VIEW_REF)
8977 err = browse_ref_tree(new_view, y, x,
8978 view->state.ref.selected_entry,
8979 view->state.ref.repo);
8980 else
8981 return got_error_msg(GOT_ERR_NOT_IMPL,
8982 "parent/child view pair not supported");
8983 break;
8984 case TOG_VIEW_REF:
8985 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8986 if (*new_view == NULL)
8987 return got_error_from_errno("view_open");
8988 if (view->type == TOG_VIEW_LOG)
8989 err = open_ref_view(*new_view, view->state.log.repo);
8990 else if (view->type == TOG_VIEW_TREE)
8991 err = open_ref_view(*new_view, view->state.tree.repo);
8992 else
8993 err = got_error_msg(GOT_ERR_NOT_IMPL,
8994 "parent/child view pair not supported");
8995 if (err)
8996 view_close(*new_view);
8997 break;
8998 case TOG_VIEW_HELP:
8999 *new_view = view_open(0, 0, y, x, TOG_VIEW_HELP);
9000 if (*new_view == NULL)
9001 return got_error_from_errno("view_open");
9002 err = open_help_view(*new_view, view);
9003 if (err)
9004 view_close(*new_view);
9005 break;
9006 default:
9007 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9010 return err;
9014 * If view was scrolled down to move the selected line into view when opening a
9015 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9017 static void
9018 offset_selection_up(struct tog_view *view)
9020 switch (view->type) {
9021 case TOG_VIEW_BLAME: {
9022 struct tog_blame_view_state *s = &view->state.blame;
9023 if (s->first_displayed_line == 1) {
9024 s->selected_line = MAX(s->selected_line - view->offset,
9025 1);
9026 break;
9028 if (s->first_displayed_line > view->offset)
9029 s->first_displayed_line -= view->offset;
9030 else
9031 s->first_displayed_line = 1;
9032 s->selected_line += view->offset;
9033 break;
9035 case TOG_VIEW_LOG:
9036 log_scroll_up(&view->state.log, view->offset);
9037 view->state.log.selected += view->offset;
9038 break;
9039 case TOG_VIEW_REF:
9040 ref_scroll_up(&view->state.ref, view->offset);
9041 view->state.ref.selected += view->offset;
9042 break;
9043 case TOG_VIEW_TREE:
9044 tree_scroll_up(&view->state.tree, view->offset);
9045 view->state.tree.selected += view->offset;
9046 break;
9047 default:
9048 break;
9051 view->offset = 0;
9055 * If the selected line is in the section of screen covered by the bottom split,
9056 * scroll down offset lines to move it into view and index its new position.
9058 static const struct got_error *
9059 offset_selection_down(struct tog_view *view)
9061 const struct got_error *err = NULL;
9062 const struct got_error *(*scrolld)(struct tog_view *, int);
9063 int *selected = NULL;
9064 int header, offset;
9066 switch (view->type) {
9067 case TOG_VIEW_BLAME: {
9068 struct tog_blame_view_state *s = &view->state.blame;
9069 header = 3;
9070 scrolld = NULL;
9071 if (s->selected_line > view->nlines - header) {
9072 offset = abs(view->nlines - s->selected_line - header);
9073 s->first_displayed_line += offset;
9074 s->selected_line -= offset;
9075 view->offset = offset;
9077 break;
9079 case TOG_VIEW_LOG: {
9080 struct tog_log_view_state *s = &view->state.log;
9081 scrolld = &log_scroll_down;
9082 header = view_is_parent_view(view) ? 3 : 2;
9083 selected = &s->selected;
9084 break;
9086 case TOG_VIEW_REF: {
9087 struct tog_ref_view_state *s = &view->state.ref;
9088 scrolld = &ref_scroll_down;
9089 header = 3;
9090 selected = &s->selected;
9091 break;
9093 case TOG_VIEW_TREE: {
9094 struct tog_tree_view_state *s = &view->state.tree;
9095 scrolld = &tree_scroll_down;
9096 header = 5;
9097 selected = &s->selected;
9098 break;
9100 default:
9101 selected = NULL;
9102 scrolld = NULL;
9103 header = 0;
9104 break;
9107 if (selected && *selected > view->nlines - header) {
9108 offset = abs(view->nlines - *selected - header);
9109 view->offset = offset;
9110 if (scrolld && offset) {
9111 err = scrolld(view, offset);
9112 *selected -= offset;
9116 return err;
9119 static void
9120 list_commands(FILE *fp)
9122 size_t i;
9124 fprintf(fp, "commands:");
9125 for (i = 0; i < nitems(tog_commands); i++) {
9126 const struct tog_cmd *cmd = &tog_commands[i];
9127 fprintf(fp, " %s", cmd->name);
9129 fputc('\n', fp);
9132 __dead static void
9133 usage(int hflag, int status)
9135 FILE *fp = (status == 0) ? stdout : stderr;
9137 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
9138 getprogname());
9139 if (hflag) {
9140 fprintf(fp, "lazy usage: %s path\n", getprogname());
9141 list_commands(fp);
9143 exit(status);
9146 static char **
9147 make_argv(int argc, ...)
9149 va_list ap;
9150 char **argv;
9151 int i;
9153 va_start(ap, argc);
9155 argv = calloc(argc, sizeof(char *));
9156 if (argv == NULL)
9157 err(1, "calloc");
9158 for (i = 0; i < argc; i++) {
9159 argv[i] = strdup(va_arg(ap, char *));
9160 if (argv[i] == NULL)
9161 err(1, "strdup");
9164 va_end(ap);
9165 return argv;
9169 * Try to convert 'tog path' into a 'tog log path' command.
9170 * The user could simply have mistyped the command rather than knowingly
9171 * provided a path. So check whether argv[0] can in fact be resolved
9172 * to a path in the HEAD commit and print a special error if not.
9173 * This hack is for mpi@ <3
9175 static const struct got_error *
9176 tog_log_with_path(int argc, char *argv[])
9178 const struct got_error *error = NULL, *close_err;
9179 const struct tog_cmd *cmd = NULL;
9180 struct got_repository *repo = NULL;
9181 struct got_worktree *worktree = NULL;
9182 struct got_object_id *commit_id = NULL, *id = NULL;
9183 struct got_commit_object *commit = NULL;
9184 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9185 char *commit_id_str = NULL, **cmd_argv = NULL;
9186 int *pack_fds = NULL;
9188 cwd = getcwd(NULL, 0);
9189 if (cwd == NULL)
9190 return got_error_from_errno("getcwd");
9192 error = got_repo_pack_fds_open(&pack_fds);
9193 if (error != NULL)
9194 goto done;
9196 error = got_worktree_open(&worktree, cwd);
9197 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9198 goto done;
9200 if (worktree)
9201 repo_path = strdup(got_worktree_get_repo_path(worktree));
9202 else
9203 repo_path = strdup(cwd);
9204 if (repo_path == NULL) {
9205 error = got_error_from_errno("strdup");
9206 goto done;
9209 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9210 if (error != NULL)
9211 goto done;
9213 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9214 repo, worktree);
9215 if (error)
9216 goto done;
9218 error = tog_load_refs(repo, 0);
9219 if (error)
9220 goto done;
9221 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9222 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9223 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9224 if (error)
9225 goto done;
9227 if (worktree) {
9228 got_worktree_close(worktree);
9229 worktree = NULL;
9232 error = got_object_open_as_commit(&commit, repo, commit_id);
9233 if (error)
9234 goto done;
9236 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9237 if (error) {
9238 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9239 goto done;
9240 fprintf(stderr, "%s: '%s' is no known command or path\n",
9241 getprogname(), argv[0]);
9242 usage(1, 1);
9243 /* not reached */
9246 error = got_object_id_str(&commit_id_str, commit_id);
9247 if (error)
9248 goto done;
9250 cmd = &tog_commands[0]; /* log */
9251 argc = 4;
9252 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9253 error = cmd->cmd_main(argc, cmd_argv);
9254 done:
9255 if (repo) {
9256 close_err = got_repo_close(repo);
9257 if (error == NULL)
9258 error = close_err;
9260 if (commit)
9261 got_object_commit_close(commit);
9262 if (worktree)
9263 got_worktree_close(worktree);
9264 if (pack_fds) {
9265 const struct got_error *pack_err =
9266 got_repo_pack_fds_close(pack_fds);
9267 if (error == NULL)
9268 error = pack_err;
9270 free(id);
9271 free(commit_id_str);
9272 free(commit_id);
9273 free(cwd);
9274 free(repo_path);
9275 free(in_repo_path);
9276 if (cmd_argv) {
9277 int i;
9278 for (i = 0; i < argc; i++)
9279 free(cmd_argv[i]);
9280 free(cmd_argv);
9282 tog_free_refs();
9283 return error;
9286 int
9287 main(int argc, char *argv[])
9289 const struct got_error *error = NULL;
9290 const struct tog_cmd *cmd = NULL;
9291 int ch, hflag = 0, Vflag = 0;
9292 char **cmd_argv = NULL;
9293 static const struct option longopts[] = {
9294 { "version", no_argument, NULL, 'V' },
9295 { NULL, 0, NULL, 0}
9297 char *diff_algo_str = NULL;
9299 if (!isatty(STDIN_FILENO))
9300 errx(1, "standard input is not a tty");
9302 setlocale(LC_CTYPE, "");
9304 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9305 switch (ch) {
9306 case 'h':
9307 hflag = 1;
9308 break;
9309 case 'V':
9310 Vflag = 1;
9311 break;
9312 default:
9313 usage(hflag, 1);
9314 /* NOTREACHED */
9318 argc -= optind;
9319 argv += optind;
9320 optind = 1;
9321 optreset = 1;
9323 if (Vflag) {
9324 got_version_print_str();
9325 return 0;
9328 #ifndef PROFILE
9329 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9330 NULL) == -1)
9331 err(1, "pledge");
9332 #endif
9334 if (argc == 0) {
9335 if (hflag)
9336 usage(hflag, 0);
9337 /* Build an argument vector which runs a default command. */
9338 cmd = &tog_commands[0];
9339 argc = 1;
9340 cmd_argv = make_argv(argc, cmd->name);
9341 } else {
9342 size_t i;
9344 /* Did the user specify a command? */
9345 for (i = 0; i < nitems(tog_commands); i++) {
9346 if (strncmp(tog_commands[i].name, argv[0],
9347 strlen(argv[0])) == 0) {
9348 cmd = &tog_commands[i];
9349 break;
9354 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9355 if (diff_algo_str) {
9356 if (strcasecmp(diff_algo_str, "patience") == 0)
9357 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9358 if (strcasecmp(diff_algo_str, "myers") == 0)
9359 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9362 if (cmd == NULL) {
9363 if (argc != 1)
9364 usage(0, 1);
9365 /* No command specified; try log with a path */
9366 error = tog_log_with_path(argc, argv);
9367 } else {
9368 if (hflag)
9369 cmd->cmd_usage();
9370 else
9371 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9374 endwin();
9375 putchar('\n');
9376 if (cmd_argv) {
9377 int i;
9378 for (i = 0; i < argc; i++)
9379 free(cmd_argv[i]);
9380 free(cmd_argv);
9383 if (error && error->code != GOT_ERR_CANCELLED)
9384 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9385 return 0;