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; Quit help screen"), \
555 KEY_("Q", "Quit tog"), \
557 KEYMAP_("Log view", 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 view", 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 view", 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 view", 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 view", 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_sigterm_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) && request != TOG_VIEW_HELP)
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 request != TOG_VIEW_HELP) {
1250 err = view_init_hsplit(view, y);
1251 if (err)
1252 return err;
1255 view->focussed = 0;
1256 new_view->focussed = 1;
1257 new_view->mode = view->mode;
1258 new_view->nlines = request == TOG_VIEW_HELP ?
1259 view->lines : view->lines - y;
1261 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1262 view_transfer_size(new_view, view);
1263 err = view_close_child(view);
1264 if (err)
1265 return err;
1266 err = view_set_child(view, new_view);
1267 if (err)
1268 return err;
1269 view->focus_child = 1;
1270 } else
1271 *requested = new_view;
1273 return NULL;
1276 static void
1277 tog_resizeterm(void)
1279 int cols, lines;
1280 struct winsize size;
1282 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1283 cols = 80; /* Default */
1284 lines = 24;
1285 } else {
1286 cols = size.ws_col;
1287 lines = size.ws_row;
1289 resize_term(lines, cols);
1292 static const struct got_error *
1293 view_search_start(struct tog_view *view)
1295 const struct got_error *err = NULL;
1296 struct tog_view *v = view;
1297 char pattern[1024];
1298 int ret;
1300 if (view->search_started) {
1301 regfree(&view->regex);
1302 view->searching = 0;
1303 memset(&view->regmatch, 0, sizeof(view->regmatch));
1305 view->search_started = 0;
1307 if (view->nlines < 1)
1308 return NULL;
1310 if (view_is_hsplit_top(view))
1311 v = view->child;
1313 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1314 wclrtoeol(v->window);
1316 nodelay(view->window, FALSE); /* block for search term input */
1317 nocbreak();
1318 echo();
1319 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1320 wrefresh(v->window);
1321 cbreak();
1322 noecho();
1323 nodelay(view->window, TRUE);
1324 if (ret == ERR)
1325 return NULL;
1327 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1328 err = view->search_start(view);
1329 if (err) {
1330 regfree(&view->regex);
1331 return err;
1333 view->search_started = 1;
1334 view->searching = TOG_SEARCH_FORWARD;
1335 view->search_next_done = 0;
1336 view->search_next(view);
1339 return NULL;
1342 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1343 static const struct got_error *
1344 switch_split(struct tog_view *view)
1346 const struct got_error *err = NULL;
1347 struct tog_view *v = NULL;
1349 if (view->parent)
1350 v = view->parent;
1351 else
1352 v = view;
1354 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1355 v->mode = TOG_VIEW_SPLIT_VERT;
1356 else
1357 v->mode = TOG_VIEW_SPLIT_HRZN;
1359 if (!v->child)
1360 return NULL;
1361 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1362 v->mode = TOG_VIEW_SPLIT_NONE;
1364 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1365 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1366 v->child->begin_y = v->child->resized_y;
1367 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1368 v->child->begin_x = v->child->resized_x;
1371 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1372 v->ncols = COLS;
1373 v->child->ncols = COLS;
1374 v->child->nscrolled = LINES - v->child->nlines;
1376 err = view_init_hsplit(v, v->child->begin_y);
1377 if (err)
1378 return err;
1380 v->child->mode = v->mode;
1381 v->child->nlines = v->lines - v->child->begin_y;
1382 v->focus_child = 1;
1384 err = view_fullscreen(v);
1385 if (err)
1386 return err;
1387 err = view_splitscreen(v->child);
1388 if (err)
1389 return err;
1391 if (v->mode == TOG_VIEW_SPLIT_NONE)
1392 v->mode = TOG_VIEW_SPLIT_VERT;
1393 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1394 err = offset_selection_down(v);
1395 if (err)
1396 return err;
1397 err = offset_selection_down(v->child);
1398 if (err)
1399 return err;
1400 } else {
1401 offset_selection_up(v);
1402 offset_selection_up(v->child);
1404 if (v->resize)
1405 err = v->resize(v, 0);
1406 else if (v->child->resize)
1407 err = v->child->resize(v->child, 0);
1409 return err;
1413 * Compute view->count from numeric input. Assign total to view->count and
1414 * return first non-numeric key entered.
1416 static int
1417 get_compound_key(struct tog_view *view, int c)
1419 struct tog_view *v = view;
1420 int x, n = 0;
1422 if (view_is_hsplit_top(view))
1423 v = view->child;
1424 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1425 v = view->parent;
1427 view->count = 0;
1428 cbreak(); /* block for input */
1429 nodelay(view->window, FALSE);
1430 wmove(v->window, v->nlines - 1, 0);
1431 wclrtoeol(v->window);
1432 waddch(v->window, ':');
1434 do {
1435 x = getcurx(v->window);
1436 if (x != ERR && x < view->ncols) {
1437 waddch(v->window, c);
1438 wrefresh(v->window);
1442 * Don't overflow. Max valid request should be the greatest
1443 * between the longest and total lines; cap at 10 million.
1445 if (n >= 9999999)
1446 n = 9999999;
1447 else
1448 n = n * 10 + (c - '0');
1449 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1451 if (c == 'G' || c == 'g') { /* nG key map */
1452 view->gline = view->hiline = n;
1453 n = 0;
1454 c = 0;
1457 /* Massage excessive or inapplicable values at the input handler. */
1458 view->count = n;
1460 return c;
1463 static const struct got_error *
1464 view_input(struct tog_view **new, int *done, struct tog_view *view,
1465 struct tog_view_list_head *views)
1467 const struct got_error *err = NULL;
1468 struct tog_view *v;
1469 int ch, errcode;
1471 *new = NULL;
1473 /* Clear "no matches" indicator. */
1474 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1475 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1476 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1477 view->count = 0;
1480 if (view->searching && !view->search_next_done) {
1481 errcode = pthread_mutex_unlock(&tog_mutex);
1482 if (errcode)
1483 return got_error_set_errno(errcode,
1484 "pthread_mutex_unlock");
1485 sched_yield();
1486 errcode = pthread_mutex_lock(&tog_mutex);
1487 if (errcode)
1488 return got_error_set_errno(errcode,
1489 "pthread_mutex_lock");
1490 view->search_next(view);
1491 return NULL;
1494 /* Allow threads to make progress while we are waiting for input. */
1495 errcode = pthread_mutex_unlock(&tog_mutex);
1496 if (errcode)
1497 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1498 /* If we have an unfinished count, let C-g or backspace abort. */
1499 if (view->count && --view->count) {
1500 cbreak();
1501 nodelay(view->window, TRUE);
1502 ch = wgetch(view->window);
1503 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1504 view->count = 0;
1505 else
1506 ch = view->ch;
1507 } else {
1508 ch = wgetch(view->window);
1509 if (ch >= '1' && ch <= '9')
1510 view->ch = ch = get_compound_key(view, ch);
1512 if (view->hiline && ch != ERR && ch != 0)
1513 view->hiline = 0; /* key pressed, clear line highlight */
1514 nodelay(view->window, TRUE);
1515 errcode = pthread_mutex_lock(&tog_mutex);
1516 if (errcode)
1517 return got_error_set_errno(errcode, "pthread_mutex_lock");
1519 if (tog_sigwinch_received || tog_sigcont_received) {
1520 tog_resizeterm();
1521 tog_sigwinch_received = 0;
1522 tog_sigcont_received = 0;
1523 TAILQ_FOREACH(v, views, entry) {
1524 err = view_resize(v);
1525 if (err)
1526 return err;
1527 err = v->input(new, v, KEY_RESIZE);
1528 if (err)
1529 return err;
1530 if (v->child) {
1531 err = view_resize(v->child);
1532 if (err)
1533 return err;
1534 err = v->child->input(new, v->child,
1535 KEY_RESIZE);
1536 if (err)
1537 return err;
1538 if (v->child->resized_x || v->child->resized_y) {
1539 err = view_resize_split(v, 0);
1540 if (err)
1541 return err;
1547 switch (ch) {
1548 case '?':
1549 case 'H':
1550 case KEY_F(1):
1551 if (view->type == TOG_VIEW_HELP)
1552 err = view->reset(view);
1553 else
1554 err = view_request_new(new, view, TOG_VIEW_HELP);
1555 break;
1556 case '\t':
1557 view->count = 0;
1558 if (view->child) {
1559 view->focussed = 0;
1560 view->child->focussed = 1;
1561 view->focus_child = 1;
1562 } else if (view->parent) {
1563 view->focussed = 0;
1564 view->parent->focussed = 1;
1565 view->parent->focus_child = 0;
1566 if (!view_is_splitscreen(view)) {
1567 if (view->parent->resize) {
1568 err = view->parent->resize(view->parent,
1569 0);
1570 if (err)
1571 return err;
1573 offset_selection_up(view->parent);
1574 err = view_fullscreen(view->parent);
1575 if (err)
1576 return err;
1579 break;
1580 case 'q':
1581 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1582 if (view->parent->resize) {
1583 /* might need more commits to fill fullscreen */
1584 err = view->parent->resize(view->parent, 0);
1585 if (err)
1586 break;
1588 offset_selection_up(view->parent);
1590 err = view->input(new, view, ch);
1591 view->dying = 1;
1592 break;
1593 case 'Q':
1594 *done = 1;
1595 break;
1596 case 'F':
1597 view->count = 0;
1598 if (view_is_parent_view(view)) {
1599 if (view->child == NULL)
1600 break;
1601 if (view_is_splitscreen(view->child)) {
1602 view->focussed = 0;
1603 view->child->focussed = 1;
1604 err = view_fullscreen(view->child);
1605 } else {
1606 err = view_splitscreen(view->child);
1607 if (!err)
1608 err = view_resize_split(view, 0);
1610 if (err)
1611 break;
1612 err = view->child->input(new, view->child,
1613 KEY_RESIZE);
1614 } else {
1615 if (view_is_splitscreen(view)) {
1616 view->parent->focussed = 0;
1617 view->focussed = 1;
1618 err = view_fullscreen(view);
1619 } else {
1620 err = view_splitscreen(view);
1621 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1622 err = view_resize(view->parent);
1623 if (!err)
1624 err = view_resize_split(view, 0);
1626 if (err)
1627 break;
1628 err = view->input(new, view, KEY_RESIZE);
1630 if (err)
1631 break;
1632 if (view->resize) {
1633 err = view->resize(view, 0);
1634 if (err)
1635 break;
1637 if (view->parent)
1638 err = offset_selection_down(view->parent);
1639 if (!err)
1640 err = offset_selection_down(view);
1641 break;
1642 case 'S':
1643 view->count = 0;
1644 err = switch_split(view);
1645 break;
1646 case '-':
1647 err = view_resize_split(view, -1);
1648 break;
1649 case '+':
1650 err = view_resize_split(view, 1);
1651 break;
1652 case KEY_RESIZE:
1653 break;
1654 case '/':
1655 view->count = 0;
1656 if (view->search_start)
1657 view_search_start(view);
1658 else
1659 err = view->input(new, view, ch);
1660 break;
1661 case 'N':
1662 case 'n':
1663 if (view->search_started && view->search_next) {
1664 view->searching = (ch == 'n' ?
1665 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1666 view->search_next_done = 0;
1667 view->search_next(view);
1668 } else
1669 err = view->input(new, view, ch);
1670 break;
1671 case 'A':
1672 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1673 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1674 else
1675 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1676 TAILQ_FOREACH(v, views, entry) {
1677 if (v->reset) {
1678 err = v->reset(v);
1679 if (err)
1680 return err;
1682 if (v->child && v->child->reset) {
1683 err = v->child->reset(v->child);
1684 if (err)
1685 return err;
1688 break;
1689 default:
1690 err = view->input(new, view, ch);
1691 break;
1694 return err;
1697 static int
1698 view_needs_focus_indication(struct tog_view *view)
1700 if (view_is_parent_view(view)) {
1701 if (view->child == NULL || view->child->focussed)
1702 return 0;
1703 if (!view_is_splitscreen(view->child))
1704 return 0;
1705 } else if (!view_is_splitscreen(view))
1706 return 0;
1708 return view->focussed;
1711 static const struct got_error *
1712 view_loop(struct tog_view *view)
1714 const struct got_error *err = NULL;
1715 struct tog_view_list_head views;
1716 struct tog_view *new_view;
1717 char *mode;
1718 int fast_refresh = 10;
1719 int done = 0, errcode;
1721 mode = getenv("TOG_VIEW_SPLIT_MODE");
1722 if (!mode || !(*mode == 'h' || *mode == 'H'))
1723 view->mode = TOG_VIEW_SPLIT_VERT;
1724 else
1725 view->mode = TOG_VIEW_SPLIT_HRZN;
1727 errcode = pthread_mutex_lock(&tog_mutex);
1728 if (errcode)
1729 return got_error_set_errno(errcode, "pthread_mutex_lock");
1731 TAILQ_INIT(&views);
1732 TAILQ_INSERT_HEAD(&views, view, entry);
1734 view->focussed = 1;
1735 err = view->show(view);
1736 if (err)
1737 return err;
1738 update_panels();
1739 doupdate();
1740 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1741 !tog_fatal_signal_received()) {
1742 /* Refresh fast during initialization, then become slower. */
1743 if (fast_refresh && fast_refresh-- == 0)
1744 halfdelay(10); /* switch to once per second */
1746 err = view_input(&new_view, &done, view, &views);
1747 if (err)
1748 break;
1749 if (view->dying) {
1750 struct tog_view *v, *prev = NULL;
1752 if (view_is_parent_view(view))
1753 prev = TAILQ_PREV(view, tog_view_list_head,
1754 entry);
1755 else if (view->parent)
1756 prev = view->parent;
1758 if (view->parent) {
1759 view->parent->child = NULL;
1760 view->parent->focus_child = 0;
1761 /* Restore fullscreen line height. */
1762 view->parent->nlines = view->parent->lines;
1763 err = view_resize(view->parent);
1764 if (err)
1765 break;
1766 /* Make resized splits persist. */
1767 view_transfer_size(view->parent, view);
1768 } else
1769 TAILQ_REMOVE(&views, view, entry);
1771 err = view_close(view);
1772 if (err)
1773 goto done;
1775 view = NULL;
1776 TAILQ_FOREACH(v, &views, entry) {
1777 if (v->focussed)
1778 break;
1780 if (view == NULL && new_view == NULL) {
1781 /* No view has focus. Try to pick one. */
1782 if (prev)
1783 view = prev;
1784 else if (!TAILQ_EMPTY(&views)) {
1785 view = TAILQ_LAST(&views,
1786 tog_view_list_head);
1788 if (view) {
1789 if (view->focus_child) {
1790 view->child->focussed = 1;
1791 view = view->child;
1792 } else
1793 view->focussed = 1;
1797 if (new_view) {
1798 struct tog_view *v, *t;
1799 /* Only allow one parent view per type. */
1800 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1801 if (v->type != new_view->type)
1802 continue;
1803 TAILQ_REMOVE(&views, v, entry);
1804 err = view_close(v);
1805 if (err)
1806 goto done;
1807 break;
1809 TAILQ_INSERT_TAIL(&views, new_view, entry);
1810 view = new_view;
1812 if (view) {
1813 if (view_is_parent_view(view)) {
1814 if (view->child && view->child->focussed)
1815 view = view->child;
1816 } else {
1817 if (view->parent && view->parent->focussed)
1818 view = view->parent;
1820 show_panel(view->panel);
1821 if (view->child && view_is_splitscreen(view->child))
1822 show_panel(view->child->panel);
1823 if (view->parent && view_is_splitscreen(view)) {
1824 err = view->parent->show(view->parent);
1825 if (err)
1826 goto done;
1828 err = view->show(view);
1829 if (err)
1830 goto done;
1831 if (view->child) {
1832 err = view->child->show(view->child);
1833 if (err)
1834 goto done;
1836 update_panels();
1837 doupdate();
1840 done:
1841 while (!TAILQ_EMPTY(&views)) {
1842 const struct got_error *close_err;
1843 view = TAILQ_FIRST(&views);
1844 TAILQ_REMOVE(&views, view, entry);
1845 close_err = view_close(view);
1846 if (close_err && err == NULL)
1847 err = close_err;
1850 errcode = pthread_mutex_unlock(&tog_mutex);
1851 if (errcode && err == NULL)
1852 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1854 return err;
1857 __dead static void
1858 usage_log(void)
1860 endwin();
1861 fprintf(stderr,
1862 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1863 getprogname());
1864 exit(1);
1867 /* Create newly allocated wide-character string equivalent to a byte string. */
1868 static const struct got_error *
1869 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1871 char *vis = NULL;
1872 const struct got_error *err = NULL;
1874 *ws = NULL;
1875 *wlen = mbstowcs(NULL, s, 0);
1876 if (*wlen == (size_t)-1) {
1877 int vislen;
1878 if (errno != EILSEQ)
1879 return got_error_from_errno("mbstowcs");
1881 /* byte string invalid in current encoding; try to "fix" it */
1882 err = got_mbsavis(&vis, &vislen, s);
1883 if (err)
1884 return err;
1885 *wlen = mbstowcs(NULL, vis, 0);
1886 if (*wlen == (size_t)-1) {
1887 err = got_error_from_errno("mbstowcs"); /* give up */
1888 goto done;
1892 *ws = calloc(*wlen + 1, sizeof(**ws));
1893 if (*ws == NULL) {
1894 err = got_error_from_errno("calloc");
1895 goto done;
1898 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1899 err = got_error_from_errno("mbstowcs");
1900 done:
1901 free(vis);
1902 if (err) {
1903 free(*ws);
1904 *ws = NULL;
1905 *wlen = 0;
1907 return err;
1910 static const struct got_error *
1911 expand_tab(char **ptr, const char *src)
1913 char *dst;
1914 size_t len, n, idx = 0, sz = 0;
1916 *ptr = NULL;
1917 n = len = strlen(src);
1918 dst = malloc(n + 1);
1919 if (dst == NULL)
1920 return got_error_from_errno("malloc");
1922 while (idx < len && src[idx]) {
1923 const char c = src[idx];
1925 if (c == '\t') {
1926 size_t nb = TABSIZE - sz % TABSIZE;
1927 char *p;
1929 p = realloc(dst, n + nb);
1930 if (p == NULL) {
1931 free(dst);
1932 return got_error_from_errno("realloc");
1935 dst = p;
1936 n += nb;
1937 memset(dst + sz, ' ', nb);
1938 sz += nb;
1939 } else
1940 dst[sz++] = src[idx];
1941 ++idx;
1944 dst[sz] = '\0';
1945 *ptr = dst;
1946 return NULL;
1950 * Advance at most n columns from wline starting at offset off.
1951 * Return the index to the first character after the span operation.
1952 * Return the combined column width of all spanned wide character in
1953 * *rcol.
1955 static int
1956 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1958 int width, i, cols = 0;
1960 if (n == 0) {
1961 *rcol = cols;
1962 return off;
1965 for (i = off; wline[i] != L'\0'; ++i) {
1966 if (wline[i] == L'\t')
1967 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1968 else
1969 width = wcwidth(wline[i]);
1971 if (width == -1) {
1972 width = 1;
1973 wline[i] = L'.';
1976 if (cols + width > n)
1977 break;
1978 cols += width;
1981 *rcol = cols;
1982 return i;
1986 * Format a line for display, ensuring that it won't overflow a width limit.
1987 * With scrolling, the width returned refers to the scrolled version of the
1988 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1990 static const struct got_error *
1991 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1992 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1994 const struct got_error *err = NULL;
1995 int cols;
1996 wchar_t *wline = NULL;
1997 char *exstr = NULL;
1998 size_t wlen;
1999 int i, scrollx;
2001 *wlinep = NULL;
2002 *widthp = 0;
2004 if (expand) {
2005 err = expand_tab(&exstr, line);
2006 if (err)
2007 return err;
2010 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2011 free(exstr);
2012 if (err)
2013 return err;
2015 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2017 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2018 wline[wlen - 1] = L'\0';
2019 wlen--;
2021 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2022 wline[wlen - 1] = L'\0';
2023 wlen--;
2026 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2027 wline[i] = L'\0';
2029 if (widthp)
2030 *widthp = cols;
2031 if (scrollxp)
2032 *scrollxp = scrollx;
2033 if (err)
2034 free(wline);
2035 else
2036 *wlinep = wline;
2037 return err;
2040 static const struct got_error*
2041 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2042 struct got_object_id *id, struct got_repository *repo)
2044 static const struct got_error *err = NULL;
2045 struct got_reflist_entry *re;
2046 char *s;
2047 const char *name;
2049 *refs_str = NULL;
2051 TAILQ_FOREACH(re, refs, entry) {
2052 struct got_tag_object *tag = NULL;
2053 struct got_object_id *ref_id;
2054 int cmp;
2056 name = got_ref_get_name(re->ref);
2057 if (strcmp(name, GOT_REF_HEAD) == 0)
2058 continue;
2059 if (strncmp(name, "refs/", 5) == 0)
2060 name += 5;
2061 if (strncmp(name, "got/", 4) == 0 &&
2062 strncmp(name, "got/backup/", 11) != 0)
2063 continue;
2064 if (strncmp(name, "heads/", 6) == 0)
2065 name += 6;
2066 if (strncmp(name, "remotes/", 8) == 0) {
2067 name += 8;
2068 s = strstr(name, "/" GOT_REF_HEAD);
2069 if (s != NULL && s[strlen(s)] == '\0')
2070 continue;
2072 err = got_ref_resolve(&ref_id, repo, re->ref);
2073 if (err)
2074 break;
2075 if (strncmp(name, "tags/", 5) == 0) {
2076 err = got_object_open_as_tag(&tag, repo, ref_id);
2077 if (err) {
2078 if (err->code != GOT_ERR_OBJ_TYPE) {
2079 free(ref_id);
2080 break;
2082 /* Ref points at something other than a tag. */
2083 err = NULL;
2084 tag = NULL;
2087 cmp = got_object_id_cmp(tag ?
2088 got_object_tag_get_object_id(tag) : ref_id, id);
2089 free(ref_id);
2090 if (tag)
2091 got_object_tag_close(tag);
2092 if (cmp != 0)
2093 continue;
2094 s = *refs_str;
2095 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2096 s ? ", " : "", name) == -1) {
2097 err = got_error_from_errno("asprintf");
2098 free(s);
2099 *refs_str = NULL;
2100 break;
2102 free(s);
2105 return err;
2108 static const struct got_error *
2109 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2110 int col_tab_align)
2112 char *smallerthan;
2114 smallerthan = strchr(author, '<');
2115 if (smallerthan && smallerthan[1] != '\0')
2116 author = smallerthan + 1;
2117 author[strcspn(author, "@>")] = '\0';
2118 return format_line(wauthor, author_width, NULL, author, 0, limit,
2119 col_tab_align, 0);
2122 static const struct got_error *
2123 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2124 struct got_object_id *id, const size_t date_display_cols,
2125 int author_display_cols)
2127 struct tog_log_view_state *s = &view->state.log;
2128 const struct got_error *err = NULL;
2129 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2130 char *logmsg0 = NULL, *logmsg = NULL;
2131 char *author = NULL;
2132 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2133 int author_width, logmsg_width;
2134 char *newline, *line = NULL;
2135 int col, limit, scrollx;
2136 const int avail = view->ncols;
2137 struct tm tm;
2138 time_t committer_time;
2139 struct tog_color *tc;
2141 committer_time = got_object_commit_get_committer_time(commit);
2142 if (gmtime_r(&committer_time, &tm) == NULL)
2143 return got_error_from_errno("gmtime_r");
2144 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2145 return got_error(GOT_ERR_NO_SPACE);
2147 if (avail <= date_display_cols)
2148 limit = MIN(sizeof(datebuf) - 1, avail);
2149 else
2150 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2151 tc = get_color(&s->colors, TOG_COLOR_DATE);
2152 if (tc)
2153 wattr_on(view->window,
2154 COLOR_PAIR(tc->colorpair), NULL);
2155 waddnstr(view->window, datebuf, limit);
2156 if (tc)
2157 wattr_off(view->window,
2158 COLOR_PAIR(tc->colorpair), NULL);
2159 col = limit;
2160 if (col > avail)
2161 goto done;
2163 if (avail >= 120) {
2164 char *id_str;
2165 err = got_object_id_str(&id_str, id);
2166 if (err)
2167 goto done;
2168 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2169 if (tc)
2170 wattr_on(view->window,
2171 COLOR_PAIR(tc->colorpair), NULL);
2172 wprintw(view->window, "%.8s ", id_str);
2173 if (tc)
2174 wattr_off(view->window,
2175 COLOR_PAIR(tc->colorpair), NULL);
2176 free(id_str);
2177 col += 9;
2178 if (col > avail)
2179 goto done;
2182 if (s->use_committer)
2183 author = strdup(got_object_commit_get_committer(commit));
2184 else
2185 author = strdup(got_object_commit_get_author(commit));
2186 if (author == NULL) {
2187 err = got_error_from_errno("strdup");
2188 goto done;
2190 err = format_author(&wauthor, &author_width, author, avail - col, col);
2191 if (err)
2192 goto done;
2193 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2194 if (tc)
2195 wattr_on(view->window,
2196 COLOR_PAIR(tc->colorpair), NULL);
2197 waddwstr(view->window, wauthor);
2198 col += author_width;
2199 while (col < avail && author_width < author_display_cols + 2) {
2200 waddch(view->window, ' ');
2201 col++;
2202 author_width++;
2204 if (tc)
2205 wattr_off(view->window,
2206 COLOR_PAIR(tc->colorpair), NULL);
2207 if (col > avail)
2208 goto done;
2210 err = got_object_commit_get_logmsg(&logmsg0, commit);
2211 if (err)
2212 goto done;
2213 logmsg = logmsg0;
2214 while (*logmsg == '\n')
2215 logmsg++;
2216 newline = strchr(logmsg, '\n');
2217 if (newline)
2218 *newline = '\0';
2219 limit = avail - col;
2220 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2221 limit--; /* for the border */
2222 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2223 limit, col, 1);
2224 if (err)
2225 goto done;
2226 waddwstr(view->window, &wlogmsg[scrollx]);
2227 col += MAX(logmsg_width, 0);
2228 while (col < avail) {
2229 waddch(view->window, ' ');
2230 col++;
2232 done:
2233 free(logmsg0);
2234 free(wlogmsg);
2235 free(author);
2236 free(wauthor);
2237 free(line);
2238 return err;
2241 static struct commit_queue_entry *
2242 alloc_commit_queue_entry(struct got_commit_object *commit,
2243 struct got_object_id *id)
2245 struct commit_queue_entry *entry;
2246 struct got_object_id *dup;
2248 entry = calloc(1, sizeof(*entry));
2249 if (entry == NULL)
2250 return NULL;
2252 dup = got_object_id_dup(id);
2253 if (dup == NULL) {
2254 free(entry);
2255 return NULL;
2258 entry->id = dup;
2259 entry->commit = commit;
2260 return entry;
2263 static void
2264 pop_commit(struct commit_queue *commits)
2266 struct commit_queue_entry *entry;
2268 entry = TAILQ_FIRST(&commits->head);
2269 TAILQ_REMOVE(&commits->head, entry, entry);
2270 got_object_commit_close(entry->commit);
2271 commits->ncommits--;
2272 free(entry->id);
2273 free(entry);
2276 static void
2277 free_commits(struct commit_queue *commits)
2279 while (!TAILQ_EMPTY(&commits->head))
2280 pop_commit(commits);
2283 static const struct got_error *
2284 match_commit(int *have_match, struct got_object_id *id,
2285 struct got_commit_object *commit, regex_t *regex)
2287 const struct got_error *err = NULL;
2288 regmatch_t regmatch;
2289 char *id_str = NULL, *logmsg = NULL;
2291 *have_match = 0;
2293 err = got_object_id_str(&id_str, id);
2294 if (err)
2295 return err;
2297 err = got_object_commit_get_logmsg(&logmsg, commit);
2298 if (err)
2299 goto done;
2301 if (regexec(regex, got_object_commit_get_author(commit), 1,
2302 &regmatch, 0) == 0 ||
2303 regexec(regex, got_object_commit_get_committer(commit), 1,
2304 &regmatch, 0) == 0 ||
2305 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2306 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2307 *have_match = 1;
2308 done:
2309 free(id_str);
2310 free(logmsg);
2311 return err;
2314 static const struct got_error *
2315 queue_commits(struct tog_log_thread_args *a)
2317 const struct got_error *err = NULL;
2320 * We keep all commits open throughout the lifetime of the log
2321 * view in order to avoid having to re-fetch commits from disk
2322 * while updating the display.
2324 do {
2325 struct got_object_id id;
2326 struct got_commit_object *commit;
2327 struct commit_queue_entry *entry;
2328 int limit_match = 0;
2329 int errcode;
2331 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2332 NULL, NULL);
2333 if (err)
2334 break;
2336 err = got_object_open_as_commit(&commit, a->repo, &id);
2337 if (err)
2338 break;
2339 entry = alloc_commit_queue_entry(commit, &id);
2340 if (entry == NULL) {
2341 err = got_error_from_errno("alloc_commit_queue_entry");
2342 break;
2345 errcode = pthread_mutex_lock(&tog_mutex);
2346 if (errcode) {
2347 err = got_error_set_errno(errcode,
2348 "pthread_mutex_lock");
2349 break;
2352 entry->idx = a->real_commits->ncommits;
2353 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2354 a->real_commits->ncommits++;
2356 if (*a->limiting) {
2357 err = match_commit(&limit_match, &id, commit,
2358 a->limit_regex);
2359 if (err)
2360 break;
2362 if (limit_match) {
2363 struct commit_queue_entry *matched;
2365 matched = alloc_commit_queue_entry(
2366 entry->commit, entry->id);
2367 if (matched == NULL) {
2368 err = got_error_from_errno(
2369 "alloc_commit_queue_entry");
2370 break;
2372 matched->commit = entry->commit;
2373 got_object_commit_retain(entry->commit);
2375 matched->idx = a->limit_commits->ncommits;
2376 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2377 matched, entry);
2378 a->limit_commits->ncommits++;
2382 * This is how we signal log_thread() that we
2383 * have found a match, and that it should be
2384 * counted as a new entry for the view.
2386 a->limit_match = limit_match;
2389 if (*a->searching == TOG_SEARCH_FORWARD &&
2390 !*a->search_next_done) {
2391 int have_match;
2392 err = match_commit(&have_match, &id, commit, a->regex);
2393 if (err)
2394 break;
2396 if (*a->limiting) {
2397 if (limit_match && have_match)
2398 *a->search_next_done =
2399 TOG_SEARCH_HAVE_MORE;
2400 } else if (have_match)
2401 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2404 errcode = pthread_mutex_unlock(&tog_mutex);
2405 if (errcode && err == NULL)
2406 err = got_error_set_errno(errcode,
2407 "pthread_mutex_unlock");
2408 if (err)
2409 break;
2410 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2412 return err;
2415 static void
2416 select_commit(struct tog_log_view_state *s)
2418 struct commit_queue_entry *entry;
2419 int ncommits = 0;
2421 entry = s->first_displayed_entry;
2422 while (entry) {
2423 if (ncommits == s->selected) {
2424 s->selected_entry = entry;
2425 break;
2427 entry = TAILQ_NEXT(entry, entry);
2428 ncommits++;
2432 static const struct got_error *
2433 draw_commits(struct tog_view *view)
2435 const struct got_error *err = NULL;
2436 struct tog_log_view_state *s = &view->state.log;
2437 struct commit_queue_entry *entry = s->selected_entry;
2438 int limit = view->nlines;
2439 int width;
2440 int ncommits, author_cols = 4;
2441 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2442 char *refs_str = NULL;
2443 wchar_t *wline;
2444 struct tog_color *tc;
2445 static const size_t date_display_cols = 12;
2447 if (view_is_hsplit_top(view))
2448 --limit; /* account for border */
2450 if (s->selected_entry &&
2451 !(view->searching && view->search_next_done == 0)) {
2452 struct got_reflist_head *refs;
2453 err = got_object_id_str(&id_str, s->selected_entry->id);
2454 if (err)
2455 return err;
2456 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2457 s->selected_entry->id);
2458 if (refs) {
2459 err = build_refs_str(&refs_str, refs,
2460 s->selected_entry->id, s->repo);
2461 if (err)
2462 goto done;
2466 if (s->thread_args.commits_needed == 0)
2467 halfdelay(10); /* disable fast refresh */
2469 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2470 if (asprintf(&ncommits_str, " [%d/%d] %s",
2471 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2472 (view->searching && !view->search_next_done) ?
2473 "searching..." : "loading...") == -1) {
2474 err = got_error_from_errno("asprintf");
2475 goto done;
2477 } else {
2478 const char *search_str = NULL;
2479 const char *limit_str = NULL;
2481 if (view->searching) {
2482 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2483 search_str = "no more matches";
2484 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2485 search_str = "no matches found";
2486 else if (!view->search_next_done)
2487 search_str = "searching...";
2490 if (s->limit_view && s->commits->ncommits == 0)
2491 limit_str = "no matches found";
2493 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2494 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2495 search_str ? search_str : (refs_str ? refs_str : ""),
2496 limit_str ? limit_str : "") == -1) {
2497 err = got_error_from_errno("asprintf");
2498 goto done;
2502 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2503 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2504 "........................................",
2505 s->in_repo_path, ncommits_str) == -1) {
2506 err = got_error_from_errno("asprintf");
2507 header = NULL;
2508 goto done;
2510 } else if (asprintf(&header, "commit %s%s",
2511 id_str ? id_str : "........................................",
2512 ncommits_str) == -1) {
2513 err = got_error_from_errno("asprintf");
2514 header = NULL;
2515 goto done;
2517 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2518 if (err)
2519 goto done;
2521 werase(view->window);
2523 if (view_needs_focus_indication(view))
2524 wstandout(view->window);
2525 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2526 if (tc)
2527 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2528 waddwstr(view->window, wline);
2529 while (width < view->ncols) {
2530 waddch(view->window, ' ');
2531 width++;
2533 if (tc)
2534 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2535 if (view_needs_focus_indication(view))
2536 wstandend(view->window);
2537 free(wline);
2538 if (limit <= 1)
2539 goto done;
2541 /* Grow author column size if necessary, and set view->maxx. */
2542 entry = s->first_displayed_entry;
2543 ncommits = 0;
2544 view->maxx = 0;
2545 while (entry) {
2546 struct got_commit_object *c = entry->commit;
2547 char *author, *eol, *msg, *msg0;
2548 wchar_t *wauthor, *wmsg;
2549 int width;
2550 if (ncommits >= limit - 1)
2551 break;
2552 if (s->use_committer)
2553 author = strdup(got_object_commit_get_committer(c));
2554 else
2555 author = strdup(got_object_commit_get_author(c));
2556 if (author == NULL) {
2557 err = got_error_from_errno("strdup");
2558 goto done;
2560 err = format_author(&wauthor, &width, author, COLS,
2561 date_display_cols);
2562 if (author_cols < width)
2563 author_cols = width;
2564 free(wauthor);
2565 free(author);
2566 if (err)
2567 goto done;
2568 err = got_object_commit_get_logmsg(&msg0, c);
2569 if (err)
2570 goto done;
2571 msg = msg0;
2572 while (*msg == '\n')
2573 ++msg;
2574 if ((eol = strchr(msg, '\n')))
2575 *eol = '\0';
2576 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2577 date_display_cols + author_cols, 0);
2578 if (err)
2579 goto done;
2580 view->maxx = MAX(view->maxx, width);
2581 free(msg0);
2582 free(wmsg);
2583 ncommits++;
2584 entry = TAILQ_NEXT(entry, entry);
2587 entry = s->first_displayed_entry;
2588 s->last_displayed_entry = s->first_displayed_entry;
2589 ncommits = 0;
2590 while (entry) {
2591 if (ncommits >= limit - 1)
2592 break;
2593 if (ncommits == s->selected)
2594 wstandout(view->window);
2595 err = draw_commit(view, entry->commit, entry->id,
2596 date_display_cols, author_cols);
2597 if (ncommits == s->selected)
2598 wstandend(view->window);
2599 if (err)
2600 goto done;
2601 ncommits++;
2602 s->last_displayed_entry = entry;
2603 entry = TAILQ_NEXT(entry, entry);
2606 view_border(view);
2607 done:
2608 free(id_str);
2609 free(refs_str);
2610 free(ncommits_str);
2611 free(header);
2612 return err;
2615 static void
2616 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2618 struct commit_queue_entry *entry;
2619 int nscrolled = 0;
2621 entry = TAILQ_FIRST(&s->commits->head);
2622 if (s->first_displayed_entry == entry)
2623 return;
2625 entry = s->first_displayed_entry;
2626 while (entry && nscrolled < maxscroll) {
2627 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2628 if (entry) {
2629 s->first_displayed_entry = entry;
2630 nscrolled++;
2635 static const struct got_error *
2636 trigger_log_thread(struct tog_view *view, int wait)
2638 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2639 int errcode;
2641 halfdelay(1); /* fast refresh while loading commits */
2643 while (!ta->log_complete && !tog_thread_error &&
2644 (ta->commits_needed > 0 || ta->load_all)) {
2645 /* Wake the log thread. */
2646 errcode = pthread_cond_signal(&ta->need_commits);
2647 if (errcode)
2648 return got_error_set_errno(errcode,
2649 "pthread_cond_signal");
2652 * The mutex will be released while the view loop waits
2653 * in wgetch(), at which time the log thread will run.
2655 if (!wait)
2656 break;
2658 /* Display progress update in log view. */
2659 show_log_view(view);
2660 update_panels();
2661 doupdate();
2663 /* Wait right here while next commit is being loaded. */
2664 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2665 if (errcode)
2666 return got_error_set_errno(errcode,
2667 "pthread_cond_wait");
2669 /* Display progress update in log view. */
2670 show_log_view(view);
2671 update_panels();
2672 doupdate();
2675 return NULL;
2678 static const struct got_error *
2679 request_log_commits(struct tog_view *view)
2681 struct tog_log_view_state *state = &view->state.log;
2682 const struct got_error *err = NULL;
2684 if (state->thread_args.log_complete)
2685 return NULL;
2687 state->thread_args.commits_needed += view->nscrolled;
2688 err = trigger_log_thread(view, 1);
2689 view->nscrolled = 0;
2691 return err;
2694 static const struct got_error *
2695 log_scroll_down(struct tog_view *view, int maxscroll)
2697 struct tog_log_view_state *s = &view->state.log;
2698 const struct got_error *err = NULL;
2699 struct commit_queue_entry *pentry;
2700 int nscrolled = 0, ncommits_needed;
2702 if (s->last_displayed_entry == NULL)
2703 return NULL;
2705 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2706 if (s->commits->ncommits < ncommits_needed &&
2707 !s->thread_args.log_complete) {
2709 * Ask the log thread for required amount of commits.
2711 s->thread_args.commits_needed +=
2712 ncommits_needed - s->commits->ncommits;
2713 err = trigger_log_thread(view, 1);
2714 if (err)
2715 return err;
2718 do {
2719 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2720 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2721 break;
2723 s->last_displayed_entry = pentry ?
2724 pentry : s->last_displayed_entry;;
2726 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2727 if (pentry == NULL)
2728 break;
2729 s->first_displayed_entry = pentry;
2730 } while (++nscrolled < maxscroll);
2732 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2733 view->nscrolled += nscrolled;
2734 else
2735 view->nscrolled = 0;
2737 return err;
2740 static const struct got_error *
2741 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2742 struct got_commit_object *commit, struct got_object_id *commit_id,
2743 struct tog_view *log_view, struct got_repository *repo)
2745 const struct got_error *err;
2746 struct got_object_qid *parent_id;
2747 struct tog_view *diff_view;
2749 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2750 if (diff_view == NULL)
2751 return got_error_from_errno("view_open");
2753 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2754 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2755 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2756 if (err == NULL)
2757 *new_view = diff_view;
2758 return err;
2761 static const struct got_error *
2762 tree_view_visit_subtree(struct tog_tree_view_state *s,
2763 struct got_tree_object *subtree)
2765 struct tog_parent_tree *parent;
2767 parent = calloc(1, sizeof(*parent));
2768 if (parent == NULL)
2769 return got_error_from_errno("calloc");
2771 parent->tree = s->tree;
2772 parent->first_displayed_entry = s->first_displayed_entry;
2773 parent->selected_entry = s->selected_entry;
2774 parent->selected = s->selected;
2775 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2776 s->tree = subtree;
2777 s->selected = 0;
2778 s->first_displayed_entry = NULL;
2779 return NULL;
2782 static const struct got_error *
2783 tree_view_walk_path(struct tog_tree_view_state *s,
2784 struct got_commit_object *commit, const char *path)
2786 const struct got_error *err = NULL;
2787 struct got_tree_object *tree = NULL;
2788 const char *p;
2789 char *slash, *subpath = NULL;
2791 /* Walk the path and open corresponding tree objects. */
2792 p = path;
2793 while (*p) {
2794 struct got_tree_entry *te;
2795 struct got_object_id *tree_id;
2796 char *te_name;
2798 while (p[0] == '/')
2799 p++;
2801 /* Ensure the correct subtree entry is selected. */
2802 slash = strchr(p, '/');
2803 if (slash == NULL)
2804 te_name = strdup(p);
2805 else
2806 te_name = strndup(p, slash - p);
2807 if (te_name == NULL) {
2808 err = got_error_from_errno("strndup");
2809 break;
2811 te = got_object_tree_find_entry(s->tree, te_name);
2812 if (te == NULL) {
2813 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2814 free(te_name);
2815 break;
2817 free(te_name);
2818 s->first_displayed_entry = s->selected_entry = te;
2820 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2821 break; /* jump to this file's entry */
2823 slash = strchr(p, '/');
2824 if (slash)
2825 subpath = strndup(path, slash - path);
2826 else
2827 subpath = strdup(path);
2828 if (subpath == NULL) {
2829 err = got_error_from_errno("strdup");
2830 break;
2833 err = got_object_id_by_path(&tree_id, s->repo, commit,
2834 subpath);
2835 if (err)
2836 break;
2838 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2839 free(tree_id);
2840 if (err)
2841 break;
2843 err = tree_view_visit_subtree(s, tree);
2844 if (err) {
2845 got_object_tree_close(tree);
2846 break;
2848 if (slash == NULL)
2849 break;
2850 free(subpath);
2851 subpath = NULL;
2852 p = slash;
2855 free(subpath);
2856 return err;
2859 static const struct got_error *
2860 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2861 struct commit_queue_entry *entry, const char *path,
2862 const char *head_ref_name, struct got_repository *repo)
2864 const struct got_error *err = NULL;
2865 struct tog_tree_view_state *s;
2866 struct tog_view *tree_view;
2868 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2869 if (tree_view == NULL)
2870 return got_error_from_errno("view_open");
2872 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2873 if (err)
2874 return err;
2875 s = &tree_view->state.tree;
2877 *new_view = tree_view;
2879 if (got_path_is_root_dir(path))
2880 return NULL;
2882 return tree_view_walk_path(s, entry->commit, path);
2885 static const struct got_error *
2886 block_signals_used_by_main_thread(void)
2888 sigset_t sigset;
2889 int errcode;
2891 if (sigemptyset(&sigset) == -1)
2892 return got_error_from_errno("sigemptyset");
2894 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2895 if (sigaddset(&sigset, SIGWINCH) == -1)
2896 return got_error_from_errno("sigaddset");
2897 if (sigaddset(&sigset, SIGCONT) == -1)
2898 return got_error_from_errno("sigaddset");
2899 if (sigaddset(&sigset, SIGINT) == -1)
2900 return got_error_from_errno("sigaddset");
2901 if (sigaddset(&sigset, SIGTERM) == -1)
2902 return got_error_from_errno("sigaddset");
2904 /* ncurses handles SIGTSTP */
2905 if (sigaddset(&sigset, SIGTSTP) == -1)
2906 return got_error_from_errno("sigaddset");
2908 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2909 if (errcode)
2910 return got_error_set_errno(errcode, "pthread_sigmask");
2912 return NULL;
2915 static void *
2916 log_thread(void *arg)
2918 const struct got_error *err = NULL;
2919 int errcode = 0;
2920 struct tog_log_thread_args *a = arg;
2921 int done = 0;
2924 * Sync startup with main thread such that we begin our
2925 * work once view_input() has released the mutex.
2927 errcode = pthread_mutex_lock(&tog_mutex);
2928 if (errcode) {
2929 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2930 return (void *)err;
2933 err = block_signals_used_by_main_thread();
2934 if (err) {
2935 pthread_mutex_unlock(&tog_mutex);
2936 goto done;
2939 while (!done && !err && !tog_fatal_signal_received()) {
2940 errcode = pthread_mutex_unlock(&tog_mutex);
2941 if (errcode) {
2942 err = got_error_set_errno(errcode,
2943 "pthread_mutex_unlock");
2944 goto done;
2946 err = queue_commits(a);
2947 if (err) {
2948 if (err->code != GOT_ERR_ITER_COMPLETED)
2949 goto done;
2950 err = NULL;
2951 done = 1;
2952 } else if (a->commits_needed > 0 && !a->load_all) {
2953 if (*a->limiting) {
2954 if (a->limit_match)
2955 a->commits_needed--;
2956 } else
2957 a->commits_needed--;
2960 errcode = pthread_mutex_lock(&tog_mutex);
2961 if (errcode) {
2962 err = got_error_set_errno(errcode,
2963 "pthread_mutex_lock");
2964 goto done;
2965 } else if (*a->quit)
2966 done = 1;
2967 else if (*a->limiting && *a->first_displayed_entry == NULL) {
2968 *a->first_displayed_entry =
2969 TAILQ_FIRST(&a->limit_commits->head);
2970 *a->selected_entry = *a->first_displayed_entry;
2971 } else if (*a->first_displayed_entry == NULL) {
2972 *a->first_displayed_entry =
2973 TAILQ_FIRST(&a->real_commits->head);
2974 *a->selected_entry = *a->first_displayed_entry;
2977 errcode = pthread_cond_signal(&a->commit_loaded);
2978 if (errcode) {
2979 err = got_error_set_errno(errcode,
2980 "pthread_cond_signal");
2981 pthread_mutex_unlock(&tog_mutex);
2982 goto done;
2985 if (done)
2986 a->commits_needed = 0;
2987 else {
2988 if (a->commits_needed == 0 && !a->load_all) {
2989 errcode = pthread_cond_wait(&a->need_commits,
2990 &tog_mutex);
2991 if (errcode) {
2992 err = got_error_set_errno(errcode,
2993 "pthread_cond_wait");
2994 pthread_mutex_unlock(&tog_mutex);
2995 goto done;
2997 if (*a->quit)
2998 done = 1;
3002 a->log_complete = 1;
3003 errcode = pthread_mutex_unlock(&tog_mutex);
3004 if (errcode)
3005 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3006 done:
3007 if (err) {
3008 tog_thread_error = 1;
3009 pthread_cond_signal(&a->commit_loaded);
3011 return (void *)err;
3014 static const struct got_error *
3015 stop_log_thread(struct tog_log_view_state *s)
3017 const struct got_error *err = NULL, *thread_err = NULL;
3018 int errcode;
3020 if (s->thread) {
3021 s->quit = 1;
3022 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3023 if (errcode)
3024 return got_error_set_errno(errcode,
3025 "pthread_cond_signal");
3026 errcode = pthread_mutex_unlock(&tog_mutex);
3027 if (errcode)
3028 return got_error_set_errno(errcode,
3029 "pthread_mutex_unlock");
3030 errcode = pthread_join(s->thread, (void **)&thread_err);
3031 if (errcode)
3032 return got_error_set_errno(errcode, "pthread_join");
3033 errcode = pthread_mutex_lock(&tog_mutex);
3034 if (errcode)
3035 return got_error_set_errno(errcode,
3036 "pthread_mutex_lock");
3037 s->thread = 0; //NULL;
3040 if (s->thread_args.repo) {
3041 err = got_repo_close(s->thread_args.repo);
3042 s->thread_args.repo = NULL;
3045 if (s->thread_args.pack_fds) {
3046 const struct got_error *pack_err =
3047 got_repo_pack_fds_close(s->thread_args.pack_fds);
3048 if (err == NULL)
3049 err = pack_err;
3050 s->thread_args.pack_fds = NULL;
3053 if (s->thread_args.graph) {
3054 got_commit_graph_close(s->thread_args.graph);
3055 s->thread_args.graph = NULL;
3058 return err ? err : thread_err;
3061 static const struct got_error *
3062 close_log_view(struct tog_view *view)
3064 const struct got_error *err = NULL;
3065 struct tog_log_view_state *s = &view->state.log;
3066 int errcode;
3068 err = stop_log_thread(s);
3070 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3071 if (errcode && err == NULL)
3072 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3074 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3075 if (errcode && err == NULL)
3076 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3078 free_commits(&s->limit_commits);
3079 free_commits(&s->real_commits);
3080 free(s->in_repo_path);
3081 s->in_repo_path = NULL;
3082 free(s->start_id);
3083 s->start_id = NULL;
3084 free(s->head_ref_name);
3085 s->head_ref_name = NULL;
3086 return err;
3090 * We use two queues to implement the limit feature: first consists of
3091 * commits matching the current limit_regex; second is the real queue
3092 * of all known commits (real_commits). When the user starts limiting,
3093 * we swap queues such that all movement and displaying functionality
3094 * works with very slight change.
3096 static const struct got_error *
3097 limit_log_view(struct tog_view *view)
3099 struct tog_log_view_state *s = &view->state.log;
3100 struct commit_queue_entry *entry;
3101 struct tog_view *v = view;
3102 const struct got_error *err = NULL;
3103 char pattern[1024];
3104 int ret;
3106 if (view_is_hsplit_top(view))
3107 v = view->child;
3108 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3109 v = view->parent;
3111 /* Get the pattern */
3112 wmove(v->window, v->nlines - 1, 0);
3113 wclrtoeol(v->window);
3114 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3115 nodelay(v->window, FALSE);
3116 nocbreak();
3117 echo();
3118 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3119 cbreak();
3120 noecho();
3121 nodelay(v->window, TRUE);
3122 if (ret == ERR)
3123 return NULL;
3125 if (*pattern == '\0') {
3127 * Safety measure for the situation where the user
3128 * resets limit without previously limiting anything.
3130 if (!s->limit_view)
3131 return NULL;
3134 * User could have pressed Ctrl+L, which refreshed the
3135 * commit queues, it means we can't save previously
3136 * (before limit took place) displayed entries,
3137 * because they would point to already free'ed memory,
3138 * so we are forced to always select first entry of
3139 * the queue.
3141 s->commits = &s->real_commits;
3142 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3143 s->selected_entry = s->first_displayed_entry;
3144 s->selected = 0;
3145 s->limit_view = 0;
3147 return NULL;
3150 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3151 return NULL;
3153 s->limit_view = 1;
3155 /* Clear the screen while loading limit view */
3156 s->first_displayed_entry = NULL;
3157 s->last_displayed_entry = NULL;
3158 s->selected_entry = NULL;
3159 s->commits = &s->limit_commits;
3161 /* Prepare limit queue for new search */
3162 free_commits(&s->limit_commits);
3163 s->limit_commits.ncommits = 0;
3165 /* First process commits, which are in queue already */
3166 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3167 int have_match = 0;
3169 err = match_commit(&have_match, entry->id,
3170 entry->commit, &s->limit_regex);
3171 if (err)
3172 return err;
3174 if (have_match) {
3175 struct commit_queue_entry *matched;
3177 matched = alloc_commit_queue_entry(entry->commit,
3178 entry->id);
3179 if (matched == NULL) {
3180 err = got_error_from_errno(
3181 "alloc_commit_queue_entry");
3182 break;
3184 matched->commit = entry->commit;
3185 got_object_commit_retain(entry->commit);
3187 matched->idx = s->limit_commits.ncommits;
3188 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3189 matched, entry);
3190 s->limit_commits.ncommits++;
3194 /* Second process all the commits, until we fill the screen */
3195 if (s->limit_commits.ncommits < view->nlines - 1 &&
3196 !s->thread_args.log_complete) {
3197 s->thread_args.commits_needed +=
3198 view->nlines - s->limit_commits.ncommits - 1;
3199 err = trigger_log_thread(view, 1);
3200 if (err)
3201 return err;
3204 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3205 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3206 s->selected = 0;
3208 return NULL;
3211 static const struct got_error *
3212 search_start_log_view(struct tog_view *view)
3214 struct tog_log_view_state *s = &view->state.log;
3216 s->matched_entry = NULL;
3217 s->search_entry = NULL;
3218 return NULL;
3221 static const struct got_error *
3222 search_next_log_view(struct tog_view *view)
3224 const struct got_error *err = NULL;
3225 struct tog_log_view_state *s = &view->state.log;
3226 struct commit_queue_entry *entry;
3228 /* Display progress update in log view. */
3229 show_log_view(view);
3230 update_panels();
3231 doupdate();
3233 if (s->search_entry) {
3234 int errcode, ch;
3235 errcode = pthread_mutex_unlock(&tog_mutex);
3236 if (errcode)
3237 return got_error_set_errno(errcode,
3238 "pthread_mutex_unlock");
3239 ch = wgetch(view->window);
3240 errcode = pthread_mutex_lock(&tog_mutex);
3241 if (errcode)
3242 return got_error_set_errno(errcode,
3243 "pthread_mutex_lock");
3244 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3245 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3246 return NULL;
3248 if (view->searching == TOG_SEARCH_FORWARD)
3249 entry = TAILQ_NEXT(s->search_entry, entry);
3250 else
3251 entry = TAILQ_PREV(s->search_entry,
3252 commit_queue_head, entry);
3253 } else if (s->matched_entry) {
3255 * If the user has moved the cursor after we hit a match,
3256 * the position from where we should continue searching
3257 * might have changed.
3259 if (view->searching == TOG_SEARCH_FORWARD)
3260 entry = TAILQ_NEXT(s->selected_entry, entry);
3261 else
3262 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3263 entry);
3264 } else {
3265 entry = s->selected_entry;
3268 while (1) {
3269 int have_match = 0;
3271 if (entry == NULL) {
3272 if (s->thread_args.log_complete ||
3273 view->searching == TOG_SEARCH_BACKWARD) {
3274 view->search_next_done =
3275 (s->matched_entry == NULL ?
3276 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3277 s->search_entry = NULL;
3278 return NULL;
3281 * Poke the log thread for more commits and return,
3282 * allowing the main loop to make progress. Search
3283 * will resume at s->search_entry once we come back.
3285 s->thread_args.commits_needed++;
3286 return trigger_log_thread(view, 0);
3289 err = match_commit(&have_match, entry->id, entry->commit,
3290 &view->regex);
3291 if (err)
3292 break;
3293 if (have_match) {
3294 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3295 s->matched_entry = entry;
3296 break;
3299 s->search_entry = entry;
3300 if (view->searching == TOG_SEARCH_FORWARD)
3301 entry = TAILQ_NEXT(entry, entry);
3302 else
3303 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3306 if (s->matched_entry) {
3307 int cur = s->selected_entry->idx;
3308 while (cur < s->matched_entry->idx) {
3309 err = input_log_view(NULL, view, KEY_DOWN);
3310 if (err)
3311 return err;
3312 cur++;
3314 while (cur > s->matched_entry->idx) {
3315 err = input_log_view(NULL, view, KEY_UP);
3316 if (err)
3317 return err;
3318 cur--;
3322 s->search_entry = NULL;
3324 return NULL;
3327 static const struct got_error *
3328 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3329 struct got_repository *repo, const char *head_ref_name,
3330 const char *in_repo_path, int log_branches)
3332 const struct got_error *err = NULL;
3333 struct tog_log_view_state *s = &view->state.log;
3334 struct got_repository *thread_repo = NULL;
3335 struct got_commit_graph *thread_graph = NULL;
3336 int errcode;
3338 if (in_repo_path != s->in_repo_path) {
3339 free(s->in_repo_path);
3340 s->in_repo_path = strdup(in_repo_path);
3341 if (s->in_repo_path == NULL)
3342 return got_error_from_errno("strdup");
3345 /* The commit queue only contains commits being displayed. */
3346 TAILQ_INIT(&s->real_commits.head);
3347 s->real_commits.ncommits = 0;
3348 s->commits = &s->real_commits;
3350 TAILQ_INIT(&s->limit_commits.head);
3351 s->limit_view = 0;
3352 s->limit_commits.ncommits = 0;
3354 s->repo = repo;
3355 if (head_ref_name) {
3356 s->head_ref_name = strdup(head_ref_name);
3357 if (s->head_ref_name == NULL) {
3358 err = got_error_from_errno("strdup");
3359 goto done;
3362 s->start_id = got_object_id_dup(start_id);
3363 if (s->start_id == NULL) {
3364 err = got_error_from_errno("got_object_id_dup");
3365 goto done;
3367 s->log_branches = log_branches;
3369 STAILQ_INIT(&s->colors);
3370 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3371 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3372 get_color_value("TOG_COLOR_COMMIT"));
3373 if (err)
3374 goto done;
3375 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3376 get_color_value("TOG_COLOR_AUTHOR"));
3377 if (err) {
3378 free_colors(&s->colors);
3379 goto done;
3381 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3382 get_color_value("TOG_COLOR_DATE"));
3383 if (err) {
3384 free_colors(&s->colors);
3385 goto done;
3389 view->show = show_log_view;
3390 view->input = input_log_view;
3391 view->resize = resize_log_view;
3392 view->close = close_log_view;
3393 view->search_start = search_start_log_view;
3394 view->search_next = search_next_log_view;
3396 if (s->thread_args.pack_fds == NULL) {
3397 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3398 if (err)
3399 goto done;
3401 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3402 s->thread_args.pack_fds);
3403 if (err)
3404 goto done;
3405 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3406 !s->log_branches);
3407 if (err)
3408 goto done;
3409 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3410 s->repo, NULL, NULL);
3411 if (err)
3412 goto done;
3414 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3415 if (errcode) {
3416 err = got_error_set_errno(errcode, "pthread_cond_init");
3417 goto done;
3419 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3420 if (errcode) {
3421 err = got_error_set_errno(errcode, "pthread_cond_init");
3422 goto done;
3425 s->thread_args.commits_needed = view->nlines;
3426 s->thread_args.graph = thread_graph;
3427 s->thread_args.real_commits = &s->real_commits;
3428 s->thread_args.limit_commits = &s->limit_commits;
3429 s->thread_args.in_repo_path = s->in_repo_path;
3430 s->thread_args.start_id = s->start_id;
3431 s->thread_args.repo = thread_repo;
3432 s->thread_args.log_complete = 0;
3433 s->thread_args.quit = &s->quit;
3434 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3435 s->thread_args.selected_entry = &s->selected_entry;
3436 s->thread_args.searching = &view->searching;
3437 s->thread_args.search_next_done = &view->search_next_done;
3438 s->thread_args.regex = &view->regex;
3439 s->thread_args.limiting = &s->limit_view;
3440 s->thread_args.limit_regex = &s->limit_regex;
3441 s->thread_args.limit_commits = &s->limit_commits;
3442 done:
3443 if (err)
3444 close_log_view(view);
3445 return err;
3448 static const struct got_error *
3449 show_log_view(struct tog_view *view)
3451 const struct got_error *err;
3452 struct tog_log_view_state *s = &view->state.log;
3454 if (s->thread == 0) { //NULL) {
3455 int errcode = pthread_create(&s->thread, NULL, log_thread,
3456 &s->thread_args);
3457 if (errcode)
3458 return got_error_set_errno(errcode, "pthread_create");
3459 if (s->thread_args.commits_needed > 0) {
3460 err = trigger_log_thread(view, 1);
3461 if (err)
3462 return err;
3466 return draw_commits(view);
3469 static void
3470 log_move_cursor_up(struct tog_view *view, int page, int home)
3472 struct tog_log_view_state *s = &view->state.log;
3474 if (s->first_displayed_entry == NULL)
3475 return;
3476 if (s->selected_entry->idx == 0)
3477 view->count = 0;
3479 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3480 || home)
3481 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3483 if (!page && !home && s->selected > 0)
3484 --s->selected;
3485 else
3486 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3488 select_commit(s);
3489 return;
3492 static const struct got_error *
3493 log_move_cursor_down(struct tog_view *view, int page)
3495 struct tog_log_view_state *s = &view->state.log;
3496 const struct got_error *err = NULL;
3497 int eos = view->nlines - 2;
3499 if (s->first_displayed_entry == NULL)
3500 return NULL;
3502 if (s->thread_args.log_complete &&
3503 s->selected_entry->idx >= s->commits->ncommits - 1)
3504 return NULL;
3506 if (view_is_hsplit_top(view))
3507 --eos; /* border consumes the last line */
3509 if (!page) {
3510 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3511 ++s->selected;
3512 else
3513 err = log_scroll_down(view, 1);
3514 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3515 struct commit_queue_entry *entry;
3516 int n;
3518 s->selected = 0;
3519 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3520 s->last_displayed_entry = entry;
3521 for (n = 0; n <= eos; n++) {
3522 if (entry == NULL)
3523 break;
3524 s->first_displayed_entry = entry;
3525 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3527 if (n > 0)
3528 s->selected = n - 1;
3529 } else {
3530 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3531 s->thread_args.log_complete)
3532 s->selected += MIN(page,
3533 s->commits->ncommits - s->selected_entry->idx - 1);
3534 else
3535 err = log_scroll_down(view, page);
3537 if (err)
3538 return err;
3541 * We might necessarily overshoot in horizontal
3542 * splits; if so, select the last displayed commit.
3544 if (s->first_displayed_entry && s->last_displayed_entry) {
3545 s->selected = MIN(s->selected,
3546 s->last_displayed_entry->idx -
3547 s->first_displayed_entry->idx);
3550 select_commit(s);
3552 if (s->thread_args.log_complete &&
3553 s->selected_entry->idx == s->commits->ncommits - 1)
3554 view->count = 0;
3556 return NULL;
3559 static void
3560 view_get_split(struct tog_view *view, int *y, int *x)
3562 *x = 0;
3563 *y = 0;
3565 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3566 if (view->child && view->child->resized_y)
3567 *y = view->child->resized_y;
3568 else if (view->resized_y)
3569 *y = view->resized_y;
3570 else
3571 *y = view_split_begin_y(view->lines);
3572 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3573 if (view->child && view->child->resized_x)
3574 *x = view->child->resized_x;
3575 else if (view->resized_x)
3576 *x = view->resized_x;
3577 else
3578 *x = view_split_begin_x(view->begin_x);
3582 /* Split view horizontally at y and offset view->state->selected line. */
3583 static const struct got_error *
3584 view_init_hsplit(struct tog_view *view, int y)
3586 const struct got_error *err = NULL;
3588 view->nlines = y;
3589 view->ncols = COLS;
3590 err = view_resize(view);
3591 if (err)
3592 return err;
3594 err = offset_selection_down(view);
3596 return err;
3599 static const struct got_error *
3600 log_goto_line(struct tog_view *view, int nlines)
3602 const struct got_error *err = NULL;
3603 struct tog_log_view_state *s = &view->state.log;
3604 int g, idx = s->selected_entry->idx;
3606 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3607 return NULL;
3609 g = view->gline;
3610 view->gline = 0;
3612 if (g >= s->first_displayed_entry->idx + 1 &&
3613 g <= s->last_displayed_entry->idx + 1 &&
3614 g - s->first_displayed_entry->idx - 1 < nlines) {
3615 s->selected = g - s->first_displayed_entry->idx - 1;
3616 select_commit(s);
3617 return NULL;
3620 if (idx + 1 < g) {
3621 err = log_move_cursor_down(view, g - idx - 1);
3622 if (!err && g > s->selected_entry->idx + 1)
3623 err = log_move_cursor_down(view,
3624 g - s->first_displayed_entry->idx - 1);
3625 if (err)
3626 return err;
3627 } else if (idx + 1 > g)
3628 log_move_cursor_up(view, idx - g + 1, 0);
3630 if (g < nlines && s->first_displayed_entry->idx == 0)
3631 s->selected = g - 1;
3633 select_commit(s);
3634 return NULL;
3638 static const struct got_error *
3639 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3641 const struct got_error *err = NULL;
3642 struct tog_log_view_state *s = &view->state.log;
3643 int eos, nscroll;
3645 if (s->thread_args.load_all) {
3646 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3647 s->thread_args.load_all = 0;
3648 else if (s->thread_args.log_complete) {
3649 err = log_move_cursor_down(view, s->commits->ncommits);
3650 s->thread_args.load_all = 0;
3652 if (err)
3653 return err;
3656 eos = nscroll = view->nlines - 1;
3657 if (view_is_hsplit_top(view))
3658 --eos; /* border */
3660 if (view->gline)
3661 return log_goto_line(view, eos);
3663 switch (ch) {
3664 case '&':
3665 err = limit_log_view(view);
3666 break;
3667 case 'q':
3668 s->quit = 1;
3669 break;
3670 case '0':
3671 view->x = 0;
3672 break;
3673 case '$':
3674 view->x = MAX(view->maxx - view->ncols / 2, 0);
3675 view->count = 0;
3676 break;
3677 case KEY_RIGHT:
3678 case 'l':
3679 if (view->x + view->ncols / 2 < view->maxx)
3680 view->x += 2; /* move two columns right */
3681 else
3682 view->count = 0;
3683 break;
3684 case KEY_LEFT:
3685 case 'h':
3686 view->x -= MIN(view->x, 2); /* move two columns back */
3687 if (view->x <= 0)
3688 view->count = 0;
3689 break;
3690 case 'k':
3691 case KEY_UP:
3692 case '<':
3693 case ',':
3694 case CTRL('p'):
3695 log_move_cursor_up(view, 0, 0);
3696 break;
3697 case 'g':
3698 case KEY_HOME:
3699 log_move_cursor_up(view, 0, 1);
3700 view->count = 0;
3701 break;
3702 case CTRL('u'):
3703 case 'u':
3704 nscroll /= 2;
3705 /* FALL THROUGH */
3706 case KEY_PPAGE:
3707 case CTRL('b'):
3708 case 'b':
3709 log_move_cursor_up(view, nscroll, 0);
3710 break;
3711 case 'j':
3712 case KEY_DOWN:
3713 case '>':
3714 case '.':
3715 case CTRL('n'):
3716 err = log_move_cursor_down(view, 0);
3717 break;
3718 case '@':
3719 s->use_committer = !s->use_committer;
3720 break;
3721 case 'G':
3722 case KEY_END: {
3723 /* We don't know yet how many commits, so we're forced to
3724 * traverse them all. */
3725 view->count = 0;
3726 s->thread_args.load_all = 1;
3727 if (!s->thread_args.log_complete)
3728 return trigger_log_thread(view, 0);
3729 err = log_move_cursor_down(view, s->commits->ncommits);
3730 s->thread_args.load_all = 0;
3731 break;
3733 case CTRL('d'):
3734 case 'd':
3735 nscroll /= 2;
3736 /* FALL THROUGH */
3737 case KEY_NPAGE:
3738 case CTRL('f'):
3739 case 'f':
3740 case ' ':
3741 err = log_move_cursor_down(view, nscroll);
3742 break;
3743 case KEY_RESIZE:
3744 if (s->selected > view->nlines - 2)
3745 s->selected = view->nlines - 2;
3746 if (s->selected > s->commits->ncommits - 1)
3747 s->selected = s->commits->ncommits - 1;
3748 select_commit(s);
3749 if (s->commits->ncommits < view->nlines - 1 &&
3750 !s->thread_args.log_complete) {
3751 s->thread_args.commits_needed += (view->nlines - 1) -
3752 s->commits->ncommits;
3753 err = trigger_log_thread(view, 1);
3755 break;
3756 case KEY_ENTER:
3757 case '\r':
3758 view->count = 0;
3759 if (s->selected_entry == NULL)
3760 break;
3761 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3762 break;
3763 case 'T':
3764 view->count = 0;
3765 if (s->selected_entry == NULL)
3766 break;
3767 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3768 break;
3769 case KEY_BACKSPACE:
3770 case CTRL('l'):
3771 case 'B':
3772 view->count = 0;
3773 if (ch == KEY_BACKSPACE &&
3774 got_path_is_root_dir(s->in_repo_path))
3775 break;
3776 err = stop_log_thread(s);
3777 if (err)
3778 return err;
3779 if (ch == KEY_BACKSPACE) {
3780 char *parent_path;
3781 err = got_path_dirname(&parent_path, s->in_repo_path);
3782 if (err)
3783 return err;
3784 free(s->in_repo_path);
3785 s->in_repo_path = parent_path;
3786 s->thread_args.in_repo_path = s->in_repo_path;
3787 } else if (ch == CTRL('l')) {
3788 struct got_object_id *start_id;
3789 err = got_repo_match_object_id(&start_id, NULL,
3790 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3791 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3792 if (err)
3793 return err;
3794 free(s->start_id);
3795 s->start_id = start_id;
3796 s->thread_args.start_id = s->start_id;
3797 } else /* 'B' */
3798 s->log_branches = !s->log_branches;
3800 if (s->thread_args.pack_fds == NULL) {
3801 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3802 if (err)
3803 return err;
3805 err = got_repo_open(&s->thread_args.repo,
3806 got_repo_get_path(s->repo), NULL,
3807 s->thread_args.pack_fds);
3808 if (err)
3809 return err;
3810 tog_free_refs();
3811 err = tog_load_refs(s->repo, 0);
3812 if (err)
3813 return err;
3814 err = got_commit_graph_open(&s->thread_args.graph,
3815 s->in_repo_path, !s->log_branches);
3816 if (err)
3817 return err;
3818 err = got_commit_graph_iter_start(s->thread_args.graph,
3819 s->start_id, s->repo, NULL, NULL);
3820 if (err)
3821 return err;
3822 free_commits(&s->real_commits);
3823 free_commits(&s->limit_commits);
3824 s->first_displayed_entry = NULL;
3825 s->last_displayed_entry = NULL;
3826 s->selected_entry = NULL;
3827 s->selected = 0;
3828 s->thread_args.log_complete = 0;
3829 s->quit = 0;
3830 s->thread_args.commits_needed = view->lines;
3831 s->matched_entry = NULL;
3832 s->search_entry = NULL;
3833 view->offset = 0;
3834 break;
3835 case 'R':
3836 view->count = 0;
3837 err = view_request_new(new_view, view, TOG_VIEW_REF);
3838 break;
3839 default:
3840 view->count = 0;
3841 break;
3844 return err;
3847 static const struct got_error *
3848 apply_unveil(const char *repo_path, const char *worktree_path)
3850 const struct got_error *error;
3852 #ifdef PROFILE
3853 if (unveil("gmon.out", "rwc") != 0)
3854 return got_error_from_errno2("unveil", "gmon.out");
3855 #endif
3856 if (repo_path && unveil(repo_path, "r") != 0)
3857 return got_error_from_errno2("unveil", repo_path);
3859 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3860 return got_error_from_errno2("unveil", worktree_path);
3862 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3863 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3865 error = got_privsep_unveil_exec_helpers();
3866 if (error != NULL)
3867 return error;
3869 if (unveil(NULL, NULL) != 0)
3870 return got_error_from_errno("unveil");
3872 return NULL;
3875 static void
3876 init_curses(void)
3879 * Override default signal handlers before starting ncurses.
3880 * This should prevent ncurses from installing its own
3881 * broken cleanup() signal handler.
3883 signal(SIGWINCH, tog_sigwinch);
3884 signal(SIGPIPE, tog_sigpipe);
3885 signal(SIGCONT, tog_sigcont);
3886 signal(SIGINT, tog_sigint);
3887 signal(SIGTERM, tog_sigterm);
3889 initscr();
3890 cbreak();
3891 halfdelay(1); /* Do fast refresh while initial view is loading. */
3892 noecho();
3893 nonl();
3894 intrflush(stdscr, FALSE);
3895 keypad(stdscr, TRUE);
3896 curs_set(0);
3897 if (getenv("TOG_COLORS") != NULL) {
3898 start_color();
3899 use_default_colors();
3903 static const struct got_error *
3904 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3905 struct got_repository *repo, struct got_worktree *worktree)
3907 const struct got_error *err = NULL;
3909 if (argc == 0) {
3910 *in_repo_path = strdup("/");
3911 if (*in_repo_path == NULL)
3912 return got_error_from_errno("strdup");
3913 return NULL;
3916 if (worktree) {
3917 const char *prefix = got_worktree_get_path_prefix(worktree);
3918 char *p;
3920 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3921 if (err)
3922 return err;
3923 if (asprintf(in_repo_path, "%s%s%s", prefix,
3924 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3925 p) == -1) {
3926 err = got_error_from_errno("asprintf");
3927 *in_repo_path = NULL;
3929 free(p);
3930 } else
3931 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3933 return err;
3936 static const struct got_error *
3937 cmd_log(int argc, char *argv[])
3939 const struct got_error *error;
3940 struct got_repository *repo = NULL;
3941 struct got_worktree *worktree = NULL;
3942 struct got_object_id *start_id = NULL;
3943 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3944 char *start_commit = NULL, *label = NULL;
3945 struct got_reference *ref = NULL;
3946 const char *head_ref_name = NULL;
3947 int ch, log_branches = 0;
3948 struct tog_view *view;
3949 int *pack_fds = NULL;
3951 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3952 switch (ch) {
3953 case 'b':
3954 log_branches = 1;
3955 break;
3956 case 'c':
3957 start_commit = optarg;
3958 break;
3959 case 'r':
3960 repo_path = realpath(optarg, NULL);
3961 if (repo_path == NULL)
3962 return got_error_from_errno2("realpath",
3963 optarg);
3964 break;
3965 default:
3966 usage_log();
3967 /* NOTREACHED */
3971 argc -= optind;
3972 argv += optind;
3974 if (argc > 1)
3975 usage_log();
3977 error = got_repo_pack_fds_open(&pack_fds);
3978 if (error != NULL)
3979 goto done;
3981 if (repo_path == NULL) {
3982 cwd = getcwd(NULL, 0);
3983 if (cwd == NULL)
3984 return got_error_from_errno("getcwd");
3985 error = got_worktree_open(&worktree, cwd);
3986 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3987 goto done;
3988 if (worktree)
3989 repo_path =
3990 strdup(got_worktree_get_repo_path(worktree));
3991 else
3992 repo_path = strdup(cwd);
3993 if (repo_path == NULL) {
3994 error = got_error_from_errno("strdup");
3995 goto done;
3999 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4000 if (error != NULL)
4001 goto done;
4003 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4004 repo, worktree);
4005 if (error)
4006 goto done;
4008 init_curses();
4010 error = apply_unveil(got_repo_get_path(repo),
4011 worktree ? got_worktree_get_root_path(worktree) : NULL);
4012 if (error)
4013 goto done;
4015 /* already loaded by tog_log_with_path()? */
4016 if (TAILQ_EMPTY(&tog_refs)) {
4017 error = tog_load_refs(repo, 0);
4018 if (error)
4019 goto done;
4022 if (start_commit == NULL) {
4023 error = got_repo_match_object_id(&start_id, &label,
4024 worktree ? got_worktree_get_head_ref_name(worktree) :
4025 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4026 if (error)
4027 goto done;
4028 head_ref_name = label;
4029 } else {
4030 error = got_ref_open(&ref, repo, start_commit, 0);
4031 if (error == NULL)
4032 head_ref_name = got_ref_get_name(ref);
4033 else if (error->code != GOT_ERR_NOT_REF)
4034 goto done;
4035 error = got_repo_match_object_id(&start_id, NULL,
4036 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4037 if (error)
4038 goto done;
4041 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4042 if (view == NULL) {
4043 error = got_error_from_errno("view_open");
4044 goto done;
4046 error = open_log_view(view, start_id, repo, head_ref_name,
4047 in_repo_path, log_branches);
4048 if (error)
4049 goto done;
4050 if (worktree) {
4051 /* Release work tree lock. */
4052 got_worktree_close(worktree);
4053 worktree = NULL;
4055 error = view_loop(view);
4056 done:
4057 free(in_repo_path);
4058 free(repo_path);
4059 free(cwd);
4060 free(start_id);
4061 free(label);
4062 if (ref)
4063 got_ref_close(ref);
4064 if (repo) {
4065 const struct got_error *close_err = got_repo_close(repo);
4066 if (error == NULL)
4067 error = close_err;
4069 if (worktree)
4070 got_worktree_close(worktree);
4071 if (pack_fds) {
4072 const struct got_error *pack_err =
4073 got_repo_pack_fds_close(pack_fds);
4074 if (error == NULL)
4075 error = pack_err;
4077 tog_free_refs();
4078 return error;
4081 __dead static void
4082 usage_diff(void)
4084 endwin();
4085 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4086 "object1 object2\n", getprogname());
4087 exit(1);
4090 static int
4091 match_line(const char *line, regex_t *regex, size_t nmatch,
4092 regmatch_t *regmatch)
4094 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4097 static struct tog_color *
4098 match_color(struct tog_colors *colors, const char *line)
4100 struct tog_color *tc = NULL;
4102 STAILQ_FOREACH(tc, colors, entry) {
4103 if (match_line(line, &tc->regex, 0, NULL))
4104 return tc;
4107 return NULL;
4110 static const struct got_error *
4111 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4112 WINDOW *window, int skipcol, regmatch_t *regmatch)
4114 const struct got_error *err = NULL;
4115 char *exstr = NULL;
4116 wchar_t *wline = NULL;
4117 int rme, rms, n, width, scrollx;
4118 int width0 = 0, width1 = 0, width2 = 0;
4119 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4121 *wtotal = 0;
4123 rms = regmatch->rm_so;
4124 rme = regmatch->rm_eo;
4126 err = expand_tab(&exstr, line);
4127 if (err)
4128 return err;
4130 /* Split the line into 3 segments, according to match offsets. */
4131 seg0 = strndup(exstr, rms);
4132 if (seg0 == NULL) {
4133 err = got_error_from_errno("strndup");
4134 goto done;
4136 seg1 = strndup(exstr + rms, rme - rms);
4137 if (seg1 == NULL) {
4138 err = got_error_from_errno("strndup");
4139 goto done;
4141 seg2 = strdup(exstr + rme);
4142 if (seg2 == NULL) {
4143 err = got_error_from_errno("strndup");
4144 goto done;
4147 /* draw up to matched token if we haven't scrolled past it */
4148 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4149 col_tab_align, 1);
4150 if (err)
4151 goto done;
4152 n = MAX(width0 - skipcol, 0);
4153 if (n) {
4154 free(wline);
4155 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4156 wlimit, col_tab_align, 1);
4157 if (err)
4158 goto done;
4159 waddwstr(window, &wline[scrollx]);
4160 wlimit -= width;
4161 *wtotal += width;
4164 if (wlimit > 0) {
4165 int i = 0, w = 0;
4166 size_t wlen;
4168 free(wline);
4169 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4170 col_tab_align, 1);
4171 if (err)
4172 goto done;
4173 wlen = wcslen(wline);
4174 while (i < wlen) {
4175 width = wcwidth(wline[i]);
4176 if (width == -1) {
4177 /* should not happen, tabs are expanded */
4178 err = got_error(GOT_ERR_RANGE);
4179 goto done;
4181 if (width0 + w + width > skipcol)
4182 break;
4183 w += width;
4184 i++;
4186 /* draw (visible part of) matched token (if scrolled into it) */
4187 if (width1 - w > 0) {
4188 wattron(window, A_STANDOUT);
4189 waddwstr(window, &wline[i]);
4190 wattroff(window, A_STANDOUT);
4191 wlimit -= (width1 - w);
4192 *wtotal += (width1 - w);
4196 if (wlimit > 0) { /* draw rest of line */
4197 free(wline);
4198 if (skipcol > width0 + width1) {
4199 err = format_line(&wline, &width2, &scrollx, seg2,
4200 skipcol - (width0 + width1), wlimit,
4201 col_tab_align, 1);
4202 if (err)
4203 goto done;
4204 waddwstr(window, &wline[scrollx]);
4205 } else {
4206 err = format_line(&wline, &width2, NULL, seg2, 0,
4207 wlimit, col_tab_align, 1);
4208 if (err)
4209 goto done;
4210 waddwstr(window, wline);
4212 *wtotal += width2;
4214 done:
4215 free(wline);
4216 free(exstr);
4217 free(seg0);
4218 free(seg1);
4219 free(seg2);
4220 return err;
4223 static int
4224 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4226 FILE *f = NULL;
4227 int *eof, *first, *selected;
4229 if (view->type == TOG_VIEW_DIFF) {
4230 struct tog_diff_view_state *s = &view->state.diff;
4232 first = &s->first_displayed_line;
4233 selected = first;
4234 eof = &s->eof;
4235 f = s->f;
4236 } else if (view->type == TOG_VIEW_HELP) {
4237 struct tog_help_view_state *s = &view->state.help;
4239 first = &s->first_displayed_line;
4240 selected = first;
4241 eof = &s->eof;
4242 f = s->f;
4243 } else if (view->type == TOG_VIEW_BLAME) {
4244 struct tog_blame_view_state *s = &view->state.blame;
4246 first = &s->first_displayed_line;
4247 selected = &s->selected_line;
4248 eof = &s->eof;
4249 f = s->blame.f;
4250 } else
4251 return 0;
4253 /* Center gline in the middle of the page like vi(1). */
4254 if (*lineno < view->gline - (view->nlines - 3) / 2)
4255 return 0;
4256 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4257 rewind(f);
4258 *eof = 0;
4259 *first = 1;
4260 *lineno = 0;
4261 *nprinted = 0;
4262 return 0;
4265 *selected = view->gline <= (view->nlines - 3) / 2 ?
4266 view->gline : (view->nlines - 3) / 2 + 1;
4267 view->gline = 0;
4269 return 1;
4272 static const struct got_error *
4273 draw_file(struct tog_view *view, const char *header)
4275 struct tog_diff_view_state *s = &view->state.diff;
4276 regmatch_t *regmatch = &view->regmatch;
4277 const struct got_error *err;
4278 int nprinted = 0;
4279 char *line;
4280 size_t linesize = 0;
4281 ssize_t linelen;
4282 wchar_t *wline;
4283 int width;
4284 int max_lines = view->nlines;
4285 int nlines = s->nlines;
4286 off_t line_offset;
4288 s->lineno = s->first_displayed_line - 1;
4289 line_offset = s->lines[s->first_displayed_line - 1].offset;
4290 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4291 return got_error_from_errno("fseek");
4293 werase(view->window);
4295 if (view->gline > s->nlines - 1)
4296 view->gline = s->nlines - 1;
4298 if (header) {
4299 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4300 1 : view->gline - (view->nlines - 3) / 2 :
4301 s->lineno + s->selected_line;
4303 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4304 return got_error_from_errno("asprintf");
4305 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4306 0, 0);
4307 free(line);
4308 if (err)
4309 return err;
4311 if (view_needs_focus_indication(view))
4312 wstandout(view->window);
4313 waddwstr(view->window, wline);
4314 free(wline);
4315 wline = NULL;
4316 while (width++ < view->ncols)
4317 waddch(view->window, ' ');
4318 if (view_needs_focus_indication(view))
4319 wstandend(view->window);
4321 if (max_lines <= 1)
4322 return NULL;
4323 max_lines--;
4326 s->eof = 0;
4327 view->maxx = 0;
4328 line = NULL;
4329 while (max_lines > 0 && nprinted < max_lines) {
4330 enum got_diff_line_type linetype;
4331 attr_t attr = 0;
4333 linelen = getline(&line, &linesize, s->f);
4334 if (linelen == -1) {
4335 if (feof(s->f)) {
4336 s->eof = 1;
4337 break;
4339 free(line);
4340 return got_ferror(s->f, GOT_ERR_IO);
4343 if (++s->lineno < s->first_displayed_line)
4344 continue;
4345 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4346 continue;
4347 if (s->lineno == view->hiline)
4348 attr = A_STANDOUT;
4350 /* Set view->maxx based on full line length. */
4351 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4352 view->x ? 1 : 0);
4353 if (err) {
4354 free(line);
4355 return err;
4357 view->maxx = MAX(view->maxx, width);
4358 free(wline);
4359 wline = NULL;
4361 linetype = s->lines[s->lineno].type;
4362 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4363 linetype < GOT_DIFF_LINE_CONTEXT)
4364 attr |= COLOR_PAIR(linetype);
4365 if (attr)
4366 wattron(view->window, attr);
4367 if (s->first_displayed_line + nprinted == s->matched_line &&
4368 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4369 err = add_matched_line(&width, line, view->ncols, 0,
4370 view->window, view->x, regmatch);
4371 if (err) {
4372 free(line);
4373 return err;
4375 } else {
4376 int skip;
4377 err = format_line(&wline, &width, &skip, line,
4378 view->x, view->ncols, 0, view->x ? 1 : 0);
4379 if (err) {
4380 free(line);
4381 return err;
4383 waddwstr(view->window, &wline[skip]);
4384 free(wline);
4385 wline = NULL;
4387 if (s->lineno == view->hiline) {
4388 /* highlight full gline length */
4389 while (width++ < view->ncols)
4390 waddch(view->window, ' ');
4391 } else {
4392 if (width <= view->ncols - 1)
4393 waddch(view->window, '\n');
4395 if (attr)
4396 wattroff(view->window, attr);
4397 if (++nprinted == 1)
4398 s->first_displayed_line = s->lineno;
4400 free(line);
4401 if (nprinted >= 1)
4402 s->last_displayed_line = s->first_displayed_line +
4403 (nprinted - 1);
4404 else
4405 s->last_displayed_line = s->first_displayed_line;
4407 view_border(view);
4409 if (s->eof) {
4410 while (nprinted < view->nlines) {
4411 waddch(view->window, '\n');
4412 nprinted++;
4415 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4416 view->ncols, 0, 0);
4417 if (err) {
4418 return err;
4421 wstandout(view->window);
4422 waddwstr(view->window, wline);
4423 free(wline);
4424 wline = NULL;
4425 wstandend(view->window);
4428 return NULL;
4431 static char *
4432 get_datestr(time_t *time, char *datebuf)
4434 struct tm mytm, *tm;
4435 char *p, *s;
4437 tm = gmtime_r(time, &mytm);
4438 if (tm == NULL)
4439 return NULL;
4440 s = asctime_r(tm, datebuf);
4441 if (s == NULL)
4442 return NULL;
4443 p = strchr(s, '\n');
4444 if (p)
4445 *p = '\0';
4446 return s;
4449 static const struct got_error *
4450 get_changed_paths(struct got_pathlist_head *paths,
4451 struct got_commit_object *commit, struct got_repository *repo)
4453 const struct got_error *err = NULL;
4454 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4455 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4456 struct got_object_qid *qid;
4458 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4459 if (qid != NULL) {
4460 struct got_commit_object *pcommit;
4461 err = got_object_open_as_commit(&pcommit, repo,
4462 &qid->id);
4463 if (err)
4464 return err;
4466 tree_id1 = got_object_id_dup(
4467 got_object_commit_get_tree_id(pcommit));
4468 if (tree_id1 == NULL) {
4469 got_object_commit_close(pcommit);
4470 return got_error_from_errno("got_object_id_dup");
4472 got_object_commit_close(pcommit);
4476 if (tree_id1) {
4477 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4478 if (err)
4479 goto done;
4482 tree_id2 = got_object_commit_get_tree_id(commit);
4483 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4484 if (err)
4485 goto done;
4487 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4488 got_diff_tree_collect_changed_paths, paths, 0);
4489 done:
4490 if (tree1)
4491 got_object_tree_close(tree1);
4492 if (tree2)
4493 got_object_tree_close(tree2);
4494 free(tree_id1);
4495 return err;
4498 static const struct got_error *
4499 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4500 off_t off, uint8_t type)
4502 struct got_diff_line *p;
4504 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4505 if (p == NULL)
4506 return got_error_from_errno("reallocarray");
4507 *lines = p;
4508 (*lines)[*nlines].offset = off;
4509 (*lines)[*nlines].type = type;
4510 (*nlines)++;
4512 return NULL;
4515 static const struct got_error *
4516 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4517 struct got_object_id *commit_id, struct got_reflist_head *refs,
4518 struct got_repository *repo, FILE *outfile)
4520 const struct got_error *err = NULL;
4521 char datebuf[26], *datestr;
4522 struct got_commit_object *commit;
4523 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4524 time_t committer_time;
4525 const char *author, *committer;
4526 char *refs_str = NULL;
4527 struct got_pathlist_head changed_paths;
4528 struct got_pathlist_entry *pe;
4529 off_t outoff = 0;
4530 int n;
4532 TAILQ_INIT(&changed_paths);
4534 if (refs) {
4535 err = build_refs_str(&refs_str, refs, commit_id, repo);
4536 if (err)
4537 return err;
4540 err = got_object_open_as_commit(&commit, repo, commit_id);
4541 if (err)
4542 return err;
4544 err = got_object_id_str(&id_str, commit_id);
4545 if (err) {
4546 err = got_error_from_errno("got_object_id_str");
4547 goto done;
4550 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4551 if (err)
4552 goto done;
4554 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4555 refs_str ? refs_str : "", refs_str ? ")" : "");
4556 if (n < 0) {
4557 err = got_error_from_errno("fprintf");
4558 goto done;
4560 outoff += n;
4561 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4562 if (err)
4563 goto done;
4565 n = fprintf(outfile, "from: %s\n",
4566 got_object_commit_get_author(commit));
4567 if (n < 0) {
4568 err = got_error_from_errno("fprintf");
4569 goto done;
4571 outoff += n;
4572 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4573 if (err)
4574 goto done;
4576 committer_time = got_object_commit_get_committer_time(commit);
4577 datestr = get_datestr(&committer_time, datebuf);
4578 if (datestr) {
4579 n = fprintf(outfile, "date: %s UTC\n", datestr);
4580 if (n < 0) {
4581 err = got_error_from_errno("fprintf");
4582 goto done;
4584 outoff += n;
4585 err = add_line_metadata(lines, nlines, outoff,
4586 GOT_DIFF_LINE_DATE);
4587 if (err)
4588 goto done;
4590 author = got_object_commit_get_author(commit);
4591 committer = got_object_commit_get_committer(commit);
4592 if (strcmp(author, committer) != 0) {
4593 n = fprintf(outfile, "via: %s\n", committer);
4594 if (n < 0) {
4595 err = got_error_from_errno("fprintf");
4596 goto done;
4598 outoff += n;
4599 err = add_line_metadata(lines, nlines, outoff,
4600 GOT_DIFF_LINE_AUTHOR);
4601 if (err)
4602 goto done;
4604 if (got_object_commit_get_nparents(commit) > 1) {
4605 const struct got_object_id_queue *parent_ids;
4606 struct got_object_qid *qid;
4607 int pn = 1;
4608 parent_ids = got_object_commit_get_parent_ids(commit);
4609 STAILQ_FOREACH(qid, parent_ids, entry) {
4610 err = got_object_id_str(&id_str, &qid->id);
4611 if (err)
4612 goto done;
4613 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4614 if (n < 0) {
4615 err = got_error_from_errno("fprintf");
4616 goto done;
4618 outoff += n;
4619 err = add_line_metadata(lines, nlines, outoff,
4620 GOT_DIFF_LINE_META);
4621 if (err)
4622 goto done;
4623 free(id_str);
4624 id_str = NULL;
4628 err = got_object_commit_get_logmsg(&logmsg, commit);
4629 if (err)
4630 goto done;
4631 s = logmsg;
4632 while ((line = strsep(&s, "\n")) != NULL) {
4633 n = fprintf(outfile, "%s\n", line);
4634 if (n < 0) {
4635 err = got_error_from_errno("fprintf");
4636 goto done;
4638 outoff += n;
4639 err = add_line_metadata(lines, nlines, outoff,
4640 GOT_DIFF_LINE_LOGMSG);
4641 if (err)
4642 goto done;
4645 err = get_changed_paths(&changed_paths, commit, repo);
4646 if (err)
4647 goto done;
4648 TAILQ_FOREACH(pe, &changed_paths, entry) {
4649 struct got_diff_changed_path *cp = pe->data;
4650 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4651 if (n < 0) {
4652 err = got_error_from_errno("fprintf");
4653 goto done;
4655 outoff += n;
4656 err = add_line_metadata(lines, nlines, outoff,
4657 GOT_DIFF_LINE_CHANGES);
4658 if (err)
4659 goto done;
4660 free((char *)pe->path);
4661 free(pe->data);
4664 fputc('\n', outfile);
4665 outoff++;
4666 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4667 done:
4668 got_pathlist_free(&changed_paths);
4669 free(id_str);
4670 free(logmsg);
4671 free(refs_str);
4672 got_object_commit_close(commit);
4673 if (err) {
4674 free(*lines);
4675 *lines = NULL;
4676 *nlines = 0;
4678 return err;
4681 static const struct got_error *
4682 create_diff(struct tog_diff_view_state *s)
4684 const struct got_error *err = NULL;
4685 FILE *f = NULL;
4686 int obj_type;
4688 free(s->lines);
4689 s->lines = malloc(sizeof(*s->lines));
4690 if (s->lines == NULL)
4691 return got_error_from_errno("malloc");
4692 s->nlines = 0;
4694 f = got_opentemp();
4695 if (f == NULL) {
4696 err = got_error_from_errno("got_opentemp");
4697 goto done;
4699 if (s->f && fclose(s->f) == EOF) {
4700 err = got_error_from_errno("fclose");
4701 goto done;
4703 s->f = f;
4705 if (s->id1)
4706 err = got_object_get_type(&obj_type, s->repo, s->id1);
4707 else
4708 err = got_object_get_type(&obj_type, s->repo, s->id2);
4709 if (err)
4710 goto done;
4712 switch (obj_type) {
4713 case GOT_OBJ_TYPE_BLOB:
4714 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4715 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4716 s->label1, s->label2, tog_diff_algo, s->diff_context,
4717 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4718 break;
4719 case GOT_OBJ_TYPE_TREE:
4720 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4721 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4722 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4723 s->force_text_diff, s->repo, s->f);
4724 break;
4725 case GOT_OBJ_TYPE_COMMIT: {
4726 const struct got_object_id_queue *parent_ids;
4727 struct got_object_qid *pid;
4728 struct got_commit_object *commit2;
4729 struct got_reflist_head *refs;
4731 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4732 if (err)
4733 goto done;
4734 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4735 /* Show commit info if we're diffing to a parent/root commit. */
4736 if (s->id1 == NULL) {
4737 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4738 refs, s->repo, s->f);
4739 if (err)
4740 goto done;
4741 } else {
4742 parent_ids = got_object_commit_get_parent_ids(commit2);
4743 STAILQ_FOREACH(pid, parent_ids, entry) {
4744 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4745 err = write_commit_info(&s->lines,
4746 &s->nlines, s->id2, refs, s->repo,
4747 s->f);
4748 if (err)
4749 goto done;
4750 break;
4754 got_object_commit_close(commit2);
4756 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4757 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4758 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4759 s->force_text_diff, s->repo, s->f);
4760 break;
4762 default:
4763 err = got_error(GOT_ERR_OBJ_TYPE);
4764 break;
4766 done:
4767 if (s->f && fflush(s->f) != 0 && err == NULL)
4768 err = got_error_from_errno("fflush");
4769 return err;
4772 static void
4773 diff_view_indicate_progress(struct tog_view *view)
4775 mvwaddstr(view->window, 0, 0, "diffing...");
4776 update_panels();
4777 doupdate();
4780 static const struct got_error *
4781 search_start_diff_view(struct tog_view *view)
4783 struct tog_diff_view_state *s = &view->state.diff;
4785 s->matched_line = 0;
4786 return NULL;
4789 static void
4790 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4791 size_t *nlines, int **first, int **last, int **match, int **selected)
4793 struct tog_diff_view_state *s = &view->state.diff;
4795 *f = s->f;
4796 *nlines = s->nlines;
4797 *line_offsets = NULL;
4798 *match = &s->matched_line;
4799 *first = &s->first_displayed_line;
4800 *last = &s->last_displayed_line;
4801 *selected = &s->selected_line;
4804 static const struct got_error *
4805 search_next_view_match(struct tog_view *view)
4807 const struct got_error *err = NULL;
4808 FILE *f;
4809 int lineno;
4810 char *line = NULL;
4811 size_t linesize = 0;
4812 ssize_t linelen;
4813 off_t *line_offsets;
4814 size_t nlines = 0;
4815 int *first, *last, *match, *selected;
4817 if (!view->search_setup)
4818 return got_error_msg(GOT_ERR_NOT_IMPL,
4819 "view search not supported");
4820 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4821 &match, &selected);
4823 if (!view->searching) {
4824 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4825 return NULL;
4828 if (*match) {
4829 if (view->searching == TOG_SEARCH_FORWARD)
4830 lineno = *match + 1;
4831 else
4832 lineno = *match - 1;
4833 } else
4834 lineno = *first - 1 + *selected;
4836 while (1) {
4837 off_t offset;
4839 if (lineno <= 0 || lineno > nlines) {
4840 if (*match == 0) {
4841 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4842 break;
4845 if (view->searching == TOG_SEARCH_FORWARD)
4846 lineno = 1;
4847 else
4848 lineno = nlines;
4851 offset = view->type == TOG_VIEW_DIFF ?
4852 view->state.diff.lines[lineno - 1].offset :
4853 line_offsets[lineno - 1];
4854 if (fseeko(f, offset, SEEK_SET) != 0) {
4855 free(line);
4856 return got_error_from_errno("fseeko");
4858 linelen = getline(&line, &linesize, f);
4859 if (linelen != -1) {
4860 char *exstr;
4861 err = expand_tab(&exstr, line);
4862 if (err)
4863 break;
4864 if (match_line(exstr, &view->regex, 1,
4865 &view->regmatch)) {
4866 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4867 *match = lineno;
4868 free(exstr);
4869 break;
4871 free(exstr);
4873 if (view->searching == TOG_SEARCH_FORWARD)
4874 lineno++;
4875 else
4876 lineno--;
4878 free(line);
4880 if (*match) {
4881 *first = *match;
4882 *selected = 1;
4885 return err;
4888 static const struct got_error *
4889 close_diff_view(struct tog_view *view)
4891 const struct got_error *err = NULL;
4892 struct tog_diff_view_state *s = &view->state.diff;
4894 free(s->id1);
4895 s->id1 = NULL;
4896 free(s->id2);
4897 s->id2 = NULL;
4898 if (s->f && fclose(s->f) == EOF)
4899 err = got_error_from_errno("fclose");
4900 s->f = NULL;
4901 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4902 err = got_error_from_errno("fclose");
4903 s->f1 = NULL;
4904 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4905 err = got_error_from_errno("fclose");
4906 s->f2 = NULL;
4907 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4908 err = got_error_from_errno("close");
4909 s->fd1 = -1;
4910 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4911 err = got_error_from_errno("close");
4912 s->fd2 = -1;
4913 free(s->lines);
4914 s->lines = NULL;
4915 s->nlines = 0;
4916 return err;
4919 static const struct got_error *
4920 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4921 struct got_object_id *id2, const char *label1, const char *label2,
4922 int diff_context, int ignore_whitespace, int force_text_diff,
4923 struct tog_view *parent_view, struct got_repository *repo)
4925 const struct got_error *err;
4926 struct tog_diff_view_state *s = &view->state.diff;
4928 memset(s, 0, sizeof(*s));
4929 s->fd1 = -1;
4930 s->fd2 = -1;
4932 if (id1 != NULL && id2 != NULL) {
4933 int type1, type2;
4934 err = got_object_get_type(&type1, repo, id1);
4935 if (err)
4936 return err;
4937 err = got_object_get_type(&type2, repo, id2);
4938 if (err)
4939 return err;
4941 if (type1 != type2)
4942 return got_error(GOT_ERR_OBJ_TYPE);
4944 s->first_displayed_line = 1;
4945 s->last_displayed_line = view->nlines;
4946 s->selected_line = 1;
4947 s->repo = repo;
4948 s->id1 = id1;
4949 s->id2 = id2;
4950 s->label1 = label1;
4951 s->label2 = label2;
4953 if (id1) {
4954 s->id1 = got_object_id_dup(id1);
4955 if (s->id1 == NULL)
4956 return got_error_from_errno("got_object_id_dup");
4957 } else
4958 s->id1 = NULL;
4960 s->id2 = got_object_id_dup(id2);
4961 if (s->id2 == NULL) {
4962 err = got_error_from_errno("got_object_id_dup");
4963 goto done;
4966 s->f1 = got_opentemp();
4967 if (s->f1 == NULL) {
4968 err = got_error_from_errno("got_opentemp");
4969 goto done;
4972 s->f2 = got_opentemp();
4973 if (s->f2 == NULL) {
4974 err = got_error_from_errno("got_opentemp");
4975 goto done;
4978 s->fd1 = got_opentempfd();
4979 if (s->fd1 == -1) {
4980 err = got_error_from_errno("got_opentempfd");
4981 goto done;
4984 s->fd2 = got_opentempfd();
4985 if (s->fd2 == -1) {
4986 err = got_error_from_errno("got_opentempfd");
4987 goto done;
4990 s->first_displayed_line = 1;
4991 s->last_displayed_line = view->nlines;
4992 s->diff_context = diff_context;
4993 s->ignore_whitespace = ignore_whitespace;
4994 s->force_text_diff = force_text_diff;
4995 s->parent_view = parent_view;
4996 s->repo = repo;
4998 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4999 int rc;
5001 rc = init_pair(GOT_DIFF_LINE_MINUS,
5002 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5003 if (rc != ERR)
5004 rc = init_pair(GOT_DIFF_LINE_PLUS,
5005 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5006 if (rc != ERR)
5007 rc = init_pair(GOT_DIFF_LINE_HUNK,
5008 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5009 if (rc != ERR)
5010 rc = init_pair(GOT_DIFF_LINE_META,
5011 get_color_value("TOG_COLOR_DIFF_META"), -1);
5012 if (rc != ERR)
5013 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5014 get_color_value("TOG_COLOR_DIFF_META"), -1);
5015 if (rc != ERR)
5016 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5017 get_color_value("TOG_COLOR_DIFF_META"), -1);
5018 if (rc != ERR)
5019 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5020 get_color_value("TOG_COLOR_DIFF_META"), -1);
5021 if (rc != ERR)
5022 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5023 get_color_value("TOG_COLOR_AUTHOR"), -1);
5024 if (rc != ERR)
5025 rc = init_pair(GOT_DIFF_LINE_DATE,
5026 get_color_value("TOG_COLOR_DATE"), -1);
5027 if (rc == ERR) {
5028 err = got_error(GOT_ERR_RANGE);
5029 goto done;
5033 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5034 view_is_splitscreen(view))
5035 show_log_view(parent_view); /* draw border */
5036 diff_view_indicate_progress(view);
5038 err = create_diff(s);
5040 view->show = show_diff_view;
5041 view->input = input_diff_view;
5042 view->reset = reset_diff_view;
5043 view->close = close_diff_view;
5044 view->search_start = search_start_diff_view;
5045 view->search_setup = search_setup_diff_view;
5046 view->search_next = search_next_view_match;
5047 done:
5048 if (err)
5049 close_diff_view(view);
5050 return err;
5053 static const struct got_error *
5054 show_diff_view(struct tog_view *view)
5056 const struct got_error *err;
5057 struct tog_diff_view_state *s = &view->state.diff;
5058 char *id_str1 = NULL, *id_str2, *header;
5059 const char *label1, *label2;
5061 if (s->id1) {
5062 err = got_object_id_str(&id_str1, s->id1);
5063 if (err)
5064 return err;
5065 label1 = s->label1 ? s->label1 : id_str1;
5066 } else
5067 label1 = "/dev/null";
5069 err = got_object_id_str(&id_str2, s->id2);
5070 if (err)
5071 return err;
5072 label2 = s->label2 ? s->label2 : id_str2;
5074 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5075 err = got_error_from_errno("asprintf");
5076 free(id_str1);
5077 free(id_str2);
5078 return err;
5080 free(id_str1);
5081 free(id_str2);
5083 err = draw_file(view, header);
5084 free(header);
5085 return err;
5088 static const struct got_error *
5089 set_selected_commit(struct tog_diff_view_state *s,
5090 struct commit_queue_entry *entry)
5092 const struct got_error *err;
5093 const struct got_object_id_queue *parent_ids;
5094 struct got_commit_object *selected_commit;
5095 struct got_object_qid *pid;
5097 free(s->id2);
5098 s->id2 = got_object_id_dup(entry->id);
5099 if (s->id2 == NULL)
5100 return got_error_from_errno("got_object_id_dup");
5102 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5103 if (err)
5104 return err;
5105 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5106 free(s->id1);
5107 pid = STAILQ_FIRST(parent_ids);
5108 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5109 got_object_commit_close(selected_commit);
5110 return NULL;
5113 static const struct got_error *
5114 reset_diff_view(struct tog_view *view)
5116 struct tog_diff_view_state *s = &view->state.diff;
5118 view->count = 0;
5119 wclear(view->window);
5120 s->first_displayed_line = 1;
5121 s->last_displayed_line = view->nlines;
5122 s->matched_line = 0;
5123 diff_view_indicate_progress(view);
5124 return create_diff(s);
5127 static void
5128 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5130 int start, i;
5132 i = start = s->first_displayed_line - 1;
5134 while (s->lines[i].type != type) {
5135 if (i == 0)
5136 i = s->nlines - 1;
5137 if (--i == start)
5138 return; /* do nothing, requested type not in file */
5141 s->selected_line = 1;
5142 s->first_displayed_line = i;
5145 static void
5146 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5148 int start, i;
5150 i = start = s->first_displayed_line + 1;
5152 while (s->lines[i].type != type) {
5153 if (i == s->nlines - 1)
5154 i = 0;
5155 if (++i == start)
5156 return; /* do nothing, requested type not in file */
5159 s->selected_line = 1;
5160 s->first_displayed_line = i;
5163 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5164 int, int, int);
5165 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5166 int, int);
5168 static const struct got_error *
5169 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5171 const struct got_error *err = NULL;
5172 struct tog_diff_view_state *s = &view->state.diff;
5173 struct tog_log_view_state *ls;
5174 struct commit_queue_entry *old_selected_entry;
5175 char *line = NULL;
5176 size_t linesize = 0;
5177 ssize_t linelen;
5178 int i, nscroll = view->nlines - 1, up = 0;
5180 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5182 switch (ch) {
5183 case '0':
5184 view->x = 0;
5185 break;
5186 case '$':
5187 view->x = MAX(view->maxx - view->ncols / 3, 0);
5188 view->count = 0;
5189 break;
5190 case KEY_RIGHT:
5191 case 'l':
5192 if (view->x + view->ncols / 3 < view->maxx)
5193 view->x += 2; /* move two columns right */
5194 else
5195 view->count = 0;
5196 break;
5197 case KEY_LEFT:
5198 case 'h':
5199 view->x -= MIN(view->x, 2); /* move two columns back */
5200 if (view->x <= 0)
5201 view->count = 0;
5202 break;
5203 case 'a':
5204 case 'w':
5205 if (ch == 'a')
5206 s->force_text_diff = !s->force_text_diff;
5207 if (ch == 'w')
5208 s->ignore_whitespace = !s->ignore_whitespace;
5209 err = reset_diff_view(view);
5210 break;
5211 case 'g':
5212 case KEY_HOME:
5213 s->first_displayed_line = 1;
5214 view->count = 0;
5215 break;
5216 case 'G':
5217 case KEY_END:
5218 view->count = 0;
5219 if (s->eof)
5220 break;
5222 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5223 s->eof = 1;
5224 break;
5225 case 'k':
5226 case KEY_UP:
5227 case CTRL('p'):
5228 if (s->first_displayed_line > 1)
5229 s->first_displayed_line--;
5230 else
5231 view->count = 0;
5232 break;
5233 case CTRL('u'):
5234 case 'u':
5235 nscroll /= 2;
5236 /* FALL THROUGH */
5237 case KEY_PPAGE:
5238 case CTRL('b'):
5239 case 'b':
5240 if (s->first_displayed_line == 1) {
5241 view->count = 0;
5242 break;
5244 i = 0;
5245 while (i++ < nscroll && s->first_displayed_line > 1)
5246 s->first_displayed_line--;
5247 break;
5248 case 'j':
5249 case KEY_DOWN:
5250 case CTRL('n'):
5251 if (!s->eof)
5252 s->first_displayed_line++;
5253 else
5254 view->count = 0;
5255 break;
5256 case CTRL('d'):
5257 case 'd':
5258 nscroll /= 2;
5259 /* FALL THROUGH */
5260 case KEY_NPAGE:
5261 case CTRL('f'):
5262 case 'f':
5263 case ' ':
5264 if (s->eof) {
5265 view->count = 0;
5266 break;
5268 i = 0;
5269 while (!s->eof && i++ < nscroll) {
5270 linelen = getline(&line, &linesize, s->f);
5271 s->first_displayed_line++;
5272 if (linelen == -1) {
5273 if (feof(s->f)) {
5274 s->eof = 1;
5275 } else
5276 err = got_ferror(s->f, GOT_ERR_IO);
5277 break;
5280 free(line);
5281 break;
5282 case '(':
5283 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5284 break;
5285 case ')':
5286 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5287 break;
5288 case '{':
5289 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5290 break;
5291 case '}':
5292 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5293 break;
5294 case '[':
5295 if (s->diff_context > 0) {
5296 s->diff_context--;
5297 s->matched_line = 0;
5298 diff_view_indicate_progress(view);
5299 err = create_diff(s);
5300 if (s->first_displayed_line + view->nlines - 1 >
5301 s->nlines) {
5302 s->first_displayed_line = 1;
5303 s->last_displayed_line = view->nlines;
5305 } else
5306 view->count = 0;
5307 break;
5308 case ']':
5309 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5310 s->diff_context++;
5311 s->matched_line = 0;
5312 diff_view_indicate_progress(view);
5313 err = create_diff(s);
5314 } else
5315 view->count = 0;
5316 break;
5317 case '<':
5318 case ',':
5319 case 'K':
5320 up = 1;
5321 /* FALL THROUGH */
5322 case '>':
5323 case '.':
5324 case 'J':
5325 if (s->parent_view == NULL) {
5326 view->count = 0;
5327 break;
5329 s->parent_view->count = view->count;
5331 if (s->parent_view->type == TOG_VIEW_LOG) {
5332 ls = &s->parent_view->state.log;
5333 old_selected_entry = ls->selected_entry;
5335 err = input_log_view(NULL, s->parent_view,
5336 up ? KEY_UP : KEY_DOWN);
5337 if (err)
5338 break;
5339 view->count = s->parent_view->count;
5341 if (old_selected_entry == ls->selected_entry)
5342 break;
5344 err = set_selected_commit(s, ls->selected_entry);
5345 if (err)
5346 break;
5347 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5348 struct tog_blame_view_state *bs;
5349 struct got_object_id *id, *prev_id;
5351 bs = &s->parent_view->state.blame;
5352 prev_id = get_annotation_for_line(bs->blame.lines,
5353 bs->blame.nlines, bs->last_diffed_line);
5355 err = input_blame_view(&view, s->parent_view,
5356 up ? KEY_UP : KEY_DOWN);
5357 if (err)
5358 break;
5359 view->count = s->parent_view->count;
5361 if (prev_id == NULL)
5362 break;
5363 id = get_selected_commit_id(bs->blame.lines,
5364 bs->blame.nlines, bs->first_displayed_line,
5365 bs->selected_line);
5366 if (id == NULL)
5367 break;
5369 if (!got_object_id_cmp(prev_id, id))
5370 break;
5372 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5373 if (err)
5374 break;
5376 s->first_displayed_line = 1;
5377 s->last_displayed_line = view->nlines;
5378 s->matched_line = 0;
5379 view->x = 0;
5381 diff_view_indicate_progress(view);
5382 err = create_diff(s);
5383 break;
5384 default:
5385 view->count = 0;
5386 break;
5389 return err;
5392 static const struct got_error *
5393 cmd_diff(int argc, char *argv[])
5395 const struct got_error *error = NULL;
5396 struct got_repository *repo = NULL;
5397 struct got_worktree *worktree = NULL;
5398 struct got_object_id *id1 = NULL, *id2 = NULL;
5399 char *repo_path = NULL, *cwd = NULL;
5400 char *id_str1 = NULL, *id_str2 = NULL;
5401 char *label1 = NULL, *label2 = NULL;
5402 int diff_context = 3, ignore_whitespace = 0;
5403 int ch, force_text_diff = 0;
5404 const char *errstr;
5405 struct tog_view *view;
5406 int *pack_fds = NULL;
5408 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5409 switch (ch) {
5410 case 'a':
5411 force_text_diff = 1;
5412 break;
5413 case 'C':
5414 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5415 &errstr);
5416 if (errstr != NULL)
5417 errx(1, "number of context lines is %s: %s",
5418 errstr, errstr);
5419 break;
5420 case 'r':
5421 repo_path = realpath(optarg, NULL);
5422 if (repo_path == NULL)
5423 return got_error_from_errno2("realpath",
5424 optarg);
5425 got_path_strip_trailing_slashes(repo_path);
5426 break;
5427 case 'w':
5428 ignore_whitespace = 1;
5429 break;
5430 default:
5431 usage_diff();
5432 /* NOTREACHED */
5436 argc -= optind;
5437 argv += optind;
5439 if (argc == 0) {
5440 usage_diff(); /* TODO show local worktree changes */
5441 } else if (argc == 2) {
5442 id_str1 = argv[0];
5443 id_str2 = argv[1];
5444 } else
5445 usage_diff();
5447 error = got_repo_pack_fds_open(&pack_fds);
5448 if (error)
5449 goto done;
5451 if (repo_path == NULL) {
5452 cwd = getcwd(NULL, 0);
5453 if (cwd == NULL)
5454 return got_error_from_errno("getcwd");
5455 error = got_worktree_open(&worktree, cwd);
5456 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5457 goto done;
5458 if (worktree)
5459 repo_path =
5460 strdup(got_worktree_get_repo_path(worktree));
5461 else
5462 repo_path = strdup(cwd);
5463 if (repo_path == NULL) {
5464 error = got_error_from_errno("strdup");
5465 goto done;
5469 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5470 if (error)
5471 goto done;
5473 init_curses();
5475 error = apply_unveil(got_repo_get_path(repo), NULL);
5476 if (error)
5477 goto done;
5479 error = tog_load_refs(repo, 0);
5480 if (error)
5481 goto done;
5483 error = got_repo_match_object_id(&id1, &label1, id_str1,
5484 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5485 if (error)
5486 goto done;
5488 error = got_repo_match_object_id(&id2, &label2, id_str2,
5489 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5490 if (error)
5491 goto done;
5493 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5494 if (view == NULL) {
5495 error = got_error_from_errno("view_open");
5496 goto done;
5498 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5499 ignore_whitespace, force_text_diff, NULL, repo);
5500 if (error)
5501 goto done;
5502 error = view_loop(view);
5503 done:
5504 free(label1);
5505 free(label2);
5506 free(repo_path);
5507 free(cwd);
5508 if (repo) {
5509 const struct got_error *close_err = got_repo_close(repo);
5510 if (error == NULL)
5511 error = close_err;
5513 if (worktree)
5514 got_worktree_close(worktree);
5515 if (pack_fds) {
5516 const struct got_error *pack_err =
5517 got_repo_pack_fds_close(pack_fds);
5518 if (error == NULL)
5519 error = pack_err;
5521 tog_free_refs();
5522 return error;
5525 __dead static void
5526 usage_blame(void)
5528 endwin();
5529 fprintf(stderr,
5530 "usage: %s blame [-c commit] [-r repository-path] path\n",
5531 getprogname());
5532 exit(1);
5535 struct tog_blame_line {
5536 int annotated;
5537 struct got_object_id *id;
5540 static const struct got_error *
5541 draw_blame(struct tog_view *view)
5543 struct tog_blame_view_state *s = &view->state.blame;
5544 struct tog_blame *blame = &s->blame;
5545 regmatch_t *regmatch = &view->regmatch;
5546 const struct got_error *err;
5547 int lineno = 0, nprinted = 0;
5548 char *line = NULL;
5549 size_t linesize = 0;
5550 ssize_t linelen;
5551 wchar_t *wline;
5552 int width;
5553 struct tog_blame_line *blame_line;
5554 struct got_object_id *prev_id = NULL;
5555 char *id_str;
5556 struct tog_color *tc;
5558 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5559 if (err)
5560 return err;
5562 rewind(blame->f);
5563 werase(view->window);
5565 if (asprintf(&line, "commit %s", id_str) == -1) {
5566 err = got_error_from_errno("asprintf");
5567 free(id_str);
5568 return err;
5571 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5572 free(line);
5573 line = NULL;
5574 if (err)
5575 return err;
5576 if (view_needs_focus_indication(view))
5577 wstandout(view->window);
5578 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5579 if (tc)
5580 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5581 waddwstr(view->window, wline);
5582 while (width++ < view->ncols)
5583 waddch(view->window, ' ');
5584 if (tc)
5585 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5586 if (view_needs_focus_indication(view))
5587 wstandend(view->window);
5588 free(wline);
5589 wline = NULL;
5591 if (view->gline > blame->nlines)
5592 view->gline = blame->nlines;
5594 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5595 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5596 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5597 free(id_str);
5598 return got_error_from_errno("asprintf");
5600 free(id_str);
5601 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5602 free(line);
5603 line = NULL;
5604 if (err)
5605 return err;
5606 waddwstr(view->window, wline);
5607 free(wline);
5608 wline = NULL;
5609 if (width < view->ncols - 1)
5610 waddch(view->window, '\n');
5612 s->eof = 0;
5613 view->maxx = 0;
5614 while (nprinted < view->nlines - 2) {
5615 linelen = getline(&line, &linesize, blame->f);
5616 if (linelen == -1) {
5617 if (feof(blame->f)) {
5618 s->eof = 1;
5619 break;
5621 free(line);
5622 return got_ferror(blame->f, GOT_ERR_IO);
5624 if (++lineno < s->first_displayed_line)
5625 continue;
5626 if (view->gline && !gotoline(view, &lineno, &nprinted))
5627 continue;
5629 /* Set view->maxx based on full line length. */
5630 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5631 if (err) {
5632 free(line);
5633 return err;
5635 free(wline);
5636 wline = NULL;
5637 view->maxx = MAX(view->maxx, width);
5639 if (nprinted == s->selected_line - 1)
5640 wstandout(view->window);
5642 if (blame->nlines > 0) {
5643 blame_line = &blame->lines[lineno - 1];
5644 if (blame_line->annotated && prev_id &&
5645 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5646 !(nprinted == s->selected_line - 1)) {
5647 waddstr(view->window, " ");
5648 } else if (blame_line->annotated) {
5649 char *id_str;
5650 err = got_object_id_str(&id_str,
5651 blame_line->id);
5652 if (err) {
5653 free(line);
5654 return err;
5656 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5657 if (tc)
5658 wattr_on(view->window,
5659 COLOR_PAIR(tc->colorpair), NULL);
5660 wprintw(view->window, "%.8s", id_str);
5661 if (tc)
5662 wattr_off(view->window,
5663 COLOR_PAIR(tc->colorpair), NULL);
5664 free(id_str);
5665 prev_id = blame_line->id;
5666 } else {
5667 waddstr(view->window, "........");
5668 prev_id = NULL;
5670 } else {
5671 waddstr(view->window, "........");
5672 prev_id = NULL;
5675 if (nprinted == s->selected_line - 1)
5676 wstandend(view->window);
5677 waddstr(view->window, " ");
5679 if (view->ncols <= 9) {
5680 width = 9;
5681 } else if (s->first_displayed_line + nprinted ==
5682 s->matched_line &&
5683 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5684 err = add_matched_line(&width, line, view->ncols - 9, 9,
5685 view->window, view->x, regmatch);
5686 if (err) {
5687 free(line);
5688 return err;
5690 width += 9;
5691 } else {
5692 int skip;
5693 err = format_line(&wline, &width, &skip, line,
5694 view->x, view->ncols - 9, 9, 1);
5695 if (err) {
5696 free(line);
5697 return err;
5699 waddwstr(view->window, &wline[skip]);
5700 width += 9;
5701 free(wline);
5702 wline = NULL;
5705 if (width <= view->ncols - 1)
5706 waddch(view->window, '\n');
5707 if (++nprinted == 1)
5708 s->first_displayed_line = lineno;
5710 free(line);
5711 s->last_displayed_line = lineno;
5713 view_border(view);
5715 return NULL;
5718 static const struct got_error *
5719 blame_cb(void *arg, int nlines, int lineno,
5720 struct got_commit_object *commit, struct got_object_id *id)
5722 const struct got_error *err = NULL;
5723 struct tog_blame_cb_args *a = arg;
5724 struct tog_blame_line *line;
5725 int errcode;
5727 if (nlines != a->nlines ||
5728 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5729 return got_error(GOT_ERR_RANGE);
5731 errcode = pthread_mutex_lock(&tog_mutex);
5732 if (errcode)
5733 return got_error_set_errno(errcode, "pthread_mutex_lock");
5735 if (*a->quit) { /* user has quit the blame view */
5736 err = got_error(GOT_ERR_ITER_COMPLETED);
5737 goto done;
5740 if (lineno == -1)
5741 goto done; /* no change in this commit */
5743 line = &a->lines[lineno - 1];
5744 if (line->annotated)
5745 goto done;
5747 line->id = got_object_id_dup(id);
5748 if (line->id == NULL) {
5749 err = got_error_from_errno("got_object_id_dup");
5750 goto done;
5752 line->annotated = 1;
5753 done:
5754 errcode = pthread_mutex_unlock(&tog_mutex);
5755 if (errcode)
5756 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5757 return err;
5760 static void *
5761 blame_thread(void *arg)
5763 const struct got_error *err, *close_err;
5764 struct tog_blame_thread_args *ta = arg;
5765 struct tog_blame_cb_args *a = ta->cb_args;
5766 int errcode, fd1 = -1, fd2 = -1;
5767 FILE *f1 = NULL, *f2 = NULL;
5769 fd1 = got_opentempfd();
5770 if (fd1 == -1)
5771 return (void *)got_error_from_errno("got_opentempfd");
5773 fd2 = got_opentempfd();
5774 if (fd2 == -1) {
5775 err = got_error_from_errno("got_opentempfd");
5776 goto done;
5779 f1 = got_opentemp();
5780 if (f1 == NULL) {
5781 err = (void *)got_error_from_errno("got_opentemp");
5782 goto done;
5784 f2 = got_opentemp();
5785 if (f2 == NULL) {
5786 err = (void *)got_error_from_errno("got_opentemp");
5787 goto done;
5790 err = block_signals_used_by_main_thread();
5791 if (err)
5792 goto done;
5794 err = got_blame(ta->path, a->commit_id, ta->repo,
5795 tog_diff_algo, blame_cb, ta->cb_args,
5796 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5797 if (err && err->code == GOT_ERR_CANCELLED)
5798 err = NULL;
5800 errcode = pthread_mutex_lock(&tog_mutex);
5801 if (errcode) {
5802 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5803 goto done;
5806 close_err = got_repo_close(ta->repo);
5807 if (err == NULL)
5808 err = close_err;
5809 ta->repo = NULL;
5810 *ta->complete = 1;
5812 errcode = pthread_mutex_unlock(&tog_mutex);
5813 if (errcode && err == NULL)
5814 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5816 done:
5817 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5818 err = got_error_from_errno("close");
5819 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5820 err = got_error_from_errno("close");
5821 if (f1 && fclose(f1) == EOF && err == NULL)
5822 err = got_error_from_errno("fclose");
5823 if (f2 && fclose(f2) == EOF && err == NULL)
5824 err = got_error_from_errno("fclose");
5826 return (void *)err;
5829 static struct got_object_id *
5830 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5831 int first_displayed_line, int selected_line)
5833 struct tog_blame_line *line;
5835 if (nlines <= 0)
5836 return NULL;
5838 line = &lines[first_displayed_line - 1 + selected_line - 1];
5839 if (!line->annotated)
5840 return NULL;
5842 return line->id;
5845 static struct got_object_id *
5846 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5847 int lineno)
5849 struct tog_blame_line *line;
5851 if (nlines <= 0 || lineno >= nlines)
5852 return NULL;
5854 line = &lines[lineno - 1];
5855 if (!line->annotated)
5856 return NULL;
5858 return line->id;
5861 static const struct got_error *
5862 stop_blame(struct tog_blame *blame)
5864 const struct got_error *err = NULL;
5865 int i;
5867 if (blame->thread) {
5868 int errcode;
5869 errcode = pthread_mutex_unlock(&tog_mutex);
5870 if (errcode)
5871 return got_error_set_errno(errcode,
5872 "pthread_mutex_unlock");
5873 errcode = pthread_join(blame->thread, (void **)&err);
5874 if (errcode)
5875 return got_error_set_errno(errcode, "pthread_join");
5876 errcode = pthread_mutex_lock(&tog_mutex);
5877 if (errcode)
5878 return got_error_set_errno(errcode,
5879 "pthread_mutex_lock");
5880 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5881 err = NULL;
5882 blame->thread = 0; //NULL;
5884 if (blame->thread_args.repo) {
5885 const struct got_error *close_err;
5886 close_err = got_repo_close(blame->thread_args.repo);
5887 if (err == NULL)
5888 err = close_err;
5889 blame->thread_args.repo = NULL;
5891 if (blame->f) {
5892 if (fclose(blame->f) == EOF && err == NULL)
5893 err = got_error_from_errno("fclose");
5894 blame->f = NULL;
5896 if (blame->lines) {
5897 for (i = 0; i < blame->nlines; i++)
5898 free(blame->lines[i].id);
5899 free(blame->lines);
5900 blame->lines = NULL;
5902 free(blame->cb_args.commit_id);
5903 blame->cb_args.commit_id = NULL;
5904 if (blame->pack_fds) {
5905 const struct got_error *pack_err =
5906 got_repo_pack_fds_close(blame->pack_fds);
5907 if (err == NULL)
5908 err = pack_err;
5909 blame->pack_fds = NULL;
5911 return err;
5914 static const struct got_error *
5915 cancel_blame_view(void *arg)
5917 const struct got_error *err = NULL;
5918 int *done = arg;
5919 int errcode;
5921 errcode = pthread_mutex_lock(&tog_mutex);
5922 if (errcode)
5923 return got_error_set_errno(errcode,
5924 "pthread_mutex_unlock");
5926 if (*done)
5927 err = got_error(GOT_ERR_CANCELLED);
5929 errcode = pthread_mutex_unlock(&tog_mutex);
5930 if (errcode)
5931 return got_error_set_errno(errcode,
5932 "pthread_mutex_lock");
5934 return err;
5937 static const struct got_error *
5938 run_blame(struct tog_view *view)
5940 struct tog_blame_view_state *s = &view->state.blame;
5941 struct tog_blame *blame = &s->blame;
5942 const struct got_error *err = NULL;
5943 struct got_commit_object *commit = NULL;
5944 struct got_blob_object *blob = NULL;
5945 struct got_repository *thread_repo = NULL;
5946 struct got_object_id *obj_id = NULL;
5947 int obj_type, fd = -1;
5948 int *pack_fds = NULL;
5950 err = got_object_open_as_commit(&commit, s->repo,
5951 &s->blamed_commit->id);
5952 if (err)
5953 return err;
5955 fd = got_opentempfd();
5956 if (fd == -1) {
5957 err = got_error_from_errno("got_opentempfd");
5958 goto done;
5961 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5962 if (err)
5963 goto done;
5965 err = got_object_get_type(&obj_type, s->repo, obj_id);
5966 if (err)
5967 goto done;
5969 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5970 err = got_error(GOT_ERR_OBJ_TYPE);
5971 goto done;
5974 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5975 if (err)
5976 goto done;
5977 blame->f = got_opentemp();
5978 if (blame->f == NULL) {
5979 err = got_error_from_errno("got_opentemp");
5980 goto done;
5982 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5983 &blame->line_offsets, blame->f, blob);
5984 if (err)
5985 goto done;
5986 if (blame->nlines == 0) {
5987 s->blame_complete = 1;
5988 goto done;
5991 /* Don't include \n at EOF in the blame line count. */
5992 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5993 blame->nlines--;
5995 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5996 if (blame->lines == NULL) {
5997 err = got_error_from_errno("calloc");
5998 goto done;
6001 err = got_repo_pack_fds_open(&pack_fds);
6002 if (err)
6003 goto done;
6004 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6005 pack_fds);
6006 if (err)
6007 goto done;
6009 blame->pack_fds = pack_fds;
6010 blame->cb_args.view = view;
6011 blame->cb_args.lines = blame->lines;
6012 blame->cb_args.nlines = blame->nlines;
6013 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6014 if (blame->cb_args.commit_id == NULL) {
6015 err = got_error_from_errno("got_object_id_dup");
6016 goto done;
6018 blame->cb_args.quit = &s->done;
6020 blame->thread_args.path = s->path;
6021 blame->thread_args.repo = thread_repo;
6022 blame->thread_args.cb_args = &blame->cb_args;
6023 blame->thread_args.complete = &s->blame_complete;
6024 blame->thread_args.cancel_cb = cancel_blame_view;
6025 blame->thread_args.cancel_arg = &s->done;
6026 s->blame_complete = 0;
6028 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6029 s->first_displayed_line = 1;
6030 s->last_displayed_line = view->nlines;
6031 s->selected_line = 1;
6033 s->matched_line = 0;
6035 done:
6036 if (commit)
6037 got_object_commit_close(commit);
6038 if (fd != -1 && close(fd) == -1 && err == NULL)
6039 err = got_error_from_errno("close");
6040 if (blob)
6041 got_object_blob_close(blob);
6042 free(obj_id);
6043 if (err)
6044 stop_blame(blame);
6045 return err;
6048 static const struct got_error *
6049 open_blame_view(struct tog_view *view, char *path,
6050 struct got_object_id *commit_id, struct got_repository *repo)
6052 const struct got_error *err = NULL;
6053 struct tog_blame_view_state *s = &view->state.blame;
6055 STAILQ_INIT(&s->blamed_commits);
6057 s->path = strdup(path);
6058 if (s->path == NULL)
6059 return got_error_from_errno("strdup");
6061 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6062 if (err) {
6063 free(s->path);
6064 return err;
6067 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6068 s->first_displayed_line = 1;
6069 s->last_displayed_line = view->nlines;
6070 s->selected_line = 1;
6071 s->blame_complete = 0;
6072 s->repo = repo;
6073 s->commit_id = commit_id;
6074 memset(&s->blame, 0, sizeof(s->blame));
6076 STAILQ_INIT(&s->colors);
6077 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6078 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6079 get_color_value("TOG_COLOR_COMMIT"));
6080 if (err)
6081 return err;
6084 view->show = show_blame_view;
6085 view->input = input_blame_view;
6086 view->reset = reset_blame_view;
6087 view->close = close_blame_view;
6088 view->search_start = search_start_blame_view;
6089 view->search_setup = search_setup_blame_view;
6090 view->search_next = search_next_view_match;
6092 return run_blame(view);
6095 static const struct got_error *
6096 close_blame_view(struct tog_view *view)
6098 const struct got_error *err = NULL;
6099 struct tog_blame_view_state *s = &view->state.blame;
6101 if (s->blame.thread)
6102 err = stop_blame(&s->blame);
6104 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6105 struct got_object_qid *blamed_commit;
6106 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6107 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6108 got_object_qid_free(blamed_commit);
6111 free(s->path);
6112 free_colors(&s->colors);
6113 return err;
6116 static const struct got_error *
6117 search_start_blame_view(struct tog_view *view)
6119 struct tog_blame_view_state *s = &view->state.blame;
6121 s->matched_line = 0;
6122 return NULL;
6125 static void
6126 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6127 size_t *nlines, int **first, int **last, int **match, int **selected)
6129 struct tog_blame_view_state *s = &view->state.blame;
6131 *f = s->blame.f;
6132 *nlines = s->blame.nlines;
6133 *line_offsets = s->blame.line_offsets;
6134 *match = &s->matched_line;
6135 *first = &s->first_displayed_line;
6136 *last = &s->last_displayed_line;
6137 *selected = &s->selected_line;
6140 static const struct got_error *
6141 show_blame_view(struct tog_view *view)
6143 const struct got_error *err = NULL;
6144 struct tog_blame_view_state *s = &view->state.blame;
6145 int errcode;
6147 if (s->blame.thread == 0 && !s->blame_complete) {
6148 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6149 &s->blame.thread_args);
6150 if (errcode)
6151 return got_error_set_errno(errcode, "pthread_create");
6153 halfdelay(1); /* fast refresh while annotating */
6156 if (s->blame_complete)
6157 halfdelay(10); /* disable fast refresh */
6159 err = draw_blame(view);
6161 view_border(view);
6162 return err;
6165 static const struct got_error *
6166 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6167 struct got_repository *repo, struct got_object_id *id)
6169 struct tog_view *log_view;
6170 const struct got_error *err = NULL;
6172 *new_view = NULL;
6174 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6175 if (log_view == NULL)
6176 return got_error_from_errno("view_open");
6178 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6179 if (err)
6180 view_close(log_view);
6181 else
6182 *new_view = log_view;
6184 return err;
6187 static const struct got_error *
6188 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6190 const struct got_error *err = NULL, *thread_err = NULL;
6191 struct tog_view *diff_view;
6192 struct tog_blame_view_state *s = &view->state.blame;
6193 int eos, nscroll, begin_y = 0, begin_x = 0;
6195 eos = nscroll = view->nlines - 2;
6196 if (view_is_hsplit_top(view))
6197 --eos; /* border */
6199 switch (ch) {
6200 case '0':
6201 view->x = 0;
6202 break;
6203 case '$':
6204 view->x = MAX(view->maxx - view->ncols / 3, 0);
6205 view->count = 0;
6206 break;
6207 case KEY_RIGHT:
6208 case 'l':
6209 if (view->x + view->ncols / 3 < view->maxx)
6210 view->x += 2; /* move two columns right */
6211 else
6212 view->count = 0;
6213 break;
6214 case KEY_LEFT:
6215 case 'h':
6216 view->x -= MIN(view->x, 2); /* move two columns back */
6217 if (view->x <= 0)
6218 view->count = 0;
6219 break;
6220 case 'q':
6221 s->done = 1;
6222 break;
6223 case 'g':
6224 case KEY_HOME:
6225 s->selected_line = 1;
6226 s->first_displayed_line = 1;
6227 view->count = 0;
6228 break;
6229 case 'G':
6230 case KEY_END:
6231 if (s->blame.nlines < eos) {
6232 s->selected_line = s->blame.nlines;
6233 s->first_displayed_line = 1;
6234 } else {
6235 s->selected_line = eos;
6236 s->first_displayed_line = s->blame.nlines - (eos - 1);
6238 view->count = 0;
6239 break;
6240 case 'k':
6241 case KEY_UP:
6242 case CTRL('p'):
6243 if (s->selected_line > 1)
6244 s->selected_line--;
6245 else if (s->selected_line == 1 &&
6246 s->first_displayed_line > 1)
6247 s->first_displayed_line--;
6248 else
6249 view->count = 0;
6250 break;
6251 case CTRL('u'):
6252 case 'u':
6253 nscroll /= 2;
6254 /* FALL THROUGH */
6255 case KEY_PPAGE:
6256 case CTRL('b'):
6257 case 'b':
6258 if (s->first_displayed_line == 1) {
6259 if (view->count > 1)
6260 nscroll += nscroll;
6261 s->selected_line = MAX(1, s->selected_line - nscroll);
6262 view->count = 0;
6263 break;
6265 if (s->first_displayed_line > nscroll)
6266 s->first_displayed_line -= nscroll;
6267 else
6268 s->first_displayed_line = 1;
6269 break;
6270 case 'j':
6271 case KEY_DOWN:
6272 case CTRL('n'):
6273 if (s->selected_line < eos && s->first_displayed_line +
6274 s->selected_line <= s->blame.nlines)
6275 s->selected_line++;
6276 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6277 s->first_displayed_line++;
6278 else
6279 view->count = 0;
6280 break;
6281 case 'c':
6282 case 'p': {
6283 struct got_object_id *id = NULL;
6285 view->count = 0;
6286 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6287 s->first_displayed_line, s->selected_line);
6288 if (id == NULL)
6289 break;
6290 if (ch == 'p') {
6291 struct got_commit_object *commit, *pcommit;
6292 struct got_object_qid *pid;
6293 struct got_object_id *blob_id = NULL;
6294 int obj_type;
6295 err = got_object_open_as_commit(&commit,
6296 s->repo, id);
6297 if (err)
6298 break;
6299 pid = STAILQ_FIRST(
6300 got_object_commit_get_parent_ids(commit));
6301 if (pid == NULL) {
6302 got_object_commit_close(commit);
6303 break;
6305 /* Check if path history ends here. */
6306 err = got_object_open_as_commit(&pcommit,
6307 s->repo, &pid->id);
6308 if (err)
6309 break;
6310 err = got_object_id_by_path(&blob_id, s->repo,
6311 pcommit, s->path);
6312 got_object_commit_close(pcommit);
6313 if (err) {
6314 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6315 err = NULL;
6316 got_object_commit_close(commit);
6317 break;
6319 err = got_object_get_type(&obj_type, s->repo,
6320 blob_id);
6321 free(blob_id);
6322 /* Can't blame non-blob type objects. */
6323 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6324 got_object_commit_close(commit);
6325 break;
6327 err = got_object_qid_alloc(&s->blamed_commit,
6328 &pid->id);
6329 got_object_commit_close(commit);
6330 } else {
6331 if (got_object_id_cmp(id,
6332 &s->blamed_commit->id) == 0)
6333 break;
6334 err = got_object_qid_alloc(&s->blamed_commit,
6335 id);
6337 if (err)
6338 break;
6339 s->done = 1;
6340 thread_err = stop_blame(&s->blame);
6341 s->done = 0;
6342 if (thread_err)
6343 break;
6344 STAILQ_INSERT_HEAD(&s->blamed_commits,
6345 s->blamed_commit, entry);
6346 err = run_blame(view);
6347 if (err)
6348 break;
6349 break;
6351 case 'C': {
6352 struct got_object_qid *first;
6354 view->count = 0;
6355 first = STAILQ_FIRST(&s->blamed_commits);
6356 if (!got_object_id_cmp(&first->id, s->commit_id))
6357 break;
6358 s->done = 1;
6359 thread_err = stop_blame(&s->blame);
6360 s->done = 0;
6361 if (thread_err)
6362 break;
6363 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6364 got_object_qid_free(s->blamed_commit);
6365 s->blamed_commit =
6366 STAILQ_FIRST(&s->blamed_commits);
6367 err = run_blame(view);
6368 if (err)
6369 break;
6370 break;
6372 case 'L':
6373 view->count = 0;
6374 s->id_to_log = get_selected_commit_id(s->blame.lines,
6375 s->blame.nlines, s->first_displayed_line, s->selected_line);
6376 if (s->id_to_log)
6377 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6378 break;
6379 case KEY_ENTER:
6380 case '\r': {
6381 struct got_object_id *id = NULL;
6382 struct got_object_qid *pid;
6383 struct got_commit_object *commit = NULL;
6385 view->count = 0;
6386 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6387 s->first_displayed_line, s->selected_line);
6388 if (id == NULL)
6389 break;
6390 err = got_object_open_as_commit(&commit, s->repo, id);
6391 if (err)
6392 break;
6393 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6394 if (*new_view) {
6395 /* traversed from diff view, release diff resources */
6396 err = close_diff_view(*new_view);
6397 if (err)
6398 break;
6399 diff_view = *new_view;
6400 } else {
6401 if (view_is_parent_view(view))
6402 view_get_split(view, &begin_y, &begin_x);
6404 diff_view = view_open(0, 0, begin_y, begin_x,
6405 TOG_VIEW_DIFF);
6406 if (diff_view == NULL) {
6407 got_object_commit_close(commit);
6408 err = got_error_from_errno("view_open");
6409 break;
6412 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6413 id, NULL, NULL, 3, 0, 0, view, s->repo);
6414 got_object_commit_close(commit);
6415 if (err) {
6416 view_close(diff_view);
6417 break;
6419 s->last_diffed_line = s->first_displayed_line - 1 +
6420 s->selected_line;
6421 if (*new_view)
6422 break; /* still open from active diff view */
6423 if (view_is_parent_view(view) &&
6424 view->mode == TOG_VIEW_SPLIT_HRZN) {
6425 err = view_init_hsplit(view, begin_y);
6426 if (err)
6427 break;
6430 view->focussed = 0;
6431 diff_view->focussed = 1;
6432 diff_view->mode = view->mode;
6433 diff_view->nlines = view->lines - begin_y;
6434 if (view_is_parent_view(view)) {
6435 view_transfer_size(diff_view, view);
6436 err = view_close_child(view);
6437 if (err)
6438 break;
6439 err = view_set_child(view, diff_view);
6440 if (err)
6441 break;
6442 view->focus_child = 1;
6443 } else
6444 *new_view = diff_view;
6445 if (err)
6446 break;
6447 break;
6449 case CTRL('d'):
6450 case 'd':
6451 nscroll /= 2;
6452 /* FALL THROUGH */
6453 case KEY_NPAGE:
6454 case CTRL('f'):
6455 case 'f':
6456 case ' ':
6457 if (s->last_displayed_line >= s->blame.nlines &&
6458 s->selected_line >= MIN(s->blame.nlines,
6459 view->nlines - 2)) {
6460 view->count = 0;
6461 break;
6463 if (s->last_displayed_line >= s->blame.nlines &&
6464 s->selected_line < view->nlines - 2) {
6465 s->selected_line +=
6466 MIN(nscroll, s->last_displayed_line -
6467 s->first_displayed_line - s->selected_line + 1);
6469 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6470 s->first_displayed_line += nscroll;
6471 else
6472 s->first_displayed_line =
6473 s->blame.nlines - (view->nlines - 3);
6474 break;
6475 case KEY_RESIZE:
6476 if (s->selected_line > view->nlines - 2) {
6477 s->selected_line = MIN(s->blame.nlines,
6478 view->nlines - 2);
6480 break;
6481 default:
6482 view->count = 0;
6483 break;
6485 return thread_err ? thread_err : err;
6488 static const struct got_error *
6489 reset_blame_view(struct tog_view *view)
6491 const struct got_error *err;
6492 struct tog_blame_view_state *s = &view->state.blame;
6494 view->count = 0;
6495 s->done = 1;
6496 err = stop_blame(&s->blame);
6497 s->done = 0;
6498 if (err)
6499 return err;
6500 return run_blame(view);
6503 static const struct got_error *
6504 cmd_blame(int argc, char *argv[])
6506 const struct got_error *error;
6507 struct got_repository *repo = NULL;
6508 struct got_worktree *worktree = NULL;
6509 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6510 char *link_target = NULL;
6511 struct got_object_id *commit_id = NULL;
6512 struct got_commit_object *commit = NULL;
6513 char *commit_id_str = NULL;
6514 int ch;
6515 struct tog_view *view;
6516 int *pack_fds = NULL;
6518 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6519 switch (ch) {
6520 case 'c':
6521 commit_id_str = optarg;
6522 break;
6523 case 'r':
6524 repo_path = realpath(optarg, NULL);
6525 if (repo_path == NULL)
6526 return got_error_from_errno2("realpath",
6527 optarg);
6528 break;
6529 default:
6530 usage_blame();
6531 /* NOTREACHED */
6535 argc -= optind;
6536 argv += optind;
6538 if (argc != 1)
6539 usage_blame();
6541 error = got_repo_pack_fds_open(&pack_fds);
6542 if (error != NULL)
6543 goto done;
6545 if (repo_path == NULL) {
6546 cwd = getcwd(NULL, 0);
6547 if (cwd == NULL)
6548 return got_error_from_errno("getcwd");
6549 error = got_worktree_open(&worktree, cwd);
6550 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6551 goto done;
6552 if (worktree)
6553 repo_path =
6554 strdup(got_worktree_get_repo_path(worktree));
6555 else
6556 repo_path = strdup(cwd);
6557 if (repo_path == NULL) {
6558 error = got_error_from_errno("strdup");
6559 goto done;
6563 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6564 if (error != NULL)
6565 goto done;
6567 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6568 worktree);
6569 if (error)
6570 goto done;
6572 init_curses();
6574 error = apply_unveil(got_repo_get_path(repo), NULL);
6575 if (error)
6576 goto done;
6578 error = tog_load_refs(repo, 0);
6579 if (error)
6580 goto done;
6582 if (commit_id_str == NULL) {
6583 struct got_reference *head_ref;
6584 error = got_ref_open(&head_ref, repo, worktree ?
6585 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6586 if (error != NULL)
6587 goto done;
6588 error = got_ref_resolve(&commit_id, repo, head_ref);
6589 got_ref_close(head_ref);
6590 } else {
6591 error = got_repo_match_object_id(&commit_id, NULL,
6592 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6594 if (error != NULL)
6595 goto done;
6597 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6598 if (view == NULL) {
6599 error = got_error_from_errno("view_open");
6600 goto done;
6603 error = got_object_open_as_commit(&commit, repo, commit_id);
6604 if (error)
6605 goto done;
6607 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6608 commit, repo);
6609 if (error)
6610 goto done;
6612 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6613 commit_id, repo);
6614 if (error)
6615 goto done;
6616 if (worktree) {
6617 /* Release work tree lock. */
6618 got_worktree_close(worktree);
6619 worktree = NULL;
6621 error = view_loop(view);
6622 done:
6623 free(repo_path);
6624 free(in_repo_path);
6625 free(link_target);
6626 free(cwd);
6627 free(commit_id);
6628 if (commit)
6629 got_object_commit_close(commit);
6630 if (worktree)
6631 got_worktree_close(worktree);
6632 if (repo) {
6633 const struct got_error *close_err = got_repo_close(repo);
6634 if (error == NULL)
6635 error = close_err;
6637 if (pack_fds) {
6638 const struct got_error *pack_err =
6639 got_repo_pack_fds_close(pack_fds);
6640 if (error == NULL)
6641 error = pack_err;
6643 tog_free_refs();
6644 return error;
6647 static const struct got_error *
6648 draw_tree_entries(struct tog_view *view, const char *parent_path)
6650 struct tog_tree_view_state *s = &view->state.tree;
6651 const struct got_error *err = NULL;
6652 struct got_tree_entry *te;
6653 wchar_t *wline;
6654 char *index = NULL;
6655 struct tog_color *tc;
6656 int width, n, nentries, i = 1;
6657 int limit = view->nlines;
6659 s->ndisplayed = 0;
6660 if (view_is_hsplit_top(view))
6661 --limit; /* border */
6663 werase(view->window);
6665 if (limit == 0)
6666 return NULL;
6668 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6669 0, 0);
6670 if (err)
6671 return err;
6672 if (view_needs_focus_indication(view))
6673 wstandout(view->window);
6674 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6675 if (tc)
6676 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6677 waddwstr(view->window, wline);
6678 free(wline);
6679 wline = NULL;
6680 while (width++ < view->ncols)
6681 waddch(view->window, ' ');
6682 if (tc)
6683 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6684 if (view_needs_focus_indication(view))
6685 wstandend(view->window);
6686 if (--limit <= 0)
6687 return NULL;
6689 i += s->selected;
6690 if (s->first_displayed_entry) {
6691 i += got_tree_entry_get_index(s->first_displayed_entry);
6692 if (s->tree != s->root)
6693 ++i; /* account for ".." entry */
6695 nentries = got_object_tree_get_nentries(s->tree);
6696 if (asprintf(&index, "[%d/%d] %s",
6697 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6698 return got_error_from_errno("asprintf");
6699 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6700 free(index);
6701 if (err)
6702 return err;
6703 waddwstr(view->window, wline);
6704 free(wline);
6705 wline = NULL;
6706 if (width < view->ncols - 1)
6707 waddch(view->window, '\n');
6708 if (--limit <= 0)
6709 return NULL;
6710 waddch(view->window, '\n');
6711 if (--limit <= 0)
6712 return NULL;
6714 if (s->first_displayed_entry == NULL) {
6715 te = got_object_tree_get_first_entry(s->tree);
6716 if (s->selected == 0) {
6717 if (view->focussed)
6718 wstandout(view->window);
6719 s->selected_entry = NULL;
6721 waddstr(view->window, " ..\n"); /* parent directory */
6722 if (s->selected == 0 && view->focussed)
6723 wstandend(view->window);
6724 s->ndisplayed++;
6725 if (--limit <= 0)
6726 return NULL;
6727 n = 1;
6728 } else {
6729 n = 0;
6730 te = s->first_displayed_entry;
6733 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6734 char *line = NULL, *id_str = NULL, *link_target = NULL;
6735 const char *modestr = "";
6736 mode_t mode;
6738 te = got_object_tree_get_entry(s->tree, i);
6739 mode = got_tree_entry_get_mode(te);
6741 if (s->show_ids) {
6742 err = got_object_id_str(&id_str,
6743 got_tree_entry_get_id(te));
6744 if (err)
6745 return got_error_from_errno(
6746 "got_object_id_str");
6748 if (got_object_tree_entry_is_submodule(te))
6749 modestr = "$";
6750 else if (S_ISLNK(mode)) {
6751 int i;
6753 err = got_tree_entry_get_symlink_target(&link_target,
6754 te, s->repo);
6755 if (err) {
6756 free(id_str);
6757 return err;
6759 for (i = 0; i < strlen(link_target); i++) {
6760 if (!isprint((unsigned char)link_target[i]))
6761 link_target[i] = '?';
6763 modestr = "@";
6765 else if (S_ISDIR(mode))
6766 modestr = "/";
6767 else if (mode & S_IXUSR)
6768 modestr = "*";
6769 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6770 got_tree_entry_get_name(te), modestr,
6771 link_target ? " -> ": "",
6772 link_target ? link_target : "") == -1) {
6773 free(id_str);
6774 free(link_target);
6775 return got_error_from_errno("asprintf");
6777 free(id_str);
6778 free(link_target);
6779 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6780 0, 0);
6781 if (err) {
6782 free(line);
6783 break;
6785 if (n == s->selected) {
6786 if (view->focussed)
6787 wstandout(view->window);
6788 s->selected_entry = te;
6790 tc = match_color(&s->colors, line);
6791 if (tc)
6792 wattr_on(view->window,
6793 COLOR_PAIR(tc->colorpair), NULL);
6794 waddwstr(view->window, wline);
6795 if (tc)
6796 wattr_off(view->window,
6797 COLOR_PAIR(tc->colorpair), NULL);
6798 if (width < view->ncols - 1)
6799 waddch(view->window, '\n');
6800 if (n == s->selected && view->focussed)
6801 wstandend(view->window);
6802 free(line);
6803 free(wline);
6804 wline = NULL;
6805 n++;
6806 s->ndisplayed++;
6807 s->last_displayed_entry = te;
6808 if (--limit <= 0)
6809 break;
6812 return err;
6815 static void
6816 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6818 struct got_tree_entry *te;
6819 int isroot = s->tree == s->root;
6820 int i = 0;
6822 if (s->first_displayed_entry == NULL)
6823 return;
6825 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6826 while (i++ < maxscroll) {
6827 if (te == NULL) {
6828 if (!isroot)
6829 s->first_displayed_entry = NULL;
6830 break;
6832 s->first_displayed_entry = te;
6833 te = got_tree_entry_get_prev(s->tree, te);
6837 static const struct got_error *
6838 tree_scroll_down(struct tog_view *view, int maxscroll)
6840 struct tog_tree_view_state *s = &view->state.tree;
6841 struct got_tree_entry *next, *last;
6842 int n = 0;
6844 if (s->first_displayed_entry)
6845 next = got_tree_entry_get_next(s->tree,
6846 s->first_displayed_entry);
6847 else
6848 next = got_object_tree_get_first_entry(s->tree);
6850 last = s->last_displayed_entry;
6851 while (next && n++ < maxscroll) {
6852 if (last) {
6853 s->last_displayed_entry = last;
6854 last = got_tree_entry_get_next(s->tree, last);
6856 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6857 s->first_displayed_entry = next;
6858 next = got_tree_entry_get_next(s->tree, next);
6862 return NULL;
6865 static const struct got_error *
6866 tree_entry_path(char **path, struct tog_parent_trees *parents,
6867 struct got_tree_entry *te)
6869 const struct got_error *err = NULL;
6870 struct tog_parent_tree *pt;
6871 size_t len = 2; /* for leading slash and NUL */
6873 TAILQ_FOREACH(pt, parents, entry)
6874 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6875 + 1 /* slash */;
6876 if (te)
6877 len += strlen(got_tree_entry_get_name(te));
6879 *path = calloc(1, len);
6880 if (path == NULL)
6881 return got_error_from_errno("calloc");
6883 (*path)[0] = '/';
6884 pt = TAILQ_LAST(parents, tog_parent_trees);
6885 while (pt) {
6886 const char *name = got_tree_entry_get_name(pt->selected_entry);
6887 if (strlcat(*path, name, len) >= len) {
6888 err = got_error(GOT_ERR_NO_SPACE);
6889 goto done;
6891 if (strlcat(*path, "/", len) >= len) {
6892 err = got_error(GOT_ERR_NO_SPACE);
6893 goto done;
6895 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6897 if (te) {
6898 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6899 err = got_error(GOT_ERR_NO_SPACE);
6900 goto done;
6903 done:
6904 if (err) {
6905 free(*path);
6906 *path = NULL;
6908 return err;
6911 static const struct got_error *
6912 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6913 struct got_tree_entry *te, struct tog_parent_trees *parents,
6914 struct got_object_id *commit_id, struct got_repository *repo)
6916 const struct got_error *err = NULL;
6917 char *path;
6918 struct tog_view *blame_view;
6920 *new_view = NULL;
6922 err = tree_entry_path(&path, parents, te);
6923 if (err)
6924 return err;
6926 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6927 if (blame_view == NULL) {
6928 err = got_error_from_errno("view_open");
6929 goto done;
6932 err = open_blame_view(blame_view, path, commit_id, repo);
6933 if (err) {
6934 if (err->code == GOT_ERR_CANCELLED)
6935 err = NULL;
6936 view_close(blame_view);
6937 } else
6938 *new_view = blame_view;
6939 done:
6940 free(path);
6941 return err;
6944 static const struct got_error *
6945 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6946 struct tog_tree_view_state *s)
6948 struct tog_view *log_view;
6949 const struct got_error *err = NULL;
6950 char *path;
6952 *new_view = NULL;
6954 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6955 if (log_view == NULL)
6956 return got_error_from_errno("view_open");
6958 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6959 if (err)
6960 return err;
6962 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6963 path, 0);
6964 if (err)
6965 view_close(log_view);
6966 else
6967 *new_view = log_view;
6968 free(path);
6969 return err;
6972 static const struct got_error *
6973 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6974 const char *head_ref_name, struct got_repository *repo)
6976 const struct got_error *err = NULL;
6977 char *commit_id_str = NULL;
6978 struct tog_tree_view_state *s = &view->state.tree;
6979 struct got_commit_object *commit = NULL;
6981 TAILQ_INIT(&s->parents);
6982 STAILQ_INIT(&s->colors);
6984 s->commit_id = got_object_id_dup(commit_id);
6985 if (s->commit_id == NULL)
6986 return got_error_from_errno("got_object_id_dup");
6988 err = got_object_open_as_commit(&commit, repo, commit_id);
6989 if (err)
6990 goto done;
6993 * The root is opened here and will be closed when the view is closed.
6994 * Any visited subtrees and their path-wise parents are opened and
6995 * closed on demand.
6997 err = got_object_open_as_tree(&s->root, repo,
6998 got_object_commit_get_tree_id(commit));
6999 if (err)
7000 goto done;
7001 s->tree = s->root;
7003 err = got_object_id_str(&commit_id_str, commit_id);
7004 if (err != NULL)
7005 goto done;
7007 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7008 err = got_error_from_errno("asprintf");
7009 goto done;
7012 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7013 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7014 if (head_ref_name) {
7015 s->head_ref_name = strdup(head_ref_name);
7016 if (s->head_ref_name == NULL) {
7017 err = got_error_from_errno("strdup");
7018 goto done;
7021 s->repo = repo;
7023 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7024 err = add_color(&s->colors, "\\$$",
7025 TOG_COLOR_TREE_SUBMODULE,
7026 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7027 if (err)
7028 goto done;
7029 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7030 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7031 if (err)
7032 goto done;
7033 err = add_color(&s->colors, "/$",
7034 TOG_COLOR_TREE_DIRECTORY,
7035 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7036 if (err)
7037 goto done;
7039 err = add_color(&s->colors, "\\*$",
7040 TOG_COLOR_TREE_EXECUTABLE,
7041 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7042 if (err)
7043 goto done;
7045 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7046 get_color_value("TOG_COLOR_COMMIT"));
7047 if (err)
7048 goto done;
7051 view->show = show_tree_view;
7052 view->input = input_tree_view;
7053 view->close = close_tree_view;
7054 view->search_start = search_start_tree_view;
7055 view->search_next = search_next_tree_view;
7056 done:
7057 free(commit_id_str);
7058 if (commit)
7059 got_object_commit_close(commit);
7060 if (err)
7061 close_tree_view(view);
7062 return err;
7065 static const struct got_error *
7066 close_tree_view(struct tog_view *view)
7068 struct tog_tree_view_state *s = &view->state.tree;
7070 free_colors(&s->colors);
7071 free(s->tree_label);
7072 s->tree_label = NULL;
7073 free(s->commit_id);
7074 s->commit_id = NULL;
7075 free(s->head_ref_name);
7076 s->head_ref_name = NULL;
7077 while (!TAILQ_EMPTY(&s->parents)) {
7078 struct tog_parent_tree *parent;
7079 parent = TAILQ_FIRST(&s->parents);
7080 TAILQ_REMOVE(&s->parents, parent, entry);
7081 if (parent->tree != s->root)
7082 got_object_tree_close(parent->tree);
7083 free(parent);
7086 if (s->tree != NULL && s->tree != s->root)
7087 got_object_tree_close(s->tree);
7088 if (s->root)
7089 got_object_tree_close(s->root);
7090 return NULL;
7093 static const struct got_error *
7094 search_start_tree_view(struct tog_view *view)
7096 struct tog_tree_view_state *s = &view->state.tree;
7098 s->matched_entry = NULL;
7099 return NULL;
7102 static int
7103 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7105 regmatch_t regmatch;
7107 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7108 0) == 0;
7111 static const struct got_error *
7112 search_next_tree_view(struct tog_view *view)
7114 struct tog_tree_view_state *s = &view->state.tree;
7115 struct got_tree_entry *te = NULL;
7117 if (!view->searching) {
7118 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7119 return NULL;
7122 if (s->matched_entry) {
7123 if (view->searching == TOG_SEARCH_FORWARD) {
7124 if (s->selected_entry)
7125 te = got_tree_entry_get_next(s->tree,
7126 s->selected_entry);
7127 else
7128 te = got_object_tree_get_first_entry(s->tree);
7129 } else {
7130 if (s->selected_entry == NULL)
7131 te = got_object_tree_get_last_entry(s->tree);
7132 else
7133 te = got_tree_entry_get_prev(s->tree,
7134 s->selected_entry);
7136 } else {
7137 if (s->selected_entry)
7138 te = s->selected_entry;
7139 else if (view->searching == TOG_SEARCH_FORWARD)
7140 te = got_object_tree_get_first_entry(s->tree);
7141 else
7142 te = got_object_tree_get_last_entry(s->tree);
7145 while (1) {
7146 if (te == NULL) {
7147 if (s->matched_entry == NULL) {
7148 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7149 return NULL;
7151 if (view->searching == TOG_SEARCH_FORWARD)
7152 te = got_object_tree_get_first_entry(s->tree);
7153 else
7154 te = got_object_tree_get_last_entry(s->tree);
7157 if (match_tree_entry(te, &view->regex)) {
7158 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7159 s->matched_entry = te;
7160 break;
7163 if (view->searching == TOG_SEARCH_FORWARD)
7164 te = got_tree_entry_get_next(s->tree, te);
7165 else
7166 te = got_tree_entry_get_prev(s->tree, te);
7169 if (s->matched_entry) {
7170 s->first_displayed_entry = s->matched_entry;
7171 s->selected = 0;
7174 return NULL;
7177 static const struct got_error *
7178 show_tree_view(struct tog_view *view)
7180 const struct got_error *err = NULL;
7181 struct tog_tree_view_state *s = &view->state.tree;
7182 char *parent_path;
7184 err = tree_entry_path(&parent_path, &s->parents, NULL);
7185 if (err)
7186 return err;
7188 err = draw_tree_entries(view, parent_path);
7189 free(parent_path);
7191 view_border(view);
7192 return err;
7195 static const struct got_error *
7196 tree_goto_line(struct tog_view *view, int nlines)
7198 const struct got_error *err = NULL;
7199 struct tog_tree_view_state *s = &view->state.tree;
7200 struct got_tree_entry **fte, **lte, **ste;
7201 int g, last, first = 1, i = 1;
7202 int root = s->tree == s->root;
7203 int off = root ? 1 : 2;
7205 g = view->gline;
7206 view->gline = 0;
7208 if (g == 0)
7209 g = 1;
7210 else if (g > got_object_tree_get_nentries(s->tree))
7211 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7213 fte = &s->first_displayed_entry;
7214 lte = &s->last_displayed_entry;
7215 ste = &s->selected_entry;
7217 if (*fte != NULL) {
7218 first = got_tree_entry_get_index(*fte);
7219 first += off; /* account for ".." */
7221 last = got_tree_entry_get_index(*lte);
7222 last += off;
7224 if (g >= first && g <= last && g - first < nlines) {
7225 s->selected = g - first;
7226 return NULL; /* gline is on the current page */
7229 if (*ste != NULL) {
7230 i = got_tree_entry_get_index(*ste);
7231 i += off;
7234 if (i < g) {
7235 err = tree_scroll_down(view, g - i);
7236 if (err)
7237 return err;
7238 if (got_tree_entry_get_index(*lte) >=
7239 got_object_tree_get_nentries(s->tree) - 1 &&
7240 first + s->selected < g &&
7241 s->selected < s->ndisplayed - 1) {
7242 first = got_tree_entry_get_index(*fte);
7243 first += off;
7244 s->selected = g - first;
7246 } else if (i > g)
7247 tree_scroll_up(s, i - g);
7249 if (g < nlines &&
7250 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7251 s->selected = g - 1;
7253 return NULL;
7256 static const struct got_error *
7257 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7259 const struct got_error *err = NULL;
7260 struct tog_tree_view_state *s = &view->state.tree;
7261 struct got_tree_entry *te;
7262 int n, nscroll = view->nlines - 3;
7264 if (view->gline)
7265 return tree_goto_line(view, nscroll);
7267 switch (ch) {
7268 case 'i':
7269 s->show_ids = !s->show_ids;
7270 view->count = 0;
7271 break;
7272 case 'L':
7273 view->count = 0;
7274 if (!s->selected_entry)
7275 break;
7276 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7277 break;
7278 case 'R':
7279 view->count = 0;
7280 err = view_request_new(new_view, view, TOG_VIEW_REF);
7281 break;
7282 case 'g':
7283 case KEY_HOME:
7284 s->selected = 0;
7285 view->count = 0;
7286 if (s->tree == s->root)
7287 s->first_displayed_entry =
7288 got_object_tree_get_first_entry(s->tree);
7289 else
7290 s->first_displayed_entry = NULL;
7291 break;
7292 case 'G':
7293 case KEY_END: {
7294 int eos = view->nlines - 3;
7296 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7297 --eos; /* border */
7298 s->selected = 0;
7299 view->count = 0;
7300 te = got_object_tree_get_last_entry(s->tree);
7301 for (n = 0; n < eos; n++) {
7302 if (te == NULL) {
7303 if (s->tree != s->root) {
7304 s->first_displayed_entry = NULL;
7305 n++;
7307 break;
7309 s->first_displayed_entry = te;
7310 te = got_tree_entry_get_prev(s->tree, te);
7312 if (n > 0)
7313 s->selected = n - 1;
7314 break;
7316 case 'k':
7317 case KEY_UP:
7318 case CTRL('p'):
7319 if (s->selected > 0) {
7320 s->selected--;
7321 break;
7323 tree_scroll_up(s, 1);
7324 if (s->selected_entry == NULL ||
7325 (s->tree == s->root && s->selected_entry ==
7326 got_object_tree_get_first_entry(s->tree)))
7327 view->count = 0;
7328 break;
7329 case CTRL('u'):
7330 case 'u':
7331 nscroll /= 2;
7332 /* FALL THROUGH */
7333 case KEY_PPAGE:
7334 case CTRL('b'):
7335 case 'b':
7336 if (s->tree == s->root) {
7337 if (got_object_tree_get_first_entry(s->tree) ==
7338 s->first_displayed_entry)
7339 s->selected -= MIN(s->selected, nscroll);
7340 } else {
7341 if (s->first_displayed_entry == NULL)
7342 s->selected -= MIN(s->selected, nscroll);
7344 tree_scroll_up(s, MAX(0, nscroll));
7345 if (s->selected_entry == NULL ||
7346 (s->tree == s->root && s->selected_entry ==
7347 got_object_tree_get_first_entry(s->tree)))
7348 view->count = 0;
7349 break;
7350 case 'j':
7351 case KEY_DOWN:
7352 case CTRL('n'):
7353 if (s->selected < s->ndisplayed - 1) {
7354 s->selected++;
7355 break;
7357 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7358 == NULL) {
7359 /* can't scroll any further */
7360 view->count = 0;
7361 break;
7363 tree_scroll_down(view, 1);
7364 break;
7365 case CTRL('d'):
7366 case 'd':
7367 nscroll /= 2;
7368 /* FALL THROUGH */
7369 case KEY_NPAGE:
7370 case CTRL('f'):
7371 case 'f':
7372 case ' ':
7373 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7374 == NULL) {
7375 /* can't scroll any further; move cursor down */
7376 if (s->selected < s->ndisplayed - 1)
7377 s->selected += MIN(nscroll,
7378 s->ndisplayed - s->selected - 1);
7379 else
7380 view->count = 0;
7381 break;
7383 tree_scroll_down(view, nscroll);
7384 break;
7385 case KEY_ENTER:
7386 case '\r':
7387 case KEY_BACKSPACE:
7388 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7389 struct tog_parent_tree *parent;
7390 /* user selected '..' */
7391 if (s->tree == s->root) {
7392 view->count = 0;
7393 break;
7395 parent = TAILQ_FIRST(&s->parents);
7396 TAILQ_REMOVE(&s->parents, parent,
7397 entry);
7398 got_object_tree_close(s->tree);
7399 s->tree = parent->tree;
7400 s->first_displayed_entry =
7401 parent->first_displayed_entry;
7402 s->selected_entry =
7403 parent->selected_entry;
7404 s->selected = parent->selected;
7405 if (s->selected > view->nlines - 3) {
7406 err = offset_selection_down(view);
7407 if (err)
7408 break;
7410 free(parent);
7411 } else if (S_ISDIR(got_tree_entry_get_mode(
7412 s->selected_entry))) {
7413 struct got_tree_object *subtree;
7414 view->count = 0;
7415 err = got_object_open_as_tree(&subtree, s->repo,
7416 got_tree_entry_get_id(s->selected_entry));
7417 if (err)
7418 break;
7419 err = tree_view_visit_subtree(s, subtree);
7420 if (err) {
7421 got_object_tree_close(subtree);
7422 break;
7424 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7425 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7426 break;
7427 case KEY_RESIZE:
7428 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7429 s->selected = view->nlines - 4;
7430 view->count = 0;
7431 break;
7432 default:
7433 view->count = 0;
7434 break;
7437 return err;
7440 __dead static void
7441 usage_tree(void)
7443 endwin();
7444 fprintf(stderr,
7445 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7446 getprogname());
7447 exit(1);
7450 static const struct got_error *
7451 cmd_tree(int argc, char *argv[])
7453 const struct got_error *error;
7454 struct got_repository *repo = NULL;
7455 struct got_worktree *worktree = NULL;
7456 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7457 struct got_object_id *commit_id = NULL;
7458 struct got_commit_object *commit = NULL;
7459 const char *commit_id_arg = NULL;
7460 char *label = NULL;
7461 struct got_reference *ref = NULL;
7462 const char *head_ref_name = NULL;
7463 int ch;
7464 struct tog_view *view;
7465 int *pack_fds = NULL;
7467 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7468 switch (ch) {
7469 case 'c':
7470 commit_id_arg = optarg;
7471 break;
7472 case 'r':
7473 repo_path = realpath(optarg, NULL);
7474 if (repo_path == NULL)
7475 return got_error_from_errno2("realpath",
7476 optarg);
7477 break;
7478 default:
7479 usage_tree();
7480 /* NOTREACHED */
7484 argc -= optind;
7485 argv += optind;
7487 if (argc > 1)
7488 usage_tree();
7490 error = got_repo_pack_fds_open(&pack_fds);
7491 if (error != NULL)
7492 goto done;
7494 if (repo_path == NULL) {
7495 cwd = getcwd(NULL, 0);
7496 if (cwd == NULL)
7497 return got_error_from_errno("getcwd");
7498 error = got_worktree_open(&worktree, cwd);
7499 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7500 goto done;
7501 if (worktree)
7502 repo_path =
7503 strdup(got_worktree_get_repo_path(worktree));
7504 else
7505 repo_path = strdup(cwd);
7506 if (repo_path == NULL) {
7507 error = got_error_from_errno("strdup");
7508 goto done;
7512 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7513 if (error != NULL)
7514 goto done;
7516 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7517 repo, worktree);
7518 if (error)
7519 goto done;
7521 init_curses();
7523 error = apply_unveil(got_repo_get_path(repo), NULL);
7524 if (error)
7525 goto done;
7527 error = tog_load_refs(repo, 0);
7528 if (error)
7529 goto done;
7531 if (commit_id_arg == NULL) {
7532 error = got_repo_match_object_id(&commit_id, &label,
7533 worktree ? got_worktree_get_head_ref_name(worktree) :
7534 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7535 if (error)
7536 goto done;
7537 head_ref_name = label;
7538 } else {
7539 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7540 if (error == NULL)
7541 head_ref_name = got_ref_get_name(ref);
7542 else if (error->code != GOT_ERR_NOT_REF)
7543 goto done;
7544 error = got_repo_match_object_id(&commit_id, NULL,
7545 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7546 if (error)
7547 goto done;
7550 error = got_object_open_as_commit(&commit, repo, commit_id);
7551 if (error)
7552 goto done;
7554 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7555 if (view == NULL) {
7556 error = got_error_from_errno("view_open");
7557 goto done;
7559 error = open_tree_view(view, commit_id, head_ref_name, repo);
7560 if (error)
7561 goto done;
7562 if (!got_path_is_root_dir(in_repo_path)) {
7563 error = tree_view_walk_path(&view->state.tree, commit,
7564 in_repo_path);
7565 if (error)
7566 goto done;
7569 if (worktree) {
7570 /* Release work tree lock. */
7571 got_worktree_close(worktree);
7572 worktree = NULL;
7574 error = view_loop(view);
7575 done:
7576 free(repo_path);
7577 free(cwd);
7578 free(commit_id);
7579 free(label);
7580 if (ref)
7581 got_ref_close(ref);
7582 if (repo) {
7583 const struct got_error *close_err = got_repo_close(repo);
7584 if (error == NULL)
7585 error = close_err;
7587 if (pack_fds) {
7588 const struct got_error *pack_err =
7589 got_repo_pack_fds_close(pack_fds);
7590 if (error == NULL)
7591 error = pack_err;
7593 tog_free_refs();
7594 return error;
7597 static const struct got_error *
7598 ref_view_load_refs(struct tog_ref_view_state *s)
7600 struct got_reflist_entry *sre;
7601 struct tog_reflist_entry *re;
7603 s->nrefs = 0;
7604 TAILQ_FOREACH(sre, &tog_refs, entry) {
7605 if (strncmp(got_ref_get_name(sre->ref),
7606 "refs/got/", 9) == 0 &&
7607 strncmp(got_ref_get_name(sre->ref),
7608 "refs/got/backup/", 16) != 0)
7609 continue;
7611 re = malloc(sizeof(*re));
7612 if (re == NULL)
7613 return got_error_from_errno("malloc");
7615 re->ref = got_ref_dup(sre->ref);
7616 if (re->ref == NULL)
7617 return got_error_from_errno("got_ref_dup");
7618 re->idx = s->nrefs++;
7619 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7622 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7623 return NULL;
7626 static void
7627 ref_view_free_refs(struct tog_ref_view_state *s)
7629 struct tog_reflist_entry *re;
7631 while (!TAILQ_EMPTY(&s->refs)) {
7632 re = TAILQ_FIRST(&s->refs);
7633 TAILQ_REMOVE(&s->refs, re, entry);
7634 got_ref_close(re->ref);
7635 free(re);
7639 static const struct got_error *
7640 open_ref_view(struct tog_view *view, struct got_repository *repo)
7642 const struct got_error *err = NULL;
7643 struct tog_ref_view_state *s = &view->state.ref;
7645 s->selected_entry = 0;
7646 s->repo = repo;
7648 TAILQ_INIT(&s->refs);
7649 STAILQ_INIT(&s->colors);
7651 err = ref_view_load_refs(s);
7652 if (err)
7653 return err;
7655 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7656 err = add_color(&s->colors, "^refs/heads/",
7657 TOG_COLOR_REFS_HEADS,
7658 get_color_value("TOG_COLOR_REFS_HEADS"));
7659 if (err)
7660 goto done;
7662 err = add_color(&s->colors, "^refs/tags/",
7663 TOG_COLOR_REFS_TAGS,
7664 get_color_value("TOG_COLOR_REFS_TAGS"));
7665 if (err)
7666 goto done;
7668 err = add_color(&s->colors, "^refs/remotes/",
7669 TOG_COLOR_REFS_REMOTES,
7670 get_color_value("TOG_COLOR_REFS_REMOTES"));
7671 if (err)
7672 goto done;
7674 err = add_color(&s->colors, "^refs/got/backup/",
7675 TOG_COLOR_REFS_BACKUP,
7676 get_color_value("TOG_COLOR_REFS_BACKUP"));
7677 if (err)
7678 goto done;
7681 view->show = show_ref_view;
7682 view->input = input_ref_view;
7683 view->close = close_ref_view;
7684 view->search_start = search_start_ref_view;
7685 view->search_next = search_next_ref_view;
7686 done:
7687 if (err)
7688 free_colors(&s->colors);
7689 return err;
7692 static const struct got_error *
7693 close_ref_view(struct tog_view *view)
7695 struct tog_ref_view_state *s = &view->state.ref;
7697 ref_view_free_refs(s);
7698 free_colors(&s->colors);
7700 return NULL;
7703 static const struct got_error *
7704 resolve_reflist_entry(struct got_object_id **commit_id,
7705 struct tog_reflist_entry *re, struct got_repository *repo)
7707 const struct got_error *err = NULL;
7708 struct got_object_id *obj_id;
7709 struct got_tag_object *tag = NULL;
7710 int obj_type;
7712 *commit_id = NULL;
7714 err = got_ref_resolve(&obj_id, repo, re->ref);
7715 if (err)
7716 return err;
7718 err = got_object_get_type(&obj_type, repo, obj_id);
7719 if (err)
7720 goto done;
7722 switch (obj_type) {
7723 case GOT_OBJ_TYPE_COMMIT:
7724 *commit_id = obj_id;
7725 break;
7726 case GOT_OBJ_TYPE_TAG:
7727 err = got_object_open_as_tag(&tag, repo, obj_id);
7728 if (err)
7729 goto done;
7730 free(obj_id);
7731 err = got_object_get_type(&obj_type, repo,
7732 got_object_tag_get_object_id(tag));
7733 if (err)
7734 goto done;
7735 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7736 err = got_error(GOT_ERR_OBJ_TYPE);
7737 goto done;
7739 *commit_id = got_object_id_dup(
7740 got_object_tag_get_object_id(tag));
7741 if (*commit_id == NULL) {
7742 err = got_error_from_errno("got_object_id_dup");
7743 goto done;
7745 break;
7746 default:
7747 err = got_error(GOT_ERR_OBJ_TYPE);
7748 break;
7751 done:
7752 if (tag)
7753 got_object_tag_close(tag);
7754 if (err) {
7755 free(*commit_id);
7756 *commit_id = NULL;
7758 return err;
7761 static const struct got_error *
7762 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7763 struct tog_reflist_entry *re, struct got_repository *repo)
7765 struct tog_view *log_view;
7766 const struct got_error *err = NULL;
7767 struct got_object_id *commit_id = NULL;
7769 *new_view = NULL;
7771 err = resolve_reflist_entry(&commit_id, re, repo);
7772 if (err) {
7773 if (err->code != GOT_ERR_OBJ_TYPE)
7774 return err;
7775 else
7776 return NULL;
7779 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7780 if (log_view == NULL) {
7781 err = got_error_from_errno("view_open");
7782 goto done;
7785 err = open_log_view(log_view, commit_id, repo,
7786 got_ref_get_name(re->ref), "", 0);
7787 done:
7788 if (err)
7789 view_close(log_view);
7790 else
7791 *new_view = log_view;
7792 free(commit_id);
7793 return err;
7796 static void
7797 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7799 struct tog_reflist_entry *re;
7800 int i = 0;
7802 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7803 return;
7805 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7806 while (i++ < maxscroll) {
7807 if (re == NULL)
7808 break;
7809 s->first_displayed_entry = re;
7810 re = TAILQ_PREV(re, tog_reflist_head, entry);
7814 static const struct got_error *
7815 ref_scroll_down(struct tog_view *view, int maxscroll)
7817 struct tog_ref_view_state *s = &view->state.ref;
7818 struct tog_reflist_entry *next, *last;
7819 int n = 0;
7821 if (s->first_displayed_entry)
7822 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7823 else
7824 next = TAILQ_FIRST(&s->refs);
7826 last = s->last_displayed_entry;
7827 while (next && n++ < maxscroll) {
7828 if (last) {
7829 s->last_displayed_entry = last;
7830 last = TAILQ_NEXT(last, entry);
7832 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7833 s->first_displayed_entry = next;
7834 next = TAILQ_NEXT(next, entry);
7838 return NULL;
7841 static const struct got_error *
7842 search_start_ref_view(struct tog_view *view)
7844 struct tog_ref_view_state *s = &view->state.ref;
7846 s->matched_entry = NULL;
7847 return NULL;
7850 static int
7851 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7853 regmatch_t regmatch;
7855 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7856 0) == 0;
7859 static const struct got_error *
7860 search_next_ref_view(struct tog_view *view)
7862 struct tog_ref_view_state *s = &view->state.ref;
7863 struct tog_reflist_entry *re = NULL;
7865 if (!view->searching) {
7866 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7867 return NULL;
7870 if (s->matched_entry) {
7871 if (view->searching == TOG_SEARCH_FORWARD) {
7872 if (s->selected_entry)
7873 re = TAILQ_NEXT(s->selected_entry, entry);
7874 else
7875 re = TAILQ_PREV(s->selected_entry,
7876 tog_reflist_head, entry);
7877 } else {
7878 if (s->selected_entry == NULL)
7879 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7880 else
7881 re = TAILQ_PREV(s->selected_entry,
7882 tog_reflist_head, entry);
7884 } else {
7885 if (s->selected_entry)
7886 re = s->selected_entry;
7887 else if (view->searching == TOG_SEARCH_FORWARD)
7888 re = TAILQ_FIRST(&s->refs);
7889 else
7890 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7893 while (1) {
7894 if (re == NULL) {
7895 if (s->matched_entry == NULL) {
7896 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7897 return NULL;
7899 if (view->searching == TOG_SEARCH_FORWARD)
7900 re = TAILQ_FIRST(&s->refs);
7901 else
7902 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7905 if (match_reflist_entry(re, &view->regex)) {
7906 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7907 s->matched_entry = re;
7908 break;
7911 if (view->searching == TOG_SEARCH_FORWARD)
7912 re = TAILQ_NEXT(re, entry);
7913 else
7914 re = TAILQ_PREV(re, tog_reflist_head, entry);
7917 if (s->matched_entry) {
7918 s->first_displayed_entry = s->matched_entry;
7919 s->selected = 0;
7922 return NULL;
7925 static const struct got_error *
7926 show_ref_view(struct tog_view *view)
7928 const struct got_error *err = NULL;
7929 struct tog_ref_view_state *s = &view->state.ref;
7930 struct tog_reflist_entry *re;
7931 char *line = NULL;
7932 wchar_t *wline;
7933 struct tog_color *tc;
7934 int width, n;
7935 int limit = view->nlines;
7937 werase(view->window);
7939 s->ndisplayed = 0;
7940 if (view_is_hsplit_top(view))
7941 --limit; /* border */
7943 if (limit == 0)
7944 return NULL;
7946 re = s->first_displayed_entry;
7948 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7949 s->nrefs) == -1)
7950 return got_error_from_errno("asprintf");
7952 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7953 if (err) {
7954 free(line);
7955 return err;
7957 if (view_needs_focus_indication(view))
7958 wstandout(view->window);
7959 waddwstr(view->window, wline);
7960 while (width++ < view->ncols)
7961 waddch(view->window, ' ');
7962 if (view_needs_focus_indication(view))
7963 wstandend(view->window);
7964 free(wline);
7965 wline = NULL;
7966 free(line);
7967 line = NULL;
7968 if (--limit <= 0)
7969 return NULL;
7971 n = 0;
7972 while (re && limit > 0) {
7973 char *line = NULL;
7974 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7976 if (s->show_date) {
7977 struct got_commit_object *ci;
7978 struct got_tag_object *tag;
7979 struct got_object_id *id;
7980 struct tm tm;
7981 time_t t;
7983 err = got_ref_resolve(&id, s->repo, re->ref);
7984 if (err)
7985 return err;
7986 err = got_object_open_as_tag(&tag, s->repo, id);
7987 if (err) {
7988 if (err->code != GOT_ERR_OBJ_TYPE) {
7989 free(id);
7990 return err;
7992 err = got_object_open_as_commit(&ci, s->repo,
7993 id);
7994 if (err) {
7995 free(id);
7996 return err;
7998 t = got_object_commit_get_committer_time(ci);
7999 got_object_commit_close(ci);
8000 } else {
8001 t = got_object_tag_get_tagger_time(tag);
8002 got_object_tag_close(tag);
8004 free(id);
8005 if (gmtime_r(&t, &tm) == NULL)
8006 return got_error_from_errno("gmtime_r");
8007 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8008 return got_error(GOT_ERR_NO_SPACE);
8010 if (got_ref_is_symbolic(re->ref)) {
8011 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8012 ymd : "", got_ref_get_name(re->ref),
8013 got_ref_get_symref_target(re->ref)) == -1)
8014 return got_error_from_errno("asprintf");
8015 } else if (s->show_ids) {
8016 struct got_object_id *id;
8017 char *id_str;
8018 err = got_ref_resolve(&id, s->repo, re->ref);
8019 if (err)
8020 return err;
8021 err = got_object_id_str(&id_str, id);
8022 if (err) {
8023 free(id);
8024 return err;
8026 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8027 got_ref_get_name(re->ref), id_str) == -1) {
8028 err = got_error_from_errno("asprintf");
8029 free(id);
8030 free(id_str);
8031 return err;
8033 free(id);
8034 free(id_str);
8035 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8036 got_ref_get_name(re->ref)) == -1)
8037 return got_error_from_errno("asprintf");
8039 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
8040 0, 0);
8041 if (err) {
8042 free(line);
8043 return err;
8045 if (n == s->selected) {
8046 if (view->focussed)
8047 wstandout(view->window);
8048 s->selected_entry = re;
8050 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8051 if (tc)
8052 wattr_on(view->window,
8053 COLOR_PAIR(tc->colorpair), NULL);
8054 waddwstr(view->window, wline);
8055 if (tc)
8056 wattr_off(view->window,
8057 COLOR_PAIR(tc->colorpair), NULL);
8058 if (width < view->ncols - 1)
8059 waddch(view->window, '\n');
8060 if (n == s->selected && view->focussed)
8061 wstandend(view->window);
8062 free(line);
8063 free(wline);
8064 wline = NULL;
8065 n++;
8066 s->ndisplayed++;
8067 s->last_displayed_entry = re;
8069 limit--;
8070 re = TAILQ_NEXT(re, entry);
8073 view_border(view);
8074 return err;
8077 static const struct got_error *
8078 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8079 struct tog_reflist_entry *re, struct got_repository *repo)
8081 const struct got_error *err = NULL;
8082 struct got_object_id *commit_id = NULL;
8083 struct tog_view *tree_view;
8085 *new_view = NULL;
8087 err = resolve_reflist_entry(&commit_id, re, repo);
8088 if (err) {
8089 if (err->code != GOT_ERR_OBJ_TYPE)
8090 return err;
8091 else
8092 return NULL;
8096 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8097 if (tree_view == NULL) {
8098 err = got_error_from_errno("view_open");
8099 goto done;
8102 err = open_tree_view(tree_view, commit_id,
8103 got_ref_get_name(re->ref), repo);
8104 if (err)
8105 goto done;
8107 *new_view = tree_view;
8108 done:
8109 free(commit_id);
8110 return err;
8113 static const struct got_error *
8114 ref_goto_line(struct tog_view *view, int nlines)
8116 const struct got_error *err = NULL;
8117 struct tog_ref_view_state *s = &view->state.ref;
8118 int g, idx = s->selected_entry->idx;
8120 g = view->gline;
8121 view->gline = 0;
8123 if (g == 0)
8124 g = 1;
8125 else if (g > s->nrefs)
8126 g = s->nrefs;
8128 if (g >= s->first_displayed_entry->idx + 1 &&
8129 g <= s->last_displayed_entry->idx + 1 &&
8130 g - s->first_displayed_entry->idx - 1 < nlines) {
8131 s->selected = g - s->first_displayed_entry->idx - 1;
8132 return NULL;
8135 if (idx + 1 < g) {
8136 err = ref_scroll_down(view, g - idx - 1);
8137 if (err)
8138 return err;
8139 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8140 s->first_displayed_entry->idx + s->selected < g &&
8141 s->selected < s->ndisplayed - 1)
8142 s->selected = g - s->first_displayed_entry->idx - 1;
8143 } else if (idx + 1 > g)
8144 ref_scroll_up(s, idx - g + 1);
8146 if (g < nlines && s->first_displayed_entry->idx == 0)
8147 s->selected = g - 1;
8149 return NULL;
8153 static const struct got_error *
8154 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8156 const struct got_error *err = NULL;
8157 struct tog_ref_view_state *s = &view->state.ref;
8158 struct tog_reflist_entry *re;
8159 int n, nscroll = view->nlines - 1;
8161 if (view->gline)
8162 return ref_goto_line(view, nscroll);
8164 switch (ch) {
8165 case 'i':
8166 s->show_ids = !s->show_ids;
8167 view->count = 0;
8168 break;
8169 case 'm':
8170 s->show_date = !s->show_date;
8171 view->count = 0;
8172 break;
8173 case 'o':
8174 s->sort_by_date = !s->sort_by_date;
8175 view->count = 0;
8176 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8177 got_ref_cmp_by_commit_timestamp_descending :
8178 tog_ref_cmp_by_name, s->repo);
8179 if (err)
8180 break;
8181 got_reflist_object_id_map_free(tog_refs_idmap);
8182 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8183 &tog_refs, s->repo);
8184 if (err)
8185 break;
8186 ref_view_free_refs(s);
8187 err = ref_view_load_refs(s);
8188 break;
8189 case KEY_ENTER:
8190 case '\r':
8191 view->count = 0;
8192 if (!s->selected_entry)
8193 break;
8194 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8195 break;
8196 case 'T':
8197 view->count = 0;
8198 if (!s->selected_entry)
8199 break;
8200 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8201 break;
8202 case 'g':
8203 case KEY_HOME:
8204 s->selected = 0;
8205 view->count = 0;
8206 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8207 break;
8208 case 'G':
8209 case KEY_END: {
8210 int eos = view->nlines - 1;
8212 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8213 --eos; /* border */
8214 s->selected = 0;
8215 view->count = 0;
8216 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8217 for (n = 0; n < eos; n++) {
8218 if (re == NULL)
8219 break;
8220 s->first_displayed_entry = re;
8221 re = TAILQ_PREV(re, tog_reflist_head, entry);
8223 if (n > 0)
8224 s->selected = n - 1;
8225 break;
8227 case 'k':
8228 case KEY_UP:
8229 case CTRL('p'):
8230 if (s->selected > 0) {
8231 s->selected--;
8232 break;
8234 ref_scroll_up(s, 1);
8235 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8236 view->count = 0;
8237 break;
8238 case CTRL('u'):
8239 case 'u':
8240 nscroll /= 2;
8241 /* FALL THROUGH */
8242 case KEY_PPAGE:
8243 case CTRL('b'):
8244 case 'b':
8245 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8246 s->selected -= MIN(nscroll, s->selected);
8247 ref_scroll_up(s, MAX(0, nscroll));
8248 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8249 view->count = 0;
8250 break;
8251 case 'j':
8252 case KEY_DOWN:
8253 case CTRL('n'):
8254 if (s->selected < s->ndisplayed - 1) {
8255 s->selected++;
8256 break;
8258 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8259 /* can't scroll any further */
8260 view->count = 0;
8261 break;
8263 ref_scroll_down(view, 1);
8264 break;
8265 case CTRL('d'):
8266 case 'd':
8267 nscroll /= 2;
8268 /* FALL THROUGH */
8269 case KEY_NPAGE:
8270 case CTRL('f'):
8271 case 'f':
8272 case ' ':
8273 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8274 /* can't scroll any further; move cursor down */
8275 if (s->selected < s->ndisplayed - 1)
8276 s->selected += MIN(nscroll,
8277 s->ndisplayed - s->selected - 1);
8278 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8279 s->selected += s->ndisplayed - s->selected - 1;
8280 view->count = 0;
8281 break;
8283 ref_scroll_down(view, nscroll);
8284 break;
8285 case CTRL('l'):
8286 view->count = 0;
8287 tog_free_refs();
8288 err = tog_load_refs(s->repo, s->sort_by_date);
8289 if (err)
8290 break;
8291 ref_view_free_refs(s);
8292 err = ref_view_load_refs(s);
8293 break;
8294 case KEY_RESIZE:
8295 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8296 s->selected = view->nlines - 2;
8297 break;
8298 default:
8299 view->count = 0;
8300 break;
8303 return err;
8306 __dead static void
8307 usage_ref(void)
8309 endwin();
8310 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8311 getprogname());
8312 exit(1);
8315 static const struct got_error *
8316 cmd_ref(int argc, char *argv[])
8318 const struct got_error *error;
8319 struct got_repository *repo = NULL;
8320 struct got_worktree *worktree = NULL;
8321 char *cwd = NULL, *repo_path = NULL;
8322 int ch;
8323 struct tog_view *view;
8324 int *pack_fds = NULL;
8326 while ((ch = getopt(argc, argv, "r:")) != -1) {
8327 switch (ch) {
8328 case 'r':
8329 repo_path = realpath(optarg, NULL);
8330 if (repo_path == NULL)
8331 return got_error_from_errno2("realpath",
8332 optarg);
8333 break;
8334 default:
8335 usage_ref();
8336 /* NOTREACHED */
8340 argc -= optind;
8341 argv += optind;
8343 if (argc > 1)
8344 usage_ref();
8346 error = got_repo_pack_fds_open(&pack_fds);
8347 if (error != NULL)
8348 goto done;
8350 if (repo_path == NULL) {
8351 cwd = getcwd(NULL, 0);
8352 if (cwd == NULL)
8353 return got_error_from_errno("getcwd");
8354 error = got_worktree_open(&worktree, cwd);
8355 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8356 goto done;
8357 if (worktree)
8358 repo_path =
8359 strdup(got_worktree_get_repo_path(worktree));
8360 else
8361 repo_path = strdup(cwd);
8362 if (repo_path == NULL) {
8363 error = got_error_from_errno("strdup");
8364 goto done;
8368 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8369 if (error != NULL)
8370 goto done;
8372 init_curses();
8374 error = apply_unveil(got_repo_get_path(repo), NULL);
8375 if (error)
8376 goto done;
8378 error = tog_load_refs(repo, 0);
8379 if (error)
8380 goto done;
8382 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8383 if (view == NULL) {
8384 error = got_error_from_errno("view_open");
8385 goto done;
8388 error = open_ref_view(view, repo);
8389 if (error)
8390 goto done;
8392 if (worktree) {
8393 /* Release work tree lock. */
8394 got_worktree_close(worktree);
8395 worktree = NULL;
8397 error = view_loop(view);
8398 done:
8399 free(repo_path);
8400 free(cwd);
8401 if (repo) {
8402 const struct got_error *close_err = got_repo_close(repo);
8403 if (close_err)
8404 error = close_err;
8406 if (pack_fds) {
8407 const struct got_error *pack_err =
8408 got_repo_pack_fds_close(pack_fds);
8409 if (error == NULL)
8410 error = pack_err;
8412 tog_free_refs();
8413 return error;
8416 static const struct got_error*
8417 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8418 const char *str)
8420 size_t len;
8422 if (win == NULL)
8423 win = stdscr;
8425 len = strlen(str);
8426 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8428 if (focus)
8429 wstandout(win);
8430 if (mvwprintw(win, y, x, "%s", str) == ERR)
8431 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8432 if (focus)
8433 wstandend(win);
8435 return NULL;
8438 static const struct got_error *
8439 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8441 off_t *p;
8443 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8444 if (p == NULL) {
8445 free(*line_offsets);
8446 *line_offsets = NULL;
8447 return got_error_from_errno("reallocarray");
8450 *line_offsets = p;
8451 (*line_offsets)[*nlines] = off;
8452 ++(*nlines);
8453 return NULL;
8456 static const struct got_error *
8457 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8459 *ret = 0;
8461 for (;n > 0; --n, ++km) {
8462 char *t0, *t, *k;
8463 size_t len = 1;
8465 if (km->keys == NULL)
8466 continue;
8468 t = t0 = strdup(km->keys);
8469 if (t0 == NULL)
8470 return got_error_from_errno("strdup");
8472 len += strlen(t);
8473 while ((k = strsep(&t, " ")) != NULL)
8474 len += strlen(k) > 1 ? 2 : 0;
8475 free(t0);
8476 *ret = MAX(*ret, len);
8479 return NULL;
8483 * Write keymap section headers, keys, and key info in km to f.
8484 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8485 * wrap control and symbolic keys in guillemets, else use <>.
8487 static const struct got_error *
8488 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8490 int n, len = width;
8492 if (km->keys) {
8493 static const char *u8_glyph[] = {
8494 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8495 "\xe2\x80\xba" /* U+203A (utf8 >) */
8497 char *t0, *t, *k;
8498 int cs, s, first = 1;
8500 cs = got_locale_is_utf8();
8502 t = t0 = strdup(km->keys);
8503 if (t0 == NULL)
8504 return got_error_from_errno("strdup");
8506 len = strlen(km->keys);
8507 while ((k = strsep(&t, " ")) != NULL) {
8508 s = strlen(k) > 1; /* control or symbolic key */
8509 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8510 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8511 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8512 if (n < 0) {
8513 free(t0);
8514 return got_error_from_errno("fprintf");
8516 first = 0;
8517 len += s ? 2 : 0;
8518 *off += n;
8520 free(t0);
8522 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8523 if (n < 0)
8524 return got_error_from_errno("fprintf");
8525 *off += n;
8527 return NULL;
8530 static const struct got_error *
8531 format_help(struct tog_help_view_state *s)
8533 const struct got_error *err = NULL;
8534 off_t off = 0;
8535 int i, max, n, show = s->all;
8536 static const struct tog_key_map km[] = {
8537 #define KEYMAP_(info, type) { NULL, (info), type }
8538 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8539 GENERATE_HELP
8540 #undef KEYMAP_
8541 #undef KEY_
8544 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8545 if (err)
8546 return err;
8548 n = nitems(km);
8549 err = max_key_str(&max, km, n);
8550 if (err)
8551 return err;
8553 for (i = 0; i < n; ++i) {
8554 if (km[i].keys == NULL) {
8555 show = s->all;
8556 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8557 km[i].type == s->type || s->all)
8558 show = 1;
8560 if (show) {
8561 err = format_help_line(&off, s->f, &km[i], max);
8562 if (err)
8563 return err;
8564 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8565 if (err)
8566 return err;
8569 fputc('\n', s->f);
8570 ++off;
8571 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8572 return err;
8575 static const struct got_error *
8576 create_help(struct tog_help_view_state *s)
8578 FILE *f;
8579 const struct got_error *err;
8581 free(s->line_offsets);
8582 s->line_offsets = NULL;
8583 s->nlines = 0;
8585 f = got_opentemp();
8586 if (f == NULL)
8587 return got_error_from_errno("got_opentemp");
8588 s->f = f;
8590 err = format_help(s);
8591 if (err)
8592 return err;
8594 if (s->f && fflush(s->f) != 0)
8595 return got_error_from_errno("fflush");
8597 return NULL;
8600 static const struct got_error *
8601 search_start_help_view(struct tog_view *view)
8603 view->state.help.matched_line = 0;
8604 return NULL;
8607 static void
8608 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8609 size_t *nlines, int **first, int **last, int **match, int **selected)
8611 struct tog_help_view_state *s = &view->state.help;
8613 *f = s->f;
8614 *nlines = s->nlines;
8615 *line_offsets = s->line_offsets;
8616 *match = &s->matched_line;
8617 *first = &s->first_displayed_line;
8618 *last = &s->last_displayed_line;
8619 *selected = &s->selected_line;
8622 static const struct got_error *
8623 show_help_view(struct tog_view *view)
8625 struct tog_help_view_state *s = &view->state.help;
8626 const struct got_error *err;
8627 regmatch_t *regmatch = &view->regmatch;
8628 wchar_t *wline;
8629 char *line;
8630 ssize_t linelen;
8631 size_t linesz = 0;
8632 int width, nprinted = 0, rc = 0;
8633 int eos = view->nlines;
8635 if (view_is_hsplit_top(view))
8636 --eos; /* account for border */
8638 s->lineno = 0;
8639 rewind(s->f);
8640 werase(view->window);
8642 if (view->gline > s->nlines - 1)
8643 view->gline = s->nlines - 1;
8645 err = win_draw_center(view->window, 0, 0, view->ncols,
8646 view_needs_focus_indication(view),
8647 "tog help (press q to return to tog)");
8648 if (err)
8649 return err;
8650 if (eos <= 1)
8651 return NULL;
8652 waddstr(view->window, "\n\n");
8653 eos -= 2;
8655 s->eof = 0;
8656 view->maxx = 0;
8657 line = NULL;
8658 while (eos > 0 && nprinted < eos) {
8659 attr_t attr = 0;
8661 linelen = getline(&line, &linesz, s->f);
8662 if (linelen == -1) {
8663 if (!feof(s->f)) {
8664 free(line);
8665 return got_ferror(s->f, GOT_ERR_IO);
8667 s->eof = 1;
8668 break;
8670 if (++s->lineno < s->first_displayed_line)
8671 continue;
8672 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8673 continue;
8674 if (s->lineno == view->hiline)
8675 attr = A_STANDOUT;
8677 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8678 view->x ? 1 : 0);
8679 if (err) {
8680 free(line);
8681 return err;
8683 view->maxx = MAX(view->maxx, width);
8684 free(wline);
8685 wline = NULL;
8687 if (attr)
8688 wattron(view->window, attr);
8689 if (s->first_displayed_line + nprinted == s->matched_line &&
8690 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8691 err = add_matched_line(&width, line, view->ncols - 1, 0,
8692 view->window, view->x, regmatch);
8693 if (err) {
8694 free(line);
8695 return err;
8697 } else {
8698 int skip;
8700 err = format_line(&wline, &width, &skip, line,
8701 view->x, view->ncols - 1, 0, view->x ? 1 : 0);
8702 if (err) {
8703 free(line);
8704 return err;
8706 rc = waddwstr(view->window, &wline[skip]);
8707 free(wline);
8708 wline = NULL;
8709 if (rc == ERR)
8710 return got_error_msg(GOT_ERR_IO, "waddwstr");
8712 if (s->lineno == view->hiline) {
8713 while (width++ < view->ncols)
8714 waddch(view->window, ' ');
8715 } else {
8716 if (width <= view->ncols)
8717 waddch(view->window, '\n');
8719 if (attr)
8720 wattroff(view->window, attr);
8721 if (++nprinted == 1)
8722 s->first_displayed_line = s->lineno;
8724 free(line);
8725 if (nprinted > 0)
8726 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8727 else
8728 s->last_displayed_line = s->first_displayed_line;
8730 view_border(view);
8732 if (s->eof) {
8733 rc = waddnstr(view->window,
8734 "See the tog(1) manual page for full documentation",
8735 view->ncols - 1);
8736 if (rc == ERR)
8737 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8738 } else {
8739 wmove(view->window, view->nlines - 1, 0);
8740 wclrtoeol(view->window);
8741 wstandout(view->window);
8742 rc = waddnstr(view->window, "scroll down for more...",
8743 view->ncols - 1);
8744 if (rc == ERR)
8745 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8746 if (getcurx(view->window) < view->ncols - 6) {
8747 rc = wprintw(view->window, "[%.0f%%]",
8748 100.00 * s->last_displayed_line / s->nlines);
8749 if (rc == ERR)
8750 return got_error_msg(GOT_ERR_IO, "wprintw");
8752 wstandend(view->window);
8755 return NULL;
8758 static const struct got_error *
8759 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8761 struct tog_help_view_state *s = &view->state.help;
8762 const struct got_error *err = NULL;
8763 char *line = NULL;
8764 ssize_t linelen;
8765 size_t linesz = 0;
8766 int eos, nscroll;
8768 eos = nscroll = view->nlines;
8769 if (view_is_hsplit_top(view))
8770 --eos; /* border */
8772 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8774 switch (ch) {
8775 case '0':
8776 view->x = 0;
8777 break;
8778 case '$':
8779 view->x = MAX(view->maxx - view->ncols / 3, 0);
8780 view->count = 0;
8781 break;
8782 case KEY_RIGHT:
8783 case 'l':
8784 if (view->x + view->ncols / 3 < view->maxx)
8785 view->x += 2;
8786 else
8787 view->count = 0;
8788 break;
8789 case KEY_LEFT:
8790 case 'h':
8791 view->x -= MIN(view->x, 2);
8792 if (view->x <= 0)
8793 view->count = 0;
8794 break;
8795 case 'g':
8796 case KEY_HOME:
8797 s->first_displayed_line = 1;
8798 view->count = 0;
8799 break;
8800 case 'G':
8801 case KEY_END:
8802 view->count = 0;
8803 if (s->eof)
8804 break;
8805 s->first_displayed_line = (s->nlines - eos) + 3;
8806 s->eof = 1;
8807 break;
8808 case 'k':
8809 case KEY_UP:
8810 if (s->first_displayed_line > 1)
8811 --s->first_displayed_line;
8812 else
8813 view->count = 0;
8814 break;
8815 case CTRL('u'):
8816 case 'u':
8817 nscroll /= 2;
8818 /* FALL THROUGH */
8819 case KEY_PPAGE:
8820 case CTRL('b'):
8821 case 'b':
8822 if (s->first_displayed_line == 1) {
8823 view->count = 0;
8824 break;
8826 while (--nscroll > 0 && s->first_displayed_line > 1)
8827 s->first_displayed_line--;
8828 break;
8829 case 'j':
8830 case KEY_DOWN:
8831 case CTRL('n'):
8832 if (!s->eof)
8833 ++s->first_displayed_line;
8834 else
8835 view->count = 0;
8836 break;
8837 case CTRL('d'):
8838 case 'd':
8839 nscroll /= 2;
8840 /* FALL THROUGH */
8841 case KEY_NPAGE:
8842 case CTRL('f'):
8843 case 'f':
8844 case ' ':
8845 if (s->eof) {
8846 view->count = 0;
8847 break;
8849 while (!s->eof && --nscroll > 0) {
8850 linelen = getline(&line, &linesz, s->f);
8851 s->first_displayed_line++;
8852 if (linelen == -1) {
8853 if (feof(s->f))
8854 s->eof = 1;
8855 else
8856 err = got_ferror(s->f, GOT_ERR_IO);
8857 break;
8860 free(line);
8861 break;
8862 default:
8863 view->count = 0;
8864 break;
8867 return err;
8870 static const struct got_error *
8871 close_help_view(struct tog_view *view)
8873 struct tog_help_view_state *s = &view->state.help;
8875 free(s->line_offsets);
8876 s->line_offsets = NULL;
8877 if (fclose(s->f) == EOF)
8878 return got_error_from_errno("fclose");
8880 return NULL;
8883 static const struct got_error *
8884 reset_help_view(struct tog_view *view)
8886 struct tog_help_view_state *s = &view->state.help;
8889 if (s->f && fclose(s->f) == EOF)
8890 return got_error_from_errno("fclose");
8892 wclear(view->window);
8893 view->count = 0;
8894 view->x = 0;
8895 s->all = !s->all;
8896 s->first_displayed_line = 1;
8897 s->last_displayed_line = view->nlines;
8898 s->matched_line = 0;
8900 return create_help(s);
8903 static const struct got_error *
8904 open_help_view(struct tog_view *view, struct tog_view *parent)
8906 const struct got_error *err = NULL;
8907 struct tog_help_view_state *s = &view->state.help;
8909 s->type = (enum tog_keymap_type)parent->type;
8910 s->first_displayed_line = 1;
8911 s->last_displayed_line = view->nlines;
8912 s->selected_line = 1;
8914 view->show = show_help_view;
8915 view->input = input_help_view;
8916 view->reset = reset_help_view;
8917 view->close = close_help_view;
8918 view->search_start = search_start_help_view;
8919 view->search_setup = search_setup_help_view;
8920 view->search_next = search_next_view_match;
8922 err = create_help(s);
8923 return err;
8926 static const struct got_error *
8927 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8928 enum tog_view_type request, int y, int x)
8930 const struct got_error *err = NULL;
8932 *new_view = NULL;
8934 switch (request) {
8935 case TOG_VIEW_DIFF:
8936 if (view->type == TOG_VIEW_LOG) {
8937 struct tog_log_view_state *s = &view->state.log;
8939 err = open_diff_view_for_commit(new_view, y, x,
8940 s->selected_entry->commit, s->selected_entry->id,
8941 view, s->repo);
8942 } else
8943 return got_error_msg(GOT_ERR_NOT_IMPL,
8944 "parent/child view pair not supported");
8945 break;
8946 case TOG_VIEW_BLAME:
8947 if (view->type == TOG_VIEW_TREE) {
8948 struct tog_tree_view_state *s = &view->state.tree;
8950 err = blame_tree_entry(new_view, y, x,
8951 s->selected_entry, &s->parents, s->commit_id,
8952 s->repo);
8953 } else
8954 return got_error_msg(GOT_ERR_NOT_IMPL,
8955 "parent/child view pair not supported");
8956 break;
8957 case TOG_VIEW_LOG:
8958 if (view->type == TOG_VIEW_BLAME)
8959 err = log_annotated_line(new_view, y, x,
8960 view->state.blame.repo, view->state.blame.id_to_log);
8961 else if (view->type == TOG_VIEW_TREE)
8962 err = log_selected_tree_entry(new_view, y, x,
8963 &view->state.tree);
8964 else if (view->type == TOG_VIEW_REF)
8965 err = log_ref_entry(new_view, y, x,
8966 view->state.ref.selected_entry,
8967 view->state.ref.repo);
8968 else
8969 return got_error_msg(GOT_ERR_NOT_IMPL,
8970 "parent/child view pair not supported");
8971 break;
8972 case TOG_VIEW_TREE:
8973 if (view->type == TOG_VIEW_LOG)
8974 err = browse_commit_tree(new_view, y, x,
8975 view->state.log.selected_entry,
8976 view->state.log.in_repo_path,
8977 view->state.log.head_ref_name,
8978 view->state.log.repo);
8979 else if (view->type == TOG_VIEW_REF)
8980 err = browse_ref_tree(new_view, y, x,
8981 view->state.ref.selected_entry,
8982 view->state.ref.repo);
8983 else
8984 return got_error_msg(GOT_ERR_NOT_IMPL,
8985 "parent/child view pair not supported");
8986 break;
8987 case TOG_VIEW_REF:
8988 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8989 if (*new_view == NULL)
8990 return got_error_from_errno("view_open");
8991 if (view->type == TOG_VIEW_LOG)
8992 err = open_ref_view(*new_view, view->state.log.repo);
8993 else if (view->type == TOG_VIEW_TREE)
8994 err = open_ref_view(*new_view, view->state.tree.repo);
8995 else
8996 err = got_error_msg(GOT_ERR_NOT_IMPL,
8997 "parent/child view pair not supported");
8998 if (err)
8999 view_close(*new_view);
9000 break;
9001 case TOG_VIEW_HELP:
9002 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9003 if (*new_view == NULL)
9004 return got_error_from_errno("view_open");
9005 err = open_help_view(*new_view, view);
9006 if (err)
9007 view_close(*new_view);
9008 break;
9009 default:
9010 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9013 return err;
9017 * If view was scrolled down to move the selected line into view when opening a
9018 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9020 static void
9021 offset_selection_up(struct tog_view *view)
9023 switch (view->type) {
9024 case TOG_VIEW_BLAME: {
9025 struct tog_blame_view_state *s = &view->state.blame;
9026 if (s->first_displayed_line == 1) {
9027 s->selected_line = MAX(s->selected_line - view->offset,
9028 1);
9029 break;
9031 if (s->first_displayed_line > view->offset)
9032 s->first_displayed_line -= view->offset;
9033 else
9034 s->first_displayed_line = 1;
9035 s->selected_line += view->offset;
9036 break;
9038 case TOG_VIEW_LOG:
9039 log_scroll_up(&view->state.log, view->offset);
9040 view->state.log.selected += view->offset;
9041 break;
9042 case TOG_VIEW_REF:
9043 ref_scroll_up(&view->state.ref, view->offset);
9044 view->state.ref.selected += view->offset;
9045 break;
9046 case TOG_VIEW_TREE:
9047 tree_scroll_up(&view->state.tree, view->offset);
9048 view->state.tree.selected += view->offset;
9049 break;
9050 default:
9051 break;
9054 view->offset = 0;
9058 * If the selected line is in the section of screen covered by the bottom split,
9059 * scroll down offset lines to move it into view and index its new position.
9061 static const struct got_error *
9062 offset_selection_down(struct tog_view *view)
9064 const struct got_error *err = NULL;
9065 const struct got_error *(*scrolld)(struct tog_view *, int);
9066 int *selected = NULL;
9067 int header, offset;
9069 switch (view->type) {
9070 case TOG_VIEW_BLAME: {
9071 struct tog_blame_view_state *s = &view->state.blame;
9072 header = 3;
9073 scrolld = NULL;
9074 if (s->selected_line > view->nlines - header) {
9075 offset = abs(view->nlines - s->selected_line - header);
9076 s->first_displayed_line += offset;
9077 s->selected_line -= offset;
9078 view->offset = offset;
9080 break;
9082 case TOG_VIEW_LOG: {
9083 struct tog_log_view_state *s = &view->state.log;
9084 scrolld = &log_scroll_down;
9085 header = view_is_parent_view(view) ? 3 : 2;
9086 selected = &s->selected;
9087 break;
9089 case TOG_VIEW_REF: {
9090 struct tog_ref_view_state *s = &view->state.ref;
9091 scrolld = &ref_scroll_down;
9092 header = 3;
9093 selected = &s->selected;
9094 break;
9096 case TOG_VIEW_TREE: {
9097 struct tog_tree_view_state *s = &view->state.tree;
9098 scrolld = &tree_scroll_down;
9099 header = 5;
9100 selected = &s->selected;
9101 break;
9103 default:
9104 selected = NULL;
9105 scrolld = NULL;
9106 header = 0;
9107 break;
9110 if (selected && *selected > view->nlines - header) {
9111 offset = abs(view->nlines - *selected - header);
9112 view->offset = offset;
9113 if (scrolld && offset) {
9114 err = scrolld(view, offset);
9115 *selected -= offset;
9119 return err;
9122 static void
9123 list_commands(FILE *fp)
9125 size_t i;
9127 fprintf(fp, "commands:");
9128 for (i = 0; i < nitems(tog_commands); i++) {
9129 const struct tog_cmd *cmd = &tog_commands[i];
9130 fprintf(fp, " %s", cmd->name);
9132 fputc('\n', fp);
9135 __dead static void
9136 usage(int hflag, int status)
9138 FILE *fp = (status == 0) ? stdout : stderr;
9140 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9141 getprogname());
9142 if (hflag) {
9143 fprintf(fp, "lazy usage: %s path\n", getprogname());
9144 list_commands(fp);
9146 exit(status);
9149 static char **
9150 make_argv(int argc, ...)
9152 va_list ap;
9153 char **argv;
9154 int i;
9156 va_start(ap, argc);
9158 argv = calloc(argc, sizeof(char *));
9159 if (argv == NULL)
9160 err(1, "calloc");
9161 for (i = 0; i < argc; i++) {
9162 argv[i] = strdup(va_arg(ap, char *));
9163 if (argv[i] == NULL)
9164 err(1, "strdup");
9167 va_end(ap);
9168 return argv;
9172 * Try to convert 'tog path' into a 'tog log path' command.
9173 * The user could simply have mistyped the command rather than knowingly
9174 * provided a path. So check whether argv[0] can in fact be resolved
9175 * to a path in the HEAD commit and print a special error if not.
9176 * This hack is for mpi@ <3
9178 static const struct got_error *
9179 tog_log_with_path(int argc, char *argv[])
9181 const struct got_error *error = NULL, *close_err;
9182 const struct tog_cmd *cmd = NULL;
9183 struct got_repository *repo = NULL;
9184 struct got_worktree *worktree = NULL;
9185 struct got_object_id *commit_id = NULL, *id = NULL;
9186 struct got_commit_object *commit = NULL;
9187 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9188 char *commit_id_str = NULL, **cmd_argv = NULL;
9189 int *pack_fds = NULL;
9191 cwd = getcwd(NULL, 0);
9192 if (cwd == NULL)
9193 return got_error_from_errno("getcwd");
9195 error = got_repo_pack_fds_open(&pack_fds);
9196 if (error != NULL)
9197 goto done;
9199 error = got_worktree_open(&worktree, cwd);
9200 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9201 goto done;
9203 if (worktree)
9204 repo_path = strdup(got_worktree_get_repo_path(worktree));
9205 else
9206 repo_path = strdup(cwd);
9207 if (repo_path == NULL) {
9208 error = got_error_from_errno("strdup");
9209 goto done;
9212 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9213 if (error != NULL)
9214 goto done;
9216 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9217 repo, worktree);
9218 if (error)
9219 goto done;
9221 error = tog_load_refs(repo, 0);
9222 if (error)
9223 goto done;
9224 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9225 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9226 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9227 if (error)
9228 goto done;
9230 if (worktree) {
9231 got_worktree_close(worktree);
9232 worktree = NULL;
9235 error = got_object_open_as_commit(&commit, repo, commit_id);
9236 if (error)
9237 goto done;
9239 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9240 if (error) {
9241 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9242 goto done;
9243 fprintf(stderr, "%s: '%s' is no known command or path\n",
9244 getprogname(), argv[0]);
9245 usage(1, 1);
9246 /* not reached */
9249 error = got_object_id_str(&commit_id_str, commit_id);
9250 if (error)
9251 goto done;
9253 cmd = &tog_commands[0]; /* log */
9254 argc = 4;
9255 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9256 error = cmd->cmd_main(argc, cmd_argv);
9257 done:
9258 if (repo) {
9259 close_err = got_repo_close(repo);
9260 if (error == NULL)
9261 error = close_err;
9263 if (commit)
9264 got_object_commit_close(commit);
9265 if (worktree)
9266 got_worktree_close(worktree);
9267 if (pack_fds) {
9268 const struct got_error *pack_err =
9269 got_repo_pack_fds_close(pack_fds);
9270 if (error == NULL)
9271 error = pack_err;
9273 free(id);
9274 free(commit_id_str);
9275 free(commit_id);
9276 free(cwd);
9277 free(repo_path);
9278 free(in_repo_path);
9279 if (cmd_argv) {
9280 int i;
9281 for (i = 0; i < argc; i++)
9282 free(cmd_argv[i]);
9283 free(cmd_argv);
9285 tog_free_refs();
9286 return error;
9289 int
9290 main(int argc, char *argv[])
9292 const struct got_error *error = NULL;
9293 const struct tog_cmd *cmd = NULL;
9294 int ch, hflag = 0, Vflag = 0;
9295 char **cmd_argv = NULL;
9296 static const struct option longopts[] = {
9297 { "version", no_argument, NULL, 'V' },
9298 { NULL, 0, NULL, 0}
9300 char *diff_algo_str = NULL;
9302 if (!isatty(STDIN_FILENO))
9303 errx(1, "standard input is not a tty");
9305 setlocale(LC_CTYPE, "");
9307 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9308 switch (ch) {
9309 case 'h':
9310 hflag = 1;
9311 break;
9312 case 'V':
9313 Vflag = 1;
9314 break;
9315 default:
9316 usage(hflag, 1);
9317 /* NOTREACHED */
9321 argc -= optind;
9322 argv += optind;
9323 optind = 1;
9324 optreset = 1;
9326 if (Vflag) {
9327 got_version_print_str();
9328 return 0;
9331 #ifndef PROFILE
9332 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9333 NULL) == -1)
9334 err(1, "pledge");
9335 #endif
9337 if (argc == 0) {
9338 if (hflag)
9339 usage(hflag, 0);
9340 /* Build an argument vector which runs a default command. */
9341 cmd = &tog_commands[0];
9342 argc = 1;
9343 cmd_argv = make_argv(argc, cmd->name);
9344 } else {
9345 size_t i;
9347 /* Did the user specify a command? */
9348 for (i = 0; i < nitems(tog_commands); i++) {
9349 if (strncmp(tog_commands[i].name, argv[0],
9350 strlen(argv[0])) == 0) {
9351 cmd = &tog_commands[i];
9352 break;
9357 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9358 if (diff_algo_str) {
9359 if (strcasecmp(diff_algo_str, "patience") == 0)
9360 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9361 if (strcasecmp(diff_algo_str, "myers") == 0)
9362 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9365 if (cmd == NULL) {
9366 if (argc != 1)
9367 usage(0, 1);
9368 /* No command specified; try log with a path */
9369 error = tog_log_with_path(argc, argv);
9370 } else {
9371 if (hflag)
9372 cmd->cmd_usage();
9373 else
9374 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9377 endwin();
9378 putchar('\n');
9379 if (cmd_argv) {
9380 int i;
9381 for (i = 0; i < argc; i++)
9382 free(cmd_argv[i]);
9383 free(cmd_argv);
9386 if (error && error->code != GOT_ERR_CANCELLED)
9387 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9388 return 0;