tog: rename regress test script envvar
[got-portable.git] / tog / tog.c
blob8fa205d719a08166373e452c826e108940372eb3
1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
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.
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.
17 #include "got_compat.h"
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 #include <sys/ioctl.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #if defined(__FreeBSD__) || defined(__APPLE__)
26 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
27 #endif
28 #include <curses.h>
29 #include <panel.h>
30 #include <locale.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <err.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <wchar.h>
41 #include <time.h>
42 #include <pthread.h>
43 #include <libgen.h>
44 #include <regex.h>
45 #include <sched.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);
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 },
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
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
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
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;
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
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;
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;
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;
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;
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;
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;
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;
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;
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;
499 struct tog_reflist_entry {
500 TAILQ_ENTRY(tog_reflist_entry) entry;
501 struct got_reference *ref;
502 int idx;
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;
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;
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", "Go to line N (default: first line)"), \
542 KEY_("Home =", "Go to the first line"), \
543 KEY_("G", "Go to line N (default: last line)"), \
544 KEY_("End *", "Go to the last line"), \
545 KEY_("l Right", "Scroll the view right"), \
546 KEY_("h Left", "Scroll the view left"), \
547 KEY_("$", "Scroll view to the rightmost position"), \
548 KEY_("0", "Scroll view to the leftmost position"), \
549 KEY_("-", "Decrease size of the focussed split"), \
550 KEY_("+", "Increase size of the focussed split"), \
551 KEY_("Tab", "Switch focus between views"), \
552 KEY_("F", "Toggle fullscreen mode"), \
553 KEY_("S", "Switch split-screen layout"), \
554 KEY_("/", "Open prompt to enter search term"), \
555 KEY_("n", "Find next line/token matching the current search term"), \
556 KEY_("N", "Find previous line/token matching the current search term"),\
557 KEY_("q", "Quit the focussed view; Quit help screen"), \
558 KEY_("Q", "Quit tog"), \
560 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
561 KEY_("< ,", "Move cursor up one commit"), \
562 KEY_("> .", "Move cursor down one commit"), \
563 KEY_("Enter", "Open diff view of the selected commit"), \
564 KEY_("B", "Reload the log view and toggle display of merged commits"), \
565 KEY_("R", "Open ref view of all repository references"), \
566 KEY_("T", "Display tree view of the repository from the selected" \
567 " commit"), \
568 KEY_("@", "Toggle between displaying author and committer name"), \
569 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
570 KEY_("C-g Backspace", "Cancel current search or log operation"), \
571 KEY_("C-l", "Reload the log view with new commits in the repository"), \
573 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
574 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
575 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
576 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
577 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
578 " data"), \
579 KEY_("(", "Go to the previous file in the diff"), \
580 KEY_(")", "Go to the next file in the diff"), \
581 KEY_("{", "Go to the previous hunk in the diff"), \
582 KEY_("}", "Go to the next hunk in the diff"), \
583 KEY_("[", "Decrease the number of context lines"), \
584 KEY_("]", "Increase the number of context lines"), \
585 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
587 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
588 KEY_("Enter", "Display diff view of the selected line's commit"), \
589 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
590 KEY_("L", "Open log view for the currently selected annotated line"), \
591 KEY_("C", "Reload view with the previously blamed commit"), \
592 KEY_("c", "Reload view with the version of the file found in the" \
593 " selected line's commit"), \
594 KEY_("p", "Reload view with the version of the file found in the" \
595 " selected line's parent commit"), \
597 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
598 KEY_("Enter", "Enter selected directory or open blame view of the" \
599 " selected file"), \
600 KEY_("L", "Open log view for the selected entry"), \
601 KEY_("R", "Open ref view of all repository references"), \
602 KEY_("i", "Show object IDs for all tree entries"), \
603 KEY_("Backspace", "Return to the parent directory"), \
605 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
606 KEY_("Enter", "Display log view of the selected reference"), \
607 KEY_("T", "Display tree view of the selected reference"), \
608 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
609 KEY_("m", "Toggle display of last modified date for each reference"), \
610 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
611 KEY_("C-l", "Reload view with all repository references")
613 struct tog_key_map {
614 const char *keys;
615 const char *info;
616 enum tog_keymap_type type;
619 /* curses io for tog regress */
620 struct tog_io {
621 FILE *cin;
622 FILE *cout;
623 FILE *f;
624 } tog_io;
625 static int using_mock_io;
627 #define TOG_SCREEN_DUMP "SCREENDUMP"
628 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
629 #define TOG_KEY_SCRDUMP SHRT_MIN
632 * We implement two types of views: parent views and child views.
634 * The 'Tab' key switches focus between a parent view and its child view.
635 * Child views are shown side-by-side to their parent view, provided
636 * there is enough screen estate.
638 * When a new view is opened from within a parent view, this new view
639 * becomes a child view of the parent view, replacing any existing child.
641 * When a new view is opened from within a child view, this new view
642 * becomes a parent view which will obscure the views below until the
643 * user quits the new parent view by typing 'q'.
645 * This list of views contains parent views only.
646 * Child views are only pointed to by their parent view.
648 TAILQ_HEAD(tog_view_list_head, tog_view);
650 struct tog_view {
651 TAILQ_ENTRY(tog_view) entry;
652 WINDOW *window;
653 PANEL *panel;
654 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
655 int resized_y, resized_x; /* begin_y/x based on user resizing */
656 int maxx, x; /* max column and current start column */
657 int lines, cols; /* copies of LINES and COLS */
658 int nscrolled, offset; /* lines scrolled and hsplit line offset */
659 int gline, hiline; /* navigate to and highlight this nG line */
660 int ch, count; /* current keymap and count prefix */
661 int resized; /* set when in a resize event */
662 int focussed; /* Only set on one parent or child view at a time. */
663 int dying;
664 struct tog_view *parent;
665 struct tog_view *child;
668 * This flag is initially set on parent views when a new child view
669 * is created. It gets toggled when the 'Tab' key switches focus
670 * between parent and child.
671 * The flag indicates whether focus should be passed on to our child
672 * view if this parent view gets picked for focus after another parent
673 * view was closed. This prevents child views from losing focus in such
674 * situations.
676 int focus_child;
678 enum tog_view_mode mode;
679 /* type-specific state */
680 enum tog_view_type type;
681 union {
682 struct tog_diff_view_state diff;
683 struct tog_log_view_state log;
684 struct tog_blame_view_state blame;
685 struct tog_tree_view_state tree;
686 struct tog_ref_view_state ref;
687 struct tog_help_view_state help;
688 } state;
690 const struct got_error *(*show)(struct tog_view *);
691 const struct got_error *(*input)(struct tog_view **,
692 struct tog_view *, int);
693 const struct got_error *(*reset)(struct tog_view *);
694 const struct got_error *(*resize)(struct tog_view *, int);
695 const struct got_error *(*close)(struct tog_view *);
697 const struct got_error *(*search_start)(struct tog_view *);
698 const struct got_error *(*search_next)(struct tog_view *);
699 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
700 int **, int **, int **, int **);
701 int search_started;
702 int searching;
703 #define TOG_SEARCH_FORWARD 1
704 #define TOG_SEARCH_BACKWARD 2
705 int search_next_done;
706 #define TOG_SEARCH_HAVE_MORE 1
707 #define TOG_SEARCH_NO_MORE 2
708 #define TOG_SEARCH_HAVE_NONE 3
709 regex_t regex;
710 regmatch_t regmatch;
711 const char *action;
714 static const struct got_error *open_diff_view(struct tog_view *,
715 struct got_object_id *, struct got_object_id *,
716 const char *, const char *, int, int, int, struct tog_view *,
717 struct got_repository *);
718 static const struct got_error *show_diff_view(struct tog_view *);
719 static const struct got_error *input_diff_view(struct tog_view **,
720 struct tog_view *, int);
721 static const struct got_error *reset_diff_view(struct tog_view *);
722 static const struct got_error* close_diff_view(struct tog_view *);
723 static const struct got_error *search_start_diff_view(struct tog_view *);
724 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
725 size_t *, int **, int **, int **, int **);
726 static const struct got_error *search_next_view_match(struct tog_view *);
728 static const struct got_error *open_log_view(struct tog_view *,
729 struct got_object_id *, struct got_repository *,
730 const char *, const char *, int);
731 static const struct got_error * show_log_view(struct tog_view *);
732 static const struct got_error *input_log_view(struct tog_view **,
733 struct tog_view *, int);
734 static const struct got_error *resize_log_view(struct tog_view *, int);
735 static const struct got_error *close_log_view(struct tog_view *);
736 static const struct got_error *search_start_log_view(struct tog_view *);
737 static const struct got_error *search_next_log_view(struct tog_view *);
739 static const struct got_error *open_blame_view(struct tog_view *, char *,
740 struct got_object_id *, struct got_repository *);
741 static const struct got_error *show_blame_view(struct tog_view *);
742 static const struct got_error *input_blame_view(struct tog_view **,
743 struct tog_view *, int);
744 static const struct got_error *reset_blame_view(struct tog_view *);
745 static const struct got_error *close_blame_view(struct tog_view *);
746 static const struct got_error *search_start_blame_view(struct tog_view *);
747 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
748 size_t *, int **, int **, int **, int **);
750 static const struct got_error *open_tree_view(struct tog_view *,
751 struct got_object_id *, const char *, struct got_repository *);
752 static const struct got_error *show_tree_view(struct tog_view *);
753 static const struct got_error *input_tree_view(struct tog_view **,
754 struct tog_view *, int);
755 static const struct got_error *close_tree_view(struct tog_view *);
756 static const struct got_error *search_start_tree_view(struct tog_view *);
757 static const struct got_error *search_next_tree_view(struct tog_view *);
759 static const struct got_error *open_ref_view(struct tog_view *,
760 struct got_repository *);
761 static const struct got_error *show_ref_view(struct tog_view *);
762 static const struct got_error *input_ref_view(struct tog_view **,
763 struct tog_view *, int);
764 static const struct got_error *close_ref_view(struct tog_view *);
765 static const struct got_error *search_start_ref_view(struct tog_view *);
766 static const struct got_error *search_next_ref_view(struct tog_view *);
768 static const struct got_error *open_help_view(struct tog_view *,
769 struct tog_view *);
770 static const struct got_error *show_help_view(struct tog_view *);
771 static const struct got_error *input_help_view(struct tog_view **,
772 struct tog_view *, int);
773 static const struct got_error *reset_help_view(struct tog_view *);
774 static const struct got_error* close_help_view(struct tog_view *);
775 static const struct got_error *search_start_help_view(struct tog_view *);
776 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
777 size_t *, int **, int **, int **, int **);
779 static volatile sig_atomic_t tog_sigwinch_received;
780 static volatile sig_atomic_t tog_sigpipe_received;
781 static volatile sig_atomic_t tog_sigcont_received;
782 static volatile sig_atomic_t tog_sigint_received;
783 static volatile sig_atomic_t tog_sigterm_received;
785 static void
786 tog_sigwinch(int signo)
788 tog_sigwinch_received = 1;
791 static void
792 tog_sigpipe(int signo)
794 tog_sigpipe_received = 1;
797 static void
798 tog_sigcont(int signo)
800 tog_sigcont_received = 1;
803 static void
804 tog_sigint(int signo)
806 tog_sigint_received = 1;
809 static void
810 tog_sigterm(int signo)
812 tog_sigterm_received = 1;
815 static int
816 tog_fatal_signal_received(void)
818 return (tog_sigpipe_received ||
819 tog_sigint_received || tog_sigterm_received);
822 static const struct got_error *
823 view_close(struct tog_view *view)
825 const struct got_error *err = NULL, *child_err = NULL;
827 if (view->child) {
828 child_err = view_close(view->child);
829 view->child = NULL;
831 if (view->close)
832 err = view->close(view);
833 if (view->panel)
834 del_panel(view->panel);
835 if (view->window)
836 delwin(view->window);
837 free(view);
838 return err ? err : child_err;
841 static struct tog_view *
842 view_open(int nlines, int ncols, int begin_y, int begin_x,
843 enum tog_view_type type)
845 struct tog_view *view = calloc(1, sizeof(*view));
847 if (view == NULL)
848 return NULL;
850 view->type = type;
851 view->lines = LINES;
852 view->cols = COLS;
853 view->nlines = nlines ? nlines : LINES - begin_y;
854 view->ncols = ncols ? ncols : COLS - begin_x;
855 view->begin_y = begin_y;
856 view->begin_x = begin_x;
857 view->window = newwin(nlines, ncols, begin_y, begin_x);
858 if (view->window == NULL) {
859 view_close(view);
860 return NULL;
862 view->panel = new_panel(view->window);
863 if (view->panel == NULL ||
864 set_panel_userptr(view->panel, view) != OK) {
865 view_close(view);
866 return NULL;
869 keypad(view->window, TRUE);
870 return view;
873 static int
874 view_split_begin_x(int begin_x)
876 if (begin_x > 0 || COLS < 120)
877 return 0;
878 return (COLS - MAX(COLS / 2, 80));
881 /* XXX Stub till we decide what to do. */
882 static int
883 view_split_begin_y(int lines)
885 return lines * HSPLIT_SCALE;
888 static const struct got_error *view_resize(struct tog_view *);
890 static const struct got_error *
891 view_splitscreen(struct tog_view *view)
893 const struct got_error *err = NULL;
895 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
896 if (view->resized_y && view->resized_y < view->lines)
897 view->begin_y = view->resized_y;
898 else
899 view->begin_y = view_split_begin_y(view->nlines);
900 view->begin_x = 0;
901 } else if (!view->resized) {
902 if (view->resized_x && view->resized_x < view->cols - 1 &&
903 view->cols > 119)
904 view->begin_x = view->resized_x;
905 else
906 view->begin_x = view_split_begin_x(0);
907 view->begin_y = 0;
909 view->nlines = LINES - view->begin_y;
910 view->ncols = COLS - view->begin_x;
911 view->lines = LINES;
912 view->cols = COLS;
913 err = view_resize(view);
914 if (err)
915 return err;
917 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
918 view->parent->nlines = view->begin_y;
920 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
921 return got_error_from_errno("mvwin");
923 return NULL;
926 static const struct got_error *
927 view_fullscreen(struct tog_view *view)
929 const struct got_error *err = NULL;
931 view->begin_x = 0;
932 view->begin_y = view->resized ? view->begin_y : 0;
933 view->nlines = view->resized ? view->nlines : LINES;
934 view->ncols = COLS;
935 view->lines = LINES;
936 view->cols = COLS;
937 err = view_resize(view);
938 if (err)
939 return err;
941 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
942 return got_error_from_errno("mvwin");
944 return NULL;
947 static int
948 view_is_parent_view(struct tog_view *view)
950 return view->parent == NULL;
953 static int
954 view_is_splitscreen(struct tog_view *view)
956 return view->begin_x > 0 || view->begin_y > 0;
959 static int
960 view_is_fullscreen(struct tog_view *view)
962 return view->nlines == LINES && view->ncols == COLS;
965 static int
966 view_is_hsplit_top(struct tog_view *view)
968 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
969 view_is_splitscreen(view->child);
972 static void
973 view_border(struct tog_view *view)
975 PANEL *panel;
976 const struct tog_view *view_above;
978 if (view->parent)
979 return view_border(view->parent);
981 panel = panel_above(view->panel);
982 if (panel == NULL)
983 return;
985 view_above = panel_userptr(panel);
986 if (view->mode == TOG_VIEW_SPLIT_HRZN)
987 mvwhline(view->window, view_above->begin_y - 1,
988 view->begin_x, got_locale_is_utf8() ?
989 ACS_HLINE : '-', view->ncols);
990 else
991 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
992 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
995 static const struct got_error *view_init_hsplit(struct tog_view *, int);
996 static const struct got_error *request_log_commits(struct tog_view *);
997 static const struct got_error *offset_selection_down(struct tog_view *);
998 static void offset_selection_up(struct tog_view *);
999 static void view_get_split(struct tog_view *, int *, int *);
1001 static const struct got_error *
1002 view_resize(struct tog_view *view)
1004 const struct got_error *err = NULL;
1005 int dif, nlines, ncols;
1007 dif = LINES - view->lines; /* line difference */
1009 if (view->lines > LINES)
1010 nlines = view->nlines - (view->lines - LINES);
1011 else
1012 nlines = view->nlines + (LINES - view->lines);
1013 if (view->cols > COLS)
1014 ncols = view->ncols - (view->cols - COLS);
1015 else
1016 ncols = view->ncols + (COLS - view->cols);
1018 if (view->child) {
1019 int hs = view->child->begin_y;
1021 if (!view_is_fullscreen(view))
1022 view->child->begin_x = view_split_begin_x(view->begin_x);
1023 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1024 view->child->begin_x == 0) {
1025 ncols = COLS;
1027 view_fullscreen(view->child);
1028 if (view->child->focussed)
1029 show_panel(view->child->panel);
1030 else
1031 show_panel(view->panel);
1032 } else {
1033 ncols = view->child->begin_x;
1035 view_splitscreen(view->child);
1036 show_panel(view->child->panel);
1039 * XXX This is ugly and needs to be moved into the above
1040 * logic but "works" for now and my attempts at moving it
1041 * break either 'tab' or 'F' key maps in horizontal splits.
1043 if (hs) {
1044 err = view_splitscreen(view->child);
1045 if (err)
1046 return err;
1047 if (dif < 0) { /* top split decreased */
1048 err = offset_selection_down(view);
1049 if (err)
1050 return err;
1052 view_border(view);
1053 update_panels();
1054 doupdate();
1055 show_panel(view->child->panel);
1056 nlines = view->nlines;
1058 } else if (view->parent == NULL)
1059 ncols = COLS;
1061 if (view->resize && dif > 0) {
1062 err = view->resize(view, dif);
1063 if (err)
1064 return err;
1067 if (wresize(view->window, nlines, ncols) == ERR)
1068 return got_error_from_errno("wresize");
1069 if (replace_panel(view->panel, view->window) == ERR)
1070 return got_error_from_errno("replace_panel");
1071 wclear(view->window);
1073 view->nlines = nlines;
1074 view->ncols = ncols;
1075 view->lines = LINES;
1076 view->cols = COLS;
1078 return NULL;
1081 static const struct got_error *
1082 resize_log_view(struct tog_view *view, int increase)
1084 struct tog_log_view_state *s = &view->state.log;
1085 const struct got_error *err = NULL;
1086 int n = 0;
1088 if (s->selected_entry)
1089 n = s->selected_entry->idx + view->lines - s->selected;
1092 * Request commits to account for the increased
1093 * height so we have enough to populate the view.
1095 if (s->commits->ncommits < n) {
1096 view->nscrolled = n - s->commits->ncommits + increase + 1;
1097 err = request_log_commits(view);
1100 return err;
1103 static void
1104 view_adjust_offset(struct tog_view *view, int n)
1106 if (n == 0)
1107 return;
1109 if (view->parent && view->parent->offset) {
1110 if (view->parent->offset + n >= 0)
1111 view->parent->offset += n;
1112 else
1113 view->parent->offset = 0;
1114 } else if (view->offset) {
1115 if (view->offset - n >= 0)
1116 view->offset -= n;
1117 else
1118 view->offset = 0;
1122 static const struct got_error *
1123 view_resize_split(struct tog_view *view, int resize)
1125 const struct got_error *err = NULL;
1126 struct tog_view *v = NULL;
1128 if (view->parent)
1129 v = view->parent;
1130 else
1131 v = view;
1133 if (!v->child || !view_is_splitscreen(v->child))
1134 return NULL;
1136 v->resized = v->child->resized = resize; /* lock for resize event */
1138 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1139 if (v->child->resized_y)
1140 v->child->begin_y = v->child->resized_y;
1141 if (view->parent)
1142 v->child->begin_y -= resize;
1143 else
1144 v->child->begin_y += resize;
1145 if (v->child->begin_y < 3) {
1146 view->count = 0;
1147 v->child->begin_y = 3;
1148 } else if (v->child->begin_y > LINES - 1) {
1149 view->count = 0;
1150 v->child->begin_y = LINES - 1;
1152 v->ncols = COLS;
1153 v->child->ncols = COLS;
1154 view_adjust_offset(view, resize);
1155 err = view_init_hsplit(v, v->child->begin_y);
1156 if (err)
1157 return err;
1158 v->child->resized_y = v->child->begin_y;
1159 } else {
1160 if (v->child->resized_x)
1161 v->child->begin_x = v->child->resized_x;
1162 if (view->parent)
1163 v->child->begin_x -= resize;
1164 else
1165 v->child->begin_x += resize;
1166 if (v->child->begin_x < 11) {
1167 view->count = 0;
1168 v->child->begin_x = 11;
1169 } else if (v->child->begin_x > COLS - 1) {
1170 view->count = 0;
1171 v->child->begin_x = COLS - 1;
1173 v->child->resized_x = v->child->begin_x;
1176 v->child->mode = v->mode;
1177 v->child->nlines = v->lines - v->child->begin_y;
1178 v->child->ncols = v->cols - v->child->begin_x;
1179 v->focus_child = 1;
1181 err = view_fullscreen(v);
1182 if (err)
1183 return err;
1184 err = view_splitscreen(v->child);
1185 if (err)
1186 return err;
1188 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1189 err = offset_selection_down(v->child);
1190 if (err)
1191 return err;
1194 if (v->resize)
1195 err = v->resize(v, 0);
1196 else if (v->child->resize)
1197 err = v->child->resize(v->child, 0);
1199 v->resized = v->child->resized = 0;
1201 return err;
1204 static void
1205 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1207 struct tog_view *v = src->child ? src->child : src;
1209 dst->resized_x = v->resized_x;
1210 dst->resized_y = v->resized_y;
1213 static const struct got_error *
1214 view_close_child(struct tog_view *view)
1216 const struct got_error *err = NULL;
1218 if (view->child == NULL)
1219 return NULL;
1221 err = view_close(view->child);
1222 view->child = NULL;
1223 return err;
1226 static const struct got_error *
1227 view_set_child(struct tog_view *view, struct tog_view *child)
1229 const struct got_error *err = NULL;
1231 view->child = child;
1232 child->parent = view;
1234 err = view_resize(view);
1235 if (err)
1236 return err;
1238 if (view->child->resized_x || view->child->resized_y)
1239 err = view_resize_split(view, 0);
1241 return err;
1244 static const struct got_error *view_dispatch_request(struct tog_view **,
1245 struct tog_view *, enum tog_view_type, int, int);
1247 static const struct got_error *
1248 view_request_new(struct tog_view **requested, struct tog_view *view,
1249 enum tog_view_type request)
1251 struct tog_view *new_view = NULL;
1252 const struct got_error *err;
1253 int y = 0, x = 0;
1255 *requested = NULL;
1257 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1258 view_get_split(view, &y, &x);
1260 err = view_dispatch_request(&new_view, view, request, y, x);
1261 if (err)
1262 return err;
1264 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1265 request != TOG_VIEW_HELP) {
1266 err = view_init_hsplit(view, y);
1267 if (err)
1268 return err;
1271 view->focussed = 0;
1272 new_view->focussed = 1;
1273 new_view->mode = view->mode;
1274 new_view->nlines = request == TOG_VIEW_HELP ?
1275 view->lines : view->lines - y;
1277 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1278 view_transfer_size(new_view, view);
1279 err = view_close_child(view);
1280 if (err)
1281 return err;
1282 err = view_set_child(view, new_view);
1283 if (err)
1284 return err;
1285 view->focus_child = 1;
1286 } else
1287 *requested = new_view;
1289 return NULL;
1292 static void
1293 tog_resizeterm(void)
1295 int cols, lines;
1296 struct winsize size;
1298 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1299 cols = 80; /* Default */
1300 lines = 24;
1301 } else {
1302 cols = size.ws_col;
1303 lines = size.ws_row;
1305 resize_term(lines, cols);
1308 static const struct got_error *
1309 view_search_start(struct tog_view *view, int fast_refresh)
1311 const struct got_error *err = NULL;
1312 struct tog_view *v = view;
1313 char pattern[1024];
1314 int ret;
1316 if (view->search_started) {
1317 regfree(&view->regex);
1318 view->searching = 0;
1319 memset(&view->regmatch, 0, sizeof(view->regmatch));
1321 view->search_started = 0;
1323 if (view->nlines < 1)
1324 return NULL;
1326 if (view_is_hsplit_top(view))
1327 v = view->child;
1328 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1329 v = view->parent;
1331 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1332 wclrtoeol(v->window);
1334 nodelay(v->window, FALSE); /* block for search term input */
1335 nocbreak();
1336 echo();
1337 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1338 wrefresh(v->window);
1339 cbreak();
1340 noecho();
1341 nodelay(v->window, TRUE);
1342 if (!fast_refresh && !using_mock_io)
1343 halfdelay(10);
1344 if (ret == ERR)
1345 return NULL;
1347 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1348 err = view->search_start(view);
1349 if (err) {
1350 regfree(&view->regex);
1351 return err;
1353 view->search_started = 1;
1354 view->searching = TOG_SEARCH_FORWARD;
1355 view->search_next_done = 0;
1356 view->search_next(view);
1359 return NULL;
1362 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1363 static const struct got_error *
1364 switch_split(struct tog_view *view)
1366 const struct got_error *err = NULL;
1367 struct tog_view *v = NULL;
1369 if (view->parent)
1370 v = view->parent;
1371 else
1372 v = view;
1374 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1375 v->mode = TOG_VIEW_SPLIT_VERT;
1376 else
1377 v->mode = TOG_VIEW_SPLIT_HRZN;
1379 if (!v->child)
1380 return NULL;
1381 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1382 v->mode = TOG_VIEW_SPLIT_NONE;
1384 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1385 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1386 v->child->begin_y = v->child->resized_y;
1387 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1388 v->child->begin_x = v->child->resized_x;
1391 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1392 v->ncols = COLS;
1393 v->child->ncols = COLS;
1394 v->child->nscrolled = LINES - v->child->nlines;
1396 err = view_init_hsplit(v, v->child->begin_y);
1397 if (err)
1398 return err;
1400 v->child->mode = v->mode;
1401 v->child->nlines = v->lines - v->child->begin_y;
1402 v->focus_child = 1;
1404 err = view_fullscreen(v);
1405 if (err)
1406 return err;
1407 err = view_splitscreen(v->child);
1408 if (err)
1409 return err;
1411 if (v->mode == TOG_VIEW_SPLIT_NONE)
1412 v->mode = TOG_VIEW_SPLIT_VERT;
1413 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1414 err = offset_selection_down(v);
1415 if (err)
1416 return err;
1417 err = offset_selection_down(v->child);
1418 if (err)
1419 return err;
1420 } else {
1421 offset_selection_up(v);
1422 offset_selection_up(v->child);
1424 if (v->resize)
1425 err = v->resize(v, 0);
1426 else if (v->child->resize)
1427 err = v->child->resize(v->child, 0);
1429 return err;
1433 * Strip trailing whitespace from str starting at byte *n;
1434 * if *n < 0, use strlen(str). Return new str length in *n.
1436 static void
1437 strip_trailing_ws(char *str, int *n)
1439 size_t x = *n;
1441 if (str == NULL || *str == '\0')
1442 return;
1444 if (x < 0)
1445 x = strlen(str);
1447 while (x-- > 0 && isspace((unsigned char)str[x]))
1448 str[x] = '\0';
1450 *n = x + 1;
1454 * Extract visible substring of line y from the curses screen
1455 * and strip trailing whitespace. If vline is set and locale is
1456 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1457 * character is written out as 'x'. Write the line to file f.
1459 static const struct got_error *
1460 view_write_line(FILE *f, int y, int vline)
1462 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1463 int r, w;
1465 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1466 if (r == ERR)
1467 return got_error_fmt(GOT_ERR_RANGE,
1468 "failed to extract line %d", y);
1471 * In some views, lines are padded with blanks to COLS width.
1472 * Strip them so we can diff without the -b flag when testing.
1474 strip_trailing_ws(line, &r);
1476 if (vline > 0 && got_locale_is_utf8())
1477 line[vline] = '|';
1479 w = fprintf(f, "%s\n", line);
1480 if (w != r + 1) /* \n */
1481 return got_ferror(f, GOT_ERR_IO);
1483 return NULL;
1487 * Capture the visible curses screen by writing each line to the
1488 * file at the path set via the TOG_SCR_DUMP environment variable.
1490 static const struct got_error *
1491 screendump(struct tog_view *view)
1493 const struct got_error *err;
1494 FILE *f = NULL;
1495 const char *path;
1496 int i;
1498 path = getenv("TOG_SCR_DUMP");
1499 if (path == NULL || *path == '\0')
1500 return got_error_msg(GOT_ERR_BAD_PATH,
1501 "TOG_SCR_DUMP path not set to capture screen dump");
1502 f = fopen(path, "wex");
1503 if (f == NULL)
1504 return got_error_from_errno_fmt("fopen: %s", path);
1506 if ((view->child && view->child->begin_x) ||
1507 (view->parent && view->begin_x)) {
1508 int ncols = view->child ? view->ncols : view->parent->ncols;
1510 /* vertical splitscreen */
1511 for (i = 0; i < view->nlines; ++i) {
1512 err = view_write_line(f, i, ncols - 1);
1513 if (err)
1514 goto done;
1516 } else {
1517 int hline = 0;
1519 /* fullscreen or horizontal splitscreen */
1520 if ((view->child && view->child->begin_y) ||
1521 (view->parent && view->begin_y)) /* hsplit */
1522 hline = view->child ?
1523 view->child->begin_y : view->begin_y;
1525 for (i = 0; i < view->lines; i++) {
1526 if (hline && got_locale_is_utf8() && i == hline - 1) {
1527 int c;
1529 /* ACS_HLINE writes out as 'q', overwrite it */
1530 for (c = 0; c < view->cols; ++c)
1531 fputc('-', f);
1532 fputc('\n', f);
1533 continue;
1536 err = view_write_line(f, i, 0);
1537 if (err)
1538 goto done;
1542 done:
1543 if (f && fclose(f) == EOF && err == NULL)
1544 err = got_ferror(f, GOT_ERR_IO);
1545 return err;
1549 * Compute view->count from numeric input. Assign total to view->count and
1550 * return first non-numeric key entered.
1552 static int
1553 get_compound_key(struct tog_view *view, int c)
1555 struct tog_view *v = view;
1556 int x, n = 0;
1558 if (view_is_hsplit_top(view))
1559 v = view->child;
1560 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1561 v = view->parent;
1563 view->count = 0;
1564 cbreak(); /* block for input */
1565 nodelay(view->window, FALSE);
1566 wmove(v->window, v->nlines - 1, 0);
1567 wclrtoeol(v->window);
1568 waddch(v->window, ':');
1570 do {
1571 x = getcurx(v->window);
1572 if (x != ERR && x < view->ncols) {
1573 waddch(v->window, c);
1574 wrefresh(v->window);
1578 * Don't overflow. Max valid request should be the greatest
1579 * between the longest and total lines; cap at 10 million.
1581 if (n >= 9999999)
1582 n = 9999999;
1583 else
1584 n = n * 10 + (c - '0');
1585 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1587 if (c == 'G' || c == 'g') { /* nG key map */
1588 view->gline = view->hiline = n;
1589 n = 0;
1590 c = 0;
1593 /* Massage excessive or inapplicable values at the input handler. */
1594 view->count = n;
1596 return c;
1599 static void
1600 action_report(struct tog_view *view)
1602 struct tog_view *v = view;
1604 if (view_is_hsplit_top(view))
1605 v = view->child;
1606 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1607 v = view->parent;
1609 wmove(v->window, v->nlines - 1, 0);
1610 wclrtoeol(v->window);
1611 wprintw(v->window, ":%s", view->action);
1612 wrefresh(v->window);
1615 * Clear action status report. Only clear in blame view
1616 * once annotating is complete, otherwise it's too fast.
1618 if (view->type == TOG_VIEW_BLAME) {
1619 if (view->state.blame.blame_complete)
1620 view->action = NULL;
1621 } else
1622 view->action = NULL;
1626 * Read the next line from the test script and assign
1627 * key instruction to *ch. If at EOF, set the *done flag.
1629 static const struct got_error *
1630 tog_read_script_key(FILE *script, int *ch, int *done)
1632 const struct got_error *err = NULL;
1633 char *line = NULL;
1634 size_t linesz = 0;
1636 if (getline(&line, &linesz, script) == -1) {
1637 if (feof(script)) {
1638 *done = 1;
1639 goto done;
1640 } else {
1641 err = got_ferror(script, GOT_ERR_IO);
1642 goto done;
1644 } else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1645 *ch = KEY_ENTER;
1646 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1647 *ch = KEY_RIGHT;
1648 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1649 *ch = KEY_LEFT;
1650 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1651 *ch = KEY_DOWN;
1652 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1653 *ch = KEY_UP;
1654 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1655 *ch = TOG_KEY_SCRDUMP;
1656 else
1657 *ch = *line;
1659 done:
1660 free(line);
1661 return err;
1664 static const struct got_error *
1665 view_input(struct tog_view **new, int *done, struct tog_view *view,
1666 struct tog_view_list_head *views, int fast_refresh)
1668 const struct got_error *err = NULL;
1669 struct tog_view *v;
1670 int ch, errcode;
1672 *new = NULL;
1674 if (view->action)
1675 action_report(view);
1677 /* Clear "no matches" indicator. */
1678 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1679 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1680 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1681 view->count = 0;
1684 if (view->searching && !view->search_next_done) {
1685 errcode = pthread_mutex_unlock(&tog_mutex);
1686 if (errcode)
1687 return got_error_set_errno(errcode,
1688 "pthread_mutex_unlock");
1689 sched_yield();
1690 errcode = pthread_mutex_lock(&tog_mutex);
1691 if (errcode)
1692 return got_error_set_errno(errcode,
1693 "pthread_mutex_lock");
1694 view->search_next(view);
1695 return NULL;
1698 /* Allow threads to make progress while we are waiting for input. */
1699 errcode = pthread_mutex_unlock(&tog_mutex);
1700 if (errcode)
1701 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1703 if (using_mock_io) {
1704 err = tog_read_script_key(tog_io.f, &ch, done);
1705 if (err)
1706 return err;
1707 } else if (view->count && --view->count) {
1708 cbreak();
1709 nodelay(view->window, TRUE);
1710 ch = wgetch(view->window);
1711 /* let C-g or backspace abort unfinished count */
1712 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1713 view->count = 0;
1714 else
1715 ch = view->ch;
1716 } else {
1717 ch = wgetch(view->window);
1718 if (ch >= '1' && ch <= '9')
1719 view->ch = ch = get_compound_key(view, ch);
1721 if (view->hiline && ch != ERR && ch != 0)
1722 view->hiline = 0; /* key pressed, clear line highlight */
1723 nodelay(view->window, TRUE);
1724 errcode = pthread_mutex_lock(&tog_mutex);
1725 if (errcode)
1726 return got_error_set_errno(errcode, "pthread_mutex_lock");
1728 if (tog_sigwinch_received || tog_sigcont_received) {
1729 tog_resizeterm();
1730 tog_sigwinch_received = 0;
1731 tog_sigcont_received = 0;
1732 TAILQ_FOREACH(v, views, entry) {
1733 err = view_resize(v);
1734 if (err)
1735 return err;
1736 err = v->input(new, v, KEY_RESIZE);
1737 if (err)
1738 return err;
1739 if (v->child) {
1740 err = view_resize(v->child);
1741 if (err)
1742 return err;
1743 err = v->child->input(new, v->child,
1744 KEY_RESIZE);
1745 if (err)
1746 return err;
1747 if (v->child->resized_x || v->child->resized_y) {
1748 err = view_resize_split(v, 0);
1749 if (err)
1750 return err;
1756 switch (ch) {
1757 case '?':
1758 case 'H':
1759 case KEY_F(1):
1760 if (view->type == TOG_VIEW_HELP)
1761 err = view->reset(view);
1762 else
1763 err = view_request_new(new, view, TOG_VIEW_HELP);
1764 break;
1765 case '\t':
1766 view->count = 0;
1767 if (view->child) {
1768 view->focussed = 0;
1769 view->child->focussed = 1;
1770 view->focus_child = 1;
1771 } else if (view->parent) {
1772 view->focussed = 0;
1773 view->parent->focussed = 1;
1774 view->parent->focus_child = 0;
1775 if (!view_is_splitscreen(view)) {
1776 if (view->parent->resize) {
1777 err = view->parent->resize(view->parent,
1779 if (err)
1780 return err;
1782 offset_selection_up(view->parent);
1783 err = view_fullscreen(view->parent);
1784 if (err)
1785 return err;
1788 break;
1789 case 'q':
1790 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1791 if (view->parent->resize) {
1792 /* might need more commits to fill fullscreen */
1793 err = view->parent->resize(view->parent, 0);
1794 if (err)
1795 break;
1797 offset_selection_up(view->parent);
1799 err = view->input(new, view, ch);
1800 view->dying = 1;
1801 break;
1802 case 'Q':
1803 *done = 1;
1804 break;
1805 case 'F':
1806 view->count = 0;
1807 if (view_is_parent_view(view)) {
1808 if (view->child == NULL)
1809 break;
1810 if (view_is_splitscreen(view->child)) {
1811 view->focussed = 0;
1812 view->child->focussed = 1;
1813 err = view_fullscreen(view->child);
1814 } else {
1815 err = view_splitscreen(view->child);
1816 if (!err)
1817 err = view_resize_split(view, 0);
1819 if (err)
1820 break;
1821 err = view->child->input(new, view->child,
1822 KEY_RESIZE);
1823 } else {
1824 if (view_is_splitscreen(view)) {
1825 view->parent->focussed = 0;
1826 view->focussed = 1;
1827 err = view_fullscreen(view);
1828 } else {
1829 err = view_splitscreen(view);
1830 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1831 err = view_resize(view->parent);
1832 if (!err)
1833 err = view_resize_split(view, 0);
1835 if (err)
1836 break;
1837 err = view->input(new, view, KEY_RESIZE);
1839 if (err)
1840 break;
1841 if (view->resize) {
1842 err = view->resize(view, 0);
1843 if (err)
1844 break;
1846 if (view->parent)
1847 err = offset_selection_down(view->parent);
1848 if (!err)
1849 err = offset_selection_down(view);
1850 break;
1851 case 'S':
1852 view->count = 0;
1853 err = switch_split(view);
1854 break;
1855 case '-':
1856 err = view_resize_split(view, -1);
1857 break;
1858 case '+':
1859 err = view_resize_split(view, 1);
1860 break;
1861 case KEY_RESIZE:
1862 break;
1863 case '/':
1864 view->count = 0;
1865 if (view->search_start)
1866 view_search_start(view, fast_refresh);
1867 else
1868 err = view->input(new, view, ch);
1869 break;
1870 case 'N':
1871 case 'n':
1872 if (view->search_started && view->search_next) {
1873 view->searching = (ch == 'n' ?
1874 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1875 view->search_next_done = 0;
1876 view->search_next(view);
1877 } else
1878 err = view->input(new, view, ch);
1879 break;
1880 case 'A':
1881 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1882 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1883 view->action = "Patience diff algorithm";
1884 } else {
1885 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1886 view->action = "Myers diff algorithm";
1888 TAILQ_FOREACH(v, views, entry) {
1889 if (v->reset) {
1890 err = v->reset(v);
1891 if (err)
1892 return err;
1894 if (v->child && v->child->reset) {
1895 err = v->child->reset(v->child);
1896 if (err)
1897 return err;
1900 break;
1901 case TOG_KEY_SCRDUMP:
1902 err = screendump(view);
1903 break;
1904 default:
1905 err = view->input(new, view, ch);
1906 break;
1909 return err;
1912 static int
1913 view_needs_focus_indication(struct tog_view *view)
1915 if (view_is_parent_view(view)) {
1916 if (view->child == NULL || view->child->focussed)
1917 return 0;
1918 if (!view_is_splitscreen(view->child))
1919 return 0;
1920 } else if (!view_is_splitscreen(view))
1921 return 0;
1923 return view->focussed;
1926 static const struct got_error *
1927 tog_io_close(void)
1929 const struct got_error *err = NULL;
1931 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1932 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1933 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1934 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1935 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1936 err = got_ferror(tog_io.f, GOT_ERR_IO);
1938 return err;
1941 static const struct got_error *
1942 view_loop(struct tog_view *view)
1944 const struct got_error *err = NULL;
1945 struct tog_view_list_head views;
1946 struct tog_view *new_view;
1947 char *mode;
1948 int fast_refresh = 10;
1949 int done = 0, errcode;
1951 mode = getenv("TOG_VIEW_SPLIT_MODE");
1952 if (!mode || !(*mode == 'h' || *mode == 'H'))
1953 view->mode = TOG_VIEW_SPLIT_VERT;
1954 else
1955 view->mode = TOG_VIEW_SPLIT_HRZN;
1957 errcode = pthread_mutex_lock(&tog_mutex);
1958 if (errcode)
1959 return got_error_set_errno(errcode, "pthread_mutex_lock");
1961 TAILQ_INIT(&views);
1962 TAILQ_INSERT_HEAD(&views, view, entry);
1964 view->focussed = 1;
1965 err = view->show(view);
1966 if (err)
1967 return err;
1968 update_panels();
1969 doupdate();
1970 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1971 !tog_fatal_signal_received()) {
1972 /* Refresh fast during initialization, then become slower. */
1973 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1974 halfdelay(10); /* switch to once per second */
1976 err = view_input(&new_view, &done, view, &views, fast_refresh);
1977 if (err)
1978 break;
1980 if (view->dying && view == TAILQ_FIRST(&views) &&
1981 TAILQ_NEXT(view, entry) == NULL)
1982 done = 1;
1983 if (done) {
1984 struct tog_view *v;
1987 * When we quit, scroll the screen up a single line
1988 * so we don't lose any information.
1990 TAILQ_FOREACH(v, &views, entry) {
1991 wmove(v->window, 0, 0);
1992 wdeleteln(v->window);
1993 wnoutrefresh(v->window);
1994 if (v->child && !view_is_fullscreen(v)) {
1995 wmove(v->child->window, 0, 0);
1996 wdeleteln(v->child->window);
1997 wnoutrefresh(v->child->window);
2000 doupdate();
2003 if (view->dying) {
2004 struct tog_view *v, *prev = NULL;
2006 if (view_is_parent_view(view))
2007 prev = TAILQ_PREV(view, tog_view_list_head,
2008 entry);
2009 else if (view->parent)
2010 prev = view->parent;
2012 if (view->parent) {
2013 view->parent->child = NULL;
2014 view->parent->focus_child = 0;
2015 /* Restore fullscreen line height. */
2016 view->parent->nlines = view->parent->lines;
2017 err = view_resize(view->parent);
2018 if (err)
2019 break;
2020 /* Make resized splits persist. */
2021 view_transfer_size(view->parent, view);
2022 } else
2023 TAILQ_REMOVE(&views, view, entry);
2025 err = view_close(view);
2026 if (err)
2027 goto done;
2029 view = NULL;
2030 TAILQ_FOREACH(v, &views, entry) {
2031 if (v->focussed)
2032 break;
2034 if (view == NULL && new_view == NULL) {
2035 /* No view has focus. Try to pick one. */
2036 if (prev)
2037 view = prev;
2038 else if (!TAILQ_EMPTY(&views)) {
2039 view = TAILQ_LAST(&views,
2040 tog_view_list_head);
2042 if (view) {
2043 if (view->focus_child) {
2044 view->child->focussed = 1;
2045 view = view->child;
2046 } else
2047 view->focussed = 1;
2051 if (new_view) {
2052 struct tog_view *v, *t;
2053 /* Only allow one parent view per type. */
2054 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2055 if (v->type != new_view->type)
2056 continue;
2057 TAILQ_REMOVE(&views, v, entry);
2058 err = view_close(v);
2059 if (err)
2060 goto done;
2061 break;
2063 TAILQ_INSERT_TAIL(&views, new_view, entry);
2064 view = new_view;
2066 if (view && !done) {
2067 if (view_is_parent_view(view)) {
2068 if (view->child && view->child->focussed)
2069 view = view->child;
2070 } else {
2071 if (view->parent && view->parent->focussed)
2072 view = view->parent;
2074 show_panel(view->panel);
2075 if (view->child && view_is_splitscreen(view->child))
2076 show_panel(view->child->panel);
2077 if (view->parent && view_is_splitscreen(view)) {
2078 err = view->parent->show(view->parent);
2079 if (err)
2080 goto done;
2082 err = view->show(view);
2083 if (err)
2084 goto done;
2085 if (view->child) {
2086 err = view->child->show(view->child);
2087 if (err)
2088 goto done;
2090 update_panels();
2091 doupdate();
2094 done:
2095 while (!TAILQ_EMPTY(&views)) {
2096 const struct got_error *close_err;
2097 view = TAILQ_FIRST(&views);
2098 TAILQ_REMOVE(&views, view, entry);
2099 close_err = view_close(view);
2100 if (close_err && err == NULL)
2101 err = close_err;
2104 errcode = pthread_mutex_unlock(&tog_mutex);
2105 if (errcode && err == NULL)
2106 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2108 return err;
2111 __dead static void
2112 usage_log(void)
2114 endwin();
2115 fprintf(stderr,
2116 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2117 getprogname());
2118 exit(1);
2121 /* Create newly allocated wide-character string equivalent to a byte string. */
2122 static const struct got_error *
2123 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2125 char *vis = NULL;
2126 const struct got_error *err = NULL;
2128 *ws = NULL;
2129 *wlen = mbstowcs(NULL, s, 0);
2130 if (*wlen == (size_t)-1) {
2131 int vislen;
2132 if (errno != EILSEQ)
2133 return got_error_from_errno("mbstowcs");
2135 /* byte string invalid in current encoding; try to "fix" it */
2136 err = got_mbsavis(&vis, &vislen, s);
2137 if (err)
2138 return err;
2139 *wlen = mbstowcs(NULL, vis, 0);
2140 if (*wlen == (size_t)-1) {
2141 err = got_error_from_errno("mbstowcs"); /* give up */
2142 goto done;
2146 *ws = calloc(*wlen + 1, sizeof(**ws));
2147 if (*ws == NULL) {
2148 err = got_error_from_errno("calloc");
2149 goto done;
2152 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2153 err = got_error_from_errno("mbstowcs");
2154 done:
2155 free(vis);
2156 if (err) {
2157 free(*ws);
2158 *ws = NULL;
2159 *wlen = 0;
2161 return err;
2164 static const struct got_error *
2165 expand_tab(char **ptr, const char *src)
2167 char *dst;
2168 size_t len, n, idx = 0, sz = 0;
2170 *ptr = NULL;
2171 n = len = strlen(src);
2172 dst = malloc(n + 1);
2173 if (dst == NULL)
2174 return got_error_from_errno("malloc");
2176 while (idx < len && src[idx]) {
2177 const char c = src[idx];
2179 if (c == '\t') {
2180 size_t nb = TABSIZE - sz % TABSIZE;
2181 char *p;
2183 p = realloc(dst, n + nb);
2184 if (p == NULL) {
2185 free(dst);
2186 return got_error_from_errno("realloc");
2189 dst = p;
2190 n += nb;
2191 memset(dst + sz, ' ', nb);
2192 sz += nb;
2193 } else
2194 dst[sz++] = src[idx];
2195 ++idx;
2198 dst[sz] = '\0';
2199 *ptr = dst;
2200 return NULL;
2204 * Advance at most n columns from wline starting at offset off.
2205 * Return the index to the first character after the span operation.
2206 * Return the combined column width of all spanned wide character in
2207 * *rcol.
2209 static int
2210 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2212 int width, i, cols = 0;
2214 if (n == 0) {
2215 *rcol = cols;
2216 return off;
2219 for (i = off; wline[i] != L'\0'; ++i) {
2220 if (wline[i] == L'\t')
2221 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2222 else
2223 width = wcwidth(wline[i]);
2225 if (width == -1) {
2226 width = 1;
2227 wline[i] = L'.';
2230 if (cols + width > n)
2231 break;
2232 cols += width;
2235 *rcol = cols;
2236 return i;
2240 * Format a line for display, ensuring that it won't overflow a width limit.
2241 * With scrolling, the width returned refers to the scrolled version of the
2242 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2244 static const struct got_error *
2245 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2246 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2248 const struct got_error *err = NULL;
2249 int cols;
2250 wchar_t *wline = NULL;
2251 char *exstr = NULL;
2252 size_t wlen;
2253 int i, scrollx;
2255 *wlinep = NULL;
2256 *widthp = 0;
2258 if (expand) {
2259 err = expand_tab(&exstr, line);
2260 if (err)
2261 return err;
2264 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2265 free(exstr);
2266 if (err)
2267 return err;
2269 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2271 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2272 wline[wlen - 1] = L'\0';
2273 wlen--;
2275 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2276 wline[wlen - 1] = L'\0';
2277 wlen--;
2280 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2281 wline[i] = L'\0';
2283 if (widthp)
2284 *widthp = cols;
2285 if (scrollxp)
2286 *scrollxp = scrollx;
2287 if (err)
2288 free(wline);
2289 else
2290 *wlinep = wline;
2291 return err;
2294 static const struct got_error*
2295 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2296 struct got_object_id *id, struct got_repository *repo)
2298 static const struct got_error *err = NULL;
2299 struct got_reflist_entry *re;
2300 char *s;
2301 const char *name;
2303 *refs_str = NULL;
2305 TAILQ_FOREACH(re, refs, entry) {
2306 struct got_tag_object *tag = NULL;
2307 struct got_object_id *ref_id;
2308 int cmp;
2310 name = got_ref_get_name(re->ref);
2311 if (strcmp(name, GOT_REF_HEAD) == 0)
2312 continue;
2313 if (strncmp(name, "refs/", 5) == 0)
2314 name += 5;
2315 if (strncmp(name, "got/", 4) == 0 &&
2316 strncmp(name, "got/backup/", 11) != 0)
2317 continue;
2318 if (strncmp(name, "heads/", 6) == 0)
2319 name += 6;
2320 if (strncmp(name, "remotes/", 8) == 0) {
2321 name += 8;
2322 s = strstr(name, "/" GOT_REF_HEAD);
2323 if (s != NULL && s[strlen(s)] == '\0')
2324 continue;
2326 err = got_ref_resolve(&ref_id, repo, re->ref);
2327 if (err)
2328 break;
2329 if (strncmp(name, "tags/", 5) == 0) {
2330 err = got_object_open_as_tag(&tag, repo, ref_id);
2331 if (err) {
2332 if (err->code != GOT_ERR_OBJ_TYPE) {
2333 free(ref_id);
2334 break;
2336 /* Ref points at something other than a tag. */
2337 err = NULL;
2338 tag = NULL;
2341 cmp = got_object_id_cmp(tag ?
2342 got_object_tag_get_object_id(tag) : ref_id, id);
2343 free(ref_id);
2344 if (tag)
2345 got_object_tag_close(tag);
2346 if (cmp != 0)
2347 continue;
2348 s = *refs_str;
2349 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2350 s ? ", " : "", name) == -1) {
2351 err = got_error_from_errno("asprintf");
2352 free(s);
2353 *refs_str = NULL;
2354 break;
2356 free(s);
2359 return err;
2362 static const struct got_error *
2363 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2364 int col_tab_align)
2366 char *smallerthan;
2368 smallerthan = strchr(author, '<');
2369 if (smallerthan && smallerthan[1] != '\0')
2370 author = smallerthan + 1;
2371 author[strcspn(author, "@>")] = '\0';
2372 return format_line(wauthor, author_width, NULL, author, 0, limit,
2373 col_tab_align, 0);
2376 static const struct got_error *
2377 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2378 struct got_object_id *id, const size_t date_display_cols,
2379 int author_display_cols)
2381 struct tog_log_view_state *s = &view->state.log;
2382 const struct got_error *err = NULL;
2383 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2384 char *logmsg0 = NULL, *logmsg = NULL;
2385 char *author = NULL;
2386 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2387 int author_width, logmsg_width;
2388 char *newline, *line = NULL;
2389 int col, limit, scrollx;
2390 const int avail = view->ncols;
2391 struct tm tm;
2392 time_t committer_time;
2393 struct tog_color *tc;
2395 committer_time = got_object_commit_get_committer_time(commit);
2396 if (gmtime_r(&committer_time, &tm) == NULL)
2397 return got_error_from_errno("gmtime_r");
2398 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2399 return got_error(GOT_ERR_NO_SPACE);
2401 if (avail <= date_display_cols)
2402 limit = MIN(sizeof(datebuf) - 1, avail);
2403 else
2404 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2405 tc = get_color(&s->colors, TOG_COLOR_DATE);
2406 if (tc)
2407 wattr_on(view->window,
2408 COLOR_PAIR(tc->colorpair), NULL);
2409 waddnstr(view->window, datebuf, limit);
2410 if (tc)
2411 wattr_off(view->window,
2412 COLOR_PAIR(tc->colorpair), NULL);
2413 col = limit;
2414 if (col > avail)
2415 goto done;
2417 if (avail >= 120) {
2418 char *id_str;
2419 err = got_object_id_str(&id_str, id);
2420 if (err)
2421 goto done;
2422 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2423 if (tc)
2424 wattr_on(view->window,
2425 COLOR_PAIR(tc->colorpair), NULL);
2426 wprintw(view->window, "%.8s ", id_str);
2427 if (tc)
2428 wattr_off(view->window,
2429 COLOR_PAIR(tc->colorpair), NULL);
2430 free(id_str);
2431 col += 9;
2432 if (col > avail)
2433 goto done;
2436 if (s->use_committer)
2437 author = strdup(got_object_commit_get_committer(commit));
2438 else
2439 author = strdup(got_object_commit_get_author(commit));
2440 if (author == NULL) {
2441 err = got_error_from_errno("strdup");
2442 goto done;
2444 err = format_author(&wauthor, &author_width, author, avail - col, col);
2445 if (err)
2446 goto done;
2447 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2448 if (tc)
2449 wattr_on(view->window,
2450 COLOR_PAIR(tc->colorpair), NULL);
2451 waddwstr(view->window, wauthor);
2452 col += author_width;
2453 while (col < avail && author_width < author_display_cols + 2) {
2454 waddch(view->window, ' ');
2455 col++;
2456 author_width++;
2458 if (tc)
2459 wattr_off(view->window,
2460 COLOR_PAIR(tc->colorpair), NULL);
2461 if (col > avail)
2462 goto done;
2464 err = got_object_commit_get_logmsg(&logmsg0, commit);
2465 if (err)
2466 goto done;
2467 logmsg = logmsg0;
2468 while (*logmsg == '\n')
2469 logmsg++;
2470 newline = strchr(logmsg, '\n');
2471 if (newline)
2472 *newline = '\0';
2473 limit = avail - col;
2474 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2475 limit--; /* for the border */
2476 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2477 limit, col, 1);
2478 if (err)
2479 goto done;
2480 waddwstr(view->window, &wlogmsg[scrollx]);
2481 col += MAX(logmsg_width, 0);
2482 while (col < avail) {
2483 waddch(view->window, ' ');
2484 col++;
2486 done:
2487 free(logmsg0);
2488 free(wlogmsg);
2489 free(author);
2490 free(wauthor);
2491 free(line);
2492 return err;
2495 static struct commit_queue_entry *
2496 alloc_commit_queue_entry(struct got_commit_object *commit,
2497 struct got_object_id *id)
2499 struct commit_queue_entry *entry;
2500 struct got_object_id *dup;
2502 entry = calloc(1, sizeof(*entry));
2503 if (entry == NULL)
2504 return NULL;
2506 dup = got_object_id_dup(id);
2507 if (dup == NULL) {
2508 free(entry);
2509 return NULL;
2512 entry->id = dup;
2513 entry->commit = commit;
2514 return entry;
2517 static void
2518 pop_commit(struct commit_queue *commits)
2520 struct commit_queue_entry *entry;
2522 entry = TAILQ_FIRST(&commits->head);
2523 TAILQ_REMOVE(&commits->head, entry, entry);
2524 got_object_commit_close(entry->commit);
2525 commits->ncommits--;
2526 free(entry->id);
2527 free(entry);
2530 static void
2531 free_commits(struct commit_queue *commits)
2533 while (!TAILQ_EMPTY(&commits->head))
2534 pop_commit(commits);
2537 static const struct got_error *
2538 match_commit(int *have_match, struct got_object_id *id,
2539 struct got_commit_object *commit, regex_t *regex)
2541 const struct got_error *err = NULL;
2542 regmatch_t regmatch;
2543 char *id_str = NULL, *logmsg = NULL;
2545 *have_match = 0;
2547 err = got_object_id_str(&id_str, id);
2548 if (err)
2549 return err;
2551 err = got_object_commit_get_logmsg(&logmsg, commit);
2552 if (err)
2553 goto done;
2555 if (regexec(regex, got_object_commit_get_author(commit), 1,
2556 &regmatch, 0) == 0 ||
2557 regexec(regex, got_object_commit_get_committer(commit), 1,
2558 &regmatch, 0) == 0 ||
2559 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2560 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2561 *have_match = 1;
2562 done:
2563 free(id_str);
2564 free(logmsg);
2565 return err;
2568 static const struct got_error *
2569 queue_commits(struct tog_log_thread_args *a)
2571 const struct got_error *err = NULL;
2574 * We keep all commits open throughout the lifetime of the log
2575 * view in order to avoid having to re-fetch commits from disk
2576 * while updating the display.
2578 do {
2579 struct got_object_id id;
2580 struct got_commit_object *commit;
2581 struct commit_queue_entry *entry;
2582 int limit_match = 0;
2583 int errcode;
2585 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2586 NULL, NULL);
2587 if (err)
2588 break;
2590 err = got_object_open_as_commit(&commit, a->repo, &id);
2591 if (err)
2592 break;
2593 entry = alloc_commit_queue_entry(commit, &id);
2594 if (entry == NULL) {
2595 err = got_error_from_errno("alloc_commit_queue_entry");
2596 break;
2599 errcode = pthread_mutex_lock(&tog_mutex);
2600 if (errcode) {
2601 err = got_error_set_errno(errcode,
2602 "pthread_mutex_lock");
2603 break;
2606 entry->idx = a->real_commits->ncommits;
2607 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2608 a->real_commits->ncommits++;
2610 if (*a->limiting) {
2611 err = match_commit(&limit_match, &id, commit,
2612 a->limit_regex);
2613 if (err)
2614 break;
2616 if (limit_match) {
2617 struct commit_queue_entry *matched;
2619 matched = alloc_commit_queue_entry(
2620 entry->commit, entry->id);
2621 if (matched == NULL) {
2622 err = got_error_from_errno(
2623 "alloc_commit_queue_entry");
2624 break;
2626 matched->commit = entry->commit;
2627 got_object_commit_retain(entry->commit);
2629 matched->idx = a->limit_commits->ncommits;
2630 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2631 matched, entry);
2632 a->limit_commits->ncommits++;
2636 * This is how we signal log_thread() that we
2637 * have found a match, and that it should be
2638 * counted as a new entry for the view.
2640 a->limit_match = limit_match;
2643 if (*a->searching == TOG_SEARCH_FORWARD &&
2644 !*a->search_next_done) {
2645 int have_match;
2646 err = match_commit(&have_match, &id, commit, a->regex);
2647 if (err)
2648 break;
2650 if (*a->limiting) {
2651 if (limit_match && have_match)
2652 *a->search_next_done =
2653 TOG_SEARCH_HAVE_MORE;
2654 } else if (have_match)
2655 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2658 errcode = pthread_mutex_unlock(&tog_mutex);
2659 if (errcode && err == NULL)
2660 err = got_error_set_errno(errcode,
2661 "pthread_mutex_unlock");
2662 if (err)
2663 break;
2664 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2666 return err;
2669 static void
2670 select_commit(struct tog_log_view_state *s)
2672 struct commit_queue_entry *entry;
2673 int ncommits = 0;
2675 entry = s->first_displayed_entry;
2676 while (entry) {
2677 if (ncommits == s->selected) {
2678 s->selected_entry = entry;
2679 break;
2681 entry = TAILQ_NEXT(entry, entry);
2682 ncommits++;
2686 static const struct got_error *
2687 draw_commits(struct tog_view *view)
2689 const struct got_error *err = NULL;
2690 struct tog_log_view_state *s = &view->state.log;
2691 struct commit_queue_entry *entry = s->selected_entry;
2692 int limit = view->nlines;
2693 int width;
2694 int ncommits, author_cols = 4;
2695 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2696 char *refs_str = NULL;
2697 wchar_t *wline;
2698 struct tog_color *tc;
2699 static const size_t date_display_cols = 12;
2701 if (view_is_hsplit_top(view))
2702 --limit; /* account for border */
2704 if (s->selected_entry &&
2705 !(view->searching && view->search_next_done == 0)) {
2706 struct got_reflist_head *refs;
2707 err = got_object_id_str(&id_str, s->selected_entry->id);
2708 if (err)
2709 return err;
2710 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2711 s->selected_entry->id);
2712 if (refs) {
2713 err = build_refs_str(&refs_str, refs,
2714 s->selected_entry->id, s->repo);
2715 if (err)
2716 goto done;
2720 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2721 halfdelay(10); /* disable fast refresh */
2723 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2724 if (asprintf(&ncommits_str, " [%d/%d] %s",
2725 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2726 (view->searching && !view->search_next_done) ?
2727 "searching..." : "loading...") == -1) {
2728 err = got_error_from_errno("asprintf");
2729 goto done;
2731 } else {
2732 const char *search_str = NULL;
2733 const char *limit_str = NULL;
2735 if (view->searching) {
2736 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2737 search_str = "no more matches";
2738 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2739 search_str = "no matches found";
2740 else if (!view->search_next_done)
2741 search_str = "searching...";
2744 if (s->limit_view && s->commits->ncommits == 0)
2745 limit_str = "no matches found";
2747 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2748 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2749 search_str ? search_str : (refs_str ? refs_str : ""),
2750 limit_str ? limit_str : "") == -1) {
2751 err = got_error_from_errno("asprintf");
2752 goto done;
2756 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2757 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2758 "........................................",
2759 s->in_repo_path, ncommits_str) == -1) {
2760 err = got_error_from_errno("asprintf");
2761 header = NULL;
2762 goto done;
2764 } else if (asprintf(&header, "commit %s%s",
2765 id_str ? id_str : "........................................",
2766 ncommits_str) == -1) {
2767 err = got_error_from_errno("asprintf");
2768 header = NULL;
2769 goto done;
2771 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2772 if (err)
2773 goto done;
2775 werase(view->window);
2777 if (view_needs_focus_indication(view))
2778 wstandout(view->window);
2779 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2780 if (tc)
2781 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2782 waddwstr(view->window, wline);
2783 while (width < view->ncols) {
2784 waddch(view->window, ' ');
2785 width++;
2787 if (tc)
2788 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2789 if (view_needs_focus_indication(view))
2790 wstandend(view->window);
2791 free(wline);
2792 if (limit <= 1)
2793 goto done;
2795 /* Grow author column size if necessary, and set view->maxx. */
2796 entry = s->first_displayed_entry;
2797 ncommits = 0;
2798 view->maxx = 0;
2799 while (entry) {
2800 struct got_commit_object *c = entry->commit;
2801 char *author, *eol, *msg, *msg0;
2802 wchar_t *wauthor, *wmsg;
2803 int width;
2804 if (ncommits >= limit - 1)
2805 break;
2806 if (s->use_committer)
2807 author = strdup(got_object_commit_get_committer(c));
2808 else
2809 author = strdup(got_object_commit_get_author(c));
2810 if (author == NULL) {
2811 err = got_error_from_errno("strdup");
2812 goto done;
2814 err = format_author(&wauthor, &width, author, COLS,
2815 date_display_cols);
2816 if (author_cols < width)
2817 author_cols = width;
2818 free(wauthor);
2819 free(author);
2820 if (err)
2821 goto done;
2822 err = got_object_commit_get_logmsg(&msg0, c);
2823 if (err)
2824 goto done;
2825 msg = msg0;
2826 while (*msg == '\n')
2827 ++msg;
2828 if ((eol = strchr(msg, '\n')))
2829 *eol = '\0';
2830 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2831 date_display_cols + author_cols, 0);
2832 if (err)
2833 goto done;
2834 view->maxx = MAX(view->maxx, width);
2835 free(msg0);
2836 free(wmsg);
2837 ncommits++;
2838 entry = TAILQ_NEXT(entry, entry);
2841 entry = s->first_displayed_entry;
2842 s->last_displayed_entry = s->first_displayed_entry;
2843 ncommits = 0;
2844 while (entry) {
2845 if (ncommits >= limit - 1)
2846 break;
2847 if (ncommits == s->selected)
2848 wstandout(view->window);
2849 err = draw_commit(view, entry->commit, entry->id,
2850 date_display_cols, author_cols);
2851 if (ncommits == s->selected)
2852 wstandend(view->window);
2853 if (err)
2854 goto done;
2855 ncommits++;
2856 s->last_displayed_entry = entry;
2857 entry = TAILQ_NEXT(entry, entry);
2860 view_border(view);
2861 done:
2862 free(id_str);
2863 free(refs_str);
2864 free(ncommits_str);
2865 free(header);
2866 return err;
2869 static void
2870 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2872 struct commit_queue_entry *entry;
2873 int nscrolled = 0;
2875 entry = TAILQ_FIRST(&s->commits->head);
2876 if (s->first_displayed_entry == entry)
2877 return;
2879 entry = s->first_displayed_entry;
2880 while (entry && nscrolled < maxscroll) {
2881 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2882 if (entry) {
2883 s->first_displayed_entry = entry;
2884 nscrolled++;
2889 static const struct got_error *
2890 trigger_log_thread(struct tog_view *view, int wait)
2892 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2893 int errcode;
2895 if (!using_mock_io)
2896 halfdelay(1); /* fast refresh while loading commits */
2898 while (!ta->log_complete && !tog_thread_error &&
2899 (ta->commits_needed > 0 || ta->load_all)) {
2900 /* Wake the log thread. */
2901 errcode = pthread_cond_signal(&ta->need_commits);
2902 if (errcode)
2903 return got_error_set_errno(errcode,
2904 "pthread_cond_signal");
2907 * The mutex will be released while the view loop waits
2908 * in wgetch(), at which time the log thread will run.
2910 if (!wait)
2911 break;
2913 /* Display progress update in log view. */
2914 show_log_view(view);
2915 update_panels();
2916 doupdate();
2918 /* Wait right here while next commit is being loaded. */
2919 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2920 if (errcode)
2921 return got_error_set_errno(errcode,
2922 "pthread_cond_wait");
2924 /* Display progress update in log view. */
2925 show_log_view(view);
2926 update_panels();
2927 doupdate();
2930 return NULL;
2933 static const struct got_error *
2934 request_log_commits(struct tog_view *view)
2936 struct tog_log_view_state *state = &view->state.log;
2937 const struct got_error *err = NULL;
2939 if (state->thread_args.log_complete)
2940 return NULL;
2942 state->thread_args.commits_needed += view->nscrolled;
2943 err = trigger_log_thread(view, 1);
2944 view->nscrolled = 0;
2946 return err;
2949 static const struct got_error *
2950 log_scroll_down(struct tog_view *view, int maxscroll)
2952 struct tog_log_view_state *s = &view->state.log;
2953 const struct got_error *err = NULL;
2954 struct commit_queue_entry *pentry;
2955 int nscrolled = 0, ncommits_needed;
2957 if (s->last_displayed_entry == NULL)
2958 return NULL;
2960 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2961 if (s->commits->ncommits < ncommits_needed &&
2962 !s->thread_args.log_complete) {
2964 * Ask the log thread for required amount of commits.
2966 s->thread_args.commits_needed +=
2967 ncommits_needed - s->commits->ncommits;
2968 err = trigger_log_thread(view, 1);
2969 if (err)
2970 return err;
2973 do {
2974 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2975 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2976 break;
2978 s->last_displayed_entry = pentry ?
2979 pentry : s->last_displayed_entry;
2981 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2982 if (pentry == NULL)
2983 break;
2984 s->first_displayed_entry = pentry;
2985 } while (++nscrolled < maxscroll);
2987 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2988 view->nscrolled += nscrolled;
2989 else
2990 view->nscrolled = 0;
2992 return err;
2995 static const struct got_error *
2996 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2997 struct got_commit_object *commit, struct got_object_id *commit_id,
2998 struct tog_view *log_view, struct got_repository *repo)
3000 const struct got_error *err;
3001 struct got_object_qid *parent_id;
3002 struct tog_view *diff_view;
3004 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3005 if (diff_view == NULL)
3006 return got_error_from_errno("view_open");
3008 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3009 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3010 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3011 if (err == NULL)
3012 *new_view = diff_view;
3013 return err;
3016 static const struct got_error *
3017 tree_view_visit_subtree(struct tog_tree_view_state *s,
3018 struct got_tree_object *subtree)
3020 struct tog_parent_tree *parent;
3022 parent = calloc(1, sizeof(*parent));
3023 if (parent == NULL)
3024 return got_error_from_errno("calloc");
3026 parent->tree = s->tree;
3027 parent->first_displayed_entry = s->first_displayed_entry;
3028 parent->selected_entry = s->selected_entry;
3029 parent->selected = s->selected;
3030 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3031 s->tree = subtree;
3032 s->selected = 0;
3033 s->first_displayed_entry = NULL;
3034 return NULL;
3037 static const struct got_error *
3038 tree_view_walk_path(struct tog_tree_view_state *s,
3039 struct got_commit_object *commit, const char *path)
3041 const struct got_error *err = NULL;
3042 struct got_tree_object *tree = NULL;
3043 const char *p;
3044 char *slash, *subpath = NULL;
3046 /* Walk the path and open corresponding tree objects. */
3047 p = path;
3048 while (*p) {
3049 struct got_tree_entry *te;
3050 struct got_object_id *tree_id;
3051 char *te_name;
3053 while (p[0] == '/')
3054 p++;
3056 /* Ensure the correct subtree entry is selected. */
3057 slash = strchr(p, '/');
3058 if (slash == NULL)
3059 te_name = strdup(p);
3060 else
3061 te_name = strndup(p, slash - p);
3062 if (te_name == NULL) {
3063 err = got_error_from_errno("strndup");
3064 break;
3066 te = got_object_tree_find_entry(s->tree, te_name);
3067 if (te == NULL) {
3068 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3069 free(te_name);
3070 break;
3072 free(te_name);
3073 s->first_displayed_entry = s->selected_entry = te;
3075 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3076 break; /* jump to this file's entry */
3078 slash = strchr(p, '/');
3079 if (slash)
3080 subpath = strndup(path, slash - path);
3081 else
3082 subpath = strdup(path);
3083 if (subpath == NULL) {
3084 err = got_error_from_errno("strdup");
3085 break;
3088 err = got_object_id_by_path(&tree_id, s->repo, commit,
3089 subpath);
3090 if (err)
3091 break;
3093 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3094 free(tree_id);
3095 if (err)
3096 break;
3098 err = tree_view_visit_subtree(s, tree);
3099 if (err) {
3100 got_object_tree_close(tree);
3101 break;
3103 if (slash == NULL)
3104 break;
3105 free(subpath);
3106 subpath = NULL;
3107 p = slash;
3110 free(subpath);
3111 return err;
3114 static const struct got_error *
3115 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3116 struct commit_queue_entry *entry, const char *path,
3117 const char *head_ref_name, struct got_repository *repo)
3119 const struct got_error *err = NULL;
3120 struct tog_tree_view_state *s;
3121 struct tog_view *tree_view;
3123 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3124 if (tree_view == NULL)
3125 return got_error_from_errno("view_open");
3127 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3128 if (err)
3129 return err;
3130 s = &tree_view->state.tree;
3132 *new_view = tree_view;
3134 if (got_path_is_root_dir(path))
3135 return NULL;
3137 return tree_view_walk_path(s, entry->commit, path);
3140 static const struct got_error *
3141 block_signals_used_by_main_thread(void)
3143 sigset_t sigset;
3144 int errcode;
3146 if (sigemptyset(&sigset) == -1)
3147 return got_error_from_errno("sigemptyset");
3149 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3150 if (sigaddset(&sigset, SIGWINCH) == -1)
3151 return got_error_from_errno("sigaddset");
3152 if (sigaddset(&sigset, SIGCONT) == -1)
3153 return got_error_from_errno("sigaddset");
3154 if (sigaddset(&sigset, SIGINT) == -1)
3155 return got_error_from_errno("sigaddset");
3156 if (sigaddset(&sigset, SIGTERM) == -1)
3157 return got_error_from_errno("sigaddset");
3159 /* ncurses handles SIGTSTP */
3160 if (sigaddset(&sigset, SIGTSTP) == -1)
3161 return got_error_from_errno("sigaddset");
3163 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3164 if (errcode)
3165 return got_error_set_errno(errcode, "pthread_sigmask");
3167 return NULL;
3170 static void *
3171 log_thread(void *arg)
3173 const struct got_error *err = NULL;
3174 int errcode = 0;
3175 struct tog_log_thread_args *a = arg;
3176 int done = 0;
3179 * Sync startup with main thread such that we begin our
3180 * work once view_input() has released the mutex.
3182 errcode = pthread_mutex_lock(&tog_mutex);
3183 if (errcode) {
3184 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3185 return (void *)err;
3188 err = block_signals_used_by_main_thread();
3189 if (err) {
3190 pthread_mutex_unlock(&tog_mutex);
3191 goto done;
3194 while (!done && !err && !tog_fatal_signal_received()) {
3195 errcode = pthread_mutex_unlock(&tog_mutex);
3196 if (errcode) {
3197 err = got_error_set_errno(errcode,
3198 "pthread_mutex_unlock");
3199 goto done;
3201 err = queue_commits(a);
3202 if (err) {
3203 if (err->code != GOT_ERR_ITER_COMPLETED)
3204 goto done;
3205 err = NULL;
3206 done = 1;
3207 } else if (a->commits_needed > 0 && !a->load_all) {
3208 if (*a->limiting) {
3209 if (a->limit_match)
3210 a->commits_needed--;
3211 } else
3212 a->commits_needed--;
3215 errcode = pthread_mutex_lock(&tog_mutex);
3216 if (errcode) {
3217 err = got_error_set_errno(errcode,
3218 "pthread_mutex_lock");
3219 goto done;
3220 } else if (*a->quit)
3221 done = 1;
3222 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3223 *a->first_displayed_entry =
3224 TAILQ_FIRST(&a->limit_commits->head);
3225 *a->selected_entry = *a->first_displayed_entry;
3226 } else if (*a->first_displayed_entry == NULL) {
3227 *a->first_displayed_entry =
3228 TAILQ_FIRST(&a->real_commits->head);
3229 *a->selected_entry = *a->first_displayed_entry;
3232 errcode = pthread_cond_signal(&a->commit_loaded);
3233 if (errcode) {
3234 err = got_error_set_errno(errcode,
3235 "pthread_cond_signal");
3236 pthread_mutex_unlock(&tog_mutex);
3237 goto done;
3240 if (done)
3241 a->commits_needed = 0;
3242 else {
3243 if (a->commits_needed == 0 && !a->load_all) {
3244 errcode = pthread_cond_wait(&a->need_commits,
3245 &tog_mutex);
3246 if (errcode) {
3247 err = got_error_set_errno(errcode,
3248 "pthread_cond_wait");
3249 pthread_mutex_unlock(&tog_mutex);
3250 goto done;
3252 if (*a->quit)
3253 done = 1;
3257 a->log_complete = 1;
3258 errcode = pthread_mutex_unlock(&tog_mutex);
3259 if (errcode)
3260 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3261 done:
3262 if (err) {
3263 tog_thread_error = 1;
3264 pthread_cond_signal(&a->commit_loaded);
3266 return (void *)err;
3269 static const struct got_error *
3270 stop_log_thread(struct tog_log_view_state *s)
3272 const struct got_error *err = NULL, *thread_err = NULL;
3273 int errcode;
3275 if (s->thread) {
3276 s->quit = 1;
3277 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3278 if (errcode)
3279 return got_error_set_errno(errcode,
3280 "pthread_cond_signal");
3281 errcode = pthread_mutex_unlock(&tog_mutex);
3282 if (errcode)
3283 return got_error_set_errno(errcode,
3284 "pthread_mutex_unlock");
3285 errcode = pthread_join(s->thread, (void **)&thread_err);
3286 if (errcode)
3287 return got_error_set_errno(errcode, "pthread_join");
3288 errcode = pthread_mutex_lock(&tog_mutex);
3289 if (errcode)
3290 return got_error_set_errno(errcode,
3291 "pthread_mutex_lock");
3292 s->thread = 0; //NULL;
3295 if (s->thread_args.repo) {
3296 err = got_repo_close(s->thread_args.repo);
3297 s->thread_args.repo = NULL;
3300 if (s->thread_args.pack_fds) {
3301 const struct got_error *pack_err =
3302 got_repo_pack_fds_close(s->thread_args.pack_fds);
3303 if (err == NULL)
3304 err = pack_err;
3305 s->thread_args.pack_fds = NULL;
3308 if (s->thread_args.graph) {
3309 got_commit_graph_close(s->thread_args.graph);
3310 s->thread_args.graph = NULL;
3313 return err ? err : thread_err;
3316 static const struct got_error *
3317 close_log_view(struct tog_view *view)
3319 const struct got_error *err = NULL;
3320 struct tog_log_view_state *s = &view->state.log;
3321 int errcode;
3323 err = stop_log_thread(s);
3325 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3326 if (errcode && err == NULL)
3327 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3329 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3330 if (errcode && err == NULL)
3331 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3333 free_commits(&s->limit_commits);
3334 free_commits(&s->real_commits);
3335 free(s->in_repo_path);
3336 s->in_repo_path = NULL;
3337 free(s->start_id);
3338 s->start_id = NULL;
3339 free(s->head_ref_name);
3340 s->head_ref_name = NULL;
3341 return err;
3345 * We use two queues to implement the limit feature: first consists of
3346 * commits matching the current limit_regex; second is the real queue
3347 * of all known commits (real_commits). When the user starts limiting,
3348 * we swap queues such that all movement and displaying functionality
3349 * works with very slight change.
3351 static const struct got_error *
3352 limit_log_view(struct tog_view *view)
3354 struct tog_log_view_state *s = &view->state.log;
3355 struct commit_queue_entry *entry;
3356 struct tog_view *v = view;
3357 const struct got_error *err = NULL;
3358 char pattern[1024];
3359 int ret;
3361 if (view_is_hsplit_top(view))
3362 v = view->child;
3363 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3364 v = view->parent;
3366 /* Get the pattern */
3367 wmove(v->window, v->nlines - 1, 0);
3368 wclrtoeol(v->window);
3369 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3370 nodelay(v->window, FALSE);
3371 nocbreak();
3372 echo();
3373 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3374 cbreak();
3375 noecho();
3376 nodelay(v->window, TRUE);
3377 if (ret == ERR)
3378 return NULL;
3380 if (*pattern == '\0') {
3382 * Safety measure for the situation where the user
3383 * resets limit without previously limiting anything.
3385 if (!s->limit_view)
3386 return NULL;
3389 * User could have pressed Ctrl+L, which refreshed the
3390 * commit queues, it means we can't save previously
3391 * (before limit took place) displayed entries,
3392 * because they would point to already free'ed memory,
3393 * so we are forced to always select first entry of
3394 * the queue.
3396 s->commits = &s->real_commits;
3397 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3398 s->selected_entry = s->first_displayed_entry;
3399 s->selected = 0;
3400 s->limit_view = 0;
3402 return NULL;
3405 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3406 return NULL;
3408 s->limit_view = 1;
3410 /* Clear the screen while loading limit view */
3411 s->first_displayed_entry = NULL;
3412 s->last_displayed_entry = NULL;
3413 s->selected_entry = NULL;
3414 s->commits = &s->limit_commits;
3416 /* Prepare limit queue for new search */
3417 free_commits(&s->limit_commits);
3418 s->limit_commits.ncommits = 0;
3420 /* First process commits, which are in queue already */
3421 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3422 int have_match = 0;
3424 err = match_commit(&have_match, entry->id,
3425 entry->commit, &s->limit_regex);
3426 if (err)
3427 return err;
3429 if (have_match) {
3430 struct commit_queue_entry *matched;
3432 matched = alloc_commit_queue_entry(entry->commit,
3433 entry->id);
3434 if (matched == NULL) {
3435 err = got_error_from_errno(
3436 "alloc_commit_queue_entry");
3437 break;
3439 matched->commit = entry->commit;
3440 got_object_commit_retain(entry->commit);
3442 matched->idx = s->limit_commits.ncommits;
3443 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3444 matched, entry);
3445 s->limit_commits.ncommits++;
3449 /* Second process all the commits, until we fill the screen */
3450 if (s->limit_commits.ncommits < view->nlines - 1 &&
3451 !s->thread_args.log_complete) {
3452 s->thread_args.commits_needed +=
3453 view->nlines - s->limit_commits.ncommits - 1;
3454 err = trigger_log_thread(view, 1);
3455 if (err)
3456 return err;
3459 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3460 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3461 s->selected = 0;
3463 return NULL;
3466 static const struct got_error *
3467 search_start_log_view(struct tog_view *view)
3469 struct tog_log_view_state *s = &view->state.log;
3471 s->matched_entry = NULL;
3472 s->search_entry = NULL;
3473 return NULL;
3476 static const struct got_error *
3477 search_next_log_view(struct tog_view *view)
3479 const struct got_error *err = NULL;
3480 struct tog_log_view_state *s = &view->state.log;
3481 struct commit_queue_entry *entry;
3483 /* Display progress update in log view. */
3484 show_log_view(view);
3485 update_panels();
3486 doupdate();
3488 if (s->search_entry) {
3489 int errcode, ch;
3490 errcode = pthread_mutex_unlock(&tog_mutex);
3491 if (errcode)
3492 return got_error_set_errno(errcode,
3493 "pthread_mutex_unlock");
3494 ch = wgetch(view->window);
3495 errcode = pthread_mutex_lock(&tog_mutex);
3496 if (errcode)
3497 return got_error_set_errno(errcode,
3498 "pthread_mutex_lock");
3499 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3500 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3501 return NULL;
3503 if (view->searching == TOG_SEARCH_FORWARD)
3504 entry = TAILQ_NEXT(s->search_entry, entry);
3505 else
3506 entry = TAILQ_PREV(s->search_entry,
3507 commit_queue_head, entry);
3508 } else if (s->matched_entry) {
3510 * If the user has moved the cursor after we hit a match,
3511 * the position from where we should continue searching
3512 * might have changed.
3514 if (view->searching == TOG_SEARCH_FORWARD)
3515 entry = TAILQ_NEXT(s->selected_entry, entry);
3516 else
3517 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3518 entry);
3519 } else {
3520 entry = s->selected_entry;
3523 while (1) {
3524 int have_match = 0;
3526 if (entry == NULL) {
3527 if (s->thread_args.log_complete ||
3528 view->searching == TOG_SEARCH_BACKWARD) {
3529 view->search_next_done =
3530 (s->matched_entry == NULL ?
3531 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3532 s->search_entry = NULL;
3533 return NULL;
3536 * Poke the log thread for more commits and return,
3537 * allowing the main loop to make progress. Search
3538 * will resume at s->search_entry once we come back.
3540 s->thread_args.commits_needed++;
3541 return trigger_log_thread(view, 0);
3544 err = match_commit(&have_match, entry->id, entry->commit,
3545 &view->regex);
3546 if (err)
3547 break;
3548 if (have_match) {
3549 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3550 s->matched_entry = entry;
3551 break;
3554 s->search_entry = entry;
3555 if (view->searching == TOG_SEARCH_FORWARD)
3556 entry = TAILQ_NEXT(entry, entry);
3557 else
3558 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3561 if (s->matched_entry) {
3562 int cur = s->selected_entry->idx;
3563 while (cur < s->matched_entry->idx) {
3564 err = input_log_view(NULL, view, KEY_DOWN);
3565 if (err)
3566 return err;
3567 cur++;
3569 while (cur > s->matched_entry->idx) {
3570 err = input_log_view(NULL, view, KEY_UP);
3571 if (err)
3572 return err;
3573 cur--;
3577 s->search_entry = NULL;
3579 return NULL;
3582 static const struct got_error *
3583 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3584 struct got_repository *repo, const char *head_ref_name,
3585 const char *in_repo_path, int log_branches)
3587 const struct got_error *err = NULL;
3588 struct tog_log_view_state *s = &view->state.log;
3589 struct got_repository *thread_repo = NULL;
3590 struct got_commit_graph *thread_graph = NULL;
3591 int errcode;
3593 if (in_repo_path != s->in_repo_path) {
3594 free(s->in_repo_path);
3595 s->in_repo_path = strdup(in_repo_path);
3596 if (s->in_repo_path == NULL) {
3597 err = got_error_from_errno("strdup");
3598 goto done;
3602 /* The commit queue only contains commits being displayed. */
3603 TAILQ_INIT(&s->real_commits.head);
3604 s->real_commits.ncommits = 0;
3605 s->commits = &s->real_commits;
3607 TAILQ_INIT(&s->limit_commits.head);
3608 s->limit_view = 0;
3609 s->limit_commits.ncommits = 0;
3611 s->repo = repo;
3612 if (head_ref_name) {
3613 s->head_ref_name = strdup(head_ref_name);
3614 if (s->head_ref_name == NULL) {
3615 err = got_error_from_errno("strdup");
3616 goto done;
3619 s->start_id = got_object_id_dup(start_id);
3620 if (s->start_id == NULL) {
3621 err = got_error_from_errno("got_object_id_dup");
3622 goto done;
3624 s->log_branches = log_branches;
3625 s->use_committer = 1;
3627 STAILQ_INIT(&s->colors);
3628 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3629 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3630 get_color_value("TOG_COLOR_COMMIT"));
3631 if (err)
3632 goto done;
3633 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3634 get_color_value("TOG_COLOR_AUTHOR"));
3635 if (err) {
3636 free_colors(&s->colors);
3637 goto done;
3639 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3640 get_color_value("TOG_COLOR_DATE"));
3641 if (err) {
3642 free_colors(&s->colors);
3643 goto done;
3647 view->show = show_log_view;
3648 view->input = input_log_view;
3649 view->resize = resize_log_view;
3650 view->close = close_log_view;
3651 view->search_start = search_start_log_view;
3652 view->search_next = search_next_log_view;
3654 if (s->thread_args.pack_fds == NULL) {
3655 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3656 if (err)
3657 goto done;
3659 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3660 s->thread_args.pack_fds);
3661 if (err)
3662 goto done;
3663 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3664 !s->log_branches);
3665 if (err)
3666 goto done;
3667 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3668 s->repo, NULL, NULL);
3669 if (err)
3670 goto done;
3672 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3673 if (errcode) {
3674 err = got_error_set_errno(errcode, "pthread_cond_init");
3675 goto done;
3677 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3678 if (errcode) {
3679 err = got_error_set_errno(errcode, "pthread_cond_init");
3680 goto done;
3683 s->thread_args.commits_needed = view->nlines;
3684 s->thread_args.graph = thread_graph;
3685 s->thread_args.real_commits = &s->real_commits;
3686 s->thread_args.limit_commits = &s->limit_commits;
3687 s->thread_args.in_repo_path = s->in_repo_path;
3688 s->thread_args.start_id = s->start_id;
3689 s->thread_args.repo = thread_repo;
3690 s->thread_args.log_complete = 0;
3691 s->thread_args.quit = &s->quit;
3692 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3693 s->thread_args.selected_entry = &s->selected_entry;
3694 s->thread_args.searching = &view->searching;
3695 s->thread_args.search_next_done = &view->search_next_done;
3696 s->thread_args.regex = &view->regex;
3697 s->thread_args.limiting = &s->limit_view;
3698 s->thread_args.limit_regex = &s->limit_regex;
3699 s->thread_args.limit_commits = &s->limit_commits;
3700 done:
3701 if (err) {
3702 if (view->close == NULL)
3703 close_log_view(view);
3704 view_close(view);
3706 return err;
3709 static const struct got_error *
3710 show_log_view(struct tog_view *view)
3712 const struct got_error *err;
3713 struct tog_log_view_state *s = &view->state.log;
3715 if (s->thread == 0) { //NULL) {
3716 int errcode = pthread_create(&s->thread, NULL, log_thread,
3717 &s->thread_args);
3718 if (errcode)
3719 return got_error_set_errno(errcode, "pthread_create");
3720 if (s->thread_args.commits_needed > 0) {
3721 err = trigger_log_thread(view, 1);
3722 if (err)
3723 return err;
3727 return draw_commits(view);
3730 static void
3731 log_move_cursor_up(struct tog_view *view, int page, int home)
3733 struct tog_log_view_state *s = &view->state.log;
3735 if (s->first_displayed_entry == NULL)
3736 return;
3737 if (s->selected_entry->idx == 0)
3738 view->count = 0;
3740 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3741 || home)
3742 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3744 if (!page && !home && s->selected > 0)
3745 --s->selected;
3746 else
3747 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3749 select_commit(s);
3750 return;
3753 static const struct got_error *
3754 log_move_cursor_down(struct tog_view *view, int page)
3756 struct tog_log_view_state *s = &view->state.log;
3757 const struct got_error *err = NULL;
3758 int eos = view->nlines - 2;
3760 if (s->first_displayed_entry == NULL)
3761 return NULL;
3763 if (s->thread_args.log_complete &&
3764 s->selected_entry->idx >= s->commits->ncommits - 1)
3765 return NULL;
3767 if (view_is_hsplit_top(view))
3768 --eos; /* border consumes the last line */
3770 if (!page) {
3771 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3772 ++s->selected;
3773 else
3774 err = log_scroll_down(view, 1);
3775 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3776 struct commit_queue_entry *entry;
3777 int n;
3779 s->selected = 0;
3780 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3781 s->last_displayed_entry = entry;
3782 for (n = 0; n <= eos; n++) {
3783 if (entry == NULL)
3784 break;
3785 s->first_displayed_entry = entry;
3786 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3788 if (n > 0)
3789 s->selected = n - 1;
3790 } else {
3791 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3792 s->thread_args.log_complete)
3793 s->selected += MIN(page,
3794 s->commits->ncommits - s->selected_entry->idx - 1);
3795 else
3796 err = log_scroll_down(view, page);
3798 if (err)
3799 return err;
3802 * We might necessarily overshoot in horizontal
3803 * splits; if so, select the last displayed commit.
3805 if (s->first_displayed_entry && s->last_displayed_entry) {
3806 s->selected = MIN(s->selected,
3807 s->last_displayed_entry->idx -
3808 s->first_displayed_entry->idx);
3811 select_commit(s);
3813 if (s->thread_args.log_complete &&
3814 s->selected_entry->idx == s->commits->ncommits - 1)
3815 view->count = 0;
3817 return NULL;
3820 static void
3821 view_get_split(struct tog_view *view, int *y, int *x)
3823 *x = 0;
3824 *y = 0;
3826 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3827 if (view->child && view->child->resized_y)
3828 *y = view->child->resized_y;
3829 else if (view->resized_y)
3830 *y = view->resized_y;
3831 else
3832 *y = view_split_begin_y(view->lines);
3833 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3834 if (view->child && view->child->resized_x)
3835 *x = view->child->resized_x;
3836 else if (view->resized_x)
3837 *x = view->resized_x;
3838 else
3839 *x = view_split_begin_x(view->begin_x);
3843 /* Split view horizontally at y and offset view->state->selected line. */
3844 static const struct got_error *
3845 view_init_hsplit(struct tog_view *view, int y)
3847 const struct got_error *err = NULL;
3849 view->nlines = y;
3850 view->ncols = COLS;
3851 err = view_resize(view);
3852 if (err)
3853 return err;
3855 err = offset_selection_down(view);
3857 return err;
3860 static const struct got_error *
3861 log_goto_line(struct tog_view *view, int nlines)
3863 const struct got_error *err = NULL;
3864 struct tog_log_view_state *s = &view->state.log;
3865 int g, idx = s->selected_entry->idx;
3867 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3868 return NULL;
3870 g = view->gline;
3871 view->gline = 0;
3873 if (g >= s->first_displayed_entry->idx + 1 &&
3874 g <= s->last_displayed_entry->idx + 1 &&
3875 g - s->first_displayed_entry->idx - 1 < nlines) {
3876 s->selected = g - s->first_displayed_entry->idx - 1;
3877 select_commit(s);
3878 return NULL;
3881 if (idx + 1 < g) {
3882 err = log_move_cursor_down(view, g - idx - 1);
3883 if (!err && g > s->selected_entry->idx + 1)
3884 err = log_move_cursor_down(view,
3885 g - s->first_displayed_entry->idx - 1);
3886 if (err)
3887 return err;
3888 } else if (idx + 1 > g)
3889 log_move_cursor_up(view, idx - g + 1, 0);
3891 if (g < nlines && s->first_displayed_entry->idx == 0)
3892 s->selected = g - 1;
3894 select_commit(s);
3895 return NULL;
3899 static void
3900 horizontal_scroll_input(struct tog_view *view, int ch)
3903 switch (ch) {
3904 case KEY_LEFT:
3905 case 'h':
3906 view->x -= MIN(view->x, 2);
3907 if (view->x <= 0)
3908 view->count = 0;
3909 break;
3910 case KEY_RIGHT:
3911 case 'l':
3912 if (view->x + view->ncols / 2 < view->maxx)
3913 view->x += 2;
3914 else
3915 view->count = 0;
3916 break;
3917 case '0':
3918 view->x = 0;
3919 break;
3920 case '$':
3921 view->x = MAX(view->maxx - view->ncols / 2, 0);
3922 view->count = 0;
3923 break;
3924 default:
3925 break;
3929 static const struct got_error *
3930 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3932 const struct got_error *err = NULL;
3933 struct tog_log_view_state *s = &view->state.log;
3934 int eos, nscroll;
3936 if (s->thread_args.load_all) {
3937 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3938 s->thread_args.load_all = 0;
3939 else if (s->thread_args.log_complete) {
3940 err = log_move_cursor_down(view, s->commits->ncommits);
3941 s->thread_args.load_all = 0;
3943 if (err)
3944 return err;
3947 eos = nscroll = view->nlines - 1;
3948 if (view_is_hsplit_top(view))
3949 --eos; /* border */
3951 if (view->gline)
3952 return log_goto_line(view, eos);
3954 switch (ch) {
3955 case '&':
3956 err = limit_log_view(view);
3957 break;
3958 case 'q':
3959 s->quit = 1;
3960 break;
3961 case '0':
3962 case '$':
3963 case KEY_RIGHT:
3964 case 'l':
3965 case KEY_LEFT:
3966 case 'h':
3967 horizontal_scroll_input(view, ch);
3968 break;
3969 case 'k':
3970 case KEY_UP:
3971 case '<':
3972 case ',':
3973 case CTRL('p'):
3974 log_move_cursor_up(view, 0, 0);
3975 break;
3976 case 'g':
3977 case '=':
3978 case KEY_HOME:
3979 log_move_cursor_up(view, 0, 1);
3980 view->count = 0;
3981 break;
3982 case CTRL('u'):
3983 case 'u':
3984 nscroll /= 2;
3985 /* FALL THROUGH */
3986 case KEY_PPAGE:
3987 case CTRL('b'):
3988 case 'b':
3989 log_move_cursor_up(view, nscroll, 0);
3990 break;
3991 case 'j':
3992 case KEY_DOWN:
3993 case '>':
3994 case '.':
3995 case CTRL('n'):
3996 err = log_move_cursor_down(view, 0);
3997 break;
3998 case '@':
3999 s->use_committer = !s->use_committer;
4000 view->action = s->use_committer ?
4001 "show committer" : "show commit author";
4002 break;
4003 case 'G':
4004 case '*':
4005 case KEY_END: {
4006 /* We don't know yet how many commits, so we're forced to
4007 * traverse them all. */
4008 view->count = 0;
4009 s->thread_args.load_all = 1;
4010 if (!s->thread_args.log_complete)
4011 return trigger_log_thread(view, 0);
4012 err = log_move_cursor_down(view, s->commits->ncommits);
4013 s->thread_args.load_all = 0;
4014 break;
4016 case CTRL('d'):
4017 case 'd':
4018 nscroll /= 2;
4019 /* FALL THROUGH */
4020 case KEY_NPAGE:
4021 case CTRL('f'):
4022 case 'f':
4023 case ' ':
4024 err = log_move_cursor_down(view, nscroll);
4025 break;
4026 case KEY_RESIZE:
4027 if (s->selected > view->nlines - 2)
4028 s->selected = view->nlines - 2;
4029 if (s->selected > s->commits->ncommits - 1)
4030 s->selected = s->commits->ncommits - 1;
4031 select_commit(s);
4032 if (s->commits->ncommits < view->nlines - 1 &&
4033 !s->thread_args.log_complete) {
4034 s->thread_args.commits_needed += (view->nlines - 1) -
4035 s->commits->ncommits;
4036 err = trigger_log_thread(view, 1);
4038 break;
4039 case KEY_ENTER:
4040 case '\r':
4041 view->count = 0;
4042 if (s->selected_entry == NULL)
4043 break;
4044 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4045 break;
4046 case 'T':
4047 view->count = 0;
4048 if (s->selected_entry == NULL)
4049 break;
4050 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4051 break;
4052 case KEY_BACKSPACE:
4053 case CTRL('l'):
4054 case 'B':
4055 view->count = 0;
4056 if (ch == KEY_BACKSPACE &&
4057 got_path_is_root_dir(s->in_repo_path))
4058 break;
4059 err = stop_log_thread(s);
4060 if (err)
4061 return err;
4062 if (ch == KEY_BACKSPACE) {
4063 char *parent_path;
4064 err = got_path_dirname(&parent_path, s->in_repo_path);
4065 if (err)
4066 return err;
4067 free(s->in_repo_path);
4068 s->in_repo_path = parent_path;
4069 s->thread_args.in_repo_path = s->in_repo_path;
4070 } else if (ch == CTRL('l')) {
4071 struct got_object_id *start_id;
4072 err = got_repo_match_object_id(&start_id, NULL,
4073 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4074 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4075 if (err) {
4076 if (s->head_ref_name == NULL ||
4077 err->code != GOT_ERR_NOT_REF)
4078 return err;
4079 /* Try to cope with deleted references. */
4080 free(s->head_ref_name);
4081 s->head_ref_name = NULL;
4082 err = got_repo_match_object_id(&start_id,
4083 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4084 &tog_refs, s->repo);
4085 if (err)
4086 return err;
4088 free(s->start_id);
4089 s->start_id = start_id;
4090 s->thread_args.start_id = s->start_id;
4091 } else /* 'B' */
4092 s->log_branches = !s->log_branches;
4094 if (s->thread_args.pack_fds == NULL) {
4095 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4096 if (err)
4097 return err;
4099 err = got_repo_open(&s->thread_args.repo,
4100 got_repo_get_path(s->repo), NULL,
4101 s->thread_args.pack_fds);
4102 if (err)
4103 return err;
4104 tog_free_refs();
4105 err = tog_load_refs(s->repo, 0);
4106 if (err)
4107 return err;
4108 err = got_commit_graph_open(&s->thread_args.graph,
4109 s->in_repo_path, !s->log_branches);
4110 if (err)
4111 return err;
4112 err = got_commit_graph_iter_start(s->thread_args.graph,
4113 s->start_id, s->repo, NULL, NULL);
4114 if (err)
4115 return err;
4116 free_commits(&s->real_commits);
4117 free_commits(&s->limit_commits);
4118 s->first_displayed_entry = NULL;
4119 s->last_displayed_entry = NULL;
4120 s->selected_entry = NULL;
4121 s->selected = 0;
4122 s->thread_args.log_complete = 0;
4123 s->quit = 0;
4124 s->thread_args.commits_needed = view->lines;
4125 s->matched_entry = NULL;
4126 s->search_entry = NULL;
4127 view->offset = 0;
4128 break;
4129 case 'R':
4130 view->count = 0;
4131 err = view_request_new(new_view, view, TOG_VIEW_REF);
4132 break;
4133 default:
4134 view->count = 0;
4135 break;
4138 return err;
4141 static const struct got_error *
4142 apply_unveil(const char *repo_path, const char *worktree_path)
4144 const struct got_error *error;
4146 #ifdef PROFILE
4147 if (unveil("gmon.out", "rwc") != 0)
4148 return got_error_from_errno2("unveil", "gmon.out");
4149 #endif
4150 if (repo_path && unveil(repo_path, "r") != 0)
4151 return got_error_from_errno2("unveil", repo_path);
4153 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4154 return got_error_from_errno2("unveil", worktree_path);
4156 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4157 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4159 error = got_privsep_unveil_exec_helpers();
4160 if (error != NULL)
4161 return error;
4163 if (unveil(NULL, NULL) != 0)
4164 return got_error_from_errno("unveil");
4166 return NULL;
4169 static const struct got_error *
4170 init_mock_term(const char *test_script_path)
4172 const struct got_error *err = NULL;
4174 if (test_script_path == NULL || *test_script_path == '\0')
4175 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4177 tog_io.f = fopen(test_script_path, "re");
4178 if (tog_io.f == NULL) {
4179 err = got_error_from_errno_fmt("fopen: %s",
4180 test_script_path);
4181 goto done;
4184 /* test mode, we don't want any output */
4185 tog_io.cout = fopen("/dev/null", "w+");
4186 if (tog_io.cout == NULL) {
4187 err = got_error_from_errno("fopen: /dev/null");
4188 goto done;
4191 tog_io.cin = fopen("/dev/tty", "r+");
4192 if (tog_io.cin == NULL) {
4193 err = got_error_from_errno("fopen: /dev/tty");
4194 goto done;
4197 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4198 err = got_error_from_errno("fseeko");
4199 goto done;
4202 /* use local TERM so we test in different environments */
4203 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4204 err = got_error_msg(GOT_ERR_IO,
4205 "newterm: failed to initialise curses");
4207 using_mock_io = 1;
4208 done:
4209 if (err)
4210 tog_io_close();
4211 return err;
4214 static void
4215 init_curses(void)
4218 * Override default signal handlers before starting ncurses.
4219 * This should prevent ncurses from installing its own
4220 * broken cleanup() signal handler.
4222 signal(SIGWINCH, tog_sigwinch);
4223 signal(SIGPIPE, tog_sigpipe);
4224 signal(SIGCONT, tog_sigcont);
4225 signal(SIGINT, tog_sigint);
4226 signal(SIGTERM, tog_sigterm);
4228 if (using_mock_io) /* In test mode we use a fake terminal */
4229 return;
4231 initscr();
4233 cbreak();
4234 halfdelay(1); /* Fast refresh while initial view is loading. */
4235 noecho();
4236 nonl();
4237 intrflush(stdscr, FALSE);
4238 keypad(stdscr, TRUE);
4239 curs_set(0);
4240 if (getenv("TOG_COLORS") != NULL) {
4241 start_color();
4242 use_default_colors();
4245 return;
4248 static const struct got_error *
4249 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4250 struct got_repository *repo, struct got_worktree *worktree)
4252 const struct got_error *err = NULL;
4254 if (argc == 0) {
4255 *in_repo_path = strdup("/");
4256 if (*in_repo_path == NULL)
4257 return got_error_from_errno("strdup");
4258 return NULL;
4261 if (worktree) {
4262 const char *prefix = got_worktree_get_path_prefix(worktree);
4263 char *p;
4265 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4266 if (err)
4267 return err;
4268 if (asprintf(in_repo_path, "%s%s%s", prefix,
4269 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4270 p) == -1) {
4271 err = got_error_from_errno("asprintf");
4272 *in_repo_path = NULL;
4274 free(p);
4275 } else
4276 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4278 return err;
4281 static const struct got_error *
4282 cmd_log(int argc, char *argv[])
4284 const struct got_error *error;
4285 struct got_repository *repo = NULL;
4286 struct got_worktree *worktree = NULL;
4287 struct got_object_id *start_id = NULL;
4288 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4289 char *start_commit = NULL, *label = NULL;
4290 struct got_reference *ref = NULL;
4291 const char *head_ref_name = NULL;
4292 int ch, log_branches = 0;
4293 struct tog_view *view;
4294 int *pack_fds = NULL;
4296 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4297 switch (ch) {
4298 case 'b':
4299 log_branches = 1;
4300 break;
4301 case 'c':
4302 start_commit = optarg;
4303 break;
4304 case 'r':
4305 repo_path = realpath(optarg, NULL);
4306 if (repo_path == NULL)
4307 return got_error_from_errno2("realpath",
4308 optarg);
4309 break;
4310 default:
4311 usage_log();
4312 /* NOTREACHED */
4316 argc -= optind;
4317 argv += optind;
4319 if (argc > 1)
4320 usage_log();
4322 error = got_repo_pack_fds_open(&pack_fds);
4323 if (error != NULL)
4324 goto done;
4326 if (repo_path == NULL) {
4327 cwd = getcwd(NULL, 0);
4328 if (cwd == NULL)
4329 return got_error_from_errno("getcwd");
4330 error = got_worktree_open(&worktree, cwd);
4331 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4332 goto done;
4333 if (worktree)
4334 repo_path =
4335 strdup(got_worktree_get_repo_path(worktree));
4336 else
4337 repo_path = strdup(cwd);
4338 if (repo_path == NULL) {
4339 error = got_error_from_errno("strdup");
4340 goto done;
4344 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4345 if (error != NULL)
4346 goto done;
4348 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4349 repo, worktree);
4350 if (error)
4351 goto done;
4353 init_curses();
4355 error = apply_unveil(got_repo_get_path(repo),
4356 worktree ? got_worktree_get_root_path(worktree) : NULL);
4357 if (error)
4358 goto done;
4360 /* already loaded by tog_log_with_path()? */
4361 if (TAILQ_EMPTY(&tog_refs)) {
4362 error = tog_load_refs(repo, 0);
4363 if (error)
4364 goto done;
4367 if (start_commit == NULL) {
4368 error = got_repo_match_object_id(&start_id, &label,
4369 worktree ? got_worktree_get_head_ref_name(worktree) :
4370 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4371 if (error)
4372 goto done;
4373 head_ref_name = label;
4374 } else {
4375 error = got_ref_open(&ref, repo, start_commit, 0);
4376 if (error == NULL)
4377 head_ref_name = got_ref_get_name(ref);
4378 else if (error->code != GOT_ERR_NOT_REF)
4379 goto done;
4380 error = got_repo_match_object_id(&start_id, NULL,
4381 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4382 if (error)
4383 goto done;
4386 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4387 if (view == NULL) {
4388 error = got_error_from_errno("view_open");
4389 goto done;
4391 error = open_log_view(view, start_id, repo, head_ref_name,
4392 in_repo_path, log_branches);
4393 if (error)
4394 goto done;
4395 if (worktree) {
4396 /* Release work tree lock. */
4397 got_worktree_close(worktree);
4398 worktree = NULL;
4400 error = view_loop(view);
4401 done:
4402 free(in_repo_path);
4403 free(repo_path);
4404 free(cwd);
4405 free(start_id);
4406 free(label);
4407 if (ref)
4408 got_ref_close(ref);
4409 if (repo) {
4410 const struct got_error *close_err = got_repo_close(repo);
4411 if (error == NULL)
4412 error = close_err;
4414 if (worktree)
4415 got_worktree_close(worktree);
4416 if (pack_fds) {
4417 const struct got_error *pack_err =
4418 got_repo_pack_fds_close(pack_fds);
4419 if (error == NULL)
4420 error = pack_err;
4422 tog_free_refs();
4423 return error;
4426 __dead static void
4427 usage_diff(void)
4429 endwin();
4430 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4431 "object1 object2\n", getprogname());
4432 exit(1);
4435 static int
4436 match_line(const char *line, regex_t *regex, size_t nmatch,
4437 regmatch_t *regmatch)
4439 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4442 static struct tog_color *
4443 match_color(struct tog_colors *colors, const char *line)
4445 struct tog_color *tc = NULL;
4447 STAILQ_FOREACH(tc, colors, entry) {
4448 if (match_line(line, &tc->regex, 0, NULL))
4449 return tc;
4452 return NULL;
4455 static const struct got_error *
4456 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4457 WINDOW *window, int skipcol, regmatch_t *regmatch)
4459 const struct got_error *err = NULL;
4460 char *exstr = NULL;
4461 wchar_t *wline = NULL;
4462 int rme, rms, n, width, scrollx;
4463 int width0 = 0, width1 = 0, width2 = 0;
4464 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4466 *wtotal = 0;
4468 rms = regmatch->rm_so;
4469 rme = regmatch->rm_eo;
4471 err = expand_tab(&exstr, line);
4472 if (err)
4473 return err;
4475 /* Split the line into 3 segments, according to match offsets. */
4476 seg0 = strndup(exstr, rms);
4477 if (seg0 == NULL) {
4478 err = got_error_from_errno("strndup");
4479 goto done;
4481 seg1 = strndup(exstr + rms, rme - rms);
4482 if (seg1 == NULL) {
4483 err = got_error_from_errno("strndup");
4484 goto done;
4486 seg2 = strdup(exstr + rme);
4487 if (seg2 == NULL) {
4488 err = got_error_from_errno("strndup");
4489 goto done;
4492 /* draw up to matched token if we haven't scrolled past it */
4493 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4494 col_tab_align, 1);
4495 if (err)
4496 goto done;
4497 n = MAX(width0 - skipcol, 0);
4498 if (n) {
4499 free(wline);
4500 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4501 wlimit, col_tab_align, 1);
4502 if (err)
4503 goto done;
4504 waddwstr(window, &wline[scrollx]);
4505 wlimit -= width;
4506 *wtotal += width;
4509 if (wlimit > 0) {
4510 int i = 0, w = 0;
4511 size_t wlen;
4513 free(wline);
4514 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4515 col_tab_align, 1);
4516 if (err)
4517 goto done;
4518 wlen = wcslen(wline);
4519 while (i < wlen) {
4520 width = wcwidth(wline[i]);
4521 if (width == -1) {
4522 /* should not happen, tabs are expanded */
4523 err = got_error(GOT_ERR_RANGE);
4524 goto done;
4526 if (width0 + w + width > skipcol)
4527 break;
4528 w += width;
4529 i++;
4531 /* draw (visible part of) matched token (if scrolled into it) */
4532 if (width1 - w > 0) {
4533 wattron(window, A_STANDOUT);
4534 waddwstr(window, &wline[i]);
4535 wattroff(window, A_STANDOUT);
4536 wlimit -= (width1 - w);
4537 *wtotal += (width1 - w);
4541 if (wlimit > 0) { /* draw rest of line */
4542 free(wline);
4543 if (skipcol > width0 + width1) {
4544 err = format_line(&wline, &width2, &scrollx, seg2,
4545 skipcol - (width0 + width1), wlimit,
4546 col_tab_align, 1);
4547 if (err)
4548 goto done;
4549 waddwstr(window, &wline[scrollx]);
4550 } else {
4551 err = format_line(&wline, &width2, NULL, seg2, 0,
4552 wlimit, col_tab_align, 1);
4553 if (err)
4554 goto done;
4555 waddwstr(window, wline);
4557 *wtotal += width2;
4559 done:
4560 free(wline);
4561 free(exstr);
4562 free(seg0);
4563 free(seg1);
4564 free(seg2);
4565 return err;
4568 static int
4569 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4571 FILE *f = NULL;
4572 int *eof, *first, *selected;
4574 if (view->type == TOG_VIEW_DIFF) {
4575 struct tog_diff_view_state *s = &view->state.diff;
4577 first = &s->first_displayed_line;
4578 selected = first;
4579 eof = &s->eof;
4580 f = s->f;
4581 } else if (view->type == TOG_VIEW_HELP) {
4582 struct tog_help_view_state *s = &view->state.help;
4584 first = &s->first_displayed_line;
4585 selected = first;
4586 eof = &s->eof;
4587 f = s->f;
4588 } else if (view->type == TOG_VIEW_BLAME) {
4589 struct tog_blame_view_state *s = &view->state.blame;
4591 first = &s->first_displayed_line;
4592 selected = &s->selected_line;
4593 eof = &s->eof;
4594 f = s->blame.f;
4595 } else
4596 return 0;
4598 /* Center gline in the middle of the page like vi(1). */
4599 if (*lineno < view->gline - (view->nlines - 3) / 2)
4600 return 0;
4601 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4602 rewind(f);
4603 *eof = 0;
4604 *first = 1;
4605 *lineno = 0;
4606 *nprinted = 0;
4607 return 0;
4610 *selected = view->gline <= (view->nlines - 3) / 2 ?
4611 view->gline : (view->nlines - 3) / 2 + 1;
4612 view->gline = 0;
4614 return 1;
4617 static const struct got_error *
4618 draw_file(struct tog_view *view, const char *header)
4620 struct tog_diff_view_state *s = &view->state.diff;
4621 regmatch_t *regmatch = &view->regmatch;
4622 const struct got_error *err;
4623 int nprinted = 0;
4624 char *line;
4625 size_t linesize = 0;
4626 ssize_t linelen;
4627 wchar_t *wline;
4628 int width;
4629 int max_lines = view->nlines;
4630 int nlines = s->nlines;
4631 off_t line_offset;
4633 s->lineno = s->first_displayed_line - 1;
4634 line_offset = s->lines[s->first_displayed_line - 1].offset;
4635 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4636 return got_error_from_errno("fseek");
4638 werase(view->window);
4640 if (view->gline > s->nlines - 1)
4641 view->gline = s->nlines - 1;
4643 if (header) {
4644 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4645 1 : view->gline - (view->nlines - 3) / 2 :
4646 s->lineno + s->selected_line;
4648 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4649 return got_error_from_errno("asprintf");
4650 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4651 0, 0);
4652 free(line);
4653 if (err)
4654 return err;
4656 if (view_needs_focus_indication(view))
4657 wstandout(view->window);
4658 waddwstr(view->window, wline);
4659 free(wline);
4660 wline = NULL;
4661 while (width++ < view->ncols)
4662 waddch(view->window, ' ');
4663 if (view_needs_focus_indication(view))
4664 wstandend(view->window);
4666 if (max_lines <= 1)
4667 return NULL;
4668 max_lines--;
4671 s->eof = 0;
4672 view->maxx = 0;
4673 line = NULL;
4674 while (max_lines > 0 && nprinted < max_lines) {
4675 enum got_diff_line_type linetype;
4676 attr_t attr = 0;
4678 linelen = getline(&line, &linesize, s->f);
4679 if (linelen == -1) {
4680 if (feof(s->f)) {
4681 s->eof = 1;
4682 break;
4684 free(line);
4685 return got_ferror(s->f, GOT_ERR_IO);
4688 if (++s->lineno < s->first_displayed_line)
4689 continue;
4690 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4691 continue;
4692 if (s->lineno == view->hiline)
4693 attr = A_STANDOUT;
4695 /* Set view->maxx based on full line length. */
4696 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4697 view->x ? 1 : 0);
4698 if (err) {
4699 free(line);
4700 return err;
4702 view->maxx = MAX(view->maxx, width);
4703 free(wline);
4704 wline = NULL;
4706 linetype = s->lines[s->lineno].type;
4707 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4708 linetype < GOT_DIFF_LINE_CONTEXT)
4709 attr |= COLOR_PAIR(linetype);
4710 if (attr)
4711 wattron(view->window, attr);
4712 if (s->first_displayed_line + nprinted == s->matched_line &&
4713 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4714 err = add_matched_line(&width, line, view->ncols, 0,
4715 view->window, view->x, regmatch);
4716 if (err) {
4717 free(line);
4718 return err;
4720 } else {
4721 int skip;
4722 err = format_line(&wline, &width, &skip, line,
4723 view->x, view->ncols, 0, view->x ? 1 : 0);
4724 if (err) {
4725 free(line);
4726 return err;
4728 waddwstr(view->window, &wline[skip]);
4729 free(wline);
4730 wline = NULL;
4732 if (s->lineno == view->hiline) {
4733 /* highlight full gline length */
4734 while (width++ < view->ncols)
4735 waddch(view->window, ' ');
4736 } else {
4737 if (width <= view->ncols - 1)
4738 waddch(view->window, '\n');
4740 if (attr)
4741 wattroff(view->window, attr);
4742 if (++nprinted == 1)
4743 s->first_displayed_line = s->lineno;
4745 free(line);
4746 if (nprinted >= 1)
4747 s->last_displayed_line = s->first_displayed_line +
4748 (nprinted - 1);
4749 else
4750 s->last_displayed_line = s->first_displayed_line;
4752 view_border(view);
4754 if (s->eof) {
4755 while (nprinted < view->nlines) {
4756 waddch(view->window, '\n');
4757 nprinted++;
4760 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4761 view->ncols, 0, 0);
4762 if (err) {
4763 return err;
4766 wstandout(view->window);
4767 waddwstr(view->window, wline);
4768 free(wline);
4769 wline = NULL;
4770 wstandend(view->window);
4773 return NULL;
4776 static char *
4777 get_datestr(time_t *time, char *datebuf)
4779 struct tm mytm, *tm;
4780 char *p, *s;
4782 tm = gmtime_r(time, &mytm);
4783 if (tm == NULL)
4784 return NULL;
4785 s = asctime_r(tm, datebuf);
4786 if (s == NULL)
4787 return NULL;
4788 p = strchr(s, '\n');
4789 if (p)
4790 *p = '\0';
4791 return s;
4794 static const struct got_error *
4795 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4796 off_t off, uint8_t type)
4798 struct got_diff_line *p;
4800 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4801 if (p == NULL)
4802 return got_error_from_errno("reallocarray");
4803 *lines = p;
4804 (*lines)[*nlines].offset = off;
4805 (*lines)[*nlines].type = type;
4806 (*nlines)++;
4808 return NULL;
4811 static const struct got_error *
4812 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4813 struct got_diff_line *s_lines, size_t s_nlines)
4815 struct got_diff_line *p;
4816 char buf[BUFSIZ];
4817 size_t i, r;
4819 if (fseeko(src, 0L, SEEK_SET) == -1)
4820 return got_error_from_errno("fseeko");
4822 for (;;) {
4823 r = fread(buf, 1, sizeof(buf), src);
4824 if (r == 0) {
4825 if (ferror(src))
4826 return got_error_from_errno("fread");
4827 if (feof(src))
4828 break;
4830 if (fwrite(buf, 1, r, dst) != r)
4831 return got_ferror(dst, GOT_ERR_IO);
4834 if (s_nlines == 0 && *d_nlines == 0)
4835 return NULL;
4838 * If commit info was in dst, increment line offsets
4839 * of the appended diff content, but skip s_lines[0]
4840 * because offset zero is already in *d_lines.
4842 if (*d_nlines > 0) {
4843 for (i = 1; i < s_nlines; ++i)
4844 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4846 if (s_nlines > 0) {
4847 --s_nlines;
4848 ++s_lines;
4852 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4853 if (p == NULL) {
4854 /* d_lines is freed in close_diff_view() */
4855 return got_error_from_errno("reallocarray");
4858 *d_lines = p;
4860 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4861 *d_nlines += s_nlines;
4863 return NULL;
4866 static const struct got_error *
4867 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4868 struct got_object_id *commit_id, struct got_reflist_head *refs,
4869 struct got_repository *repo, int ignore_ws, int force_text_diff,
4870 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4872 const struct got_error *err = NULL;
4873 char datebuf[26], *datestr;
4874 struct got_commit_object *commit;
4875 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4876 time_t committer_time;
4877 const char *author, *committer;
4878 char *refs_str = NULL;
4879 struct got_pathlist_entry *pe;
4880 off_t outoff = 0;
4881 int n;
4883 if (refs) {
4884 err = build_refs_str(&refs_str, refs, commit_id, repo);
4885 if (err)
4886 return err;
4889 err = got_object_open_as_commit(&commit, repo, commit_id);
4890 if (err)
4891 return err;
4893 err = got_object_id_str(&id_str, commit_id);
4894 if (err) {
4895 err = got_error_from_errno("got_object_id_str");
4896 goto done;
4899 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4900 if (err)
4901 goto done;
4903 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4904 refs_str ? refs_str : "", refs_str ? ")" : "");
4905 if (n < 0) {
4906 err = got_error_from_errno("fprintf");
4907 goto done;
4909 outoff += n;
4910 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4911 if (err)
4912 goto done;
4914 n = fprintf(outfile, "from: %s\n",
4915 got_object_commit_get_author(commit));
4916 if (n < 0) {
4917 err = got_error_from_errno("fprintf");
4918 goto done;
4920 outoff += n;
4921 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4922 if (err)
4923 goto done;
4925 author = got_object_commit_get_author(commit);
4926 committer = got_object_commit_get_committer(commit);
4927 if (strcmp(author, committer) != 0) {
4928 n = fprintf(outfile, "via: %s\n", committer);
4929 if (n < 0) {
4930 err = got_error_from_errno("fprintf");
4931 goto done;
4933 outoff += n;
4934 err = add_line_metadata(lines, nlines, outoff,
4935 GOT_DIFF_LINE_AUTHOR);
4936 if (err)
4937 goto done;
4939 committer_time = got_object_commit_get_committer_time(commit);
4940 datestr = get_datestr(&committer_time, datebuf);
4941 if (datestr) {
4942 n = fprintf(outfile, "date: %s UTC\n", datestr);
4943 if (n < 0) {
4944 err = got_error_from_errno("fprintf");
4945 goto done;
4947 outoff += n;
4948 err = add_line_metadata(lines, nlines, outoff,
4949 GOT_DIFF_LINE_DATE);
4950 if (err)
4951 goto done;
4953 if (got_object_commit_get_nparents(commit) > 1) {
4954 const struct got_object_id_queue *parent_ids;
4955 struct got_object_qid *qid;
4956 int pn = 1;
4957 parent_ids = got_object_commit_get_parent_ids(commit);
4958 STAILQ_FOREACH(qid, parent_ids, entry) {
4959 err = got_object_id_str(&id_str, &qid->id);
4960 if (err)
4961 goto done;
4962 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4963 if (n < 0) {
4964 err = got_error_from_errno("fprintf");
4965 goto done;
4967 outoff += n;
4968 err = add_line_metadata(lines, nlines, outoff,
4969 GOT_DIFF_LINE_META);
4970 if (err)
4971 goto done;
4972 free(id_str);
4973 id_str = NULL;
4977 err = got_object_commit_get_logmsg(&logmsg, commit);
4978 if (err)
4979 goto done;
4980 s = logmsg;
4981 while ((line = strsep(&s, "\n")) != NULL) {
4982 n = fprintf(outfile, "%s\n", line);
4983 if (n < 0) {
4984 err = got_error_from_errno("fprintf");
4985 goto done;
4987 outoff += n;
4988 err = add_line_metadata(lines, nlines, outoff,
4989 GOT_DIFF_LINE_LOGMSG);
4990 if (err)
4991 goto done;
4994 TAILQ_FOREACH(pe, dsa->paths, entry) {
4995 struct got_diff_changed_path *cp = pe->data;
4996 int pad = dsa->max_path_len - pe->path_len + 1;
4998 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4999 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5000 dsa->rm_cols + 1, cp->rm);
5001 if (n < 0) {
5002 err = got_error_from_errno("fprintf");
5003 goto done;
5005 outoff += n;
5006 err = add_line_metadata(lines, nlines, outoff,
5007 GOT_DIFF_LINE_CHANGES);
5008 if (err)
5009 goto done;
5012 fputc('\n', outfile);
5013 outoff++;
5014 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5015 if (err)
5016 goto done;
5018 n = fprintf(outfile,
5019 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5020 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5021 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5022 if (n < 0) {
5023 err = got_error_from_errno("fprintf");
5024 goto done;
5026 outoff += n;
5027 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5028 if (err)
5029 goto done;
5031 fputc('\n', outfile);
5032 outoff++;
5033 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5034 done:
5035 free(id_str);
5036 free(logmsg);
5037 free(refs_str);
5038 got_object_commit_close(commit);
5039 if (err) {
5040 free(*lines);
5041 *lines = NULL;
5042 *nlines = 0;
5044 return err;
5047 static const struct got_error *
5048 create_diff(struct tog_diff_view_state *s)
5050 const struct got_error *err = NULL;
5051 FILE *f = NULL, *tmp_diff_file = NULL;
5052 int obj_type;
5053 struct got_diff_line *lines = NULL;
5054 struct got_pathlist_head changed_paths;
5056 TAILQ_INIT(&changed_paths);
5058 free(s->lines);
5059 s->lines = malloc(sizeof(*s->lines));
5060 if (s->lines == NULL)
5061 return got_error_from_errno("malloc");
5062 s->nlines = 0;
5064 f = got_opentemp();
5065 if (f == NULL) {
5066 err = got_error_from_errno("got_opentemp");
5067 goto done;
5069 tmp_diff_file = got_opentemp();
5070 if (tmp_diff_file == NULL) {
5071 err = got_error_from_errno("got_opentemp");
5072 goto done;
5074 if (s->f && fclose(s->f) == EOF) {
5075 err = got_error_from_errno("fclose");
5076 goto done;
5078 s->f = f;
5080 if (s->id1)
5081 err = got_object_get_type(&obj_type, s->repo, s->id1);
5082 else
5083 err = got_object_get_type(&obj_type, s->repo, s->id2);
5084 if (err)
5085 goto done;
5087 switch (obj_type) {
5088 case GOT_OBJ_TYPE_BLOB:
5089 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5090 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5091 s->label1, s->label2, tog_diff_algo, s->diff_context,
5092 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5093 s->f);
5094 break;
5095 case GOT_OBJ_TYPE_TREE:
5096 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5097 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5098 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5099 s->force_text_diff, NULL, s->repo, s->f);
5100 break;
5101 case GOT_OBJ_TYPE_COMMIT: {
5102 const struct got_object_id_queue *parent_ids;
5103 struct got_object_qid *pid;
5104 struct got_commit_object *commit2;
5105 struct got_reflist_head *refs;
5106 size_t nlines = 0;
5107 struct got_diffstat_cb_arg dsa = {
5108 0, 0, 0, 0, 0, 0,
5109 &changed_paths,
5110 s->ignore_whitespace,
5111 s->force_text_diff,
5112 tog_diff_algo
5115 lines = malloc(sizeof(*lines));
5116 if (lines == NULL) {
5117 err = got_error_from_errno("malloc");
5118 goto done;
5121 /* build diff first in tmp file then append to commit info */
5122 err = got_diff_objects_as_commits(&lines, &nlines,
5123 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5124 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5125 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5126 if (err)
5127 break;
5129 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5130 if (err)
5131 goto done;
5132 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5133 /* Show commit info if we're diffing to a parent/root commit. */
5134 if (s->id1 == NULL) {
5135 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5136 refs, s->repo, s->ignore_whitespace,
5137 s->force_text_diff, &dsa, s->f);
5138 if (err)
5139 goto done;
5140 } else {
5141 parent_ids = got_object_commit_get_parent_ids(commit2);
5142 STAILQ_FOREACH(pid, parent_ids, entry) {
5143 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5144 err = write_commit_info(&s->lines,
5145 &s->nlines, s->id2, refs, s->repo,
5146 s->ignore_whitespace,
5147 s->force_text_diff, &dsa, s->f);
5148 if (err)
5149 goto done;
5150 break;
5154 got_object_commit_close(commit2);
5156 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5157 lines, nlines);
5158 break;
5160 default:
5161 err = got_error(GOT_ERR_OBJ_TYPE);
5162 break;
5164 done:
5165 free(lines);
5166 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5167 if (s->f && fflush(s->f) != 0 && err == NULL)
5168 err = got_error_from_errno("fflush");
5169 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5170 err = got_error_from_errno("fclose");
5171 return err;
5174 static void
5175 diff_view_indicate_progress(struct tog_view *view)
5177 mvwaddstr(view->window, 0, 0, "diffing...");
5178 update_panels();
5179 doupdate();
5182 static const struct got_error *
5183 search_start_diff_view(struct tog_view *view)
5185 struct tog_diff_view_state *s = &view->state.diff;
5187 s->matched_line = 0;
5188 return NULL;
5191 static void
5192 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5193 size_t *nlines, int **first, int **last, int **match, int **selected)
5195 struct tog_diff_view_state *s = &view->state.diff;
5197 *f = s->f;
5198 *nlines = s->nlines;
5199 *line_offsets = NULL;
5200 *match = &s->matched_line;
5201 *first = &s->first_displayed_line;
5202 *last = &s->last_displayed_line;
5203 *selected = &s->selected_line;
5206 static const struct got_error *
5207 search_next_view_match(struct tog_view *view)
5209 const struct got_error *err = NULL;
5210 FILE *f;
5211 int lineno;
5212 char *line = NULL;
5213 size_t linesize = 0;
5214 ssize_t linelen;
5215 off_t *line_offsets;
5216 size_t nlines = 0;
5217 int *first, *last, *match, *selected;
5219 if (!view->search_setup)
5220 return got_error_msg(GOT_ERR_NOT_IMPL,
5221 "view search not supported");
5222 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5223 &match, &selected);
5225 if (!view->searching) {
5226 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5227 return NULL;
5230 if (*match) {
5231 if (view->searching == TOG_SEARCH_FORWARD)
5232 lineno = *first + 1;
5233 else
5234 lineno = *first - 1;
5235 } else
5236 lineno = *first - 1 + *selected;
5238 while (1) {
5239 off_t offset;
5241 if (lineno <= 0 || lineno > nlines) {
5242 if (*match == 0) {
5243 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5244 break;
5247 if (view->searching == TOG_SEARCH_FORWARD)
5248 lineno = 1;
5249 else
5250 lineno = nlines;
5253 offset = view->type == TOG_VIEW_DIFF ?
5254 view->state.diff.lines[lineno - 1].offset :
5255 line_offsets[lineno - 1];
5256 if (fseeko(f, offset, SEEK_SET) != 0) {
5257 free(line);
5258 return got_error_from_errno("fseeko");
5260 linelen = getline(&line, &linesize, f);
5261 if (linelen != -1) {
5262 char *exstr;
5263 err = expand_tab(&exstr, line);
5264 if (err)
5265 break;
5266 if (match_line(exstr, &view->regex, 1,
5267 &view->regmatch)) {
5268 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5269 *match = lineno;
5270 free(exstr);
5271 break;
5273 free(exstr);
5275 if (view->searching == TOG_SEARCH_FORWARD)
5276 lineno++;
5277 else
5278 lineno--;
5280 free(line);
5282 if (*match) {
5283 *first = *match;
5284 *selected = 1;
5287 return err;
5290 static const struct got_error *
5291 close_diff_view(struct tog_view *view)
5293 const struct got_error *err = NULL;
5294 struct tog_diff_view_state *s = &view->state.diff;
5296 free(s->id1);
5297 s->id1 = NULL;
5298 free(s->id2);
5299 s->id2 = NULL;
5300 if (s->f && fclose(s->f) == EOF)
5301 err = got_error_from_errno("fclose");
5302 s->f = NULL;
5303 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5304 err = got_error_from_errno("fclose");
5305 s->f1 = NULL;
5306 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5307 err = got_error_from_errno("fclose");
5308 s->f2 = NULL;
5309 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5310 err = got_error_from_errno("close");
5311 s->fd1 = -1;
5312 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5313 err = got_error_from_errno("close");
5314 s->fd2 = -1;
5315 free(s->lines);
5316 s->lines = NULL;
5317 s->nlines = 0;
5318 return err;
5321 static const struct got_error *
5322 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5323 struct got_object_id *id2, const char *label1, const char *label2,
5324 int diff_context, int ignore_whitespace, int force_text_diff,
5325 struct tog_view *parent_view, struct got_repository *repo)
5327 const struct got_error *err;
5328 struct tog_diff_view_state *s = &view->state.diff;
5330 memset(s, 0, sizeof(*s));
5331 s->fd1 = -1;
5332 s->fd2 = -1;
5334 if (id1 != NULL && id2 != NULL) {
5335 int type1, type2;
5337 err = got_object_get_type(&type1, repo, id1);
5338 if (err)
5339 goto done;
5340 err = got_object_get_type(&type2, repo, id2);
5341 if (err)
5342 goto done;
5344 if (type1 != type2) {
5345 err = got_error(GOT_ERR_OBJ_TYPE);
5346 goto done;
5349 s->first_displayed_line = 1;
5350 s->last_displayed_line = view->nlines;
5351 s->selected_line = 1;
5352 s->repo = repo;
5353 s->id1 = id1;
5354 s->id2 = id2;
5355 s->label1 = label1;
5356 s->label2 = label2;
5358 if (id1) {
5359 s->id1 = got_object_id_dup(id1);
5360 if (s->id1 == NULL) {
5361 err = got_error_from_errno("got_object_id_dup");
5362 goto done;
5364 } else
5365 s->id1 = NULL;
5367 s->id2 = got_object_id_dup(id2);
5368 if (s->id2 == NULL) {
5369 err = got_error_from_errno("got_object_id_dup");
5370 goto done;
5373 s->f1 = got_opentemp();
5374 if (s->f1 == NULL) {
5375 err = got_error_from_errno("got_opentemp");
5376 goto done;
5379 s->f2 = got_opentemp();
5380 if (s->f2 == NULL) {
5381 err = got_error_from_errno("got_opentemp");
5382 goto done;
5385 s->fd1 = got_opentempfd();
5386 if (s->fd1 == -1) {
5387 err = got_error_from_errno("got_opentempfd");
5388 goto done;
5391 s->fd2 = got_opentempfd();
5392 if (s->fd2 == -1) {
5393 err = got_error_from_errno("got_opentempfd");
5394 goto done;
5397 s->diff_context = diff_context;
5398 s->ignore_whitespace = ignore_whitespace;
5399 s->force_text_diff = force_text_diff;
5400 s->parent_view = parent_view;
5401 s->repo = repo;
5403 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5404 int rc;
5406 rc = init_pair(GOT_DIFF_LINE_MINUS,
5407 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5408 if (rc != ERR)
5409 rc = init_pair(GOT_DIFF_LINE_PLUS,
5410 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5411 if (rc != ERR)
5412 rc = init_pair(GOT_DIFF_LINE_HUNK,
5413 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5414 if (rc != ERR)
5415 rc = init_pair(GOT_DIFF_LINE_META,
5416 get_color_value("TOG_COLOR_DIFF_META"), -1);
5417 if (rc != ERR)
5418 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5419 get_color_value("TOG_COLOR_DIFF_META"), -1);
5420 if (rc != ERR)
5421 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5422 get_color_value("TOG_COLOR_DIFF_META"), -1);
5423 if (rc != ERR)
5424 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5425 get_color_value("TOG_COLOR_DIFF_META"), -1);
5426 if (rc != ERR)
5427 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5428 get_color_value("TOG_COLOR_AUTHOR"), -1);
5429 if (rc != ERR)
5430 rc = init_pair(GOT_DIFF_LINE_DATE,
5431 get_color_value("TOG_COLOR_DATE"), -1);
5432 if (rc == ERR) {
5433 err = got_error(GOT_ERR_RANGE);
5434 goto done;
5438 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5439 view_is_splitscreen(view))
5440 show_log_view(parent_view); /* draw border */
5441 diff_view_indicate_progress(view);
5443 err = create_diff(s);
5445 view->show = show_diff_view;
5446 view->input = input_diff_view;
5447 view->reset = reset_diff_view;
5448 view->close = close_diff_view;
5449 view->search_start = search_start_diff_view;
5450 view->search_setup = search_setup_diff_view;
5451 view->search_next = search_next_view_match;
5452 done:
5453 if (err) {
5454 if (view->close == NULL)
5455 close_diff_view(view);
5456 view_close(view);
5458 return err;
5461 static const struct got_error *
5462 show_diff_view(struct tog_view *view)
5464 const struct got_error *err;
5465 struct tog_diff_view_state *s = &view->state.diff;
5466 char *id_str1 = NULL, *id_str2, *header;
5467 const char *label1, *label2;
5469 if (s->id1) {
5470 err = got_object_id_str(&id_str1, s->id1);
5471 if (err)
5472 return err;
5473 label1 = s->label1 ? s->label1 : id_str1;
5474 } else
5475 label1 = "/dev/null";
5477 err = got_object_id_str(&id_str2, s->id2);
5478 if (err)
5479 return err;
5480 label2 = s->label2 ? s->label2 : id_str2;
5482 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5483 err = got_error_from_errno("asprintf");
5484 free(id_str1);
5485 free(id_str2);
5486 return err;
5488 free(id_str1);
5489 free(id_str2);
5491 err = draw_file(view, header);
5492 free(header);
5493 return err;
5496 static const struct got_error *
5497 set_selected_commit(struct tog_diff_view_state *s,
5498 struct commit_queue_entry *entry)
5500 const struct got_error *err;
5501 const struct got_object_id_queue *parent_ids;
5502 struct got_commit_object *selected_commit;
5503 struct got_object_qid *pid;
5505 free(s->id2);
5506 s->id2 = got_object_id_dup(entry->id);
5507 if (s->id2 == NULL)
5508 return got_error_from_errno("got_object_id_dup");
5510 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5511 if (err)
5512 return err;
5513 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5514 free(s->id1);
5515 pid = STAILQ_FIRST(parent_ids);
5516 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5517 got_object_commit_close(selected_commit);
5518 return NULL;
5521 static const struct got_error *
5522 reset_diff_view(struct tog_view *view)
5524 struct tog_diff_view_state *s = &view->state.diff;
5526 view->count = 0;
5527 wclear(view->window);
5528 s->first_displayed_line = 1;
5529 s->last_displayed_line = view->nlines;
5530 s->matched_line = 0;
5531 diff_view_indicate_progress(view);
5532 return create_diff(s);
5535 static void
5536 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5538 int start, i;
5540 i = start = s->first_displayed_line - 1;
5542 while (s->lines[i].type != type) {
5543 if (i == 0)
5544 i = s->nlines - 1;
5545 if (--i == start)
5546 return; /* do nothing, requested type not in file */
5549 s->selected_line = 1;
5550 s->first_displayed_line = i;
5553 static void
5554 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5556 int start, i;
5558 i = start = s->first_displayed_line + 1;
5560 while (s->lines[i].type != type) {
5561 if (i == s->nlines - 1)
5562 i = 0;
5563 if (++i == start)
5564 return; /* do nothing, requested type not in file */
5567 s->selected_line = 1;
5568 s->first_displayed_line = i;
5571 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5572 int, int, int);
5573 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5574 int, int);
5576 static const struct got_error *
5577 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5579 const struct got_error *err = NULL;
5580 struct tog_diff_view_state *s = &view->state.diff;
5581 struct tog_log_view_state *ls;
5582 struct commit_queue_entry *old_selected_entry;
5583 char *line = NULL;
5584 size_t linesize = 0;
5585 ssize_t linelen;
5586 int i, nscroll = view->nlines - 1, up = 0;
5588 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5590 switch (ch) {
5591 case '0':
5592 case '$':
5593 case KEY_RIGHT:
5594 case 'l':
5595 case KEY_LEFT:
5596 case 'h':
5597 horizontal_scroll_input(view, ch);
5598 break;
5599 case 'a':
5600 case 'w':
5601 if (ch == 'a') {
5602 s->force_text_diff = !s->force_text_diff;
5603 view->action = s->force_text_diff ?
5604 "force ASCII text enabled" :
5605 "force ASCII text disabled";
5607 else if (ch == 'w') {
5608 s->ignore_whitespace = !s->ignore_whitespace;
5609 view->action = s->ignore_whitespace ?
5610 "ignore whitespace enabled" :
5611 "ignore whitespace disabled";
5613 err = reset_diff_view(view);
5614 break;
5615 case 'g':
5616 case KEY_HOME:
5617 s->first_displayed_line = 1;
5618 view->count = 0;
5619 break;
5620 case 'G':
5621 case KEY_END:
5622 view->count = 0;
5623 if (s->eof)
5624 break;
5626 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5627 s->eof = 1;
5628 break;
5629 case 'k':
5630 case KEY_UP:
5631 case CTRL('p'):
5632 if (s->first_displayed_line > 1)
5633 s->first_displayed_line--;
5634 else
5635 view->count = 0;
5636 break;
5637 case CTRL('u'):
5638 case 'u':
5639 nscroll /= 2;
5640 /* FALL THROUGH */
5641 case KEY_PPAGE:
5642 case CTRL('b'):
5643 case 'b':
5644 if (s->first_displayed_line == 1) {
5645 view->count = 0;
5646 break;
5648 i = 0;
5649 while (i++ < nscroll && s->first_displayed_line > 1)
5650 s->first_displayed_line--;
5651 break;
5652 case 'j':
5653 case KEY_DOWN:
5654 case CTRL('n'):
5655 if (!s->eof)
5656 s->first_displayed_line++;
5657 else
5658 view->count = 0;
5659 break;
5660 case CTRL('d'):
5661 case 'd':
5662 nscroll /= 2;
5663 /* FALL THROUGH */
5664 case KEY_NPAGE:
5665 case CTRL('f'):
5666 case 'f':
5667 case ' ':
5668 if (s->eof) {
5669 view->count = 0;
5670 break;
5672 i = 0;
5673 while (!s->eof && i++ < nscroll) {
5674 linelen = getline(&line, &linesize, s->f);
5675 s->first_displayed_line++;
5676 if (linelen == -1) {
5677 if (feof(s->f)) {
5678 s->eof = 1;
5679 } else
5680 err = got_ferror(s->f, GOT_ERR_IO);
5681 break;
5684 free(line);
5685 break;
5686 case '(':
5687 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5688 break;
5689 case ')':
5690 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5691 break;
5692 case '{':
5693 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5694 break;
5695 case '}':
5696 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5697 break;
5698 case '[':
5699 if (s->diff_context > 0) {
5700 s->diff_context--;
5701 s->matched_line = 0;
5702 diff_view_indicate_progress(view);
5703 err = create_diff(s);
5704 if (s->first_displayed_line + view->nlines - 1 >
5705 s->nlines) {
5706 s->first_displayed_line = 1;
5707 s->last_displayed_line = view->nlines;
5709 } else
5710 view->count = 0;
5711 break;
5712 case ']':
5713 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5714 s->diff_context++;
5715 s->matched_line = 0;
5716 diff_view_indicate_progress(view);
5717 err = create_diff(s);
5718 } else
5719 view->count = 0;
5720 break;
5721 case '<':
5722 case ',':
5723 case 'K':
5724 up = 1;
5725 /* FALL THROUGH */
5726 case '>':
5727 case '.':
5728 case 'J':
5729 if (s->parent_view == NULL) {
5730 view->count = 0;
5731 break;
5733 s->parent_view->count = view->count;
5735 if (s->parent_view->type == TOG_VIEW_LOG) {
5736 ls = &s->parent_view->state.log;
5737 old_selected_entry = ls->selected_entry;
5739 err = input_log_view(NULL, s->parent_view,
5740 up ? KEY_UP : KEY_DOWN);
5741 if (err)
5742 break;
5743 view->count = s->parent_view->count;
5745 if (old_selected_entry == ls->selected_entry)
5746 break;
5748 err = set_selected_commit(s, ls->selected_entry);
5749 if (err)
5750 break;
5751 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5752 struct tog_blame_view_state *bs;
5753 struct got_object_id *id, *prev_id;
5755 bs = &s->parent_view->state.blame;
5756 prev_id = get_annotation_for_line(bs->blame.lines,
5757 bs->blame.nlines, bs->last_diffed_line);
5759 err = input_blame_view(&view, s->parent_view,
5760 up ? KEY_UP : KEY_DOWN);
5761 if (err)
5762 break;
5763 view->count = s->parent_view->count;
5765 if (prev_id == NULL)
5766 break;
5767 id = get_selected_commit_id(bs->blame.lines,
5768 bs->blame.nlines, bs->first_displayed_line,
5769 bs->selected_line);
5770 if (id == NULL)
5771 break;
5773 if (!got_object_id_cmp(prev_id, id))
5774 break;
5776 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5777 if (err)
5778 break;
5780 s->first_displayed_line = 1;
5781 s->last_displayed_line = view->nlines;
5782 s->matched_line = 0;
5783 view->x = 0;
5785 diff_view_indicate_progress(view);
5786 err = create_diff(s);
5787 break;
5788 default:
5789 view->count = 0;
5790 break;
5793 return err;
5796 static const struct got_error *
5797 cmd_diff(int argc, char *argv[])
5799 const struct got_error *error;
5800 struct got_repository *repo = NULL;
5801 struct got_worktree *worktree = NULL;
5802 struct got_object_id *id1 = NULL, *id2 = NULL;
5803 char *repo_path = NULL, *cwd = NULL;
5804 char *id_str1 = NULL, *id_str2 = NULL;
5805 char *label1 = NULL, *label2 = NULL;
5806 int diff_context = 3, ignore_whitespace = 0;
5807 int ch, force_text_diff = 0;
5808 const char *errstr;
5809 struct tog_view *view;
5810 int *pack_fds = NULL;
5812 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5813 switch (ch) {
5814 case 'a':
5815 force_text_diff = 1;
5816 break;
5817 case 'C':
5818 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5819 &errstr);
5820 if (errstr != NULL)
5821 errx(1, "number of context lines is %s: %s",
5822 errstr, errstr);
5823 break;
5824 case 'r':
5825 repo_path = realpath(optarg, NULL);
5826 if (repo_path == NULL)
5827 return got_error_from_errno2("realpath",
5828 optarg);
5829 got_path_strip_trailing_slashes(repo_path);
5830 break;
5831 case 'w':
5832 ignore_whitespace = 1;
5833 break;
5834 default:
5835 usage_diff();
5836 /* NOTREACHED */
5840 argc -= optind;
5841 argv += optind;
5843 if (argc == 0) {
5844 usage_diff(); /* TODO show local worktree changes */
5845 } else if (argc == 2) {
5846 id_str1 = argv[0];
5847 id_str2 = argv[1];
5848 } else
5849 usage_diff();
5851 error = got_repo_pack_fds_open(&pack_fds);
5852 if (error)
5853 goto done;
5855 if (repo_path == NULL) {
5856 cwd = getcwd(NULL, 0);
5857 if (cwd == NULL)
5858 return got_error_from_errno("getcwd");
5859 error = got_worktree_open(&worktree, cwd);
5860 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5861 goto done;
5862 if (worktree)
5863 repo_path =
5864 strdup(got_worktree_get_repo_path(worktree));
5865 else
5866 repo_path = strdup(cwd);
5867 if (repo_path == NULL) {
5868 error = got_error_from_errno("strdup");
5869 goto done;
5873 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5874 if (error)
5875 goto done;
5877 init_curses();
5879 error = apply_unveil(got_repo_get_path(repo), NULL);
5880 if (error)
5881 goto done;
5883 error = tog_load_refs(repo, 0);
5884 if (error)
5885 goto done;
5887 error = got_repo_match_object_id(&id1, &label1, id_str1,
5888 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5889 if (error)
5890 goto done;
5892 error = got_repo_match_object_id(&id2, &label2, id_str2,
5893 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5894 if (error)
5895 goto done;
5897 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5898 if (view == NULL) {
5899 error = got_error_from_errno("view_open");
5900 goto done;
5902 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5903 ignore_whitespace, force_text_diff, NULL, repo);
5904 if (error)
5905 goto done;
5906 error = view_loop(view);
5907 done:
5908 free(label1);
5909 free(label2);
5910 free(repo_path);
5911 free(cwd);
5912 if (repo) {
5913 const struct got_error *close_err = got_repo_close(repo);
5914 if (error == NULL)
5915 error = close_err;
5917 if (worktree)
5918 got_worktree_close(worktree);
5919 if (pack_fds) {
5920 const struct got_error *pack_err =
5921 got_repo_pack_fds_close(pack_fds);
5922 if (error == NULL)
5923 error = pack_err;
5925 tog_free_refs();
5926 return error;
5929 __dead static void
5930 usage_blame(void)
5932 endwin();
5933 fprintf(stderr,
5934 "usage: %s blame [-c commit] [-r repository-path] path\n",
5935 getprogname());
5936 exit(1);
5939 struct tog_blame_line {
5940 int annotated;
5941 struct got_object_id *id;
5944 static const struct got_error *
5945 draw_blame(struct tog_view *view)
5947 struct tog_blame_view_state *s = &view->state.blame;
5948 struct tog_blame *blame = &s->blame;
5949 regmatch_t *regmatch = &view->regmatch;
5950 const struct got_error *err;
5951 int lineno = 0, nprinted = 0;
5952 char *line = NULL;
5953 size_t linesize = 0;
5954 ssize_t linelen;
5955 wchar_t *wline;
5956 int width;
5957 struct tog_blame_line *blame_line;
5958 struct got_object_id *prev_id = NULL;
5959 char *id_str;
5960 struct tog_color *tc;
5962 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5963 if (err)
5964 return err;
5966 rewind(blame->f);
5967 werase(view->window);
5969 if (asprintf(&line, "commit %s", id_str) == -1) {
5970 err = got_error_from_errno("asprintf");
5971 free(id_str);
5972 return err;
5975 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5976 free(line);
5977 line = NULL;
5978 if (err)
5979 return err;
5980 if (view_needs_focus_indication(view))
5981 wstandout(view->window);
5982 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5983 if (tc)
5984 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5985 waddwstr(view->window, wline);
5986 while (width++ < view->ncols)
5987 waddch(view->window, ' ');
5988 if (tc)
5989 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5990 if (view_needs_focus_indication(view))
5991 wstandend(view->window);
5992 free(wline);
5993 wline = NULL;
5995 if (view->gline > blame->nlines)
5996 view->gline = blame->nlines;
5998 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5999 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6000 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6001 free(id_str);
6002 return got_error_from_errno("asprintf");
6004 free(id_str);
6005 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6006 free(line);
6007 line = NULL;
6008 if (err)
6009 return err;
6010 waddwstr(view->window, wline);
6011 free(wline);
6012 wline = NULL;
6013 if (width < view->ncols - 1)
6014 waddch(view->window, '\n');
6016 s->eof = 0;
6017 view->maxx = 0;
6018 while (nprinted < view->nlines - 2) {
6019 linelen = getline(&line, &linesize, blame->f);
6020 if (linelen == -1) {
6021 if (feof(blame->f)) {
6022 s->eof = 1;
6023 break;
6025 free(line);
6026 return got_ferror(blame->f, GOT_ERR_IO);
6028 if (++lineno < s->first_displayed_line)
6029 continue;
6030 if (view->gline && !gotoline(view, &lineno, &nprinted))
6031 continue;
6033 /* Set view->maxx based on full line length. */
6034 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6035 if (err) {
6036 free(line);
6037 return err;
6039 free(wline);
6040 wline = NULL;
6041 view->maxx = MAX(view->maxx, width);
6043 if (nprinted == s->selected_line - 1)
6044 wstandout(view->window);
6046 if (blame->nlines > 0) {
6047 blame_line = &blame->lines[lineno - 1];
6048 if (blame_line->annotated && prev_id &&
6049 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6050 !(nprinted == s->selected_line - 1)) {
6051 waddstr(view->window, " ");
6052 } else if (blame_line->annotated) {
6053 char *id_str;
6054 err = got_object_id_str(&id_str,
6055 blame_line->id);
6056 if (err) {
6057 free(line);
6058 return err;
6060 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6061 if (tc)
6062 wattr_on(view->window,
6063 COLOR_PAIR(tc->colorpair), NULL);
6064 wprintw(view->window, "%.8s", id_str);
6065 if (tc)
6066 wattr_off(view->window,
6067 COLOR_PAIR(tc->colorpair), NULL);
6068 free(id_str);
6069 prev_id = blame_line->id;
6070 } else {
6071 waddstr(view->window, "........");
6072 prev_id = NULL;
6074 } else {
6075 waddstr(view->window, "........");
6076 prev_id = NULL;
6079 if (nprinted == s->selected_line - 1)
6080 wstandend(view->window);
6081 waddstr(view->window, " ");
6083 if (view->ncols <= 9) {
6084 width = 9;
6085 } else if (s->first_displayed_line + nprinted ==
6086 s->matched_line &&
6087 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6088 err = add_matched_line(&width, line, view->ncols - 9, 9,
6089 view->window, view->x, regmatch);
6090 if (err) {
6091 free(line);
6092 return err;
6094 width += 9;
6095 } else {
6096 int skip;
6097 err = format_line(&wline, &width, &skip, line,
6098 view->x, view->ncols - 9, 9, 1);
6099 if (err) {
6100 free(line);
6101 return err;
6103 waddwstr(view->window, &wline[skip]);
6104 width += 9;
6105 free(wline);
6106 wline = NULL;
6109 if (width <= view->ncols - 1)
6110 waddch(view->window, '\n');
6111 if (++nprinted == 1)
6112 s->first_displayed_line = lineno;
6114 free(line);
6115 s->last_displayed_line = lineno;
6117 view_border(view);
6119 return NULL;
6122 static const struct got_error *
6123 blame_cb(void *arg, int nlines, int lineno,
6124 struct got_commit_object *commit, struct got_object_id *id)
6126 const struct got_error *err = NULL;
6127 struct tog_blame_cb_args *a = arg;
6128 struct tog_blame_line *line;
6129 int errcode;
6131 if (nlines != a->nlines ||
6132 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6133 return got_error(GOT_ERR_RANGE);
6135 errcode = pthread_mutex_lock(&tog_mutex);
6136 if (errcode)
6137 return got_error_set_errno(errcode, "pthread_mutex_lock");
6139 if (*a->quit) { /* user has quit the blame view */
6140 err = got_error(GOT_ERR_ITER_COMPLETED);
6141 goto done;
6144 if (lineno == -1)
6145 goto done; /* no change in this commit */
6147 line = &a->lines[lineno - 1];
6148 if (line->annotated)
6149 goto done;
6151 line->id = got_object_id_dup(id);
6152 if (line->id == NULL) {
6153 err = got_error_from_errno("got_object_id_dup");
6154 goto done;
6156 line->annotated = 1;
6157 done:
6158 errcode = pthread_mutex_unlock(&tog_mutex);
6159 if (errcode)
6160 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6161 return err;
6164 static void *
6165 blame_thread(void *arg)
6167 const struct got_error *err, *close_err;
6168 struct tog_blame_thread_args *ta = arg;
6169 struct tog_blame_cb_args *a = ta->cb_args;
6170 int errcode, fd1 = -1, fd2 = -1;
6171 FILE *f1 = NULL, *f2 = NULL;
6173 fd1 = got_opentempfd();
6174 if (fd1 == -1)
6175 return (void *)got_error_from_errno("got_opentempfd");
6177 fd2 = got_opentempfd();
6178 if (fd2 == -1) {
6179 err = got_error_from_errno("got_opentempfd");
6180 goto done;
6183 f1 = got_opentemp();
6184 if (f1 == NULL) {
6185 err = (void *)got_error_from_errno("got_opentemp");
6186 goto done;
6188 f2 = got_opentemp();
6189 if (f2 == NULL) {
6190 err = (void *)got_error_from_errno("got_opentemp");
6191 goto done;
6194 err = block_signals_used_by_main_thread();
6195 if (err)
6196 goto done;
6198 err = got_blame(ta->path, a->commit_id, ta->repo,
6199 tog_diff_algo, blame_cb, ta->cb_args,
6200 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6201 if (err && err->code == GOT_ERR_CANCELLED)
6202 err = NULL;
6204 errcode = pthread_mutex_lock(&tog_mutex);
6205 if (errcode) {
6206 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6207 goto done;
6210 close_err = got_repo_close(ta->repo);
6211 if (err == NULL)
6212 err = close_err;
6213 ta->repo = NULL;
6214 *ta->complete = 1;
6216 errcode = pthread_mutex_unlock(&tog_mutex);
6217 if (errcode && err == NULL)
6218 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6220 done:
6221 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6222 err = got_error_from_errno("close");
6223 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6224 err = got_error_from_errno("close");
6225 if (f1 && fclose(f1) == EOF && err == NULL)
6226 err = got_error_from_errno("fclose");
6227 if (f2 && fclose(f2) == EOF && err == NULL)
6228 err = got_error_from_errno("fclose");
6230 return (void *)err;
6233 static struct got_object_id *
6234 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6235 int first_displayed_line, int selected_line)
6237 struct tog_blame_line *line;
6239 if (nlines <= 0)
6240 return NULL;
6242 line = &lines[first_displayed_line - 1 + selected_line - 1];
6243 if (!line->annotated)
6244 return NULL;
6246 return line->id;
6249 static struct got_object_id *
6250 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6251 int lineno)
6253 struct tog_blame_line *line;
6255 if (nlines <= 0 || lineno >= nlines)
6256 return NULL;
6258 line = &lines[lineno - 1];
6259 if (!line->annotated)
6260 return NULL;
6262 return line->id;
6265 static const struct got_error *
6266 stop_blame(struct tog_blame *blame)
6268 const struct got_error *err = NULL;
6269 int i;
6271 if (blame->thread) {
6272 int errcode;
6273 errcode = pthread_mutex_unlock(&tog_mutex);
6274 if (errcode)
6275 return got_error_set_errno(errcode,
6276 "pthread_mutex_unlock");
6277 errcode = pthread_join(blame->thread, (void **)&err);
6278 if (errcode)
6279 return got_error_set_errno(errcode, "pthread_join");
6280 errcode = pthread_mutex_lock(&tog_mutex);
6281 if (errcode)
6282 return got_error_set_errno(errcode,
6283 "pthread_mutex_lock");
6284 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6285 err = NULL;
6286 blame->thread = 0; //NULL;
6288 if (blame->thread_args.repo) {
6289 const struct got_error *close_err;
6290 close_err = got_repo_close(blame->thread_args.repo);
6291 if (err == NULL)
6292 err = close_err;
6293 blame->thread_args.repo = NULL;
6295 if (blame->f) {
6296 if (fclose(blame->f) == EOF && err == NULL)
6297 err = got_error_from_errno("fclose");
6298 blame->f = NULL;
6300 if (blame->lines) {
6301 for (i = 0; i < blame->nlines; i++)
6302 free(blame->lines[i].id);
6303 free(blame->lines);
6304 blame->lines = NULL;
6306 free(blame->cb_args.commit_id);
6307 blame->cb_args.commit_id = NULL;
6308 if (blame->pack_fds) {
6309 const struct got_error *pack_err =
6310 got_repo_pack_fds_close(blame->pack_fds);
6311 if (err == NULL)
6312 err = pack_err;
6313 blame->pack_fds = NULL;
6315 return err;
6318 static const struct got_error *
6319 cancel_blame_view(void *arg)
6321 const struct got_error *err = NULL;
6322 int *done = arg;
6323 int errcode;
6325 errcode = pthread_mutex_lock(&tog_mutex);
6326 if (errcode)
6327 return got_error_set_errno(errcode,
6328 "pthread_mutex_unlock");
6330 if (*done)
6331 err = got_error(GOT_ERR_CANCELLED);
6333 errcode = pthread_mutex_unlock(&tog_mutex);
6334 if (errcode)
6335 return got_error_set_errno(errcode,
6336 "pthread_mutex_lock");
6338 return err;
6341 static const struct got_error *
6342 run_blame(struct tog_view *view)
6344 struct tog_blame_view_state *s = &view->state.blame;
6345 struct tog_blame *blame = &s->blame;
6346 const struct got_error *err = NULL;
6347 struct got_commit_object *commit = NULL;
6348 struct got_blob_object *blob = NULL;
6349 struct got_repository *thread_repo = NULL;
6350 struct got_object_id *obj_id = NULL;
6351 int obj_type, fd = -1;
6352 int *pack_fds = NULL;
6354 err = got_object_open_as_commit(&commit, s->repo,
6355 &s->blamed_commit->id);
6356 if (err)
6357 return err;
6359 fd = got_opentempfd();
6360 if (fd == -1) {
6361 err = got_error_from_errno("got_opentempfd");
6362 goto done;
6365 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6366 if (err)
6367 goto done;
6369 err = got_object_get_type(&obj_type, s->repo, obj_id);
6370 if (err)
6371 goto done;
6373 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6374 err = got_error(GOT_ERR_OBJ_TYPE);
6375 goto done;
6378 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6379 if (err)
6380 goto done;
6381 blame->f = got_opentemp();
6382 if (blame->f == NULL) {
6383 err = got_error_from_errno("got_opentemp");
6384 goto done;
6386 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6387 &blame->line_offsets, blame->f, blob);
6388 if (err)
6389 goto done;
6390 if (blame->nlines == 0) {
6391 s->blame_complete = 1;
6392 goto done;
6395 /* Don't include \n at EOF in the blame line count. */
6396 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6397 blame->nlines--;
6399 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6400 if (blame->lines == NULL) {
6401 err = got_error_from_errno("calloc");
6402 goto done;
6405 err = got_repo_pack_fds_open(&pack_fds);
6406 if (err)
6407 goto done;
6408 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6409 pack_fds);
6410 if (err)
6411 goto done;
6413 blame->pack_fds = pack_fds;
6414 blame->cb_args.view = view;
6415 blame->cb_args.lines = blame->lines;
6416 blame->cb_args.nlines = blame->nlines;
6417 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6418 if (blame->cb_args.commit_id == NULL) {
6419 err = got_error_from_errno("got_object_id_dup");
6420 goto done;
6422 blame->cb_args.quit = &s->done;
6424 blame->thread_args.path = s->path;
6425 blame->thread_args.repo = thread_repo;
6426 blame->thread_args.cb_args = &blame->cb_args;
6427 blame->thread_args.complete = &s->blame_complete;
6428 blame->thread_args.cancel_cb = cancel_blame_view;
6429 blame->thread_args.cancel_arg = &s->done;
6430 s->blame_complete = 0;
6432 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6433 s->first_displayed_line = 1;
6434 s->last_displayed_line = view->nlines;
6435 s->selected_line = 1;
6437 s->matched_line = 0;
6439 done:
6440 if (commit)
6441 got_object_commit_close(commit);
6442 if (fd != -1 && close(fd) == -1 && err == NULL)
6443 err = got_error_from_errno("close");
6444 if (blob)
6445 got_object_blob_close(blob);
6446 free(obj_id);
6447 if (err)
6448 stop_blame(blame);
6449 return err;
6452 static const struct got_error *
6453 open_blame_view(struct tog_view *view, char *path,
6454 struct got_object_id *commit_id, struct got_repository *repo)
6456 const struct got_error *err = NULL;
6457 struct tog_blame_view_state *s = &view->state.blame;
6459 STAILQ_INIT(&s->blamed_commits);
6461 s->path = strdup(path);
6462 if (s->path == NULL)
6463 return got_error_from_errno("strdup");
6465 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6466 if (err) {
6467 free(s->path);
6468 return err;
6471 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6472 s->first_displayed_line = 1;
6473 s->last_displayed_line = view->nlines;
6474 s->selected_line = 1;
6475 s->blame_complete = 0;
6476 s->repo = repo;
6477 s->commit_id = commit_id;
6478 memset(&s->blame, 0, sizeof(s->blame));
6480 STAILQ_INIT(&s->colors);
6481 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6482 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6483 get_color_value("TOG_COLOR_COMMIT"));
6484 if (err)
6485 return err;
6488 view->show = show_blame_view;
6489 view->input = input_blame_view;
6490 view->reset = reset_blame_view;
6491 view->close = close_blame_view;
6492 view->search_start = search_start_blame_view;
6493 view->search_setup = search_setup_blame_view;
6494 view->search_next = search_next_view_match;
6496 return run_blame(view);
6499 static const struct got_error *
6500 close_blame_view(struct tog_view *view)
6502 const struct got_error *err = NULL;
6503 struct tog_blame_view_state *s = &view->state.blame;
6505 if (s->blame.thread)
6506 err = stop_blame(&s->blame);
6508 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6509 struct got_object_qid *blamed_commit;
6510 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6511 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6512 got_object_qid_free(blamed_commit);
6515 free(s->path);
6516 free_colors(&s->colors);
6517 return err;
6520 static const struct got_error *
6521 search_start_blame_view(struct tog_view *view)
6523 struct tog_blame_view_state *s = &view->state.blame;
6525 s->matched_line = 0;
6526 return NULL;
6529 static void
6530 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6531 size_t *nlines, int **first, int **last, int **match, int **selected)
6533 struct tog_blame_view_state *s = &view->state.blame;
6535 *f = s->blame.f;
6536 *nlines = s->blame.nlines;
6537 *line_offsets = s->blame.line_offsets;
6538 *match = &s->matched_line;
6539 *first = &s->first_displayed_line;
6540 *last = &s->last_displayed_line;
6541 *selected = &s->selected_line;
6544 static const struct got_error *
6545 show_blame_view(struct tog_view *view)
6547 const struct got_error *err = NULL;
6548 struct tog_blame_view_state *s = &view->state.blame;
6549 int errcode;
6551 if (s->blame.thread == 0 && !s->blame_complete) {
6552 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6553 &s->blame.thread_args);
6554 if (errcode)
6555 return got_error_set_errno(errcode, "pthread_create");
6557 if (!using_mock_io)
6558 halfdelay(1); /* fast refresh while annotating */
6561 if (s->blame_complete && !using_mock_io)
6562 halfdelay(10); /* disable fast refresh */
6564 err = draw_blame(view);
6566 view_border(view);
6567 return err;
6570 static const struct got_error *
6571 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6572 struct got_repository *repo, struct got_object_id *id)
6574 struct tog_view *log_view;
6575 const struct got_error *err = NULL;
6577 *new_view = NULL;
6579 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6580 if (log_view == NULL)
6581 return got_error_from_errno("view_open");
6583 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6584 if (err)
6585 view_close(log_view);
6586 else
6587 *new_view = log_view;
6589 return err;
6592 static const struct got_error *
6593 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6595 const struct got_error *err = NULL, *thread_err = NULL;
6596 struct tog_view *diff_view;
6597 struct tog_blame_view_state *s = &view->state.blame;
6598 int eos, nscroll, begin_y = 0, begin_x = 0;
6600 eos = nscroll = view->nlines - 2;
6601 if (view_is_hsplit_top(view))
6602 --eos; /* border */
6604 switch (ch) {
6605 case '0':
6606 case '$':
6607 case KEY_RIGHT:
6608 case 'l':
6609 case KEY_LEFT:
6610 case 'h':
6611 horizontal_scroll_input(view, ch);
6612 break;
6613 case 'q':
6614 s->done = 1;
6615 break;
6616 case 'g':
6617 case KEY_HOME:
6618 s->selected_line = 1;
6619 s->first_displayed_line = 1;
6620 view->count = 0;
6621 break;
6622 case 'G':
6623 case KEY_END:
6624 if (s->blame.nlines < eos) {
6625 s->selected_line = s->blame.nlines;
6626 s->first_displayed_line = 1;
6627 } else {
6628 s->selected_line = eos;
6629 s->first_displayed_line = s->blame.nlines - (eos - 1);
6631 view->count = 0;
6632 break;
6633 case 'k':
6634 case KEY_UP:
6635 case CTRL('p'):
6636 if (s->selected_line > 1)
6637 s->selected_line--;
6638 else if (s->selected_line == 1 &&
6639 s->first_displayed_line > 1)
6640 s->first_displayed_line--;
6641 else
6642 view->count = 0;
6643 break;
6644 case CTRL('u'):
6645 case 'u':
6646 nscroll /= 2;
6647 /* FALL THROUGH */
6648 case KEY_PPAGE:
6649 case CTRL('b'):
6650 case 'b':
6651 if (s->first_displayed_line == 1) {
6652 if (view->count > 1)
6653 nscroll += nscroll;
6654 s->selected_line = MAX(1, s->selected_line - nscroll);
6655 view->count = 0;
6656 break;
6658 if (s->first_displayed_line > nscroll)
6659 s->first_displayed_line -= nscroll;
6660 else
6661 s->first_displayed_line = 1;
6662 break;
6663 case 'j':
6664 case KEY_DOWN:
6665 case CTRL('n'):
6666 if (s->selected_line < eos && s->first_displayed_line +
6667 s->selected_line <= s->blame.nlines)
6668 s->selected_line++;
6669 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6670 s->first_displayed_line++;
6671 else
6672 view->count = 0;
6673 break;
6674 case 'c':
6675 case 'p': {
6676 struct got_object_id *id = NULL;
6678 view->count = 0;
6679 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6680 s->first_displayed_line, s->selected_line);
6681 if (id == NULL)
6682 break;
6683 if (ch == 'p') {
6684 struct got_commit_object *commit, *pcommit;
6685 struct got_object_qid *pid;
6686 struct got_object_id *blob_id = NULL;
6687 int obj_type;
6688 err = got_object_open_as_commit(&commit,
6689 s->repo, id);
6690 if (err)
6691 break;
6692 pid = STAILQ_FIRST(
6693 got_object_commit_get_parent_ids(commit));
6694 if (pid == NULL) {
6695 got_object_commit_close(commit);
6696 break;
6698 /* Check if path history ends here. */
6699 err = got_object_open_as_commit(&pcommit,
6700 s->repo, &pid->id);
6701 if (err)
6702 break;
6703 err = got_object_id_by_path(&blob_id, s->repo,
6704 pcommit, s->path);
6705 got_object_commit_close(pcommit);
6706 if (err) {
6707 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6708 err = NULL;
6709 got_object_commit_close(commit);
6710 break;
6712 err = got_object_get_type(&obj_type, s->repo,
6713 blob_id);
6714 free(blob_id);
6715 /* Can't blame non-blob type objects. */
6716 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6717 got_object_commit_close(commit);
6718 break;
6720 err = got_object_qid_alloc(&s->blamed_commit,
6721 &pid->id);
6722 got_object_commit_close(commit);
6723 } else {
6724 if (got_object_id_cmp(id,
6725 &s->blamed_commit->id) == 0)
6726 break;
6727 err = got_object_qid_alloc(&s->blamed_commit,
6728 id);
6730 if (err)
6731 break;
6732 s->done = 1;
6733 thread_err = stop_blame(&s->blame);
6734 s->done = 0;
6735 if (thread_err)
6736 break;
6737 STAILQ_INSERT_HEAD(&s->blamed_commits,
6738 s->blamed_commit, entry);
6739 err = run_blame(view);
6740 if (err)
6741 break;
6742 break;
6744 case 'C': {
6745 struct got_object_qid *first;
6747 view->count = 0;
6748 first = STAILQ_FIRST(&s->blamed_commits);
6749 if (!got_object_id_cmp(&first->id, s->commit_id))
6750 break;
6751 s->done = 1;
6752 thread_err = stop_blame(&s->blame);
6753 s->done = 0;
6754 if (thread_err)
6755 break;
6756 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6757 got_object_qid_free(s->blamed_commit);
6758 s->blamed_commit =
6759 STAILQ_FIRST(&s->blamed_commits);
6760 err = run_blame(view);
6761 if (err)
6762 break;
6763 break;
6765 case 'L':
6766 view->count = 0;
6767 s->id_to_log = get_selected_commit_id(s->blame.lines,
6768 s->blame.nlines, s->first_displayed_line, s->selected_line);
6769 if (s->id_to_log)
6770 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6771 break;
6772 case KEY_ENTER:
6773 case '\r': {
6774 struct got_object_id *id = NULL;
6775 struct got_object_qid *pid;
6776 struct got_commit_object *commit = NULL;
6778 view->count = 0;
6779 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6780 s->first_displayed_line, s->selected_line);
6781 if (id == NULL)
6782 break;
6783 err = got_object_open_as_commit(&commit, s->repo, id);
6784 if (err)
6785 break;
6786 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6787 if (*new_view) {
6788 /* traversed from diff view, release diff resources */
6789 err = close_diff_view(*new_view);
6790 if (err)
6791 break;
6792 diff_view = *new_view;
6793 } else {
6794 if (view_is_parent_view(view))
6795 view_get_split(view, &begin_y, &begin_x);
6797 diff_view = view_open(0, 0, begin_y, begin_x,
6798 TOG_VIEW_DIFF);
6799 if (diff_view == NULL) {
6800 got_object_commit_close(commit);
6801 err = got_error_from_errno("view_open");
6802 break;
6805 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6806 id, NULL, NULL, 3, 0, 0, view, s->repo);
6807 got_object_commit_close(commit);
6808 if (err) {
6809 view_close(diff_view);
6810 break;
6812 s->last_diffed_line = s->first_displayed_line - 1 +
6813 s->selected_line;
6814 if (*new_view)
6815 break; /* still open from active diff view */
6816 if (view_is_parent_view(view) &&
6817 view->mode == TOG_VIEW_SPLIT_HRZN) {
6818 err = view_init_hsplit(view, begin_y);
6819 if (err)
6820 break;
6823 view->focussed = 0;
6824 diff_view->focussed = 1;
6825 diff_view->mode = view->mode;
6826 diff_view->nlines = view->lines - begin_y;
6827 if (view_is_parent_view(view)) {
6828 view_transfer_size(diff_view, view);
6829 err = view_close_child(view);
6830 if (err)
6831 break;
6832 err = view_set_child(view, diff_view);
6833 if (err)
6834 break;
6835 view->focus_child = 1;
6836 } else
6837 *new_view = diff_view;
6838 if (err)
6839 break;
6840 break;
6842 case CTRL('d'):
6843 case 'd':
6844 nscroll /= 2;
6845 /* FALL THROUGH */
6846 case KEY_NPAGE:
6847 case CTRL('f'):
6848 case 'f':
6849 case ' ':
6850 if (s->last_displayed_line >= s->blame.nlines &&
6851 s->selected_line >= MIN(s->blame.nlines,
6852 view->nlines - 2)) {
6853 view->count = 0;
6854 break;
6856 if (s->last_displayed_line >= s->blame.nlines &&
6857 s->selected_line < view->nlines - 2) {
6858 s->selected_line +=
6859 MIN(nscroll, s->last_displayed_line -
6860 s->first_displayed_line - s->selected_line + 1);
6862 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6863 s->first_displayed_line += nscroll;
6864 else
6865 s->first_displayed_line =
6866 s->blame.nlines - (view->nlines - 3);
6867 break;
6868 case KEY_RESIZE:
6869 if (s->selected_line > view->nlines - 2) {
6870 s->selected_line = MIN(s->blame.nlines,
6871 view->nlines - 2);
6873 break;
6874 default:
6875 view->count = 0;
6876 break;
6878 return thread_err ? thread_err : err;
6881 static const struct got_error *
6882 reset_blame_view(struct tog_view *view)
6884 const struct got_error *err;
6885 struct tog_blame_view_state *s = &view->state.blame;
6887 view->count = 0;
6888 s->done = 1;
6889 err = stop_blame(&s->blame);
6890 s->done = 0;
6891 if (err)
6892 return err;
6893 return run_blame(view);
6896 static const struct got_error *
6897 cmd_blame(int argc, char *argv[])
6899 const struct got_error *error;
6900 struct got_repository *repo = NULL;
6901 struct got_worktree *worktree = NULL;
6902 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6903 char *link_target = NULL;
6904 struct got_object_id *commit_id = NULL;
6905 struct got_commit_object *commit = NULL;
6906 char *commit_id_str = NULL;
6907 int ch;
6908 struct tog_view *view = NULL;
6909 int *pack_fds = NULL;
6911 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6912 switch (ch) {
6913 case 'c':
6914 commit_id_str = optarg;
6915 break;
6916 case 'r':
6917 repo_path = realpath(optarg, NULL);
6918 if (repo_path == NULL)
6919 return got_error_from_errno2("realpath",
6920 optarg);
6921 break;
6922 default:
6923 usage_blame();
6924 /* NOTREACHED */
6928 argc -= optind;
6929 argv += optind;
6931 if (argc != 1)
6932 usage_blame();
6934 error = got_repo_pack_fds_open(&pack_fds);
6935 if (error != NULL)
6936 goto done;
6938 if (repo_path == NULL) {
6939 cwd = getcwd(NULL, 0);
6940 if (cwd == NULL)
6941 return got_error_from_errno("getcwd");
6942 error = got_worktree_open(&worktree, cwd);
6943 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6944 goto done;
6945 if (worktree)
6946 repo_path =
6947 strdup(got_worktree_get_repo_path(worktree));
6948 else
6949 repo_path = strdup(cwd);
6950 if (repo_path == NULL) {
6951 error = got_error_from_errno("strdup");
6952 goto done;
6956 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6957 if (error != NULL)
6958 goto done;
6960 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6961 worktree);
6962 if (error)
6963 goto done;
6965 init_curses();
6967 error = apply_unveil(got_repo_get_path(repo), NULL);
6968 if (error)
6969 goto done;
6971 error = tog_load_refs(repo, 0);
6972 if (error)
6973 goto done;
6975 if (commit_id_str == NULL) {
6976 struct got_reference *head_ref;
6977 error = got_ref_open(&head_ref, repo, worktree ?
6978 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6979 if (error != NULL)
6980 goto done;
6981 error = got_ref_resolve(&commit_id, repo, head_ref);
6982 got_ref_close(head_ref);
6983 } else {
6984 error = got_repo_match_object_id(&commit_id, NULL,
6985 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6987 if (error != NULL)
6988 goto done;
6990 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6991 if (view == NULL) {
6992 error = got_error_from_errno("view_open");
6993 goto done;
6996 error = got_object_open_as_commit(&commit, repo, commit_id);
6997 if (error)
6998 goto done;
7000 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7001 commit, repo);
7002 if (error)
7003 goto done;
7005 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7006 commit_id, repo);
7007 if (error)
7008 goto done;
7009 if (worktree) {
7010 /* Release work tree lock. */
7011 got_worktree_close(worktree);
7012 worktree = NULL;
7014 error = view_loop(view);
7015 done:
7016 free(repo_path);
7017 free(in_repo_path);
7018 free(link_target);
7019 free(cwd);
7020 free(commit_id);
7021 if (error != NULL && view != NULL) {
7022 if (view->close == NULL)
7023 close_blame_view(view);
7024 view_close(view);
7026 if (commit)
7027 got_object_commit_close(commit);
7028 if (worktree)
7029 got_worktree_close(worktree);
7030 if (repo) {
7031 const struct got_error *close_err = got_repo_close(repo);
7032 if (error == NULL)
7033 error = close_err;
7035 if (pack_fds) {
7036 const struct got_error *pack_err =
7037 got_repo_pack_fds_close(pack_fds);
7038 if (error == NULL)
7039 error = pack_err;
7041 tog_free_refs();
7042 return error;
7045 static const struct got_error *
7046 draw_tree_entries(struct tog_view *view, const char *parent_path)
7048 struct tog_tree_view_state *s = &view->state.tree;
7049 const struct got_error *err = NULL;
7050 struct got_tree_entry *te;
7051 wchar_t *wline;
7052 char *index = NULL;
7053 struct tog_color *tc;
7054 int width, n, nentries, scrollx, i = 1;
7055 int limit = view->nlines;
7057 s->ndisplayed = 0;
7058 if (view_is_hsplit_top(view))
7059 --limit; /* border */
7061 werase(view->window);
7063 if (limit == 0)
7064 return NULL;
7066 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7067 0, 0);
7068 if (err)
7069 return err;
7070 if (view_needs_focus_indication(view))
7071 wstandout(view->window);
7072 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7073 if (tc)
7074 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7075 waddwstr(view->window, wline);
7076 free(wline);
7077 wline = NULL;
7078 while (width++ < view->ncols)
7079 waddch(view->window, ' ');
7080 if (tc)
7081 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7082 if (view_needs_focus_indication(view))
7083 wstandend(view->window);
7084 if (--limit <= 0)
7085 return NULL;
7087 i += s->selected;
7088 if (s->first_displayed_entry) {
7089 i += got_tree_entry_get_index(s->first_displayed_entry);
7090 if (s->tree != s->root)
7091 ++i; /* account for ".." entry */
7093 nentries = got_object_tree_get_nentries(s->tree);
7094 if (asprintf(&index, "[%d/%d] %s",
7095 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7096 return got_error_from_errno("asprintf");
7097 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7098 free(index);
7099 if (err)
7100 return err;
7101 waddwstr(view->window, wline);
7102 free(wline);
7103 wline = NULL;
7104 if (width < view->ncols - 1)
7105 waddch(view->window, '\n');
7106 if (--limit <= 0)
7107 return NULL;
7108 waddch(view->window, '\n');
7109 if (--limit <= 0)
7110 return NULL;
7112 if (s->first_displayed_entry == NULL) {
7113 te = got_object_tree_get_first_entry(s->tree);
7114 if (s->selected == 0) {
7115 if (view->focussed)
7116 wstandout(view->window);
7117 s->selected_entry = NULL;
7119 waddstr(view->window, " ..\n"); /* parent directory */
7120 if (s->selected == 0 && view->focussed)
7121 wstandend(view->window);
7122 s->ndisplayed++;
7123 if (--limit <= 0)
7124 return NULL;
7125 n = 1;
7126 } else {
7127 n = 0;
7128 te = s->first_displayed_entry;
7131 view->maxx = 0;
7132 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7133 char *line = NULL, *id_str = NULL, *link_target = NULL;
7134 const char *modestr = "";
7135 mode_t mode;
7137 te = got_object_tree_get_entry(s->tree, i);
7138 mode = got_tree_entry_get_mode(te);
7140 if (s->show_ids) {
7141 err = got_object_id_str(&id_str,
7142 got_tree_entry_get_id(te));
7143 if (err)
7144 return got_error_from_errno(
7145 "got_object_id_str");
7147 if (got_object_tree_entry_is_submodule(te))
7148 modestr = "$";
7149 else if (S_ISLNK(mode)) {
7150 int i;
7152 err = got_tree_entry_get_symlink_target(&link_target,
7153 te, s->repo);
7154 if (err) {
7155 free(id_str);
7156 return err;
7158 for (i = 0; i < strlen(link_target); i++) {
7159 if (!isprint((unsigned char)link_target[i]))
7160 link_target[i] = '?';
7162 modestr = "@";
7164 else if (S_ISDIR(mode))
7165 modestr = "/";
7166 else if (mode & S_IXUSR)
7167 modestr = "*";
7168 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7169 got_tree_entry_get_name(te), modestr,
7170 link_target ? " -> ": "",
7171 link_target ? link_target : "") == -1) {
7172 free(id_str);
7173 free(link_target);
7174 return got_error_from_errno("asprintf");
7176 free(id_str);
7177 free(link_target);
7179 /* use full line width to determine view->maxx */
7180 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7181 if (err) {
7182 free(line);
7183 break;
7185 view->maxx = MAX(view->maxx, width);
7186 free(wline);
7187 wline = NULL;
7189 err = format_line(&wline, &width, &scrollx, line, view->x,
7190 view->ncols, 0, 0);
7191 if (err) {
7192 free(line);
7193 break;
7195 if (n == s->selected) {
7196 if (view->focussed)
7197 wstandout(view->window);
7198 s->selected_entry = te;
7200 tc = match_color(&s->colors, line);
7201 if (tc)
7202 wattr_on(view->window,
7203 COLOR_PAIR(tc->colorpair), NULL);
7204 waddwstr(view->window, &wline[scrollx]);
7205 if (tc)
7206 wattr_off(view->window,
7207 COLOR_PAIR(tc->colorpair), NULL);
7208 if (width < view->ncols)
7209 waddch(view->window, '\n');
7210 if (n == s->selected && view->focussed)
7211 wstandend(view->window);
7212 free(line);
7213 free(wline);
7214 wline = NULL;
7215 n++;
7216 s->ndisplayed++;
7217 s->last_displayed_entry = te;
7218 if (--limit <= 0)
7219 break;
7222 return err;
7225 static void
7226 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7228 struct got_tree_entry *te;
7229 int isroot = s->tree == s->root;
7230 int i = 0;
7232 if (s->first_displayed_entry == NULL)
7233 return;
7235 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7236 while (i++ < maxscroll) {
7237 if (te == NULL) {
7238 if (!isroot)
7239 s->first_displayed_entry = NULL;
7240 break;
7242 s->first_displayed_entry = te;
7243 te = got_tree_entry_get_prev(s->tree, te);
7247 static const struct got_error *
7248 tree_scroll_down(struct tog_view *view, int maxscroll)
7250 struct tog_tree_view_state *s = &view->state.tree;
7251 struct got_tree_entry *next, *last;
7252 int n = 0;
7254 if (s->first_displayed_entry)
7255 next = got_tree_entry_get_next(s->tree,
7256 s->first_displayed_entry);
7257 else
7258 next = got_object_tree_get_first_entry(s->tree);
7260 last = s->last_displayed_entry;
7261 while (next && n++ < maxscroll) {
7262 if (last) {
7263 s->last_displayed_entry = last;
7264 last = got_tree_entry_get_next(s->tree, last);
7266 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7267 s->first_displayed_entry = next;
7268 next = got_tree_entry_get_next(s->tree, next);
7272 return NULL;
7275 static const struct got_error *
7276 tree_entry_path(char **path, struct tog_parent_trees *parents,
7277 struct got_tree_entry *te)
7279 const struct got_error *err = NULL;
7280 struct tog_parent_tree *pt;
7281 size_t len = 2; /* for leading slash and NUL */
7283 TAILQ_FOREACH(pt, parents, entry)
7284 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7285 + 1 /* slash */;
7286 if (te)
7287 len += strlen(got_tree_entry_get_name(te));
7289 *path = calloc(1, len);
7290 if (path == NULL)
7291 return got_error_from_errno("calloc");
7293 (*path)[0] = '/';
7294 pt = TAILQ_LAST(parents, tog_parent_trees);
7295 while (pt) {
7296 const char *name = got_tree_entry_get_name(pt->selected_entry);
7297 if (strlcat(*path, name, len) >= len) {
7298 err = got_error(GOT_ERR_NO_SPACE);
7299 goto done;
7301 if (strlcat(*path, "/", len) >= len) {
7302 err = got_error(GOT_ERR_NO_SPACE);
7303 goto done;
7305 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7307 if (te) {
7308 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7309 err = got_error(GOT_ERR_NO_SPACE);
7310 goto done;
7313 done:
7314 if (err) {
7315 free(*path);
7316 *path = NULL;
7318 return err;
7321 static const struct got_error *
7322 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7323 struct got_tree_entry *te, struct tog_parent_trees *parents,
7324 struct got_object_id *commit_id, struct got_repository *repo)
7326 const struct got_error *err = NULL;
7327 char *path;
7328 struct tog_view *blame_view;
7330 *new_view = NULL;
7332 err = tree_entry_path(&path, parents, te);
7333 if (err)
7334 return err;
7336 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7337 if (blame_view == NULL) {
7338 err = got_error_from_errno("view_open");
7339 goto done;
7342 err = open_blame_view(blame_view, path, commit_id, repo);
7343 if (err) {
7344 if (err->code == GOT_ERR_CANCELLED)
7345 err = NULL;
7346 view_close(blame_view);
7347 } else
7348 *new_view = blame_view;
7349 done:
7350 free(path);
7351 return err;
7354 static const struct got_error *
7355 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7356 struct tog_tree_view_state *s)
7358 struct tog_view *log_view;
7359 const struct got_error *err = NULL;
7360 char *path;
7362 *new_view = NULL;
7364 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7365 if (log_view == NULL)
7366 return got_error_from_errno("view_open");
7368 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7369 if (err)
7370 return err;
7372 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7373 path, 0);
7374 if (err)
7375 view_close(log_view);
7376 else
7377 *new_view = log_view;
7378 free(path);
7379 return err;
7382 static const struct got_error *
7383 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7384 const char *head_ref_name, struct got_repository *repo)
7386 const struct got_error *err = NULL;
7387 char *commit_id_str = NULL;
7388 struct tog_tree_view_state *s = &view->state.tree;
7389 struct got_commit_object *commit = NULL;
7391 TAILQ_INIT(&s->parents);
7392 STAILQ_INIT(&s->colors);
7394 s->commit_id = got_object_id_dup(commit_id);
7395 if (s->commit_id == NULL) {
7396 err = got_error_from_errno("got_object_id_dup");
7397 goto done;
7400 err = got_object_open_as_commit(&commit, repo, commit_id);
7401 if (err)
7402 goto done;
7405 * The root is opened here and will be closed when the view is closed.
7406 * Any visited subtrees and their path-wise parents are opened and
7407 * closed on demand.
7409 err = got_object_open_as_tree(&s->root, repo,
7410 got_object_commit_get_tree_id(commit));
7411 if (err)
7412 goto done;
7413 s->tree = s->root;
7415 err = got_object_id_str(&commit_id_str, commit_id);
7416 if (err != NULL)
7417 goto done;
7419 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7420 err = got_error_from_errno("asprintf");
7421 goto done;
7424 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7425 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7426 if (head_ref_name) {
7427 s->head_ref_name = strdup(head_ref_name);
7428 if (s->head_ref_name == NULL) {
7429 err = got_error_from_errno("strdup");
7430 goto done;
7433 s->repo = repo;
7435 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7436 err = add_color(&s->colors, "\\$$",
7437 TOG_COLOR_TREE_SUBMODULE,
7438 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7439 if (err)
7440 goto done;
7441 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7442 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7443 if (err)
7444 goto done;
7445 err = add_color(&s->colors, "/$",
7446 TOG_COLOR_TREE_DIRECTORY,
7447 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7448 if (err)
7449 goto done;
7451 err = add_color(&s->colors, "\\*$",
7452 TOG_COLOR_TREE_EXECUTABLE,
7453 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7454 if (err)
7455 goto done;
7457 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7458 get_color_value("TOG_COLOR_COMMIT"));
7459 if (err)
7460 goto done;
7463 view->show = show_tree_view;
7464 view->input = input_tree_view;
7465 view->close = close_tree_view;
7466 view->search_start = search_start_tree_view;
7467 view->search_next = search_next_tree_view;
7468 done:
7469 free(commit_id_str);
7470 if (commit)
7471 got_object_commit_close(commit);
7472 if (err) {
7473 if (view->close == NULL)
7474 close_tree_view(view);
7475 view_close(view);
7477 return err;
7480 static const struct got_error *
7481 close_tree_view(struct tog_view *view)
7483 struct tog_tree_view_state *s = &view->state.tree;
7485 free_colors(&s->colors);
7486 free(s->tree_label);
7487 s->tree_label = NULL;
7488 free(s->commit_id);
7489 s->commit_id = NULL;
7490 free(s->head_ref_name);
7491 s->head_ref_name = NULL;
7492 while (!TAILQ_EMPTY(&s->parents)) {
7493 struct tog_parent_tree *parent;
7494 parent = TAILQ_FIRST(&s->parents);
7495 TAILQ_REMOVE(&s->parents, parent, entry);
7496 if (parent->tree != s->root)
7497 got_object_tree_close(parent->tree);
7498 free(parent);
7501 if (s->tree != NULL && s->tree != s->root)
7502 got_object_tree_close(s->tree);
7503 if (s->root)
7504 got_object_tree_close(s->root);
7505 return NULL;
7508 static const struct got_error *
7509 search_start_tree_view(struct tog_view *view)
7511 struct tog_tree_view_state *s = &view->state.tree;
7513 s->matched_entry = NULL;
7514 return NULL;
7517 static int
7518 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7520 regmatch_t regmatch;
7522 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7523 0) == 0;
7526 static const struct got_error *
7527 search_next_tree_view(struct tog_view *view)
7529 struct tog_tree_view_state *s = &view->state.tree;
7530 struct got_tree_entry *te = NULL;
7532 if (!view->searching) {
7533 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7534 return NULL;
7537 if (s->matched_entry) {
7538 if (view->searching == TOG_SEARCH_FORWARD) {
7539 if (s->selected_entry)
7540 te = got_tree_entry_get_next(s->tree,
7541 s->selected_entry);
7542 else
7543 te = got_object_tree_get_first_entry(s->tree);
7544 } else {
7545 if (s->selected_entry == NULL)
7546 te = got_object_tree_get_last_entry(s->tree);
7547 else
7548 te = got_tree_entry_get_prev(s->tree,
7549 s->selected_entry);
7551 } else {
7552 if (s->selected_entry)
7553 te = s->selected_entry;
7554 else if (view->searching == TOG_SEARCH_FORWARD)
7555 te = got_object_tree_get_first_entry(s->tree);
7556 else
7557 te = got_object_tree_get_last_entry(s->tree);
7560 while (1) {
7561 if (te == NULL) {
7562 if (s->matched_entry == NULL) {
7563 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7564 return NULL;
7566 if (view->searching == TOG_SEARCH_FORWARD)
7567 te = got_object_tree_get_first_entry(s->tree);
7568 else
7569 te = got_object_tree_get_last_entry(s->tree);
7572 if (match_tree_entry(te, &view->regex)) {
7573 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7574 s->matched_entry = te;
7575 break;
7578 if (view->searching == TOG_SEARCH_FORWARD)
7579 te = got_tree_entry_get_next(s->tree, te);
7580 else
7581 te = got_tree_entry_get_prev(s->tree, te);
7584 if (s->matched_entry) {
7585 s->first_displayed_entry = s->matched_entry;
7586 s->selected = 0;
7589 return NULL;
7592 static const struct got_error *
7593 show_tree_view(struct tog_view *view)
7595 const struct got_error *err = NULL;
7596 struct tog_tree_view_state *s = &view->state.tree;
7597 char *parent_path;
7599 err = tree_entry_path(&parent_path, &s->parents, NULL);
7600 if (err)
7601 return err;
7603 err = draw_tree_entries(view, parent_path);
7604 free(parent_path);
7606 view_border(view);
7607 return err;
7610 static const struct got_error *
7611 tree_goto_line(struct tog_view *view, int nlines)
7613 const struct got_error *err = NULL;
7614 struct tog_tree_view_state *s = &view->state.tree;
7615 struct got_tree_entry **fte, **lte, **ste;
7616 int g, last, first = 1, i = 1;
7617 int root = s->tree == s->root;
7618 int off = root ? 1 : 2;
7620 g = view->gline;
7621 view->gline = 0;
7623 if (g == 0)
7624 g = 1;
7625 else if (g > got_object_tree_get_nentries(s->tree))
7626 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7628 fte = &s->first_displayed_entry;
7629 lte = &s->last_displayed_entry;
7630 ste = &s->selected_entry;
7632 if (*fte != NULL) {
7633 first = got_tree_entry_get_index(*fte);
7634 first += off; /* account for ".." */
7636 last = got_tree_entry_get_index(*lte);
7637 last += off;
7639 if (g >= first && g <= last && g - first < nlines) {
7640 s->selected = g - first;
7641 return NULL; /* gline is on the current page */
7644 if (*ste != NULL) {
7645 i = got_tree_entry_get_index(*ste);
7646 i += off;
7649 if (i < g) {
7650 err = tree_scroll_down(view, g - i);
7651 if (err)
7652 return err;
7653 if (got_tree_entry_get_index(*lte) >=
7654 got_object_tree_get_nentries(s->tree) - 1 &&
7655 first + s->selected < g &&
7656 s->selected < s->ndisplayed - 1) {
7657 first = got_tree_entry_get_index(*fte);
7658 first += off;
7659 s->selected = g - first;
7661 } else if (i > g)
7662 tree_scroll_up(s, i - g);
7664 if (g < nlines &&
7665 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7666 s->selected = g - 1;
7668 return NULL;
7671 static const struct got_error *
7672 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7674 const struct got_error *err = NULL;
7675 struct tog_tree_view_state *s = &view->state.tree;
7676 struct got_tree_entry *te;
7677 int n, nscroll = view->nlines - 3;
7679 if (view->gline)
7680 return tree_goto_line(view, nscroll);
7682 switch (ch) {
7683 case '0':
7684 case '$':
7685 case KEY_RIGHT:
7686 case 'l':
7687 case KEY_LEFT:
7688 case 'h':
7689 horizontal_scroll_input(view, ch);
7690 break;
7691 case 'i':
7692 s->show_ids = !s->show_ids;
7693 view->count = 0;
7694 break;
7695 case 'L':
7696 view->count = 0;
7697 if (!s->selected_entry)
7698 break;
7699 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7700 break;
7701 case 'R':
7702 view->count = 0;
7703 err = view_request_new(new_view, view, TOG_VIEW_REF);
7704 break;
7705 case 'g':
7706 case '=':
7707 case KEY_HOME:
7708 s->selected = 0;
7709 view->count = 0;
7710 if (s->tree == s->root)
7711 s->first_displayed_entry =
7712 got_object_tree_get_first_entry(s->tree);
7713 else
7714 s->first_displayed_entry = NULL;
7715 break;
7716 case 'G':
7717 case '*':
7718 case KEY_END: {
7719 int eos = view->nlines - 3;
7721 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7722 --eos; /* border */
7723 s->selected = 0;
7724 view->count = 0;
7725 te = got_object_tree_get_last_entry(s->tree);
7726 for (n = 0; n < eos; n++) {
7727 if (te == NULL) {
7728 if (s->tree != s->root) {
7729 s->first_displayed_entry = NULL;
7730 n++;
7732 break;
7734 s->first_displayed_entry = te;
7735 te = got_tree_entry_get_prev(s->tree, te);
7737 if (n > 0)
7738 s->selected = n - 1;
7739 break;
7741 case 'k':
7742 case KEY_UP:
7743 case CTRL('p'):
7744 if (s->selected > 0) {
7745 s->selected--;
7746 break;
7748 tree_scroll_up(s, 1);
7749 if (s->selected_entry == NULL ||
7750 (s->tree == s->root && s->selected_entry ==
7751 got_object_tree_get_first_entry(s->tree)))
7752 view->count = 0;
7753 break;
7754 case CTRL('u'):
7755 case 'u':
7756 nscroll /= 2;
7757 /* FALL THROUGH */
7758 case KEY_PPAGE:
7759 case CTRL('b'):
7760 case 'b':
7761 if (s->tree == s->root) {
7762 if (got_object_tree_get_first_entry(s->tree) ==
7763 s->first_displayed_entry)
7764 s->selected -= MIN(s->selected, nscroll);
7765 } else {
7766 if (s->first_displayed_entry == NULL)
7767 s->selected -= MIN(s->selected, nscroll);
7769 tree_scroll_up(s, MAX(0, nscroll));
7770 if (s->selected_entry == NULL ||
7771 (s->tree == s->root && s->selected_entry ==
7772 got_object_tree_get_first_entry(s->tree)))
7773 view->count = 0;
7774 break;
7775 case 'j':
7776 case KEY_DOWN:
7777 case CTRL('n'):
7778 if (s->selected < s->ndisplayed - 1) {
7779 s->selected++;
7780 break;
7782 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7783 == NULL) {
7784 /* can't scroll any further */
7785 view->count = 0;
7786 break;
7788 tree_scroll_down(view, 1);
7789 break;
7790 case CTRL('d'):
7791 case 'd':
7792 nscroll /= 2;
7793 /* FALL THROUGH */
7794 case KEY_NPAGE:
7795 case CTRL('f'):
7796 case 'f':
7797 case ' ':
7798 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7799 == NULL) {
7800 /* can't scroll any further; move cursor down */
7801 if (s->selected < s->ndisplayed - 1)
7802 s->selected += MIN(nscroll,
7803 s->ndisplayed - s->selected - 1);
7804 else
7805 view->count = 0;
7806 break;
7808 tree_scroll_down(view, nscroll);
7809 break;
7810 case KEY_ENTER:
7811 case '\r':
7812 case KEY_BACKSPACE:
7813 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7814 struct tog_parent_tree *parent;
7815 /* user selected '..' */
7816 if (s->tree == s->root) {
7817 view->count = 0;
7818 break;
7820 parent = TAILQ_FIRST(&s->parents);
7821 TAILQ_REMOVE(&s->parents, parent,
7822 entry);
7823 got_object_tree_close(s->tree);
7824 s->tree = parent->tree;
7825 s->first_displayed_entry =
7826 parent->first_displayed_entry;
7827 s->selected_entry =
7828 parent->selected_entry;
7829 s->selected = parent->selected;
7830 if (s->selected > view->nlines - 3) {
7831 err = offset_selection_down(view);
7832 if (err)
7833 break;
7835 free(parent);
7836 } else if (S_ISDIR(got_tree_entry_get_mode(
7837 s->selected_entry))) {
7838 struct got_tree_object *subtree;
7839 view->count = 0;
7840 err = got_object_open_as_tree(&subtree, s->repo,
7841 got_tree_entry_get_id(s->selected_entry));
7842 if (err)
7843 break;
7844 err = tree_view_visit_subtree(s, subtree);
7845 if (err) {
7846 got_object_tree_close(subtree);
7847 break;
7849 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7850 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7851 break;
7852 case KEY_RESIZE:
7853 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7854 s->selected = view->nlines - 4;
7855 view->count = 0;
7856 break;
7857 default:
7858 view->count = 0;
7859 break;
7862 return err;
7865 __dead static void
7866 usage_tree(void)
7868 endwin();
7869 fprintf(stderr,
7870 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7871 getprogname());
7872 exit(1);
7875 static const struct got_error *
7876 cmd_tree(int argc, char *argv[])
7878 const struct got_error *error;
7879 struct got_repository *repo = NULL;
7880 struct got_worktree *worktree = NULL;
7881 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7882 struct got_object_id *commit_id = NULL;
7883 struct got_commit_object *commit = NULL;
7884 const char *commit_id_arg = NULL;
7885 char *label = NULL;
7886 struct got_reference *ref = NULL;
7887 const char *head_ref_name = NULL;
7888 int ch;
7889 struct tog_view *view;
7890 int *pack_fds = NULL;
7892 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7893 switch (ch) {
7894 case 'c':
7895 commit_id_arg = optarg;
7896 break;
7897 case 'r':
7898 repo_path = realpath(optarg, NULL);
7899 if (repo_path == NULL)
7900 return got_error_from_errno2("realpath",
7901 optarg);
7902 break;
7903 default:
7904 usage_tree();
7905 /* NOTREACHED */
7909 argc -= optind;
7910 argv += optind;
7912 if (argc > 1)
7913 usage_tree();
7915 error = got_repo_pack_fds_open(&pack_fds);
7916 if (error != NULL)
7917 goto done;
7919 if (repo_path == NULL) {
7920 cwd = getcwd(NULL, 0);
7921 if (cwd == NULL)
7922 return got_error_from_errno("getcwd");
7923 error = got_worktree_open(&worktree, cwd);
7924 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7925 goto done;
7926 if (worktree)
7927 repo_path =
7928 strdup(got_worktree_get_repo_path(worktree));
7929 else
7930 repo_path = strdup(cwd);
7931 if (repo_path == NULL) {
7932 error = got_error_from_errno("strdup");
7933 goto done;
7937 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7938 if (error != NULL)
7939 goto done;
7941 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7942 repo, worktree);
7943 if (error)
7944 goto done;
7946 init_curses();
7948 error = apply_unveil(got_repo_get_path(repo), NULL);
7949 if (error)
7950 goto done;
7952 error = tog_load_refs(repo, 0);
7953 if (error)
7954 goto done;
7956 if (commit_id_arg == NULL) {
7957 error = got_repo_match_object_id(&commit_id, &label,
7958 worktree ? got_worktree_get_head_ref_name(worktree) :
7959 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7960 if (error)
7961 goto done;
7962 head_ref_name = label;
7963 } else {
7964 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7965 if (error == NULL)
7966 head_ref_name = got_ref_get_name(ref);
7967 else if (error->code != GOT_ERR_NOT_REF)
7968 goto done;
7969 error = got_repo_match_object_id(&commit_id, NULL,
7970 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7971 if (error)
7972 goto done;
7975 error = got_object_open_as_commit(&commit, repo, commit_id);
7976 if (error)
7977 goto done;
7979 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7980 if (view == NULL) {
7981 error = got_error_from_errno("view_open");
7982 goto done;
7984 error = open_tree_view(view, commit_id, head_ref_name, repo);
7985 if (error)
7986 goto done;
7987 if (!got_path_is_root_dir(in_repo_path)) {
7988 error = tree_view_walk_path(&view->state.tree, commit,
7989 in_repo_path);
7990 if (error)
7991 goto done;
7994 if (worktree) {
7995 /* Release work tree lock. */
7996 got_worktree_close(worktree);
7997 worktree = NULL;
7999 error = view_loop(view);
8000 done:
8001 free(repo_path);
8002 free(cwd);
8003 free(commit_id);
8004 free(label);
8005 if (ref)
8006 got_ref_close(ref);
8007 if (repo) {
8008 const struct got_error *close_err = got_repo_close(repo);
8009 if (error == NULL)
8010 error = close_err;
8012 if (pack_fds) {
8013 const struct got_error *pack_err =
8014 got_repo_pack_fds_close(pack_fds);
8015 if (error == NULL)
8016 error = pack_err;
8018 tog_free_refs();
8019 return error;
8022 static const struct got_error *
8023 ref_view_load_refs(struct tog_ref_view_state *s)
8025 struct got_reflist_entry *sre;
8026 struct tog_reflist_entry *re;
8028 s->nrefs = 0;
8029 TAILQ_FOREACH(sre, &tog_refs, entry) {
8030 if (strncmp(got_ref_get_name(sre->ref),
8031 "refs/got/", 9) == 0 &&
8032 strncmp(got_ref_get_name(sre->ref),
8033 "refs/got/backup/", 16) != 0)
8034 continue;
8036 re = malloc(sizeof(*re));
8037 if (re == NULL)
8038 return got_error_from_errno("malloc");
8040 re->ref = got_ref_dup(sre->ref);
8041 if (re->ref == NULL)
8042 return got_error_from_errno("got_ref_dup");
8043 re->idx = s->nrefs++;
8044 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8047 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8048 return NULL;
8051 static void
8052 ref_view_free_refs(struct tog_ref_view_state *s)
8054 struct tog_reflist_entry *re;
8056 while (!TAILQ_EMPTY(&s->refs)) {
8057 re = TAILQ_FIRST(&s->refs);
8058 TAILQ_REMOVE(&s->refs, re, entry);
8059 got_ref_close(re->ref);
8060 free(re);
8064 static const struct got_error *
8065 open_ref_view(struct tog_view *view, struct got_repository *repo)
8067 const struct got_error *err = NULL;
8068 struct tog_ref_view_state *s = &view->state.ref;
8070 s->selected_entry = 0;
8071 s->repo = repo;
8073 TAILQ_INIT(&s->refs);
8074 STAILQ_INIT(&s->colors);
8076 err = ref_view_load_refs(s);
8077 if (err)
8078 goto done;
8080 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8081 err = add_color(&s->colors, "^refs/heads/",
8082 TOG_COLOR_REFS_HEADS,
8083 get_color_value("TOG_COLOR_REFS_HEADS"));
8084 if (err)
8085 goto done;
8087 err = add_color(&s->colors, "^refs/tags/",
8088 TOG_COLOR_REFS_TAGS,
8089 get_color_value("TOG_COLOR_REFS_TAGS"));
8090 if (err)
8091 goto done;
8093 err = add_color(&s->colors, "^refs/remotes/",
8094 TOG_COLOR_REFS_REMOTES,
8095 get_color_value("TOG_COLOR_REFS_REMOTES"));
8096 if (err)
8097 goto done;
8099 err = add_color(&s->colors, "^refs/got/backup/",
8100 TOG_COLOR_REFS_BACKUP,
8101 get_color_value("TOG_COLOR_REFS_BACKUP"));
8102 if (err)
8103 goto done;
8106 view->show = show_ref_view;
8107 view->input = input_ref_view;
8108 view->close = close_ref_view;
8109 view->search_start = search_start_ref_view;
8110 view->search_next = search_next_ref_view;
8111 done:
8112 if (err) {
8113 if (view->close == NULL)
8114 close_ref_view(view);
8115 view_close(view);
8117 return err;
8120 static const struct got_error *
8121 close_ref_view(struct tog_view *view)
8123 struct tog_ref_view_state *s = &view->state.ref;
8125 ref_view_free_refs(s);
8126 free_colors(&s->colors);
8128 return NULL;
8131 static const struct got_error *
8132 resolve_reflist_entry(struct got_object_id **commit_id,
8133 struct tog_reflist_entry *re, struct got_repository *repo)
8135 const struct got_error *err = NULL;
8136 struct got_object_id *obj_id;
8137 struct got_tag_object *tag = NULL;
8138 int obj_type;
8140 *commit_id = NULL;
8142 err = got_ref_resolve(&obj_id, repo, re->ref);
8143 if (err)
8144 return err;
8146 err = got_object_get_type(&obj_type, repo, obj_id);
8147 if (err)
8148 goto done;
8150 switch (obj_type) {
8151 case GOT_OBJ_TYPE_COMMIT:
8152 *commit_id = obj_id;
8153 break;
8154 case GOT_OBJ_TYPE_TAG:
8155 err = got_object_open_as_tag(&tag, repo, obj_id);
8156 if (err)
8157 goto done;
8158 free(obj_id);
8159 err = got_object_get_type(&obj_type, repo,
8160 got_object_tag_get_object_id(tag));
8161 if (err)
8162 goto done;
8163 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8164 err = got_error(GOT_ERR_OBJ_TYPE);
8165 goto done;
8167 *commit_id = got_object_id_dup(
8168 got_object_tag_get_object_id(tag));
8169 if (*commit_id == NULL) {
8170 err = got_error_from_errno("got_object_id_dup");
8171 goto done;
8173 break;
8174 default:
8175 err = got_error(GOT_ERR_OBJ_TYPE);
8176 break;
8179 done:
8180 if (tag)
8181 got_object_tag_close(tag);
8182 if (err) {
8183 free(*commit_id);
8184 *commit_id = NULL;
8186 return err;
8189 static const struct got_error *
8190 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8191 struct tog_reflist_entry *re, struct got_repository *repo)
8193 struct tog_view *log_view;
8194 const struct got_error *err = NULL;
8195 struct got_object_id *commit_id = NULL;
8197 *new_view = NULL;
8199 err = resolve_reflist_entry(&commit_id, re, repo);
8200 if (err) {
8201 if (err->code != GOT_ERR_OBJ_TYPE)
8202 return err;
8203 else
8204 return NULL;
8207 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8208 if (log_view == NULL) {
8209 err = got_error_from_errno("view_open");
8210 goto done;
8213 err = open_log_view(log_view, commit_id, repo,
8214 got_ref_get_name(re->ref), "", 0);
8215 done:
8216 if (err)
8217 view_close(log_view);
8218 else
8219 *new_view = log_view;
8220 free(commit_id);
8221 return err;
8224 static void
8225 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8227 struct tog_reflist_entry *re;
8228 int i = 0;
8230 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8231 return;
8233 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8234 while (i++ < maxscroll) {
8235 if (re == NULL)
8236 break;
8237 s->first_displayed_entry = re;
8238 re = TAILQ_PREV(re, tog_reflist_head, entry);
8242 static const struct got_error *
8243 ref_scroll_down(struct tog_view *view, int maxscroll)
8245 struct tog_ref_view_state *s = &view->state.ref;
8246 struct tog_reflist_entry *next, *last;
8247 int n = 0;
8249 if (s->first_displayed_entry)
8250 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8251 else
8252 next = TAILQ_FIRST(&s->refs);
8254 last = s->last_displayed_entry;
8255 while (next && n++ < maxscroll) {
8256 if (last) {
8257 s->last_displayed_entry = last;
8258 last = TAILQ_NEXT(last, entry);
8260 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8261 s->first_displayed_entry = next;
8262 next = TAILQ_NEXT(next, entry);
8266 return NULL;
8269 static const struct got_error *
8270 search_start_ref_view(struct tog_view *view)
8272 struct tog_ref_view_state *s = &view->state.ref;
8274 s->matched_entry = NULL;
8275 return NULL;
8278 static int
8279 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8281 regmatch_t regmatch;
8283 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8284 0) == 0;
8287 static const struct got_error *
8288 search_next_ref_view(struct tog_view *view)
8290 struct tog_ref_view_state *s = &view->state.ref;
8291 struct tog_reflist_entry *re = NULL;
8293 if (!view->searching) {
8294 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8295 return NULL;
8298 if (s->matched_entry) {
8299 if (view->searching == TOG_SEARCH_FORWARD) {
8300 if (s->selected_entry)
8301 re = TAILQ_NEXT(s->selected_entry, entry);
8302 else
8303 re = TAILQ_PREV(s->selected_entry,
8304 tog_reflist_head, entry);
8305 } else {
8306 if (s->selected_entry == NULL)
8307 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8308 else
8309 re = TAILQ_PREV(s->selected_entry,
8310 tog_reflist_head, entry);
8312 } else {
8313 if (s->selected_entry)
8314 re = s->selected_entry;
8315 else if (view->searching == TOG_SEARCH_FORWARD)
8316 re = TAILQ_FIRST(&s->refs);
8317 else
8318 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8321 while (1) {
8322 if (re == NULL) {
8323 if (s->matched_entry == NULL) {
8324 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8325 return NULL;
8327 if (view->searching == TOG_SEARCH_FORWARD)
8328 re = TAILQ_FIRST(&s->refs);
8329 else
8330 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8333 if (match_reflist_entry(re, &view->regex)) {
8334 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8335 s->matched_entry = re;
8336 break;
8339 if (view->searching == TOG_SEARCH_FORWARD)
8340 re = TAILQ_NEXT(re, entry);
8341 else
8342 re = TAILQ_PREV(re, tog_reflist_head, entry);
8345 if (s->matched_entry) {
8346 s->first_displayed_entry = s->matched_entry;
8347 s->selected = 0;
8350 return NULL;
8353 static const struct got_error *
8354 show_ref_view(struct tog_view *view)
8356 const struct got_error *err = NULL;
8357 struct tog_ref_view_state *s = &view->state.ref;
8358 struct tog_reflist_entry *re;
8359 char *line = NULL;
8360 wchar_t *wline;
8361 struct tog_color *tc;
8362 int width, n, scrollx;
8363 int limit = view->nlines;
8365 werase(view->window);
8367 s->ndisplayed = 0;
8368 if (view_is_hsplit_top(view))
8369 --limit; /* border */
8371 if (limit == 0)
8372 return NULL;
8374 re = s->first_displayed_entry;
8376 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8377 s->nrefs) == -1)
8378 return got_error_from_errno("asprintf");
8380 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8381 if (err) {
8382 free(line);
8383 return err;
8385 if (view_needs_focus_indication(view))
8386 wstandout(view->window);
8387 waddwstr(view->window, wline);
8388 while (width++ < view->ncols)
8389 waddch(view->window, ' ');
8390 if (view_needs_focus_indication(view))
8391 wstandend(view->window);
8392 free(wline);
8393 wline = NULL;
8394 free(line);
8395 line = NULL;
8396 if (--limit <= 0)
8397 return NULL;
8399 n = 0;
8400 view->maxx = 0;
8401 while (re && limit > 0) {
8402 char *line = NULL;
8403 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8405 if (s->show_date) {
8406 struct got_commit_object *ci;
8407 struct got_tag_object *tag;
8408 struct got_object_id *id;
8409 struct tm tm;
8410 time_t t;
8412 err = got_ref_resolve(&id, s->repo, re->ref);
8413 if (err)
8414 return err;
8415 err = got_object_open_as_tag(&tag, s->repo, id);
8416 if (err) {
8417 if (err->code != GOT_ERR_OBJ_TYPE) {
8418 free(id);
8419 return err;
8421 err = got_object_open_as_commit(&ci, s->repo,
8422 id);
8423 if (err) {
8424 free(id);
8425 return err;
8427 t = got_object_commit_get_committer_time(ci);
8428 got_object_commit_close(ci);
8429 } else {
8430 t = got_object_tag_get_tagger_time(tag);
8431 got_object_tag_close(tag);
8433 free(id);
8434 if (gmtime_r(&t, &tm) == NULL)
8435 return got_error_from_errno("gmtime_r");
8436 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8437 return got_error(GOT_ERR_NO_SPACE);
8439 if (got_ref_is_symbolic(re->ref)) {
8440 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8441 ymd : "", got_ref_get_name(re->ref),
8442 got_ref_get_symref_target(re->ref)) == -1)
8443 return got_error_from_errno("asprintf");
8444 } else if (s->show_ids) {
8445 struct got_object_id *id;
8446 char *id_str;
8447 err = got_ref_resolve(&id, s->repo, re->ref);
8448 if (err)
8449 return err;
8450 err = got_object_id_str(&id_str, id);
8451 if (err) {
8452 free(id);
8453 return err;
8455 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8456 got_ref_get_name(re->ref), id_str) == -1) {
8457 err = got_error_from_errno("asprintf");
8458 free(id);
8459 free(id_str);
8460 return err;
8462 free(id);
8463 free(id_str);
8464 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8465 got_ref_get_name(re->ref)) == -1)
8466 return got_error_from_errno("asprintf");
8468 /* use full line width to determine view->maxx */
8469 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8470 if (err) {
8471 free(line);
8472 return err;
8474 view->maxx = MAX(view->maxx, width);
8475 free(wline);
8476 wline = NULL;
8478 err = format_line(&wline, &width, &scrollx, line, view->x,
8479 view->ncols, 0, 0);
8480 if (err) {
8481 free(line);
8482 return err;
8484 if (n == s->selected) {
8485 if (view->focussed)
8486 wstandout(view->window);
8487 s->selected_entry = re;
8489 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8490 if (tc)
8491 wattr_on(view->window,
8492 COLOR_PAIR(tc->colorpair), NULL);
8493 waddwstr(view->window, &wline[scrollx]);
8494 if (tc)
8495 wattr_off(view->window,
8496 COLOR_PAIR(tc->colorpair), NULL);
8497 if (width < view->ncols)
8498 waddch(view->window, '\n');
8499 if (n == s->selected && view->focussed)
8500 wstandend(view->window);
8501 free(line);
8502 free(wline);
8503 wline = NULL;
8504 n++;
8505 s->ndisplayed++;
8506 s->last_displayed_entry = re;
8508 limit--;
8509 re = TAILQ_NEXT(re, entry);
8512 view_border(view);
8513 return err;
8516 static const struct got_error *
8517 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8518 struct tog_reflist_entry *re, struct got_repository *repo)
8520 const struct got_error *err = NULL;
8521 struct got_object_id *commit_id = NULL;
8522 struct tog_view *tree_view;
8524 *new_view = NULL;
8526 err = resolve_reflist_entry(&commit_id, re, repo);
8527 if (err) {
8528 if (err->code != GOT_ERR_OBJ_TYPE)
8529 return err;
8530 else
8531 return NULL;
8535 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8536 if (tree_view == NULL) {
8537 err = got_error_from_errno("view_open");
8538 goto done;
8541 err = open_tree_view(tree_view, commit_id,
8542 got_ref_get_name(re->ref), repo);
8543 if (err)
8544 goto done;
8546 *new_view = tree_view;
8547 done:
8548 free(commit_id);
8549 return err;
8552 static const struct got_error *
8553 ref_goto_line(struct tog_view *view, int nlines)
8555 const struct got_error *err = NULL;
8556 struct tog_ref_view_state *s = &view->state.ref;
8557 int g, idx = s->selected_entry->idx;
8559 g = view->gline;
8560 view->gline = 0;
8562 if (g == 0)
8563 g = 1;
8564 else if (g > s->nrefs)
8565 g = s->nrefs;
8567 if (g >= s->first_displayed_entry->idx + 1 &&
8568 g <= s->last_displayed_entry->idx + 1 &&
8569 g - s->first_displayed_entry->idx - 1 < nlines) {
8570 s->selected = g - s->first_displayed_entry->idx - 1;
8571 return NULL;
8574 if (idx + 1 < g) {
8575 err = ref_scroll_down(view, g - idx - 1);
8576 if (err)
8577 return err;
8578 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8579 s->first_displayed_entry->idx + s->selected < g &&
8580 s->selected < s->ndisplayed - 1)
8581 s->selected = g - s->first_displayed_entry->idx - 1;
8582 } else if (idx + 1 > g)
8583 ref_scroll_up(s, idx - g + 1);
8585 if (g < nlines && s->first_displayed_entry->idx == 0)
8586 s->selected = g - 1;
8588 return NULL;
8592 static const struct got_error *
8593 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8595 const struct got_error *err = NULL;
8596 struct tog_ref_view_state *s = &view->state.ref;
8597 struct tog_reflist_entry *re;
8598 int n, nscroll = view->nlines - 1;
8600 if (view->gline)
8601 return ref_goto_line(view, nscroll);
8603 switch (ch) {
8604 case '0':
8605 case '$':
8606 case KEY_RIGHT:
8607 case 'l':
8608 case KEY_LEFT:
8609 case 'h':
8610 horizontal_scroll_input(view, ch);
8611 break;
8612 case 'i':
8613 s->show_ids = !s->show_ids;
8614 view->count = 0;
8615 break;
8616 case 'm':
8617 s->show_date = !s->show_date;
8618 view->count = 0;
8619 break;
8620 case 'o':
8621 s->sort_by_date = !s->sort_by_date;
8622 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8623 view->count = 0;
8624 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8625 got_ref_cmp_by_commit_timestamp_descending :
8626 tog_ref_cmp_by_name, s->repo);
8627 if (err)
8628 break;
8629 got_reflist_object_id_map_free(tog_refs_idmap);
8630 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8631 &tog_refs, s->repo);
8632 if (err)
8633 break;
8634 ref_view_free_refs(s);
8635 err = ref_view_load_refs(s);
8636 break;
8637 case KEY_ENTER:
8638 case '\r':
8639 view->count = 0;
8640 if (!s->selected_entry)
8641 break;
8642 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8643 break;
8644 case 'T':
8645 view->count = 0;
8646 if (!s->selected_entry)
8647 break;
8648 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8649 break;
8650 case 'g':
8651 case '=':
8652 case KEY_HOME:
8653 s->selected = 0;
8654 view->count = 0;
8655 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8656 break;
8657 case 'G':
8658 case '*':
8659 case KEY_END: {
8660 int eos = view->nlines - 1;
8662 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8663 --eos; /* border */
8664 s->selected = 0;
8665 view->count = 0;
8666 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8667 for (n = 0; n < eos; n++) {
8668 if (re == NULL)
8669 break;
8670 s->first_displayed_entry = re;
8671 re = TAILQ_PREV(re, tog_reflist_head, entry);
8673 if (n > 0)
8674 s->selected = n - 1;
8675 break;
8677 case 'k':
8678 case KEY_UP:
8679 case CTRL('p'):
8680 if (s->selected > 0) {
8681 s->selected--;
8682 break;
8684 ref_scroll_up(s, 1);
8685 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8686 view->count = 0;
8687 break;
8688 case CTRL('u'):
8689 case 'u':
8690 nscroll /= 2;
8691 /* FALL THROUGH */
8692 case KEY_PPAGE:
8693 case CTRL('b'):
8694 case 'b':
8695 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8696 s->selected -= MIN(nscroll, s->selected);
8697 ref_scroll_up(s, MAX(0, nscroll));
8698 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8699 view->count = 0;
8700 break;
8701 case 'j':
8702 case KEY_DOWN:
8703 case CTRL('n'):
8704 if (s->selected < s->ndisplayed - 1) {
8705 s->selected++;
8706 break;
8708 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8709 /* can't scroll any further */
8710 view->count = 0;
8711 break;
8713 ref_scroll_down(view, 1);
8714 break;
8715 case CTRL('d'):
8716 case 'd':
8717 nscroll /= 2;
8718 /* FALL THROUGH */
8719 case KEY_NPAGE:
8720 case CTRL('f'):
8721 case 'f':
8722 case ' ':
8723 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8724 /* can't scroll any further; move cursor down */
8725 if (s->selected < s->ndisplayed - 1)
8726 s->selected += MIN(nscroll,
8727 s->ndisplayed - s->selected - 1);
8728 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8729 s->selected += s->ndisplayed - s->selected - 1;
8730 view->count = 0;
8731 break;
8733 ref_scroll_down(view, nscroll);
8734 break;
8735 case CTRL('l'):
8736 view->count = 0;
8737 tog_free_refs();
8738 err = tog_load_refs(s->repo, s->sort_by_date);
8739 if (err)
8740 break;
8741 ref_view_free_refs(s);
8742 err = ref_view_load_refs(s);
8743 break;
8744 case KEY_RESIZE:
8745 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8746 s->selected = view->nlines - 2;
8747 break;
8748 default:
8749 view->count = 0;
8750 break;
8753 return err;
8756 __dead static void
8757 usage_ref(void)
8759 endwin();
8760 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8761 getprogname());
8762 exit(1);
8765 static const struct got_error *
8766 cmd_ref(int argc, char *argv[])
8768 const struct got_error *error;
8769 struct got_repository *repo = NULL;
8770 struct got_worktree *worktree = NULL;
8771 char *cwd = NULL, *repo_path = NULL;
8772 int ch;
8773 struct tog_view *view;
8774 int *pack_fds = NULL;
8776 while ((ch = getopt(argc, argv, "r:")) != -1) {
8777 switch (ch) {
8778 case 'r':
8779 repo_path = realpath(optarg, NULL);
8780 if (repo_path == NULL)
8781 return got_error_from_errno2("realpath",
8782 optarg);
8783 break;
8784 default:
8785 usage_ref();
8786 /* NOTREACHED */
8790 argc -= optind;
8791 argv += optind;
8793 if (argc > 1)
8794 usage_ref();
8796 error = got_repo_pack_fds_open(&pack_fds);
8797 if (error != NULL)
8798 goto done;
8800 if (repo_path == NULL) {
8801 cwd = getcwd(NULL, 0);
8802 if (cwd == NULL)
8803 return got_error_from_errno("getcwd");
8804 error = got_worktree_open(&worktree, cwd);
8805 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8806 goto done;
8807 if (worktree)
8808 repo_path =
8809 strdup(got_worktree_get_repo_path(worktree));
8810 else
8811 repo_path = strdup(cwd);
8812 if (repo_path == NULL) {
8813 error = got_error_from_errno("strdup");
8814 goto done;
8818 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8819 if (error != NULL)
8820 goto done;
8822 init_curses();
8824 error = apply_unveil(got_repo_get_path(repo), NULL);
8825 if (error)
8826 goto done;
8828 error = tog_load_refs(repo, 0);
8829 if (error)
8830 goto done;
8832 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8833 if (view == NULL) {
8834 error = got_error_from_errno("view_open");
8835 goto done;
8838 error = open_ref_view(view, repo);
8839 if (error)
8840 goto done;
8842 if (worktree) {
8843 /* Release work tree lock. */
8844 got_worktree_close(worktree);
8845 worktree = NULL;
8847 error = view_loop(view);
8848 done:
8849 free(repo_path);
8850 free(cwd);
8851 if (repo) {
8852 const struct got_error *close_err = got_repo_close(repo);
8853 if (close_err)
8854 error = close_err;
8856 if (pack_fds) {
8857 const struct got_error *pack_err =
8858 got_repo_pack_fds_close(pack_fds);
8859 if (error == NULL)
8860 error = pack_err;
8862 tog_free_refs();
8863 return error;
8866 static const struct got_error*
8867 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8868 const char *str)
8870 size_t len;
8872 if (win == NULL)
8873 win = stdscr;
8875 len = strlen(str);
8876 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8878 if (focus)
8879 wstandout(win);
8880 if (mvwprintw(win, y, x, "%s", str) == ERR)
8881 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8882 if (focus)
8883 wstandend(win);
8885 return NULL;
8888 static const struct got_error *
8889 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8891 off_t *p;
8893 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8894 if (p == NULL) {
8895 free(*line_offsets);
8896 *line_offsets = NULL;
8897 return got_error_from_errno("reallocarray");
8900 *line_offsets = p;
8901 (*line_offsets)[*nlines] = off;
8902 ++(*nlines);
8903 return NULL;
8906 static const struct got_error *
8907 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8909 *ret = 0;
8911 for (;n > 0; --n, ++km) {
8912 char *t0, *t, *k;
8913 size_t len = 1;
8915 if (km->keys == NULL)
8916 continue;
8918 t = t0 = strdup(km->keys);
8919 if (t0 == NULL)
8920 return got_error_from_errno("strdup");
8922 len += strlen(t);
8923 while ((k = strsep(&t, " ")) != NULL)
8924 len += strlen(k) > 1 ? 2 : 0;
8925 free(t0);
8926 *ret = MAX(*ret, len);
8929 return NULL;
8933 * Write keymap section headers, keys, and key info in km to f.
8934 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8935 * wrap control and symbolic keys in guillemets, else use <>.
8937 static const struct got_error *
8938 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8940 int n, len = width;
8942 if (km->keys) {
8943 static const char *u8_glyph[] = {
8944 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8945 "\xe2\x80\xba" /* U+203A (utf8 >) */
8947 char *t0, *t, *k;
8948 int cs, s, first = 1;
8950 cs = got_locale_is_utf8();
8952 t = t0 = strdup(km->keys);
8953 if (t0 == NULL)
8954 return got_error_from_errno("strdup");
8956 len = strlen(km->keys);
8957 while ((k = strsep(&t, " ")) != NULL) {
8958 s = strlen(k) > 1; /* control or symbolic key */
8959 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8960 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8961 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8962 if (n < 0) {
8963 free(t0);
8964 return got_error_from_errno("fprintf");
8966 first = 0;
8967 len += s ? 2 : 0;
8968 *off += n;
8970 free(t0);
8972 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8973 if (n < 0)
8974 return got_error_from_errno("fprintf");
8975 *off += n;
8977 return NULL;
8980 static const struct got_error *
8981 format_help(struct tog_help_view_state *s)
8983 const struct got_error *err = NULL;
8984 off_t off = 0;
8985 int i, max, n, show = s->all;
8986 static const struct tog_key_map km[] = {
8987 #define KEYMAP_(info, type) { NULL, (info), type }
8988 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8989 GENERATE_HELP
8990 #undef KEYMAP_
8991 #undef KEY_
8994 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8995 if (err)
8996 return err;
8998 n = nitems(km);
8999 err = max_key_str(&max, km, n);
9000 if (err)
9001 return err;
9003 for (i = 0; i < n; ++i) {
9004 if (km[i].keys == NULL) {
9005 show = s->all;
9006 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9007 km[i].type == s->type || s->all)
9008 show = 1;
9010 if (show) {
9011 err = format_help_line(&off, s->f, &km[i], max);
9012 if (err)
9013 return err;
9014 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9015 if (err)
9016 return err;
9019 fputc('\n', s->f);
9020 ++off;
9021 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9022 return err;
9025 static const struct got_error *
9026 create_help(struct tog_help_view_state *s)
9028 FILE *f;
9029 const struct got_error *err;
9031 free(s->line_offsets);
9032 s->line_offsets = NULL;
9033 s->nlines = 0;
9035 f = got_opentemp();
9036 if (f == NULL)
9037 return got_error_from_errno("got_opentemp");
9038 s->f = f;
9040 err = format_help(s);
9041 if (err)
9042 return err;
9044 if (s->f && fflush(s->f) != 0)
9045 return got_error_from_errno("fflush");
9047 return NULL;
9050 static const struct got_error *
9051 search_start_help_view(struct tog_view *view)
9053 view->state.help.matched_line = 0;
9054 return NULL;
9057 static void
9058 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9059 size_t *nlines, int **first, int **last, int **match, int **selected)
9061 struct tog_help_view_state *s = &view->state.help;
9063 *f = s->f;
9064 *nlines = s->nlines;
9065 *line_offsets = s->line_offsets;
9066 *match = &s->matched_line;
9067 *first = &s->first_displayed_line;
9068 *last = &s->last_displayed_line;
9069 *selected = &s->selected_line;
9072 static const struct got_error *
9073 show_help_view(struct tog_view *view)
9075 struct tog_help_view_state *s = &view->state.help;
9076 const struct got_error *err;
9077 regmatch_t *regmatch = &view->regmatch;
9078 wchar_t *wline;
9079 char *line;
9080 ssize_t linelen;
9081 size_t linesz = 0;
9082 int width, nprinted = 0, rc = 0;
9083 int eos = view->nlines;
9085 if (view_is_hsplit_top(view))
9086 --eos; /* account for border */
9088 s->lineno = 0;
9089 rewind(s->f);
9090 werase(view->window);
9092 if (view->gline > s->nlines - 1)
9093 view->gline = s->nlines - 1;
9095 err = win_draw_center(view->window, 0, 0, view->ncols,
9096 view_needs_focus_indication(view),
9097 "tog help (press q to return to tog)");
9098 if (err)
9099 return err;
9100 if (eos <= 1)
9101 return NULL;
9102 waddstr(view->window, "\n\n");
9103 eos -= 2;
9105 s->eof = 0;
9106 view->maxx = 0;
9107 line = NULL;
9108 while (eos > 0 && nprinted < eos) {
9109 attr_t attr = 0;
9111 linelen = getline(&line, &linesz, s->f);
9112 if (linelen == -1) {
9113 if (!feof(s->f)) {
9114 free(line);
9115 return got_ferror(s->f, GOT_ERR_IO);
9117 s->eof = 1;
9118 break;
9120 if (++s->lineno < s->first_displayed_line)
9121 continue;
9122 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9123 continue;
9124 if (s->lineno == view->hiline)
9125 attr = A_STANDOUT;
9127 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9128 view->x ? 1 : 0);
9129 if (err) {
9130 free(line);
9131 return err;
9133 view->maxx = MAX(view->maxx, width);
9134 free(wline);
9135 wline = NULL;
9137 if (attr)
9138 wattron(view->window, attr);
9139 if (s->first_displayed_line + nprinted == s->matched_line &&
9140 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9141 err = add_matched_line(&width, line, view->ncols - 1, 0,
9142 view->window, view->x, regmatch);
9143 if (err) {
9144 free(line);
9145 return err;
9147 } else {
9148 int skip;
9150 err = format_line(&wline, &width, &skip, line,
9151 view->x, view->ncols, 0, view->x ? 1 : 0);
9152 if (err) {
9153 free(line);
9154 return err;
9156 waddwstr(view->window, &wline[skip]);
9157 free(wline);
9158 wline = NULL;
9160 if (s->lineno == view->hiline) {
9161 while (width++ < view->ncols)
9162 waddch(view->window, ' ');
9163 } else {
9164 if (width < view->ncols)
9165 waddch(view->window, '\n');
9167 if (attr)
9168 wattroff(view->window, attr);
9169 if (++nprinted == 1)
9170 s->first_displayed_line = s->lineno;
9172 free(line);
9173 if (nprinted > 0)
9174 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9175 else
9176 s->last_displayed_line = s->first_displayed_line;
9178 view_border(view);
9180 if (s->eof) {
9181 rc = waddnstr(view->window,
9182 "See the tog(1) manual page for full documentation",
9183 view->ncols - 1);
9184 if (rc == ERR)
9185 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9186 } else {
9187 wmove(view->window, view->nlines - 1, 0);
9188 wclrtoeol(view->window);
9189 wstandout(view->window);
9190 rc = waddnstr(view->window, "scroll down for more...",
9191 view->ncols - 1);
9192 if (rc == ERR)
9193 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9194 if (getcurx(view->window) < view->ncols - 6) {
9195 rc = wprintw(view->window, "[%.0f%%]",
9196 100.00 * s->last_displayed_line / s->nlines);
9197 if (rc == ERR)
9198 return got_error_msg(GOT_ERR_IO, "wprintw");
9200 wstandend(view->window);
9203 return NULL;
9206 static const struct got_error *
9207 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9209 struct tog_help_view_state *s = &view->state.help;
9210 const struct got_error *err = NULL;
9211 char *line = NULL;
9212 ssize_t linelen;
9213 size_t linesz = 0;
9214 int eos, nscroll;
9216 eos = nscroll = view->nlines;
9217 if (view_is_hsplit_top(view))
9218 --eos; /* border */
9220 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9222 switch (ch) {
9223 case '0':
9224 case '$':
9225 case KEY_RIGHT:
9226 case 'l':
9227 case KEY_LEFT:
9228 case 'h':
9229 horizontal_scroll_input(view, ch);
9230 break;
9231 case 'g':
9232 case KEY_HOME:
9233 s->first_displayed_line = 1;
9234 view->count = 0;
9235 break;
9236 case 'G':
9237 case KEY_END:
9238 view->count = 0;
9239 if (s->eof)
9240 break;
9241 s->first_displayed_line = (s->nlines - eos) + 3;
9242 s->eof = 1;
9243 break;
9244 case 'k':
9245 case KEY_UP:
9246 if (s->first_displayed_line > 1)
9247 --s->first_displayed_line;
9248 else
9249 view->count = 0;
9250 break;
9251 case CTRL('u'):
9252 case 'u':
9253 nscroll /= 2;
9254 /* FALL THROUGH */
9255 case KEY_PPAGE:
9256 case CTRL('b'):
9257 case 'b':
9258 if (s->first_displayed_line == 1) {
9259 view->count = 0;
9260 break;
9262 while (--nscroll > 0 && s->first_displayed_line > 1)
9263 s->first_displayed_line--;
9264 break;
9265 case 'j':
9266 case KEY_DOWN:
9267 case CTRL('n'):
9268 if (!s->eof)
9269 ++s->first_displayed_line;
9270 else
9271 view->count = 0;
9272 break;
9273 case CTRL('d'):
9274 case 'd':
9275 nscroll /= 2;
9276 /* FALL THROUGH */
9277 case KEY_NPAGE:
9278 case CTRL('f'):
9279 case 'f':
9280 case ' ':
9281 if (s->eof) {
9282 view->count = 0;
9283 break;
9285 while (!s->eof && --nscroll > 0) {
9286 linelen = getline(&line, &linesz, s->f);
9287 s->first_displayed_line++;
9288 if (linelen == -1) {
9289 if (feof(s->f))
9290 s->eof = 1;
9291 else
9292 err = got_ferror(s->f, GOT_ERR_IO);
9293 break;
9296 free(line);
9297 break;
9298 default:
9299 view->count = 0;
9300 break;
9303 return err;
9306 static const struct got_error *
9307 close_help_view(struct tog_view *view)
9309 struct tog_help_view_state *s = &view->state.help;
9311 free(s->line_offsets);
9312 s->line_offsets = NULL;
9313 if (fclose(s->f) == EOF)
9314 return got_error_from_errno("fclose");
9316 return NULL;
9319 static const struct got_error *
9320 reset_help_view(struct tog_view *view)
9322 struct tog_help_view_state *s = &view->state.help;
9325 if (s->f && fclose(s->f) == EOF)
9326 return got_error_from_errno("fclose");
9328 wclear(view->window);
9329 view->count = 0;
9330 view->x = 0;
9331 s->all = !s->all;
9332 s->first_displayed_line = 1;
9333 s->last_displayed_line = view->nlines;
9334 s->matched_line = 0;
9336 return create_help(s);
9339 static const struct got_error *
9340 open_help_view(struct tog_view *view, struct tog_view *parent)
9342 const struct got_error *err = NULL;
9343 struct tog_help_view_state *s = &view->state.help;
9345 s->type = (enum tog_keymap_type)parent->type;
9346 s->first_displayed_line = 1;
9347 s->last_displayed_line = view->nlines;
9348 s->selected_line = 1;
9350 view->show = show_help_view;
9351 view->input = input_help_view;
9352 view->reset = reset_help_view;
9353 view->close = close_help_view;
9354 view->search_start = search_start_help_view;
9355 view->search_setup = search_setup_help_view;
9356 view->search_next = search_next_view_match;
9358 err = create_help(s);
9359 return err;
9362 static const struct got_error *
9363 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9364 enum tog_view_type request, int y, int x)
9366 const struct got_error *err = NULL;
9368 *new_view = NULL;
9370 switch (request) {
9371 case TOG_VIEW_DIFF:
9372 if (view->type == TOG_VIEW_LOG) {
9373 struct tog_log_view_state *s = &view->state.log;
9375 err = open_diff_view_for_commit(new_view, y, x,
9376 s->selected_entry->commit, s->selected_entry->id,
9377 view, s->repo);
9378 } else
9379 return got_error_msg(GOT_ERR_NOT_IMPL,
9380 "parent/child view pair not supported");
9381 break;
9382 case TOG_VIEW_BLAME:
9383 if (view->type == TOG_VIEW_TREE) {
9384 struct tog_tree_view_state *s = &view->state.tree;
9386 err = blame_tree_entry(new_view, y, x,
9387 s->selected_entry, &s->parents, s->commit_id,
9388 s->repo);
9389 } else
9390 return got_error_msg(GOT_ERR_NOT_IMPL,
9391 "parent/child view pair not supported");
9392 break;
9393 case TOG_VIEW_LOG:
9394 if (view->type == TOG_VIEW_BLAME)
9395 err = log_annotated_line(new_view, y, x,
9396 view->state.blame.repo, view->state.blame.id_to_log);
9397 else if (view->type == TOG_VIEW_TREE)
9398 err = log_selected_tree_entry(new_view, y, x,
9399 &view->state.tree);
9400 else if (view->type == TOG_VIEW_REF)
9401 err = log_ref_entry(new_view, y, x,
9402 view->state.ref.selected_entry,
9403 view->state.ref.repo);
9404 else
9405 return got_error_msg(GOT_ERR_NOT_IMPL,
9406 "parent/child view pair not supported");
9407 break;
9408 case TOG_VIEW_TREE:
9409 if (view->type == TOG_VIEW_LOG)
9410 err = browse_commit_tree(new_view, y, x,
9411 view->state.log.selected_entry,
9412 view->state.log.in_repo_path,
9413 view->state.log.head_ref_name,
9414 view->state.log.repo);
9415 else if (view->type == TOG_VIEW_REF)
9416 err = browse_ref_tree(new_view, y, x,
9417 view->state.ref.selected_entry,
9418 view->state.ref.repo);
9419 else
9420 return got_error_msg(GOT_ERR_NOT_IMPL,
9421 "parent/child view pair not supported");
9422 break;
9423 case TOG_VIEW_REF:
9424 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9425 if (*new_view == NULL)
9426 return got_error_from_errno("view_open");
9427 if (view->type == TOG_VIEW_LOG)
9428 err = open_ref_view(*new_view, view->state.log.repo);
9429 else if (view->type == TOG_VIEW_TREE)
9430 err = open_ref_view(*new_view, view->state.tree.repo);
9431 else
9432 err = got_error_msg(GOT_ERR_NOT_IMPL,
9433 "parent/child view pair not supported");
9434 if (err)
9435 view_close(*new_view);
9436 break;
9437 case TOG_VIEW_HELP:
9438 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9439 if (*new_view == NULL)
9440 return got_error_from_errno("view_open");
9441 err = open_help_view(*new_view, view);
9442 if (err)
9443 view_close(*new_view);
9444 break;
9445 default:
9446 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9449 return err;
9453 * If view was scrolled down to move the selected line into view when opening a
9454 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9456 static void
9457 offset_selection_up(struct tog_view *view)
9459 switch (view->type) {
9460 case TOG_VIEW_BLAME: {
9461 struct tog_blame_view_state *s = &view->state.blame;
9462 if (s->first_displayed_line == 1) {
9463 s->selected_line = MAX(s->selected_line - view->offset,
9465 break;
9467 if (s->first_displayed_line > view->offset)
9468 s->first_displayed_line -= view->offset;
9469 else
9470 s->first_displayed_line = 1;
9471 s->selected_line += view->offset;
9472 break;
9474 case TOG_VIEW_LOG:
9475 log_scroll_up(&view->state.log, view->offset);
9476 view->state.log.selected += view->offset;
9477 break;
9478 case TOG_VIEW_REF:
9479 ref_scroll_up(&view->state.ref, view->offset);
9480 view->state.ref.selected += view->offset;
9481 break;
9482 case TOG_VIEW_TREE:
9483 tree_scroll_up(&view->state.tree, view->offset);
9484 view->state.tree.selected += view->offset;
9485 break;
9486 default:
9487 break;
9490 view->offset = 0;
9494 * If the selected line is in the section of screen covered by the bottom split,
9495 * scroll down offset lines to move it into view and index its new position.
9497 static const struct got_error *
9498 offset_selection_down(struct tog_view *view)
9500 const struct got_error *err = NULL;
9501 const struct got_error *(*scrolld)(struct tog_view *, int);
9502 int *selected = NULL;
9503 int header, offset;
9505 switch (view->type) {
9506 case TOG_VIEW_BLAME: {
9507 struct tog_blame_view_state *s = &view->state.blame;
9508 header = 3;
9509 scrolld = NULL;
9510 if (s->selected_line > view->nlines - header) {
9511 offset = abs(view->nlines - s->selected_line - header);
9512 s->first_displayed_line += offset;
9513 s->selected_line -= offset;
9514 view->offset = offset;
9516 break;
9518 case TOG_VIEW_LOG: {
9519 struct tog_log_view_state *s = &view->state.log;
9520 scrolld = &log_scroll_down;
9521 header = view_is_parent_view(view) ? 3 : 2;
9522 selected = &s->selected;
9523 break;
9525 case TOG_VIEW_REF: {
9526 struct tog_ref_view_state *s = &view->state.ref;
9527 scrolld = &ref_scroll_down;
9528 header = 3;
9529 selected = &s->selected;
9530 break;
9532 case TOG_VIEW_TREE: {
9533 struct tog_tree_view_state *s = &view->state.tree;
9534 scrolld = &tree_scroll_down;
9535 header = 5;
9536 selected = &s->selected;
9537 break;
9539 default:
9540 selected = NULL;
9541 scrolld = NULL;
9542 header = 0;
9543 break;
9546 if (selected && *selected > view->nlines - header) {
9547 offset = abs(view->nlines - *selected - header);
9548 view->offset = offset;
9549 if (scrolld && offset) {
9550 err = scrolld(view, offset);
9551 *selected -= offset;
9555 return err;
9558 static void
9559 list_commands(FILE *fp)
9561 size_t i;
9563 fprintf(fp, "commands:");
9564 for (i = 0; i < nitems(tog_commands); i++) {
9565 const struct tog_cmd *cmd = &tog_commands[i];
9566 fprintf(fp, " %s", cmd->name);
9568 fputc('\n', fp);
9571 __dead static void
9572 usage(int hflag, int status)
9574 FILE *fp = (status == 0) ? stdout : stderr;
9576 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9577 getprogname());
9578 if (hflag) {
9579 fprintf(fp, "lazy usage: %s path\n", getprogname());
9580 list_commands(fp);
9582 exit(status);
9585 static char **
9586 make_argv(int argc, ...)
9588 va_list ap;
9589 char **argv;
9590 int i;
9592 va_start(ap, argc);
9594 argv = calloc(argc, sizeof(char *));
9595 if (argv == NULL)
9596 err(1, "calloc");
9597 for (i = 0; i < argc; i++) {
9598 argv[i] = strdup(va_arg(ap, char *));
9599 if (argv[i] == NULL)
9600 err(1, "strdup");
9603 va_end(ap);
9604 return argv;
9608 * Try to convert 'tog path' into a 'tog log path' command.
9609 * The user could simply have mistyped the command rather than knowingly
9610 * provided a path. So check whether argv[0] can in fact be resolved
9611 * to a path in the HEAD commit and print a special error if not.
9612 * This hack is for mpi@ <3
9614 static const struct got_error *
9615 tog_log_with_path(int argc, char *argv[])
9617 const struct got_error *error = NULL, *close_err;
9618 const struct tog_cmd *cmd = NULL;
9619 struct got_repository *repo = NULL;
9620 struct got_worktree *worktree = NULL;
9621 struct got_object_id *commit_id = NULL, *id = NULL;
9622 struct got_commit_object *commit = NULL;
9623 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9624 char *commit_id_str = NULL, **cmd_argv = NULL;
9625 int *pack_fds = NULL;
9627 cwd = getcwd(NULL, 0);
9628 if (cwd == NULL)
9629 return got_error_from_errno("getcwd");
9631 error = got_repo_pack_fds_open(&pack_fds);
9632 if (error != NULL)
9633 goto done;
9635 error = got_worktree_open(&worktree, cwd);
9636 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9637 goto done;
9639 if (worktree)
9640 repo_path = strdup(got_worktree_get_repo_path(worktree));
9641 else
9642 repo_path = strdup(cwd);
9643 if (repo_path == NULL) {
9644 error = got_error_from_errno("strdup");
9645 goto done;
9648 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9649 if (error != NULL)
9650 goto done;
9652 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9653 repo, worktree);
9654 if (error)
9655 goto done;
9657 error = tog_load_refs(repo, 0);
9658 if (error)
9659 goto done;
9660 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9661 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9662 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9663 if (error)
9664 goto done;
9666 if (worktree) {
9667 got_worktree_close(worktree);
9668 worktree = NULL;
9671 error = got_object_open_as_commit(&commit, repo, commit_id);
9672 if (error)
9673 goto done;
9675 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9676 if (error) {
9677 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9678 goto done;
9679 fprintf(stderr, "%s: '%s' is no known command or path\n",
9680 getprogname(), argv[0]);
9681 usage(1, 1);
9682 /* not reached */
9685 error = got_object_id_str(&commit_id_str, commit_id);
9686 if (error)
9687 goto done;
9689 cmd = &tog_commands[0]; /* log */
9690 argc = 4;
9691 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9692 error = cmd->cmd_main(argc, cmd_argv);
9693 done:
9694 if (repo) {
9695 close_err = got_repo_close(repo);
9696 if (error == NULL)
9697 error = close_err;
9699 if (commit)
9700 got_object_commit_close(commit);
9701 if (worktree)
9702 got_worktree_close(worktree);
9703 if (pack_fds) {
9704 const struct got_error *pack_err =
9705 got_repo_pack_fds_close(pack_fds);
9706 if (error == NULL)
9707 error = pack_err;
9709 free(id);
9710 free(commit_id_str);
9711 free(commit_id);
9712 free(cwd);
9713 free(repo_path);
9714 free(in_repo_path);
9715 if (cmd_argv) {
9716 int i;
9717 for (i = 0; i < argc; i++)
9718 free(cmd_argv[i]);
9719 free(cmd_argv);
9721 tog_free_refs();
9722 return error;
9726 main(int argc, char *argv[])
9728 const struct got_error *io_err, *error = NULL;
9729 const struct tog_cmd *cmd = NULL;
9730 int ch, hflag = 0, Vflag = 0;
9731 char **cmd_argv = NULL;
9732 static const struct option longopts[] = {
9733 { "version", no_argument, NULL, 'V' },
9734 { NULL, 0, NULL, 0}
9736 char *diff_algo_str = NULL;
9737 const char *test_script_path;
9739 setlocale(LC_CTYPE, "");
9742 * Test mode init must happen before pledge() because "tty" will
9743 * not allow TTY-related ioctls to occur via regular files.
9745 test_script_path = getenv("TOG_TEST_SCRIPT");
9746 if (test_script_path != NULL) {
9747 error = init_mock_term(test_script_path);
9748 if (error) {
9749 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9750 return 1;
9754 #if !defined(PROFILE)
9755 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9756 NULL) == -1)
9757 err(1, "pledge");
9758 #endif
9760 if (!isatty(STDIN_FILENO))
9761 errx(1, "standard input is not a tty");
9763 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9764 switch (ch) {
9765 case 'h':
9766 hflag = 1;
9767 break;
9768 case 'V':
9769 Vflag = 1;
9770 break;
9771 default:
9772 usage(hflag, 1);
9773 /* NOTREACHED */
9777 argc -= optind;
9778 argv += optind;
9779 optind = 1;
9780 optreset = 1;
9782 if (Vflag) {
9783 got_version_print_str();
9784 return 0;
9787 if (argc == 0) {
9788 if (hflag)
9789 usage(hflag, 0);
9790 /* Build an argument vector which runs a default command. */
9791 cmd = &tog_commands[0];
9792 argc = 1;
9793 cmd_argv = make_argv(argc, cmd->name);
9794 } else {
9795 size_t i;
9797 /* Did the user specify a command? */
9798 for (i = 0; i < nitems(tog_commands); i++) {
9799 if (strncmp(tog_commands[i].name, argv[0],
9800 strlen(argv[0])) == 0) {
9801 cmd = &tog_commands[i];
9802 break;
9807 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9808 if (diff_algo_str) {
9809 if (strcasecmp(diff_algo_str, "patience") == 0)
9810 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9811 if (strcasecmp(diff_algo_str, "myers") == 0)
9812 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9815 if (cmd == NULL) {
9816 if (argc != 1)
9817 usage(0, 1);
9818 /* No command specified; try log with a path */
9819 error = tog_log_with_path(argc, argv);
9820 } else {
9821 if (hflag)
9822 cmd->cmd_usage();
9823 else
9824 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9827 if (using_mock_io) {
9828 io_err = tog_io_close();
9829 if (error == NULL)
9830 error = io_err;
9832 endwin();
9833 if (cmd_argv) {
9834 int i;
9835 for (i = 0; i < argc; i++)
9836 free(cmd_argv[i]);
9837 free(cmd_argv);
9840 if (error && error->code != GOT_ERR_CANCELLED &&
9841 error->code != GOT_ERR_EOF &&
9842 error->code != GOT_ERR_PRIVSEP_EXIT &&
9843 error->code != GOT_ERR_PRIVSEP_PIPE &&
9844 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9845 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9846 return 0;