Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
60 #ifndef MIN
61 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
62 #endif
64 #ifndef MAX
65 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
66 #endif
68 #define CTRL(x) ((x) & 0x1f)
70 #ifndef nitems
71 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
72 #endif
74 struct tog_cmd {
75 const char *name;
76 const struct got_error *(*cmd_main)(int, char *[]);
77 void (*cmd_usage)(void);
78 };
80 __dead static void usage(int, int);
81 __dead static void usage_log(void);
82 __dead static void usage_diff(void);
83 __dead static void usage_blame(void);
84 __dead static void usage_tree(void);
85 __dead static void usage_ref(void);
87 static const struct got_error* cmd_log(int, char *[]);
88 static const struct got_error* cmd_diff(int, char *[]);
89 static const struct got_error* cmd_blame(int, char *[]);
90 static const struct got_error* cmd_tree(int, char *[]);
91 static const struct got_error* cmd_ref(int, char *[]);
93 static const struct tog_cmd tog_commands[] = {
94 { "log", cmd_log, usage_log },
95 { "diff", cmd_diff, usage_diff },
96 { "blame", cmd_blame, usage_blame },
97 { "tree", cmd_tree, usage_tree },
98 { "ref", cmd_ref, usage_ref },
99 };
101 enum tog_view_type {
102 TOG_VIEW_DIFF,
103 TOG_VIEW_LOG,
104 TOG_VIEW_BLAME,
105 TOG_VIEW_TREE,
106 TOG_VIEW_REF,
107 TOG_VIEW_HELP
108 };
110 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
111 enum tog_keymap_type {
112 TOG_KEYMAP_KEYS = -2,
113 TOG_KEYMAP_GLOBAL,
114 TOG_KEYMAP_DIFF,
115 TOG_KEYMAP_LOG,
116 TOG_KEYMAP_BLAME,
117 TOG_KEYMAP_TREE,
118 TOG_KEYMAP_REF,
119 TOG_KEYMAP_HELP
120 };
122 enum tog_view_mode {
123 TOG_VIEW_SPLIT_NONE,
124 TOG_VIEW_SPLIT_VERT,
125 TOG_VIEW_SPLIT_HRZN
126 };
128 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
130 #define TOG_EOF_STRING "(END)"
132 struct commit_queue_entry {
133 TAILQ_ENTRY(commit_queue_entry) entry;
134 struct got_object_id *id;
135 struct got_commit_object *commit;
136 int idx;
137 };
138 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
139 struct commit_queue {
140 int ncommits;
141 struct commit_queue_head head;
142 };
144 struct tog_color {
145 STAILQ_ENTRY(tog_color) entry;
146 regex_t regex;
147 short colorpair;
148 };
149 STAILQ_HEAD(tog_colors, tog_color);
151 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
152 static struct got_reflist_object_id_map *tog_refs_idmap;
153 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
155 static const struct got_error *
156 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
157 struct got_reference* re2)
159 const char *name1 = got_ref_get_name(re1);
160 const char *name2 = got_ref_get_name(re2);
161 int isbackup1, isbackup2;
163 /* Sort backup refs towards the bottom of the list. */
164 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
165 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
166 if (!isbackup1 && isbackup2) {
167 *cmp = -1;
168 return NULL;
169 } else if (isbackup1 && !isbackup2) {
170 *cmp = 1;
171 return NULL;
174 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
175 return NULL;
178 static const struct got_error *
179 tog_load_refs(struct got_repository *repo, int sort_by_date)
181 const struct got_error *err;
183 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
184 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
185 repo);
186 if (err)
187 return err;
189 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
190 repo);
193 static void
194 tog_free_refs(void)
196 if (tog_refs_idmap) {
197 got_reflist_object_id_map_free(tog_refs_idmap);
198 tog_refs_idmap = NULL;
200 got_ref_list_free(&tog_refs);
203 static const struct got_error *
204 add_color(struct tog_colors *colors, const char *pattern,
205 int idx, short color)
207 const struct got_error *err = NULL;
208 struct tog_color *tc;
209 int regerr = 0;
211 if (idx < 1 || idx > COLOR_PAIRS - 1)
212 return NULL;
214 init_pair(idx, color, -1);
216 tc = calloc(1, sizeof(*tc));
217 if (tc == NULL)
218 return got_error_from_errno("calloc");
219 regerr = regcomp(&tc->regex, pattern,
220 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
221 if (regerr) {
222 static char regerr_msg[512];
223 static char err_msg[512];
224 regerror(regerr, &tc->regex, regerr_msg,
225 sizeof(regerr_msg));
226 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
227 regerr_msg);
228 err = got_error_msg(GOT_ERR_REGEX, err_msg);
229 free(tc);
230 return err;
232 tc->colorpair = idx;
233 STAILQ_INSERT_HEAD(colors, tc, entry);
234 return NULL;
237 static void
238 free_colors(struct tog_colors *colors)
240 struct tog_color *tc;
242 while (!STAILQ_EMPTY(colors)) {
243 tc = STAILQ_FIRST(colors);
244 STAILQ_REMOVE_HEAD(colors, entry);
245 regfree(&tc->regex);
246 free(tc);
250 static struct tog_color *
251 get_color(struct tog_colors *colors, int colorpair)
253 struct tog_color *tc = NULL;
255 STAILQ_FOREACH(tc, colors, entry) {
256 if (tc->colorpair == colorpair)
257 return tc;
260 return NULL;
263 static int
264 default_color_value(const char *envvar)
266 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
281 return COLOR_GREEN;
282 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
287 return COLOR_YELLOW;
288 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
291 return COLOR_MAGENTA;
292 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
295 return COLOR_CYAN;
297 return -1;
300 static int
301 get_color_value(const char *envvar)
303 const char *val = getenv(envvar);
305 if (val == NULL)
306 return default_color_value(envvar);
308 if (strcasecmp(val, "black") == 0)
309 return COLOR_BLACK;
310 if (strcasecmp(val, "red") == 0)
311 return COLOR_RED;
312 if (strcasecmp(val, "green") == 0)
313 return COLOR_GREEN;
314 if (strcasecmp(val, "yellow") == 0)
315 return COLOR_YELLOW;
316 if (strcasecmp(val, "blue") == 0)
317 return COLOR_BLUE;
318 if (strcasecmp(val, "magenta") == 0)
319 return COLOR_MAGENTA;
320 if (strcasecmp(val, "cyan") == 0)
321 return COLOR_CYAN;
322 if (strcasecmp(val, "white") == 0)
323 return COLOR_WHITE;
324 if (strcasecmp(val, "default") == 0)
325 return -1;
327 return default_color_value(envvar);
330 struct tog_diff_view_state {
331 struct got_object_id *id1, *id2;
332 const char *label1, *label2;
333 FILE *f, *f1, *f2;
334 int fd1, fd2;
335 int lineno;
336 int first_displayed_line;
337 int last_displayed_line;
338 int eof;
339 int diff_context;
340 int ignore_whitespace;
341 int force_text_diff;
342 struct got_repository *repo;
343 struct got_diff_line *lines;
344 size_t nlines;
345 int matched_line;
346 int selected_line;
348 /* passed from log or blame view; may be NULL */
349 struct tog_view *parent_view;
350 };
352 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
353 static volatile sig_atomic_t tog_thread_error;
355 struct tog_log_thread_args {
356 pthread_cond_t need_commits;
357 pthread_cond_t commit_loaded;
358 int commits_needed;
359 int load_all;
360 struct got_commit_graph *graph;
361 struct commit_queue *real_commits;
362 const char *in_repo_path;
363 struct got_object_id *start_id;
364 struct got_repository *repo;
365 int *pack_fds;
366 int log_complete;
367 sig_atomic_t *quit;
368 struct commit_queue_entry **first_displayed_entry;
369 struct commit_queue_entry **selected_entry;
370 int *searching;
371 int *search_next_done;
372 regex_t *regex;
373 int *limiting;
374 int limit_match;
375 regex_t *limit_regex;
376 struct commit_queue *limit_commits;
377 };
379 struct tog_log_view_state {
380 struct commit_queue *commits;
381 struct commit_queue_entry *first_displayed_entry;
382 struct commit_queue_entry *last_displayed_entry;
383 struct commit_queue_entry *selected_entry;
384 struct commit_queue real_commits;
385 int selected;
386 char *in_repo_path;
387 char *head_ref_name;
388 int log_branches;
389 struct got_repository *repo;
390 struct got_object_id *start_id;
391 sig_atomic_t quit;
392 pthread_t thread;
393 struct tog_log_thread_args thread_args;
394 struct commit_queue_entry *matched_entry;
395 struct commit_queue_entry *search_entry;
396 struct tog_colors colors;
397 int use_committer;
398 int limit_view;
399 regex_t limit_regex;
400 struct commit_queue limit_commits;
401 };
403 #define TOG_COLOR_DIFF_MINUS 1
404 #define TOG_COLOR_DIFF_PLUS 2
405 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
406 #define TOG_COLOR_DIFF_META 4
407 #define TOG_COLOR_TREE_SUBMODULE 5
408 #define TOG_COLOR_TREE_SYMLINK 6
409 #define TOG_COLOR_TREE_DIRECTORY 7
410 #define TOG_COLOR_TREE_EXECUTABLE 8
411 #define TOG_COLOR_COMMIT 9
412 #define TOG_COLOR_AUTHOR 10
413 #define TOG_COLOR_DATE 11
414 #define TOG_COLOR_REFS_HEADS 12
415 #define TOG_COLOR_REFS_TAGS 13
416 #define TOG_COLOR_REFS_REMOTES 14
417 #define TOG_COLOR_REFS_BACKUP 15
419 struct tog_blame_cb_args {
420 struct tog_blame_line *lines; /* one per line */
421 int nlines;
423 struct tog_view *view;
424 struct got_object_id *commit_id;
425 int *quit;
426 };
428 struct tog_blame_thread_args {
429 const char *path;
430 struct got_repository *repo;
431 struct tog_blame_cb_args *cb_args;
432 int *complete;
433 got_cancel_cb cancel_cb;
434 void *cancel_arg;
435 };
437 struct tog_blame {
438 FILE *f;
439 off_t filesize;
440 struct tog_blame_line *lines;
441 int nlines;
442 off_t *line_offsets;
443 pthread_t thread;
444 struct tog_blame_thread_args thread_args;
445 struct tog_blame_cb_args cb_args;
446 const char *path;
447 int *pack_fds;
448 };
450 struct tog_blame_view_state {
451 int first_displayed_line;
452 int last_displayed_line;
453 int selected_line;
454 int last_diffed_line;
455 int blame_complete;
456 int eof;
457 int done;
458 struct got_object_id_queue blamed_commits;
459 struct got_object_qid *blamed_commit;
460 char *path;
461 struct got_repository *repo;
462 struct got_object_id *commit_id;
463 struct got_object_id *id_to_log;
464 struct tog_blame blame;
465 int matched_line;
466 struct tog_colors colors;
467 };
469 struct tog_parent_tree {
470 TAILQ_ENTRY(tog_parent_tree) entry;
471 struct got_tree_object *tree;
472 struct got_tree_entry *first_displayed_entry;
473 struct got_tree_entry *selected_entry;
474 int selected;
475 };
477 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
479 struct tog_tree_view_state {
480 char *tree_label;
481 struct got_object_id *commit_id;/* commit which this tree belongs to */
482 struct got_tree_object *root; /* the commit's root tree entry */
483 struct got_tree_object *tree; /* currently displayed (sub-)tree */
484 struct got_tree_entry *first_displayed_entry;
485 struct got_tree_entry *last_displayed_entry;
486 struct got_tree_entry *selected_entry;
487 int ndisplayed, selected, show_ids;
488 struct tog_parent_trees parents; /* parent trees of current sub-tree */
489 char *head_ref_name;
490 struct got_repository *repo;
491 struct got_tree_entry *matched_entry;
492 struct tog_colors colors;
493 };
495 struct tog_reflist_entry {
496 TAILQ_ENTRY(tog_reflist_entry) entry;
497 struct got_reference *ref;
498 int idx;
499 };
501 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
503 struct tog_ref_view_state {
504 struct tog_reflist_head refs;
505 struct tog_reflist_entry *first_displayed_entry;
506 struct tog_reflist_entry *last_displayed_entry;
507 struct tog_reflist_entry *selected_entry;
508 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
509 struct got_repository *repo;
510 struct tog_reflist_entry *matched_entry;
511 struct tog_colors colors;
512 };
514 struct tog_help_view_state {
515 FILE *f;
516 off_t *line_offsets;
517 size_t nlines;
518 int lineno;
519 int first_displayed_line;
520 int last_displayed_line;
521 int eof;
522 int matched_line;
523 int selected_line;
524 int all;
525 enum tog_keymap_type type;
526 };
528 #define GENERATE_HELP \
529 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
530 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
531 KEY_("k C-p Up", "Move cursor or page up one line"), \
532 KEY_("j C-n Down", "Move cursor or page down one line"), \
533 KEY_("C-b b PgUp", "Scroll the view up one page"), \
534 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
535 KEY_("C-u u", "Scroll the view up one half page"), \
536 KEY_("C-d d", "Scroll the view down one half page"), \
537 KEY_("g", "Go to line N (default: first line)"), \
538 KEY_("Home =", "Go to the first line"), \
539 KEY_("G", "Go to line N (default: last line)"), \
540 KEY_("End *", "Go to the last line"), \
541 KEY_("l Right", "Scroll the view right"), \
542 KEY_("h Left", "Scroll the view left"), \
543 KEY_("$", "Scroll view to the rightmost position"), \
544 KEY_("0", "Scroll view to the leftmost position"), \
545 KEY_("-", "Decrease size of the focussed split"), \
546 KEY_("+", "Increase size of the focussed split"), \
547 KEY_("Tab", "Switch focus between views"), \
548 KEY_("F", "Toggle fullscreen mode"), \
549 KEY_("S", "Switch split-screen layout"), \
550 KEY_("/", "Open prompt to enter search term"), \
551 KEY_("n", "Find next line/token matching the current search term"), \
552 KEY_("N", "Find previous line/token matching the current search term"),\
553 KEY_("q", "Quit the focussed view; Quit help screen"), \
554 KEY_("Q", "Quit tog"), \
556 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
557 KEY_("< ,", "Move cursor up one commit"), \
558 KEY_("> .", "Move cursor down one commit"), \
559 KEY_("Enter", "Open diff view of the selected commit"), \
560 KEY_("B", "Reload the log view and toggle display of merged commits"), \
561 KEY_("R", "Open ref view of all repository references"), \
562 KEY_("T", "Display tree view of the repository from the selected" \
563 " commit"), \
564 KEY_("@", "Toggle between displaying author and committer name"), \
565 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
566 KEY_("C-g Backspace", "Cancel current search or log operation"), \
567 KEY_("C-l", "Reload the log view with new commits in the repository"), \
569 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
570 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
571 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
572 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
573 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
574 " data"), \
575 KEY_("(", "Go to the previous file in the diff"), \
576 KEY_(")", "Go to the next file in the diff"), \
577 KEY_("{", "Go to the previous hunk in the diff"), \
578 KEY_("}", "Go to the next hunk in the diff"), \
579 KEY_("[", "Decrease the number of context lines"), \
580 KEY_("]", "Increase the number of context lines"), \
581 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
583 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
584 KEY_("Enter", "Display diff view of the selected line's commit"), \
585 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
586 KEY_("L", "Open log view for the currently selected annotated line"), \
587 KEY_("C", "Reload view with the previously blamed commit"), \
588 KEY_("c", "Reload view with the version of the file found in the" \
589 " selected line's commit"), \
590 KEY_("p", "Reload view with the version of the file found in the" \
591 " selected line's parent commit"), \
593 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
594 KEY_("Enter", "Enter selected directory or open blame view of the" \
595 " selected file"), \
596 KEY_("L", "Open log view for the selected entry"), \
597 KEY_("R", "Open ref view of all repository references"), \
598 KEY_("i", "Show object IDs for all tree entries"), \
599 KEY_("Backspace", "Return to the parent directory"), \
601 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
602 KEY_("Enter", "Display log view of the selected reference"), \
603 KEY_("T", "Display tree view of the selected reference"), \
604 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
605 KEY_("m", "Toggle display of last modified date for each reference"), \
606 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
607 KEY_("C-l", "Reload view with all repository references")
609 struct tog_key_map {
610 const char *keys;
611 const char *info;
612 enum tog_keymap_type type;
613 };
615 /* curses io for tog regress */
616 struct tog_io {
617 FILE *cin;
618 FILE *cout;
619 FILE *f;
620 } tog_io;
621 static int using_mock_io;
623 #define TOG_SCREEN_DUMP "SCREENDUMP"
624 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
625 #define TOG_KEY_SCRDUMP SHRT_MIN
627 /*
628 * We implement two types of views: parent views and child views.
630 * The 'Tab' key switches focus between a parent view and its child view.
631 * Child views are shown side-by-side to their parent view, provided
632 * there is enough screen estate.
634 * When a new view is opened from within a parent view, this new view
635 * becomes a child view of the parent view, replacing any existing child.
637 * When a new view is opened from within a child view, this new view
638 * becomes a parent view which will obscure the views below until the
639 * user quits the new parent view by typing 'q'.
641 * This list of views contains parent views only.
642 * Child views are only pointed to by their parent view.
643 */
644 TAILQ_HEAD(tog_view_list_head, tog_view);
646 struct tog_view {
647 TAILQ_ENTRY(tog_view) entry;
648 WINDOW *window;
649 PANEL *panel;
650 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
651 int resized_y, resized_x; /* begin_y/x based on user resizing */
652 int maxx, x; /* max column and current start column */
653 int lines, cols; /* copies of LINES and COLS */
654 int nscrolled, offset; /* lines scrolled and hsplit line offset */
655 int gline, hiline; /* navigate to and highlight this nG line */
656 int ch, count; /* current keymap and count prefix */
657 int resized; /* set when in a resize event */
658 int focussed; /* Only set on one parent or child view at a time. */
659 int dying;
660 struct tog_view *parent;
661 struct tog_view *child;
663 /*
664 * This flag is initially set on parent views when a new child view
665 * is created. It gets toggled when the 'Tab' key switches focus
666 * between parent and child.
667 * The flag indicates whether focus should be passed on to our child
668 * view if this parent view gets picked for focus after another parent
669 * view was closed. This prevents child views from losing focus in such
670 * situations.
671 */
672 int focus_child;
674 enum tog_view_mode mode;
675 /* type-specific state */
676 enum tog_view_type type;
677 union {
678 struct tog_diff_view_state diff;
679 struct tog_log_view_state log;
680 struct tog_blame_view_state blame;
681 struct tog_tree_view_state tree;
682 struct tog_ref_view_state ref;
683 struct tog_help_view_state help;
684 } state;
686 const struct got_error *(*show)(struct tog_view *);
687 const struct got_error *(*input)(struct tog_view **,
688 struct tog_view *, int);
689 const struct got_error *(*reset)(struct tog_view *);
690 const struct got_error *(*resize)(struct tog_view *, int);
691 const struct got_error *(*close)(struct tog_view *);
693 const struct got_error *(*search_start)(struct tog_view *);
694 const struct got_error *(*search_next)(struct tog_view *);
695 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
696 int **, int **, int **, int **);
697 int search_started;
698 int searching;
699 #define TOG_SEARCH_FORWARD 1
700 #define TOG_SEARCH_BACKWARD 2
701 int search_next_done;
702 #define TOG_SEARCH_HAVE_MORE 1
703 #define TOG_SEARCH_NO_MORE 2
704 #define TOG_SEARCH_HAVE_NONE 3
705 regex_t regex;
706 regmatch_t regmatch;
707 const char *action;
708 };
710 static const struct got_error *open_diff_view(struct tog_view *,
711 struct got_object_id *, struct got_object_id *,
712 const char *, const char *, int, int, int, struct tog_view *,
713 struct got_repository *);
714 static const struct got_error *show_diff_view(struct tog_view *);
715 static const struct got_error *input_diff_view(struct tog_view **,
716 struct tog_view *, int);
717 static const struct got_error *reset_diff_view(struct tog_view *);
718 static const struct got_error* close_diff_view(struct tog_view *);
719 static const struct got_error *search_start_diff_view(struct tog_view *);
720 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
721 size_t *, int **, int **, int **, int **);
722 static const struct got_error *search_next_view_match(struct tog_view *);
724 static const struct got_error *open_log_view(struct tog_view *,
725 struct got_object_id *, struct got_repository *,
726 const char *, const char *, int);
727 static const struct got_error * show_log_view(struct tog_view *);
728 static const struct got_error *input_log_view(struct tog_view **,
729 struct tog_view *, int);
730 static const struct got_error *resize_log_view(struct tog_view *, int);
731 static const struct got_error *close_log_view(struct tog_view *);
732 static const struct got_error *search_start_log_view(struct tog_view *);
733 static const struct got_error *search_next_log_view(struct tog_view *);
735 static const struct got_error *open_blame_view(struct tog_view *, char *,
736 struct got_object_id *, struct got_repository *);
737 static const struct got_error *show_blame_view(struct tog_view *);
738 static const struct got_error *input_blame_view(struct tog_view **,
739 struct tog_view *, int);
740 static const struct got_error *reset_blame_view(struct tog_view *);
741 static const struct got_error *close_blame_view(struct tog_view *);
742 static const struct got_error *search_start_blame_view(struct tog_view *);
743 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
744 size_t *, int **, int **, int **, int **);
746 static const struct got_error *open_tree_view(struct tog_view *,
747 struct got_object_id *, const char *, struct got_repository *);
748 static const struct got_error *show_tree_view(struct tog_view *);
749 static const struct got_error *input_tree_view(struct tog_view **,
750 struct tog_view *, int);
751 static const struct got_error *close_tree_view(struct tog_view *);
752 static const struct got_error *search_start_tree_view(struct tog_view *);
753 static const struct got_error *search_next_tree_view(struct tog_view *);
755 static const struct got_error *open_ref_view(struct tog_view *,
756 struct got_repository *);
757 static const struct got_error *show_ref_view(struct tog_view *);
758 static const struct got_error *input_ref_view(struct tog_view **,
759 struct tog_view *, int);
760 static const struct got_error *close_ref_view(struct tog_view *);
761 static const struct got_error *search_start_ref_view(struct tog_view *);
762 static const struct got_error *search_next_ref_view(struct tog_view *);
764 static const struct got_error *open_help_view(struct tog_view *,
765 struct tog_view *);
766 static const struct got_error *show_help_view(struct tog_view *);
767 static const struct got_error *input_help_view(struct tog_view **,
768 struct tog_view *, int);
769 static const struct got_error *reset_help_view(struct tog_view *);
770 static const struct got_error* close_help_view(struct tog_view *);
771 static const struct got_error *search_start_help_view(struct tog_view *);
772 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
773 size_t *, int **, int **, int **, int **);
775 static volatile sig_atomic_t tog_sigwinch_received;
776 static volatile sig_atomic_t tog_sigpipe_received;
777 static volatile sig_atomic_t tog_sigcont_received;
778 static volatile sig_atomic_t tog_sigint_received;
779 static volatile sig_atomic_t tog_sigterm_received;
781 static void
782 tog_sigwinch(int signo)
784 tog_sigwinch_received = 1;
787 static void
788 tog_sigpipe(int signo)
790 tog_sigpipe_received = 1;
793 static void
794 tog_sigcont(int signo)
796 tog_sigcont_received = 1;
799 static void
800 tog_sigint(int signo)
802 tog_sigint_received = 1;
805 static void
806 tog_sigterm(int signo)
808 tog_sigterm_received = 1;
811 static int
812 tog_fatal_signal_received(void)
814 return (tog_sigpipe_received ||
815 tog_sigint_received || tog_sigterm_received);
818 static const struct got_error *
819 view_close(struct tog_view *view)
821 const struct got_error *err = NULL, *child_err = NULL;
823 if (view->child) {
824 child_err = view_close(view->child);
825 view->child = NULL;
827 if (view->close)
828 err = view->close(view);
829 if (view->panel)
830 del_panel(view->panel);
831 if (view->window)
832 delwin(view->window);
833 free(view);
834 return err ? err : child_err;
837 static struct tog_view *
838 view_open(int nlines, int ncols, int begin_y, int begin_x,
839 enum tog_view_type type)
841 struct tog_view *view = calloc(1, sizeof(*view));
843 if (view == NULL)
844 return NULL;
846 view->type = type;
847 view->lines = LINES;
848 view->cols = COLS;
849 view->nlines = nlines ? nlines : LINES - begin_y;
850 view->ncols = ncols ? ncols : COLS - begin_x;
851 view->begin_y = begin_y;
852 view->begin_x = begin_x;
853 view->window = newwin(nlines, ncols, begin_y, begin_x);
854 if (view->window == NULL) {
855 view_close(view);
856 return NULL;
858 view->panel = new_panel(view->window);
859 if (view->panel == NULL ||
860 set_panel_userptr(view->panel, view) != OK) {
861 view_close(view);
862 return NULL;
865 keypad(view->window, TRUE);
866 return view;
869 static int
870 view_split_begin_x(int begin_x)
872 if (begin_x > 0 || COLS < 120)
873 return 0;
874 return (COLS - MAX(COLS / 2, 80));
877 /* XXX Stub till we decide what to do. */
878 static int
879 view_split_begin_y(int lines)
881 return lines * HSPLIT_SCALE;
884 static const struct got_error *view_resize(struct tog_view *);
886 static const struct got_error *
887 view_splitscreen(struct tog_view *view)
889 const struct got_error *err = NULL;
891 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
892 if (view->resized_y && view->resized_y < view->lines)
893 view->begin_y = view->resized_y;
894 else
895 view->begin_y = view_split_begin_y(view->nlines);
896 view->begin_x = 0;
897 } else if (!view->resized) {
898 if (view->resized_x && view->resized_x < view->cols - 1 &&
899 view->cols > 119)
900 view->begin_x = view->resized_x;
901 else
902 view->begin_x = view_split_begin_x(0);
903 view->begin_y = 0;
905 view->nlines = LINES - view->begin_y;
906 view->ncols = COLS - view->begin_x;
907 view->lines = LINES;
908 view->cols = COLS;
909 err = view_resize(view);
910 if (err)
911 return err;
913 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
914 view->parent->nlines = view->begin_y;
916 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
917 return got_error_from_errno("mvwin");
919 return NULL;
922 static const struct got_error *
923 view_fullscreen(struct tog_view *view)
925 const struct got_error *err = NULL;
927 view->begin_x = 0;
928 view->begin_y = view->resized ? view->begin_y : 0;
929 view->nlines = view->resized ? view->nlines : LINES;
930 view->ncols = COLS;
931 view->lines = LINES;
932 view->cols = COLS;
933 err = view_resize(view);
934 if (err)
935 return err;
937 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
938 return got_error_from_errno("mvwin");
940 return NULL;
943 static int
944 view_is_parent_view(struct tog_view *view)
946 return view->parent == NULL;
949 static int
950 view_is_splitscreen(struct tog_view *view)
952 return view->begin_x > 0 || view->begin_y > 0;
955 static int
956 view_is_fullscreen(struct tog_view *view)
958 return view->nlines == LINES && view->ncols == COLS;
961 static int
962 view_is_hsplit_top(struct tog_view *view)
964 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
965 view_is_splitscreen(view->child);
968 static void
969 view_border(struct tog_view *view)
971 PANEL *panel;
972 const struct tog_view *view_above;
974 if (view->parent)
975 return view_border(view->parent);
977 panel = panel_above(view->panel);
978 if (panel == NULL)
979 return;
981 view_above = panel_userptr(panel);
982 if (view->mode == TOG_VIEW_SPLIT_HRZN)
983 mvwhline(view->window, view_above->begin_y - 1,
984 view->begin_x, got_locale_is_utf8() ?
985 ACS_HLINE : '-', view->ncols);
986 else
987 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
988 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
991 static const struct got_error *view_init_hsplit(struct tog_view *, int);
992 static const struct got_error *request_log_commits(struct tog_view *);
993 static const struct got_error *offset_selection_down(struct tog_view *);
994 static void offset_selection_up(struct tog_view *);
995 static void view_get_split(struct tog_view *, int *, int *);
997 static const struct got_error *
998 view_resize(struct tog_view *view)
1000 const struct got_error *err = NULL;
1001 int dif, nlines, ncols;
1003 dif = LINES - view->lines; /* line difference */
1005 if (view->lines > LINES)
1006 nlines = view->nlines - (view->lines - LINES);
1007 else
1008 nlines = view->nlines + (LINES - view->lines);
1009 if (view->cols > COLS)
1010 ncols = view->ncols - (view->cols - COLS);
1011 else
1012 ncols = view->ncols + (COLS - view->cols);
1014 if (view->child) {
1015 int hs = view->child->begin_y;
1017 if (!view_is_fullscreen(view))
1018 view->child->begin_x = view_split_begin_x(view->begin_x);
1019 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1020 view->child->begin_x == 0) {
1021 ncols = COLS;
1023 view_fullscreen(view->child);
1024 if (view->child->focussed)
1025 show_panel(view->child->panel);
1026 else
1027 show_panel(view->panel);
1028 } else {
1029 ncols = view->child->begin_x;
1031 view_splitscreen(view->child);
1032 show_panel(view->child->panel);
1035 * XXX This is ugly and needs to be moved into the above
1036 * logic but "works" for now and my attempts at moving it
1037 * break either 'tab' or 'F' key maps in horizontal splits.
1039 if (hs) {
1040 err = view_splitscreen(view->child);
1041 if (err)
1042 return err;
1043 if (dif < 0) { /* top split decreased */
1044 err = offset_selection_down(view);
1045 if (err)
1046 return err;
1048 view_border(view);
1049 update_panels();
1050 doupdate();
1051 show_panel(view->child->panel);
1052 nlines = view->nlines;
1054 } else if (view->parent == NULL)
1055 ncols = COLS;
1057 if (view->resize && dif > 0) {
1058 err = view->resize(view, dif);
1059 if (err)
1060 return err;
1063 if (wresize(view->window, nlines, ncols) == ERR)
1064 return got_error_from_errno("wresize");
1065 if (replace_panel(view->panel, view->window) == ERR)
1066 return got_error_from_errno("replace_panel");
1067 wclear(view->window);
1069 view->nlines = nlines;
1070 view->ncols = ncols;
1071 view->lines = LINES;
1072 view->cols = COLS;
1074 return NULL;
1077 static const struct got_error *
1078 resize_log_view(struct tog_view *view, int increase)
1080 struct tog_log_view_state *s = &view->state.log;
1081 const struct got_error *err = NULL;
1082 int n = 0;
1084 if (s->selected_entry)
1085 n = s->selected_entry->idx + view->lines - s->selected;
1088 * Request commits to account for the increased
1089 * height so we have enough to populate the view.
1091 if (s->commits->ncommits < n) {
1092 view->nscrolled = n - s->commits->ncommits + increase + 1;
1093 err = request_log_commits(view);
1096 return err;
1099 static void
1100 view_adjust_offset(struct tog_view *view, int n)
1102 if (n == 0)
1103 return;
1105 if (view->parent && view->parent->offset) {
1106 if (view->parent->offset + n >= 0)
1107 view->parent->offset += n;
1108 else
1109 view->parent->offset = 0;
1110 } else if (view->offset) {
1111 if (view->offset - n >= 0)
1112 view->offset -= n;
1113 else
1114 view->offset = 0;
1118 static const struct got_error *
1119 view_resize_split(struct tog_view *view, int resize)
1121 const struct got_error *err = NULL;
1122 struct tog_view *v = NULL;
1124 if (view->parent)
1125 v = view->parent;
1126 else
1127 v = view;
1129 if (!v->child || !view_is_splitscreen(v->child))
1130 return NULL;
1132 v->resized = v->child->resized = resize; /* lock for resize event */
1134 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1135 if (v->child->resized_y)
1136 v->child->begin_y = v->child->resized_y;
1137 if (view->parent)
1138 v->child->begin_y -= resize;
1139 else
1140 v->child->begin_y += resize;
1141 if (v->child->begin_y < 3) {
1142 view->count = 0;
1143 v->child->begin_y = 3;
1144 } else if (v->child->begin_y > LINES - 1) {
1145 view->count = 0;
1146 v->child->begin_y = LINES - 1;
1148 v->ncols = COLS;
1149 v->child->ncols = COLS;
1150 view_adjust_offset(view, resize);
1151 err = view_init_hsplit(v, v->child->begin_y);
1152 if (err)
1153 return err;
1154 v->child->resized_y = v->child->begin_y;
1155 } else {
1156 if (v->child->resized_x)
1157 v->child->begin_x = v->child->resized_x;
1158 if (view->parent)
1159 v->child->begin_x -= resize;
1160 else
1161 v->child->begin_x += resize;
1162 if (v->child->begin_x < 11) {
1163 view->count = 0;
1164 v->child->begin_x = 11;
1165 } else if (v->child->begin_x > COLS - 1) {
1166 view->count = 0;
1167 v->child->begin_x = COLS - 1;
1169 v->child->resized_x = v->child->begin_x;
1172 v->child->mode = v->mode;
1173 v->child->nlines = v->lines - v->child->begin_y;
1174 v->child->ncols = v->cols - v->child->begin_x;
1175 v->focus_child = 1;
1177 err = view_fullscreen(v);
1178 if (err)
1179 return err;
1180 err = view_splitscreen(v->child);
1181 if (err)
1182 return err;
1184 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1185 err = offset_selection_down(v->child);
1186 if (err)
1187 return err;
1190 if (v->resize)
1191 err = v->resize(v, 0);
1192 else if (v->child->resize)
1193 err = v->child->resize(v->child, 0);
1195 v->resized = v->child->resized = 0;
1197 return err;
1200 static void
1201 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1203 struct tog_view *v = src->child ? src->child : src;
1205 dst->resized_x = v->resized_x;
1206 dst->resized_y = v->resized_y;
1209 static const struct got_error *
1210 view_close_child(struct tog_view *view)
1212 const struct got_error *err = NULL;
1214 if (view->child == NULL)
1215 return NULL;
1217 err = view_close(view->child);
1218 view->child = NULL;
1219 return err;
1222 static const struct got_error *
1223 view_set_child(struct tog_view *view, struct tog_view *child)
1225 const struct got_error *err = NULL;
1227 view->child = child;
1228 child->parent = view;
1230 err = view_resize(view);
1231 if (err)
1232 return err;
1234 if (view->child->resized_x || view->child->resized_y)
1235 err = view_resize_split(view, 0);
1237 return err;
1240 static const struct got_error *view_dispatch_request(struct tog_view **,
1241 struct tog_view *, enum tog_view_type, int, int);
1243 static const struct got_error *
1244 view_request_new(struct tog_view **requested, struct tog_view *view,
1245 enum tog_view_type request)
1247 struct tog_view *new_view = NULL;
1248 const struct got_error *err;
1249 int y = 0, x = 0;
1251 *requested = NULL;
1253 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1254 view_get_split(view, &y, &x);
1256 err = view_dispatch_request(&new_view, view, request, y, x);
1257 if (err)
1258 return err;
1260 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1261 request != TOG_VIEW_HELP) {
1262 err = view_init_hsplit(view, y);
1263 if (err)
1264 return err;
1267 view->focussed = 0;
1268 new_view->focussed = 1;
1269 new_view->mode = view->mode;
1270 new_view->nlines = request == TOG_VIEW_HELP ?
1271 view->lines : view->lines - y;
1273 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1274 view_transfer_size(new_view, view);
1275 err = view_close_child(view);
1276 if (err)
1277 return err;
1278 err = view_set_child(view, new_view);
1279 if (err)
1280 return err;
1281 view->focus_child = 1;
1282 } else
1283 *requested = new_view;
1285 return NULL;
1288 static void
1289 tog_resizeterm(void)
1291 int cols, lines;
1292 struct winsize size;
1294 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1295 cols = 80; /* Default */
1296 lines = 24;
1297 } else {
1298 cols = size.ws_col;
1299 lines = size.ws_row;
1301 resize_term(lines, cols);
1304 static const struct got_error *
1305 view_search_start(struct tog_view *view, int fast_refresh)
1307 const struct got_error *err = NULL;
1308 struct tog_view *v = view;
1309 char pattern[1024];
1310 int ret;
1312 if (view->search_started) {
1313 regfree(&view->regex);
1314 view->searching = 0;
1315 memset(&view->regmatch, 0, sizeof(view->regmatch));
1317 view->search_started = 0;
1319 if (view->nlines < 1)
1320 return NULL;
1322 if (view_is_hsplit_top(view))
1323 v = view->child;
1324 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1325 v = view->parent;
1327 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1328 wclrtoeol(v->window);
1330 nodelay(v->window, FALSE); /* block for search term input */
1331 nocbreak();
1332 echo();
1333 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1334 wrefresh(v->window);
1335 cbreak();
1336 noecho();
1337 nodelay(v->window, TRUE);
1338 if (!fast_refresh && !using_mock_io)
1339 halfdelay(10);
1340 if (ret == ERR)
1341 return NULL;
1343 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1344 err = view->search_start(view);
1345 if (err) {
1346 regfree(&view->regex);
1347 return err;
1349 view->search_started = 1;
1350 view->searching = TOG_SEARCH_FORWARD;
1351 view->search_next_done = 0;
1352 view->search_next(view);
1355 return NULL;
1358 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1359 static const struct got_error *
1360 switch_split(struct tog_view *view)
1362 const struct got_error *err = NULL;
1363 struct tog_view *v = NULL;
1365 if (view->parent)
1366 v = view->parent;
1367 else
1368 v = view;
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1371 v->mode = TOG_VIEW_SPLIT_VERT;
1372 else
1373 v->mode = TOG_VIEW_SPLIT_HRZN;
1375 if (!v->child)
1376 return NULL;
1377 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1378 v->mode = TOG_VIEW_SPLIT_NONE;
1380 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1381 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1382 v->child->begin_y = v->child->resized_y;
1383 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1384 v->child->begin_x = v->child->resized_x;
1387 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1388 v->ncols = COLS;
1389 v->child->ncols = COLS;
1390 v->child->nscrolled = LINES - v->child->nlines;
1392 err = view_init_hsplit(v, v->child->begin_y);
1393 if (err)
1394 return err;
1396 v->child->mode = v->mode;
1397 v->child->nlines = v->lines - v->child->begin_y;
1398 v->focus_child = 1;
1400 err = view_fullscreen(v);
1401 if (err)
1402 return err;
1403 err = view_splitscreen(v->child);
1404 if (err)
1405 return err;
1407 if (v->mode == TOG_VIEW_SPLIT_NONE)
1408 v->mode = TOG_VIEW_SPLIT_VERT;
1409 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1410 err = offset_selection_down(v);
1411 if (err)
1412 return err;
1413 err = offset_selection_down(v->child);
1414 if (err)
1415 return err;
1416 } else {
1417 offset_selection_up(v);
1418 offset_selection_up(v->child);
1420 if (v->resize)
1421 err = v->resize(v, 0);
1422 else if (v->child->resize)
1423 err = v->child->resize(v->child, 0);
1425 return err;
1429 * Strip trailing whitespace from str starting at byte *n;
1430 * if *n < 0, use strlen(str). Return new str length in *n.
1432 static void
1433 strip_trailing_ws(char *str, int *n)
1435 size_t x = *n;
1437 if (str == NULL || *str == '\0')
1438 return;
1440 if (x < 0)
1441 x = strlen(str);
1443 while (x-- > 0 && isspace((unsigned char)str[x]))
1444 str[x] = '\0';
1446 *n = x + 1;
1450 * Extract visible substring of line y from the curses screen
1451 * and strip trailing whitespace. If vline is set and locale is
1452 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1453 * character is written out as 'x'. Write the line to file f.
1455 static const struct got_error *
1456 view_write_line(FILE *f, int y, int vline)
1458 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1459 int r, w;
1461 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1462 if (r == ERR)
1463 return got_error_fmt(GOT_ERR_RANGE,
1464 "failed to extract line %d", y);
1467 * In some views, lines are padded with blanks to COLS width.
1468 * Strip them so we can diff without the -b flag when testing.
1470 strip_trailing_ws(line, &r);
1472 if (vline > 0 && got_locale_is_utf8())
1473 line[vline] = '|';
1475 w = fprintf(f, "%s\n", line);
1476 if (w != r + 1) /* \n */
1477 return got_ferror(f, GOT_ERR_IO);
1479 return NULL;
1483 * Capture the visible curses screen by writing each line to the
1484 * file at the path set via the TOG_SCR_DUMP environment variable.
1486 static const struct got_error *
1487 screendump(struct tog_view *view)
1489 const struct got_error *err;
1490 FILE *f = NULL;
1491 const char *path;
1492 int i;
1494 path = getenv("TOG_SCR_DUMP");
1495 if (path == NULL || *path == '\0')
1496 return got_error_msg(GOT_ERR_BAD_PATH,
1497 "TOG_SCR_DUMP path not set to capture screen dump");
1498 f = fopen(path, "wex");
1499 if (f == NULL)
1500 return got_error_from_errno_fmt("fopen: %s", path);
1502 if ((view->child && view->child->begin_x) ||
1503 (view->parent && view->begin_x)) {
1504 int ncols = view->child ? view->ncols : view->parent->ncols;
1506 /* vertical splitscreen */
1507 for (i = 0; i < view->nlines; ++i) {
1508 err = view_write_line(f, i, ncols - 1);
1509 if (err)
1510 goto done;
1512 } else {
1513 int hline = 0;
1515 /* fullscreen or horizontal splitscreen */
1516 if ((view->child && view->child->begin_y) ||
1517 (view->parent && view->begin_y)) /* hsplit */
1518 hline = view->child ?
1519 view->child->begin_y : view->begin_y;
1521 for (i = 0; i < view->lines; i++) {
1522 if (hline && got_locale_is_utf8() && i == hline - 1) {
1523 int c;
1525 /* ACS_HLINE writes out as 'q', overwrite it */
1526 for (c = 0; c < view->cols; ++c)
1527 fputc('-', f);
1528 fputc('\n', f);
1529 continue;
1532 err = view_write_line(f, i, 0);
1533 if (err)
1534 goto done;
1538 done:
1539 if (f && fclose(f) == EOF && err == NULL)
1540 err = got_ferror(f, GOT_ERR_IO);
1541 return err;
1545 * Compute view->count from numeric input. Assign total to view->count and
1546 * return first non-numeric key entered.
1548 static int
1549 get_compound_key(struct tog_view *view, int c)
1551 struct tog_view *v = view;
1552 int x, n = 0;
1554 if (view_is_hsplit_top(view))
1555 v = view->child;
1556 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1557 v = view->parent;
1559 view->count = 0;
1560 cbreak(); /* block for input */
1561 nodelay(view->window, FALSE);
1562 wmove(v->window, v->nlines - 1, 0);
1563 wclrtoeol(v->window);
1564 waddch(v->window, ':');
1566 do {
1567 x = getcurx(v->window);
1568 if (x != ERR && x < view->ncols) {
1569 waddch(v->window, c);
1570 wrefresh(v->window);
1574 * Don't overflow. Max valid request should be the greatest
1575 * between the longest and total lines; cap at 10 million.
1577 if (n >= 9999999)
1578 n = 9999999;
1579 else
1580 n = n * 10 + (c - '0');
1581 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1583 if (c == 'G' || c == 'g') { /* nG key map */
1584 view->gline = view->hiline = n;
1585 n = 0;
1586 c = 0;
1589 /* Massage excessive or inapplicable values at the input handler. */
1590 view->count = n;
1592 return c;
1595 static void
1596 action_report(struct tog_view *view)
1598 struct tog_view *v = view;
1600 if (view_is_hsplit_top(view))
1601 v = view->child;
1602 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1603 v = view->parent;
1605 wmove(v->window, v->nlines - 1, 0);
1606 wclrtoeol(v->window);
1607 wprintw(v->window, ":%s", view->action);
1608 wrefresh(v->window);
1611 * Clear action status report. Only clear in blame view
1612 * once annotating is complete, otherwise it's too fast.
1614 if (view->type == TOG_VIEW_BLAME) {
1615 if (view->state.blame.blame_complete)
1616 view->action = NULL;
1617 } else
1618 view->action = NULL;
1622 * Read the next line from the test script and assign
1623 * key instruction to *ch. If at EOF, set the *done flag.
1625 static const struct got_error *
1626 tog_read_script_key(FILE *script, int *ch, int *done)
1628 const struct got_error *err = NULL;
1629 char *line = NULL;
1630 size_t linesz = 0;
1632 if (getline(&line, &linesz, script) == -1) {
1633 if (feof(script)) {
1634 *done = 1;
1635 goto done;
1636 } else {
1637 err = got_ferror(script, GOT_ERR_IO);
1638 goto done;
1640 } else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1641 *ch = KEY_ENTER;
1642 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1643 *ch = KEY_RIGHT;
1644 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1645 *ch = KEY_LEFT;
1646 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1647 *ch = KEY_DOWN;
1648 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1649 *ch = KEY_UP;
1650 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1651 *ch = TOG_KEY_SCRDUMP;
1652 else
1653 *ch = *line;
1655 done:
1656 free(line);
1657 return err;
1660 static const struct got_error *
1661 view_input(struct tog_view **new, int *done, struct tog_view *view,
1662 struct tog_view_list_head *views, int fast_refresh)
1664 const struct got_error *err = NULL;
1665 struct tog_view *v;
1666 int ch, errcode;
1668 *new = NULL;
1670 if (view->action)
1671 action_report(view);
1673 /* Clear "no matches" indicator. */
1674 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1675 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1676 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1677 view->count = 0;
1680 if (view->searching && !view->search_next_done) {
1681 errcode = pthread_mutex_unlock(&tog_mutex);
1682 if (errcode)
1683 return got_error_set_errno(errcode,
1684 "pthread_mutex_unlock");
1685 sched_yield();
1686 errcode = pthread_mutex_lock(&tog_mutex);
1687 if (errcode)
1688 return got_error_set_errno(errcode,
1689 "pthread_mutex_lock");
1690 view->search_next(view);
1691 return NULL;
1694 /* Allow threads to make progress while we are waiting for input. */
1695 errcode = pthread_mutex_unlock(&tog_mutex);
1696 if (errcode)
1697 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1699 if (using_mock_io) {
1700 err = tog_read_script_key(tog_io.f, &ch, done);
1701 if (err)
1702 return err;
1703 } else if (view->count && --view->count) {
1704 cbreak();
1705 nodelay(view->window, TRUE);
1706 ch = wgetch(view->window);
1707 /* let C-g or backspace abort unfinished count */
1708 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1709 view->count = 0;
1710 else
1711 ch = view->ch;
1712 } else {
1713 ch = wgetch(view->window);
1714 if (ch >= '1' && ch <= '9')
1715 view->ch = ch = get_compound_key(view, ch);
1717 if (view->hiline && ch != ERR && ch != 0)
1718 view->hiline = 0; /* key pressed, clear line highlight */
1719 nodelay(view->window, TRUE);
1720 errcode = pthread_mutex_lock(&tog_mutex);
1721 if (errcode)
1722 return got_error_set_errno(errcode, "pthread_mutex_lock");
1724 if (tog_sigwinch_received || tog_sigcont_received) {
1725 tog_resizeterm();
1726 tog_sigwinch_received = 0;
1727 tog_sigcont_received = 0;
1728 TAILQ_FOREACH(v, views, entry) {
1729 err = view_resize(v);
1730 if (err)
1731 return err;
1732 err = v->input(new, v, KEY_RESIZE);
1733 if (err)
1734 return err;
1735 if (v->child) {
1736 err = view_resize(v->child);
1737 if (err)
1738 return err;
1739 err = v->child->input(new, v->child,
1740 KEY_RESIZE);
1741 if (err)
1742 return err;
1743 if (v->child->resized_x || v->child->resized_y) {
1744 err = view_resize_split(v, 0);
1745 if (err)
1746 return err;
1752 switch (ch) {
1753 case '?':
1754 case 'H':
1755 case KEY_F(1):
1756 if (view->type == TOG_VIEW_HELP)
1757 err = view->reset(view);
1758 else
1759 err = view_request_new(new, view, TOG_VIEW_HELP);
1760 break;
1761 case '\t':
1762 view->count = 0;
1763 if (view->child) {
1764 view->focussed = 0;
1765 view->child->focussed = 1;
1766 view->focus_child = 1;
1767 } else if (view->parent) {
1768 view->focussed = 0;
1769 view->parent->focussed = 1;
1770 view->parent->focus_child = 0;
1771 if (!view_is_splitscreen(view)) {
1772 if (view->parent->resize) {
1773 err = view->parent->resize(view->parent,
1774 0);
1775 if (err)
1776 return err;
1778 offset_selection_up(view->parent);
1779 err = view_fullscreen(view->parent);
1780 if (err)
1781 return err;
1784 break;
1785 case 'q':
1786 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1787 if (view->parent->resize) {
1788 /* might need more commits to fill fullscreen */
1789 err = view->parent->resize(view->parent, 0);
1790 if (err)
1791 break;
1793 offset_selection_up(view->parent);
1795 err = view->input(new, view, ch);
1796 view->dying = 1;
1797 break;
1798 case 'Q':
1799 *done = 1;
1800 break;
1801 case 'F':
1802 view->count = 0;
1803 if (view_is_parent_view(view)) {
1804 if (view->child == NULL)
1805 break;
1806 if (view_is_splitscreen(view->child)) {
1807 view->focussed = 0;
1808 view->child->focussed = 1;
1809 err = view_fullscreen(view->child);
1810 } else {
1811 err = view_splitscreen(view->child);
1812 if (!err)
1813 err = view_resize_split(view, 0);
1815 if (err)
1816 break;
1817 err = view->child->input(new, view->child,
1818 KEY_RESIZE);
1819 } else {
1820 if (view_is_splitscreen(view)) {
1821 view->parent->focussed = 0;
1822 view->focussed = 1;
1823 err = view_fullscreen(view);
1824 } else {
1825 err = view_splitscreen(view);
1826 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1827 err = view_resize(view->parent);
1828 if (!err)
1829 err = view_resize_split(view, 0);
1831 if (err)
1832 break;
1833 err = view->input(new, view, KEY_RESIZE);
1835 if (err)
1836 break;
1837 if (view->resize) {
1838 err = view->resize(view, 0);
1839 if (err)
1840 break;
1842 if (view->parent)
1843 err = offset_selection_down(view->parent);
1844 if (!err)
1845 err = offset_selection_down(view);
1846 break;
1847 case 'S':
1848 view->count = 0;
1849 err = switch_split(view);
1850 break;
1851 case '-':
1852 err = view_resize_split(view, -1);
1853 break;
1854 case '+':
1855 err = view_resize_split(view, 1);
1856 break;
1857 case KEY_RESIZE:
1858 break;
1859 case '/':
1860 view->count = 0;
1861 if (view->search_start)
1862 view_search_start(view, fast_refresh);
1863 else
1864 err = view->input(new, view, ch);
1865 break;
1866 case 'N':
1867 case 'n':
1868 if (view->search_started && view->search_next) {
1869 view->searching = (ch == 'n' ?
1870 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1871 view->search_next_done = 0;
1872 view->search_next(view);
1873 } else
1874 err = view->input(new, view, ch);
1875 break;
1876 case 'A':
1877 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1878 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1879 view->action = "Patience diff algorithm";
1880 } else {
1881 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1882 view->action = "Myers diff algorithm";
1884 TAILQ_FOREACH(v, views, entry) {
1885 if (v->reset) {
1886 err = v->reset(v);
1887 if (err)
1888 return err;
1890 if (v->child && v->child->reset) {
1891 err = v->child->reset(v->child);
1892 if (err)
1893 return err;
1896 break;
1897 case TOG_KEY_SCRDUMP:
1898 err = screendump(view);
1899 break;
1900 default:
1901 err = view->input(new, view, ch);
1902 break;
1905 return err;
1908 static int
1909 view_needs_focus_indication(struct tog_view *view)
1911 if (view_is_parent_view(view)) {
1912 if (view->child == NULL || view->child->focussed)
1913 return 0;
1914 if (!view_is_splitscreen(view->child))
1915 return 0;
1916 } else if (!view_is_splitscreen(view))
1917 return 0;
1919 return view->focussed;
1922 static const struct got_error *
1923 tog_io_close(void)
1925 const struct got_error *err = NULL;
1927 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1928 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1929 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1930 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1931 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1932 err = got_ferror(tog_io.f, GOT_ERR_IO);
1934 return err;
1937 static const struct got_error *
1938 view_loop(struct tog_view *view)
1940 const struct got_error *err = NULL;
1941 struct tog_view_list_head views;
1942 struct tog_view *new_view;
1943 char *mode;
1944 int fast_refresh = 10;
1945 int done = 0, errcode;
1947 mode = getenv("TOG_VIEW_SPLIT_MODE");
1948 if (!mode || !(*mode == 'h' || *mode == 'H'))
1949 view->mode = TOG_VIEW_SPLIT_VERT;
1950 else
1951 view->mode = TOG_VIEW_SPLIT_HRZN;
1953 errcode = pthread_mutex_lock(&tog_mutex);
1954 if (errcode)
1955 return got_error_set_errno(errcode, "pthread_mutex_lock");
1957 TAILQ_INIT(&views);
1958 TAILQ_INSERT_HEAD(&views, view, entry);
1960 view->focussed = 1;
1961 err = view->show(view);
1962 if (err)
1963 return err;
1964 update_panels();
1965 doupdate();
1966 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1967 !tog_fatal_signal_received()) {
1968 /* Refresh fast during initialization, then become slower. */
1969 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1970 halfdelay(10); /* switch to once per second */
1972 err = view_input(&new_view, &done, view, &views, fast_refresh);
1973 if (err)
1974 break;
1976 if (view->dying && view == TAILQ_FIRST(&views) &&
1977 TAILQ_NEXT(view, entry) == NULL)
1978 done = 1;
1979 if (done) {
1980 struct tog_view *v;
1983 * When we quit, scroll the screen up a single line
1984 * so we don't lose any information.
1986 TAILQ_FOREACH(v, &views, entry) {
1987 wmove(v->window, 0, 0);
1988 wdeleteln(v->window);
1989 wnoutrefresh(v->window);
1990 if (v->child && !view_is_fullscreen(v)) {
1991 wmove(v->child->window, 0, 0);
1992 wdeleteln(v->child->window);
1993 wnoutrefresh(v->child->window);
1996 doupdate();
1999 if (view->dying) {
2000 struct tog_view *v, *prev = NULL;
2002 if (view_is_parent_view(view))
2003 prev = TAILQ_PREV(view, tog_view_list_head,
2004 entry);
2005 else if (view->parent)
2006 prev = view->parent;
2008 if (view->parent) {
2009 view->parent->child = NULL;
2010 view->parent->focus_child = 0;
2011 /* Restore fullscreen line height. */
2012 view->parent->nlines = view->parent->lines;
2013 err = view_resize(view->parent);
2014 if (err)
2015 break;
2016 /* Make resized splits persist. */
2017 view_transfer_size(view->parent, view);
2018 } else
2019 TAILQ_REMOVE(&views, view, entry);
2021 err = view_close(view);
2022 if (err)
2023 goto done;
2025 view = NULL;
2026 TAILQ_FOREACH(v, &views, entry) {
2027 if (v->focussed)
2028 break;
2030 if (view == NULL && new_view == NULL) {
2031 /* No view has focus. Try to pick one. */
2032 if (prev)
2033 view = prev;
2034 else if (!TAILQ_EMPTY(&views)) {
2035 view = TAILQ_LAST(&views,
2036 tog_view_list_head);
2038 if (view) {
2039 if (view->focus_child) {
2040 view->child->focussed = 1;
2041 view = view->child;
2042 } else
2043 view->focussed = 1;
2047 if (new_view) {
2048 struct tog_view *v, *t;
2049 /* Only allow one parent view per type. */
2050 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2051 if (v->type != new_view->type)
2052 continue;
2053 TAILQ_REMOVE(&views, v, entry);
2054 err = view_close(v);
2055 if (err)
2056 goto done;
2057 break;
2059 TAILQ_INSERT_TAIL(&views, new_view, entry);
2060 view = new_view;
2062 if (view && !done) {
2063 if (view_is_parent_view(view)) {
2064 if (view->child && view->child->focussed)
2065 view = view->child;
2066 } else {
2067 if (view->parent && view->parent->focussed)
2068 view = view->parent;
2070 show_panel(view->panel);
2071 if (view->child && view_is_splitscreen(view->child))
2072 show_panel(view->child->panel);
2073 if (view->parent && view_is_splitscreen(view)) {
2074 err = view->parent->show(view->parent);
2075 if (err)
2076 goto done;
2078 err = view->show(view);
2079 if (err)
2080 goto done;
2081 if (view->child) {
2082 err = view->child->show(view->child);
2083 if (err)
2084 goto done;
2086 update_panels();
2087 doupdate();
2090 done:
2091 while (!TAILQ_EMPTY(&views)) {
2092 const struct got_error *close_err;
2093 view = TAILQ_FIRST(&views);
2094 TAILQ_REMOVE(&views, view, entry);
2095 close_err = view_close(view);
2096 if (close_err && err == NULL)
2097 err = close_err;
2100 errcode = pthread_mutex_unlock(&tog_mutex);
2101 if (errcode && err == NULL)
2102 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2104 return err;
2107 __dead static void
2108 usage_log(void)
2110 endwin();
2111 fprintf(stderr,
2112 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2113 getprogname());
2114 exit(1);
2117 /* Create newly allocated wide-character string equivalent to a byte string. */
2118 static const struct got_error *
2119 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2121 char *vis = NULL;
2122 const struct got_error *err = NULL;
2124 *ws = NULL;
2125 *wlen = mbstowcs(NULL, s, 0);
2126 if (*wlen == (size_t)-1) {
2127 int vislen;
2128 if (errno != EILSEQ)
2129 return got_error_from_errno("mbstowcs");
2131 /* byte string invalid in current encoding; try to "fix" it */
2132 err = got_mbsavis(&vis, &vislen, s);
2133 if (err)
2134 return err;
2135 *wlen = mbstowcs(NULL, vis, 0);
2136 if (*wlen == (size_t)-1) {
2137 err = got_error_from_errno("mbstowcs"); /* give up */
2138 goto done;
2142 *ws = calloc(*wlen + 1, sizeof(**ws));
2143 if (*ws == NULL) {
2144 err = got_error_from_errno("calloc");
2145 goto done;
2148 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2149 err = got_error_from_errno("mbstowcs");
2150 done:
2151 free(vis);
2152 if (err) {
2153 free(*ws);
2154 *ws = NULL;
2155 *wlen = 0;
2157 return err;
2160 static const struct got_error *
2161 expand_tab(char **ptr, const char *src)
2163 char *dst;
2164 size_t len, n, idx = 0, sz = 0;
2166 *ptr = NULL;
2167 n = len = strlen(src);
2168 dst = malloc(n + 1);
2169 if (dst == NULL)
2170 return got_error_from_errno("malloc");
2172 while (idx < len && src[idx]) {
2173 const char c = src[idx];
2175 if (c == '\t') {
2176 size_t nb = TABSIZE - sz % TABSIZE;
2177 char *p;
2179 p = realloc(dst, n + nb);
2180 if (p == NULL) {
2181 free(dst);
2182 return got_error_from_errno("realloc");
2185 dst = p;
2186 n += nb;
2187 memset(dst + sz, ' ', nb);
2188 sz += nb;
2189 } else
2190 dst[sz++] = src[idx];
2191 ++idx;
2194 dst[sz] = '\0';
2195 *ptr = dst;
2196 return NULL;
2200 * Advance at most n columns from wline starting at offset off.
2201 * Return the index to the first character after the span operation.
2202 * Return the combined column width of all spanned wide character in
2203 * *rcol.
2205 static int
2206 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2208 int width, i, cols = 0;
2210 if (n == 0) {
2211 *rcol = cols;
2212 return off;
2215 for (i = off; wline[i] != L'\0'; ++i) {
2216 if (wline[i] == L'\t')
2217 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2218 else
2219 width = wcwidth(wline[i]);
2221 if (width == -1) {
2222 width = 1;
2223 wline[i] = L'.';
2226 if (cols + width > n)
2227 break;
2228 cols += width;
2231 *rcol = cols;
2232 return i;
2236 * Format a line for display, ensuring that it won't overflow a width limit.
2237 * With scrolling, the width returned refers to the scrolled version of the
2238 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2240 static const struct got_error *
2241 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2242 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2244 const struct got_error *err = NULL;
2245 int cols;
2246 wchar_t *wline = NULL;
2247 char *exstr = NULL;
2248 size_t wlen;
2249 int i, scrollx;
2251 *wlinep = NULL;
2252 *widthp = 0;
2254 if (expand) {
2255 err = expand_tab(&exstr, line);
2256 if (err)
2257 return err;
2260 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2261 free(exstr);
2262 if (err)
2263 return err;
2265 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2267 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2268 wline[wlen - 1] = L'\0';
2269 wlen--;
2271 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2272 wline[wlen - 1] = L'\0';
2273 wlen--;
2276 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2277 wline[i] = L'\0';
2279 if (widthp)
2280 *widthp = cols;
2281 if (scrollxp)
2282 *scrollxp = scrollx;
2283 if (err)
2284 free(wline);
2285 else
2286 *wlinep = wline;
2287 return err;
2290 static const struct got_error*
2291 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2292 struct got_object_id *id, struct got_repository *repo)
2294 static const struct got_error *err = NULL;
2295 struct got_reflist_entry *re;
2296 char *s;
2297 const char *name;
2299 *refs_str = NULL;
2301 TAILQ_FOREACH(re, refs, entry) {
2302 struct got_tag_object *tag = NULL;
2303 struct got_object_id *ref_id;
2304 int cmp;
2306 name = got_ref_get_name(re->ref);
2307 if (strcmp(name, GOT_REF_HEAD) == 0)
2308 continue;
2309 if (strncmp(name, "refs/", 5) == 0)
2310 name += 5;
2311 if (strncmp(name, "got/", 4) == 0 &&
2312 strncmp(name, "got/backup/", 11) != 0)
2313 continue;
2314 if (strncmp(name, "heads/", 6) == 0)
2315 name += 6;
2316 if (strncmp(name, "remotes/", 8) == 0) {
2317 name += 8;
2318 s = strstr(name, "/" GOT_REF_HEAD);
2319 if (s != NULL && s[strlen(s)] == '\0')
2320 continue;
2322 err = got_ref_resolve(&ref_id, repo, re->ref);
2323 if (err)
2324 break;
2325 if (strncmp(name, "tags/", 5) == 0) {
2326 err = got_object_open_as_tag(&tag, repo, ref_id);
2327 if (err) {
2328 if (err->code != GOT_ERR_OBJ_TYPE) {
2329 free(ref_id);
2330 break;
2332 /* Ref points at something other than a tag. */
2333 err = NULL;
2334 tag = NULL;
2337 cmp = got_object_id_cmp(tag ?
2338 got_object_tag_get_object_id(tag) : ref_id, id);
2339 free(ref_id);
2340 if (tag)
2341 got_object_tag_close(tag);
2342 if (cmp != 0)
2343 continue;
2344 s = *refs_str;
2345 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2346 s ? ", " : "", name) == -1) {
2347 err = got_error_from_errno("asprintf");
2348 free(s);
2349 *refs_str = NULL;
2350 break;
2352 free(s);
2355 return err;
2358 static const struct got_error *
2359 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2360 int col_tab_align)
2362 char *smallerthan;
2364 smallerthan = strchr(author, '<');
2365 if (smallerthan && smallerthan[1] != '\0')
2366 author = smallerthan + 1;
2367 author[strcspn(author, "@>")] = '\0';
2368 return format_line(wauthor, author_width, NULL, author, 0, limit,
2369 col_tab_align, 0);
2372 static const struct got_error *
2373 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2374 struct got_object_id *id, const size_t date_display_cols,
2375 int author_display_cols)
2377 struct tog_log_view_state *s = &view->state.log;
2378 const struct got_error *err = NULL;
2379 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2380 char *logmsg0 = NULL, *logmsg = NULL;
2381 char *author = NULL;
2382 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2383 int author_width, logmsg_width;
2384 char *newline, *line = NULL;
2385 int col, limit, scrollx;
2386 const int avail = view->ncols;
2387 struct tm tm;
2388 time_t committer_time;
2389 struct tog_color *tc;
2391 committer_time = got_object_commit_get_committer_time(commit);
2392 if (gmtime_r(&committer_time, &tm) == NULL)
2393 return got_error_from_errno("gmtime_r");
2394 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2395 return got_error(GOT_ERR_NO_SPACE);
2397 if (avail <= date_display_cols)
2398 limit = MIN(sizeof(datebuf) - 1, avail);
2399 else
2400 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2401 tc = get_color(&s->colors, TOG_COLOR_DATE);
2402 if (tc)
2403 wattr_on(view->window,
2404 COLOR_PAIR(tc->colorpair), NULL);
2405 waddnstr(view->window, datebuf, limit);
2406 if (tc)
2407 wattr_off(view->window,
2408 COLOR_PAIR(tc->colorpair), NULL);
2409 col = limit;
2410 if (col > avail)
2411 goto done;
2413 if (avail >= 120) {
2414 char *id_str;
2415 err = got_object_id_str(&id_str, id);
2416 if (err)
2417 goto done;
2418 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2419 if (tc)
2420 wattr_on(view->window,
2421 COLOR_PAIR(tc->colorpair), NULL);
2422 wprintw(view->window, "%.8s ", id_str);
2423 if (tc)
2424 wattr_off(view->window,
2425 COLOR_PAIR(tc->colorpair), NULL);
2426 free(id_str);
2427 col += 9;
2428 if (col > avail)
2429 goto done;
2432 if (s->use_committer)
2433 author = strdup(got_object_commit_get_committer(commit));
2434 else
2435 author = strdup(got_object_commit_get_author(commit));
2436 if (author == NULL) {
2437 err = got_error_from_errno("strdup");
2438 goto done;
2440 err = format_author(&wauthor, &author_width, author, avail - col, col);
2441 if (err)
2442 goto done;
2443 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2444 if (tc)
2445 wattr_on(view->window,
2446 COLOR_PAIR(tc->colorpair), NULL);
2447 waddwstr(view->window, wauthor);
2448 col += author_width;
2449 while (col < avail && author_width < author_display_cols + 2) {
2450 waddch(view->window, ' ');
2451 col++;
2452 author_width++;
2454 if (tc)
2455 wattr_off(view->window,
2456 COLOR_PAIR(tc->colorpair), NULL);
2457 if (col > avail)
2458 goto done;
2460 err = got_object_commit_get_logmsg(&logmsg0, commit);
2461 if (err)
2462 goto done;
2463 logmsg = logmsg0;
2464 while (*logmsg == '\n')
2465 logmsg++;
2466 newline = strchr(logmsg, '\n');
2467 if (newline)
2468 *newline = '\0';
2469 limit = avail - col;
2470 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2471 limit--; /* for the border */
2472 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2473 limit, col, 1);
2474 if (err)
2475 goto done;
2476 waddwstr(view->window, &wlogmsg[scrollx]);
2477 col += MAX(logmsg_width, 0);
2478 while (col < avail) {
2479 waddch(view->window, ' ');
2480 col++;
2482 done:
2483 free(logmsg0);
2484 free(wlogmsg);
2485 free(author);
2486 free(wauthor);
2487 free(line);
2488 return err;
2491 static struct commit_queue_entry *
2492 alloc_commit_queue_entry(struct got_commit_object *commit,
2493 struct got_object_id *id)
2495 struct commit_queue_entry *entry;
2496 struct got_object_id *dup;
2498 entry = calloc(1, sizeof(*entry));
2499 if (entry == NULL)
2500 return NULL;
2502 dup = got_object_id_dup(id);
2503 if (dup == NULL) {
2504 free(entry);
2505 return NULL;
2508 entry->id = dup;
2509 entry->commit = commit;
2510 return entry;
2513 static void
2514 pop_commit(struct commit_queue *commits)
2516 struct commit_queue_entry *entry;
2518 entry = TAILQ_FIRST(&commits->head);
2519 TAILQ_REMOVE(&commits->head, entry, entry);
2520 got_object_commit_close(entry->commit);
2521 commits->ncommits--;
2522 free(entry->id);
2523 free(entry);
2526 static void
2527 free_commits(struct commit_queue *commits)
2529 while (!TAILQ_EMPTY(&commits->head))
2530 pop_commit(commits);
2533 static const struct got_error *
2534 match_commit(int *have_match, struct got_object_id *id,
2535 struct got_commit_object *commit, regex_t *regex)
2537 const struct got_error *err = NULL;
2538 regmatch_t regmatch;
2539 char *id_str = NULL, *logmsg = NULL;
2541 *have_match = 0;
2543 err = got_object_id_str(&id_str, id);
2544 if (err)
2545 return err;
2547 err = got_object_commit_get_logmsg(&logmsg, commit);
2548 if (err)
2549 goto done;
2551 if (regexec(regex, got_object_commit_get_author(commit), 1,
2552 &regmatch, 0) == 0 ||
2553 regexec(regex, got_object_commit_get_committer(commit), 1,
2554 &regmatch, 0) == 0 ||
2555 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2556 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2557 *have_match = 1;
2558 done:
2559 free(id_str);
2560 free(logmsg);
2561 return err;
2564 static const struct got_error *
2565 queue_commits(struct tog_log_thread_args *a)
2567 const struct got_error *err = NULL;
2570 * We keep all commits open throughout the lifetime of the log
2571 * view in order to avoid having to re-fetch commits from disk
2572 * while updating the display.
2574 do {
2575 struct got_object_id id;
2576 struct got_commit_object *commit;
2577 struct commit_queue_entry *entry;
2578 int limit_match = 0;
2579 int errcode;
2581 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2582 NULL, NULL);
2583 if (err)
2584 break;
2586 err = got_object_open_as_commit(&commit, a->repo, &id);
2587 if (err)
2588 break;
2589 entry = alloc_commit_queue_entry(commit, &id);
2590 if (entry == NULL) {
2591 err = got_error_from_errno("alloc_commit_queue_entry");
2592 break;
2595 errcode = pthread_mutex_lock(&tog_mutex);
2596 if (errcode) {
2597 err = got_error_set_errno(errcode,
2598 "pthread_mutex_lock");
2599 break;
2602 entry->idx = a->real_commits->ncommits;
2603 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2604 a->real_commits->ncommits++;
2606 if (*a->limiting) {
2607 err = match_commit(&limit_match, &id, commit,
2608 a->limit_regex);
2609 if (err)
2610 break;
2612 if (limit_match) {
2613 struct commit_queue_entry *matched;
2615 matched = alloc_commit_queue_entry(
2616 entry->commit, entry->id);
2617 if (matched == NULL) {
2618 err = got_error_from_errno(
2619 "alloc_commit_queue_entry");
2620 break;
2622 matched->commit = entry->commit;
2623 got_object_commit_retain(entry->commit);
2625 matched->idx = a->limit_commits->ncommits;
2626 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2627 matched, entry);
2628 a->limit_commits->ncommits++;
2632 * This is how we signal log_thread() that we
2633 * have found a match, and that it should be
2634 * counted as a new entry for the view.
2636 a->limit_match = limit_match;
2639 if (*a->searching == TOG_SEARCH_FORWARD &&
2640 !*a->search_next_done) {
2641 int have_match;
2642 err = match_commit(&have_match, &id, commit, a->regex);
2643 if (err)
2644 break;
2646 if (*a->limiting) {
2647 if (limit_match && have_match)
2648 *a->search_next_done =
2649 TOG_SEARCH_HAVE_MORE;
2650 } else if (have_match)
2651 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2654 errcode = pthread_mutex_unlock(&tog_mutex);
2655 if (errcode && err == NULL)
2656 err = got_error_set_errno(errcode,
2657 "pthread_mutex_unlock");
2658 if (err)
2659 break;
2660 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2662 return err;
2665 static void
2666 select_commit(struct tog_log_view_state *s)
2668 struct commit_queue_entry *entry;
2669 int ncommits = 0;
2671 entry = s->first_displayed_entry;
2672 while (entry) {
2673 if (ncommits == s->selected) {
2674 s->selected_entry = entry;
2675 break;
2677 entry = TAILQ_NEXT(entry, entry);
2678 ncommits++;
2682 static const struct got_error *
2683 draw_commits(struct tog_view *view)
2685 const struct got_error *err = NULL;
2686 struct tog_log_view_state *s = &view->state.log;
2687 struct commit_queue_entry *entry = s->selected_entry;
2688 int limit = view->nlines;
2689 int width;
2690 int ncommits, author_cols = 4;
2691 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2692 char *refs_str = NULL;
2693 wchar_t *wline;
2694 struct tog_color *tc;
2695 static const size_t date_display_cols = 12;
2697 if (view_is_hsplit_top(view))
2698 --limit; /* account for border */
2700 if (s->selected_entry &&
2701 !(view->searching && view->search_next_done == 0)) {
2702 struct got_reflist_head *refs;
2703 err = got_object_id_str(&id_str, s->selected_entry->id);
2704 if (err)
2705 return err;
2706 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2707 s->selected_entry->id);
2708 if (refs) {
2709 err = build_refs_str(&refs_str, refs,
2710 s->selected_entry->id, s->repo);
2711 if (err)
2712 goto done;
2716 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2717 halfdelay(10); /* disable fast refresh */
2719 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2720 if (asprintf(&ncommits_str, " [%d/%d] %s",
2721 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2722 (view->searching && !view->search_next_done) ?
2723 "searching..." : "loading...") == -1) {
2724 err = got_error_from_errno("asprintf");
2725 goto done;
2727 } else {
2728 const char *search_str = NULL;
2729 const char *limit_str = NULL;
2731 if (view->searching) {
2732 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2733 search_str = "no more matches";
2734 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2735 search_str = "no matches found";
2736 else if (!view->search_next_done)
2737 search_str = "searching...";
2740 if (s->limit_view && s->commits->ncommits == 0)
2741 limit_str = "no matches found";
2743 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2744 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2745 search_str ? search_str : (refs_str ? refs_str : ""),
2746 limit_str ? limit_str : "") == -1) {
2747 err = got_error_from_errno("asprintf");
2748 goto done;
2752 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2753 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2754 "........................................",
2755 s->in_repo_path, ncommits_str) == -1) {
2756 err = got_error_from_errno("asprintf");
2757 header = NULL;
2758 goto done;
2760 } else if (asprintf(&header, "commit %s%s",
2761 id_str ? id_str : "........................................",
2762 ncommits_str) == -1) {
2763 err = got_error_from_errno("asprintf");
2764 header = NULL;
2765 goto done;
2767 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2768 if (err)
2769 goto done;
2771 werase(view->window);
2773 if (view_needs_focus_indication(view))
2774 wstandout(view->window);
2775 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2776 if (tc)
2777 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2778 waddwstr(view->window, wline);
2779 while (width < view->ncols) {
2780 waddch(view->window, ' ');
2781 width++;
2783 if (tc)
2784 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2785 if (view_needs_focus_indication(view))
2786 wstandend(view->window);
2787 free(wline);
2788 if (limit <= 1)
2789 goto done;
2791 /* Grow author column size if necessary, and set view->maxx. */
2792 entry = s->first_displayed_entry;
2793 ncommits = 0;
2794 view->maxx = 0;
2795 while (entry) {
2796 struct got_commit_object *c = entry->commit;
2797 char *author, *eol, *msg, *msg0;
2798 wchar_t *wauthor, *wmsg;
2799 int width;
2800 if (ncommits >= limit - 1)
2801 break;
2802 if (s->use_committer)
2803 author = strdup(got_object_commit_get_committer(c));
2804 else
2805 author = strdup(got_object_commit_get_author(c));
2806 if (author == NULL) {
2807 err = got_error_from_errno("strdup");
2808 goto done;
2810 err = format_author(&wauthor, &width, author, COLS,
2811 date_display_cols);
2812 if (author_cols < width)
2813 author_cols = width;
2814 free(wauthor);
2815 free(author);
2816 if (err)
2817 goto done;
2818 err = got_object_commit_get_logmsg(&msg0, c);
2819 if (err)
2820 goto done;
2821 msg = msg0;
2822 while (*msg == '\n')
2823 ++msg;
2824 if ((eol = strchr(msg, '\n')))
2825 *eol = '\0';
2826 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2827 date_display_cols + author_cols, 0);
2828 if (err)
2829 goto done;
2830 view->maxx = MAX(view->maxx, width);
2831 free(msg0);
2832 free(wmsg);
2833 ncommits++;
2834 entry = TAILQ_NEXT(entry, entry);
2837 entry = s->first_displayed_entry;
2838 s->last_displayed_entry = s->first_displayed_entry;
2839 ncommits = 0;
2840 while (entry) {
2841 if (ncommits >= limit - 1)
2842 break;
2843 if (ncommits == s->selected)
2844 wstandout(view->window);
2845 err = draw_commit(view, entry->commit, entry->id,
2846 date_display_cols, author_cols);
2847 if (ncommits == s->selected)
2848 wstandend(view->window);
2849 if (err)
2850 goto done;
2851 ncommits++;
2852 s->last_displayed_entry = entry;
2853 entry = TAILQ_NEXT(entry, entry);
2856 view_border(view);
2857 done:
2858 free(id_str);
2859 free(refs_str);
2860 free(ncommits_str);
2861 free(header);
2862 return err;
2865 static void
2866 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2868 struct commit_queue_entry *entry;
2869 int nscrolled = 0;
2871 entry = TAILQ_FIRST(&s->commits->head);
2872 if (s->first_displayed_entry == entry)
2873 return;
2875 entry = s->first_displayed_entry;
2876 while (entry && nscrolled < maxscroll) {
2877 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2878 if (entry) {
2879 s->first_displayed_entry = entry;
2880 nscrolled++;
2885 static const struct got_error *
2886 trigger_log_thread(struct tog_view *view, int wait)
2888 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2889 int errcode;
2891 if (!using_mock_io)
2892 halfdelay(1); /* fast refresh while loading commits */
2894 while (!ta->log_complete && !tog_thread_error &&
2895 (ta->commits_needed > 0 || ta->load_all)) {
2896 /* Wake the log thread. */
2897 errcode = pthread_cond_signal(&ta->need_commits);
2898 if (errcode)
2899 return got_error_set_errno(errcode,
2900 "pthread_cond_signal");
2903 * The mutex will be released while the view loop waits
2904 * in wgetch(), at which time the log thread will run.
2906 if (!wait)
2907 break;
2909 /* Display progress update in log view. */
2910 show_log_view(view);
2911 update_panels();
2912 doupdate();
2914 /* Wait right here while next commit is being loaded. */
2915 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2916 if (errcode)
2917 return got_error_set_errno(errcode,
2918 "pthread_cond_wait");
2920 /* Display progress update in log view. */
2921 show_log_view(view);
2922 update_panels();
2923 doupdate();
2926 return NULL;
2929 static const struct got_error *
2930 request_log_commits(struct tog_view *view)
2932 struct tog_log_view_state *state = &view->state.log;
2933 const struct got_error *err = NULL;
2935 if (state->thread_args.log_complete)
2936 return NULL;
2938 state->thread_args.commits_needed += view->nscrolled;
2939 err = trigger_log_thread(view, 1);
2940 view->nscrolled = 0;
2942 return err;
2945 static const struct got_error *
2946 log_scroll_down(struct tog_view *view, int maxscroll)
2948 struct tog_log_view_state *s = &view->state.log;
2949 const struct got_error *err = NULL;
2950 struct commit_queue_entry *pentry;
2951 int nscrolled = 0, ncommits_needed;
2953 if (s->last_displayed_entry == NULL)
2954 return NULL;
2956 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2957 if (s->commits->ncommits < ncommits_needed &&
2958 !s->thread_args.log_complete) {
2960 * Ask the log thread for required amount of commits.
2962 s->thread_args.commits_needed +=
2963 ncommits_needed - s->commits->ncommits;
2964 err = trigger_log_thread(view, 1);
2965 if (err)
2966 return err;
2969 do {
2970 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2971 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2972 break;
2974 s->last_displayed_entry = pentry ?
2975 pentry : s->last_displayed_entry;
2977 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2978 if (pentry == NULL)
2979 break;
2980 s->first_displayed_entry = pentry;
2981 } while (++nscrolled < maxscroll);
2983 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2984 view->nscrolled += nscrolled;
2985 else
2986 view->nscrolled = 0;
2988 return err;
2991 static const struct got_error *
2992 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2993 struct got_commit_object *commit, struct got_object_id *commit_id,
2994 struct tog_view *log_view, struct got_repository *repo)
2996 const struct got_error *err;
2997 struct got_object_qid *parent_id;
2998 struct tog_view *diff_view;
3000 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3001 if (diff_view == NULL)
3002 return got_error_from_errno("view_open");
3004 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3005 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3006 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3007 if (err == NULL)
3008 *new_view = diff_view;
3009 return err;
3012 static const struct got_error *
3013 tree_view_visit_subtree(struct tog_tree_view_state *s,
3014 struct got_tree_object *subtree)
3016 struct tog_parent_tree *parent;
3018 parent = calloc(1, sizeof(*parent));
3019 if (parent == NULL)
3020 return got_error_from_errno("calloc");
3022 parent->tree = s->tree;
3023 parent->first_displayed_entry = s->first_displayed_entry;
3024 parent->selected_entry = s->selected_entry;
3025 parent->selected = s->selected;
3026 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3027 s->tree = subtree;
3028 s->selected = 0;
3029 s->first_displayed_entry = NULL;
3030 return NULL;
3033 static const struct got_error *
3034 tree_view_walk_path(struct tog_tree_view_state *s,
3035 struct got_commit_object *commit, const char *path)
3037 const struct got_error *err = NULL;
3038 struct got_tree_object *tree = NULL;
3039 const char *p;
3040 char *slash, *subpath = NULL;
3042 /* Walk the path and open corresponding tree objects. */
3043 p = path;
3044 while (*p) {
3045 struct got_tree_entry *te;
3046 struct got_object_id *tree_id;
3047 char *te_name;
3049 while (p[0] == '/')
3050 p++;
3052 /* Ensure the correct subtree entry is selected. */
3053 slash = strchr(p, '/');
3054 if (slash == NULL)
3055 te_name = strdup(p);
3056 else
3057 te_name = strndup(p, slash - p);
3058 if (te_name == NULL) {
3059 err = got_error_from_errno("strndup");
3060 break;
3062 te = got_object_tree_find_entry(s->tree, te_name);
3063 if (te == NULL) {
3064 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3065 free(te_name);
3066 break;
3068 free(te_name);
3069 s->first_displayed_entry = s->selected_entry = te;
3071 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3072 break; /* jump to this file's entry */
3074 slash = strchr(p, '/');
3075 if (slash)
3076 subpath = strndup(path, slash - path);
3077 else
3078 subpath = strdup(path);
3079 if (subpath == NULL) {
3080 err = got_error_from_errno("strdup");
3081 break;
3084 err = got_object_id_by_path(&tree_id, s->repo, commit,
3085 subpath);
3086 if (err)
3087 break;
3089 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3090 free(tree_id);
3091 if (err)
3092 break;
3094 err = tree_view_visit_subtree(s, tree);
3095 if (err) {
3096 got_object_tree_close(tree);
3097 break;
3099 if (slash == NULL)
3100 break;
3101 free(subpath);
3102 subpath = NULL;
3103 p = slash;
3106 free(subpath);
3107 return err;
3110 static const struct got_error *
3111 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3112 struct commit_queue_entry *entry, const char *path,
3113 const char *head_ref_name, struct got_repository *repo)
3115 const struct got_error *err = NULL;
3116 struct tog_tree_view_state *s;
3117 struct tog_view *tree_view;
3119 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3120 if (tree_view == NULL)
3121 return got_error_from_errno("view_open");
3123 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3124 if (err)
3125 return err;
3126 s = &tree_view->state.tree;
3128 *new_view = tree_view;
3130 if (got_path_is_root_dir(path))
3131 return NULL;
3133 return tree_view_walk_path(s, entry->commit, path);
3136 static const struct got_error *
3137 block_signals_used_by_main_thread(void)
3139 sigset_t sigset;
3140 int errcode;
3142 if (sigemptyset(&sigset) == -1)
3143 return got_error_from_errno("sigemptyset");
3145 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3146 if (sigaddset(&sigset, SIGWINCH) == -1)
3147 return got_error_from_errno("sigaddset");
3148 if (sigaddset(&sigset, SIGCONT) == -1)
3149 return got_error_from_errno("sigaddset");
3150 if (sigaddset(&sigset, SIGINT) == -1)
3151 return got_error_from_errno("sigaddset");
3152 if (sigaddset(&sigset, SIGTERM) == -1)
3153 return got_error_from_errno("sigaddset");
3155 /* ncurses handles SIGTSTP */
3156 if (sigaddset(&sigset, SIGTSTP) == -1)
3157 return got_error_from_errno("sigaddset");
3159 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3160 if (errcode)
3161 return got_error_set_errno(errcode, "pthread_sigmask");
3163 return NULL;
3166 static void *
3167 log_thread(void *arg)
3169 const struct got_error *err = NULL;
3170 int errcode = 0;
3171 struct tog_log_thread_args *a = arg;
3172 int done = 0;
3175 * Sync startup with main thread such that we begin our
3176 * work once view_input() has released the mutex.
3178 errcode = pthread_mutex_lock(&tog_mutex);
3179 if (errcode) {
3180 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3181 return (void *)err;
3184 err = block_signals_used_by_main_thread();
3185 if (err) {
3186 pthread_mutex_unlock(&tog_mutex);
3187 goto done;
3190 while (!done && !err && !tog_fatal_signal_received()) {
3191 errcode = pthread_mutex_unlock(&tog_mutex);
3192 if (errcode) {
3193 err = got_error_set_errno(errcode,
3194 "pthread_mutex_unlock");
3195 goto done;
3197 err = queue_commits(a);
3198 if (err) {
3199 if (err->code != GOT_ERR_ITER_COMPLETED)
3200 goto done;
3201 err = NULL;
3202 done = 1;
3203 } else if (a->commits_needed > 0 && !a->load_all) {
3204 if (*a->limiting) {
3205 if (a->limit_match)
3206 a->commits_needed--;
3207 } else
3208 a->commits_needed--;
3211 errcode = pthread_mutex_lock(&tog_mutex);
3212 if (errcode) {
3213 err = got_error_set_errno(errcode,
3214 "pthread_mutex_lock");
3215 goto done;
3216 } else if (*a->quit)
3217 done = 1;
3218 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3219 *a->first_displayed_entry =
3220 TAILQ_FIRST(&a->limit_commits->head);
3221 *a->selected_entry = *a->first_displayed_entry;
3222 } else if (*a->first_displayed_entry == NULL) {
3223 *a->first_displayed_entry =
3224 TAILQ_FIRST(&a->real_commits->head);
3225 *a->selected_entry = *a->first_displayed_entry;
3228 errcode = pthread_cond_signal(&a->commit_loaded);
3229 if (errcode) {
3230 err = got_error_set_errno(errcode,
3231 "pthread_cond_signal");
3232 pthread_mutex_unlock(&tog_mutex);
3233 goto done;
3236 if (done)
3237 a->commits_needed = 0;
3238 else {
3239 if (a->commits_needed == 0 && !a->load_all) {
3240 errcode = pthread_cond_wait(&a->need_commits,
3241 &tog_mutex);
3242 if (errcode) {
3243 err = got_error_set_errno(errcode,
3244 "pthread_cond_wait");
3245 pthread_mutex_unlock(&tog_mutex);
3246 goto done;
3248 if (*a->quit)
3249 done = 1;
3253 a->log_complete = 1;
3254 errcode = pthread_mutex_unlock(&tog_mutex);
3255 if (errcode)
3256 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3257 done:
3258 if (err) {
3259 tog_thread_error = 1;
3260 pthread_cond_signal(&a->commit_loaded);
3262 return (void *)err;
3265 static const struct got_error *
3266 stop_log_thread(struct tog_log_view_state *s)
3268 const struct got_error *err = NULL, *thread_err = NULL;
3269 int errcode;
3271 if (s->thread) {
3272 s->quit = 1;
3273 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3274 if (errcode)
3275 return got_error_set_errno(errcode,
3276 "pthread_cond_signal");
3277 errcode = pthread_mutex_unlock(&tog_mutex);
3278 if (errcode)
3279 return got_error_set_errno(errcode,
3280 "pthread_mutex_unlock");
3281 errcode = pthread_join(s->thread, (void **)&thread_err);
3282 if (errcode)
3283 return got_error_set_errno(errcode, "pthread_join");
3284 errcode = pthread_mutex_lock(&tog_mutex);
3285 if (errcode)
3286 return got_error_set_errno(errcode,
3287 "pthread_mutex_lock");
3288 s->thread = NULL;
3291 if (s->thread_args.repo) {
3292 err = got_repo_close(s->thread_args.repo);
3293 s->thread_args.repo = NULL;
3296 if (s->thread_args.pack_fds) {
3297 const struct got_error *pack_err =
3298 got_repo_pack_fds_close(s->thread_args.pack_fds);
3299 if (err == NULL)
3300 err = pack_err;
3301 s->thread_args.pack_fds = NULL;
3304 if (s->thread_args.graph) {
3305 got_commit_graph_close(s->thread_args.graph);
3306 s->thread_args.graph = NULL;
3309 return err ? err : thread_err;
3312 static const struct got_error *
3313 close_log_view(struct tog_view *view)
3315 const struct got_error *err = NULL;
3316 struct tog_log_view_state *s = &view->state.log;
3317 int errcode;
3319 err = stop_log_thread(s);
3321 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3322 if (errcode && err == NULL)
3323 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3325 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3326 if (errcode && err == NULL)
3327 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3329 free_commits(&s->limit_commits);
3330 free_commits(&s->real_commits);
3331 free(s->in_repo_path);
3332 s->in_repo_path = NULL;
3333 free(s->start_id);
3334 s->start_id = NULL;
3335 free(s->head_ref_name);
3336 s->head_ref_name = NULL;
3337 return err;
3341 * We use two queues to implement the limit feature: first consists of
3342 * commits matching the current limit_regex; second is the real queue
3343 * of all known commits (real_commits). When the user starts limiting,
3344 * we swap queues such that all movement and displaying functionality
3345 * works with very slight change.
3347 static const struct got_error *
3348 limit_log_view(struct tog_view *view)
3350 struct tog_log_view_state *s = &view->state.log;
3351 struct commit_queue_entry *entry;
3352 struct tog_view *v = view;
3353 const struct got_error *err = NULL;
3354 char pattern[1024];
3355 int ret;
3357 if (view_is_hsplit_top(view))
3358 v = view->child;
3359 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3360 v = view->parent;
3362 /* Get the pattern */
3363 wmove(v->window, v->nlines - 1, 0);
3364 wclrtoeol(v->window);
3365 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3366 nodelay(v->window, FALSE);
3367 nocbreak();
3368 echo();
3369 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3370 cbreak();
3371 noecho();
3372 nodelay(v->window, TRUE);
3373 if (ret == ERR)
3374 return NULL;
3376 if (*pattern == '\0') {
3378 * Safety measure for the situation where the user
3379 * resets limit without previously limiting anything.
3381 if (!s->limit_view)
3382 return NULL;
3385 * User could have pressed Ctrl+L, which refreshed the
3386 * commit queues, it means we can't save previously
3387 * (before limit took place) displayed entries,
3388 * because they would point to already free'ed memory,
3389 * so we are forced to always select first entry of
3390 * the queue.
3392 s->commits = &s->real_commits;
3393 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3394 s->selected_entry = s->first_displayed_entry;
3395 s->selected = 0;
3396 s->limit_view = 0;
3398 return NULL;
3401 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3402 return NULL;
3404 s->limit_view = 1;
3406 /* Clear the screen while loading limit view */
3407 s->first_displayed_entry = NULL;
3408 s->last_displayed_entry = NULL;
3409 s->selected_entry = NULL;
3410 s->commits = &s->limit_commits;
3412 /* Prepare limit queue for new search */
3413 free_commits(&s->limit_commits);
3414 s->limit_commits.ncommits = 0;
3416 /* First process commits, which are in queue already */
3417 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3418 int have_match = 0;
3420 err = match_commit(&have_match, entry->id,
3421 entry->commit, &s->limit_regex);
3422 if (err)
3423 return err;
3425 if (have_match) {
3426 struct commit_queue_entry *matched;
3428 matched = alloc_commit_queue_entry(entry->commit,
3429 entry->id);
3430 if (matched == NULL) {
3431 err = got_error_from_errno(
3432 "alloc_commit_queue_entry");
3433 break;
3435 matched->commit = entry->commit;
3436 got_object_commit_retain(entry->commit);
3438 matched->idx = s->limit_commits.ncommits;
3439 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3440 matched, entry);
3441 s->limit_commits.ncommits++;
3445 /* Second process all the commits, until we fill the screen */
3446 if (s->limit_commits.ncommits < view->nlines - 1 &&
3447 !s->thread_args.log_complete) {
3448 s->thread_args.commits_needed +=
3449 view->nlines - s->limit_commits.ncommits - 1;
3450 err = trigger_log_thread(view, 1);
3451 if (err)
3452 return err;
3455 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3456 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3457 s->selected = 0;
3459 return NULL;
3462 static const struct got_error *
3463 search_start_log_view(struct tog_view *view)
3465 struct tog_log_view_state *s = &view->state.log;
3467 s->matched_entry = NULL;
3468 s->search_entry = NULL;
3469 return NULL;
3472 static const struct got_error *
3473 search_next_log_view(struct tog_view *view)
3475 const struct got_error *err = NULL;
3476 struct tog_log_view_state *s = &view->state.log;
3477 struct commit_queue_entry *entry;
3479 /* Display progress update in log view. */
3480 show_log_view(view);
3481 update_panels();
3482 doupdate();
3484 if (s->search_entry) {
3485 int errcode, ch;
3486 errcode = pthread_mutex_unlock(&tog_mutex);
3487 if (errcode)
3488 return got_error_set_errno(errcode,
3489 "pthread_mutex_unlock");
3490 ch = wgetch(view->window);
3491 errcode = pthread_mutex_lock(&tog_mutex);
3492 if (errcode)
3493 return got_error_set_errno(errcode,
3494 "pthread_mutex_lock");
3495 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3496 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3497 return NULL;
3499 if (view->searching == TOG_SEARCH_FORWARD)
3500 entry = TAILQ_NEXT(s->search_entry, entry);
3501 else
3502 entry = TAILQ_PREV(s->search_entry,
3503 commit_queue_head, entry);
3504 } else if (s->matched_entry) {
3506 * If the user has moved the cursor after we hit a match,
3507 * the position from where we should continue searching
3508 * might have changed.
3510 if (view->searching == TOG_SEARCH_FORWARD)
3511 entry = TAILQ_NEXT(s->selected_entry, entry);
3512 else
3513 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3514 entry);
3515 } else {
3516 entry = s->selected_entry;
3519 while (1) {
3520 int have_match = 0;
3522 if (entry == NULL) {
3523 if (s->thread_args.log_complete ||
3524 view->searching == TOG_SEARCH_BACKWARD) {
3525 view->search_next_done =
3526 (s->matched_entry == NULL ?
3527 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3528 s->search_entry = NULL;
3529 return NULL;
3532 * Poke the log thread for more commits and return,
3533 * allowing the main loop to make progress. Search
3534 * will resume at s->search_entry once we come back.
3536 s->thread_args.commits_needed++;
3537 return trigger_log_thread(view, 0);
3540 err = match_commit(&have_match, entry->id, entry->commit,
3541 &view->regex);
3542 if (err)
3543 break;
3544 if (have_match) {
3545 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3546 s->matched_entry = entry;
3547 break;
3550 s->search_entry = entry;
3551 if (view->searching == TOG_SEARCH_FORWARD)
3552 entry = TAILQ_NEXT(entry, entry);
3553 else
3554 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3557 if (s->matched_entry) {
3558 int cur = s->selected_entry->idx;
3559 while (cur < s->matched_entry->idx) {
3560 err = input_log_view(NULL, view, KEY_DOWN);
3561 if (err)
3562 return err;
3563 cur++;
3565 while (cur > s->matched_entry->idx) {
3566 err = input_log_view(NULL, view, KEY_UP);
3567 if (err)
3568 return err;
3569 cur--;
3573 s->search_entry = NULL;
3575 return NULL;
3578 static const struct got_error *
3579 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3580 struct got_repository *repo, const char *head_ref_name,
3581 const char *in_repo_path, int log_branches)
3583 const struct got_error *err = NULL;
3584 struct tog_log_view_state *s = &view->state.log;
3585 struct got_repository *thread_repo = NULL;
3586 struct got_commit_graph *thread_graph = NULL;
3587 int errcode;
3589 if (in_repo_path != s->in_repo_path) {
3590 free(s->in_repo_path);
3591 s->in_repo_path = strdup(in_repo_path);
3592 if (s->in_repo_path == NULL) {
3593 err = got_error_from_errno("strdup");
3594 goto done;
3598 /* The commit queue only contains commits being displayed. */
3599 TAILQ_INIT(&s->real_commits.head);
3600 s->real_commits.ncommits = 0;
3601 s->commits = &s->real_commits;
3603 TAILQ_INIT(&s->limit_commits.head);
3604 s->limit_view = 0;
3605 s->limit_commits.ncommits = 0;
3607 s->repo = repo;
3608 if (head_ref_name) {
3609 s->head_ref_name = strdup(head_ref_name);
3610 if (s->head_ref_name == NULL) {
3611 err = got_error_from_errno("strdup");
3612 goto done;
3615 s->start_id = got_object_id_dup(start_id);
3616 if (s->start_id == NULL) {
3617 err = got_error_from_errno("got_object_id_dup");
3618 goto done;
3620 s->log_branches = log_branches;
3621 s->use_committer = 1;
3623 STAILQ_INIT(&s->colors);
3624 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3625 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3626 get_color_value("TOG_COLOR_COMMIT"));
3627 if (err)
3628 goto done;
3629 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3630 get_color_value("TOG_COLOR_AUTHOR"));
3631 if (err) {
3632 free_colors(&s->colors);
3633 goto done;
3635 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3636 get_color_value("TOG_COLOR_DATE"));
3637 if (err) {
3638 free_colors(&s->colors);
3639 goto done;
3643 view->show = show_log_view;
3644 view->input = input_log_view;
3645 view->resize = resize_log_view;
3646 view->close = close_log_view;
3647 view->search_start = search_start_log_view;
3648 view->search_next = search_next_log_view;
3650 if (s->thread_args.pack_fds == NULL) {
3651 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3652 if (err)
3653 goto done;
3655 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3656 s->thread_args.pack_fds);
3657 if (err)
3658 goto done;
3659 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3660 !s->log_branches);
3661 if (err)
3662 goto done;
3663 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3664 s->repo, NULL, NULL);
3665 if (err)
3666 goto done;
3668 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3669 if (errcode) {
3670 err = got_error_set_errno(errcode, "pthread_cond_init");
3671 goto done;
3673 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3674 if (errcode) {
3675 err = got_error_set_errno(errcode, "pthread_cond_init");
3676 goto done;
3679 s->thread_args.commits_needed = view->nlines;
3680 s->thread_args.graph = thread_graph;
3681 s->thread_args.real_commits = &s->real_commits;
3682 s->thread_args.limit_commits = &s->limit_commits;
3683 s->thread_args.in_repo_path = s->in_repo_path;
3684 s->thread_args.start_id = s->start_id;
3685 s->thread_args.repo = thread_repo;
3686 s->thread_args.log_complete = 0;
3687 s->thread_args.quit = &s->quit;
3688 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3689 s->thread_args.selected_entry = &s->selected_entry;
3690 s->thread_args.searching = &view->searching;
3691 s->thread_args.search_next_done = &view->search_next_done;
3692 s->thread_args.regex = &view->regex;
3693 s->thread_args.limiting = &s->limit_view;
3694 s->thread_args.limit_regex = &s->limit_regex;
3695 s->thread_args.limit_commits = &s->limit_commits;
3696 done:
3697 if (err) {
3698 if (view->close == NULL)
3699 close_log_view(view);
3700 view_close(view);
3702 return err;
3705 static const struct got_error *
3706 show_log_view(struct tog_view *view)
3708 const struct got_error *err;
3709 struct tog_log_view_state *s = &view->state.log;
3711 if (s->thread == NULL) {
3712 int errcode = pthread_create(&s->thread, NULL, log_thread,
3713 &s->thread_args);
3714 if (errcode)
3715 return got_error_set_errno(errcode, "pthread_create");
3716 if (s->thread_args.commits_needed > 0) {
3717 err = trigger_log_thread(view, 1);
3718 if (err)
3719 return err;
3723 return draw_commits(view);
3726 static void
3727 log_move_cursor_up(struct tog_view *view, int page, int home)
3729 struct tog_log_view_state *s = &view->state.log;
3731 if (s->first_displayed_entry == NULL)
3732 return;
3733 if (s->selected_entry->idx == 0)
3734 view->count = 0;
3736 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3737 || home)
3738 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3740 if (!page && !home && s->selected > 0)
3741 --s->selected;
3742 else
3743 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3745 select_commit(s);
3746 return;
3749 static const struct got_error *
3750 log_move_cursor_down(struct tog_view *view, int page)
3752 struct tog_log_view_state *s = &view->state.log;
3753 const struct got_error *err = NULL;
3754 int eos = view->nlines - 2;
3756 if (s->first_displayed_entry == NULL)
3757 return NULL;
3759 if (s->thread_args.log_complete &&
3760 s->selected_entry->idx >= s->commits->ncommits - 1)
3761 return NULL;
3763 if (view_is_hsplit_top(view))
3764 --eos; /* border consumes the last line */
3766 if (!page) {
3767 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3768 ++s->selected;
3769 else
3770 err = log_scroll_down(view, 1);
3771 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3772 struct commit_queue_entry *entry;
3773 int n;
3775 s->selected = 0;
3776 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3777 s->last_displayed_entry = entry;
3778 for (n = 0; n <= eos; n++) {
3779 if (entry == NULL)
3780 break;
3781 s->first_displayed_entry = entry;
3782 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3784 if (n > 0)
3785 s->selected = n - 1;
3786 } else {
3787 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3788 s->thread_args.log_complete)
3789 s->selected += MIN(page,
3790 s->commits->ncommits - s->selected_entry->idx - 1);
3791 else
3792 err = log_scroll_down(view, page);
3794 if (err)
3795 return err;
3798 * We might necessarily overshoot in horizontal
3799 * splits; if so, select the last displayed commit.
3801 if (s->first_displayed_entry && s->last_displayed_entry) {
3802 s->selected = MIN(s->selected,
3803 s->last_displayed_entry->idx -
3804 s->first_displayed_entry->idx);
3807 select_commit(s);
3809 if (s->thread_args.log_complete &&
3810 s->selected_entry->idx == s->commits->ncommits - 1)
3811 view->count = 0;
3813 return NULL;
3816 static void
3817 view_get_split(struct tog_view *view, int *y, int *x)
3819 *x = 0;
3820 *y = 0;
3822 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3823 if (view->child && view->child->resized_y)
3824 *y = view->child->resized_y;
3825 else if (view->resized_y)
3826 *y = view->resized_y;
3827 else
3828 *y = view_split_begin_y(view->lines);
3829 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3830 if (view->child && view->child->resized_x)
3831 *x = view->child->resized_x;
3832 else if (view->resized_x)
3833 *x = view->resized_x;
3834 else
3835 *x = view_split_begin_x(view->begin_x);
3839 /* Split view horizontally at y and offset view->state->selected line. */
3840 static const struct got_error *
3841 view_init_hsplit(struct tog_view *view, int y)
3843 const struct got_error *err = NULL;
3845 view->nlines = y;
3846 view->ncols = COLS;
3847 err = view_resize(view);
3848 if (err)
3849 return err;
3851 err = offset_selection_down(view);
3853 return err;
3856 static const struct got_error *
3857 log_goto_line(struct tog_view *view, int nlines)
3859 const struct got_error *err = NULL;
3860 struct tog_log_view_state *s = &view->state.log;
3861 int g, idx = s->selected_entry->idx;
3863 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3864 return NULL;
3866 g = view->gline;
3867 view->gline = 0;
3869 if (g >= s->first_displayed_entry->idx + 1 &&
3870 g <= s->last_displayed_entry->idx + 1 &&
3871 g - s->first_displayed_entry->idx - 1 < nlines) {
3872 s->selected = g - s->first_displayed_entry->idx - 1;
3873 select_commit(s);
3874 return NULL;
3877 if (idx + 1 < g) {
3878 err = log_move_cursor_down(view, g - idx - 1);
3879 if (!err && g > s->selected_entry->idx + 1)
3880 err = log_move_cursor_down(view,
3881 g - s->first_displayed_entry->idx - 1);
3882 if (err)
3883 return err;
3884 } else if (idx + 1 > g)
3885 log_move_cursor_up(view, idx - g + 1, 0);
3887 if (g < nlines && s->first_displayed_entry->idx == 0)
3888 s->selected = g - 1;
3890 select_commit(s);
3891 return NULL;
3895 static void
3896 horizontal_scroll_input(struct tog_view *view, int ch)
3899 switch (ch) {
3900 case KEY_LEFT:
3901 case 'h':
3902 view->x -= MIN(view->x, 2);
3903 if (view->x <= 0)
3904 view->count = 0;
3905 break;
3906 case KEY_RIGHT:
3907 case 'l':
3908 if (view->x + view->ncols / 2 < view->maxx)
3909 view->x += 2;
3910 else
3911 view->count = 0;
3912 break;
3913 case '0':
3914 view->x = 0;
3915 break;
3916 case '$':
3917 view->x = MAX(view->maxx - view->ncols / 2, 0);
3918 view->count = 0;
3919 break;
3920 default:
3921 break;
3925 static const struct got_error *
3926 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3928 const struct got_error *err = NULL;
3929 struct tog_log_view_state *s = &view->state.log;
3930 int eos, nscroll;
3932 if (s->thread_args.load_all) {
3933 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3934 s->thread_args.load_all = 0;
3935 else if (s->thread_args.log_complete) {
3936 err = log_move_cursor_down(view, s->commits->ncommits);
3937 s->thread_args.load_all = 0;
3939 if (err)
3940 return err;
3943 eos = nscroll = view->nlines - 1;
3944 if (view_is_hsplit_top(view))
3945 --eos; /* border */
3947 if (view->gline)
3948 return log_goto_line(view, eos);
3950 switch (ch) {
3951 case '&':
3952 err = limit_log_view(view);
3953 break;
3954 case 'q':
3955 s->quit = 1;
3956 break;
3957 case '0':
3958 case '$':
3959 case KEY_RIGHT:
3960 case 'l':
3961 case KEY_LEFT:
3962 case 'h':
3963 horizontal_scroll_input(view, ch);
3964 break;
3965 case 'k':
3966 case KEY_UP:
3967 case '<':
3968 case ',':
3969 case CTRL('p'):
3970 log_move_cursor_up(view, 0, 0);
3971 break;
3972 case 'g':
3973 case '=':
3974 case KEY_HOME:
3975 log_move_cursor_up(view, 0, 1);
3976 view->count = 0;
3977 break;
3978 case CTRL('u'):
3979 case 'u':
3980 nscroll /= 2;
3981 /* FALL THROUGH */
3982 case KEY_PPAGE:
3983 case CTRL('b'):
3984 case 'b':
3985 log_move_cursor_up(view, nscroll, 0);
3986 break;
3987 case 'j':
3988 case KEY_DOWN:
3989 case '>':
3990 case '.':
3991 case CTRL('n'):
3992 err = log_move_cursor_down(view, 0);
3993 break;
3994 case '@':
3995 s->use_committer = !s->use_committer;
3996 view->action = s->use_committer ?
3997 "show committer" : "show commit author";
3998 break;
3999 case 'G':
4000 case '*':
4001 case KEY_END: {
4002 /* We don't know yet how many commits, so we're forced to
4003 * traverse them all. */
4004 view->count = 0;
4005 s->thread_args.load_all = 1;
4006 if (!s->thread_args.log_complete)
4007 return trigger_log_thread(view, 0);
4008 err = log_move_cursor_down(view, s->commits->ncommits);
4009 s->thread_args.load_all = 0;
4010 break;
4012 case CTRL('d'):
4013 case 'd':
4014 nscroll /= 2;
4015 /* FALL THROUGH */
4016 case KEY_NPAGE:
4017 case CTRL('f'):
4018 case 'f':
4019 case ' ':
4020 err = log_move_cursor_down(view, nscroll);
4021 break;
4022 case KEY_RESIZE:
4023 if (s->selected > view->nlines - 2)
4024 s->selected = view->nlines - 2;
4025 if (s->selected > s->commits->ncommits - 1)
4026 s->selected = s->commits->ncommits - 1;
4027 select_commit(s);
4028 if (s->commits->ncommits < view->nlines - 1 &&
4029 !s->thread_args.log_complete) {
4030 s->thread_args.commits_needed += (view->nlines - 1) -
4031 s->commits->ncommits;
4032 err = trigger_log_thread(view, 1);
4034 break;
4035 case KEY_ENTER:
4036 case '\r':
4037 view->count = 0;
4038 if (s->selected_entry == NULL)
4039 break;
4040 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4041 break;
4042 case 'T':
4043 view->count = 0;
4044 if (s->selected_entry == NULL)
4045 break;
4046 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4047 break;
4048 case KEY_BACKSPACE:
4049 case CTRL('l'):
4050 case 'B':
4051 view->count = 0;
4052 if (ch == KEY_BACKSPACE &&
4053 got_path_is_root_dir(s->in_repo_path))
4054 break;
4055 err = stop_log_thread(s);
4056 if (err)
4057 return err;
4058 if (ch == KEY_BACKSPACE) {
4059 char *parent_path;
4060 err = got_path_dirname(&parent_path, s->in_repo_path);
4061 if (err)
4062 return err;
4063 free(s->in_repo_path);
4064 s->in_repo_path = parent_path;
4065 s->thread_args.in_repo_path = s->in_repo_path;
4066 } else if (ch == CTRL('l')) {
4067 struct got_object_id *start_id;
4068 err = got_repo_match_object_id(&start_id, NULL,
4069 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4070 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4071 if (err) {
4072 if (s->head_ref_name == NULL ||
4073 err->code != GOT_ERR_NOT_REF)
4074 return err;
4075 /* Try to cope with deleted references. */
4076 free(s->head_ref_name);
4077 s->head_ref_name = NULL;
4078 err = got_repo_match_object_id(&start_id,
4079 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4080 &tog_refs, s->repo);
4081 if (err)
4082 return err;
4084 free(s->start_id);
4085 s->start_id = start_id;
4086 s->thread_args.start_id = s->start_id;
4087 } else /* 'B' */
4088 s->log_branches = !s->log_branches;
4090 if (s->thread_args.pack_fds == NULL) {
4091 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4092 if (err)
4093 return err;
4095 err = got_repo_open(&s->thread_args.repo,
4096 got_repo_get_path(s->repo), NULL,
4097 s->thread_args.pack_fds);
4098 if (err)
4099 return err;
4100 tog_free_refs();
4101 err = tog_load_refs(s->repo, 0);
4102 if (err)
4103 return err;
4104 err = got_commit_graph_open(&s->thread_args.graph,
4105 s->in_repo_path, !s->log_branches);
4106 if (err)
4107 return err;
4108 err = got_commit_graph_iter_start(s->thread_args.graph,
4109 s->start_id, s->repo, NULL, NULL);
4110 if (err)
4111 return err;
4112 free_commits(&s->real_commits);
4113 free_commits(&s->limit_commits);
4114 s->first_displayed_entry = NULL;
4115 s->last_displayed_entry = NULL;
4116 s->selected_entry = NULL;
4117 s->selected = 0;
4118 s->thread_args.log_complete = 0;
4119 s->quit = 0;
4120 s->thread_args.commits_needed = view->lines;
4121 s->matched_entry = NULL;
4122 s->search_entry = NULL;
4123 view->offset = 0;
4124 break;
4125 case 'R':
4126 view->count = 0;
4127 err = view_request_new(new_view, view, TOG_VIEW_REF);
4128 break;
4129 default:
4130 view->count = 0;
4131 break;
4134 return err;
4137 static const struct got_error *
4138 apply_unveil(const char *repo_path, const char *worktree_path)
4140 const struct got_error *error;
4142 #ifdef PROFILE
4143 if (unveil("gmon.out", "rwc") != 0)
4144 return got_error_from_errno2("unveil", "gmon.out");
4145 #endif
4146 if (repo_path && unveil(repo_path, "r") != 0)
4147 return got_error_from_errno2("unveil", repo_path);
4149 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4150 return got_error_from_errno2("unveil", worktree_path);
4152 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4153 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4155 error = got_privsep_unveil_exec_helpers();
4156 if (error != NULL)
4157 return error;
4159 if (unveil(NULL, NULL) != 0)
4160 return got_error_from_errno("unveil");
4162 return NULL;
4165 static const struct got_error *
4166 init_mock_term(const char *test_script_path)
4168 const struct got_error *err = NULL;
4170 if (test_script_path == NULL || *test_script_path == '\0')
4171 return got_error_msg(GOT_ERR_IO, "GOT_TOG_TEST not defined");
4173 tog_io.f = fopen(test_script_path, "re");
4174 if (tog_io.f == NULL) {
4175 err = got_error_from_errno_fmt("fopen: %s",
4176 test_script_path);
4177 goto done;
4180 /* test mode, we don't want any output */
4181 tog_io.cout = fopen("/dev/null", "w+");
4182 if (tog_io.cout == NULL) {
4183 err = got_error_from_errno("fopen: /dev/null");
4184 goto done;
4187 tog_io.cin = fopen("/dev/tty", "r+");
4188 if (tog_io.cin == NULL) {
4189 err = got_error_from_errno("fopen: /dev/tty");
4190 goto done;
4193 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4194 err = got_error_from_errno("fseeko");
4195 goto done;
4198 /* use local TERM so we test in different environments */
4199 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4200 err = got_error_msg(GOT_ERR_IO,
4201 "newterm: failed to initialise curses");
4203 using_mock_io = 1;
4204 done:
4205 if (err)
4206 tog_io_close();
4207 return err;
4210 static void
4211 init_curses(void)
4214 * Override default signal handlers before starting ncurses.
4215 * This should prevent ncurses from installing its own
4216 * broken cleanup() signal handler.
4218 signal(SIGWINCH, tog_sigwinch);
4219 signal(SIGPIPE, tog_sigpipe);
4220 signal(SIGCONT, tog_sigcont);
4221 signal(SIGINT, tog_sigint);
4222 signal(SIGTERM, tog_sigterm);
4224 if (using_mock_io) /* In test mode we use a fake terminal */
4225 return;
4227 initscr();
4229 cbreak();
4230 halfdelay(1); /* Fast refresh while initial view is loading. */
4231 noecho();
4232 nonl();
4233 intrflush(stdscr, FALSE);
4234 keypad(stdscr, TRUE);
4235 curs_set(0);
4236 if (getenv("TOG_COLORS") != NULL) {
4237 start_color();
4238 use_default_colors();
4241 return;
4244 static const struct got_error *
4245 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4246 struct got_repository *repo, struct got_worktree *worktree)
4248 const struct got_error *err = NULL;
4250 if (argc == 0) {
4251 *in_repo_path = strdup("/");
4252 if (*in_repo_path == NULL)
4253 return got_error_from_errno("strdup");
4254 return NULL;
4257 if (worktree) {
4258 const char *prefix = got_worktree_get_path_prefix(worktree);
4259 char *p;
4261 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4262 if (err)
4263 return err;
4264 if (asprintf(in_repo_path, "%s%s%s", prefix,
4265 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4266 p) == -1) {
4267 err = got_error_from_errno("asprintf");
4268 *in_repo_path = NULL;
4270 free(p);
4271 } else
4272 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4274 return err;
4277 static const struct got_error *
4278 cmd_log(int argc, char *argv[])
4280 const struct got_error *error;
4281 struct got_repository *repo = NULL;
4282 struct got_worktree *worktree = NULL;
4283 struct got_object_id *start_id = NULL;
4284 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4285 char *start_commit = NULL, *label = NULL;
4286 struct got_reference *ref = NULL;
4287 const char *head_ref_name = NULL;
4288 int ch, log_branches = 0;
4289 struct tog_view *view;
4290 int *pack_fds = NULL;
4292 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4293 switch (ch) {
4294 case 'b':
4295 log_branches = 1;
4296 break;
4297 case 'c':
4298 start_commit = optarg;
4299 break;
4300 case 'r':
4301 repo_path = realpath(optarg, NULL);
4302 if (repo_path == NULL)
4303 return got_error_from_errno2("realpath",
4304 optarg);
4305 break;
4306 default:
4307 usage_log();
4308 /* NOTREACHED */
4312 argc -= optind;
4313 argv += optind;
4315 if (argc > 1)
4316 usage_log();
4318 error = got_repo_pack_fds_open(&pack_fds);
4319 if (error != NULL)
4320 goto done;
4322 if (repo_path == NULL) {
4323 cwd = getcwd(NULL, 0);
4324 if (cwd == NULL)
4325 return got_error_from_errno("getcwd");
4326 error = got_worktree_open(&worktree, cwd);
4327 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4328 goto done;
4329 if (worktree)
4330 repo_path =
4331 strdup(got_worktree_get_repo_path(worktree));
4332 else
4333 repo_path = strdup(cwd);
4334 if (repo_path == NULL) {
4335 error = got_error_from_errno("strdup");
4336 goto done;
4340 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4341 if (error != NULL)
4342 goto done;
4344 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4345 repo, worktree);
4346 if (error)
4347 goto done;
4349 init_curses();
4351 error = apply_unveil(got_repo_get_path(repo),
4352 worktree ? got_worktree_get_root_path(worktree) : NULL);
4353 if (error)
4354 goto done;
4356 /* already loaded by tog_log_with_path()? */
4357 if (TAILQ_EMPTY(&tog_refs)) {
4358 error = tog_load_refs(repo, 0);
4359 if (error)
4360 goto done;
4363 if (start_commit == NULL) {
4364 error = got_repo_match_object_id(&start_id, &label,
4365 worktree ? got_worktree_get_head_ref_name(worktree) :
4366 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4367 if (error)
4368 goto done;
4369 head_ref_name = label;
4370 } else {
4371 error = got_ref_open(&ref, repo, start_commit, 0);
4372 if (error == NULL)
4373 head_ref_name = got_ref_get_name(ref);
4374 else if (error->code != GOT_ERR_NOT_REF)
4375 goto done;
4376 error = got_repo_match_object_id(&start_id, NULL,
4377 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4378 if (error)
4379 goto done;
4382 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4383 if (view == NULL) {
4384 error = got_error_from_errno("view_open");
4385 goto done;
4387 error = open_log_view(view, start_id, repo, head_ref_name,
4388 in_repo_path, log_branches);
4389 if (error)
4390 goto done;
4391 if (worktree) {
4392 /* Release work tree lock. */
4393 got_worktree_close(worktree);
4394 worktree = NULL;
4396 error = view_loop(view);
4397 done:
4398 free(in_repo_path);
4399 free(repo_path);
4400 free(cwd);
4401 free(start_id);
4402 free(label);
4403 if (ref)
4404 got_ref_close(ref);
4405 if (repo) {
4406 const struct got_error *close_err = got_repo_close(repo);
4407 if (error == NULL)
4408 error = close_err;
4410 if (worktree)
4411 got_worktree_close(worktree);
4412 if (pack_fds) {
4413 const struct got_error *pack_err =
4414 got_repo_pack_fds_close(pack_fds);
4415 if (error == NULL)
4416 error = pack_err;
4418 tog_free_refs();
4419 return error;
4422 __dead static void
4423 usage_diff(void)
4425 endwin();
4426 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4427 "object1 object2\n", getprogname());
4428 exit(1);
4431 static int
4432 match_line(const char *line, regex_t *regex, size_t nmatch,
4433 regmatch_t *regmatch)
4435 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4438 static struct tog_color *
4439 match_color(struct tog_colors *colors, const char *line)
4441 struct tog_color *tc = NULL;
4443 STAILQ_FOREACH(tc, colors, entry) {
4444 if (match_line(line, &tc->regex, 0, NULL))
4445 return tc;
4448 return NULL;
4451 static const struct got_error *
4452 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4453 WINDOW *window, int skipcol, regmatch_t *regmatch)
4455 const struct got_error *err = NULL;
4456 char *exstr = NULL;
4457 wchar_t *wline = NULL;
4458 int rme, rms, n, width, scrollx;
4459 int width0 = 0, width1 = 0, width2 = 0;
4460 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4462 *wtotal = 0;
4464 rms = regmatch->rm_so;
4465 rme = regmatch->rm_eo;
4467 err = expand_tab(&exstr, line);
4468 if (err)
4469 return err;
4471 /* Split the line into 3 segments, according to match offsets. */
4472 seg0 = strndup(exstr, rms);
4473 if (seg0 == NULL) {
4474 err = got_error_from_errno("strndup");
4475 goto done;
4477 seg1 = strndup(exstr + rms, rme - rms);
4478 if (seg1 == NULL) {
4479 err = got_error_from_errno("strndup");
4480 goto done;
4482 seg2 = strdup(exstr + rme);
4483 if (seg2 == NULL) {
4484 err = got_error_from_errno("strndup");
4485 goto done;
4488 /* draw up to matched token if we haven't scrolled past it */
4489 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4490 col_tab_align, 1);
4491 if (err)
4492 goto done;
4493 n = MAX(width0 - skipcol, 0);
4494 if (n) {
4495 free(wline);
4496 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4497 wlimit, col_tab_align, 1);
4498 if (err)
4499 goto done;
4500 waddwstr(window, &wline[scrollx]);
4501 wlimit -= width;
4502 *wtotal += width;
4505 if (wlimit > 0) {
4506 int i = 0, w = 0;
4507 size_t wlen;
4509 free(wline);
4510 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4511 col_tab_align, 1);
4512 if (err)
4513 goto done;
4514 wlen = wcslen(wline);
4515 while (i < wlen) {
4516 width = wcwidth(wline[i]);
4517 if (width == -1) {
4518 /* should not happen, tabs are expanded */
4519 err = got_error(GOT_ERR_RANGE);
4520 goto done;
4522 if (width0 + w + width > skipcol)
4523 break;
4524 w += width;
4525 i++;
4527 /* draw (visible part of) matched token (if scrolled into it) */
4528 if (width1 - w > 0) {
4529 wattron(window, A_STANDOUT);
4530 waddwstr(window, &wline[i]);
4531 wattroff(window, A_STANDOUT);
4532 wlimit -= (width1 - w);
4533 *wtotal += (width1 - w);
4537 if (wlimit > 0) { /* draw rest of line */
4538 free(wline);
4539 if (skipcol > width0 + width1) {
4540 err = format_line(&wline, &width2, &scrollx, seg2,
4541 skipcol - (width0 + width1), wlimit,
4542 col_tab_align, 1);
4543 if (err)
4544 goto done;
4545 waddwstr(window, &wline[scrollx]);
4546 } else {
4547 err = format_line(&wline, &width2, NULL, seg2, 0,
4548 wlimit, col_tab_align, 1);
4549 if (err)
4550 goto done;
4551 waddwstr(window, wline);
4553 *wtotal += width2;
4555 done:
4556 free(wline);
4557 free(exstr);
4558 free(seg0);
4559 free(seg1);
4560 free(seg2);
4561 return err;
4564 static int
4565 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4567 FILE *f = NULL;
4568 int *eof, *first, *selected;
4570 if (view->type == TOG_VIEW_DIFF) {
4571 struct tog_diff_view_state *s = &view->state.diff;
4573 first = &s->first_displayed_line;
4574 selected = first;
4575 eof = &s->eof;
4576 f = s->f;
4577 } else if (view->type == TOG_VIEW_HELP) {
4578 struct tog_help_view_state *s = &view->state.help;
4580 first = &s->first_displayed_line;
4581 selected = first;
4582 eof = &s->eof;
4583 f = s->f;
4584 } else if (view->type == TOG_VIEW_BLAME) {
4585 struct tog_blame_view_state *s = &view->state.blame;
4587 first = &s->first_displayed_line;
4588 selected = &s->selected_line;
4589 eof = &s->eof;
4590 f = s->blame.f;
4591 } else
4592 return 0;
4594 /* Center gline in the middle of the page like vi(1). */
4595 if (*lineno < view->gline - (view->nlines - 3) / 2)
4596 return 0;
4597 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4598 rewind(f);
4599 *eof = 0;
4600 *first = 1;
4601 *lineno = 0;
4602 *nprinted = 0;
4603 return 0;
4606 *selected = view->gline <= (view->nlines - 3) / 2 ?
4607 view->gline : (view->nlines - 3) / 2 + 1;
4608 view->gline = 0;
4610 return 1;
4613 static const struct got_error *
4614 draw_file(struct tog_view *view, const char *header)
4616 struct tog_diff_view_state *s = &view->state.diff;
4617 regmatch_t *regmatch = &view->regmatch;
4618 const struct got_error *err;
4619 int nprinted = 0;
4620 char *line;
4621 size_t linesize = 0;
4622 ssize_t linelen;
4623 wchar_t *wline;
4624 int width;
4625 int max_lines = view->nlines;
4626 int nlines = s->nlines;
4627 off_t line_offset;
4629 s->lineno = s->first_displayed_line - 1;
4630 line_offset = s->lines[s->first_displayed_line - 1].offset;
4631 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4632 return got_error_from_errno("fseek");
4634 werase(view->window);
4636 if (view->gline > s->nlines - 1)
4637 view->gline = s->nlines - 1;
4639 if (header) {
4640 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4641 1 : view->gline - (view->nlines - 3) / 2 :
4642 s->lineno + s->selected_line;
4644 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4645 return got_error_from_errno("asprintf");
4646 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4647 0, 0);
4648 free(line);
4649 if (err)
4650 return err;
4652 if (view_needs_focus_indication(view))
4653 wstandout(view->window);
4654 waddwstr(view->window, wline);
4655 free(wline);
4656 wline = NULL;
4657 while (width++ < view->ncols)
4658 waddch(view->window, ' ');
4659 if (view_needs_focus_indication(view))
4660 wstandend(view->window);
4662 if (max_lines <= 1)
4663 return NULL;
4664 max_lines--;
4667 s->eof = 0;
4668 view->maxx = 0;
4669 line = NULL;
4670 while (max_lines > 0 && nprinted < max_lines) {
4671 enum got_diff_line_type linetype;
4672 attr_t attr = 0;
4674 linelen = getline(&line, &linesize, s->f);
4675 if (linelen == -1) {
4676 if (feof(s->f)) {
4677 s->eof = 1;
4678 break;
4680 free(line);
4681 return got_ferror(s->f, GOT_ERR_IO);
4684 if (++s->lineno < s->first_displayed_line)
4685 continue;
4686 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4687 continue;
4688 if (s->lineno == view->hiline)
4689 attr = A_STANDOUT;
4691 /* Set view->maxx based on full line length. */
4692 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4693 view->x ? 1 : 0);
4694 if (err) {
4695 free(line);
4696 return err;
4698 view->maxx = MAX(view->maxx, width);
4699 free(wline);
4700 wline = NULL;
4702 linetype = s->lines[s->lineno].type;
4703 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4704 linetype < GOT_DIFF_LINE_CONTEXT)
4705 attr |= COLOR_PAIR(linetype);
4706 if (attr)
4707 wattron(view->window, attr);
4708 if (s->first_displayed_line + nprinted == s->matched_line &&
4709 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4710 err = add_matched_line(&width, line, view->ncols, 0,
4711 view->window, view->x, regmatch);
4712 if (err) {
4713 free(line);
4714 return err;
4716 } else {
4717 int skip;
4718 err = format_line(&wline, &width, &skip, line,
4719 view->x, view->ncols, 0, view->x ? 1 : 0);
4720 if (err) {
4721 free(line);
4722 return err;
4724 waddwstr(view->window, &wline[skip]);
4725 free(wline);
4726 wline = NULL;
4728 if (s->lineno == view->hiline) {
4729 /* highlight full gline length */
4730 while (width++ < view->ncols)
4731 waddch(view->window, ' ');
4732 } else {
4733 if (width <= view->ncols - 1)
4734 waddch(view->window, '\n');
4736 if (attr)
4737 wattroff(view->window, attr);
4738 if (++nprinted == 1)
4739 s->first_displayed_line = s->lineno;
4741 free(line);
4742 if (nprinted >= 1)
4743 s->last_displayed_line = s->first_displayed_line +
4744 (nprinted - 1);
4745 else
4746 s->last_displayed_line = s->first_displayed_line;
4748 view_border(view);
4750 if (s->eof) {
4751 while (nprinted < view->nlines) {
4752 waddch(view->window, '\n');
4753 nprinted++;
4756 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4757 view->ncols, 0, 0);
4758 if (err) {
4759 return err;
4762 wstandout(view->window);
4763 waddwstr(view->window, wline);
4764 free(wline);
4765 wline = NULL;
4766 wstandend(view->window);
4769 return NULL;
4772 static char *
4773 get_datestr(time_t *time, char *datebuf)
4775 struct tm mytm, *tm;
4776 char *p, *s;
4778 tm = gmtime_r(time, &mytm);
4779 if (tm == NULL)
4780 return NULL;
4781 s = asctime_r(tm, datebuf);
4782 if (s == NULL)
4783 return NULL;
4784 p = strchr(s, '\n');
4785 if (p)
4786 *p = '\0';
4787 return s;
4790 static const struct got_error *
4791 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4792 off_t off, uint8_t type)
4794 struct got_diff_line *p;
4796 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4797 if (p == NULL)
4798 return got_error_from_errno("reallocarray");
4799 *lines = p;
4800 (*lines)[*nlines].offset = off;
4801 (*lines)[*nlines].type = type;
4802 (*nlines)++;
4804 return NULL;
4807 static const struct got_error *
4808 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4809 struct got_diff_line *s_lines, size_t s_nlines)
4811 struct got_diff_line *p;
4812 char buf[BUFSIZ];
4813 size_t i, r;
4815 if (fseeko(src, 0L, SEEK_SET) == -1)
4816 return got_error_from_errno("fseeko");
4818 for (;;) {
4819 r = fread(buf, 1, sizeof(buf), src);
4820 if (r == 0) {
4821 if (ferror(src))
4822 return got_error_from_errno("fread");
4823 if (feof(src))
4824 break;
4826 if (fwrite(buf, 1, r, dst) != r)
4827 return got_ferror(dst, GOT_ERR_IO);
4830 if (s_nlines == 0 && *d_nlines == 0)
4831 return NULL;
4834 * If commit info was in dst, increment line offsets
4835 * of the appended diff content, but skip s_lines[0]
4836 * because offset zero is already in *d_lines.
4838 if (*d_nlines > 0) {
4839 for (i = 1; i < s_nlines; ++i)
4840 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4842 if (s_nlines > 0) {
4843 --s_nlines;
4844 ++s_lines;
4848 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4849 if (p == NULL) {
4850 /* d_lines is freed in close_diff_view() */
4851 return got_error_from_errno("reallocarray");
4854 *d_lines = p;
4856 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4857 *d_nlines += s_nlines;
4859 return NULL;
4862 static const struct got_error *
4863 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4864 struct got_object_id *commit_id, struct got_reflist_head *refs,
4865 struct got_repository *repo, int ignore_ws, int force_text_diff,
4866 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4868 const struct got_error *err = NULL;
4869 char datebuf[26], *datestr;
4870 struct got_commit_object *commit;
4871 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4872 time_t committer_time;
4873 const char *author, *committer;
4874 char *refs_str = NULL;
4875 struct got_pathlist_entry *pe;
4876 off_t outoff = 0;
4877 int n;
4879 if (refs) {
4880 err = build_refs_str(&refs_str, refs, commit_id, repo);
4881 if (err)
4882 return err;
4885 err = got_object_open_as_commit(&commit, repo, commit_id);
4886 if (err)
4887 return err;
4889 err = got_object_id_str(&id_str, commit_id);
4890 if (err) {
4891 err = got_error_from_errno("got_object_id_str");
4892 goto done;
4895 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4896 if (err)
4897 goto done;
4899 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4900 refs_str ? refs_str : "", refs_str ? ")" : "");
4901 if (n < 0) {
4902 err = got_error_from_errno("fprintf");
4903 goto done;
4905 outoff += n;
4906 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4907 if (err)
4908 goto done;
4910 n = fprintf(outfile, "from: %s\n",
4911 got_object_commit_get_author(commit));
4912 if (n < 0) {
4913 err = got_error_from_errno("fprintf");
4914 goto done;
4916 outoff += n;
4917 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4918 if (err)
4919 goto done;
4921 author = got_object_commit_get_author(commit);
4922 committer = got_object_commit_get_committer(commit);
4923 if (strcmp(author, committer) != 0) {
4924 n = fprintf(outfile, "via: %s\n", committer);
4925 if (n < 0) {
4926 err = got_error_from_errno("fprintf");
4927 goto done;
4929 outoff += n;
4930 err = add_line_metadata(lines, nlines, outoff,
4931 GOT_DIFF_LINE_AUTHOR);
4932 if (err)
4933 goto done;
4935 committer_time = got_object_commit_get_committer_time(commit);
4936 datestr = get_datestr(&committer_time, datebuf);
4937 if (datestr) {
4938 n = fprintf(outfile, "date: %s UTC\n", datestr);
4939 if (n < 0) {
4940 err = got_error_from_errno("fprintf");
4941 goto done;
4943 outoff += n;
4944 err = add_line_metadata(lines, nlines, outoff,
4945 GOT_DIFF_LINE_DATE);
4946 if (err)
4947 goto done;
4949 if (got_object_commit_get_nparents(commit) > 1) {
4950 const struct got_object_id_queue *parent_ids;
4951 struct got_object_qid *qid;
4952 int pn = 1;
4953 parent_ids = got_object_commit_get_parent_ids(commit);
4954 STAILQ_FOREACH(qid, parent_ids, entry) {
4955 err = got_object_id_str(&id_str, &qid->id);
4956 if (err)
4957 goto done;
4958 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4959 if (n < 0) {
4960 err = got_error_from_errno("fprintf");
4961 goto done;
4963 outoff += n;
4964 err = add_line_metadata(lines, nlines, outoff,
4965 GOT_DIFF_LINE_META);
4966 if (err)
4967 goto done;
4968 free(id_str);
4969 id_str = NULL;
4973 err = got_object_commit_get_logmsg(&logmsg, commit);
4974 if (err)
4975 goto done;
4976 s = logmsg;
4977 while ((line = strsep(&s, "\n")) != NULL) {
4978 n = fprintf(outfile, "%s\n", line);
4979 if (n < 0) {
4980 err = got_error_from_errno("fprintf");
4981 goto done;
4983 outoff += n;
4984 err = add_line_metadata(lines, nlines, outoff,
4985 GOT_DIFF_LINE_LOGMSG);
4986 if (err)
4987 goto done;
4990 TAILQ_FOREACH(pe, dsa->paths, entry) {
4991 struct got_diff_changed_path *cp = pe->data;
4992 int pad = dsa->max_path_len - pe->path_len + 1;
4994 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4995 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4996 dsa->rm_cols + 1, cp->rm);
4997 if (n < 0) {
4998 err = got_error_from_errno("fprintf");
4999 goto done;
5001 outoff += n;
5002 err = add_line_metadata(lines, nlines, outoff,
5003 GOT_DIFF_LINE_CHANGES);
5004 if (err)
5005 goto done;
5008 fputc('\n', outfile);
5009 outoff++;
5010 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5011 if (err)
5012 goto done;
5014 n = fprintf(outfile,
5015 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5016 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5017 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5018 if (n < 0) {
5019 err = got_error_from_errno("fprintf");
5020 goto done;
5022 outoff += n;
5023 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5024 if (err)
5025 goto done;
5027 fputc('\n', outfile);
5028 outoff++;
5029 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5030 done:
5031 free(id_str);
5032 free(logmsg);
5033 free(refs_str);
5034 got_object_commit_close(commit);
5035 if (err) {
5036 free(*lines);
5037 *lines = NULL;
5038 *nlines = 0;
5040 return err;
5043 static const struct got_error *
5044 create_diff(struct tog_diff_view_state *s)
5046 const struct got_error *err = NULL;
5047 FILE *f = NULL, *tmp_diff_file = NULL;
5048 int obj_type;
5049 struct got_diff_line *lines = NULL;
5050 struct got_pathlist_head changed_paths;
5052 TAILQ_INIT(&changed_paths);
5054 free(s->lines);
5055 s->lines = malloc(sizeof(*s->lines));
5056 if (s->lines == NULL)
5057 return got_error_from_errno("malloc");
5058 s->nlines = 0;
5060 f = got_opentemp();
5061 if (f == NULL) {
5062 err = got_error_from_errno("got_opentemp");
5063 goto done;
5065 tmp_diff_file = got_opentemp();
5066 if (tmp_diff_file == NULL) {
5067 err = got_error_from_errno("got_opentemp");
5068 goto done;
5070 if (s->f && fclose(s->f) == EOF) {
5071 err = got_error_from_errno("fclose");
5072 goto done;
5074 s->f = f;
5076 if (s->id1)
5077 err = got_object_get_type(&obj_type, s->repo, s->id1);
5078 else
5079 err = got_object_get_type(&obj_type, s->repo, s->id2);
5080 if (err)
5081 goto done;
5083 switch (obj_type) {
5084 case GOT_OBJ_TYPE_BLOB:
5085 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5086 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5087 s->label1, s->label2, tog_diff_algo, s->diff_context,
5088 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5089 s->f);
5090 break;
5091 case GOT_OBJ_TYPE_TREE:
5092 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5093 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5094 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5095 s->force_text_diff, NULL, s->repo, s->f);
5096 break;
5097 case GOT_OBJ_TYPE_COMMIT: {
5098 const struct got_object_id_queue *parent_ids;
5099 struct got_object_qid *pid;
5100 struct got_commit_object *commit2;
5101 struct got_reflist_head *refs;
5102 size_t nlines = 0;
5103 struct got_diffstat_cb_arg dsa = {
5104 0, 0, 0, 0, 0, 0,
5105 &changed_paths,
5106 s->ignore_whitespace,
5107 s->force_text_diff,
5108 tog_diff_algo
5111 lines = malloc(sizeof(*lines));
5112 if (lines == NULL) {
5113 err = got_error_from_errno("malloc");
5114 goto done;
5117 /* build diff first in tmp file then append to commit info */
5118 err = got_diff_objects_as_commits(&lines, &nlines,
5119 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5120 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5121 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5122 if (err)
5123 break;
5125 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5126 if (err)
5127 goto done;
5128 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5129 /* Show commit info if we're diffing to a parent/root commit. */
5130 if (s->id1 == NULL) {
5131 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5132 refs, s->repo, s->ignore_whitespace,
5133 s->force_text_diff, &dsa, s->f);
5134 if (err)
5135 goto done;
5136 } else {
5137 parent_ids = got_object_commit_get_parent_ids(commit2);
5138 STAILQ_FOREACH(pid, parent_ids, entry) {
5139 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5140 err = write_commit_info(&s->lines,
5141 &s->nlines, s->id2, refs, s->repo,
5142 s->ignore_whitespace,
5143 s->force_text_diff, &dsa, s->f);
5144 if (err)
5145 goto done;
5146 break;
5150 got_object_commit_close(commit2);
5152 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5153 lines, nlines);
5154 break;
5156 default:
5157 err = got_error(GOT_ERR_OBJ_TYPE);
5158 break;
5160 done:
5161 free(lines);
5162 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5163 if (s->f && fflush(s->f) != 0 && err == NULL)
5164 err = got_error_from_errno("fflush");
5165 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5166 err = got_error_from_errno("fclose");
5167 return err;
5170 static void
5171 diff_view_indicate_progress(struct tog_view *view)
5173 mvwaddstr(view->window, 0, 0, "diffing...");
5174 update_panels();
5175 doupdate();
5178 static const struct got_error *
5179 search_start_diff_view(struct tog_view *view)
5181 struct tog_diff_view_state *s = &view->state.diff;
5183 s->matched_line = 0;
5184 return NULL;
5187 static void
5188 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5189 size_t *nlines, int **first, int **last, int **match, int **selected)
5191 struct tog_diff_view_state *s = &view->state.diff;
5193 *f = s->f;
5194 *nlines = s->nlines;
5195 *line_offsets = NULL;
5196 *match = &s->matched_line;
5197 *first = &s->first_displayed_line;
5198 *last = &s->last_displayed_line;
5199 *selected = &s->selected_line;
5202 static const struct got_error *
5203 search_next_view_match(struct tog_view *view)
5205 const struct got_error *err = NULL;
5206 FILE *f;
5207 int lineno;
5208 char *line = NULL;
5209 size_t linesize = 0;
5210 ssize_t linelen;
5211 off_t *line_offsets;
5212 size_t nlines = 0;
5213 int *first, *last, *match, *selected;
5215 if (!view->search_setup)
5216 return got_error_msg(GOT_ERR_NOT_IMPL,
5217 "view search not supported");
5218 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5219 &match, &selected);
5221 if (!view->searching) {
5222 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5223 return NULL;
5226 if (*match) {
5227 if (view->searching == TOG_SEARCH_FORWARD)
5228 lineno = *first + 1;
5229 else
5230 lineno = *first - 1;
5231 } else
5232 lineno = *first - 1 + *selected;
5234 while (1) {
5235 off_t offset;
5237 if (lineno <= 0 || lineno > nlines) {
5238 if (*match == 0) {
5239 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5240 break;
5243 if (view->searching == TOG_SEARCH_FORWARD)
5244 lineno = 1;
5245 else
5246 lineno = nlines;
5249 offset = view->type == TOG_VIEW_DIFF ?
5250 view->state.diff.lines[lineno - 1].offset :
5251 line_offsets[lineno - 1];
5252 if (fseeko(f, offset, SEEK_SET) != 0) {
5253 free(line);
5254 return got_error_from_errno("fseeko");
5256 linelen = getline(&line, &linesize, f);
5257 if (linelen != -1) {
5258 char *exstr;
5259 err = expand_tab(&exstr, line);
5260 if (err)
5261 break;
5262 if (match_line(exstr, &view->regex, 1,
5263 &view->regmatch)) {
5264 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5265 *match = lineno;
5266 free(exstr);
5267 break;
5269 free(exstr);
5271 if (view->searching == TOG_SEARCH_FORWARD)
5272 lineno++;
5273 else
5274 lineno--;
5276 free(line);
5278 if (*match) {
5279 *first = *match;
5280 *selected = 1;
5283 return err;
5286 static const struct got_error *
5287 close_diff_view(struct tog_view *view)
5289 const struct got_error *err = NULL;
5290 struct tog_diff_view_state *s = &view->state.diff;
5292 free(s->id1);
5293 s->id1 = NULL;
5294 free(s->id2);
5295 s->id2 = NULL;
5296 if (s->f && fclose(s->f) == EOF)
5297 err = got_error_from_errno("fclose");
5298 s->f = NULL;
5299 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5300 err = got_error_from_errno("fclose");
5301 s->f1 = NULL;
5302 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5303 err = got_error_from_errno("fclose");
5304 s->f2 = NULL;
5305 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5306 err = got_error_from_errno("close");
5307 s->fd1 = -1;
5308 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5309 err = got_error_from_errno("close");
5310 s->fd2 = -1;
5311 free(s->lines);
5312 s->lines = NULL;
5313 s->nlines = 0;
5314 return err;
5317 static const struct got_error *
5318 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5319 struct got_object_id *id2, const char *label1, const char *label2,
5320 int diff_context, int ignore_whitespace, int force_text_diff,
5321 struct tog_view *parent_view, struct got_repository *repo)
5323 const struct got_error *err;
5324 struct tog_diff_view_state *s = &view->state.diff;
5326 memset(s, 0, sizeof(*s));
5327 s->fd1 = -1;
5328 s->fd2 = -1;
5330 if (id1 != NULL && id2 != NULL) {
5331 int type1, type2;
5333 err = got_object_get_type(&type1, repo, id1);
5334 if (err)
5335 goto done;
5336 err = got_object_get_type(&type2, repo, id2);
5337 if (err)
5338 goto done;
5340 if (type1 != type2) {
5341 err = got_error(GOT_ERR_OBJ_TYPE);
5342 goto done;
5345 s->first_displayed_line = 1;
5346 s->last_displayed_line = view->nlines;
5347 s->selected_line = 1;
5348 s->repo = repo;
5349 s->id1 = id1;
5350 s->id2 = id2;
5351 s->label1 = label1;
5352 s->label2 = label2;
5354 if (id1) {
5355 s->id1 = got_object_id_dup(id1);
5356 if (s->id1 == NULL) {
5357 err = got_error_from_errno("got_object_id_dup");
5358 goto done;
5360 } else
5361 s->id1 = NULL;
5363 s->id2 = got_object_id_dup(id2);
5364 if (s->id2 == NULL) {
5365 err = got_error_from_errno("got_object_id_dup");
5366 goto done;
5369 s->f1 = got_opentemp();
5370 if (s->f1 == NULL) {
5371 err = got_error_from_errno("got_opentemp");
5372 goto done;
5375 s->f2 = got_opentemp();
5376 if (s->f2 == NULL) {
5377 err = got_error_from_errno("got_opentemp");
5378 goto done;
5381 s->fd1 = got_opentempfd();
5382 if (s->fd1 == -1) {
5383 err = got_error_from_errno("got_opentempfd");
5384 goto done;
5387 s->fd2 = got_opentempfd();
5388 if (s->fd2 == -1) {
5389 err = got_error_from_errno("got_opentempfd");
5390 goto done;
5393 s->diff_context = diff_context;
5394 s->ignore_whitespace = ignore_whitespace;
5395 s->force_text_diff = force_text_diff;
5396 s->parent_view = parent_view;
5397 s->repo = repo;
5399 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5400 int rc;
5402 rc = init_pair(GOT_DIFF_LINE_MINUS,
5403 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5404 if (rc != ERR)
5405 rc = init_pair(GOT_DIFF_LINE_PLUS,
5406 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5407 if (rc != ERR)
5408 rc = init_pair(GOT_DIFF_LINE_HUNK,
5409 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5410 if (rc != ERR)
5411 rc = init_pair(GOT_DIFF_LINE_META,
5412 get_color_value("TOG_COLOR_DIFF_META"), -1);
5413 if (rc != ERR)
5414 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5415 get_color_value("TOG_COLOR_DIFF_META"), -1);
5416 if (rc != ERR)
5417 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5418 get_color_value("TOG_COLOR_DIFF_META"), -1);
5419 if (rc != ERR)
5420 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5421 get_color_value("TOG_COLOR_DIFF_META"), -1);
5422 if (rc != ERR)
5423 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5424 get_color_value("TOG_COLOR_AUTHOR"), -1);
5425 if (rc != ERR)
5426 rc = init_pair(GOT_DIFF_LINE_DATE,
5427 get_color_value("TOG_COLOR_DATE"), -1);
5428 if (rc == ERR) {
5429 err = got_error(GOT_ERR_RANGE);
5430 goto done;
5434 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5435 view_is_splitscreen(view))
5436 show_log_view(parent_view); /* draw border */
5437 diff_view_indicate_progress(view);
5439 err = create_diff(s);
5441 view->show = show_diff_view;
5442 view->input = input_diff_view;
5443 view->reset = reset_diff_view;
5444 view->close = close_diff_view;
5445 view->search_start = search_start_diff_view;
5446 view->search_setup = search_setup_diff_view;
5447 view->search_next = search_next_view_match;
5448 done:
5449 if (err) {
5450 if (view->close == NULL)
5451 close_diff_view(view);
5452 view_close(view);
5454 return err;
5457 static const struct got_error *
5458 show_diff_view(struct tog_view *view)
5460 const struct got_error *err;
5461 struct tog_diff_view_state *s = &view->state.diff;
5462 char *id_str1 = NULL, *id_str2, *header;
5463 const char *label1, *label2;
5465 if (s->id1) {
5466 err = got_object_id_str(&id_str1, s->id1);
5467 if (err)
5468 return err;
5469 label1 = s->label1 ? s->label1 : id_str1;
5470 } else
5471 label1 = "/dev/null";
5473 err = got_object_id_str(&id_str2, s->id2);
5474 if (err)
5475 return err;
5476 label2 = s->label2 ? s->label2 : id_str2;
5478 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5479 err = got_error_from_errno("asprintf");
5480 free(id_str1);
5481 free(id_str2);
5482 return err;
5484 free(id_str1);
5485 free(id_str2);
5487 err = draw_file(view, header);
5488 free(header);
5489 return err;
5492 static const struct got_error *
5493 set_selected_commit(struct tog_diff_view_state *s,
5494 struct commit_queue_entry *entry)
5496 const struct got_error *err;
5497 const struct got_object_id_queue *parent_ids;
5498 struct got_commit_object *selected_commit;
5499 struct got_object_qid *pid;
5501 free(s->id2);
5502 s->id2 = got_object_id_dup(entry->id);
5503 if (s->id2 == NULL)
5504 return got_error_from_errno("got_object_id_dup");
5506 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5507 if (err)
5508 return err;
5509 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5510 free(s->id1);
5511 pid = STAILQ_FIRST(parent_ids);
5512 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5513 got_object_commit_close(selected_commit);
5514 return NULL;
5517 static const struct got_error *
5518 reset_diff_view(struct tog_view *view)
5520 struct tog_diff_view_state *s = &view->state.diff;
5522 view->count = 0;
5523 wclear(view->window);
5524 s->first_displayed_line = 1;
5525 s->last_displayed_line = view->nlines;
5526 s->matched_line = 0;
5527 diff_view_indicate_progress(view);
5528 return create_diff(s);
5531 static void
5532 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5534 int start, i;
5536 i = start = s->first_displayed_line - 1;
5538 while (s->lines[i].type != type) {
5539 if (i == 0)
5540 i = s->nlines - 1;
5541 if (--i == start)
5542 return; /* do nothing, requested type not in file */
5545 s->selected_line = 1;
5546 s->first_displayed_line = i;
5549 static void
5550 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5552 int start, i;
5554 i = start = s->first_displayed_line + 1;
5556 while (s->lines[i].type != type) {
5557 if (i == s->nlines - 1)
5558 i = 0;
5559 if (++i == start)
5560 return; /* do nothing, requested type not in file */
5563 s->selected_line = 1;
5564 s->first_displayed_line = i;
5567 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5568 int, int, int);
5569 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5570 int, int);
5572 static const struct got_error *
5573 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5575 const struct got_error *err = NULL;
5576 struct tog_diff_view_state *s = &view->state.diff;
5577 struct tog_log_view_state *ls;
5578 struct commit_queue_entry *old_selected_entry;
5579 char *line = NULL;
5580 size_t linesize = 0;
5581 ssize_t linelen;
5582 int i, nscroll = view->nlines - 1, up = 0;
5584 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5586 switch (ch) {
5587 case '0':
5588 case '$':
5589 case KEY_RIGHT:
5590 case 'l':
5591 case KEY_LEFT:
5592 case 'h':
5593 horizontal_scroll_input(view, ch);
5594 break;
5595 case 'a':
5596 case 'w':
5597 if (ch == 'a') {
5598 s->force_text_diff = !s->force_text_diff;
5599 view->action = s->force_text_diff ?
5600 "force ASCII text enabled" :
5601 "force ASCII text disabled";
5603 else if (ch == 'w') {
5604 s->ignore_whitespace = !s->ignore_whitespace;
5605 view->action = s->ignore_whitespace ?
5606 "ignore whitespace enabled" :
5607 "ignore whitespace disabled";
5609 err = reset_diff_view(view);
5610 break;
5611 case 'g':
5612 case KEY_HOME:
5613 s->first_displayed_line = 1;
5614 view->count = 0;
5615 break;
5616 case 'G':
5617 case KEY_END:
5618 view->count = 0;
5619 if (s->eof)
5620 break;
5622 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5623 s->eof = 1;
5624 break;
5625 case 'k':
5626 case KEY_UP:
5627 case CTRL('p'):
5628 if (s->first_displayed_line > 1)
5629 s->first_displayed_line--;
5630 else
5631 view->count = 0;
5632 break;
5633 case CTRL('u'):
5634 case 'u':
5635 nscroll /= 2;
5636 /* FALL THROUGH */
5637 case KEY_PPAGE:
5638 case CTRL('b'):
5639 case 'b':
5640 if (s->first_displayed_line == 1) {
5641 view->count = 0;
5642 break;
5644 i = 0;
5645 while (i++ < nscroll && s->first_displayed_line > 1)
5646 s->first_displayed_line--;
5647 break;
5648 case 'j':
5649 case KEY_DOWN:
5650 case CTRL('n'):
5651 if (!s->eof)
5652 s->first_displayed_line++;
5653 else
5654 view->count = 0;
5655 break;
5656 case CTRL('d'):
5657 case 'd':
5658 nscroll /= 2;
5659 /* FALL THROUGH */
5660 case KEY_NPAGE:
5661 case CTRL('f'):
5662 case 'f':
5663 case ' ':
5664 if (s->eof) {
5665 view->count = 0;
5666 break;
5668 i = 0;
5669 while (!s->eof && i++ < nscroll) {
5670 linelen = getline(&line, &linesize, s->f);
5671 s->first_displayed_line++;
5672 if (linelen == -1) {
5673 if (feof(s->f)) {
5674 s->eof = 1;
5675 } else
5676 err = got_ferror(s->f, GOT_ERR_IO);
5677 break;
5680 free(line);
5681 break;
5682 case '(':
5683 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5684 break;
5685 case ')':
5686 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5687 break;
5688 case '{':
5689 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5690 break;
5691 case '}':
5692 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5693 break;
5694 case '[':
5695 if (s->diff_context > 0) {
5696 s->diff_context--;
5697 s->matched_line = 0;
5698 diff_view_indicate_progress(view);
5699 err = create_diff(s);
5700 if (s->first_displayed_line + view->nlines - 1 >
5701 s->nlines) {
5702 s->first_displayed_line = 1;
5703 s->last_displayed_line = view->nlines;
5705 } else
5706 view->count = 0;
5707 break;
5708 case ']':
5709 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5710 s->diff_context++;
5711 s->matched_line = 0;
5712 diff_view_indicate_progress(view);
5713 err = create_diff(s);
5714 } else
5715 view->count = 0;
5716 break;
5717 case '<':
5718 case ',':
5719 case 'K':
5720 up = 1;
5721 /* FALL THROUGH */
5722 case '>':
5723 case '.':
5724 case 'J':
5725 if (s->parent_view == NULL) {
5726 view->count = 0;
5727 break;
5729 s->parent_view->count = view->count;
5731 if (s->parent_view->type == TOG_VIEW_LOG) {
5732 ls = &s->parent_view->state.log;
5733 old_selected_entry = ls->selected_entry;
5735 err = input_log_view(NULL, s->parent_view,
5736 up ? KEY_UP : KEY_DOWN);
5737 if (err)
5738 break;
5739 view->count = s->parent_view->count;
5741 if (old_selected_entry == ls->selected_entry)
5742 break;
5744 err = set_selected_commit(s, ls->selected_entry);
5745 if (err)
5746 break;
5747 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5748 struct tog_blame_view_state *bs;
5749 struct got_object_id *id, *prev_id;
5751 bs = &s->parent_view->state.blame;
5752 prev_id = get_annotation_for_line(bs->blame.lines,
5753 bs->blame.nlines, bs->last_diffed_line);
5755 err = input_blame_view(&view, s->parent_view,
5756 up ? KEY_UP : KEY_DOWN);
5757 if (err)
5758 break;
5759 view->count = s->parent_view->count;
5761 if (prev_id == NULL)
5762 break;
5763 id = get_selected_commit_id(bs->blame.lines,
5764 bs->blame.nlines, bs->first_displayed_line,
5765 bs->selected_line);
5766 if (id == NULL)
5767 break;
5769 if (!got_object_id_cmp(prev_id, id))
5770 break;
5772 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5773 if (err)
5774 break;
5776 s->first_displayed_line = 1;
5777 s->last_displayed_line = view->nlines;
5778 s->matched_line = 0;
5779 view->x = 0;
5781 diff_view_indicate_progress(view);
5782 err = create_diff(s);
5783 break;
5784 default:
5785 view->count = 0;
5786 break;
5789 return err;
5792 static const struct got_error *
5793 cmd_diff(int argc, char *argv[])
5795 const struct got_error *error;
5796 struct got_repository *repo = NULL;
5797 struct got_worktree *worktree = NULL;
5798 struct got_object_id *id1 = NULL, *id2 = NULL;
5799 char *repo_path = NULL, *cwd = NULL;
5800 char *id_str1 = NULL, *id_str2 = NULL;
5801 char *label1 = NULL, *label2 = NULL;
5802 int diff_context = 3, ignore_whitespace = 0;
5803 int ch, force_text_diff = 0;
5804 const char *errstr;
5805 struct tog_view *view;
5806 int *pack_fds = NULL;
5808 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5809 switch (ch) {
5810 case 'a':
5811 force_text_diff = 1;
5812 break;
5813 case 'C':
5814 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5815 &errstr);
5816 if (errstr != NULL)
5817 errx(1, "number of context lines is %s: %s",
5818 errstr, errstr);
5819 break;
5820 case 'r':
5821 repo_path = realpath(optarg, NULL);
5822 if (repo_path == NULL)
5823 return got_error_from_errno2("realpath",
5824 optarg);
5825 got_path_strip_trailing_slashes(repo_path);
5826 break;
5827 case 'w':
5828 ignore_whitespace = 1;
5829 break;
5830 default:
5831 usage_diff();
5832 /* NOTREACHED */
5836 argc -= optind;
5837 argv += optind;
5839 if (argc == 0) {
5840 usage_diff(); /* TODO show local worktree changes */
5841 } else if (argc == 2) {
5842 id_str1 = argv[0];
5843 id_str2 = argv[1];
5844 } else
5845 usage_diff();
5847 error = got_repo_pack_fds_open(&pack_fds);
5848 if (error)
5849 goto done;
5851 if (repo_path == NULL) {
5852 cwd = getcwd(NULL, 0);
5853 if (cwd == NULL)
5854 return got_error_from_errno("getcwd");
5855 error = got_worktree_open(&worktree, cwd);
5856 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5857 goto done;
5858 if (worktree)
5859 repo_path =
5860 strdup(got_worktree_get_repo_path(worktree));
5861 else
5862 repo_path = strdup(cwd);
5863 if (repo_path == NULL) {
5864 error = got_error_from_errno("strdup");
5865 goto done;
5869 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5870 if (error)
5871 goto done;
5873 init_curses();
5875 error = apply_unveil(got_repo_get_path(repo), NULL);
5876 if (error)
5877 goto done;
5879 error = tog_load_refs(repo, 0);
5880 if (error)
5881 goto done;
5883 error = got_repo_match_object_id(&id1, &label1, id_str1,
5884 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5885 if (error)
5886 goto done;
5888 error = got_repo_match_object_id(&id2, &label2, id_str2,
5889 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5890 if (error)
5891 goto done;
5893 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5894 if (view == NULL) {
5895 error = got_error_from_errno("view_open");
5896 goto done;
5898 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5899 ignore_whitespace, force_text_diff, NULL, repo);
5900 if (error)
5901 goto done;
5902 error = view_loop(view);
5903 done:
5904 free(label1);
5905 free(label2);
5906 free(repo_path);
5907 free(cwd);
5908 if (repo) {
5909 const struct got_error *close_err = got_repo_close(repo);
5910 if (error == NULL)
5911 error = close_err;
5913 if (worktree)
5914 got_worktree_close(worktree);
5915 if (pack_fds) {
5916 const struct got_error *pack_err =
5917 got_repo_pack_fds_close(pack_fds);
5918 if (error == NULL)
5919 error = pack_err;
5921 tog_free_refs();
5922 return error;
5925 __dead static void
5926 usage_blame(void)
5928 endwin();
5929 fprintf(stderr,
5930 "usage: %s blame [-c commit] [-r repository-path] path\n",
5931 getprogname());
5932 exit(1);
5935 struct tog_blame_line {
5936 int annotated;
5937 struct got_object_id *id;
5940 static const struct got_error *
5941 draw_blame(struct tog_view *view)
5943 struct tog_blame_view_state *s = &view->state.blame;
5944 struct tog_blame *blame = &s->blame;
5945 regmatch_t *regmatch = &view->regmatch;
5946 const struct got_error *err;
5947 int lineno = 0, nprinted = 0;
5948 char *line = NULL;
5949 size_t linesize = 0;
5950 ssize_t linelen;
5951 wchar_t *wline;
5952 int width;
5953 struct tog_blame_line *blame_line;
5954 struct got_object_id *prev_id = NULL;
5955 char *id_str;
5956 struct tog_color *tc;
5958 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5959 if (err)
5960 return err;
5962 rewind(blame->f);
5963 werase(view->window);
5965 if (asprintf(&line, "commit %s", id_str) == -1) {
5966 err = got_error_from_errno("asprintf");
5967 free(id_str);
5968 return err;
5971 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5972 free(line);
5973 line = NULL;
5974 if (err)
5975 return err;
5976 if (view_needs_focus_indication(view))
5977 wstandout(view->window);
5978 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5979 if (tc)
5980 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5981 waddwstr(view->window, wline);
5982 while (width++ < view->ncols)
5983 waddch(view->window, ' ');
5984 if (tc)
5985 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5986 if (view_needs_focus_indication(view))
5987 wstandend(view->window);
5988 free(wline);
5989 wline = NULL;
5991 if (view->gline > blame->nlines)
5992 view->gline = blame->nlines;
5994 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5995 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5996 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5997 free(id_str);
5998 return got_error_from_errno("asprintf");
6000 free(id_str);
6001 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6002 free(line);
6003 line = NULL;
6004 if (err)
6005 return err;
6006 waddwstr(view->window, wline);
6007 free(wline);
6008 wline = NULL;
6009 if (width < view->ncols - 1)
6010 waddch(view->window, '\n');
6012 s->eof = 0;
6013 view->maxx = 0;
6014 while (nprinted < view->nlines - 2) {
6015 linelen = getline(&line, &linesize, blame->f);
6016 if (linelen == -1) {
6017 if (feof(blame->f)) {
6018 s->eof = 1;
6019 break;
6021 free(line);
6022 return got_ferror(blame->f, GOT_ERR_IO);
6024 if (++lineno < s->first_displayed_line)
6025 continue;
6026 if (view->gline && !gotoline(view, &lineno, &nprinted))
6027 continue;
6029 /* Set view->maxx based on full line length. */
6030 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6031 if (err) {
6032 free(line);
6033 return err;
6035 free(wline);
6036 wline = NULL;
6037 view->maxx = MAX(view->maxx, width);
6039 if (nprinted == s->selected_line - 1)
6040 wstandout(view->window);
6042 if (blame->nlines > 0) {
6043 blame_line = &blame->lines[lineno - 1];
6044 if (blame_line->annotated && prev_id &&
6045 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6046 !(nprinted == s->selected_line - 1)) {
6047 waddstr(view->window, " ");
6048 } else if (blame_line->annotated) {
6049 char *id_str;
6050 err = got_object_id_str(&id_str,
6051 blame_line->id);
6052 if (err) {
6053 free(line);
6054 return err;
6056 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6057 if (tc)
6058 wattr_on(view->window,
6059 COLOR_PAIR(tc->colorpair), NULL);
6060 wprintw(view->window, "%.8s", id_str);
6061 if (tc)
6062 wattr_off(view->window,
6063 COLOR_PAIR(tc->colorpair), NULL);
6064 free(id_str);
6065 prev_id = blame_line->id;
6066 } else {
6067 waddstr(view->window, "........");
6068 prev_id = NULL;
6070 } else {
6071 waddstr(view->window, "........");
6072 prev_id = NULL;
6075 if (nprinted == s->selected_line - 1)
6076 wstandend(view->window);
6077 waddstr(view->window, " ");
6079 if (view->ncols <= 9) {
6080 width = 9;
6081 } else if (s->first_displayed_line + nprinted ==
6082 s->matched_line &&
6083 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6084 err = add_matched_line(&width, line, view->ncols - 9, 9,
6085 view->window, view->x, regmatch);
6086 if (err) {
6087 free(line);
6088 return err;
6090 width += 9;
6091 } else {
6092 int skip;
6093 err = format_line(&wline, &width, &skip, line,
6094 view->x, view->ncols - 9, 9, 1);
6095 if (err) {
6096 free(line);
6097 return err;
6099 waddwstr(view->window, &wline[skip]);
6100 width += 9;
6101 free(wline);
6102 wline = NULL;
6105 if (width <= view->ncols - 1)
6106 waddch(view->window, '\n');
6107 if (++nprinted == 1)
6108 s->first_displayed_line = lineno;
6110 free(line);
6111 s->last_displayed_line = lineno;
6113 view_border(view);
6115 return NULL;
6118 static const struct got_error *
6119 blame_cb(void *arg, int nlines, int lineno,
6120 struct got_commit_object *commit, struct got_object_id *id)
6122 const struct got_error *err = NULL;
6123 struct tog_blame_cb_args *a = arg;
6124 struct tog_blame_line *line;
6125 int errcode;
6127 if (nlines != a->nlines ||
6128 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6129 return got_error(GOT_ERR_RANGE);
6131 errcode = pthread_mutex_lock(&tog_mutex);
6132 if (errcode)
6133 return got_error_set_errno(errcode, "pthread_mutex_lock");
6135 if (*a->quit) { /* user has quit the blame view */
6136 err = got_error(GOT_ERR_ITER_COMPLETED);
6137 goto done;
6140 if (lineno == -1)
6141 goto done; /* no change in this commit */
6143 line = &a->lines[lineno - 1];
6144 if (line->annotated)
6145 goto done;
6147 line->id = got_object_id_dup(id);
6148 if (line->id == NULL) {
6149 err = got_error_from_errno("got_object_id_dup");
6150 goto done;
6152 line->annotated = 1;
6153 done:
6154 errcode = pthread_mutex_unlock(&tog_mutex);
6155 if (errcode)
6156 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6157 return err;
6160 static void *
6161 blame_thread(void *arg)
6163 const struct got_error *err, *close_err;
6164 struct tog_blame_thread_args *ta = arg;
6165 struct tog_blame_cb_args *a = ta->cb_args;
6166 int errcode, fd1 = -1, fd2 = -1;
6167 FILE *f1 = NULL, *f2 = NULL;
6169 fd1 = got_opentempfd();
6170 if (fd1 == -1)
6171 return (void *)got_error_from_errno("got_opentempfd");
6173 fd2 = got_opentempfd();
6174 if (fd2 == -1) {
6175 err = got_error_from_errno("got_opentempfd");
6176 goto done;
6179 f1 = got_opentemp();
6180 if (f1 == NULL) {
6181 err = (void *)got_error_from_errno("got_opentemp");
6182 goto done;
6184 f2 = got_opentemp();
6185 if (f2 == NULL) {
6186 err = (void *)got_error_from_errno("got_opentemp");
6187 goto done;
6190 err = block_signals_used_by_main_thread();
6191 if (err)
6192 goto done;
6194 err = got_blame(ta->path, a->commit_id, ta->repo,
6195 tog_diff_algo, blame_cb, ta->cb_args,
6196 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6197 if (err && err->code == GOT_ERR_CANCELLED)
6198 err = NULL;
6200 errcode = pthread_mutex_lock(&tog_mutex);
6201 if (errcode) {
6202 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6203 goto done;
6206 close_err = got_repo_close(ta->repo);
6207 if (err == NULL)
6208 err = close_err;
6209 ta->repo = NULL;
6210 *ta->complete = 1;
6212 errcode = pthread_mutex_unlock(&tog_mutex);
6213 if (errcode && err == NULL)
6214 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6216 done:
6217 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6218 err = got_error_from_errno("close");
6219 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6220 err = got_error_from_errno("close");
6221 if (f1 && fclose(f1) == EOF && err == NULL)
6222 err = got_error_from_errno("fclose");
6223 if (f2 && fclose(f2) == EOF && err == NULL)
6224 err = got_error_from_errno("fclose");
6226 return (void *)err;
6229 static struct got_object_id *
6230 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6231 int first_displayed_line, int selected_line)
6233 struct tog_blame_line *line;
6235 if (nlines <= 0)
6236 return NULL;
6238 line = &lines[first_displayed_line - 1 + selected_line - 1];
6239 if (!line->annotated)
6240 return NULL;
6242 return line->id;
6245 static struct got_object_id *
6246 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6247 int lineno)
6249 struct tog_blame_line *line;
6251 if (nlines <= 0 || lineno >= nlines)
6252 return NULL;
6254 line = &lines[lineno - 1];
6255 if (!line->annotated)
6256 return NULL;
6258 return line->id;
6261 static const struct got_error *
6262 stop_blame(struct tog_blame *blame)
6264 const struct got_error *err = NULL;
6265 int i;
6267 if (blame->thread) {
6268 int errcode;
6269 errcode = pthread_mutex_unlock(&tog_mutex);
6270 if (errcode)
6271 return got_error_set_errno(errcode,
6272 "pthread_mutex_unlock");
6273 errcode = pthread_join(blame->thread, (void **)&err);
6274 if (errcode)
6275 return got_error_set_errno(errcode, "pthread_join");
6276 errcode = pthread_mutex_lock(&tog_mutex);
6277 if (errcode)
6278 return got_error_set_errno(errcode,
6279 "pthread_mutex_lock");
6280 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6281 err = NULL;
6282 blame->thread = NULL;
6284 if (blame->thread_args.repo) {
6285 const struct got_error *close_err;
6286 close_err = got_repo_close(blame->thread_args.repo);
6287 if (err == NULL)
6288 err = close_err;
6289 blame->thread_args.repo = NULL;
6291 if (blame->f) {
6292 if (fclose(blame->f) == EOF && err == NULL)
6293 err = got_error_from_errno("fclose");
6294 blame->f = NULL;
6296 if (blame->lines) {
6297 for (i = 0; i < blame->nlines; i++)
6298 free(blame->lines[i].id);
6299 free(blame->lines);
6300 blame->lines = NULL;
6302 free(blame->cb_args.commit_id);
6303 blame->cb_args.commit_id = NULL;
6304 if (blame->pack_fds) {
6305 const struct got_error *pack_err =
6306 got_repo_pack_fds_close(blame->pack_fds);
6307 if (err == NULL)
6308 err = pack_err;
6309 blame->pack_fds = NULL;
6311 return err;
6314 static const struct got_error *
6315 cancel_blame_view(void *arg)
6317 const struct got_error *err = NULL;
6318 int *done = arg;
6319 int errcode;
6321 errcode = pthread_mutex_lock(&tog_mutex);
6322 if (errcode)
6323 return got_error_set_errno(errcode,
6324 "pthread_mutex_unlock");
6326 if (*done)
6327 err = got_error(GOT_ERR_CANCELLED);
6329 errcode = pthread_mutex_unlock(&tog_mutex);
6330 if (errcode)
6331 return got_error_set_errno(errcode,
6332 "pthread_mutex_lock");
6334 return err;
6337 static const struct got_error *
6338 run_blame(struct tog_view *view)
6340 struct tog_blame_view_state *s = &view->state.blame;
6341 struct tog_blame *blame = &s->blame;
6342 const struct got_error *err = NULL;
6343 struct got_commit_object *commit = NULL;
6344 struct got_blob_object *blob = NULL;
6345 struct got_repository *thread_repo = NULL;
6346 struct got_object_id *obj_id = NULL;
6347 int obj_type, fd = -1;
6348 int *pack_fds = NULL;
6350 err = got_object_open_as_commit(&commit, s->repo,
6351 &s->blamed_commit->id);
6352 if (err)
6353 return err;
6355 fd = got_opentempfd();
6356 if (fd == -1) {
6357 err = got_error_from_errno("got_opentempfd");
6358 goto done;
6361 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6362 if (err)
6363 goto done;
6365 err = got_object_get_type(&obj_type, s->repo, obj_id);
6366 if (err)
6367 goto done;
6369 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6370 err = got_error(GOT_ERR_OBJ_TYPE);
6371 goto done;
6374 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6375 if (err)
6376 goto done;
6377 blame->f = got_opentemp();
6378 if (blame->f == NULL) {
6379 err = got_error_from_errno("got_opentemp");
6380 goto done;
6382 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6383 &blame->line_offsets, blame->f, blob);
6384 if (err)
6385 goto done;
6386 if (blame->nlines == 0) {
6387 s->blame_complete = 1;
6388 goto done;
6391 /* Don't include \n at EOF in the blame line count. */
6392 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6393 blame->nlines--;
6395 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6396 if (blame->lines == NULL) {
6397 err = got_error_from_errno("calloc");
6398 goto done;
6401 err = got_repo_pack_fds_open(&pack_fds);
6402 if (err)
6403 goto done;
6404 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6405 pack_fds);
6406 if (err)
6407 goto done;
6409 blame->pack_fds = pack_fds;
6410 blame->cb_args.view = view;
6411 blame->cb_args.lines = blame->lines;
6412 blame->cb_args.nlines = blame->nlines;
6413 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6414 if (blame->cb_args.commit_id == NULL) {
6415 err = got_error_from_errno("got_object_id_dup");
6416 goto done;
6418 blame->cb_args.quit = &s->done;
6420 blame->thread_args.path = s->path;
6421 blame->thread_args.repo = thread_repo;
6422 blame->thread_args.cb_args = &blame->cb_args;
6423 blame->thread_args.complete = &s->blame_complete;
6424 blame->thread_args.cancel_cb = cancel_blame_view;
6425 blame->thread_args.cancel_arg = &s->done;
6426 s->blame_complete = 0;
6428 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6429 s->first_displayed_line = 1;
6430 s->last_displayed_line = view->nlines;
6431 s->selected_line = 1;
6433 s->matched_line = 0;
6435 done:
6436 if (commit)
6437 got_object_commit_close(commit);
6438 if (fd != -1 && close(fd) == -1 && err == NULL)
6439 err = got_error_from_errno("close");
6440 if (blob)
6441 got_object_blob_close(blob);
6442 free(obj_id);
6443 if (err)
6444 stop_blame(blame);
6445 return err;
6448 static const struct got_error *
6449 open_blame_view(struct tog_view *view, char *path,
6450 struct got_object_id *commit_id, struct got_repository *repo)
6452 const struct got_error *err = NULL;
6453 struct tog_blame_view_state *s = &view->state.blame;
6455 STAILQ_INIT(&s->blamed_commits);
6457 s->path = strdup(path);
6458 if (s->path == NULL)
6459 return got_error_from_errno("strdup");
6461 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6462 if (err) {
6463 free(s->path);
6464 return err;
6467 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6468 s->first_displayed_line = 1;
6469 s->last_displayed_line = view->nlines;
6470 s->selected_line = 1;
6471 s->blame_complete = 0;
6472 s->repo = repo;
6473 s->commit_id = commit_id;
6474 memset(&s->blame, 0, sizeof(s->blame));
6476 STAILQ_INIT(&s->colors);
6477 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6478 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6479 get_color_value("TOG_COLOR_COMMIT"));
6480 if (err)
6481 return err;
6484 view->show = show_blame_view;
6485 view->input = input_blame_view;
6486 view->reset = reset_blame_view;
6487 view->close = close_blame_view;
6488 view->search_start = search_start_blame_view;
6489 view->search_setup = search_setup_blame_view;
6490 view->search_next = search_next_view_match;
6492 return run_blame(view);
6495 static const struct got_error *
6496 close_blame_view(struct tog_view *view)
6498 const struct got_error *err = NULL;
6499 struct tog_blame_view_state *s = &view->state.blame;
6501 if (s->blame.thread)
6502 err = stop_blame(&s->blame);
6504 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6505 struct got_object_qid *blamed_commit;
6506 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6507 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6508 got_object_qid_free(blamed_commit);
6511 free(s->path);
6512 free_colors(&s->colors);
6513 return err;
6516 static const struct got_error *
6517 search_start_blame_view(struct tog_view *view)
6519 struct tog_blame_view_state *s = &view->state.blame;
6521 s->matched_line = 0;
6522 return NULL;
6525 static void
6526 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6527 size_t *nlines, int **first, int **last, int **match, int **selected)
6529 struct tog_blame_view_state *s = &view->state.blame;
6531 *f = s->blame.f;
6532 *nlines = s->blame.nlines;
6533 *line_offsets = s->blame.line_offsets;
6534 *match = &s->matched_line;
6535 *first = &s->first_displayed_line;
6536 *last = &s->last_displayed_line;
6537 *selected = &s->selected_line;
6540 static const struct got_error *
6541 show_blame_view(struct tog_view *view)
6543 const struct got_error *err = NULL;
6544 struct tog_blame_view_state *s = &view->state.blame;
6545 int errcode;
6547 if (s->blame.thread == NULL && !s->blame_complete) {
6548 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6549 &s->blame.thread_args);
6550 if (errcode)
6551 return got_error_set_errno(errcode, "pthread_create");
6553 if (!using_mock_io)
6554 halfdelay(1); /* fast refresh while annotating */
6557 if (s->blame_complete && !using_mock_io)
6558 halfdelay(10); /* disable fast refresh */
6560 err = draw_blame(view);
6562 view_border(view);
6563 return err;
6566 static const struct got_error *
6567 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6568 struct got_repository *repo, struct got_object_id *id)
6570 struct tog_view *log_view;
6571 const struct got_error *err = NULL;
6573 *new_view = NULL;
6575 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6576 if (log_view == NULL)
6577 return got_error_from_errno("view_open");
6579 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6580 if (err)
6581 view_close(log_view);
6582 else
6583 *new_view = log_view;
6585 return err;
6588 static const struct got_error *
6589 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6591 const struct got_error *err = NULL, *thread_err = NULL;
6592 struct tog_view *diff_view;
6593 struct tog_blame_view_state *s = &view->state.blame;
6594 int eos, nscroll, begin_y = 0, begin_x = 0;
6596 eos = nscroll = view->nlines - 2;
6597 if (view_is_hsplit_top(view))
6598 --eos; /* border */
6600 switch (ch) {
6601 case '0':
6602 case '$':
6603 case KEY_RIGHT:
6604 case 'l':
6605 case KEY_LEFT:
6606 case 'h':
6607 horizontal_scroll_input(view, ch);
6608 break;
6609 case 'q':
6610 s->done = 1;
6611 break;
6612 case 'g':
6613 case KEY_HOME:
6614 s->selected_line = 1;
6615 s->first_displayed_line = 1;
6616 view->count = 0;
6617 break;
6618 case 'G':
6619 case KEY_END:
6620 if (s->blame.nlines < eos) {
6621 s->selected_line = s->blame.nlines;
6622 s->first_displayed_line = 1;
6623 } else {
6624 s->selected_line = eos;
6625 s->first_displayed_line = s->blame.nlines - (eos - 1);
6627 view->count = 0;
6628 break;
6629 case 'k':
6630 case KEY_UP:
6631 case CTRL('p'):
6632 if (s->selected_line > 1)
6633 s->selected_line--;
6634 else if (s->selected_line == 1 &&
6635 s->first_displayed_line > 1)
6636 s->first_displayed_line--;
6637 else
6638 view->count = 0;
6639 break;
6640 case CTRL('u'):
6641 case 'u':
6642 nscroll /= 2;
6643 /* FALL THROUGH */
6644 case KEY_PPAGE:
6645 case CTRL('b'):
6646 case 'b':
6647 if (s->first_displayed_line == 1) {
6648 if (view->count > 1)
6649 nscroll += nscroll;
6650 s->selected_line = MAX(1, s->selected_line - nscroll);
6651 view->count = 0;
6652 break;
6654 if (s->first_displayed_line > nscroll)
6655 s->first_displayed_line -= nscroll;
6656 else
6657 s->first_displayed_line = 1;
6658 break;
6659 case 'j':
6660 case KEY_DOWN:
6661 case CTRL('n'):
6662 if (s->selected_line < eos && s->first_displayed_line +
6663 s->selected_line <= s->blame.nlines)
6664 s->selected_line++;
6665 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6666 s->first_displayed_line++;
6667 else
6668 view->count = 0;
6669 break;
6670 case 'c':
6671 case 'p': {
6672 struct got_object_id *id = NULL;
6674 view->count = 0;
6675 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6676 s->first_displayed_line, s->selected_line);
6677 if (id == NULL)
6678 break;
6679 if (ch == 'p') {
6680 struct got_commit_object *commit, *pcommit;
6681 struct got_object_qid *pid;
6682 struct got_object_id *blob_id = NULL;
6683 int obj_type;
6684 err = got_object_open_as_commit(&commit,
6685 s->repo, id);
6686 if (err)
6687 break;
6688 pid = STAILQ_FIRST(
6689 got_object_commit_get_parent_ids(commit));
6690 if (pid == NULL) {
6691 got_object_commit_close(commit);
6692 break;
6694 /* Check if path history ends here. */
6695 err = got_object_open_as_commit(&pcommit,
6696 s->repo, &pid->id);
6697 if (err)
6698 break;
6699 err = got_object_id_by_path(&blob_id, s->repo,
6700 pcommit, s->path);
6701 got_object_commit_close(pcommit);
6702 if (err) {
6703 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6704 err = NULL;
6705 got_object_commit_close(commit);
6706 break;
6708 err = got_object_get_type(&obj_type, s->repo,
6709 blob_id);
6710 free(blob_id);
6711 /* Can't blame non-blob type objects. */
6712 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6713 got_object_commit_close(commit);
6714 break;
6716 err = got_object_qid_alloc(&s->blamed_commit,
6717 &pid->id);
6718 got_object_commit_close(commit);
6719 } else {
6720 if (got_object_id_cmp(id,
6721 &s->blamed_commit->id) == 0)
6722 break;
6723 err = got_object_qid_alloc(&s->blamed_commit,
6724 id);
6726 if (err)
6727 break;
6728 s->done = 1;
6729 thread_err = stop_blame(&s->blame);
6730 s->done = 0;
6731 if (thread_err)
6732 break;
6733 STAILQ_INSERT_HEAD(&s->blamed_commits,
6734 s->blamed_commit, entry);
6735 err = run_blame(view);
6736 if (err)
6737 break;
6738 break;
6740 case 'C': {
6741 struct got_object_qid *first;
6743 view->count = 0;
6744 first = STAILQ_FIRST(&s->blamed_commits);
6745 if (!got_object_id_cmp(&first->id, s->commit_id))
6746 break;
6747 s->done = 1;
6748 thread_err = stop_blame(&s->blame);
6749 s->done = 0;
6750 if (thread_err)
6751 break;
6752 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6753 got_object_qid_free(s->blamed_commit);
6754 s->blamed_commit =
6755 STAILQ_FIRST(&s->blamed_commits);
6756 err = run_blame(view);
6757 if (err)
6758 break;
6759 break;
6761 case 'L':
6762 view->count = 0;
6763 s->id_to_log = get_selected_commit_id(s->blame.lines,
6764 s->blame.nlines, s->first_displayed_line, s->selected_line);
6765 if (s->id_to_log)
6766 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6767 break;
6768 case KEY_ENTER:
6769 case '\r': {
6770 struct got_object_id *id = NULL;
6771 struct got_object_qid *pid;
6772 struct got_commit_object *commit = NULL;
6774 view->count = 0;
6775 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6776 s->first_displayed_line, s->selected_line);
6777 if (id == NULL)
6778 break;
6779 err = got_object_open_as_commit(&commit, s->repo, id);
6780 if (err)
6781 break;
6782 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6783 if (*new_view) {
6784 /* traversed from diff view, release diff resources */
6785 err = close_diff_view(*new_view);
6786 if (err)
6787 break;
6788 diff_view = *new_view;
6789 } else {
6790 if (view_is_parent_view(view))
6791 view_get_split(view, &begin_y, &begin_x);
6793 diff_view = view_open(0, 0, begin_y, begin_x,
6794 TOG_VIEW_DIFF);
6795 if (diff_view == NULL) {
6796 got_object_commit_close(commit);
6797 err = got_error_from_errno("view_open");
6798 break;
6801 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6802 id, NULL, NULL, 3, 0, 0, view, s->repo);
6803 got_object_commit_close(commit);
6804 if (err) {
6805 view_close(diff_view);
6806 break;
6808 s->last_diffed_line = s->first_displayed_line - 1 +
6809 s->selected_line;
6810 if (*new_view)
6811 break; /* still open from active diff view */
6812 if (view_is_parent_view(view) &&
6813 view->mode == TOG_VIEW_SPLIT_HRZN) {
6814 err = view_init_hsplit(view, begin_y);
6815 if (err)
6816 break;
6819 view->focussed = 0;
6820 diff_view->focussed = 1;
6821 diff_view->mode = view->mode;
6822 diff_view->nlines = view->lines - begin_y;
6823 if (view_is_parent_view(view)) {
6824 view_transfer_size(diff_view, view);
6825 err = view_close_child(view);
6826 if (err)
6827 break;
6828 err = view_set_child(view, diff_view);
6829 if (err)
6830 break;
6831 view->focus_child = 1;
6832 } else
6833 *new_view = diff_view;
6834 if (err)
6835 break;
6836 break;
6838 case CTRL('d'):
6839 case 'd':
6840 nscroll /= 2;
6841 /* FALL THROUGH */
6842 case KEY_NPAGE:
6843 case CTRL('f'):
6844 case 'f':
6845 case ' ':
6846 if (s->last_displayed_line >= s->blame.nlines &&
6847 s->selected_line >= MIN(s->blame.nlines,
6848 view->nlines - 2)) {
6849 view->count = 0;
6850 break;
6852 if (s->last_displayed_line >= s->blame.nlines &&
6853 s->selected_line < view->nlines - 2) {
6854 s->selected_line +=
6855 MIN(nscroll, s->last_displayed_line -
6856 s->first_displayed_line - s->selected_line + 1);
6858 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6859 s->first_displayed_line += nscroll;
6860 else
6861 s->first_displayed_line =
6862 s->blame.nlines - (view->nlines - 3);
6863 break;
6864 case KEY_RESIZE:
6865 if (s->selected_line > view->nlines - 2) {
6866 s->selected_line = MIN(s->blame.nlines,
6867 view->nlines - 2);
6869 break;
6870 default:
6871 view->count = 0;
6872 break;
6874 return thread_err ? thread_err : err;
6877 static const struct got_error *
6878 reset_blame_view(struct tog_view *view)
6880 const struct got_error *err;
6881 struct tog_blame_view_state *s = &view->state.blame;
6883 view->count = 0;
6884 s->done = 1;
6885 err = stop_blame(&s->blame);
6886 s->done = 0;
6887 if (err)
6888 return err;
6889 return run_blame(view);
6892 static const struct got_error *
6893 cmd_blame(int argc, char *argv[])
6895 const struct got_error *error;
6896 struct got_repository *repo = NULL;
6897 struct got_worktree *worktree = NULL;
6898 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6899 char *link_target = NULL;
6900 struct got_object_id *commit_id = NULL;
6901 struct got_commit_object *commit = NULL;
6902 char *commit_id_str = NULL;
6903 int ch;
6904 struct tog_view *view = NULL;
6905 int *pack_fds = NULL;
6907 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6908 switch (ch) {
6909 case 'c':
6910 commit_id_str = optarg;
6911 break;
6912 case 'r':
6913 repo_path = realpath(optarg, NULL);
6914 if (repo_path == NULL)
6915 return got_error_from_errno2("realpath",
6916 optarg);
6917 break;
6918 default:
6919 usage_blame();
6920 /* NOTREACHED */
6924 argc -= optind;
6925 argv += optind;
6927 if (argc != 1)
6928 usage_blame();
6930 error = got_repo_pack_fds_open(&pack_fds);
6931 if (error != NULL)
6932 goto done;
6934 if (repo_path == NULL) {
6935 cwd = getcwd(NULL, 0);
6936 if (cwd == NULL)
6937 return got_error_from_errno("getcwd");
6938 error = got_worktree_open(&worktree, cwd);
6939 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6940 goto done;
6941 if (worktree)
6942 repo_path =
6943 strdup(got_worktree_get_repo_path(worktree));
6944 else
6945 repo_path = strdup(cwd);
6946 if (repo_path == NULL) {
6947 error = got_error_from_errno("strdup");
6948 goto done;
6952 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6953 if (error != NULL)
6954 goto done;
6956 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6957 worktree);
6958 if (error)
6959 goto done;
6961 init_curses();
6963 error = apply_unveil(got_repo_get_path(repo), NULL);
6964 if (error)
6965 goto done;
6967 error = tog_load_refs(repo, 0);
6968 if (error)
6969 goto done;
6971 if (commit_id_str == NULL) {
6972 struct got_reference *head_ref;
6973 error = got_ref_open(&head_ref, repo, worktree ?
6974 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6975 if (error != NULL)
6976 goto done;
6977 error = got_ref_resolve(&commit_id, repo, head_ref);
6978 got_ref_close(head_ref);
6979 } else {
6980 error = got_repo_match_object_id(&commit_id, NULL,
6981 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6983 if (error != NULL)
6984 goto done;
6986 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6987 if (view == NULL) {
6988 error = got_error_from_errno("view_open");
6989 goto done;
6992 error = got_object_open_as_commit(&commit, repo, commit_id);
6993 if (error)
6994 goto done;
6996 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6997 commit, repo);
6998 if (error)
6999 goto done;
7001 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7002 commit_id, repo);
7003 if (error)
7004 goto done;
7005 if (worktree) {
7006 /* Release work tree lock. */
7007 got_worktree_close(worktree);
7008 worktree = NULL;
7010 error = view_loop(view);
7011 done:
7012 free(repo_path);
7013 free(in_repo_path);
7014 free(link_target);
7015 free(cwd);
7016 free(commit_id);
7017 if (error != NULL && view != NULL) {
7018 if (view->close == NULL)
7019 close_blame_view(view);
7020 view_close(view);
7022 if (commit)
7023 got_object_commit_close(commit);
7024 if (worktree)
7025 got_worktree_close(worktree);
7026 if (repo) {
7027 const struct got_error *close_err = got_repo_close(repo);
7028 if (error == NULL)
7029 error = close_err;
7031 if (pack_fds) {
7032 const struct got_error *pack_err =
7033 got_repo_pack_fds_close(pack_fds);
7034 if (error == NULL)
7035 error = pack_err;
7037 tog_free_refs();
7038 return error;
7041 static const struct got_error *
7042 draw_tree_entries(struct tog_view *view, const char *parent_path)
7044 struct tog_tree_view_state *s = &view->state.tree;
7045 const struct got_error *err = NULL;
7046 struct got_tree_entry *te;
7047 wchar_t *wline;
7048 char *index = NULL;
7049 struct tog_color *tc;
7050 int width, n, nentries, scrollx, i = 1;
7051 int limit = view->nlines;
7053 s->ndisplayed = 0;
7054 if (view_is_hsplit_top(view))
7055 --limit; /* border */
7057 werase(view->window);
7059 if (limit == 0)
7060 return NULL;
7062 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7063 0, 0);
7064 if (err)
7065 return err;
7066 if (view_needs_focus_indication(view))
7067 wstandout(view->window);
7068 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7069 if (tc)
7070 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7071 waddwstr(view->window, wline);
7072 free(wline);
7073 wline = NULL;
7074 while (width++ < view->ncols)
7075 waddch(view->window, ' ');
7076 if (tc)
7077 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7078 if (view_needs_focus_indication(view))
7079 wstandend(view->window);
7080 if (--limit <= 0)
7081 return NULL;
7083 i += s->selected;
7084 if (s->first_displayed_entry) {
7085 i += got_tree_entry_get_index(s->first_displayed_entry);
7086 if (s->tree != s->root)
7087 ++i; /* account for ".." entry */
7089 nentries = got_object_tree_get_nentries(s->tree);
7090 if (asprintf(&index, "[%d/%d] %s",
7091 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7092 return got_error_from_errno("asprintf");
7093 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7094 free(index);
7095 if (err)
7096 return err;
7097 waddwstr(view->window, wline);
7098 free(wline);
7099 wline = NULL;
7100 if (width < view->ncols - 1)
7101 waddch(view->window, '\n');
7102 if (--limit <= 0)
7103 return NULL;
7104 waddch(view->window, '\n');
7105 if (--limit <= 0)
7106 return NULL;
7108 if (s->first_displayed_entry == NULL) {
7109 te = got_object_tree_get_first_entry(s->tree);
7110 if (s->selected == 0) {
7111 if (view->focussed)
7112 wstandout(view->window);
7113 s->selected_entry = NULL;
7115 waddstr(view->window, " ..\n"); /* parent directory */
7116 if (s->selected == 0 && view->focussed)
7117 wstandend(view->window);
7118 s->ndisplayed++;
7119 if (--limit <= 0)
7120 return NULL;
7121 n = 1;
7122 } else {
7123 n = 0;
7124 te = s->first_displayed_entry;
7127 view->maxx = 0;
7128 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7129 char *line = NULL, *id_str = NULL, *link_target = NULL;
7130 const char *modestr = "";
7131 mode_t mode;
7133 te = got_object_tree_get_entry(s->tree, i);
7134 mode = got_tree_entry_get_mode(te);
7136 if (s->show_ids) {
7137 err = got_object_id_str(&id_str,
7138 got_tree_entry_get_id(te));
7139 if (err)
7140 return got_error_from_errno(
7141 "got_object_id_str");
7143 if (got_object_tree_entry_is_submodule(te))
7144 modestr = "$";
7145 else if (S_ISLNK(mode)) {
7146 int i;
7148 err = got_tree_entry_get_symlink_target(&link_target,
7149 te, s->repo);
7150 if (err) {
7151 free(id_str);
7152 return err;
7154 for (i = 0; i < strlen(link_target); i++) {
7155 if (!isprint((unsigned char)link_target[i]))
7156 link_target[i] = '?';
7158 modestr = "@";
7160 else if (S_ISDIR(mode))
7161 modestr = "/";
7162 else if (mode & S_IXUSR)
7163 modestr = "*";
7164 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7165 got_tree_entry_get_name(te), modestr,
7166 link_target ? " -> ": "",
7167 link_target ? link_target : "") == -1) {
7168 free(id_str);
7169 free(link_target);
7170 return got_error_from_errno("asprintf");
7172 free(id_str);
7173 free(link_target);
7175 /* use full line width to determine view->maxx */
7176 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7177 if (err) {
7178 free(line);
7179 break;
7181 view->maxx = MAX(view->maxx, width);
7182 free(wline);
7183 wline = NULL;
7185 err = format_line(&wline, &width, &scrollx, line, view->x,
7186 view->ncols, 0, 0);
7187 if (err) {
7188 free(line);
7189 break;
7191 if (n == s->selected) {
7192 if (view->focussed)
7193 wstandout(view->window);
7194 s->selected_entry = te;
7196 tc = match_color(&s->colors, line);
7197 if (tc)
7198 wattr_on(view->window,
7199 COLOR_PAIR(tc->colorpair), NULL);
7200 waddwstr(view->window, &wline[scrollx]);
7201 if (tc)
7202 wattr_off(view->window,
7203 COLOR_PAIR(tc->colorpair), NULL);
7204 if (width < view->ncols)
7205 waddch(view->window, '\n');
7206 if (n == s->selected && view->focussed)
7207 wstandend(view->window);
7208 free(line);
7209 free(wline);
7210 wline = NULL;
7211 n++;
7212 s->ndisplayed++;
7213 s->last_displayed_entry = te;
7214 if (--limit <= 0)
7215 break;
7218 return err;
7221 static void
7222 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7224 struct got_tree_entry *te;
7225 int isroot = s->tree == s->root;
7226 int i = 0;
7228 if (s->first_displayed_entry == NULL)
7229 return;
7231 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7232 while (i++ < maxscroll) {
7233 if (te == NULL) {
7234 if (!isroot)
7235 s->first_displayed_entry = NULL;
7236 break;
7238 s->first_displayed_entry = te;
7239 te = got_tree_entry_get_prev(s->tree, te);
7243 static const struct got_error *
7244 tree_scroll_down(struct tog_view *view, int maxscroll)
7246 struct tog_tree_view_state *s = &view->state.tree;
7247 struct got_tree_entry *next, *last;
7248 int n = 0;
7250 if (s->first_displayed_entry)
7251 next = got_tree_entry_get_next(s->tree,
7252 s->first_displayed_entry);
7253 else
7254 next = got_object_tree_get_first_entry(s->tree);
7256 last = s->last_displayed_entry;
7257 while (next && n++ < maxscroll) {
7258 if (last) {
7259 s->last_displayed_entry = last;
7260 last = got_tree_entry_get_next(s->tree, last);
7262 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7263 s->first_displayed_entry = next;
7264 next = got_tree_entry_get_next(s->tree, next);
7268 return NULL;
7271 static const struct got_error *
7272 tree_entry_path(char **path, struct tog_parent_trees *parents,
7273 struct got_tree_entry *te)
7275 const struct got_error *err = NULL;
7276 struct tog_parent_tree *pt;
7277 size_t len = 2; /* for leading slash and NUL */
7279 TAILQ_FOREACH(pt, parents, entry)
7280 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7281 + 1 /* slash */;
7282 if (te)
7283 len += strlen(got_tree_entry_get_name(te));
7285 *path = calloc(1, len);
7286 if (path == NULL)
7287 return got_error_from_errno("calloc");
7289 (*path)[0] = '/';
7290 pt = TAILQ_LAST(parents, tog_parent_trees);
7291 while (pt) {
7292 const char *name = got_tree_entry_get_name(pt->selected_entry);
7293 if (strlcat(*path, name, len) >= len) {
7294 err = got_error(GOT_ERR_NO_SPACE);
7295 goto done;
7297 if (strlcat(*path, "/", len) >= len) {
7298 err = got_error(GOT_ERR_NO_SPACE);
7299 goto done;
7301 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7303 if (te) {
7304 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7305 err = got_error(GOT_ERR_NO_SPACE);
7306 goto done;
7309 done:
7310 if (err) {
7311 free(*path);
7312 *path = NULL;
7314 return err;
7317 static const struct got_error *
7318 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7319 struct got_tree_entry *te, struct tog_parent_trees *parents,
7320 struct got_object_id *commit_id, struct got_repository *repo)
7322 const struct got_error *err = NULL;
7323 char *path;
7324 struct tog_view *blame_view;
7326 *new_view = NULL;
7328 err = tree_entry_path(&path, parents, te);
7329 if (err)
7330 return err;
7332 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7333 if (blame_view == NULL) {
7334 err = got_error_from_errno("view_open");
7335 goto done;
7338 err = open_blame_view(blame_view, path, commit_id, repo);
7339 if (err) {
7340 if (err->code == GOT_ERR_CANCELLED)
7341 err = NULL;
7342 view_close(blame_view);
7343 } else
7344 *new_view = blame_view;
7345 done:
7346 free(path);
7347 return err;
7350 static const struct got_error *
7351 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7352 struct tog_tree_view_state *s)
7354 struct tog_view *log_view;
7355 const struct got_error *err = NULL;
7356 char *path;
7358 *new_view = NULL;
7360 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7361 if (log_view == NULL)
7362 return got_error_from_errno("view_open");
7364 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7365 if (err)
7366 return err;
7368 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7369 path, 0);
7370 if (err)
7371 view_close(log_view);
7372 else
7373 *new_view = log_view;
7374 free(path);
7375 return err;
7378 static const struct got_error *
7379 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7380 const char *head_ref_name, struct got_repository *repo)
7382 const struct got_error *err = NULL;
7383 char *commit_id_str = NULL;
7384 struct tog_tree_view_state *s = &view->state.tree;
7385 struct got_commit_object *commit = NULL;
7387 TAILQ_INIT(&s->parents);
7388 STAILQ_INIT(&s->colors);
7390 s->commit_id = got_object_id_dup(commit_id);
7391 if (s->commit_id == NULL) {
7392 err = got_error_from_errno("got_object_id_dup");
7393 goto done;
7396 err = got_object_open_as_commit(&commit, repo, commit_id);
7397 if (err)
7398 goto done;
7401 * The root is opened here and will be closed when the view is closed.
7402 * Any visited subtrees and their path-wise parents are opened and
7403 * closed on demand.
7405 err = got_object_open_as_tree(&s->root, repo,
7406 got_object_commit_get_tree_id(commit));
7407 if (err)
7408 goto done;
7409 s->tree = s->root;
7411 err = got_object_id_str(&commit_id_str, commit_id);
7412 if (err != NULL)
7413 goto done;
7415 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7416 err = got_error_from_errno("asprintf");
7417 goto done;
7420 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7421 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7422 if (head_ref_name) {
7423 s->head_ref_name = strdup(head_ref_name);
7424 if (s->head_ref_name == NULL) {
7425 err = got_error_from_errno("strdup");
7426 goto done;
7429 s->repo = repo;
7431 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7432 err = add_color(&s->colors, "\\$$",
7433 TOG_COLOR_TREE_SUBMODULE,
7434 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7435 if (err)
7436 goto done;
7437 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7438 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7439 if (err)
7440 goto done;
7441 err = add_color(&s->colors, "/$",
7442 TOG_COLOR_TREE_DIRECTORY,
7443 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7444 if (err)
7445 goto done;
7447 err = add_color(&s->colors, "\\*$",
7448 TOG_COLOR_TREE_EXECUTABLE,
7449 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7450 if (err)
7451 goto done;
7453 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7454 get_color_value("TOG_COLOR_COMMIT"));
7455 if (err)
7456 goto done;
7459 view->show = show_tree_view;
7460 view->input = input_tree_view;
7461 view->close = close_tree_view;
7462 view->search_start = search_start_tree_view;
7463 view->search_next = search_next_tree_view;
7464 done:
7465 free(commit_id_str);
7466 if (commit)
7467 got_object_commit_close(commit);
7468 if (err) {
7469 if (view->close == NULL)
7470 close_tree_view(view);
7471 view_close(view);
7473 return err;
7476 static const struct got_error *
7477 close_tree_view(struct tog_view *view)
7479 struct tog_tree_view_state *s = &view->state.tree;
7481 free_colors(&s->colors);
7482 free(s->tree_label);
7483 s->tree_label = NULL;
7484 free(s->commit_id);
7485 s->commit_id = NULL;
7486 free(s->head_ref_name);
7487 s->head_ref_name = NULL;
7488 while (!TAILQ_EMPTY(&s->parents)) {
7489 struct tog_parent_tree *parent;
7490 parent = TAILQ_FIRST(&s->parents);
7491 TAILQ_REMOVE(&s->parents, parent, entry);
7492 if (parent->tree != s->root)
7493 got_object_tree_close(parent->tree);
7494 free(parent);
7497 if (s->tree != NULL && s->tree != s->root)
7498 got_object_tree_close(s->tree);
7499 if (s->root)
7500 got_object_tree_close(s->root);
7501 return NULL;
7504 static const struct got_error *
7505 search_start_tree_view(struct tog_view *view)
7507 struct tog_tree_view_state *s = &view->state.tree;
7509 s->matched_entry = NULL;
7510 return NULL;
7513 static int
7514 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7516 regmatch_t regmatch;
7518 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7519 0) == 0;
7522 static const struct got_error *
7523 search_next_tree_view(struct tog_view *view)
7525 struct tog_tree_view_state *s = &view->state.tree;
7526 struct got_tree_entry *te = NULL;
7528 if (!view->searching) {
7529 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7530 return NULL;
7533 if (s->matched_entry) {
7534 if (view->searching == TOG_SEARCH_FORWARD) {
7535 if (s->selected_entry)
7536 te = got_tree_entry_get_next(s->tree,
7537 s->selected_entry);
7538 else
7539 te = got_object_tree_get_first_entry(s->tree);
7540 } else {
7541 if (s->selected_entry == NULL)
7542 te = got_object_tree_get_last_entry(s->tree);
7543 else
7544 te = got_tree_entry_get_prev(s->tree,
7545 s->selected_entry);
7547 } else {
7548 if (s->selected_entry)
7549 te = s->selected_entry;
7550 else if (view->searching == TOG_SEARCH_FORWARD)
7551 te = got_object_tree_get_first_entry(s->tree);
7552 else
7553 te = got_object_tree_get_last_entry(s->tree);
7556 while (1) {
7557 if (te == NULL) {
7558 if (s->matched_entry == NULL) {
7559 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7560 return NULL;
7562 if (view->searching == TOG_SEARCH_FORWARD)
7563 te = got_object_tree_get_first_entry(s->tree);
7564 else
7565 te = got_object_tree_get_last_entry(s->tree);
7568 if (match_tree_entry(te, &view->regex)) {
7569 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7570 s->matched_entry = te;
7571 break;
7574 if (view->searching == TOG_SEARCH_FORWARD)
7575 te = got_tree_entry_get_next(s->tree, te);
7576 else
7577 te = got_tree_entry_get_prev(s->tree, te);
7580 if (s->matched_entry) {
7581 s->first_displayed_entry = s->matched_entry;
7582 s->selected = 0;
7585 return NULL;
7588 static const struct got_error *
7589 show_tree_view(struct tog_view *view)
7591 const struct got_error *err = NULL;
7592 struct tog_tree_view_state *s = &view->state.tree;
7593 char *parent_path;
7595 err = tree_entry_path(&parent_path, &s->parents, NULL);
7596 if (err)
7597 return err;
7599 err = draw_tree_entries(view, parent_path);
7600 free(parent_path);
7602 view_border(view);
7603 return err;
7606 static const struct got_error *
7607 tree_goto_line(struct tog_view *view, int nlines)
7609 const struct got_error *err = NULL;
7610 struct tog_tree_view_state *s = &view->state.tree;
7611 struct got_tree_entry **fte, **lte, **ste;
7612 int g, last, first = 1, i = 1;
7613 int root = s->tree == s->root;
7614 int off = root ? 1 : 2;
7616 g = view->gline;
7617 view->gline = 0;
7619 if (g == 0)
7620 g = 1;
7621 else if (g > got_object_tree_get_nentries(s->tree))
7622 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7624 fte = &s->first_displayed_entry;
7625 lte = &s->last_displayed_entry;
7626 ste = &s->selected_entry;
7628 if (*fte != NULL) {
7629 first = got_tree_entry_get_index(*fte);
7630 first += off; /* account for ".." */
7632 last = got_tree_entry_get_index(*lte);
7633 last += off;
7635 if (g >= first && g <= last && g - first < nlines) {
7636 s->selected = g - first;
7637 return NULL; /* gline is on the current page */
7640 if (*ste != NULL) {
7641 i = got_tree_entry_get_index(*ste);
7642 i += off;
7645 if (i < g) {
7646 err = tree_scroll_down(view, g - i);
7647 if (err)
7648 return err;
7649 if (got_tree_entry_get_index(*lte) >=
7650 got_object_tree_get_nentries(s->tree) - 1 &&
7651 first + s->selected < g &&
7652 s->selected < s->ndisplayed - 1) {
7653 first = got_tree_entry_get_index(*fte);
7654 first += off;
7655 s->selected = g - first;
7657 } else if (i > g)
7658 tree_scroll_up(s, i - g);
7660 if (g < nlines &&
7661 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7662 s->selected = g - 1;
7664 return NULL;
7667 static const struct got_error *
7668 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7670 const struct got_error *err = NULL;
7671 struct tog_tree_view_state *s = &view->state.tree;
7672 struct got_tree_entry *te;
7673 int n, nscroll = view->nlines - 3;
7675 if (view->gline)
7676 return tree_goto_line(view, nscroll);
7678 switch (ch) {
7679 case '0':
7680 case '$':
7681 case KEY_RIGHT:
7682 case 'l':
7683 case KEY_LEFT:
7684 case 'h':
7685 horizontal_scroll_input(view, ch);
7686 break;
7687 case 'i':
7688 s->show_ids = !s->show_ids;
7689 view->count = 0;
7690 break;
7691 case 'L':
7692 view->count = 0;
7693 if (!s->selected_entry)
7694 break;
7695 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7696 break;
7697 case 'R':
7698 view->count = 0;
7699 err = view_request_new(new_view, view, TOG_VIEW_REF);
7700 break;
7701 case 'g':
7702 case '=':
7703 case KEY_HOME:
7704 s->selected = 0;
7705 view->count = 0;
7706 if (s->tree == s->root)
7707 s->first_displayed_entry =
7708 got_object_tree_get_first_entry(s->tree);
7709 else
7710 s->first_displayed_entry = NULL;
7711 break;
7712 case 'G':
7713 case '*':
7714 case KEY_END: {
7715 int eos = view->nlines - 3;
7717 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7718 --eos; /* border */
7719 s->selected = 0;
7720 view->count = 0;
7721 te = got_object_tree_get_last_entry(s->tree);
7722 for (n = 0; n < eos; n++) {
7723 if (te == NULL) {
7724 if (s->tree != s->root) {
7725 s->first_displayed_entry = NULL;
7726 n++;
7728 break;
7730 s->first_displayed_entry = te;
7731 te = got_tree_entry_get_prev(s->tree, te);
7733 if (n > 0)
7734 s->selected = n - 1;
7735 break;
7737 case 'k':
7738 case KEY_UP:
7739 case CTRL('p'):
7740 if (s->selected > 0) {
7741 s->selected--;
7742 break;
7744 tree_scroll_up(s, 1);
7745 if (s->selected_entry == NULL ||
7746 (s->tree == s->root && s->selected_entry ==
7747 got_object_tree_get_first_entry(s->tree)))
7748 view->count = 0;
7749 break;
7750 case CTRL('u'):
7751 case 'u':
7752 nscroll /= 2;
7753 /* FALL THROUGH */
7754 case KEY_PPAGE:
7755 case CTRL('b'):
7756 case 'b':
7757 if (s->tree == s->root) {
7758 if (got_object_tree_get_first_entry(s->tree) ==
7759 s->first_displayed_entry)
7760 s->selected -= MIN(s->selected, nscroll);
7761 } else {
7762 if (s->first_displayed_entry == NULL)
7763 s->selected -= MIN(s->selected, nscroll);
7765 tree_scroll_up(s, MAX(0, nscroll));
7766 if (s->selected_entry == NULL ||
7767 (s->tree == s->root && s->selected_entry ==
7768 got_object_tree_get_first_entry(s->tree)))
7769 view->count = 0;
7770 break;
7771 case 'j':
7772 case KEY_DOWN:
7773 case CTRL('n'):
7774 if (s->selected < s->ndisplayed - 1) {
7775 s->selected++;
7776 break;
7778 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7779 == NULL) {
7780 /* can't scroll any further */
7781 view->count = 0;
7782 break;
7784 tree_scroll_down(view, 1);
7785 break;
7786 case CTRL('d'):
7787 case 'd':
7788 nscroll /= 2;
7789 /* FALL THROUGH */
7790 case KEY_NPAGE:
7791 case CTRL('f'):
7792 case 'f':
7793 case ' ':
7794 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7795 == NULL) {
7796 /* can't scroll any further; move cursor down */
7797 if (s->selected < s->ndisplayed - 1)
7798 s->selected += MIN(nscroll,
7799 s->ndisplayed - s->selected - 1);
7800 else
7801 view->count = 0;
7802 break;
7804 tree_scroll_down(view, nscroll);
7805 break;
7806 case KEY_ENTER:
7807 case '\r':
7808 case KEY_BACKSPACE:
7809 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7810 struct tog_parent_tree *parent;
7811 /* user selected '..' */
7812 if (s->tree == s->root) {
7813 view->count = 0;
7814 break;
7816 parent = TAILQ_FIRST(&s->parents);
7817 TAILQ_REMOVE(&s->parents, parent,
7818 entry);
7819 got_object_tree_close(s->tree);
7820 s->tree = parent->tree;
7821 s->first_displayed_entry =
7822 parent->first_displayed_entry;
7823 s->selected_entry =
7824 parent->selected_entry;
7825 s->selected = parent->selected;
7826 if (s->selected > view->nlines - 3) {
7827 err = offset_selection_down(view);
7828 if (err)
7829 break;
7831 free(parent);
7832 } else if (S_ISDIR(got_tree_entry_get_mode(
7833 s->selected_entry))) {
7834 struct got_tree_object *subtree;
7835 view->count = 0;
7836 err = got_object_open_as_tree(&subtree, s->repo,
7837 got_tree_entry_get_id(s->selected_entry));
7838 if (err)
7839 break;
7840 err = tree_view_visit_subtree(s, subtree);
7841 if (err) {
7842 got_object_tree_close(subtree);
7843 break;
7845 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7846 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7847 break;
7848 case KEY_RESIZE:
7849 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7850 s->selected = view->nlines - 4;
7851 view->count = 0;
7852 break;
7853 default:
7854 view->count = 0;
7855 break;
7858 return err;
7861 __dead static void
7862 usage_tree(void)
7864 endwin();
7865 fprintf(stderr,
7866 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7867 getprogname());
7868 exit(1);
7871 static const struct got_error *
7872 cmd_tree(int argc, char *argv[])
7874 const struct got_error *error;
7875 struct got_repository *repo = NULL;
7876 struct got_worktree *worktree = NULL;
7877 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7878 struct got_object_id *commit_id = NULL;
7879 struct got_commit_object *commit = NULL;
7880 const char *commit_id_arg = NULL;
7881 char *label = NULL;
7882 struct got_reference *ref = NULL;
7883 const char *head_ref_name = NULL;
7884 int ch;
7885 struct tog_view *view;
7886 int *pack_fds = NULL;
7888 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7889 switch (ch) {
7890 case 'c':
7891 commit_id_arg = optarg;
7892 break;
7893 case 'r':
7894 repo_path = realpath(optarg, NULL);
7895 if (repo_path == NULL)
7896 return got_error_from_errno2("realpath",
7897 optarg);
7898 break;
7899 default:
7900 usage_tree();
7901 /* NOTREACHED */
7905 argc -= optind;
7906 argv += optind;
7908 if (argc > 1)
7909 usage_tree();
7911 error = got_repo_pack_fds_open(&pack_fds);
7912 if (error != NULL)
7913 goto done;
7915 if (repo_path == NULL) {
7916 cwd = getcwd(NULL, 0);
7917 if (cwd == NULL)
7918 return got_error_from_errno("getcwd");
7919 error = got_worktree_open(&worktree, cwd);
7920 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7921 goto done;
7922 if (worktree)
7923 repo_path =
7924 strdup(got_worktree_get_repo_path(worktree));
7925 else
7926 repo_path = strdup(cwd);
7927 if (repo_path == NULL) {
7928 error = got_error_from_errno("strdup");
7929 goto done;
7933 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7934 if (error != NULL)
7935 goto done;
7937 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7938 repo, worktree);
7939 if (error)
7940 goto done;
7942 init_curses();
7944 error = apply_unveil(got_repo_get_path(repo), NULL);
7945 if (error)
7946 goto done;
7948 error = tog_load_refs(repo, 0);
7949 if (error)
7950 goto done;
7952 if (commit_id_arg == NULL) {
7953 error = got_repo_match_object_id(&commit_id, &label,
7954 worktree ? got_worktree_get_head_ref_name(worktree) :
7955 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7956 if (error)
7957 goto done;
7958 head_ref_name = label;
7959 } else {
7960 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7961 if (error == NULL)
7962 head_ref_name = got_ref_get_name(ref);
7963 else if (error->code != GOT_ERR_NOT_REF)
7964 goto done;
7965 error = got_repo_match_object_id(&commit_id, NULL,
7966 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7967 if (error)
7968 goto done;
7971 error = got_object_open_as_commit(&commit, repo, commit_id);
7972 if (error)
7973 goto done;
7975 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7976 if (view == NULL) {
7977 error = got_error_from_errno("view_open");
7978 goto done;
7980 error = open_tree_view(view, commit_id, head_ref_name, repo);
7981 if (error)
7982 goto done;
7983 if (!got_path_is_root_dir(in_repo_path)) {
7984 error = tree_view_walk_path(&view->state.tree, commit,
7985 in_repo_path);
7986 if (error)
7987 goto done;
7990 if (worktree) {
7991 /* Release work tree lock. */
7992 got_worktree_close(worktree);
7993 worktree = NULL;
7995 error = view_loop(view);
7996 done:
7997 free(repo_path);
7998 free(cwd);
7999 free(commit_id);
8000 free(label);
8001 if (ref)
8002 got_ref_close(ref);
8003 if (repo) {
8004 const struct got_error *close_err = got_repo_close(repo);
8005 if (error == NULL)
8006 error = close_err;
8008 if (pack_fds) {
8009 const struct got_error *pack_err =
8010 got_repo_pack_fds_close(pack_fds);
8011 if (error == NULL)
8012 error = pack_err;
8014 tog_free_refs();
8015 return error;
8018 static const struct got_error *
8019 ref_view_load_refs(struct tog_ref_view_state *s)
8021 struct got_reflist_entry *sre;
8022 struct tog_reflist_entry *re;
8024 s->nrefs = 0;
8025 TAILQ_FOREACH(sre, &tog_refs, entry) {
8026 if (strncmp(got_ref_get_name(sre->ref),
8027 "refs/got/", 9) == 0 &&
8028 strncmp(got_ref_get_name(sre->ref),
8029 "refs/got/backup/", 16) != 0)
8030 continue;
8032 re = malloc(sizeof(*re));
8033 if (re == NULL)
8034 return got_error_from_errno("malloc");
8036 re->ref = got_ref_dup(sre->ref);
8037 if (re->ref == NULL)
8038 return got_error_from_errno("got_ref_dup");
8039 re->idx = s->nrefs++;
8040 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8043 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8044 return NULL;
8047 static void
8048 ref_view_free_refs(struct tog_ref_view_state *s)
8050 struct tog_reflist_entry *re;
8052 while (!TAILQ_EMPTY(&s->refs)) {
8053 re = TAILQ_FIRST(&s->refs);
8054 TAILQ_REMOVE(&s->refs, re, entry);
8055 got_ref_close(re->ref);
8056 free(re);
8060 static const struct got_error *
8061 open_ref_view(struct tog_view *view, struct got_repository *repo)
8063 const struct got_error *err = NULL;
8064 struct tog_ref_view_state *s = &view->state.ref;
8066 s->selected_entry = 0;
8067 s->repo = repo;
8069 TAILQ_INIT(&s->refs);
8070 STAILQ_INIT(&s->colors);
8072 err = ref_view_load_refs(s);
8073 if (err)
8074 goto done;
8076 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8077 err = add_color(&s->colors, "^refs/heads/",
8078 TOG_COLOR_REFS_HEADS,
8079 get_color_value("TOG_COLOR_REFS_HEADS"));
8080 if (err)
8081 goto done;
8083 err = add_color(&s->colors, "^refs/tags/",
8084 TOG_COLOR_REFS_TAGS,
8085 get_color_value("TOG_COLOR_REFS_TAGS"));
8086 if (err)
8087 goto done;
8089 err = add_color(&s->colors, "^refs/remotes/",
8090 TOG_COLOR_REFS_REMOTES,
8091 get_color_value("TOG_COLOR_REFS_REMOTES"));
8092 if (err)
8093 goto done;
8095 err = add_color(&s->colors, "^refs/got/backup/",
8096 TOG_COLOR_REFS_BACKUP,
8097 get_color_value("TOG_COLOR_REFS_BACKUP"));
8098 if (err)
8099 goto done;
8102 view->show = show_ref_view;
8103 view->input = input_ref_view;
8104 view->close = close_ref_view;
8105 view->search_start = search_start_ref_view;
8106 view->search_next = search_next_ref_view;
8107 done:
8108 if (err) {
8109 if (view->close == NULL)
8110 close_ref_view(view);
8111 view_close(view);
8113 return err;
8116 static const struct got_error *
8117 close_ref_view(struct tog_view *view)
8119 struct tog_ref_view_state *s = &view->state.ref;
8121 ref_view_free_refs(s);
8122 free_colors(&s->colors);
8124 return NULL;
8127 static const struct got_error *
8128 resolve_reflist_entry(struct got_object_id **commit_id,
8129 struct tog_reflist_entry *re, struct got_repository *repo)
8131 const struct got_error *err = NULL;
8132 struct got_object_id *obj_id;
8133 struct got_tag_object *tag = NULL;
8134 int obj_type;
8136 *commit_id = NULL;
8138 err = got_ref_resolve(&obj_id, repo, re->ref);
8139 if (err)
8140 return err;
8142 err = got_object_get_type(&obj_type, repo, obj_id);
8143 if (err)
8144 goto done;
8146 switch (obj_type) {
8147 case GOT_OBJ_TYPE_COMMIT:
8148 *commit_id = obj_id;
8149 break;
8150 case GOT_OBJ_TYPE_TAG:
8151 err = got_object_open_as_tag(&tag, repo, obj_id);
8152 if (err)
8153 goto done;
8154 free(obj_id);
8155 err = got_object_get_type(&obj_type, repo,
8156 got_object_tag_get_object_id(tag));
8157 if (err)
8158 goto done;
8159 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8160 err = got_error(GOT_ERR_OBJ_TYPE);
8161 goto done;
8163 *commit_id = got_object_id_dup(
8164 got_object_tag_get_object_id(tag));
8165 if (*commit_id == NULL) {
8166 err = got_error_from_errno("got_object_id_dup");
8167 goto done;
8169 break;
8170 default:
8171 err = got_error(GOT_ERR_OBJ_TYPE);
8172 break;
8175 done:
8176 if (tag)
8177 got_object_tag_close(tag);
8178 if (err) {
8179 free(*commit_id);
8180 *commit_id = NULL;
8182 return err;
8185 static const struct got_error *
8186 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8187 struct tog_reflist_entry *re, struct got_repository *repo)
8189 struct tog_view *log_view;
8190 const struct got_error *err = NULL;
8191 struct got_object_id *commit_id = NULL;
8193 *new_view = NULL;
8195 err = resolve_reflist_entry(&commit_id, re, repo);
8196 if (err) {
8197 if (err->code != GOT_ERR_OBJ_TYPE)
8198 return err;
8199 else
8200 return NULL;
8203 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8204 if (log_view == NULL) {
8205 err = got_error_from_errno("view_open");
8206 goto done;
8209 err = open_log_view(log_view, commit_id, repo,
8210 got_ref_get_name(re->ref), "", 0);
8211 done:
8212 if (err)
8213 view_close(log_view);
8214 else
8215 *new_view = log_view;
8216 free(commit_id);
8217 return err;
8220 static void
8221 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8223 struct tog_reflist_entry *re;
8224 int i = 0;
8226 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8227 return;
8229 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8230 while (i++ < maxscroll) {
8231 if (re == NULL)
8232 break;
8233 s->first_displayed_entry = re;
8234 re = TAILQ_PREV(re, tog_reflist_head, entry);
8238 static const struct got_error *
8239 ref_scroll_down(struct tog_view *view, int maxscroll)
8241 struct tog_ref_view_state *s = &view->state.ref;
8242 struct tog_reflist_entry *next, *last;
8243 int n = 0;
8245 if (s->first_displayed_entry)
8246 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8247 else
8248 next = TAILQ_FIRST(&s->refs);
8250 last = s->last_displayed_entry;
8251 while (next && n++ < maxscroll) {
8252 if (last) {
8253 s->last_displayed_entry = last;
8254 last = TAILQ_NEXT(last, entry);
8256 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8257 s->first_displayed_entry = next;
8258 next = TAILQ_NEXT(next, entry);
8262 return NULL;
8265 static const struct got_error *
8266 search_start_ref_view(struct tog_view *view)
8268 struct tog_ref_view_state *s = &view->state.ref;
8270 s->matched_entry = NULL;
8271 return NULL;
8274 static int
8275 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8277 regmatch_t regmatch;
8279 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8280 0) == 0;
8283 static const struct got_error *
8284 search_next_ref_view(struct tog_view *view)
8286 struct tog_ref_view_state *s = &view->state.ref;
8287 struct tog_reflist_entry *re = NULL;
8289 if (!view->searching) {
8290 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8291 return NULL;
8294 if (s->matched_entry) {
8295 if (view->searching == TOG_SEARCH_FORWARD) {
8296 if (s->selected_entry)
8297 re = TAILQ_NEXT(s->selected_entry, entry);
8298 else
8299 re = TAILQ_PREV(s->selected_entry,
8300 tog_reflist_head, entry);
8301 } else {
8302 if (s->selected_entry == NULL)
8303 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8304 else
8305 re = TAILQ_PREV(s->selected_entry,
8306 tog_reflist_head, entry);
8308 } else {
8309 if (s->selected_entry)
8310 re = s->selected_entry;
8311 else if (view->searching == TOG_SEARCH_FORWARD)
8312 re = TAILQ_FIRST(&s->refs);
8313 else
8314 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8317 while (1) {
8318 if (re == NULL) {
8319 if (s->matched_entry == NULL) {
8320 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8321 return NULL;
8323 if (view->searching == TOG_SEARCH_FORWARD)
8324 re = TAILQ_FIRST(&s->refs);
8325 else
8326 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8329 if (match_reflist_entry(re, &view->regex)) {
8330 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8331 s->matched_entry = re;
8332 break;
8335 if (view->searching == TOG_SEARCH_FORWARD)
8336 re = TAILQ_NEXT(re, entry);
8337 else
8338 re = TAILQ_PREV(re, tog_reflist_head, entry);
8341 if (s->matched_entry) {
8342 s->first_displayed_entry = s->matched_entry;
8343 s->selected = 0;
8346 return NULL;
8349 static const struct got_error *
8350 show_ref_view(struct tog_view *view)
8352 const struct got_error *err = NULL;
8353 struct tog_ref_view_state *s = &view->state.ref;
8354 struct tog_reflist_entry *re;
8355 char *line = NULL;
8356 wchar_t *wline;
8357 struct tog_color *tc;
8358 int width, n, scrollx;
8359 int limit = view->nlines;
8361 werase(view->window);
8363 s->ndisplayed = 0;
8364 if (view_is_hsplit_top(view))
8365 --limit; /* border */
8367 if (limit == 0)
8368 return NULL;
8370 re = s->first_displayed_entry;
8372 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8373 s->nrefs) == -1)
8374 return got_error_from_errno("asprintf");
8376 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8377 if (err) {
8378 free(line);
8379 return err;
8381 if (view_needs_focus_indication(view))
8382 wstandout(view->window);
8383 waddwstr(view->window, wline);
8384 while (width++ < view->ncols)
8385 waddch(view->window, ' ');
8386 if (view_needs_focus_indication(view))
8387 wstandend(view->window);
8388 free(wline);
8389 wline = NULL;
8390 free(line);
8391 line = NULL;
8392 if (--limit <= 0)
8393 return NULL;
8395 n = 0;
8396 view->maxx = 0;
8397 while (re && limit > 0) {
8398 char *line = NULL;
8399 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8401 if (s->show_date) {
8402 struct got_commit_object *ci;
8403 struct got_tag_object *tag;
8404 struct got_object_id *id;
8405 struct tm tm;
8406 time_t t;
8408 err = got_ref_resolve(&id, s->repo, re->ref);
8409 if (err)
8410 return err;
8411 err = got_object_open_as_tag(&tag, s->repo, id);
8412 if (err) {
8413 if (err->code != GOT_ERR_OBJ_TYPE) {
8414 free(id);
8415 return err;
8417 err = got_object_open_as_commit(&ci, s->repo,
8418 id);
8419 if (err) {
8420 free(id);
8421 return err;
8423 t = got_object_commit_get_committer_time(ci);
8424 got_object_commit_close(ci);
8425 } else {
8426 t = got_object_tag_get_tagger_time(tag);
8427 got_object_tag_close(tag);
8429 free(id);
8430 if (gmtime_r(&t, &tm) == NULL)
8431 return got_error_from_errno("gmtime_r");
8432 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8433 return got_error(GOT_ERR_NO_SPACE);
8435 if (got_ref_is_symbolic(re->ref)) {
8436 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8437 ymd : "", got_ref_get_name(re->ref),
8438 got_ref_get_symref_target(re->ref)) == -1)
8439 return got_error_from_errno("asprintf");
8440 } else if (s->show_ids) {
8441 struct got_object_id *id;
8442 char *id_str;
8443 err = got_ref_resolve(&id, s->repo, re->ref);
8444 if (err)
8445 return err;
8446 err = got_object_id_str(&id_str, id);
8447 if (err) {
8448 free(id);
8449 return err;
8451 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8452 got_ref_get_name(re->ref), id_str) == -1) {
8453 err = got_error_from_errno("asprintf");
8454 free(id);
8455 free(id_str);
8456 return err;
8458 free(id);
8459 free(id_str);
8460 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8461 got_ref_get_name(re->ref)) == -1)
8462 return got_error_from_errno("asprintf");
8464 /* use full line width to determine view->maxx */
8465 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8466 if (err) {
8467 free(line);
8468 return err;
8470 view->maxx = MAX(view->maxx, width);
8471 free(wline);
8472 wline = NULL;
8474 err = format_line(&wline, &width, &scrollx, line, view->x,
8475 view->ncols, 0, 0);
8476 if (err) {
8477 free(line);
8478 return err;
8480 if (n == s->selected) {
8481 if (view->focussed)
8482 wstandout(view->window);
8483 s->selected_entry = re;
8485 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8486 if (tc)
8487 wattr_on(view->window,
8488 COLOR_PAIR(tc->colorpair), NULL);
8489 waddwstr(view->window, &wline[scrollx]);
8490 if (tc)
8491 wattr_off(view->window,
8492 COLOR_PAIR(tc->colorpair), NULL);
8493 if (width < view->ncols)
8494 waddch(view->window, '\n');
8495 if (n == s->selected && view->focussed)
8496 wstandend(view->window);
8497 free(line);
8498 free(wline);
8499 wline = NULL;
8500 n++;
8501 s->ndisplayed++;
8502 s->last_displayed_entry = re;
8504 limit--;
8505 re = TAILQ_NEXT(re, entry);
8508 view_border(view);
8509 return err;
8512 static const struct got_error *
8513 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8514 struct tog_reflist_entry *re, struct got_repository *repo)
8516 const struct got_error *err = NULL;
8517 struct got_object_id *commit_id = NULL;
8518 struct tog_view *tree_view;
8520 *new_view = NULL;
8522 err = resolve_reflist_entry(&commit_id, re, repo);
8523 if (err) {
8524 if (err->code != GOT_ERR_OBJ_TYPE)
8525 return err;
8526 else
8527 return NULL;
8531 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8532 if (tree_view == NULL) {
8533 err = got_error_from_errno("view_open");
8534 goto done;
8537 err = open_tree_view(tree_view, commit_id,
8538 got_ref_get_name(re->ref), repo);
8539 if (err)
8540 goto done;
8542 *new_view = tree_view;
8543 done:
8544 free(commit_id);
8545 return err;
8548 static const struct got_error *
8549 ref_goto_line(struct tog_view *view, int nlines)
8551 const struct got_error *err = NULL;
8552 struct tog_ref_view_state *s = &view->state.ref;
8553 int g, idx = s->selected_entry->idx;
8555 g = view->gline;
8556 view->gline = 0;
8558 if (g == 0)
8559 g = 1;
8560 else if (g > s->nrefs)
8561 g = s->nrefs;
8563 if (g >= s->first_displayed_entry->idx + 1 &&
8564 g <= s->last_displayed_entry->idx + 1 &&
8565 g - s->first_displayed_entry->idx - 1 < nlines) {
8566 s->selected = g - s->first_displayed_entry->idx - 1;
8567 return NULL;
8570 if (idx + 1 < g) {
8571 err = ref_scroll_down(view, g - idx - 1);
8572 if (err)
8573 return err;
8574 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8575 s->first_displayed_entry->idx + s->selected < g &&
8576 s->selected < s->ndisplayed - 1)
8577 s->selected = g - s->first_displayed_entry->idx - 1;
8578 } else if (idx + 1 > g)
8579 ref_scroll_up(s, idx - g + 1);
8581 if (g < nlines && s->first_displayed_entry->idx == 0)
8582 s->selected = g - 1;
8584 return NULL;
8588 static const struct got_error *
8589 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8591 const struct got_error *err = NULL;
8592 struct tog_ref_view_state *s = &view->state.ref;
8593 struct tog_reflist_entry *re;
8594 int n, nscroll = view->nlines - 1;
8596 if (view->gline)
8597 return ref_goto_line(view, nscroll);
8599 switch (ch) {
8600 case '0':
8601 case '$':
8602 case KEY_RIGHT:
8603 case 'l':
8604 case KEY_LEFT:
8605 case 'h':
8606 horizontal_scroll_input(view, ch);
8607 break;
8608 case 'i':
8609 s->show_ids = !s->show_ids;
8610 view->count = 0;
8611 break;
8612 case 'm':
8613 s->show_date = !s->show_date;
8614 view->count = 0;
8615 break;
8616 case 'o':
8617 s->sort_by_date = !s->sort_by_date;
8618 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8619 view->count = 0;
8620 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8621 got_ref_cmp_by_commit_timestamp_descending :
8622 tog_ref_cmp_by_name, s->repo);
8623 if (err)
8624 break;
8625 got_reflist_object_id_map_free(tog_refs_idmap);
8626 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8627 &tog_refs, s->repo);
8628 if (err)
8629 break;
8630 ref_view_free_refs(s);
8631 err = ref_view_load_refs(s);
8632 break;
8633 case KEY_ENTER:
8634 case '\r':
8635 view->count = 0;
8636 if (!s->selected_entry)
8637 break;
8638 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8639 break;
8640 case 'T':
8641 view->count = 0;
8642 if (!s->selected_entry)
8643 break;
8644 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8645 break;
8646 case 'g':
8647 case '=':
8648 case KEY_HOME:
8649 s->selected = 0;
8650 view->count = 0;
8651 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8652 break;
8653 case 'G':
8654 case '*':
8655 case KEY_END: {
8656 int eos = view->nlines - 1;
8658 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8659 --eos; /* border */
8660 s->selected = 0;
8661 view->count = 0;
8662 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8663 for (n = 0; n < eos; n++) {
8664 if (re == NULL)
8665 break;
8666 s->first_displayed_entry = re;
8667 re = TAILQ_PREV(re, tog_reflist_head, entry);
8669 if (n > 0)
8670 s->selected = n - 1;
8671 break;
8673 case 'k':
8674 case KEY_UP:
8675 case CTRL('p'):
8676 if (s->selected > 0) {
8677 s->selected--;
8678 break;
8680 ref_scroll_up(s, 1);
8681 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8682 view->count = 0;
8683 break;
8684 case CTRL('u'):
8685 case 'u':
8686 nscroll /= 2;
8687 /* FALL THROUGH */
8688 case KEY_PPAGE:
8689 case CTRL('b'):
8690 case 'b':
8691 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8692 s->selected -= MIN(nscroll, s->selected);
8693 ref_scroll_up(s, MAX(0, nscroll));
8694 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8695 view->count = 0;
8696 break;
8697 case 'j':
8698 case KEY_DOWN:
8699 case CTRL('n'):
8700 if (s->selected < s->ndisplayed - 1) {
8701 s->selected++;
8702 break;
8704 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8705 /* can't scroll any further */
8706 view->count = 0;
8707 break;
8709 ref_scroll_down(view, 1);
8710 break;
8711 case CTRL('d'):
8712 case 'd':
8713 nscroll /= 2;
8714 /* FALL THROUGH */
8715 case KEY_NPAGE:
8716 case CTRL('f'):
8717 case 'f':
8718 case ' ':
8719 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8720 /* can't scroll any further; move cursor down */
8721 if (s->selected < s->ndisplayed - 1)
8722 s->selected += MIN(nscroll,
8723 s->ndisplayed - s->selected - 1);
8724 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8725 s->selected += s->ndisplayed - s->selected - 1;
8726 view->count = 0;
8727 break;
8729 ref_scroll_down(view, nscroll);
8730 break;
8731 case CTRL('l'):
8732 view->count = 0;
8733 tog_free_refs();
8734 err = tog_load_refs(s->repo, s->sort_by_date);
8735 if (err)
8736 break;
8737 ref_view_free_refs(s);
8738 err = ref_view_load_refs(s);
8739 break;
8740 case KEY_RESIZE:
8741 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8742 s->selected = view->nlines - 2;
8743 break;
8744 default:
8745 view->count = 0;
8746 break;
8749 return err;
8752 __dead static void
8753 usage_ref(void)
8755 endwin();
8756 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8757 getprogname());
8758 exit(1);
8761 static const struct got_error *
8762 cmd_ref(int argc, char *argv[])
8764 const struct got_error *error;
8765 struct got_repository *repo = NULL;
8766 struct got_worktree *worktree = NULL;
8767 char *cwd = NULL, *repo_path = NULL;
8768 int ch;
8769 struct tog_view *view;
8770 int *pack_fds = NULL;
8772 while ((ch = getopt(argc, argv, "r:")) != -1) {
8773 switch (ch) {
8774 case 'r':
8775 repo_path = realpath(optarg, NULL);
8776 if (repo_path == NULL)
8777 return got_error_from_errno2("realpath",
8778 optarg);
8779 break;
8780 default:
8781 usage_ref();
8782 /* NOTREACHED */
8786 argc -= optind;
8787 argv += optind;
8789 if (argc > 1)
8790 usage_ref();
8792 error = got_repo_pack_fds_open(&pack_fds);
8793 if (error != NULL)
8794 goto done;
8796 if (repo_path == NULL) {
8797 cwd = getcwd(NULL, 0);
8798 if (cwd == NULL)
8799 return got_error_from_errno("getcwd");
8800 error = got_worktree_open(&worktree, cwd);
8801 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8802 goto done;
8803 if (worktree)
8804 repo_path =
8805 strdup(got_worktree_get_repo_path(worktree));
8806 else
8807 repo_path = strdup(cwd);
8808 if (repo_path == NULL) {
8809 error = got_error_from_errno("strdup");
8810 goto done;
8814 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8815 if (error != NULL)
8816 goto done;
8818 init_curses();
8820 error = apply_unveil(got_repo_get_path(repo), NULL);
8821 if (error)
8822 goto done;
8824 error = tog_load_refs(repo, 0);
8825 if (error)
8826 goto done;
8828 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8829 if (view == NULL) {
8830 error = got_error_from_errno("view_open");
8831 goto done;
8834 error = open_ref_view(view, repo);
8835 if (error)
8836 goto done;
8838 if (worktree) {
8839 /* Release work tree lock. */
8840 got_worktree_close(worktree);
8841 worktree = NULL;
8843 error = view_loop(view);
8844 done:
8845 free(repo_path);
8846 free(cwd);
8847 if (repo) {
8848 const struct got_error *close_err = got_repo_close(repo);
8849 if (close_err)
8850 error = close_err;
8852 if (pack_fds) {
8853 const struct got_error *pack_err =
8854 got_repo_pack_fds_close(pack_fds);
8855 if (error == NULL)
8856 error = pack_err;
8858 tog_free_refs();
8859 return error;
8862 static const struct got_error*
8863 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8864 const char *str)
8866 size_t len;
8868 if (win == NULL)
8869 win = stdscr;
8871 len = strlen(str);
8872 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8874 if (focus)
8875 wstandout(win);
8876 if (mvwprintw(win, y, x, "%s", str) == ERR)
8877 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8878 if (focus)
8879 wstandend(win);
8881 return NULL;
8884 static const struct got_error *
8885 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8887 off_t *p;
8889 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8890 if (p == NULL) {
8891 free(*line_offsets);
8892 *line_offsets = NULL;
8893 return got_error_from_errno("reallocarray");
8896 *line_offsets = p;
8897 (*line_offsets)[*nlines] = off;
8898 ++(*nlines);
8899 return NULL;
8902 static const struct got_error *
8903 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8905 *ret = 0;
8907 for (;n > 0; --n, ++km) {
8908 char *t0, *t, *k;
8909 size_t len = 1;
8911 if (km->keys == NULL)
8912 continue;
8914 t = t0 = strdup(km->keys);
8915 if (t0 == NULL)
8916 return got_error_from_errno("strdup");
8918 len += strlen(t);
8919 while ((k = strsep(&t, " ")) != NULL)
8920 len += strlen(k) > 1 ? 2 : 0;
8921 free(t0);
8922 *ret = MAX(*ret, len);
8925 return NULL;
8929 * Write keymap section headers, keys, and key info in km to f.
8930 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8931 * wrap control and symbolic keys in guillemets, else use <>.
8933 static const struct got_error *
8934 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8936 int n, len = width;
8938 if (km->keys) {
8939 static const char *u8_glyph[] = {
8940 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8941 "\xe2\x80\xba" /* U+203A (utf8 >) */
8943 char *t0, *t, *k;
8944 int cs, s, first = 1;
8946 cs = got_locale_is_utf8();
8948 t = t0 = strdup(km->keys);
8949 if (t0 == NULL)
8950 return got_error_from_errno("strdup");
8952 len = strlen(km->keys);
8953 while ((k = strsep(&t, " ")) != NULL) {
8954 s = strlen(k) > 1; /* control or symbolic key */
8955 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8956 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8957 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8958 if (n < 0) {
8959 free(t0);
8960 return got_error_from_errno("fprintf");
8962 first = 0;
8963 len += s ? 2 : 0;
8964 *off += n;
8966 free(t0);
8968 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8969 if (n < 0)
8970 return got_error_from_errno("fprintf");
8971 *off += n;
8973 return NULL;
8976 static const struct got_error *
8977 format_help(struct tog_help_view_state *s)
8979 const struct got_error *err = NULL;
8980 off_t off = 0;
8981 int i, max, n, show = s->all;
8982 static const struct tog_key_map km[] = {
8983 #define KEYMAP_(info, type) { NULL, (info), type }
8984 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8985 GENERATE_HELP
8986 #undef KEYMAP_
8987 #undef KEY_
8990 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8991 if (err)
8992 return err;
8994 n = nitems(km);
8995 err = max_key_str(&max, km, n);
8996 if (err)
8997 return err;
8999 for (i = 0; i < n; ++i) {
9000 if (km[i].keys == NULL) {
9001 show = s->all;
9002 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9003 km[i].type == s->type || s->all)
9004 show = 1;
9006 if (show) {
9007 err = format_help_line(&off, s->f, &km[i], max);
9008 if (err)
9009 return err;
9010 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9011 if (err)
9012 return err;
9015 fputc('\n', s->f);
9016 ++off;
9017 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9018 return err;
9021 static const struct got_error *
9022 create_help(struct tog_help_view_state *s)
9024 FILE *f;
9025 const struct got_error *err;
9027 free(s->line_offsets);
9028 s->line_offsets = NULL;
9029 s->nlines = 0;
9031 f = got_opentemp();
9032 if (f == NULL)
9033 return got_error_from_errno("got_opentemp");
9034 s->f = f;
9036 err = format_help(s);
9037 if (err)
9038 return err;
9040 if (s->f && fflush(s->f) != 0)
9041 return got_error_from_errno("fflush");
9043 return NULL;
9046 static const struct got_error *
9047 search_start_help_view(struct tog_view *view)
9049 view->state.help.matched_line = 0;
9050 return NULL;
9053 static void
9054 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9055 size_t *nlines, int **first, int **last, int **match, int **selected)
9057 struct tog_help_view_state *s = &view->state.help;
9059 *f = s->f;
9060 *nlines = s->nlines;
9061 *line_offsets = s->line_offsets;
9062 *match = &s->matched_line;
9063 *first = &s->first_displayed_line;
9064 *last = &s->last_displayed_line;
9065 *selected = &s->selected_line;
9068 static const struct got_error *
9069 show_help_view(struct tog_view *view)
9071 struct tog_help_view_state *s = &view->state.help;
9072 const struct got_error *err;
9073 regmatch_t *regmatch = &view->regmatch;
9074 wchar_t *wline;
9075 char *line;
9076 ssize_t linelen;
9077 size_t linesz = 0;
9078 int width, nprinted = 0, rc = 0;
9079 int eos = view->nlines;
9081 if (view_is_hsplit_top(view))
9082 --eos; /* account for border */
9084 s->lineno = 0;
9085 rewind(s->f);
9086 werase(view->window);
9088 if (view->gline > s->nlines - 1)
9089 view->gline = s->nlines - 1;
9091 err = win_draw_center(view->window, 0, 0, view->ncols,
9092 view_needs_focus_indication(view),
9093 "tog help (press q to return to tog)");
9094 if (err)
9095 return err;
9096 if (eos <= 1)
9097 return NULL;
9098 waddstr(view->window, "\n\n");
9099 eos -= 2;
9101 s->eof = 0;
9102 view->maxx = 0;
9103 line = NULL;
9104 while (eos > 0 && nprinted < eos) {
9105 attr_t attr = 0;
9107 linelen = getline(&line, &linesz, s->f);
9108 if (linelen == -1) {
9109 if (!feof(s->f)) {
9110 free(line);
9111 return got_ferror(s->f, GOT_ERR_IO);
9113 s->eof = 1;
9114 break;
9116 if (++s->lineno < s->first_displayed_line)
9117 continue;
9118 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9119 continue;
9120 if (s->lineno == view->hiline)
9121 attr = A_STANDOUT;
9123 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9124 view->x ? 1 : 0);
9125 if (err) {
9126 free(line);
9127 return err;
9129 view->maxx = MAX(view->maxx, width);
9130 free(wline);
9131 wline = NULL;
9133 if (attr)
9134 wattron(view->window, attr);
9135 if (s->first_displayed_line + nprinted == s->matched_line &&
9136 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9137 err = add_matched_line(&width, line, view->ncols - 1, 0,
9138 view->window, view->x, regmatch);
9139 if (err) {
9140 free(line);
9141 return err;
9143 } else {
9144 int skip;
9146 err = format_line(&wline, &width, &skip, line,
9147 view->x, view->ncols, 0, view->x ? 1 : 0);
9148 if (err) {
9149 free(line);
9150 return err;
9152 waddwstr(view->window, &wline[skip]);
9153 free(wline);
9154 wline = NULL;
9156 if (s->lineno == view->hiline) {
9157 while (width++ < view->ncols)
9158 waddch(view->window, ' ');
9159 } else {
9160 if (width < view->ncols)
9161 waddch(view->window, '\n');
9163 if (attr)
9164 wattroff(view->window, attr);
9165 if (++nprinted == 1)
9166 s->first_displayed_line = s->lineno;
9168 free(line);
9169 if (nprinted > 0)
9170 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9171 else
9172 s->last_displayed_line = s->first_displayed_line;
9174 view_border(view);
9176 if (s->eof) {
9177 rc = waddnstr(view->window,
9178 "See the tog(1) manual page for full documentation",
9179 view->ncols - 1);
9180 if (rc == ERR)
9181 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9182 } else {
9183 wmove(view->window, view->nlines - 1, 0);
9184 wclrtoeol(view->window);
9185 wstandout(view->window);
9186 rc = waddnstr(view->window, "scroll down for more...",
9187 view->ncols - 1);
9188 if (rc == ERR)
9189 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9190 if (getcurx(view->window) < view->ncols - 6) {
9191 rc = wprintw(view->window, "[%.0f%%]",
9192 100.00 * s->last_displayed_line / s->nlines);
9193 if (rc == ERR)
9194 return got_error_msg(GOT_ERR_IO, "wprintw");
9196 wstandend(view->window);
9199 return NULL;
9202 static const struct got_error *
9203 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9205 struct tog_help_view_state *s = &view->state.help;
9206 const struct got_error *err = NULL;
9207 char *line = NULL;
9208 ssize_t linelen;
9209 size_t linesz = 0;
9210 int eos, nscroll;
9212 eos = nscroll = view->nlines;
9213 if (view_is_hsplit_top(view))
9214 --eos; /* border */
9216 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9218 switch (ch) {
9219 case '0':
9220 case '$':
9221 case KEY_RIGHT:
9222 case 'l':
9223 case KEY_LEFT:
9224 case 'h':
9225 horizontal_scroll_input(view, ch);
9226 break;
9227 case 'g':
9228 case KEY_HOME:
9229 s->first_displayed_line = 1;
9230 view->count = 0;
9231 break;
9232 case 'G':
9233 case KEY_END:
9234 view->count = 0;
9235 if (s->eof)
9236 break;
9237 s->first_displayed_line = (s->nlines - eos) + 3;
9238 s->eof = 1;
9239 break;
9240 case 'k':
9241 case KEY_UP:
9242 if (s->first_displayed_line > 1)
9243 --s->first_displayed_line;
9244 else
9245 view->count = 0;
9246 break;
9247 case CTRL('u'):
9248 case 'u':
9249 nscroll /= 2;
9250 /* FALL THROUGH */
9251 case KEY_PPAGE:
9252 case CTRL('b'):
9253 case 'b':
9254 if (s->first_displayed_line == 1) {
9255 view->count = 0;
9256 break;
9258 while (--nscroll > 0 && s->first_displayed_line > 1)
9259 s->first_displayed_line--;
9260 break;
9261 case 'j':
9262 case KEY_DOWN:
9263 case CTRL('n'):
9264 if (!s->eof)
9265 ++s->first_displayed_line;
9266 else
9267 view->count = 0;
9268 break;
9269 case CTRL('d'):
9270 case 'd':
9271 nscroll /= 2;
9272 /* FALL THROUGH */
9273 case KEY_NPAGE:
9274 case CTRL('f'):
9275 case 'f':
9276 case ' ':
9277 if (s->eof) {
9278 view->count = 0;
9279 break;
9281 while (!s->eof && --nscroll > 0) {
9282 linelen = getline(&line, &linesz, s->f);
9283 s->first_displayed_line++;
9284 if (linelen == -1) {
9285 if (feof(s->f))
9286 s->eof = 1;
9287 else
9288 err = got_ferror(s->f, GOT_ERR_IO);
9289 break;
9292 free(line);
9293 break;
9294 default:
9295 view->count = 0;
9296 break;
9299 return err;
9302 static const struct got_error *
9303 close_help_view(struct tog_view *view)
9305 struct tog_help_view_state *s = &view->state.help;
9307 free(s->line_offsets);
9308 s->line_offsets = NULL;
9309 if (fclose(s->f) == EOF)
9310 return got_error_from_errno("fclose");
9312 return NULL;
9315 static const struct got_error *
9316 reset_help_view(struct tog_view *view)
9318 struct tog_help_view_state *s = &view->state.help;
9321 if (s->f && fclose(s->f) == EOF)
9322 return got_error_from_errno("fclose");
9324 wclear(view->window);
9325 view->count = 0;
9326 view->x = 0;
9327 s->all = !s->all;
9328 s->first_displayed_line = 1;
9329 s->last_displayed_line = view->nlines;
9330 s->matched_line = 0;
9332 return create_help(s);
9335 static const struct got_error *
9336 open_help_view(struct tog_view *view, struct tog_view *parent)
9338 const struct got_error *err = NULL;
9339 struct tog_help_view_state *s = &view->state.help;
9341 s->type = (enum tog_keymap_type)parent->type;
9342 s->first_displayed_line = 1;
9343 s->last_displayed_line = view->nlines;
9344 s->selected_line = 1;
9346 view->show = show_help_view;
9347 view->input = input_help_view;
9348 view->reset = reset_help_view;
9349 view->close = close_help_view;
9350 view->search_start = search_start_help_view;
9351 view->search_setup = search_setup_help_view;
9352 view->search_next = search_next_view_match;
9354 err = create_help(s);
9355 return err;
9358 static const struct got_error *
9359 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9360 enum tog_view_type request, int y, int x)
9362 const struct got_error *err = NULL;
9364 *new_view = NULL;
9366 switch (request) {
9367 case TOG_VIEW_DIFF:
9368 if (view->type == TOG_VIEW_LOG) {
9369 struct tog_log_view_state *s = &view->state.log;
9371 err = open_diff_view_for_commit(new_view, y, x,
9372 s->selected_entry->commit, s->selected_entry->id,
9373 view, s->repo);
9374 } else
9375 return got_error_msg(GOT_ERR_NOT_IMPL,
9376 "parent/child view pair not supported");
9377 break;
9378 case TOG_VIEW_BLAME:
9379 if (view->type == TOG_VIEW_TREE) {
9380 struct tog_tree_view_state *s = &view->state.tree;
9382 err = blame_tree_entry(new_view, y, x,
9383 s->selected_entry, &s->parents, s->commit_id,
9384 s->repo);
9385 } else
9386 return got_error_msg(GOT_ERR_NOT_IMPL,
9387 "parent/child view pair not supported");
9388 break;
9389 case TOG_VIEW_LOG:
9390 if (view->type == TOG_VIEW_BLAME)
9391 err = log_annotated_line(new_view, y, x,
9392 view->state.blame.repo, view->state.blame.id_to_log);
9393 else if (view->type == TOG_VIEW_TREE)
9394 err = log_selected_tree_entry(new_view, y, x,
9395 &view->state.tree);
9396 else if (view->type == TOG_VIEW_REF)
9397 err = log_ref_entry(new_view, y, x,
9398 view->state.ref.selected_entry,
9399 view->state.ref.repo);
9400 else
9401 return got_error_msg(GOT_ERR_NOT_IMPL,
9402 "parent/child view pair not supported");
9403 break;
9404 case TOG_VIEW_TREE:
9405 if (view->type == TOG_VIEW_LOG)
9406 err = browse_commit_tree(new_view, y, x,
9407 view->state.log.selected_entry,
9408 view->state.log.in_repo_path,
9409 view->state.log.head_ref_name,
9410 view->state.log.repo);
9411 else if (view->type == TOG_VIEW_REF)
9412 err = browse_ref_tree(new_view, y, x,
9413 view->state.ref.selected_entry,
9414 view->state.ref.repo);
9415 else
9416 return got_error_msg(GOT_ERR_NOT_IMPL,
9417 "parent/child view pair not supported");
9418 break;
9419 case TOG_VIEW_REF:
9420 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9421 if (*new_view == NULL)
9422 return got_error_from_errno("view_open");
9423 if (view->type == TOG_VIEW_LOG)
9424 err = open_ref_view(*new_view, view->state.log.repo);
9425 else if (view->type == TOG_VIEW_TREE)
9426 err = open_ref_view(*new_view, view->state.tree.repo);
9427 else
9428 err = got_error_msg(GOT_ERR_NOT_IMPL,
9429 "parent/child view pair not supported");
9430 if (err)
9431 view_close(*new_view);
9432 break;
9433 case TOG_VIEW_HELP:
9434 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9435 if (*new_view == NULL)
9436 return got_error_from_errno("view_open");
9437 err = open_help_view(*new_view, view);
9438 if (err)
9439 view_close(*new_view);
9440 break;
9441 default:
9442 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9445 return err;
9449 * If view was scrolled down to move the selected line into view when opening a
9450 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9452 static void
9453 offset_selection_up(struct tog_view *view)
9455 switch (view->type) {
9456 case TOG_VIEW_BLAME: {
9457 struct tog_blame_view_state *s = &view->state.blame;
9458 if (s->first_displayed_line == 1) {
9459 s->selected_line = MAX(s->selected_line - view->offset,
9460 1);
9461 break;
9463 if (s->first_displayed_line > view->offset)
9464 s->first_displayed_line -= view->offset;
9465 else
9466 s->first_displayed_line = 1;
9467 s->selected_line += view->offset;
9468 break;
9470 case TOG_VIEW_LOG:
9471 log_scroll_up(&view->state.log, view->offset);
9472 view->state.log.selected += view->offset;
9473 break;
9474 case TOG_VIEW_REF:
9475 ref_scroll_up(&view->state.ref, view->offset);
9476 view->state.ref.selected += view->offset;
9477 break;
9478 case TOG_VIEW_TREE:
9479 tree_scroll_up(&view->state.tree, view->offset);
9480 view->state.tree.selected += view->offset;
9481 break;
9482 default:
9483 break;
9486 view->offset = 0;
9490 * If the selected line is in the section of screen covered by the bottom split,
9491 * scroll down offset lines to move it into view and index its new position.
9493 static const struct got_error *
9494 offset_selection_down(struct tog_view *view)
9496 const struct got_error *err = NULL;
9497 const struct got_error *(*scrolld)(struct tog_view *, int);
9498 int *selected = NULL;
9499 int header, offset;
9501 switch (view->type) {
9502 case TOG_VIEW_BLAME: {
9503 struct tog_blame_view_state *s = &view->state.blame;
9504 header = 3;
9505 scrolld = NULL;
9506 if (s->selected_line > view->nlines - header) {
9507 offset = abs(view->nlines - s->selected_line - header);
9508 s->first_displayed_line += offset;
9509 s->selected_line -= offset;
9510 view->offset = offset;
9512 break;
9514 case TOG_VIEW_LOG: {
9515 struct tog_log_view_state *s = &view->state.log;
9516 scrolld = &log_scroll_down;
9517 header = view_is_parent_view(view) ? 3 : 2;
9518 selected = &s->selected;
9519 break;
9521 case TOG_VIEW_REF: {
9522 struct tog_ref_view_state *s = &view->state.ref;
9523 scrolld = &ref_scroll_down;
9524 header = 3;
9525 selected = &s->selected;
9526 break;
9528 case TOG_VIEW_TREE: {
9529 struct tog_tree_view_state *s = &view->state.tree;
9530 scrolld = &tree_scroll_down;
9531 header = 5;
9532 selected = &s->selected;
9533 break;
9535 default:
9536 selected = NULL;
9537 scrolld = NULL;
9538 header = 0;
9539 break;
9542 if (selected && *selected > view->nlines - header) {
9543 offset = abs(view->nlines - *selected - header);
9544 view->offset = offset;
9545 if (scrolld && offset) {
9546 err = scrolld(view, offset);
9547 *selected -= offset;
9551 return err;
9554 static void
9555 list_commands(FILE *fp)
9557 size_t i;
9559 fprintf(fp, "commands:");
9560 for (i = 0; i < nitems(tog_commands); i++) {
9561 const struct tog_cmd *cmd = &tog_commands[i];
9562 fprintf(fp, " %s", cmd->name);
9564 fputc('\n', fp);
9567 __dead static void
9568 usage(int hflag, int status)
9570 FILE *fp = (status == 0) ? stdout : stderr;
9572 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9573 getprogname());
9574 if (hflag) {
9575 fprintf(fp, "lazy usage: %s path\n", getprogname());
9576 list_commands(fp);
9578 exit(status);
9581 static char **
9582 make_argv(int argc, ...)
9584 va_list ap;
9585 char **argv;
9586 int i;
9588 va_start(ap, argc);
9590 argv = calloc(argc, sizeof(char *));
9591 if (argv == NULL)
9592 err(1, "calloc");
9593 for (i = 0; i < argc; i++) {
9594 argv[i] = strdup(va_arg(ap, char *));
9595 if (argv[i] == NULL)
9596 err(1, "strdup");
9599 va_end(ap);
9600 return argv;
9604 * Try to convert 'tog path' into a 'tog log path' command.
9605 * The user could simply have mistyped the command rather than knowingly
9606 * provided a path. So check whether argv[0] can in fact be resolved
9607 * to a path in the HEAD commit and print a special error if not.
9608 * This hack is for mpi@ <3
9610 static const struct got_error *
9611 tog_log_with_path(int argc, char *argv[])
9613 const struct got_error *error = NULL, *close_err;
9614 const struct tog_cmd *cmd = NULL;
9615 struct got_repository *repo = NULL;
9616 struct got_worktree *worktree = NULL;
9617 struct got_object_id *commit_id = NULL, *id = NULL;
9618 struct got_commit_object *commit = NULL;
9619 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9620 char *commit_id_str = NULL, **cmd_argv = NULL;
9621 int *pack_fds = NULL;
9623 cwd = getcwd(NULL, 0);
9624 if (cwd == NULL)
9625 return got_error_from_errno("getcwd");
9627 error = got_repo_pack_fds_open(&pack_fds);
9628 if (error != NULL)
9629 goto done;
9631 error = got_worktree_open(&worktree, cwd);
9632 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9633 goto done;
9635 if (worktree)
9636 repo_path = strdup(got_worktree_get_repo_path(worktree));
9637 else
9638 repo_path = strdup(cwd);
9639 if (repo_path == NULL) {
9640 error = got_error_from_errno("strdup");
9641 goto done;
9644 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9645 if (error != NULL)
9646 goto done;
9648 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9649 repo, worktree);
9650 if (error)
9651 goto done;
9653 error = tog_load_refs(repo, 0);
9654 if (error)
9655 goto done;
9656 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9657 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9658 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9659 if (error)
9660 goto done;
9662 if (worktree) {
9663 got_worktree_close(worktree);
9664 worktree = NULL;
9667 error = got_object_open_as_commit(&commit, repo, commit_id);
9668 if (error)
9669 goto done;
9671 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9672 if (error) {
9673 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9674 goto done;
9675 fprintf(stderr, "%s: '%s' is no known command or path\n",
9676 getprogname(), argv[0]);
9677 usage(1, 1);
9678 /* not reached */
9681 error = got_object_id_str(&commit_id_str, commit_id);
9682 if (error)
9683 goto done;
9685 cmd = &tog_commands[0]; /* log */
9686 argc = 4;
9687 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9688 error = cmd->cmd_main(argc, cmd_argv);
9689 done:
9690 if (repo) {
9691 close_err = got_repo_close(repo);
9692 if (error == NULL)
9693 error = close_err;
9695 if (commit)
9696 got_object_commit_close(commit);
9697 if (worktree)
9698 got_worktree_close(worktree);
9699 if (pack_fds) {
9700 const struct got_error *pack_err =
9701 got_repo_pack_fds_close(pack_fds);
9702 if (error == NULL)
9703 error = pack_err;
9705 free(id);
9706 free(commit_id_str);
9707 free(commit_id);
9708 free(cwd);
9709 free(repo_path);
9710 free(in_repo_path);
9711 if (cmd_argv) {
9712 int i;
9713 for (i = 0; i < argc; i++)
9714 free(cmd_argv[i]);
9715 free(cmd_argv);
9717 tog_free_refs();
9718 return error;
9721 int
9722 main(int argc, char *argv[])
9724 const struct got_error *io_err, *error = NULL;
9725 const struct tog_cmd *cmd = NULL;
9726 int ch, hflag = 0, Vflag = 0;
9727 char **cmd_argv = NULL;
9728 static const struct option longopts[] = {
9729 { "version", no_argument, NULL, 'V' },
9730 { NULL, 0, NULL, 0}
9732 char *diff_algo_str = NULL;
9733 const char *test_script_path;
9735 setlocale(LC_CTYPE, "");
9738 * Test mode init must happen before pledge() because "tty" will
9739 * not allow TTY-related ioctls to occur via regular files.
9741 test_script_path = getenv("GOT_TOG_TEST");
9742 if (test_script_path != NULL) {
9743 error = init_mock_term(test_script_path);
9744 if (error) {
9745 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9746 return 1;
9750 #if !defined(PROFILE)
9751 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9752 NULL) == -1)
9753 err(1, "pledge");
9754 #endif
9756 if (!isatty(STDIN_FILENO))
9757 errx(1, "standard input is not a tty");
9759 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9760 switch (ch) {
9761 case 'h':
9762 hflag = 1;
9763 break;
9764 case 'V':
9765 Vflag = 1;
9766 break;
9767 default:
9768 usage(hflag, 1);
9769 /* NOTREACHED */
9773 argc -= optind;
9774 argv += optind;
9775 optind = 1;
9776 optreset = 1;
9778 if (Vflag) {
9779 got_version_print_str();
9780 return 0;
9783 if (argc == 0) {
9784 if (hflag)
9785 usage(hflag, 0);
9786 /* Build an argument vector which runs a default command. */
9787 cmd = &tog_commands[0];
9788 argc = 1;
9789 cmd_argv = make_argv(argc, cmd->name);
9790 } else {
9791 size_t i;
9793 /* Did the user specify a command? */
9794 for (i = 0; i < nitems(tog_commands); i++) {
9795 if (strncmp(tog_commands[i].name, argv[0],
9796 strlen(argv[0])) == 0) {
9797 cmd = &tog_commands[i];
9798 break;
9803 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9804 if (diff_algo_str) {
9805 if (strcasecmp(diff_algo_str, "patience") == 0)
9806 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9807 if (strcasecmp(diff_algo_str, "myers") == 0)
9808 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9811 if (cmd == NULL) {
9812 if (argc != 1)
9813 usage(0, 1);
9814 /* No command specified; try log with a path */
9815 error = tog_log_with_path(argc, argv);
9816 } else {
9817 if (hflag)
9818 cmd->cmd_usage();
9819 else
9820 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9823 if (using_mock_io) {
9824 io_err = tog_io_close();
9825 if (error == NULL)
9826 error = io_err;
9828 endwin();
9829 if (cmd_argv) {
9830 int i;
9831 for (i = 0; i < argc; i++)
9832 free(cmd_argv[i]);
9833 free(cmd_argv);
9836 if (error && error->code != GOT_ERR_CANCELLED &&
9837 error->code != GOT_ERR_EOF &&
9838 error->code != GOT_ERR_PRIVSEP_EXIT &&
9839 error->code != GOT_ERR_PRIVSEP_PIPE &&
9840 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9841 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9842 return 0;