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_("/", "Open prompt to enter search term"), \
550 KEY_("n", "Find next line/token matching the current search term"), \
551 KEY_("N", "Find previous line/token matching the current search term"),\
552 KEY_("q", "Quit the focussed view; Quit help screen"), \
553 KEY_("Q", "Quit tog"), \
555 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
556 KEY_("< ,", "Move cursor up one commit"), \
557 KEY_("> .", "Move cursor down one commit"), \
558 KEY_("Enter", "Open diff view of the selected commit"), \
559 KEY_("B", "Reload the log view and toggle display of merged commits"), \
560 KEY_("R", "Open ref view of all repository references"), \
561 KEY_("T", "Display tree view of the repository from the selected" \
562 " commit"), \
563 KEY_("@", "Toggle between displaying author and committer name"), \
564 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
565 KEY_("C-g Backspace", "Cancel current search or log operation"), \
566 KEY_("C-l", "Reload the log view with new commits in the repository"), \
568 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
569 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
570 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
571 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
572 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
573 " data"), \
574 KEY_("(", "Go to the previous file in the diff"), \
575 KEY_(")", "Go to the next file in the diff"), \
576 KEY_("{", "Go to the previous hunk in the diff"), \
577 KEY_("}", "Go to the next hunk in the diff"), \
578 KEY_("[", "Decrease the number of context lines"), \
579 KEY_("]", "Increase the number of context lines"), \
580 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
582 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
583 KEY_("Enter", "Display diff view of the selected line's commit"), \
584 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
585 KEY_("L", "Open log view for the currently selected annotated line"), \
586 KEY_("C", "Reload view with the previously blamed commit"), \
587 KEY_("c", "Reload view with the version of the file found in the" \
588 " selected line's commit"), \
589 KEY_("p", "Reload view with the version of the file found in the" \
590 " selected line's parent commit"), \
592 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
593 KEY_("Enter", "Enter selected directory or open blame view of the" \
594 " selected file"), \
595 KEY_("L", "Open log view for the selected entry"), \
596 KEY_("R", "Open ref view of all repository references"), \
597 KEY_("i", "Show object IDs for all tree entries"), \
598 KEY_("Backspace", "Return to the parent directory"), \
600 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
601 KEY_("Enter", "Display log view of the selected reference"), \
602 KEY_("T", "Display tree view of the selected reference"), \
603 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
604 KEY_("m", "Toggle display of last modified date for each reference"), \
605 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
606 KEY_("C-l", "Reload view with all repository references")
608 struct tog_key_map {
609 const char *keys;
610 const char *info;
611 enum tog_keymap_type type;
612 };
614 /* curses io for tog regress */
615 struct tog_io {
616 FILE *cin;
617 FILE *cout;
618 FILE *f;
619 } tog_io;
620 static int using_mock_io;
622 #define TOG_SCREEN_DUMP "SCREENDUMP"
623 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
624 #define TOG_KEY_SCRDUMP SHRT_MIN
626 /*
627 * We implement two types of views: parent views and child views.
629 * The 'Tab' key switches focus between a parent view and its child view.
630 * Child views are shown side-by-side to their parent view, provided
631 * there is enough screen estate.
633 * When a new view is opened from within a parent view, this new view
634 * becomes a child view of the parent view, replacing any existing child.
636 * When a new view is opened from within a child view, this new view
637 * becomes a parent view which will obscure the views below until the
638 * user quits the new parent view by typing 'q'.
640 * This list of views contains parent views only.
641 * Child views are only pointed to by their parent view.
642 */
643 TAILQ_HEAD(tog_view_list_head, tog_view);
645 struct tog_view {
646 TAILQ_ENTRY(tog_view) entry;
647 WINDOW *window;
648 PANEL *panel;
649 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
650 int resized_y, resized_x; /* begin_y/x based on user resizing */
651 int maxx, x; /* max column and current start column */
652 int lines, cols; /* copies of LINES and COLS */
653 int nscrolled, offset; /* lines scrolled and hsplit line offset */
654 int gline, hiline; /* navigate to and highlight this nG line */
655 int ch, count; /* current keymap and count prefix */
656 int resized; /* set when in a resize event */
657 int focussed; /* Only set on one parent or child view at a time. */
658 int dying;
659 struct tog_view *parent;
660 struct tog_view *child;
662 /*
663 * This flag is initially set on parent views when a new child view
664 * is created. It gets toggled when the 'Tab' key switches focus
665 * between parent and child.
666 * The flag indicates whether focus should be passed on to our child
667 * view if this parent view gets picked for focus after another parent
668 * view was closed. This prevents child views from losing focus in such
669 * situations.
670 */
671 int focus_child;
673 enum tog_view_mode mode;
674 /* type-specific state */
675 enum tog_view_type type;
676 union {
677 struct tog_diff_view_state diff;
678 struct tog_log_view_state log;
679 struct tog_blame_view_state blame;
680 struct tog_tree_view_state tree;
681 struct tog_ref_view_state ref;
682 struct tog_help_view_state help;
683 } state;
685 const struct got_error *(*show)(struct tog_view *);
686 const struct got_error *(*input)(struct tog_view **,
687 struct tog_view *, int);
688 const struct got_error *(*reset)(struct tog_view *);
689 const struct got_error *(*resize)(struct tog_view *, int);
690 const struct got_error *(*close)(struct tog_view *);
692 const struct got_error *(*search_start)(struct tog_view *);
693 const struct got_error *(*search_next)(struct tog_view *);
694 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
695 int **, int **, int **, int **);
696 int search_started;
697 int searching;
698 #define TOG_SEARCH_FORWARD 1
699 #define TOG_SEARCH_BACKWARD 2
700 int search_next_done;
701 #define TOG_SEARCH_HAVE_MORE 1
702 #define TOG_SEARCH_NO_MORE 2
703 #define TOG_SEARCH_HAVE_NONE 3
704 regex_t regex;
705 regmatch_t regmatch;
706 const char *action;
707 };
709 static const struct got_error *open_diff_view(struct tog_view *,
710 struct got_object_id *, struct got_object_id *,
711 const char *, const char *, int, int, int, struct tog_view *,
712 struct got_repository *);
713 static const struct got_error *show_diff_view(struct tog_view *);
714 static const struct got_error *input_diff_view(struct tog_view **,
715 struct tog_view *, int);
716 static const struct got_error *reset_diff_view(struct tog_view *);
717 static const struct got_error* close_diff_view(struct tog_view *);
718 static const struct got_error *search_start_diff_view(struct tog_view *);
719 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
720 size_t *, int **, int **, int **, int **);
721 static const struct got_error *search_next_view_match(struct tog_view *);
723 static const struct got_error *open_log_view(struct tog_view *,
724 struct got_object_id *, struct got_repository *,
725 const char *, const char *, int);
726 static const struct got_error * show_log_view(struct tog_view *);
727 static const struct got_error *input_log_view(struct tog_view **,
728 struct tog_view *, int);
729 static const struct got_error *resize_log_view(struct tog_view *, int);
730 static const struct got_error *close_log_view(struct tog_view *);
731 static const struct got_error *search_start_log_view(struct tog_view *);
732 static const struct got_error *search_next_log_view(struct tog_view *);
734 static const struct got_error *open_blame_view(struct tog_view *, char *,
735 struct got_object_id *, struct got_repository *);
736 static const struct got_error *show_blame_view(struct tog_view *);
737 static const struct got_error *input_blame_view(struct tog_view **,
738 struct tog_view *, int);
739 static const struct got_error *reset_blame_view(struct tog_view *);
740 static const struct got_error *close_blame_view(struct tog_view *);
741 static const struct got_error *search_start_blame_view(struct tog_view *);
742 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
743 size_t *, int **, int **, int **, int **);
745 static const struct got_error *open_tree_view(struct tog_view *,
746 struct got_object_id *, const char *, struct got_repository *);
747 static const struct got_error *show_tree_view(struct tog_view *);
748 static const struct got_error *input_tree_view(struct tog_view **,
749 struct tog_view *, int);
750 static const struct got_error *close_tree_view(struct tog_view *);
751 static const struct got_error *search_start_tree_view(struct tog_view *);
752 static const struct got_error *search_next_tree_view(struct tog_view *);
754 static const struct got_error *open_ref_view(struct tog_view *,
755 struct got_repository *);
756 static const struct got_error *show_ref_view(struct tog_view *);
757 static const struct got_error *input_ref_view(struct tog_view **,
758 struct tog_view *, int);
759 static const struct got_error *close_ref_view(struct tog_view *);
760 static const struct got_error *search_start_ref_view(struct tog_view *);
761 static const struct got_error *search_next_ref_view(struct tog_view *);
763 static const struct got_error *open_help_view(struct tog_view *,
764 struct tog_view *);
765 static const struct got_error *show_help_view(struct tog_view *);
766 static const struct got_error *input_help_view(struct tog_view **,
767 struct tog_view *, int);
768 static const struct got_error *reset_help_view(struct tog_view *);
769 static const struct got_error* close_help_view(struct tog_view *);
770 static const struct got_error *search_start_help_view(struct tog_view *);
771 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
772 size_t *, int **, int **, int **, int **);
774 static volatile sig_atomic_t tog_sigwinch_received;
775 static volatile sig_atomic_t tog_sigpipe_received;
776 static volatile sig_atomic_t tog_sigcont_received;
777 static volatile sig_atomic_t tog_sigint_received;
778 static volatile sig_atomic_t tog_sigterm_received;
780 static void
781 tog_sigwinch(int signo)
783 tog_sigwinch_received = 1;
786 static void
787 tog_sigpipe(int signo)
789 tog_sigpipe_received = 1;
792 static void
793 tog_sigcont(int signo)
795 tog_sigcont_received = 1;
798 static void
799 tog_sigint(int signo)
801 tog_sigint_received = 1;
804 static void
805 tog_sigterm(int signo)
807 tog_sigterm_received = 1;
810 static int
811 tog_fatal_signal_received(void)
813 return (tog_sigpipe_received ||
814 tog_sigint_received || tog_sigterm_received);
817 static const struct got_error *
818 view_close(struct tog_view *view)
820 const struct got_error *err = NULL, *child_err = NULL;
822 if (view->child) {
823 child_err = view_close(view->child);
824 view->child = NULL;
826 if (view->close)
827 err = view->close(view);
828 if (view->panel)
829 del_panel(view->panel);
830 if (view->window)
831 delwin(view->window);
832 free(view);
833 return err ? err : child_err;
836 static struct tog_view *
837 view_open(int nlines, int ncols, int begin_y, int begin_x,
838 enum tog_view_type type)
840 struct tog_view *view = calloc(1, sizeof(*view));
842 if (view == NULL)
843 return NULL;
845 view->type = type;
846 view->lines = LINES;
847 view->cols = COLS;
848 view->nlines = nlines ? nlines : LINES - begin_y;
849 view->ncols = ncols ? ncols : COLS - begin_x;
850 view->begin_y = begin_y;
851 view->begin_x = begin_x;
852 view->window = newwin(nlines, ncols, begin_y, begin_x);
853 if (view->window == NULL) {
854 view_close(view);
855 return NULL;
857 view->panel = new_panel(view->window);
858 if (view->panel == NULL ||
859 set_panel_userptr(view->panel, view) != OK) {
860 view_close(view);
861 return NULL;
864 keypad(view->window, TRUE);
865 return view;
868 static int
869 view_split_begin_x(int begin_x)
871 if (begin_x > 0 || COLS < 120)
872 return 0;
873 return (COLS - MAX(COLS / 2, 80));
876 /* XXX Stub till we decide what to do. */
877 static int
878 view_split_begin_y(int lines)
880 return lines * HSPLIT_SCALE;
883 static const struct got_error *view_resize(struct tog_view *);
885 static const struct got_error *
886 view_splitscreen(struct tog_view *view)
888 const struct got_error *err = NULL;
890 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
891 if (view->resized_y && view->resized_y < view->lines)
892 view->begin_y = view->resized_y;
893 else
894 view->begin_y = view_split_begin_y(view->nlines);
895 view->begin_x = 0;
896 } else if (!view->resized) {
897 if (view->resized_x && view->resized_x < view->cols - 1 &&
898 view->cols > 119)
899 view->begin_x = view->resized_x;
900 else
901 view->begin_x = view_split_begin_x(0);
902 view->begin_y = 0;
904 view->nlines = LINES - view->begin_y;
905 view->ncols = COLS - view->begin_x;
906 view->lines = LINES;
907 view->cols = COLS;
908 err = view_resize(view);
909 if (err)
910 return err;
912 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
913 view->parent->nlines = view->begin_y;
915 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
916 return got_error_from_errno("mvwin");
918 return NULL;
921 static const struct got_error *
922 view_fullscreen(struct tog_view *view)
924 const struct got_error *err = NULL;
926 view->begin_x = 0;
927 view->begin_y = view->resized ? view->begin_y : 0;
928 view->nlines = view->resized ? view->nlines : LINES;
929 view->ncols = COLS;
930 view->lines = LINES;
931 view->cols = COLS;
932 err = view_resize(view);
933 if (err)
934 return err;
936 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
937 return got_error_from_errno("mvwin");
939 return NULL;
942 static int
943 view_is_parent_view(struct tog_view *view)
945 return view->parent == NULL;
948 static int
949 view_is_splitscreen(struct tog_view *view)
951 return view->begin_x > 0 || view->begin_y > 0;
954 static int
955 view_is_fullscreen(struct tog_view *view)
957 return view->nlines == LINES && view->ncols == COLS;
960 static int
961 view_is_hsplit_top(struct tog_view *view)
963 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
964 view_is_splitscreen(view->child);
967 static void
968 view_border(struct tog_view *view)
970 PANEL *panel;
971 const struct tog_view *view_above;
973 if (view->parent)
974 return view_border(view->parent);
976 panel = panel_above(view->panel);
977 if (panel == NULL)
978 return;
980 view_above = panel_userptr(panel);
981 if (view->mode == TOG_VIEW_SPLIT_HRZN)
982 mvwhline(view->window, view_above->begin_y - 1,
983 view->begin_x, got_locale_is_utf8() ?
984 ACS_HLINE : '-', view->ncols);
985 else
986 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
987 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
990 static const struct got_error *view_init_hsplit(struct tog_view *, int);
991 static const struct got_error *request_log_commits(struct tog_view *);
992 static const struct got_error *offset_selection_down(struct tog_view *);
993 static void offset_selection_up(struct tog_view *);
994 static void view_get_split(struct tog_view *, int *, int *);
996 static const struct got_error *
997 view_resize(struct tog_view *view)
999 const struct got_error *err = NULL;
1000 int dif, nlines, ncols;
1002 dif = LINES - view->lines; /* line difference */
1004 if (view->lines > LINES)
1005 nlines = view->nlines - (view->lines - LINES);
1006 else
1007 nlines = view->nlines + (LINES - view->lines);
1008 if (view->cols > COLS)
1009 ncols = view->ncols - (view->cols - COLS);
1010 else
1011 ncols = view->ncols + (COLS - view->cols);
1013 if (view->child) {
1014 int hs = view->child->begin_y;
1016 if (!view_is_fullscreen(view))
1017 view->child->begin_x = view_split_begin_x(view->begin_x);
1018 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1019 view->child->begin_x == 0) {
1020 ncols = COLS;
1022 view_fullscreen(view->child);
1023 if (view->child->focussed)
1024 show_panel(view->child->panel);
1025 else
1026 show_panel(view->panel);
1027 } else {
1028 ncols = view->child->begin_x;
1030 view_splitscreen(view->child);
1031 show_panel(view->child->panel);
1034 * XXX This is ugly and needs to be moved into the above
1035 * logic but "works" for now and my attempts at moving it
1036 * break either 'tab' or 'F' key maps in horizontal splits.
1038 if (hs) {
1039 err = view_splitscreen(view->child);
1040 if (err)
1041 return err;
1042 if (dif < 0) { /* top split decreased */
1043 err = offset_selection_down(view);
1044 if (err)
1045 return err;
1047 view_border(view);
1048 update_panels();
1049 doupdate();
1050 show_panel(view->child->panel);
1051 nlines = view->nlines;
1053 } else if (view->parent == NULL)
1054 ncols = COLS;
1056 if (view->resize && dif > 0) {
1057 err = view->resize(view, dif);
1058 if (err)
1059 return err;
1062 if (wresize(view->window, nlines, ncols) == ERR)
1063 return got_error_from_errno("wresize");
1064 if (replace_panel(view->panel, view->window) == ERR)
1065 return got_error_from_errno("replace_panel");
1066 wclear(view->window);
1068 view->nlines = nlines;
1069 view->ncols = ncols;
1070 view->lines = LINES;
1071 view->cols = COLS;
1073 return NULL;
1076 static const struct got_error *
1077 resize_log_view(struct tog_view *view, int increase)
1079 struct tog_log_view_state *s = &view->state.log;
1080 const struct got_error *err = NULL;
1081 int n = 0;
1083 if (s->selected_entry)
1084 n = s->selected_entry->idx + view->lines - s->selected;
1087 * Request commits to account for the increased
1088 * height so we have enough to populate the view.
1090 if (s->commits->ncommits < n) {
1091 view->nscrolled = n - s->commits->ncommits + increase + 1;
1092 err = request_log_commits(view);
1095 return err;
1098 static void
1099 view_adjust_offset(struct tog_view *view, int n)
1101 if (n == 0)
1102 return;
1104 if (view->parent && view->parent->offset) {
1105 if (view->parent->offset + n >= 0)
1106 view->parent->offset += n;
1107 else
1108 view->parent->offset = 0;
1109 } else if (view->offset) {
1110 if (view->offset - n >= 0)
1111 view->offset -= n;
1112 else
1113 view->offset = 0;
1117 static const struct got_error *
1118 view_resize_split(struct tog_view *view, int resize)
1120 const struct got_error *err = NULL;
1121 struct tog_view *v = NULL;
1123 if (view->parent)
1124 v = view->parent;
1125 else
1126 v = view;
1128 if (!v->child || !view_is_splitscreen(v->child))
1129 return NULL;
1131 v->resized = v->child->resized = resize; /* lock for resize event */
1133 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1134 if (v->child->resized_y)
1135 v->child->begin_y = v->child->resized_y;
1136 if (view->parent)
1137 v->child->begin_y -= resize;
1138 else
1139 v->child->begin_y += resize;
1140 if (v->child->begin_y < 3) {
1141 view->count = 0;
1142 v->child->begin_y = 3;
1143 } else if (v->child->begin_y > LINES - 1) {
1144 view->count = 0;
1145 v->child->begin_y = LINES - 1;
1147 v->ncols = COLS;
1148 v->child->ncols = COLS;
1149 view_adjust_offset(view, resize);
1150 err = view_init_hsplit(v, v->child->begin_y);
1151 if (err)
1152 return err;
1153 v->child->resized_y = v->child->begin_y;
1154 } else {
1155 if (v->child->resized_x)
1156 v->child->begin_x = v->child->resized_x;
1157 if (view->parent)
1158 v->child->begin_x -= resize;
1159 else
1160 v->child->begin_x += resize;
1161 if (v->child->begin_x < 11) {
1162 view->count = 0;
1163 v->child->begin_x = 11;
1164 } else if (v->child->begin_x > COLS - 1) {
1165 view->count = 0;
1166 v->child->begin_x = COLS - 1;
1168 v->child->resized_x = v->child->begin_x;
1171 v->child->mode = v->mode;
1172 v->child->nlines = v->lines - v->child->begin_y;
1173 v->child->ncols = v->cols - v->child->begin_x;
1174 v->focus_child = 1;
1176 err = view_fullscreen(v);
1177 if (err)
1178 return err;
1179 err = view_splitscreen(v->child);
1180 if (err)
1181 return err;
1183 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1184 err = offset_selection_down(v->child);
1185 if (err)
1186 return err;
1189 if (v->resize)
1190 err = v->resize(v, 0);
1191 else if (v->child->resize)
1192 err = v->child->resize(v->child, 0);
1194 v->resized = v->child->resized = 0;
1196 return err;
1199 static void
1200 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1202 struct tog_view *v = src->child ? src->child : src;
1204 dst->resized_x = v->resized_x;
1205 dst->resized_y = v->resized_y;
1208 static const struct got_error *
1209 view_close_child(struct tog_view *view)
1211 const struct got_error *err = NULL;
1213 if (view->child == NULL)
1214 return NULL;
1216 err = view_close(view->child);
1217 view->child = NULL;
1218 return err;
1221 static const struct got_error *
1222 view_set_child(struct tog_view *view, struct tog_view *child)
1224 const struct got_error *err = NULL;
1226 view->child = child;
1227 child->parent = view;
1229 err = view_resize(view);
1230 if (err)
1231 return err;
1233 if (view->child->resized_x || view->child->resized_y)
1234 err = view_resize_split(view, 0);
1236 return err;
1239 static const struct got_error *view_dispatch_request(struct tog_view **,
1240 struct tog_view *, enum tog_view_type, int, int);
1242 static const struct got_error *
1243 view_request_new(struct tog_view **requested, struct tog_view *view,
1244 enum tog_view_type request)
1246 struct tog_view *new_view = NULL;
1247 const struct got_error *err;
1248 int y = 0, x = 0;
1250 *requested = NULL;
1252 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1253 view_get_split(view, &y, &x);
1255 err = view_dispatch_request(&new_view, view, request, y, x);
1256 if (err)
1257 return err;
1259 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1260 request != TOG_VIEW_HELP) {
1261 err = view_init_hsplit(view, y);
1262 if (err)
1263 return err;
1266 view->focussed = 0;
1267 new_view->focussed = 1;
1268 new_view->mode = view->mode;
1269 new_view->nlines = request == TOG_VIEW_HELP ?
1270 view->lines : view->lines - y;
1272 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1273 view_transfer_size(new_view, view);
1274 err = view_close_child(view);
1275 if (err)
1276 return err;
1277 err = view_set_child(view, new_view);
1278 if (err)
1279 return err;
1280 view->focus_child = 1;
1281 } else
1282 *requested = new_view;
1284 return NULL;
1287 static void
1288 tog_resizeterm(void)
1290 int cols, lines;
1291 struct winsize size;
1293 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1294 cols = 80; /* Default */
1295 lines = 24;
1296 } else {
1297 cols = size.ws_col;
1298 lines = size.ws_row;
1300 resize_term(lines, cols);
1303 static const struct got_error *
1304 view_search_start(struct tog_view *view, int fast_refresh)
1306 const struct got_error *err = NULL;
1307 struct tog_view *v = view;
1308 char pattern[1024];
1309 int ret;
1311 if (view->search_started) {
1312 regfree(&view->regex);
1313 view->searching = 0;
1314 memset(&view->regmatch, 0, sizeof(view->regmatch));
1316 view->search_started = 0;
1318 if (view->nlines < 1)
1319 return NULL;
1321 if (view_is_hsplit_top(view))
1322 v = view->child;
1323 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1324 v = view->parent;
1326 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1327 wclrtoeol(v->window);
1329 nodelay(v->window, FALSE); /* block for search term input */
1330 nocbreak();
1331 echo();
1332 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1333 wrefresh(v->window);
1334 cbreak();
1335 noecho();
1336 nodelay(v->window, TRUE);
1337 if (!fast_refresh && !using_mock_io)
1338 halfdelay(10);
1339 if (ret == ERR)
1340 return NULL;
1342 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1343 err = view->search_start(view);
1344 if (err) {
1345 regfree(&view->regex);
1346 return err;
1348 view->search_started = 1;
1349 view->searching = TOG_SEARCH_FORWARD;
1350 view->search_next_done = 0;
1351 view->search_next(view);
1354 return NULL;
1357 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1358 static const struct got_error *
1359 switch_split(struct tog_view *view)
1361 const struct got_error *err = NULL;
1362 struct tog_view *v = NULL;
1364 if (view->parent)
1365 v = view->parent;
1366 else
1367 v = view;
1369 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1370 v->mode = TOG_VIEW_SPLIT_VERT;
1371 else
1372 v->mode = TOG_VIEW_SPLIT_HRZN;
1374 if (!v->child)
1375 return NULL;
1376 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1377 v->mode = TOG_VIEW_SPLIT_NONE;
1379 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1380 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1381 v->child->begin_y = v->child->resized_y;
1382 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1383 v->child->begin_x = v->child->resized_x;
1386 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1387 v->ncols = COLS;
1388 v->child->ncols = COLS;
1389 v->child->nscrolled = LINES - v->child->nlines;
1391 err = view_init_hsplit(v, v->child->begin_y);
1392 if (err)
1393 return err;
1395 v->child->mode = v->mode;
1396 v->child->nlines = v->lines - v->child->begin_y;
1397 v->focus_child = 1;
1399 err = view_fullscreen(v);
1400 if (err)
1401 return err;
1402 err = view_splitscreen(v->child);
1403 if (err)
1404 return err;
1406 if (v->mode == TOG_VIEW_SPLIT_NONE)
1407 v->mode = TOG_VIEW_SPLIT_VERT;
1408 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1409 err = offset_selection_down(v);
1410 if (err)
1411 return err;
1412 err = offset_selection_down(v->child);
1413 if (err)
1414 return err;
1415 } else {
1416 offset_selection_up(v);
1417 offset_selection_up(v->child);
1419 if (v->resize)
1420 err = v->resize(v, 0);
1421 else if (v->child->resize)
1422 err = v->child->resize(v->child, 0);
1424 return err;
1428 * Strip trailing whitespace from str starting at byte *n;
1429 * if *n < 0, use strlen(str). Return new str length in *n.
1431 static void
1432 strip_trailing_ws(char *str, int *n)
1434 size_t x = *n;
1436 if (str == NULL || *str == '\0')
1437 return;
1439 if (x < 0)
1440 x = strlen(str);
1442 while (x-- > 0 && isspace((unsigned char)str[x]))
1443 str[x] = '\0';
1445 *n = x + 1;
1449 * Extract visible substring of line y from the curses screen
1450 * and strip trailing whitespace. If vline is set and locale is
1451 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1452 * character is written out as 'x'. Write the line to file f.
1454 static const struct got_error *
1455 view_write_line(FILE *f, int y, int vline)
1457 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1458 int r, w;
1460 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1461 if (r == ERR)
1462 return got_error_fmt(GOT_ERR_RANGE,
1463 "failed to extract line %d", y);
1466 * In some views, lines are padded with blanks to COLS width.
1467 * Strip them so we can diff without the -b flag when testing.
1469 strip_trailing_ws(line, &r);
1471 if (vline > 0 && got_locale_is_utf8())
1472 line[vline] = '|';
1474 w = fprintf(f, "%s\n", line);
1475 if (w != r + 1) /* \n */
1476 return got_ferror(f, GOT_ERR_IO);
1478 return NULL;
1482 * Capture the visible curses screen by writing each line to the
1483 * file at the path set via the TOG_SCR_DUMP environment variable.
1485 static const struct got_error *
1486 screendump(struct tog_view *view)
1488 const struct got_error *err;
1489 FILE *f = NULL;
1490 const char *path;
1491 int i;
1493 path = getenv("TOG_SCR_DUMP");
1494 if (path == NULL || *path == '\0')
1495 return got_error_msg(GOT_ERR_BAD_PATH,
1496 "TOG_SCR_DUMP path not set to capture screen dump");
1497 f = fopen(path, "wex");
1498 if (f == NULL)
1499 return got_error_from_errno_fmt("fopen: %s", path);
1501 if ((view->child && view->child->begin_x) ||
1502 (view->parent && view->begin_x)) {
1503 int ncols = view->child ? view->ncols : view->parent->ncols;
1505 /* vertical splitscreen */
1506 for (i = 0; i < view->nlines; ++i) {
1507 err = view_write_line(f, i, ncols - 1);
1508 if (err)
1509 goto done;
1511 } else {
1512 int hline = 0;
1514 /* fullscreen or horizontal splitscreen */
1515 if ((view->child && view->child->begin_y) ||
1516 (view->parent && view->begin_y)) /* hsplit */
1517 hline = view->child ?
1518 view->child->begin_y : view->begin_y;
1520 for (i = 0; i < view->lines; i++) {
1521 if (hline && got_locale_is_utf8() && i == hline - 1) {
1522 int c;
1524 /* ACS_HLINE writes out as 'q', overwrite it */
1525 for (c = 0; c < view->cols; ++c)
1526 fputc('-', f);
1527 fputc('\n', f);
1528 continue;
1531 err = view_write_line(f, i, 0);
1532 if (err)
1533 goto done;
1537 done:
1538 if (f && fclose(f) == EOF && err == NULL)
1539 err = got_ferror(f, GOT_ERR_IO);
1540 return err;
1544 * Compute view->count from numeric input. Assign total to view->count and
1545 * return first non-numeric key entered.
1547 static int
1548 get_compound_key(struct tog_view *view, int c)
1550 struct tog_view *v = view;
1551 int x, n = 0;
1553 if (view_is_hsplit_top(view))
1554 v = view->child;
1555 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1556 v = view->parent;
1558 view->count = 0;
1559 cbreak(); /* block for input */
1560 nodelay(view->window, FALSE);
1561 wmove(v->window, v->nlines - 1, 0);
1562 wclrtoeol(v->window);
1563 waddch(v->window, ':');
1565 do {
1566 x = getcurx(v->window);
1567 if (x != ERR && x < view->ncols) {
1568 waddch(v->window, c);
1569 wrefresh(v->window);
1573 * Don't overflow. Max valid request should be the greatest
1574 * between the longest and total lines; cap at 10 million.
1576 if (n >= 9999999)
1577 n = 9999999;
1578 else
1579 n = n * 10 + (c - '0');
1580 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1582 if (c == 'G' || c == 'g') { /* nG key map */
1583 view->gline = view->hiline = n;
1584 n = 0;
1585 c = 0;
1588 /* Massage excessive or inapplicable values at the input handler. */
1589 view->count = n;
1591 return c;
1594 static void
1595 action_report(struct tog_view *view)
1597 struct tog_view *v = view;
1599 if (view_is_hsplit_top(view))
1600 v = view->child;
1601 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1602 v = view->parent;
1604 wmove(v->window, v->nlines - 1, 0);
1605 wclrtoeol(v->window);
1606 wprintw(v->window, ":%s", view->action);
1607 wrefresh(v->window);
1610 * Clear action status report. Only clear in blame view
1611 * once annotating is complete, otherwise it's too fast.
1613 if (view->type == TOG_VIEW_BLAME) {
1614 if (view->state.blame.blame_complete)
1615 view->action = NULL;
1616 } else
1617 view->action = NULL;
1621 * Read the next line from the test script and assign
1622 * key instruction to *ch. If at EOF, set the *done flag.
1624 static const struct got_error *
1625 tog_read_script_key(FILE *script, int *ch, int *done)
1627 const struct got_error *err = NULL;
1628 char *line = NULL;
1629 size_t linesz = 0;
1631 if (getline(&line, &linesz, script) == -1) {
1632 if (feof(script)) {
1633 *done = 1;
1634 goto done;
1635 } else {
1636 err = got_ferror(script, GOT_ERR_IO);
1637 goto done;
1639 } else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1640 *ch = KEY_ENTER;
1641 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1642 *ch = KEY_RIGHT;
1643 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1644 *ch = KEY_LEFT;
1645 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1646 *ch = KEY_DOWN;
1647 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1648 *ch = KEY_UP;
1649 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1650 *ch = TOG_KEY_SCRDUMP;
1651 else
1652 *ch = *line;
1654 done:
1655 free(line);
1656 return err;
1659 static const struct got_error *
1660 view_input(struct tog_view **new, int *done, struct tog_view *view,
1661 struct tog_view_list_head *views, int fast_refresh)
1663 const struct got_error *err = NULL;
1664 struct tog_view *v;
1665 int ch, errcode;
1667 *new = NULL;
1669 if (view->action)
1670 action_report(view);
1672 /* Clear "no matches" indicator. */
1673 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1674 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1675 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1676 view->count = 0;
1679 if (view->searching && !view->search_next_done) {
1680 errcode = pthread_mutex_unlock(&tog_mutex);
1681 if (errcode)
1682 return got_error_set_errno(errcode,
1683 "pthread_mutex_unlock");
1684 sched_yield();
1685 errcode = pthread_mutex_lock(&tog_mutex);
1686 if (errcode)
1687 return got_error_set_errno(errcode,
1688 "pthread_mutex_lock");
1689 view->search_next(view);
1690 return NULL;
1693 /* Allow threads to make progress while we are waiting for input. */
1694 errcode = pthread_mutex_unlock(&tog_mutex);
1695 if (errcode)
1696 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1698 if (using_mock_io) {
1699 err = tog_read_script_key(tog_io.f, &ch, done);
1700 if (err)
1701 return err;
1702 } else if (view->count && --view->count) {
1703 cbreak();
1704 nodelay(view->window, TRUE);
1705 ch = wgetch(view->window);
1706 /* let C-g or backspace abort unfinished count */
1707 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1708 view->count = 0;
1709 else
1710 ch = view->ch;
1711 } else {
1712 ch = wgetch(view->window);
1713 if (ch >= '1' && ch <= '9')
1714 view->ch = ch = get_compound_key(view, ch);
1716 if (view->hiline && ch != ERR && ch != 0)
1717 view->hiline = 0; /* key pressed, clear line highlight */
1718 nodelay(view->window, TRUE);
1719 errcode = pthread_mutex_lock(&tog_mutex);
1720 if (errcode)
1721 return got_error_set_errno(errcode, "pthread_mutex_lock");
1723 if (tog_sigwinch_received || tog_sigcont_received) {
1724 tog_resizeterm();
1725 tog_sigwinch_received = 0;
1726 tog_sigcont_received = 0;
1727 TAILQ_FOREACH(v, views, entry) {
1728 err = view_resize(v);
1729 if (err)
1730 return err;
1731 err = v->input(new, v, KEY_RESIZE);
1732 if (err)
1733 return err;
1734 if (v->child) {
1735 err = view_resize(v->child);
1736 if (err)
1737 return err;
1738 err = v->child->input(new, v->child,
1739 KEY_RESIZE);
1740 if (err)
1741 return err;
1742 if (v->child->resized_x || v->child->resized_y) {
1743 err = view_resize_split(v, 0);
1744 if (err)
1745 return err;
1751 switch (ch) {
1752 case '?':
1753 case 'H':
1754 case KEY_F(1):
1755 if (view->type == TOG_VIEW_HELP)
1756 err = view->reset(view);
1757 else
1758 err = view_request_new(new, view, TOG_VIEW_HELP);
1759 break;
1760 case '\t':
1761 view->count = 0;
1762 if (view->child) {
1763 view->focussed = 0;
1764 view->child->focussed = 1;
1765 view->focus_child = 1;
1766 } else if (view->parent) {
1767 view->focussed = 0;
1768 view->parent->focussed = 1;
1769 view->parent->focus_child = 0;
1770 if (!view_is_splitscreen(view)) {
1771 if (view->parent->resize) {
1772 err = view->parent->resize(view->parent,
1773 0);
1774 if (err)
1775 return err;
1777 offset_selection_up(view->parent);
1778 err = view_fullscreen(view->parent);
1779 if (err)
1780 return err;
1783 break;
1784 case 'q':
1785 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1786 if (view->parent->resize) {
1787 /* might need more commits to fill fullscreen */
1788 err = view->parent->resize(view->parent, 0);
1789 if (err)
1790 break;
1792 offset_selection_up(view->parent);
1794 err = view->input(new, view, ch);
1795 view->dying = 1;
1796 break;
1797 case 'Q':
1798 *done = 1;
1799 break;
1800 case 'F':
1801 view->count = 0;
1802 if (view_is_parent_view(view)) {
1803 if (view->child == NULL)
1804 break;
1805 if (view_is_splitscreen(view->child)) {
1806 view->focussed = 0;
1807 view->child->focussed = 1;
1808 err = view_fullscreen(view->child);
1809 } else {
1810 err = view_splitscreen(view->child);
1811 if (!err)
1812 err = view_resize_split(view, 0);
1814 if (err)
1815 break;
1816 err = view->child->input(new, view->child,
1817 KEY_RESIZE);
1818 } else {
1819 if (view_is_splitscreen(view)) {
1820 view->parent->focussed = 0;
1821 view->focussed = 1;
1822 err = view_fullscreen(view);
1823 } else {
1824 err = view_splitscreen(view);
1825 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1826 err = view_resize(view->parent);
1827 if (!err)
1828 err = view_resize_split(view, 0);
1830 if (err)
1831 break;
1832 err = view->input(new, view, KEY_RESIZE);
1834 if (err)
1835 break;
1836 if (view->resize) {
1837 err = view->resize(view, 0);
1838 if (err)
1839 break;
1841 if (view->parent)
1842 err = offset_selection_down(view->parent);
1843 if (!err)
1844 err = offset_selection_down(view);
1845 break;
1846 case 'S':
1847 view->count = 0;
1848 err = switch_split(view);
1849 break;
1850 case '-':
1851 err = view_resize_split(view, -1);
1852 break;
1853 case '+':
1854 err = view_resize_split(view, 1);
1855 break;
1856 case KEY_RESIZE:
1857 break;
1858 case '/':
1859 view->count = 0;
1860 if (view->search_start)
1861 view_search_start(view, fast_refresh);
1862 else
1863 err = view->input(new, view, ch);
1864 break;
1865 case 'N':
1866 case 'n':
1867 if (view->search_started && view->search_next) {
1868 view->searching = (ch == 'n' ?
1869 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1870 view->search_next_done = 0;
1871 view->search_next(view);
1872 } else
1873 err = view->input(new, view, ch);
1874 break;
1875 case 'A':
1876 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1877 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1878 view->action = "Patience diff algorithm";
1879 } else {
1880 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1881 view->action = "Myers diff algorithm";
1883 TAILQ_FOREACH(v, views, entry) {
1884 if (v->reset) {
1885 err = v->reset(v);
1886 if (err)
1887 return err;
1889 if (v->child && v->child->reset) {
1890 err = v->child->reset(v->child);
1891 if (err)
1892 return err;
1895 break;
1896 case TOG_KEY_SCRDUMP:
1897 err = screendump(view);
1898 break;
1899 default:
1900 err = view->input(new, view, ch);
1901 break;
1904 return err;
1907 static int
1908 view_needs_focus_indication(struct tog_view *view)
1910 if (view_is_parent_view(view)) {
1911 if (view->child == NULL || view->child->focussed)
1912 return 0;
1913 if (!view_is_splitscreen(view->child))
1914 return 0;
1915 } else if (!view_is_splitscreen(view))
1916 return 0;
1918 return view->focussed;
1921 static const struct got_error *
1922 tog_io_close(void)
1924 const struct got_error *err = NULL;
1926 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1927 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1928 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1929 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1930 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1931 err = got_ferror(tog_io.f, GOT_ERR_IO);
1933 return err;
1936 static const struct got_error *
1937 view_loop(struct tog_view *view)
1939 const struct got_error *err = NULL;
1940 struct tog_view_list_head views;
1941 struct tog_view *new_view;
1942 char *mode;
1943 int fast_refresh = 10;
1944 int done = 0, errcode;
1946 mode = getenv("TOG_VIEW_SPLIT_MODE");
1947 if (!mode || !(*mode == 'h' || *mode == 'H'))
1948 view->mode = TOG_VIEW_SPLIT_VERT;
1949 else
1950 view->mode = TOG_VIEW_SPLIT_HRZN;
1952 errcode = pthread_mutex_lock(&tog_mutex);
1953 if (errcode)
1954 return got_error_set_errno(errcode, "pthread_mutex_lock");
1956 TAILQ_INIT(&views);
1957 TAILQ_INSERT_HEAD(&views, view, entry);
1959 view->focussed = 1;
1960 err = view->show(view);
1961 if (err)
1962 return err;
1963 update_panels();
1964 doupdate();
1965 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1966 !tog_fatal_signal_received()) {
1967 /* Refresh fast during initialization, then become slower. */
1968 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1969 halfdelay(10); /* switch to once per second */
1971 err = view_input(&new_view, &done, view, &views, fast_refresh);
1972 if (err)
1973 break;
1975 if (view->dying && view == TAILQ_FIRST(&views) &&
1976 TAILQ_NEXT(view, entry) == NULL)
1977 done = 1;
1978 if (done) {
1979 struct tog_view *v;
1982 * When we quit, scroll the screen up a single line
1983 * so we don't lose any information.
1985 TAILQ_FOREACH(v, &views, entry) {
1986 wmove(v->window, 0, 0);
1987 wdeleteln(v->window);
1988 wnoutrefresh(v->window);
1989 if (v->child && !view_is_fullscreen(v)) {
1990 wmove(v->child->window, 0, 0);
1991 wdeleteln(v->child->window);
1992 wnoutrefresh(v->child->window);
1995 doupdate();
1998 if (view->dying) {
1999 struct tog_view *v, *prev = NULL;
2001 if (view_is_parent_view(view))
2002 prev = TAILQ_PREV(view, tog_view_list_head,
2003 entry);
2004 else if (view->parent)
2005 prev = view->parent;
2007 if (view->parent) {
2008 view->parent->child = NULL;
2009 view->parent->focus_child = 0;
2010 /* Restore fullscreen line height. */
2011 view->parent->nlines = view->parent->lines;
2012 err = view_resize(view->parent);
2013 if (err)
2014 break;
2015 /* Make resized splits persist. */
2016 view_transfer_size(view->parent, view);
2017 } else
2018 TAILQ_REMOVE(&views, view, entry);
2020 err = view_close(view);
2021 if (err)
2022 goto done;
2024 view = NULL;
2025 TAILQ_FOREACH(v, &views, entry) {
2026 if (v->focussed)
2027 break;
2029 if (view == NULL && new_view == NULL) {
2030 /* No view has focus. Try to pick one. */
2031 if (prev)
2032 view = prev;
2033 else if (!TAILQ_EMPTY(&views)) {
2034 view = TAILQ_LAST(&views,
2035 tog_view_list_head);
2037 if (view) {
2038 if (view->focus_child) {
2039 view->child->focussed = 1;
2040 view = view->child;
2041 } else
2042 view->focussed = 1;
2046 if (new_view) {
2047 struct tog_view *v, *t;
2048 /* Only allow one parent view per type. */
2049 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2050 if (v->type != new_view->type)
2051 continue;
2052 TAILQ_REMOVE(&views, v, entry);
2053 err = view_close(v);
2054 if (err)
2055 goto done;
2056 break;
2058 TAILQ_INSERT_TAIL(&views, new_view, entry);
2059 view = new_view;
2061 if (view && !done) {
2062 if (view_is_parent_view(view)) {
2063 if (view->child && view->child->focussed)
2064 view = view->child;
2065 } else {
2066 if (view->parent && view->parent->focussed)
2067 view = view->parent;
2069 show_panel(view->panel);
2070 if (view->child && view_is_splitscreen(view->child))
2071 show_panel(view->child->panel);
2072 if (view->parent && view_is_splitscreen(view)) {
2073 err = view->parent->show(view->parent);
2074 if (err)
2075 goto done;
2077 err = view->show(view);
2078 if (err)
2079 goto done;
2080 if (view->child) {
2081 err = view->child->show(view->child);
2082 if (err)
2083 goto done;
2085 update_panels();
2086 doupdate();
2089 done:
2090 while (!TAILQ_EMPTY(&views)) {
2091 const struct got_error *close_err;
2092 view = TAILQ_FIRST(&views);
2093 TAILQ_REMOVE(&views, view, entry);
2094 close_err = view_close(view);
2095 if (close_err && err == NULL)
2096 err = close_err;
2099 errcode = pthread_mutex_unlock(&tog_mutex);
2100 if (errcode && err == NULL)
2101 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2103 return err;
2106 __dead static void
2107 usage_log(void)
2109 endwin();
2110 fprintf(stderr,
2111 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2112 getprogname());
2113 exit(1);
2116 /* Create newly allocated wide-character string equivalent to a byte string. */
2117 static const struct got_error *
2118 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2120 char *vis = NULL;
2121 const struct got_error *err = NULL;
2123 *ws = NULL;
2124 *wlen = mbstowcs(NULL, s, 0);
2125 if (*wlen == (size_t)-1) {
2126 int vislen;
2127 if (errno != EILSEQ)
2128 return got_error_from_errno("mbstowcs");
2130 /* byte string invalid in current encoding; try to "fix" it */
2131 err = got_mbsavis(&vis, &vislen, s);
2132 if (err)
2133 return err;
2134 *wlen = mbstowcs(NULL, vis, 0);
2135 if (*wlen == (size_t)-1) {
2136 err = got_error_from_errno("mbstowcs"); /* give up */
2137 goto done;
2141 *ws = calloc(*wlen + 1, sizeof(**ws));
2142 if (*ws == NULL) {
2143 err = got_error_from_errno("calloc");
2144 goto done;
2147 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2148 err = got_error_from_errno("mbstowcs");
2149 done:
2150 free(vis);
2151 if (err) {
2152 free(*ws);
2153 *ws = NULL;
2154 *wlen = 0;
2156 return err;
2159 static const struct got_error *
2160 expand_tab(char **ptr, const char *src)
2162 char *dst;
2163 size_t len, n, idx = 0, sz = 0;
2165 *ptr = NULL;
2166 n = len = strlen(src);
2167 dst = malloc(n + 1);
2168 if (dst == NULL)
2169 return got_error_from_errno("malloc");
2171 while (idx < len && src[idx]) {
2172 const char c = src[idx];
2174 if (c == '\t') {
2175 size_t nb = TABSIZE - sz % TABSIZE;
2176 char *p;
2178 p = realloc(dst, n + nb);
2179 if (p == NULL) {
2180 free(dst);
2181 return got_error_from_errno("realloc");
2184 dst = p;
2185 n += nb;
2186 memset(dst + sz, ' ', nb);
2187 sz += nb;
2188 } else
2189 dst[sz++] = src[idx];
2190 ++idx;
2193 dst[sz] = '\0';
2194 *ptr = dst;
2195 return NULL;
2199 * Advance at most n columns from wline starting at offset off.
2200 * Return the index to the first character after the span operation.
2201 * Return the combined column width of all spanned wide character in
2202 * *rcol.
2204 static int
2205 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2207 int width, i, cols = 0;
2209 if (n == 0) {
2210 *rcol = cols;
2211 return off;
2214 for (i = off; wline[i] != L'\0'; ++i) {
2215 if (wline[i] == L'\t')
2216 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2217 else
2218 width = wcwidth(wline[i]);
2220 if (width == -1) {
2221 width = 1;
2222 wline[i] = L'.';
2225 if (cols + width > n)
2226 break;
2227 cols += width;
2230 *rcol = cols;
2231 return i;
2235 * Format a line for display, ensuring that it won't overflow a width limit.
2236 * With scrolling, the width returned refers to the scrolled version of the
2237 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2239 static const struct got_error *
2240 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2241 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2243 const struct got_error *err = NULL;
2244 int cols;
2245 wchar_t *wline = NULL;
2246 char *exstr = NULL;
2247 size_t wlen;
2248 int i, scrollx;
2250 *wlinep = NULL;
2251 *widthp = 0;
2253 if (expand) {
2254 err = expand_tab(&exstr, line);
2255 if (err)
2256 return err;
2259 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2260 free(exstr);
2261 if (err)
2262 return err;
2264 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2266 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2267 wline[wlen - 1] = L'\0';
2268 wlen--;
2270 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2271 wline[wlen - 1] = L'\0';
2272 wlen--;
2275 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2276 wline[i] = L'\0';
2278 if (widthp)
2279 *widthp = cols;
2280 if (scrollxp)
2281 *scrollxp = scrollx;
2282 if (err)
2283 free(wline);
2284 else
2285 *wlinep = wline;
2286 return err;
2289 static const struct got_error*
2290 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2291 struct got_object_id *id, struct got_repository *repo)
2293 static const struct got_error *err = NULL;
2294 struct got_reflist_entry *re;
2295 char *s;
2296 const char *name;
2298 *refs_str = NULL;
2300 TAILQ_FOREACH(re, refs, entry) {
2301 struct got_tag_object *tag = NULL;
2302 struct got_object_id *ref_id;
2303 int cmp;
2305 name = got_ref_get_name(re->ref);
2306 if (strcmp(name, GOT_REF_HEAD) == 0)
2307 continue;
2308 if (strncmp(name, "refs/", 5) == 0)
2309 name += 5;
2310 if (strncmp(name, "got/", 4) == 0 &&
2311 strncmp(name, "got/backup/", 11) != 0)
2312 continue;
2313 if (strncmp(name, "heads/", 6) == 0)
2314 name += 6;
2315 if (strncmp(name, "remotes/", 8) == 0) {
2316 name += 8;
2317 s = strstr(name, "/" GOT_REF_HEAD);
2318 if (s != NULL && s[strlen(s)] == '\0')
2319 continue;
2321 err = got_ref_resolve(&ref_id, repo, re->ref);
2322 if (err)
2323 break;
2324 if (strncmp(name, "tags/", 5) == 0) {
2325 err = got_object_open_as_tag(&tag, repo, ref_id);
2326 if (err) {
2327 if (err->code != GOT_ERR_OBJ_TYPE) {
2328 free(ref_id);
2329 break;
2331 /* Ref points at something other than a tag. */
2332 err = NULL;
2333 tag = NULL;
2336 cmp = got_object_id_cmp(tag ?
2337 got_object_tag_get_object_id(tag) : ref_id, id);
2338 free(ref_id);
2339 if (tag)
2340 got_object_tag_close(tag);
2341 if (cmp != 0)
2342 continue;
2343 s = *refs_str;
2344 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2345 s ? ", " : "", name) == -1) {
2346 err = got_error_from_errno("asprintf");
2347 free(s);
2348 *refs_str = NULL;
2349 break;
2351 free(s);
2354 return err;
2357 static const struct got_error *
2358 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2359 int col_tab_align)
2361 char *smallerthan;
2363 smallerthan = strchr(author, '<');
2364 if (smallerthan && smallerthan[1] != '\0')
2365 author = smallerthan + 1;
2366 author[strcspn(author, "@>")] = '\0';
2367 return format_line(wauthor, author_width, NULL, author, 0, limit,
2368 col_tab_align, 0);
2371 static const struct got_error *
2372 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2373 struct got_object_id *id, const size_t date_display_cols,
2374 int author_display_cols)
2376 struct tog_log_view_state *s = &view->state.log;
2377 const struct got_error *err = NULL;
2378 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2379 char *logmsg0 = NULL, *logmsg = NULL;
2380 char *author = NULL;
2381 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2382 int author_width, logmsg_width;
2383 char *newline, *line = NULL;
2384 int col, limit, scrollx;
2385 const int avail = view->ncols;
2386 struct tm tm;
2387 time_t committer_time;
2388 struct tog_color *tc;
2390 committer_time = got_object_commit_get_committer_time(commit);
2391 if (gmtime_r(&committer_time, &tm) == NULL)
2392 return got_error_from_errno("gmtime_r");
2393 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2394 return got_error(GOT_ERR_NO_SPACE);
2396 if (avail <= date_display_cols)
2397 limit = MIN(sizeof(datebuf) - 1, avail);
2398 else
2399 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2400 tc = get_color(&s->colors, TOG_COLOR_DATE);
2401 if (tc)
2402 wattr_on(view->window,
2403 COLOR_PAIR(tc->colorpair), NULL);
2404 waddnstr(view->window, datebuf, limit);
2405 if (tc)
2406 wattr_off(view->window,
2407 COLOR_PAIR(tc->colorpair), NULL);
2408 col = limit;
2409 if (col > avail)
2410 goto done;
2412 if (avail >= 120) {
2413 char *id_str;
2414 err = got_object_id_str(&id_str, id);
2415 if (err)
2416 goto done;
2417 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2418 if (tc)
2419 wattr_on(view->window,
2420 COLOR_PAIR(tc->colorpair), NULL);
2421 wprintw(view->window, "%.8s ", id_str);
2422 if (tc)
2423 wattr_off(view->window,
2424 COLOR_PAIR(tc->colorpair), NULL);
2425 free(id_str);
2426 col += 9;
2427 if (col > avail)
2428 goto done;
2431 if (s->use_committer)
2432 author = strdup(got_object_commit_get_committer(commit));
2433 else
2434 author = strdup(got_object_commit_get_author(commit));
2435 if (author == NULL) {
2436 err = got_error_from_errno("strdup");
2437 goto done;
2439 err = format_author(&wauthor, &author_width, author, avail - col, col);
2440 if (err)
2441 goto done;
2442 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2443 if (tc)
2444 wattr_on(view->window,
2445 COLOR_PAIR(tc->colorpair), NULL);
2446 waddwstr(view->window, wauthor);
2447 col += author_width;
2448 while (col < avail && author_width < author_display_cols + 2) {
2449 waddch(view->window, ' ');
2450 col++;
2451 author_width++;
2453 if (tc)
2454 wattr_off(view->window,
2455 COLOR_PAIR(tc->colorpair), NULL);
2456 if (col > avail)
2457 goto done;
2459 err = got_object_commit_get_logmsg(&logmsg0, commit);
2460 if (err)
2461 goto done;
2462 logmsg = logmsg0;
2463 while (*logmsg == '\n')
2464 logmsg++;
2465 newline = strchr(logmsg, '\n');
2466 if (newline)
2467 *newline = '\0';
2468 limit = avail - col;
2469 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2470 limit--; /* for the border */
2471 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2472 limit, col, 1);
2473 if (err)
2474 goto done;
2475 waddwstr(view->window, &wlogmsg[scrollx]);
2476 col += MAX(logmsg_width, 0);
2477 while (col < avail) {
2478 waddch(view->window, ' ');
2479 col++;
2481 done:
2482 free(logmsg0);
2483 free(wlogmsg);
2484 free(author);
2485 free(wauthor);
2486 free(line);
2487 return err;
2490 static struct commit_queue_entry *
2491 alloc_commit_queue_entry(struct got_commit_object *commit,
2492 struct got_object_id *id)
2494 struct commit_queue_entry *entry;
2495 struct got_object_id *dup;
2497 entry = calloc(1, sizeof(*entry));
2498 if (entry == NULL)
2499 return NULL;
2501 dup = got_object_id_dup(id);
2502 if (dup == NULL) {
2503 free(entry);
2504 return NULL;
2507 entry->id = dup;
2508 entry->commit = commit;
2509 return entry;
2512 static void
2513 pop_commit(struct commit_queue *commits)
2515 struct commit_queue_entry *entry;
2517 entry = TAILQ_FIRST(&commits->head);
2518 TAILQ_REMOVE(&commits->head, entry, entry);
2519 got_object_commit_close(entry->commit);
2520 commits->ncommits--;
2521 free(entry->id);
2522 free(entry);
2525 static void
2526 free_commits(struct commit_queue *commits)
2528 while (!TAILQ_EMPTY(&commits->head))
2529 pop_commit(commits);
2532 static const struct got_error *
2533 match_commit(int *have_match, struct got_object_id *id,
2534 struct got_commit_object *commit, regex_t *regex)
2536 const struct got_error *err = NULL;
2537 regmatch_t regmatch;
2538 char *id_str = NULL, *logmsg = NULL;
2540 *have_match = 0;
2542 err = got_object_id_str(&id_str, id);
2543 if (err)
2544 return err;
2546 err = got_object_commit_get_logmsg(&logmsg, commit);
2547 if (err)
2548 goto done;
2550 if (regexec(regex, got_object_commit_get_author(commit), 1,
2551 &regmatch, 0) == 0 ||
2552 regexec(regex, got_object_commit_get_committer(commit), 1,
2553 &regmatch, 0) == 0 ||
2554 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2555 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2556 *have_match = 1;
2557 done:
2558 free(id_str);
2559 free(logmsg);
2560 return err;
2563 static const struct got_error *
2564 queue_commits(struct tog_log_thread_args *a)
2566 const struct got_error *err = NULL;
2569 * We keep all commits open throughout the lifetime of the log
2570 * view in order to avoid having to re-fetch commits from disk
2571 * while updating the display.
2573 do {
2574 struct got_object_id id;
2575 struct got_commit_object *commit;
2576 struct commit_queue_entry *entry;
2577 int limit_match = 0;
2578 int errcode;
2580 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2581 NULL, NULL);
2582 if (err)
2583 break;
2585 err = got_object_open_as_commit(&commit, a->repo, &id);
2586 if (err)
2587 break;
2588 entry = alloc_commit_queue_entry(commit, &id);
2589 if (entry == NULL) {
2590 err = got_error_from_errno("alloc_commit_queue_entry");
2591 break;
2594 errcode = pthread_mutex_lock(&tog_mutex);
2595 if (errcode) {
2596 err = got_error_set_errno(errcode,
2597 "pthread_mutex_lock");
2598 break;
2601 entry->idx = a->real_commits->ncommits;
2602 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2603 a->real_commits->ncommits++;
2605 if (*a->limiting) {
2606 err = match_commit(&limit_match, &id, commit,
2607 a->limit_regex);
2608 if (err)
2609 break;
2611 if (limit_match) {
2612 struct commit_queue_entry *matched;
2614 matched = alloc_commit_queue_entry(
2615 entry->commit, entry->id);
2616 if (matched == NULL) {
2617 err = got_error_from_errno(
2618 "alloc_commit_queue_entry");
2619 break;
2621 matched->commit = entry->commit;
2622 got_object_commit_retain(entry->commit);
2624 matched->idx = a->limit_commits->ncommits;
2625 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2626 matched, entry);
2627 a->limit_commits->ncommits++;
2631 * This is how we signal log_thread() that we
2632 * have found a match, and that it should be
2633 * counted as a new entry for the view.
2635 a->limit_match = limit_match;
2638 if (*a->searching == TOG_SEARCH_FORWARD &&
2639 !*a->search_next_done) {
2640 int have_match;
2641 err = match_commit(&have_match, &id, commit, a->regex);
2642 if (err)
2643 break;
2645 if (*a->limiting) {
2646 if (limit_match && have_match)
2647 *a->search_next_done =
2648 TOG_SEARCH_HAVE_MORE;
2649 } else if (have_match)
2650 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2653 errcode = pthread_mutex_unlock(&tog_mutex);
2654 if (errcode && err == NULL)
2655 err = got_error_set_errno(errcode,
2656 "pthread_mutex_unlock");
2657 if (err)
2658 break;
2659 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2661 return err;
2664 static void
2665 select_commit(struct tog_log_view_state *s)
2667 struct commit_queue_entry *entry;
2668 int ncommits = 0;
2670 entry = s->first_displayed_entry;
2671 while (entry) {
2672 if (ncommits == s->selected) {
2673 s->selected_entry = entry;
2674 break;
2676 entry = TAILQ_NEXT(entry, entry);
2677 ncommits++;
2681 static const struct got_error *
2682 draw_commits(struct tog_view *view)
2684 const struct got_error *err = NULL;
2685 struct tog_log_view_state *s = &view->state.log;
2686 struct commit_queue_entry *entry = s->selected_entry;
2687 int limit = view->nlines;
2688 int width;
2689 int ncommits, author_cols = 4;
2690 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2691 char *refs_str = NULL;
2692 wchar_t *wline;
2693 struct tog_color *tc;
2694 static const size_t date_display_cols = 12;
2696 if (view_is_hsplit_top(view))
2697 --limit; /* account for border */
2699 if (s->selected_entry &&
2700 !(view->searching && view->search_next_done == 0)) {
2701 struct got_reflist_head *refs;
2702 err = got_object_id_str(&id_str, s->selected_entry->id);
2703 if (err)
2704 return err;
2705 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2706 s->selected_entry->id);
2707 if (refs) {
2708 err = build_refs_str(&refs_str, refs,
2709 s->selected_entry->id, s->repo);
2710 if (err)
2711 goto done;
2715 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2716 halfdelay(10); /* disable fast refresh */
2718 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2719 if (asprintf(&ncommits_str, " [%d/%d] %s",
2720 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2721 (view->searching && !view->search_next_done) ?
2722 "searching..." : "loading...") == -1) {
2723 err = got_error_from_errno("asprintf");
2724 goto done;
2726 } else {
2727 const char *search_str = NULL;
2728 const char *limit_str = NULL;
2730 if (view->searching) {
2731 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2732 search_str = "no more matches";
2733 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2734 search_str = "no matches found";
2735 else if (!view->search_next_done)
2736 search_str = "searching...";
2739 if (s->limit_view && s->commits->ncommits == 0)
2740 limit_str = "no matches found";
2742 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2743 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2744 search_str ? search_str : (refs_str ? refs_str : ""),
2745 limit_str ? limit_str : "") == -1) {
2746 err = got_error_from_errno("asprintf");
2747 goto done;
2751 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2752 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2753 "........................................",
2754 s->in_repo_path, ncommits_str) == -1) {
2755 err = got_error_from_errno("asprintf");
2756 header = NULL;
2757 goto done;
2759 } else if (asprintf(&header, "commit %s%s",
2760 id_str ? id_str : "........................................",
2761 ncommits_str) == -1) {
2762 err = got_error_from_errno("asprintf");
2763 header = NULL;
2764 goto done;
2766 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2767 if (err)
2768 goto done;
2770 werase(view->window);
2772 if (view_needs_focus_indication(view))
2773 wstandout(view->window);
2774 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2775 if (tc)
2776 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2777 waddwstr(view->window, wline);
2778 while (width < view->ncols) {
2779 waddch(view->window, ' ');
2780 width++;
2782 if (tc)
2783 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2784 if (view_needs_focus_indication(view))
2785 wstandend(view->window);
2786 free(wline);
2787 if (limit <= 1)
2788 goto done;
2790 /* Grow author column size if necessary, and set view->maxx. */
2791 entry = s->first_displayed_entry;
2792 ncommits = 0;
2793 view->maxx = 0;
2794 while (entry) {
2795 struct got_commit_object *c = entry->commit;
2796 char *author, *eol, *msg, *msg0;
2797 wchar_t *wauthor, *wmsg;
2798 int width;
2799 if (ncommits >= limit - 1)
2800 break;
2801 if (s->use_committer)
2802 author = strdup(got_object_commit_get_committer(c));
2803 else
2804 author = strdup(got_object_commit_get_author(c));
2805 if (author == NULL) {
2806 err = got_error_from_errno("strdup");
2807 goto done;
2809 err = format_author(&wauthor, &width, author, COLS,
2810 date_display_cols);
2811 if (author_cols < width)
2812 author_cols = width;
2813 free(wauthor);
2814 free(author);
2815 if (err)
2816 goto done;
2817 err = got_object_commit_get_logmsg(&msg0, c);
2818 if (err)
2819 goto done;
2820 msg = msg0;
2821 while (*msg == '\n')
2822 ++msg;
2823 if ((eol = strchr(msg, '\n')))
2824 *eol = '\0';
2825 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2826 date_display_cols + author_cols, 0);
2827 if (err)
2828 goto done;
2829 view->maxx = MAX(view->maxx, width);
2830 free(msg0);
2831 free(wmsg);
2832 ncommits++;
2833 entry = TAILQ_NEXT(entry, entry);
2836 entry = s->first_displayed_entry;
2837 s->last_displayed_entry = s->first_displayed_entry;
2838 ncommits = 0;
2839 while (entry) {
2840 if (ncommits >= limit - 1)
2841 break;
2842 if (ncommits == s->selected)
2843 wstandout(view->window);
2844 err = draw_commit(view, entry->commit, entry->id,
2845 date_display_cols, author_cols);
2846 if (ncommits == s->selected)
2847 wstandend(view->window);
2848 if (err)
2849 goto done;
2850 ncommits++;
2851 s->last_displayed_entry = entry;
2852 entry = TAILQ_NEXT(entry, entry);
2855 view_border(view);
2856 done:
2857 free(id_str);
2858 free(refs_str);
2859 free(ncommits_str);
2860 free(header);
2861 return err;
2864 static void
2865 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2867 struct commit_queue_entry *entry;
2868 int nscrolled = 0;
2870 entry = TAILQ_FIRST(&s->commits->head);
2871 if (s->first_displayed_entry == entry)
2872 return;
2874 entry = s->first_displayed_entry;
2875 while (entry && nscrolled < maxscroll) {
2876 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2877 if (entry) {
2878 s->first_displayed_entry = entry;
2879 nscrolled++;
2884 static const struct got_error *
2885 trigger_log_thread(struct tog_view *view, int wait)
2887 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2888 int errcode;
2890 if (!using_mock_io)
2891 halfdelay(1); /* fast refresh while loading commits */
2893 while (!ta->log_complete && !tog_thread_error &&
2894 (ta->commits_needed > 0 || ta->load_all)) {
2895 /* Wake the log thread. */
2896 errcode = pthread_cond_signal(&ta->need_commits);
2897 if (errcode)
2898 return got_error_set_errno(errcode,
2899 "pthread_cond_signal");
2902 * The mutex will be released while the view loop waits
2903 * in wgetch(), at which time the log thread will run.
2905 if (!wait)
2906 break;
2908 /* Display progress update in log view. */
2909 show_log_view(view);
2910 update_panels();
2911 doupdate();
2913 /* Wait right here while next commit is being loaded. */
2914 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2915 if (errcode)
2916 return got_error_set_errno(errcode,
2917 "pthread_cond_wait");
2919 /* Display progress update in log view. */
2920 show_log_view(view);
2921 update_panels();
2922 doupdate();
2925 return NULL;
2928 static const struct got_error *
2929 request_log_commits(struct tog_view *view)
2931 struct tog_log_view_state *state = &view->state.log;
2932 const struct got_error *err = NULL;
2934 if (state->thread_args.log_complete)
2935 return NULL;
2937 state->thread_args.commits_needed += view->nscrolled;
2938 err = trigger_log_thread(view, 1);
2939 view->nscrolled = 0;
2941 return err;
2944 static const struct got_error *
2945 log_scroll_down(struct tog_view *view, int maxscroll)
2947 struct tog_log_view_state *s = &view->state.log;
2948 const struct got_error *err = NULL;
2949 struct commit_queue_entry *pentry;
2950 int nscrolled = 0, ncommits_needed;
2952 if (s->last_displayed_entry == NULL)
2953 return NULL;
2955 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2956 if (s->commits->ncommits < ncommits_needed &&
2957 !s->thread_args.log_complete) {
2959 * Ask the log thread for required amount of commits.
2961 s->thread_args.commits_needed +=
2962 ncommits_needed - s->commits->ncommits;
2963 err = trigger_log_thread(view, 1);
2964 if (err)
2965 return err;
2968 do {
2969 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2970 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2971 break;
2973 s->last_displayed_entry = pentry ?
2974 pentry : s->last_displayed_entry;
2976 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2977 if (pentry == NULL)
2978 break;
2979 s->first_displayed_entry = pentry;
2980 } while (++nscrolled < maxscroll);
2982 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2983 view->nscrolled += nscrolled;
2984 else
2985 view->nscrolled = 0;
2987 return err;
2990 static const struct got_error *
2991 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2992 struct got_commit_object *commit, struct got_object_id *commit_id,
2993 struct tog_view *log_view, struct got_repository *repo)
2995 const struct got_error *err;
2996 struct got_object_qid *parent_id;
2997 struct tog_view *diff_view;
2999 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3000 if (diff_view == NULL)
3001 return got_error_from_errno("view_open");
3003 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3004 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3005 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3006 if (err == NULL)
3007 *new_view = diff_view;
3008 return err;
3011 static const struct got_error *
3012 tree_view_visit_subtree(struct tog_tree_view_state *s,
3013 struct got_tree_object *subtree)
3015 struct tog_parent_tree *parent;
3017 parent = calloc(1, sizeof(*parent));
3018 if (parent == NULL)
3019 return got_error_from_errno("calloc");
3021 parent->tree = s->tree;
3022 parent->first_displayed_entry = s->first_displayed_entry;
3023 parent->selected_entry = s->selected_entry;
3024 parent->selected = s->selected;
3025 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3026 s->tree = subtree;
3027 s->selected = 0;
3028 s->first_displayed_entry = NULL;
3029 return NULL;
3032 static const struct got_error *
3033 tree_view_walk_path(struct tog_tree_view_state *s,
3034 struct got_commit_object *commit, const char *path)
3036 const struct got_error *err = NULL;
3037 struct got_tree_object *tree = NULL;
3038 const char *p;
3039 char *slash, *subpath = NULL;
3041 /* Walk the path and open corresponding tree objects. */
3042 p = path;
3043 while (*p) {
3044 struct got_tree_entry *te;
3045 struct got_object_id *tree_id;
3046 char *te_name;
3048 while (p[0] == '/')
3049 p++;
3051 /* Ensure the correct subtree entry is selected. */
3052 slash = strchr(p, '/');
3053 if (slash == NULL)
3054 te_name = strdup(p);
3055 else
3056 te_name = strndup(p, slash - p);
3057 if (te_name == NULL) {
3058 err = got_error_from_errno("strndup");
3059 break;
3061 te = got_object_tree_find_entry(s->tree, te_name);
3062 if (te == NULL) {
3063 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3064 free(te_name);
3065 break;
3067 free(te_name);
3068 s->first_displayed_entry = s->selected_entry = te;
3070 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3071 break; /* jump to this file's entry */
3073 slash = strchr(p, '/');
3074 if (slash)
3075 subpath = strndup(path, slash - path);
3076 else
3077 subpath = strdup(path);
3078 if (subpath == NULL) {
3079 err = got_error_from_errno("strdup");
3080 break;
3083 err = got_object_id_by_path(&tree_id, s->repo, commit,
3084 subpath);
3085 if (err)
3086 break;
3088 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3089 free(tree_id);
3090 if (err)
3091 break;
3093 err = tree_view_visit_subtree(s, tree);
3094 if (err) {
3095 got_object_tree_close(tree);
3096 break;
3098 if (slash == NULL)
3099 break;
3100 free(subpath);
3101 subpath = NULL;
3102 p = slash;
3105 free(subpath);
3106 return err;
3109 static const struct got_error *
3110 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3111 struct commit_queue_entry *entry, const char *path,
3112 const char *head_ref_name, struct got_repository *repo)
3114 const struct got_error *err = NULL;
3115 struct tog_tree_view_state *s;
3116 struct tog_view *tree_view;
3118 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3119 if (tree_view == NULL)
3120 return got_error_from_errno("view_open");
3122 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3123 if (err)
3124 return err;
3125 s = &tree_view->state.tree;
3127 *new_view = tree_view;
3129 if (got_path_is_root_dir(path))
3130 return NULL;
3132 return tree_view_walk_path(s, entry->commit, path);
3135 static const struct got_error *
3136 block_signals_used_by_main_thread(void)
3138 sigset_t sigset;
3139 int errcode;
3141 if (sigemptyset(&sigset) == -1)
3142 return got_error_from_errno("sigemptyset");
3144 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3145 if (sigaddset(&sigset, SIGWINCH) == -1)
3146 return got_error_from_errno("sigaddset");
3147 if (sigaddset(&sigset, SIGCONT) == -1)
3148 return got_error_from_errno("sigaddset");
3149 if (sigaddset(&sigset, SIGINT) == -1)
3150 return got_error_from_errno("sigaddset");
3151 if (sigaddset(&sigset, SIGTERM) == -1)
3152 return got_error_from_errno("sigaddset");
3154 /* ncurses handles SIGTSTP */
3155 if (sigaddset(&sigset, SIGTSTP) == -1)
3156 return got_error_from_errno("sigaddset");
3158 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3159 if (errcode)
3160 return got_error_set_errno(errcode, "pthread_sigmask");
3162 return NULL;
3165 static void *
3166 log_thread(void *arg)
3168 const struct got_error *err = NULL;
3169 int errcode = 0;
3170 struct tog_log_thread_args *a = arg;
3171 int done = 0;
3174 * Sync startup with main thread such that we begin our
3175 * work once view_input() has released the mutex.
3177 errcode = pthread_mutex_lock(&tog_mutex);
3178 if (errcode) {
3179 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3180 return (void *)err;
3183 err = block_signals_used_by_main_thread();
3184 if (err) {
3185 pthread_mutex_unlock(&tog_mutex);
3186 goto done;
3189 while (!done && !err && !tog_fatal_signal_received()) {
3190 errcode = pthread_mutex_unlock(&tog_mutex);
3191 if (errcode) {
3192 err = got_error_set_errno(errcode,
3193 "pthread_mutex_unlock");
3194 goto done;
3196 err = queue_commits(a);
3197 if (err) {
3198 if (err->code != GOT_ERR_ITER_COMPLETED)
3199 goto done;
3200 err = NULL;
3201 done = 1;
3202 } else if (a->commits_needed > 0 && !a->load_all) {
3203 if (*a->limiting) {
3204 if (a->limit_match)
3205 a->commits_needed--;
3206 } else
3207 a->commits_needed--;
3210 errcode = pthread_mutex_lock(&tog_mutex);
3211 if (errcode) {
3212 err = got_error_set_errno(errcode,
3213 "pthread_mutex_lock");
3214 goto done;
3215 } else if (*a->quit)
3216 done = 1;
3217 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3218 *a->first_displayed_entry =
3219 TAILQ_FIRST(&a->limit_commits->head);
3220 *a->selected_entry = *a->first_displayed_entry;
3221 } else if (*a->first_displayed_entry == NULL) {
3222 *a->first_displayed_entry =
3223 TAILQ_FIRST(&a->real_commits->head);
3224 *a->selected_entry = *a->first_displayed_entry;
3227 errcode = pthread_cond_signal(&a->commit_loaded);
3228 if (errcode) {
3229 err = got_error_set_errno(errcode,
3230 "pthread_cond_signal");
3231 pthread_mutex_unlock(&tog_mutex);
3232 goto done;
3235 if (done)
3236 a->commits_needed = 0;
3237 else {
3238 if (a->commits_needed == 0 && !a->load_all) {
3239 errcode = pthread_cond_wait(&a->need_commits,
3240 &tog_mutex);
3241 if (errcode) {
3242 err = got_error_set_errno(errcode,
3243 "pthread_cond_wait");
3244 pthread_mutex_unlock(&tog_mutex);
3245 goto done;
3247 if (*a->quit)
3248 done = 1;
3252 a->log_complete = 1;
3253 errcode = pthread_mutex_unlock(&tog_mutex);
3254 if (errcode)
3255 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3256 done:
3257 if (err) {
3258 tog_thread_error = 1;
3259 pthread_cond_signal(&a->commit_loaded);
3261 return (void *)err;
3264 static const struct got_error *
3265 stop_log_thread(struct tog_log_view_state *s)
3267 const struct got_error *err = NULL, *thread_err = NULL;
3268 int errcode;
3270 if (s->thread) {
3271 s->quit = 1;
3272 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3273 if (errcode)
3274 return got_error_set_errno(errcode,
3275 "pthread_cond_signal");
3276 errcode = pthread_mutex_unlock(&tog_mutex);
3277 if (errcode)
3278 return got_error_set_errno(errcode,
3279 "pthread_mutex_unlock");
3280 errcode = pthread_join(s->thread, (void **)&thread_err);
3281 if (errcode)
3282 return got_error_set_errno(errcode, "pthread_join");
3283 errcode = pthread_mutex_lock(&tog_mutex);
3284 if (errcode)
3285 return got_error_set_errno(errcode,
3286 "pthread_mutex_lock");
3287 s->thread = NULL;
3290 if (s->thread_args.repo) {
3291 err = got_repo_close(s->thread_args.repo);
3292 s->thread_args.repo = NULL;
3295 if (s->thread_args.pack_fds) {
3296 const struct got_error *pack_err =
3297 got_repo_pack_fds_close(s->thread_args.pack_fds);
3298 if (err == NULL)
3299 err = pack_err;
3300 s->thread_args.pack_fds = NULL;
3303 if (s->thread_args.graph) {
3304 got_commit_graph_close(s->thread_args.graph);
3305 s->thread_args.graph = NULL;
3308 return err ? err : thread_err;
3311 static const struct got_error *
3312 close_log_view(struct tog_view *view)
3314 const struct got_error *err = NULL;
3315 struct tog_log_view_state *s = &view->state.log;
3316 int errcode;
3318 err = stop_log_thread(s);
3320 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3321 if (errcode && err == NULL)
3322 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3324 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3325 if (errcode && err == NULL)
3326 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3328 free_commits(&s->limit_commits);
3329 free_commits(&s->real_commits);
3330 free(s->in_repo_path);
3331 s->in_repo_path = NULL;
3332 free(s->start_id);
3333 s->start_id = NULL;
3334 free(s->head_ref_name);
3335 s->head_ref_name = NULL;
3336 return err;
3340 * We use two queues to implement the limit feature: first consists of
3341 * commits matching the current limit_regex; second is the real queue
3342 * of all known commits (real_commits). When the user starts limiting,
3343 * we swap queues such that all movement and displaying functionality
3344 * works with very slight change.
3346 static const struct got_error *
3347 limit_log_view(struct tog_view *view)
3349 struct tog_log_view_state *s = &view->state.log;
3350 struct commit_queue_entry *entry;
3351 struct tog_view *v = view;
3352 const struct got_error *err = NULL;
3353 char pattern[1024];
3354 int ret;
3356 if (view_is_hsplit_top(view))
3357 v = view->child;
3358 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3359 v = view->parent;
3361 /* Get the pattern */
3362 wmove(v->window, v->nlines - 1, 0);
3363 wclrtoeol(v->window);
3364 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3365 nodelay(v->window, FALSE);
3366 nocbreak();
3367 echo();
3368 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3369 cbreak();
3370 noecho();
3371 nodelay(v->window, TRUE);
3372 if (ret == ERR)
3373 return NULL;
3375 if (*pattern == '\0') {
3377 * Safety measure for the situation where the user
3378 * resets limit without previously limiting anything.
3380 if (!s->limit_view)
3381 return NULL;
3384 * User could have pressed Ctrl+L, which refreshed the
3385 * commit queues, it means we can't save previously
3386 * (before limit took place) displayed entries,
3387 * because they would point to already free'ed memory,
3388 * so we are forced to always select first entry of
3389 * the queue.
3391 s->commits = &s->real_commits;
3392 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3393 s->selected_entry = s->first_displayed_entry;
3394 s->selected = 0;
3395 s->limit_view = 0;
3397 return NULL;
3400 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3401 return NULL;
3403 s->limit_view = 1;
3405 /* Clear the screen while loading limit view */
3406 s->first_displayed_entry = NULL;
3407 s->last_displayed_entry = NULL;
3408 s->selected_entry = NULL;
3409 s->commits = &s->limit_commits;
3411 /* Prepare limit queue for new search */
3412 free_commits(&s->limit_commits);
3413 s->limit_commits.ncommits = 0;
3415 /* First process commits, which are in queue already */
3416 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3417 int have_match = 0;
3419 err = match_commit(&have_match, entry->id,
3420 entry->commit, &s->limit_regex);
3421 if (err)
3422 return err;
3424 if (have_match) {
3425 struct commit_queue_entry *matched;
3427 matched = alloc_commit_queue_entry(entry->commit,
3428 entry->id);
3429 if (matched == NULL) {
3430 err = got_error_from_errno(
3431 "alloc_commit_queue_entry");
3432 break;
3434 matched->commit = entry->commit;
3435 got_object_commit_retain(entry->commit);
3437 matched->idx = s->limit_commits.ncommits;
3438 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3439 matched, entry);
3440 s->limit_commits.ncommits++;
3444 /* Second process all the commits, until we fill the screen */
3445 if (s->limit_commits.ncommits < view->nlines - 1 &&
3446 !s->thread_args.log_complete) {
3447 s->thread_args.commits_needed +=
3448 view->nlines - s->limit_commits.ncommits - 1;
3449 err = trigger_log_thread(view, 1);
3450 if (err)
3451 return err;
3454 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3455 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3456 s->selected = 0;
3458 return NULL;
3461 static const struct got_error *
3462 search_start_log_view(struct tog_view *view)
3464 struct tog_log_view_state *s = &view->state.log;
3466 s->matched_entry = NULL;
3467 s->search_entry = NULL;
3468 return NULL;
3471 static const struct got_error *
3472 search_next_log_view(struct tog_view *view)
3474 const struct got_error *err = NULL;
3475 struct tog_log_view_state *s = &view->state.log;
3476 struct commit_queue_entry *entry;
3478 /* Display progress update in log view. */
3479 show_log_view(view);
3480 update_panels();
3481 doupdate();
3483 if (s->search_entry) {
3484 int errcode, ch;
3485 errcode = pthread_mutex_unlock(&tog_mutex);
3486 if (errcode)
3487 return got_error_set_errno(errcode,
3488 "pthread_mutex_unlock");
3489 ch = wgetch(view->window);
3490 errcode = pthread_mutex_lock(&tog_mutex);
3491 if (errcode)
3492 return got_error_set_errno(errcode,
3493 "pthread_mutex_lock");
3494 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3495 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3496 return NULL;
3498 if (view->searching == TOG_SEARCH_FORWARD)
3499 entry = TAILQ_NEXT(s->search_entry, entry);
3500 else
3501 entry = TAILQ_PREV(s->search_entry,
3502 commit_queue_head, entry);
3503 } else if (s->matched_entry) {
3505 * If the user has moved the cursor after we hit a match,
3506 * the position from where we should continue searching
3507 * might have changed.
3509 if (view->searching == TOG_SEARCH_FORWARD)
3510 entry = TAILQ_NEXT(s->selected_entry, entry);
3511 else
3512 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3513 entry);
3514 } else {
3515 entry = s->selected_entry;
3518 while (1) {
3519 int have_match = 0;
3521 if (entry == NULL) {
3522 if (s->thread_args.log_complete ||
3523 view->searching == TOG_SEARCH_BACKWARD) {
3524 view->search_next_done =
3525 (s->matched_entry == NULL ?
3526 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3527 s->search_entry = NULL;
3528 return NULL;
3531 * Poke the log thread for more commits and return,
3532 * allowing the main loop to make progress. Search
3533 * will resume at s->search_entry once we come back.
3535 s->thread_args.commits_needed++;
3536 return trigger_log_thread(view, 0);
3539 err = match_commit(&have_match, entry->id, entry->commit,
3540 &view->regex);
3541 if (err)
3542 break;
3543 if (have_match) {
3544 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3545 s->matched_entry = entry;
3546 break;
3549 s->search_entry = entry;
3550 if (view->searching == TOG_SEARCH_FORWARD)
3551 entry = TAILQ_NEXT(entry, entry);
3552 else
3553 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3556 if (s->matched_entry) {
3557 int cur = s->selected_entry->idx;
3558 while (cur < s->matched_entry->idx) {
3559 err = input_log_view(NULL, view, KEY_DOWN);
3560 if (err)
3561 return err;
3562 cur++;
3564 while (cur > s->matched_entry->idx) {
3565 err = input_log_view(NULL, view, KEY_UP);
3566 if (err)
3567 return err;
3568 cur--;
3572 s->search_entry = NULL;
3574 return NULL;
3577 static const struct got_error *
3578 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3579 struct got_repository *repo, const char *head_ref_name,
3580 const char *in_repo_path, int log_branches)
3582 const struct got_error *err = NULL;
3583 struct tog_log_view_state *s = &view->state.log;
3584 struct got_repository *thread_repo = NULL;
3585 struct got_commit_graph *thread_graph = NULL;
3586 int errcode;
3588 if (in_repo_path != s->in_repo_path) {
3589 free(s->in_repo_path);
3590 s->in_repo_path = strdup(in_repo_path);
3591 if (s->in_repo_path == NULL)
3592 return got_error_from_errno("strdup");
3595 /* The commit queue only contains commits being displayed. */
3596 TAILQ_INIT(&s->real_commits.head);
3597 s->real_commits.ncommits = 0;
3598 s->commits = &s->real_commits;
3600 TAILQ_INIT(&s->limit_commits.head);
3601 s->limit_view = 0;
3602 s->limit_commits.ncommits = 0;
3604 s->repo = repo;
3605 if (head_ref_name) {
3606 s->head_ref_name = strdup(head_ref_name);
3607 if (s->head_ref_name == NULL) {
3608 err = got_error_from_errno("strdup");
3609 goto done;
3612 s->start_id = got_object_id_dup(start_id);
3613 if (s->start_id == NULL) {
3614 err = got_error_from_errno("got_object_id_dup");
3615 goto done;
3617 s->log_branches = log_branches;
3618 s->use_committer = 1;
3620 STAILQ_INIT(&s->colors);
3621 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3622 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3623 get_color_value("TOG_COLOR_COMMIT"));
3624 if (err)
3625 goto done;
3626 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3627 get_color_value("TOG_COLOR_AUTHOR"));
3628 if (err) {
3629 free_colors(&s->colors);
3630 goto done;
3632 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3633 get_color_value("TOG_COLOR_DATE"));
3634 if (err) {
3635 free_colors(&s->colors);
3636 goto done;
3640 view->show = show_log_view;
3641 view->input = input_log_view;
3642 view->resize = resize_log_view;
3643 view->close = close_log_view;
3644 view->search_start = search_start_log_view;
3645 view->search_next = search_next_log_view;
3647 if (s->thread_args.pack_fds == NULL) {
3648 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3649 if (err)
3650 goto done;
3652 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3653 s->thread_args.pack_fds);
3654 if (err)
3655 goto done;
3656 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3657 !s->log_branches);
3658 if (err)
3659 goto done;
3660 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3661 s->repo, NULL, NULL);
3662 if (err)
3663 goto done;
3665 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3666 if (errcode) {
3667 err = got_error_set_errno(errcode, "pthread_cond_init");
3668 goto done;
3670 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3671 if (errcode) {
3672 err = got_error_set_errno(errcode, "pthread_cond_init");
3673 goto done;
3676 s->thread_args.commits_needed = view->nlines;
3677 s->thread_args.graph = thread_graph;
3678 s->thread_args.real_commits = &s->real_commits;
3679 s->thread_args.limit_commits = &s->limit_commits;
3680 s->thread_args.in_repo_path = s->in_repo_path;
3681 s->thread_args.start_id = s->start_id;
3682 s->thread_args.repo = thread_repo;
3683 s->thread_args.log_complete = 0;
3684 s->thread_args.quit = &s->quit;
3685 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3686 s->thread_args.selected_entry = &s->selected_entry;
3687 s->thread_args.searching = &view->searching;
3688 s->thread_args.search_next_done = &view->search_next_done;
3689 s->thread_args.regex = &view->regex;
3690 s->thread_args.limiting = &s->limit_view;
3691 s->thread_args.limit_regex = &s->limit_regex;
3692 s->thread_args.limit_commits = &s->limit_commits;
3693 done:
3694 if (err)
3695 close_log_view(view);
3696 return err;
3699 static const struct got_error *
3700 show_log_view(struct tog_view *view)
3702 const struct got_error *err;
3703 struct tog_log_view_state *s = &view->state.log;
3705 if (s->thread == NULL) {
3706 int errcode = pthread_create(&s->thread, NULL, log_thread,
3707 &s->thread_args);
3708 if (errcode)
3709 return got_error_set_errno(errcode, "pthread_create");
3710 if (s->thread_args.commits_needed > 0) {
3711 err = trigger_log_thread(view, 1);
3712 if (err)
3713 return err;
3717 return draw_commits(view);
3720 static void
3721 log_move_cursor_up(struct tog_view *view, int page, int home)
3723 struct tog_log_view_state *s = &view->state.log;
3725 if (s->first_displayed_entry == NULL)
3726 return;
3727 if (s->selected_entry->idx == 0)
3728 view->count = 0;
3730 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3731 || home)
3732 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3734 if (!page && !home && s->selected > 0)
3735 --s->selected;
3736 else
3737 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3739 select_commit(s);
3740 return;
3743 static const struct got_error *
3744 log_move_cursor_down(struct tog_view *view, int page)
3746 struct tog_log_view_state *s = &view->state.log;
3747 const struct got_error *err = NULL;
3748 int eos = view->nlines - 2;
3750 if (s->first_displayed_entry == NULL)
3751 return NULL;
3753 if (s->thread_args.log_complete &&
3754 s->selected_entry->idx >= s->commits->ncommits - 1)
3755 return NULL;
3757 if (view_is_hsplit_top(view))
3758 --eos; /* border consumes the last line */
3760 if (!page) {
3761 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3762 ++s->selected;
3763 else
3764 err = log_scroll_down(view, 1);
3765 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3766 struct commit_queue_entry *entry;
3767 int n;
3769 s->selected = 0;
3770 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3771 s->last_displayed_entry = entry;
3772 for (n = 0; n <= eos; n++) {
3773 if (entry == NULL)
3774 break;
3775 s->first_displayed_entry = entry;
3776 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3778 if (n > 0)
3779 s->selected = n - 1;
3780 } else {
3781 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3782 s->thread_args.log_complete)
3783 s->selected += MIN(page,
3784 s->commits->ncommits - s->selected_entry->idx - 1);
3785 else
3786 err = log_scroll_down(view, page);
3788 if (err)
3789 return err;
3792 * We might necessarily overshoot in horizontal
3793 * splits; if so, select the last displayed commit.
3795 if (s->first_displayed_entry && s->last_displayed_entry) {
3796 s->selected = MIN(s->selected,
3797 s->last_displayed_entry->idx -
3798 s->first_displayed_entry->idx);
3801 select_commit(s);
3803 if (s->thread_args.log_complete &&
3804 s->selected_entry->idx == s->commits->ncommits - 1)
3805 view->count = 0;
3807 return NULL;
3810 static void
3811 view_get_split(struct tog_view *view, int *y, int *x)
3813 *x = 0;
3814 *y = 0;
3816 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3817 if (view->child && view->child->resized_y)
3818 *y = view->child->resized_y;
3819 else if (view->resized_y)
3820 *y = view->resized_y;
3821 else
3822 *y = view_split_begin_y(view->lines);
3823 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3824 if (view->child && view->child->resized_x)
3825 *x = view->child->resized_x;
3826 else if (view->resized_x)
3827 *x = view->resized_x;
3828 else
3829 *x = view_split_begin_x(view->begin_x);
3833 /* Split view horizontally at y and offset view->state->selected line. */
3834 static const struct got_error *
3835 view_init_hsplit(struct tog_view *view, int y)
3837 const struct got_error *err = NULL;
3839 view->nlines = y;
3840 view->ncols = COLS;
3841 err = view_resize(view);
3842 if (err)
3843 return err;
3845 err = offset_selection_down(view);
3847 return err;
3850 static const struct got_error *
3851 log_goto_line(struct tog_view *view, int nlines)
3853 const struct got_error *err = NULL;
3854 struct tog_log_view_state *s = &view->state.log;
3855 int g, idx = s->selected_entry->idx;
3857 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3858 return NULL;
3860 g = view->gline;
3861 view->gline = 0;
3863 if (g >= s->first_displayed_entry->idx + 1 &&
3864 g <= s->last_displayed_entry->idx + 1 &&
3865 g - s->first_displayed_entry->idx - 1 < nlines) {
3866 s->selected = g - s->first_displayed_entry->idx - 1;
3867 select_commit(s);
3868 return NULL;
3871 if (idx + 1 < g) {
3872 err = log_move_cursor_down(view, g - idx - 1);
3873 if (!err && g > s->selected_entry->idx + 1)
3874 err = log_move_cursor_down(view,
3875 g - s->first_displayed_entry->idx - 1);
3876 if (err)
3877 return err;
3878 } else if (idx + 1 > g)
3879 log_move_cursor_up(view, idx - g + 1, 0);
3881 if (g < nlines && s->first_displayed_entry->idx == 0)
3882 s->selected = g - 1;
3884 select_commit(s);
3885 return NULL;
3889 static void
3890 horizontal_scroll_input(struct tog_view *view, int ch)
3893 switch (ch) {
3894 case KEY_LEFT:
3895 case 'h':
3896 view->x -= MIN(view->x, 2);
3897 if (view->x <= 0)
3898 view->count = 0;
3899 break;
3900 case KEY_RIGHT:
3901 case 'l':
3902 if (view->x + view->ncols / 2 < view->maxx)
3903 view->x += 2;
3904 else
3905 view->count = 0;
3906 break;
3907 case '0':
3908 view->x = 0;
3909 break;
3910 case '$':
3911 view->x = MAX(view->maxx - view->ncols / 2, 0);
3912 view->count = 0;
3913 break;
3914 default:
3915 break;
3919 static const struct got_error *
3920 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3922 const struct got_error *err = NULL;
3923 struct tog_log_view_state *s = &view->state.log;
3924 int eos, nscroll;
3926 if (s->thread_args.load_all) {
3927 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3928 s->thread_args.load_all = 0;
3929 else if (s->thread_args.log_complete) {
3930 err = log_move_cursor_down(view, s->commits->ncommits);
3931 s->thread_args.load_all = 0;
3933 if (err)
3934 return err;
3937 eos = nscroll = view->nlines - 1;
3938 if (view_is_hsplit_top(view))
3939 --eos; /* border */
3941 if (view->gline)
3942 return log_goto_line(view, eos);
3944 switch (ch) {
3945 case '&':
3946 err = limit_log_view(view);
3947 break;
3948 case 'q':
3949 s->quit = 1;
3950 break;
3951 case '0':
3952 case '$':
3953 case KEY_RIGHT:
3954 case 'l':
3955 case KEY_LEFT:
3956 case 'h':
3957 horizontal_scroll_input(view, ch);
3958 break;
3959 case 'k':
3960 case KEY_UP:
3961 case '<':
3962 case ',':
3963 case CTRL('p'):
3964 log_move_cursor_up(view, 0, 0);
3965 break;
3966 case 'g':
3967 case '=':
3968 case KEY_HOME:
3969 log_move_cursor_up(view, 0, 1);
3970 view->count = 0;
3971 break;
3972 case CTRL('u'):
3973 case 'u':
3974 nscroll /= 2;
3975 /* FALL THROUGH */
3976 case KEY_PPAGE:
3977 case CTRL('b'):
3978 case 'b':
3979 log_move_cursor_up(view, nscroll, 0);
3980 break;
3981 case 'j':
3982 case KEY_DOWN:
3983 case '>':
3984 case '.':
3985 case CTRL('n'):
3986 err = log_move_cursor_down(view, 0);
3987 break;
3988 case '@':
3989 s->use_committer = !s->use_committer;
3990 view->action = s->use_committer ?
3991 "show committer" : "show commit author";
3992 break;
3993 case 'G':
3994 case '*':
3995 case KEY_END: {
3996 /* We don't know yet how many commits, so we're forced to
3997 * traverse them all. */
3998 view->count = 0;
3999 s->thread_args.load_all = 1;
4000 if (!s->thread_args.log_complete)
4001 return trigger_log_thread(view, 0);
4002 err = log_move_cursor_down(view, s->commits->ncommits);
4003 s->thread_args.load_all = 0;
4004 break;
4006 case CTRL('d'):
4007 case 'd':
4008 nscroll /= 2;
4009 /* FALL THROUGH */
4010 case KEY_NPAGE:
4011 case CTRL('f'):
4012 case 'f':
4013 case ' ':
4014 err = log_move_cursor_down(view, nscroll);
4015 break;
4016 case KEY_RESIZE:
4017 if (s->selected > view->nlines - 2)
4018 s->selected = view->nlines - 2;
4019 if (s->selected > s->commits->ncommits - 1)
4020 s->selected = s->commits->ncommits - 1;
4021 select_commit(s);
4022 if (s->commits->ncommits < view->nlines - 1 &&
4023 !s->thread_args.log_complete) {
4024 s->thread_args.commits_needed += (view->nlines - 1) -
4025 s->commits->ncommits;
4026 err = trigger_log_thread(view, 1);
4028 break;
4029 case KEY_ENTER:
4030 case '\r':
4031 view->count = 0;
4032 if (s->selected_entry == NULL)
4033 break;
4034 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4035 break;
4036 case 'T':
4037 view->count = 0;
4038 if (s->selected_entry == NULL)
4039 break;
4040 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4041 break;
4042 case KEY_BACKSPACE:
4043 case CTRL('l'):
4044 case 'B':
4045 view->count = 0;
4046 if (ch == KEY_BACKSPACE &&
4047 got_path_is_root_dir(s->in_repo_path))
4048 break;
4049 err = stop_log_thread(s);
4050 if (err)
4051 return err;
4052 if (ch == KEY_BACKSPACE) {
4053 char *parent_path;
4054 err = got_path_dirname(&parent_path, s->in_repo_path);
4055 if (err)
4056 return err;
4057 free(s->in_repo_path);
4058 s->in_repo_path = parent_path;
4059 s->thread_args.in_repo_path = s->in_repo_path;
4060 } else if (ch == CTRL('l')) {
4061 struct got_object_id *start_id;
4062 err = got_repo_match_object_id(&start_id, NULL,
4063 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4064 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4065 if (err) {
4066 if (s->head_ref_name == NULL ||
4067 err->code != GOT_ERR_NOT_REF)
4068 return err;
4069 /* Try to cope with deleted references. */
4070 free(s->head_ref_name);
4071 s->head_ref_name = NULL;
4072 err = got_repo_match_object_id(&start_id,
4073 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4074 &tog_refs, s->repo);
4075 if (err)
4076 return err;
4078 free(s->start_id);
4079 s->start_id = start_id;
4080 s->thread_args.start_id = s->start_id;
4081 } else /* 'B' */
4082 s->log_branches = !s->log_branches;
4084 if (s->thread_args.pack_fds == NULL) {
4085 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4086 if (err)
4087 return err;
4089 err = got_repo_open(&s->thread_args.repo,
4090 got_repo_get_path(s->repo), NULL,
4091 s->thread_args.pack_fds);
4092 if (err)
4093 return err;
4094 tog_free_refs();
4095 err = tog_load_refs(s->repo, 0);
4096 if (err)
4097 return err;
4098 err = got_commit_graph_open(&s->thread_args.graph,
4099 s->in_repo_path, !s->log_branches);
4100 if (err)
4101 return err;
4102 err = got_commit_graph_iter_start(s->thread_args.graph,
4103 s->start_id, s->repo, NULL, NULL);
4104 if (err)
4105 return err;
4106 free_commits(&s->real_commits);
4107 free_commits(&s->limit_commits);
4108 s->first_displayed_entry = NULL;
4109 s->last_displayed_entry = NULL;
4110 s->selected_entry = NULL;
4111 s->selected = 0;
4112 s->thread_args.log_complete = 0;
4113 s->quit = 0;
4114 s->thread_args.commits_needed = view->lines;
4115 s->matched_entry = NULL;
4116 s->search_entry = NULL;
4117 view->offset = 0;
4118 break;
4119 case 'R':
4120 view->count = 0;
4121 err = view_request_new(new_view, view, TOG_VIEW_REF);
4122 break;
4123 default:
4124 view->count = 0;
4125 break;
4128 return err;
4131 static const struct got_error *
4132 apply_unveil(const char *repo_path, const char *worktree_path)
4134 const struct got_error *error;
4136 #ifdef PROFILE
4137 if (unveil("gmon.out", "rwc") != 0)
4138 return got_error_from_errno2("unveil", "gmon.out");
4139 #endif
4140 if (repo_path && unveil(repo_path, "r") != 0)
4141 return got_error_from_errno2("unveil", repo_path);
4143 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4144 return got_error_from_errno2("unveil", worktree_path);
4146 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4147 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4149 error = got_privsep_unveil_exec_helpers();
4150 if (error != NULL)
4151 return error;
4153 if (unveil(NULL, NULL) != 0)
4154 return got_error_from_errno("unveil");
4156 return NULL;
4159 static const struct got_error *
4160 init_mock_term(const char *test_script_path)
4162 const struct got_error *err = NULL;
4164 if (test_script_path == NULL || *test_script_path == '\0')
4165 return got_error_msg(GOT_ERR_IO, "GOT_TOG_TEST not defined");
4167 tog_io.f = fopen(test_script_path, "re");
4168 if (tog_io.f == NULL) {
4169 err = got_error_from_errno_fmt("fopen: %s",
4170 test_script_path);
4171 goto done;
4174 /* test mode, we don't want any output */
4175 tog_io.cout = fopen("/dev/null", "w+");
4176 if (tog_io.cout == NULL) {
4177 err = got_error_from_errno("fopen: /dev/null");
4178 goto done;
4181 tog_io.cin = fopen("/dev/tty", "r+");
4182 if (tog_io.cin == NULL) {
4183 err = got_error_from_errno("fopen: /dev/tty");
4184 goto done;
4187 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4188 err = got_error_from_errno("fseeko");
4189 goto done;
4193 * XXX Perhaps we should define "xterm" as the terminal
4194 * type for standardised testing instead of using $TERM?
4196 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4197 err = got_error_msg(GOT_ERR_IO,
4198 "newterm: failed to initialise curses");
4200 using_mock_io = 1;
4201 done:
4202 if (err)
4203 tog_io_close();
4204 return err;
4207 static void
4208 init_curses(void)
4211 * Override default signal handlers before starting ncurses.
4212 * This should prevent ncurses from installing its own
4213 * broken cleanup() signal handler.
4215 signal(SIGWINCH, tog_sigwinch);
4216 signal(SIGPIPE, tog_sigpipe);
4217 signal(SIGCONT, tog_sigcont);
4218 signal(SIGINT, tog_sigint);
4219 signal(SIGTERM, tog_sigterm);
4221 if (using_mock_io) /* In test mode we use a fake terminal */
4222 return;
4224 initscr();
4226 cbreak();
4227 halfdelay(1); /* Fast refresh while initial view is loading. */
4228 noecho();
4229 nonl();
4230 intrflush(stdscr, FALSE);
4231 keypad(stdscr, TRUE);
4232 curs_set(0);
4233 if (getenv("TOG_COLORS") != NULL) {
4234 start_color();
4235 use_default_colors();
4238 return;
4241 static const struct got_error *
4242 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4243 struct got_repository *repo, struct got_worktree *worktree)
4245 const struct got_error *err = NULL;
4247 if (argc == 0) {
4248 *in_repo_path = strdup("/");
4249 if (*in_repo_path == NULL)
4250 return got_error_from_errno("strdup");
4251 return NULL;
4254 if (worktree) {
4255 const char *prefix = got_worktree_get_path_prefix(worktree);
4256 char *p;
4258 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4259 if (err)
4260 return err;
4261 if (asprintf(in_repo_path, "%s%s%s", prefix,
4262 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4263 p) == -1) {
4264 err = got_error_from_errno("asprintf");
4265 *in_repo_path = NULL;
4267 free(p);
4268 } else
4269 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4271 return err;
4274 static const struct got_error *
4275 cmd_log(int argc, char *argv[])
4277 const struct got_error *io_err, *error;
4278 struct got_repository *repo = NULL;
4279 struct got_worktree *worktree = NULL;
4280 struct got_object_id *start_id = NULL;
4281 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4282 char *start_commit = NULL, *label = NULL;
4283 struct got_reference *ref = NULL;
4284 const char *head_ref_name = NULL;
4285 int ch, log_branches = 0;
4286 struct tog_view *view;
4287 int *pack_fds = NULL;
4289 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4290 switch (ch) {
4291 case 'b':
4292 log_branches = 1;
4293 break;
4294 case 'c':
4295 start_commit = optarg;
4296 break;
4297 case 'r':
4298 repo_path = realpath(optarg, NULL);
4299 if (repo_path == NULL)
4300 return got_error_from_errno2("realpath",
4301 optarg);
4302 break;
4303 default:
4304 usage_log();
4305 /* NOTREACHED */
4309 argc -= optind;
4310 argv += optind;
4312 if (argc > 1)
4313 usage_log();
4315 error = got_repo_pack_fds_open(&pack_fds);
4316 if (error != NULL)
4317 goto done;
4319 if (repo_path == NULL) {
4320 cwd = getcwd(NULL, 0);
4321 if (cwd == NULL)
4322 return got_error_from_errno("getcwd");
4323 error = got_worktree_open(&worktree, cwd);
4324 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4325 goto done;
4326 if (worktree)
4327 repo_path =
4328 strdup(got_worktree_get_repo_path(worktree));
4329 else
4330 repo_path = strdup(cwd);
4331 if (repo_path == NULL) {
4332 error = got_error_from_errno("strdup");
4333 goto done;
4337 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4338 if (error != NULL)
4339 goto done;
4341 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4342 repo, worktree);
4343 if (error)
4344 goto done;
4346 init_curses();
4348 error = apply_unveil(got_repo_get_path(repo),
4349 worktree ? got_worktree_get_root_path(worktree) : NULL);
4350 if (error)
4351 goto done;
4353 /* already loaded by tog_log_with_path()? */
4354 if (TAILQ_EMPTY(&tog_refs)) {
4355 error = tog_load_refs(repo, 0);
4356 if (error)
4357 goto done;
4360 if (start_commit == NULL) {
4361 error = got_repo_match_object_id(&start_id, &label,
4362 worktree ? got_worktree_get_head_ref_name(worktree) :
4363 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4364 if (error)
4365 goto done;
4366 head_ref_name = label;
4367 } else {
4368 error = got_ref_open(&ref, repo, start_commit, 0);
4369 if (error == NULL)
4370 head_ref_name = got_ref_get_name(ref);
4371 else if (error->code != GOT_ERR_NOT_REF)
4372 goto done;
4373 error = got_repo_match_object_id(&start_id, NULL,
4374 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4375 if (error)
4376 goto done;
4379 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4380 if (view == NULL) {
4381 error = got_error_from_errno("view_open");
4382 goto done;
4384 error = open_log_view(view, start_id, repo, head_ref_name,
4385 in_repo_path, log_branches);
4386 if (error)
4387 goto done;
4388 if (worktree) {
4389 /* Release work tree lock. */
4390 got_worktree_close(worktree);
4391 worktree = NULL;
4393 error = view_loop(view);
4394 done:
4395 free(in_repo_path);
4396 free(repo_path);
4397 free(cwd);
4398 free(start_id);
4399 free(label);
4400 if (ref)
4401 got_ref_close(ref);
4402 if (repo) {
4403 const struct got_error *close_err = got_repo_close(repo);
4404 if (error == NULL)
4405 error = close_err;
4407 if (worktree)
4408 got_worktree_close(worktree);
4409 if (pack_fds) {
4410 const struct got_error *pack_err =
4411 got_repo_pack_fds_close(pack_fds);
4412 if (error == NULL)
4413 error = pack_err;
4415 if (using_mock_io) {
4416 io_err = tog_io_close();
4417 if (error == NULL)
4418 error = io_err;
4420 tog_free_refs();
4421 return error;
4424 __dead static void
4425 usage_diff(void)
4427 endwin();
4428 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4429 "object1 object2\n", getprogname());
4430 exit(1);
4433 static int
4434 match_line(const char *line, regex_t *regex, size_t nmatch,
4435 regmatch_t *regmatch)
4437 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4440 static struct tog_color *
4441 match_color(struct tog_colors *colors, const char *line)
4443 struct tog_color *tc = NULL;
4445 STAILQ_FOREACH(tc, colors, entry) {
4446 if (match_line(line, &tc->regex, 0, NULL))
4447 return tc;
4450 return NULL;
4453 static const struct got_error *
4454 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4455 WINDOW *window, int skipcol, regmatch_t *regmatch)
4457 const struct got_error *err = NULL;
4458 char *exstr = NULL;
4459 wchar_t *wline = NULL;
4460 int rme, rms, n, width, scrollx;
4461 int width0 = 0, width1 = 0, width2 = 0;
4462 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4464 *wtotal = 0;
4466 rms = regmatch->rm_so;
4467 rme = regmatch->rm_eo;
4469 err = expand_tab(&exstr, line);
4470 if (err)
4471 return err;
4473 /* Split the line into 3 segments, according to match offsets. */
4474 seg0 = strndup(exstr, rms);
4475 if (seg0 == NULL) {
4476 err = got_error_from_errno("strndup");
4477 goto done;
4479 seg1 = strndup(exstr + rms, rme - rms);
4480 if (seg1 == NULL) {
4481 err = got_error_from_errno("strndup");
4482 goto done;
4484 seg2 = strdup(exstr + rme);
4485 if (seg2 == NULL) {
4486 err = got_error_from_errno("strndup");
4487 goto done;
4490 /* draw up to matched token if we haven't scrolled past it */
4491 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4492 col_tab_align, 1);
4493 if (err)
4494 goto done;
4495 n = MAX(width0 - skipcol, 0);
4496 if (n) {
4497 free(wline);
4498 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4499 wlimit, col_tab_align, 1);
4500 if (err)
4501 goto done;
4502 waddwstr(window, &wline[scrollx]);
4503 wlimit -= width;
4504 *wtotal += width;
4507 if (wlimit > 0) {
4508 int i = 0, w = 0;
4509 size_t wlen;
4511 free(wline);
4512 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4513 col_tab_align, 1);
4514 if (err)
4515 goto done;
4516 wlen = wcslen(wline);
4517 while (i < wlen) {
4518 width = wcwidth(wline[i]);
4519 if (width == -1) {
4520 /* should not happen, tabs are expanded */
4521 err = got_error(GOT_ERR_RANGE);
4522 goto done;
4524 if (width0 + w + width > skipcol)
4525 break;
4526 w += width;
4527 i++;
4529 /* draw (visible part of) matched token (if scrolled into it) */
4530 if (width1 - w > 0) {
4531 wattron(window, A_STANDOUT);
4532 waddwstr(window, &wline[i]);
4533 wattroff(window, A_STANDOUT);
4534 wlimit -= (width1 - w);
4535 *wtotal += (width1 - w);
4539 if (wlimit > 0) { /* draw rest of line */
4540 free(wline);
4541 if (skipcol > width0 + width1) {
4542 err = format_line(&wline, &width2, &scrollx, seg2,
4543 skipcol - (width0 + width1), wlimit,
4544 col_tab_align, 1);
4545 if (err)
4546 goto done;
4547 waddwstr(window, &wline[scrollx]);
4548 } else {
4549 err = format_line(&wline, &width2, NULL, seg2, 0,
4550 wlimit, col_tab_align, 1);
4551 if (err)
4552 goto done;
4553 waddwstr(window, wline);
4555 *wtotal += width2;
4557 done:
4558 free(wline);
4559 free(exstr);
4560 free(seg0);
4561 free(seg1);
4562 free(seg2);
4563 return err;
4566 static int
4567 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4569 FILE *f = NULL;
4570 int *eof, *first, *selected;
4572 if (view->type == TOG_VIEW_DIFF) {
4573 struct tog_diff_view_state *s = &view->state.diff;
4575 first = &s->first_displayed_line;
4576 selected = first;
4577 eof = &s->eof;
4578 f = s->f;
4579 } else if (view->type == TOG_VIEW_HELP) {
4580 struct tog_help_view_state *s = &view->state.help;
4582 first = &s->first_displayed_line;
4583 selected = first;
4584 eof = &s->eof;
4585 f = s->f;
4586 } else if (view->type == TOG_VIEW_BLAME) {
4587 struct tog_blame_view_state *s = &view->state.blame;
4589 first = &s->first_displayed_line;
4590 selected = &s->selected_line;
4591 eof = &s->eof;
4592 f = s->blame.f;
4593 } else
4594 return 0;
4596 /* Center gline in the middle of the page like vi(1). */
4597 if (*lineno < view->gline - (view->nlines - 3) / 2)
4598 return 0;
4599 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4600 rewind(f);
4601 *eof = 0;
4602 *first = 1;
4603 *lineno = 0;
4604 *nprinted = 0;
4605 return 0;
4608 *selected = view->gline <= (view->nlines - 3) / 2 ?
4609 view->gline : (view->nlines - 3) / 2 + 1;
4610 view->gline = 0;
4612 return 1;
4615 static const struct got_error *
4616 draw_file(struct tog_view *view, const char *header)
4618 struct tog_diff_view_state *s = &view->state.diff;
4619 regmatch_t *regmatch = &view->regmatch;
4620 const struct got_error *err;
4621 int nprinted = 0;
4622 char *line;
4623 size_t linesize = 0;
4624 ssize_t linelen;
4625 wchar_t *wline;
4626 int width;
4627 int max_lines = view->nlines;
4628 int nlines = s->nlines;
4629 off_t line_offset;
4631 s->lineno = s->first_displayed_line - 1;
4632 line_offset = s->lines[s->first_displayed_line - 1].offset;
4633 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4634 return got_error_from_errno("fseek");
4636 werase(view->window);
4638 if (view->gline > s->nlines - 1)
4639 view->gline = s->nlines - 1;
4641 if (header) {
4642 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4643 1 : view->gline - (view->nlines - 3) / 2 :
4644 s->lineno + s->selected_line;
4646 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4647 return got_error_from_errno("asprintf");
4648 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4649 0, 0);
4650 free(line);
4651 if (err)
4652 return err;
4654 if (view_needs_focus_indication(view))
4655 wstandout(view->window);
4656 waddwstr(view->window, wline);
4657 free(wline);
4658 wline = NULL;
4659 while (width++ < view->ncols)
4660 waddch(view->window, ' ');
4661 if (view_needs_focus_indication(view))
4662 wstandend(view->window);
4664 if (max_lines <= 1)
4665 return NULL;
4666 max_lines--;
4669 s->eof = 0;
4670 view->maxx = 0;
4671 line = NULL;
4672 while (max_lines > 0 && nprinted < max_lines) {
4673 enum got_diff_line_type linetype;
4674 attr_t attr = 0;
4676 linelen = getline(&line, &linesize, s->f);
4677 if (linelen == -1) {
4678 if (feof(s->f)) {
4679 s->eof = 1;
4680 break;
4682 free(line);
4683 return got_ferror(s->f, GOT_ERR_IO);
4686 if (++s->lineno < s->first_displayed_line)
4687 continue;
4688 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4689 continue;
4690 if (s->lineno == view->hiline)
4691 attr = A_STANDOUT;
4693 /* Set view->maxx based on full line length. */
4694 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4695 view->x ? 1 : 0);
4696 if (err) {
4697 free(line);
4698 return err;
4700 view->maxx = MAX(view->maxx, width);
4701 free(wline);
4702 wline = NULL;
4704 linetype = s->lines[s->lineno].type;
4705 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4706 linetype < GOT_DIFF_LINE_CONTEXT)
4707 attr |= COLOR_PAIR(linetype);
4708 if (attr)
4709 wattron(view->window, attr);
4710 if (s->first_displayed_line + nprinted == s->matched_line &&
4711 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4712 err = add_matched_line(&width, line, view->ncols, 0,
4713 view->window, view->x, regmatch);
4714 if (err) {
4715 free(line);
4716 return err;
4718 } else {
4719 int skip;
4720 err = format_line(&wline, &width, &skip, line,
4721 view->x, view->ncols, 0, view->x ? 1 : 0);
4722 if (err) {
4723 free(line);
4724 return err;
4726 waddwstr(view->window, &wline[skip]);
4727 free(wline);
4728 wline = NULL;
4730 if (s->lineno == view->hiline) {
4731 /* highlight full gline length */
4732 while (width++ < view->ncols)
4733 waddch(view->window, ' ');
4734 } else {
4735 if (width <= view->ncols - 1)
4736 waddch(view->window, '\n');
4738 if (attr)
4739 wattroff(view->window, attr);
4740 if (++nprinted == 1)
4741 s->first_displayed_line = s->lineno;
4743 free(line);
4744 if (nprinted >= 1)
4745 s->last_displayed_line = s->first_displayed_line +
4746 (nprinted - 1);
4747 else
4748 s->last_displayed_line = s->first_displayed_line;
4750 view_border(view);
4752 if (s->eof) {
4753 while (nprinted < view->nlines) {
4754 waddch(view->window, '\n');
4755 nprinted++;
4758 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4759 view->ncols, 0, 0);
4760 if (err) {
4761 return err;
4764 wstandout(view->window);
4765 waddwstr(view->window, wline);
4766 free(wline);
4767 wline = NULL;
4768 wstandend(view->window);
4771 return NULL;
4774 static char *
4775 get_datestr(time_t *time, char *datebuf)
4777 struct tm mytm, *tm;
4778 char *p, *s;
4780 tm = gmtime_r(time, &mytm);
4781 if (tm == NULL)
4782 return NULL;
4783 s = asctime_r(tm, datebuf);
4784 if (s == NULL)
4785 return NULL;
4786 p = strchr(s, '\n');
4787 if (p)
4788 *p = '\0';
4789 return s;
4792 static const struct got_error *
4793 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4794 off_t off, uint8_t type)
4796 struct got_diff_line *p;
4798 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4799 if (p == NULL)
4800 return got_error_from_errno("reallocarray");
4801 *lines = p;
4802 (*lines)[*nlines].offset = off;
4803 (*lines)[*nlines].type = type;
4804 (*nlines)++;
4806 return NULL;
4809 static const struct got_error *
4810 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4811 struct got_diff_line *s_lines, size_t s_nlines)
4813 struct got_diff_line *p;
4814 char buf[BUFSIZ];
4815 size_t i, r;
4817 if (fseeko(src, 0L, SEEK_SET) == -1)
4818 return got_error_from_errno("fseeko");
4820 for (;;) {
4821 r = fread(buf, 1, sizeof(buf), src);
4822 if (r == 0) {
4823 if (ferror(src))
4824 return got_error_from_errno("fread");
4825 if (feof(src))
4826 break;
4828 if (fwrite(buf, 1, r, dst) != r)
4829 return got_ferror(dst, GOT_ERR_IO);
4832 if (s_nlines == 0 && *d_nlines == 0)
4833 return NULL;
4836 * If commit info was in dst, increment line offsets
4837 * of the appended diff content, but skip s_lines[0]
4838 * because offset zero is already in *d_lines.
4840 if (*d_nlines > 0) {
4841 for (i = 1; i < s_nlines; ++i)
4842 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4844 if (s_nlines > 0) {
4845 --s_nlines;
4846 ++s_lines;
4850 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4851 if (p == NULL) {
4852 /* d_lines is freed in close_diff_view() */
4853 return got_error_from_errno("reallocarray");
4856 *d_lines = p;
4858 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4859 *d_nlines += s_nlines;
4861 return NULL;
4864 static const struct got_error *
4865 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4866 struct got_object_id *commit_id, struct got_reflist_head *refs,
4867 struct got_repository *repo, int ignore_ws, int force_text_diff,
4868 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4870 const struct got_error *err = NULL;
4871 char datebuf[26], *datestr;
4872 struct got_commit_object *commit;
4873 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4874 time_t committer_time;
4875 const char *author, *committer;
4876 char *refs_str = NULL;
4877 struct got_pathlist_entry *pe;
4878 off_t outoff = 0;
4879 int n;
4881 if (refs) {
4882 err = build_refs_str(&refs_str, refs, commit_id, repo);
4883 if (err)
4884 return err;
4887 err = got_object_open_as_commit(&commit, repo, commit_id);
4888 if (err)
4889 return err;
4891 err = got_object_id_str(&id_str, commit_id);
4892 if (err) {
4893 err = got_error_from_errno("got_object_id_str");
4894 goto done;
4897 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4898 if (err)
4899 goto done;
4901 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4902 refs_str ? refs_str : "", refs_str ? ")" : "");
4903 if (n < 0) {
4904 err = got_error_from_errno("fprintf");
4905 goto done;
4907 outoff += n;
4908 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4909 if (err)
4910 goto done;
4912 n = fprintf(outfile, "from: %s\n",
4913 got_object_commit_get_author(commit));
4914 if (n < 0) {
4915 err = got_error_from_errno("fprintf");
4916 goto done;
4918 outoff += n;
4919 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4920 if (err)
4921 goto done;
4923 author = got_object_commit_get_author(commit);
4924 committer = got_object_commit_get_committer(commit);
4925 if (strcmp(author, committer) != 0) {
4926 n = fprintf(outfile, "via: %s\n", committer);
4927 if (n < 0) {
4928 err = got_error_from_errno("fprintf");
4929 goto done;
4931 outoff += n;
4932 err = add_line_metadata(lines, nlines, outoff,
4933 GOT_DIFF_LINE_AUTHOR);
4934 if (err)
4935 goto done;
4937 committer_time = got_object_commit_get_committer_time(commit);
4938 datestr = get_datestr(&committer_time, datebuf);
4939 if (datestr) {
4940 n = fprintf(outfile, "date: %s UTC\n", datestr);
4941 if (n < 0) {
4942 err = got_error_from_errno("fprintf");
4943 goto done;
4945 outoff += n;
4946 err = add_line_metadata(lines, nlines, outoff,
4947 GOT_DIFF_LINE_DATE);
4948 if (err)
4949 goto done;
4951 if (got_object_commit_get_nparents(commit) > 1) {
4952 const struct got_object_id_queue *parent_ids;
4953 struct got_object_qid *qid;
4954 int pn = 1;
4955 parent_ids = got_object_commit_get_parent_ids(commit);
4956 STAILQ_FOREACH(qid, parent_ids, entry) {
4957 err = got_object_id_str(&id_str, &qid->id);
4958 if (err)
4959 goto done;
4960 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4961 if (n < 0) {
4962 err = got_error_from_errno("fprintf");
4963 goto done;
4965 outoff += n;
4966 err = add_line_metadata(lines, nlines, outoff,
4967 GOT_DIFF_LINE_META);
4968 if (err)
4969 goto done;
4970 free(id_str);
4971 id_str = NULL;
4975 err = got_object_commit_get_logmsg(&logmsg, commit);
4976 if (err)
4977 goto done;
4978 s = logmsg;
4979 while ((line = strsep(&s, "\n")) != NULL) {
4980 n = fprintf(outfile, "%s\n", line);
4981 if (n < 0) {
4982 err = got_error_from_errno("fprintf");
4983 goto done;
4985 outoff += n;
4986 err = add_line_metadata(lines, nlines, outoff,
4987 GOT_DIFF_LINE_LOGMSG);
4988 if (err)
4989 goto done;
4992 TAILQ_FOREACH(pe, dsa->paths, entry) {
4993 struct got_diff_changed_path *cp = pe->data;
4994 int pad = dsa->max_path_len - pe->path_len + 1;
4996 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4997 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4998 dsa->rm_cols + 1, cp->rm);
4999 if (n < 0) {
5000 err = got_error_from_errno("fprintf");
5001 goto done;
5003 outoff += n;
5004 err = add_line_metadata(lines, nlines, outoff,
5005 GOT_DIFF_LINE_CHANGES);
5006 if (err)
5007 goto done;
5010 fputc('\n', outfile);
5011 outoff++;
5012 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5013 if (err)
5014 goto done;
5016 n = fprintf(outfile,
5017 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5018 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5019 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5020 if (n < 0) {
5021 err = got_error_from_errno("fprintf");
5022 goto done;
5024 outoff += n;
5025 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5026 if (err)
5027 goto done;
5029 fputc('\n', outfile);
5030 outoff++;
5031 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5032 done:
5033 free(id_str);
5034 free(logmsg);
5035 free(refs_str);
5036 got_object_commit_close(commit);
5037 if (err) {
5038 free(*lines);
5039 *lines = NULL;
5040 *nlines = 0;
5042 return err;
5045 static const struct got_error *
5046 create_diff(struct tog_diff_view_state *s)
5048 const struct got_error *err = NULL;
5049 FILE *f = NULL, *tmp_diff_file = NULL;
5050 int obj_type;
5051 struct got_diff_line *lines = NULL;
5052 struct got_pathlist_head changed_paths;
5054 TAILQ_INIT(&changed_paths);
5056 free(s->lines);
5057 s->lines = malloc(sizeof(*s->lines));
5058 if (s->lines == NULL)
5059 return got_error_from_errno("malloc");
5060 s->nlines = 0;
5062 f = got_opentemp();
5063 if (f == NULL) {
5064 err = got_error_from_errno("got_opentemp");
5065 goto done;
5067 tmp_diff_file = got_opentemp();
5068 if (tmp_diff_file == NULL) {
5069 err = got_error_from_errno("got_opentemp");
5070 goto done;
5072 if (s->f && fclose(s->f) == EOF) {
5073 err = got_error_from_errno("fclose");
5074 goto done;
5076 s->f = f;
5078 if (s->id1)
5079 err = got_object_get_type(&obj_type, s->repo, s->id1);
5080 else
5081 err = got_object_get_type(&obj_type, s->repo, s->id2);
5082 if (err)
5083 goto done;
5085 switch (obj_type) {
5086 case GOT_OBJ_TYPE_BLOB:
5087 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5088 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5089 s->label1, s->label2, tog_diff_algo, s->diff_context,
5090 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5091 s->f);
5092 break;
5093 case GOT_OBJ_TYPE_TREE:
5094 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5095 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5096 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5097 s->force_text_diff, NULL, s->repo, s->f);
5098 break;
5099 case GOT_OBJ_TYPE_COMMIT: {
5100 const struct got_object_id_queue *parent_ids;
5101 struct got_object_qid *pid;
5102 struct got_commit_object *commit2;
5103 struct got_reflist_head *refs;
5104 size_t nlines = 0;
5105 struct got_diffstat_cb_arg dsa = {
5106 0, 0, 0, 0, 0, 0,
5107 &changed_paths,
5108 s->ignore_whitespace,
5109 s->force_text_diff,
5110 tog_diff_algo
5113 lines = malloc(sizeof(*lines));
5114 if (lines == NULL) {
5115 err = got_error_from_errno("malloc");
5116 goto done;
5119 /* build diff first in tmp file then append to commit info */
5120 err = got_diff_objects_as_commits(&lines, &nlines,
5121 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5122 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5123 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5124 if (err)
5125 break;
5127 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5128 if (err)
5129 goto done;
5130 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5131 /* Show commit info if we're diffing to a parent/root commit. */
5132 if (s->id1 == NULL) {
5133 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5134 refs, s->repo, s->ignore_whitespace,
5135 s->force_text_diff, &dsa, s->f);
5136 if (err)
5137 goto done;
5138 } else {
5139 parent_ids = got_object_commit_get_parent_ids(commit2);
5140 STAILQ_FOREACH(pid, parent_ids, entry) {
5141 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5142 err = write_commit_info(&s->lines,
5143 &s->nlines, s->id2, refs, s->repo,
5144 s->ignore_whitespace,
5145 s->force_text_diff, &dsa, s->f);
5146 if (err)
5147 goto done;
5148 break;
5152 got_object_commit_close(commit2);
5154 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5155 lines, nlines);
5156 break;
5158 default:
5159 err = got_error(GOT_ERR_OBJ_TYPE);
5160 break;
5162 done:
5163 free(lines);
5164 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5165 if (s->f && fflush(s->f) != 0 && err == NULL)
5166 err = got_error_from_errno("fflush");
5167 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5168 err = got_error_from_errno("fclose");
5169 return err;
5172 static void
5173 diff_view_indicate_progress(struct tog_view *view)
5175 mvwaddstr(view->window, 0, 0, "diffing...");
5176 update_panels();
5177 doupdate();
5180 static const struct got_error *
5181 search_start_diff_view(struct tog_view *view)
5183 struct tog_diff_view_state *s = &view->state.diff;
5185 s->matched_line = 0;
5186 return NULL;
5189 static void
5190 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5191 size_t *nlines, int **first, int **last, int **match, int **selected)
5193 struct tog_diff_view_state *s = &view->state.diff;
5195 *f = s->f;
5196 *nlines = s->nlines;
5197 *line_offsets = NULL;
5198 *match = &s->matched_line;
5199 *first = &s->first_displayed_line;
5200 *last = &s->last_displayed_line;
5201 *selected = &s->selected_line;
5204 static const struct got_error *
5205 search_next_view_match(struct tog_view *view)
5207 const struct got_error *err = NULL;
5208 FILE *f;
5209 int lineno;
5210 char *line = NULL;
5211 size_t linesize = 0;
5212 ssize_t linelen;
5213 off_t *line_offsets;
5214 size_t nlines = 0;
5215 int *first, *last, *match, *selected;
5217 if (!view->search_setup)
5218 return got_error_msg(GOT_ERR_NOT_IMPL,
5219 "view search not supported");
5220 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5221 &match, &selected);
5223 if (!view->searching) {
5224 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5225 return NULL;
5228 if (*match) {
5229 if (view->searching == TOG_SEARCH_FORWARD)
5230 lineno = *first + 1;
5231 else
5232 lineno = *first - 1;
5233 } else
5234 lineno = *first - 1 + *selected;
5236 while (1) {
5237 off_t offset;
5239 if (lineno <= 0 || lineno > nlines) {
5240 if (*match == 0) {
5241 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5242 break;
5245 if (view->searching == TOG_SEARCH_FORWARD)
5246 lineno = 1;
5247 else
5248 lineno = nlines;
5251 offset = view->type == TOG_VIEW_DIFF ?
5252 view->state.diff.lines[lineno - 1].offset :
5253 line_offsets[lineno - 1];
5254 if (fseeko(f, offset, SEEK_SET) != 0) {
5255 free(line);
5256 return got_error_from_errno("fseeko");
5258 linelen = getline(&line, &linesize, f);
5259 if (linelen != -1) {
5260 char *exstr;
5261 err = expand_tab(&exstr, line);
5262 if (err)
5263 break;
5264 if (match_line(exstr, &view->regex, 1,
5265 &view->regmatch)) {
5266 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5267 *match = lineno;
5268 free(exstr);
5269 break;
5271 free(exstr);
5273 if (view->searching == TOG_SEARCH_FORWARD)
5274 lineno++;
5275 else
5276 lineno--;
5278 free(line);
5280 if (*match) {
5281 *first = *match;
5282 *selected = 1;
5285 return err;
5288 static const struct got_error *
5289 close_diff_view(struct tog_view *view)
5291 const struct got_error *err = NULL;
5292 struct tog_diff_view_state *s = &view->state.diff;
5294 free(s->id1);
5295 s->id1 = NULL;
5296 free(s->id2);
5297 s->id2 = NULL;
5298 if (s->f && fclose(s->f) == EOF)
5299 err = got_error_from_errno("fclose");
5300 s->f = NULL;
5301 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5302 err = got_error_from_errno("fclose");
5303 s->f1 = NULL;
5304 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5305 err = got_error_from_errno("fclose");
5306 s->f2 = NULL;
5307 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5308 err = got_error_from_errno("close");
5309 s->fd1 = -1;
5310 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5311 err = got_error_from_errno("close");
5312 s->fd2 = -1;
5313 free(s->lines);
5314 s->lines = NULL;
5315 s->nlines = 0;
5316 return err;
5319 static const struct got_error *
5320 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5321 struct got_object_id *id2, const char *label1, const char *label2,
5322 int diff_context, int ignore_whitespace, int force_text_diff,
5323 struct tog_view *parent_view, struct got_repository *repo)
5325 const struct got_error *err;
5326 struct tog_diff_view_state *s = &view->state.diff;
5328 memset(s, 0, sizeof(*s));
5329 s->fd1 = -1;
5330 s->fd2 = -1;
5332 if (id1 != NULL && id2 != NULL) {
5333 int type1, type2;
5334 err = got_object_get_type(&type1, repo, id1);
5335 if (err)
5336 return err;
5337 err = got_object_get_type(&type2, repo, id2);
5338 if (err)
5339 return err;
5341 if (type1 != type2)
5342 return got_error(GOT_ERR_OBJ_TYPE);
5344 s->first_displayed_line = 1;
5345 s->last_displayed_line = view->nlines;
5346 s->selected_line = 1;
5347 s->repo = repo;
5348 s->id1 = id1;
5349 s->id2 = id2;
5350 s->label1 = label1;
5351 s->label2 = label2;
5353 if (id1) {
5354 s->id1 = got_object_id_dup(id1);
5355 if (s->id1 == NULL)
5356 return got_error_from_errno("got_object_id_dup");
5357 } else
5358 s->id1 = NULL;
5360 s->id2 = got_object_id_dup(id2);
5361 if (s->id2 == NULL) {
5362 err = got_error_from_errno("got_object_id_dup");
5363 goto done;
5366 s->f1 = got_opentemp();
5367 if (s->f1 == NULL) {
5368 err = got_error_from_errno("got_opentemp");
5369 goto done;
5372 s->f2 = got_opentemp();
5373 if (s->f2 == NULL) {
5374 err = got_error_from_errno("got_opentemp");
5375 goto done;
5378 s->fd1 = got_opentempfd();
5379 if (s->fd1 == -1) {
5380 err = got_error_from_errno("got_opentempfd");
5381 goto done;
5384 s->fd2 = got_opentempfd();
5385 if (s->fd2 == -1) {
5386 err = got_error_from_errno("got_opentempfd");
5387 goto done;
5390 s->diff_context = diff_context;
5391 s->ignore_whitespace = ignore_whitespace;
5392 s->force_text_diff = force_text_diff;
5393 s->parent_view = parent_view;
5394 s->repo = repo;
5396 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5397 int rc;
5399 rc = init_pair(GOT_DIFF_LINE_MINUS,
5400 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5401 if (rc != ERR)
5402 rc = init_pair(GOT_DIFF_LINE_PLUS,
5403 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5404 if (rc != ERR)
5405 rc = init_pair(GOT_DIFF_LINE_HUNK,
5406 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5407 if (rc != ERR)
5408 rc = init_pair(GOT_DIFF_LINE_META,
5409 get_color_value("TOG_COLOR_DIFF_META"), -1);
5410 if (rc != ERR)
5411 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5412 get_color_value("TOG_COLOR_DIFF_META"), -1);
5413 if (rc != ERR)
5414 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5415 get_color_value("TOG_COLOR_DIFF_META"), -1);
5416 if (rc != ERR)
5417 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5418 get_color_value("TOG_COLOR_DIFF_META"), -1);
5419 if (rc != ERR)
5420 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5421 get_color_value("TOG_COLOR_AUTHOR"), -1);
5422 if (rc != ERR)
5423 rc = init_pair(GOT_DIFF_LINE_DATE,
5424 get_color_value("TOG_COLOR_DATE"), -1);
5425 if (rc == ERR) {
5426 err = got_error(GOT_ERR_RANGE);
5427 goto done;
5431 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5432 view_is_splitscreen(view))
5433 show_log_view(parent_view); /* draw border */
5434 diff_view_indicate_progress(view);
5436 err = create_diff(s);
5438 view->show = show_diff_view;
5439 view->input = input_diff_view;
5440 view->reset = reset_diff_view;
5441 view->close = close_diff_view;
5442 view->search_start = search_start_diff_view;
5443 view->search_setup = search_setup_diff_view;
5444 view->search_next = search_next_view_match;
5445 done:
5446 if (err)
5447 close_diff_view(view);
5448 return err;
5451 static const struct got_error *
5452 show_diff_view(struct tog_view *view)
5454 const struct got_error *err;
5455 struct tog_diff_view_state *s = &view->state.diff;
5456 char *id_str1 = NULL, *id_str2, *header;
5457 const char *label1, *label2;
5459 if (s->id1) {
5460 err = got_object_id_str(&id_str1, s->id1);
5461 if (err)
5462 return err;
5463 label1 = s->label1 ? s->label1 : id_str1;
5464 } else
5465 label1 = "/dev/null";
5467 err = got_object_id_str(&id_str2, s->id2);
5468 if (err)
5469 return err;
5470 label2 = s->label2 ? s->label2 : id_str2;
5472 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5473 err = got_error_from_errno("asprintf");
5474 free(id_str1);
5475 free(id_str2);
5476 return err;
5478 free(id_str1);
5479 free(id_str2);
5481 err = draw_file(view, header);
5482 free(header);
5483 return err;
5486 static const struct got_error *
5487 set_selected_commit(struct tog_diff_view_state *s,
5488 struct commit_queue_entry *entry)
5490 const struct got_error *err;
5491 const struct got_object_id_queue *parent_ids;
5492 struct got_commit_object *selected_commit;
5493 struct got_object_qid *pid;
5495 free(s->id2);
5496 s->id2 = got_object_id_dup(entry->id);
5497 if (s->id2 == NULL)
5498 return got_error_from_errno("got_object_id_dup");
5500 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5501 if (err)
5502 return err;
5503 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5504 free(s->id1);
5505 pid = STAILQ_FIRST(parent_ids);
5506 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5507 got_object_commit_close(selected_commit);
5508 return NULL;
5511 static const struct got_error *
5512 reset_diff_view(struct tog_view *view)
5514 struct tog_diff_view_state *s = &view->state.diff;
5516 view->count = 0;
5517 wclear(view->window);
5518 s->first_displayed_line = 1;
5519 s->last_displayed_line = view->nlines;
5520 s->matched_line = 0;
5521 diff_view_indicate_progress(view);
5522 return create_diff(s);
5525 static void
5526 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5528 int start, i;
5530 i = start = s->first_displayed_line - 1;
5532 while (s->lines[i].type != type) {
5533 if (i == 0)
5534 i = s->nlines - 1;
5535 if (--i == start)
5536 return; /* do nothing, requested type not in file */
5539 s->selected_line = 1;
5540 s->first_displayed_line = i;
5543 static void
5544 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5546 int start, i;
5548 i = start = s->first_displayed_line + 1;
5550 while (s->lines[i].type != type) {
5551 if (i == s->nlines - 1)
5552 i = 0;
5553 if (++i == start)
5554 return; /* do nothing, requested type not in file */
5557 s->selected_line = 1;
5558 s->first_displayed_line = i;
5561 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5562 int, int, int);
5563 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5564 int, int);
5566 static const struct got_error *
5567 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5569 const struct got_error *err = NULL;
5570 struct tog_diff_view_state *s = &view->state.diff;
5571 struct tog_log_view_state *ls;
5572 struct commit_queue_entry *old_selected_entry;
5573 char *line = NULL;
5574 size_t linesize = 0;
5575 ssize_t linelen;
5576 int i, nscroll = view->nlines - 1, up = 0;
5578 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5580 switch (ch) {
5581 case '0':
5582 case '$':
5583 case KEY_RIGHT:
5584 case 'l':
5585 case KEY_LEFT:
5586 case 'h':
5587 horizontal_scroll_input(view, ch);
5588 break;
5589 case 'a':
5590 case 'w':
5591 if (ch == 'a') {
5592 s->force_text_diff = !s->force_text_diff;
5593 view->action = s->force_text_diff ?
5594 "force ASCII text enabled" :
5595 "force ASCII text disabled";
5597 else if (ch == 'w') {
5598 s->ignore_whitespace = !s->ignore_whitespace;
5599 view->action = s->ignore_whitespace ?
5600 "ignore whitespace enabled" :
5601 "ignore whitespace disabled";
5603 err = reset_diff_view(view);
5604 break;
5605 case 'g':
5606 case KEY_HOME:
5607 s->first_displayed_line = 1;
5608 view->count = 0;
5609 break;
5610 case 'G':
5611 case KEY_END:
5612 view->count = 0;
5613 if (s->eof)
5614 break;
5616 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5617 s->eof = 1;
5618 break;
5619 case 'k':
5620 case KEY_UP:
5621 case CTRL('p'):
5622 if (s->first_displayed_line > 1)
5623 s->first_displayed_line--;
5624 else
5625 view->count = 0;
5626 break;
5627 case CTRL('u'):
5628 case 'u':
5629 nscroll /= 2;
5630 /* FALL THROUGH */
5631 case KEY_PPAGE:
5632 case CTRL('b'):
5633 case 'b':
5634 if (s->first_displayed_line == 1) {
5635 view->count = 0;
5636 break;
5638 i = 0;
5639 while (i++ < nscroll && s->first_displayed_line > 1)
5640 s->first_displayed_line--;
5641 break;
5642 case 'j':
5643 case KEY_DOWN:
5644 case CTRL('n'):
5645 if (!s->eof)
5646 s->first_displayed_line++;
5647 else
5648 view->count = 0;
5649 break;
5650 case CTRL('d'):
5651 case 'd':
5652 nscroll /= 2;
5653 /* FALL THROUGH */
5654 case KEY_NPAGE:
5655 case CTRL('f'):
5656 case 'f':
5657 case ' ':
5658 if (s->eof) {
5659 view->count = 0;
5660 break;
5662 i = 0;
5663 while (!s->eof && i++ < nscroll) {
5664 linelen = getline(&line, &linesize, s->f);
5665 s->first_displayed_line++;
5666 if (linelen == -1) {
5667 if (feof(s->f)) {
5668 s->eof = 1;
5669 } else
5670 err = got_ferror(s->f, GOT_ERR_IO);
5671 break;
5674 free(line);
5675 break;
5676 case '(':
5677 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5678 break;
5679 case ')':
5680 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5681 break;
5682 case '{':
5683 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5684 break;
5685 case '}':
5686 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5687 break;
5688 case '[':
5689 if (s->diff_context > 0) {
5690 s->diff_context--;
5691 s->matched_line = 0;
5692 diff_view_indicate_progress(view);
5693 err = create_diff(s);
5694 if (s->first_displayed_line + view->nlines - 1 >
5695 s->nlines) {
5696 s->first_displayed_line = 1;
5697 s->last_displayed_line = view->nlines;
5699 } else
5700 view->count = 0;
5701 break;
5702 case ']':
5703 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5704 s->diff_context++;
5705 s->matched_line = 0;
5706 diff_view_indicate_progress(view);
5707 err = create_diff(s);
5708 } else
5709 view->count = 0;
5710 break;
5711 case '<':
5712 case ',':
5713 case 'K':
5714 up = 1;
5715 /* FALL THROUGH */
5716 case '>':
5717 case '.':
5718 case 'J':
5719 if (s->parent_view == NULL) {
5720 view->count = 0;
5721 break;
5723 s->parent_view->count = view->count;
5725 if (s->parent_view->type == TOG_VIEW_LOG) {
5726 ls = &s->parent_view->state.log;
5727 old_selected_entry = ls->selected_entry;
5729 err = input_log_view(NULL, s->parent_view,
5730 up ? KEY_UP : KEY_DOWN);
5731 if (err)
5732 break;
5733 view->count = s->parent_view->count;
5735 if (old_selected_entry == ls->selected_entry)
5736 break;
5738 err = set_selected_commit(s, ls->selected_entry);
5739 if (err)
5740 break;
5741 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5742 struct tog_blame_view_state *bs;
5743 struct got_object_id *id, *prev_id;
5745 bs = &s->parent_view->state.blame;
5746 prev_id = get_annotation_for_line(bs->blame.lines,
5747 bs->blame.nlines, bs->last_diffed_line);
5749 err = input_blame_view(&view, s->parent_view,
5750 up ? KEY_UP : KEY_DOWN);
5751 if (err)
5752 break;
5753 view->count = s->parent_view->count;
5755 if (prev_id == NULL)
5756 break;
5757 id = get_selected_commit_id(bs->blame.lines,
5758 bs->blame.nlines, bs->first_displayed_line,
5759 bs->selected_line);
5760 if (id == NULL)
5761 break;
5763 if (!got_object_id_cmp(prev_id, id))
5764 break;
5766 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5767 if (err)
5768 break;
5770 s->first_displayed_line = 1;
5771 s->last_displayed_line = view->nlines;
5772 s->matched_line = 0;
5773 view->x = 0;
5775 diff_view_indicate_progress(view);
5776 err = create_diff(s);
5777 break;
5778 default:
5779 view->count = 0;
5780 break;
5783 return err;
5786 static const struct got_error *
5787 cmd_diff(int argc, char *argv[])
5789 const struct got_error *io_err, *error;
5790 struct got_repository *repo = NULL;
5791 struct got_worktree *worktree = NULL;
5792 struct got_object_id *id1 = NULL, *id2 = NULL;
5793 char *repo_path = NULL, *cwd = NULL;
5794 char *id_str1 = NULL, *id_str2 = NULL;
5795 char *label1 = NULL, *label2 = NULL;
5796 int diff_context = 3, ignore_whitespace = 0;
5797 int ch, force_text_diff = 0;
5798 const char *errstr;
5799 struct tog_view *view;
5800 int *pack_fds = NULL;
5802 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5803 switch (ch) {
5804 case 'a':
5805 force_text_diff = 1;
5806 break;
5807 case 'C':
5808 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5809 &errstr);
5810 if (errstr != NULL)
5811 errx(1, "number of context lines is %s: %s",
5812 errstr, errstr);
5813 break;
5814 case 'r':
5815 repo_path = realpath(optarg, NULL);
5816 if (repo_path == NULL)
5817 return got_error_from_errno2("realpath",
5818 optarg);
5819 got_path_strip_trailing_slashes(repo_path);
5820 break;
5821 case 'w':
5822 ignore_whitespace = 1;
5823 break;
5824 default:
5825 usage_diff();
5826 /* NOTREACHED */
5830 argc -= optind;
5831 argv += optind;
5833 if (argc == 0) {
5834 usage_diff(); /* TODO show local worktree changes */
5835 } else if (argc == 2) {
5836 id_str1 = argv[0];
5837 id_str2 = argv[1];
5838 } else
5839 usage_diff();
5841 error = got_repo_pack_fds_open(&pack_fds);
5842 if (error)
5843 goto done;
5845 if (repo_path == NULL) {
5846 cwd = getcwd(NULL, 0);
5847 if (cwd == NULL)
5848 return got_error_from_errno("getcwd");
5849 error = got_worktree_open(&worktree, cwd);
5850 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5851 goto done;
5852 if (worktree)
5853 repo_path =
5854 strdup(got_worktree_get_repo_path(worktree));
5855 else
5856 repo_path = strdup(cwd);
5857 if (repo_path == NULL) {
5858 error = got_error_from_errno("strdup");
5859 goto done;
5863 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5864 if (error)
5865 goto done;
5867 init_curses();
5869 error = apply_unveil(got_repo_get_path(repo), NULL);
5870 if (error)
5871 goto done;
5873 error = tog_load_refs(repo, 0);
5874 if (error)
5875 goto done;
5877 error = got_repo_match_object_id(&id1, &label1, id_str1,
5878 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5879 if (error)
5880 goto done;
5882 error = got_repo_match_object_id(&id2, &label2, id_str2,
5883 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5884 if (error)
5885 goto done;
5887 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5888 if (view == NULL) {
5889 error = got_error_from_errno("view_open");
5890 goto done;
5892 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5893 ignore_whitespace, force_text_diff, NULL, repo);
5894 if (error)
5895 goto done;
5896 error = view_loop(view);
5897 done:
5898 free(label1);
5899 free(label2);
5900 free(repo_path);
5901 free(cwd);
5902 if (repo) {
5903 const struct got_error *close_err = got_repo_close(repo);
5904 if (error == NULL)
5905 error = close_err;
5907 if (worktree)
5908 got_worktree_close(worktree);
5909 if (pack_fds) {
5910 const struct got_error *pack_err =
5911 got_repo_pack_fds_close(pack_fds);
5912 if (error == NULL)
5913 error = pack_err;
5915 if (using_mock_io) {
5916 io_err = tog_io_close();
5917 if (error == NULL)
5918 error = io_err;
5920 tog_free_refs();
5921 return error;
5924 __dead static void
5925 usage_blame(void)
5927 endwin();
5928 fprintf(stderr,
5929 "usage: %s blame [-c commit] [-r repository-path] path\n",
5930 getprogname());
5931 exit(1);
5934 struct tog_blame_line {
5935 int annotated;
5936 struct got_object_id *id;
5939 static const struct got_error *
5940 draw_blame(struct tog_view *view)
5942 struct tog_blame_view_state *s = &view->state.blame;
5943 struct tog_blame *blame = &s->blame;
5944 regmatch_t *regmatch = &view->regmatch;
5945 const struct got_error *err;
5946 int lineno = 0, nprinted = 0;
5947 char *line = NULL;
5948 size_t linesize = 0;
5949 ssize_t linelen;
5950 wchar_t *wline;
5951 int width;
5952 struct tog_blame_line *blame_line;
5953 struct got_object_id *prev_id = NULL;
5954 char *id_str;
5955 struct tog_color *tc;
5957 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5958 if (err)
5959 return err;
5961 rewind(blame->f);
5962 werase(view->window);
5964 if (asprintf(&line, "commit %s", id_str) == -1) {
5965 err = got_error_from_errno("asprintf");
5966 free(id_str);
5967 return err;
5970 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5971 free(line);
5972 line = NULL;
5973 if (err)
5974 return err;
5975 if (view_needs_focus_indication(view))
5976 wstandout(view->window);
5977 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5978 if (tc)
5979 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5980 waddwstr(view->window, wline);
5981 while (width++ < view->ncols)
5982 waddch(view->window, ' ');
5983 if (tc)
5984 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5985 if (view_needs_focus_indication(view))
5986 wstandend(view->window);
5987 free(wline);
5988 wline = NULL;
5990 if (view->gline > blame->nlines)
5991 view->gline = blame->nlines;
5993 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5994 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5995 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5996 free(id_str);
5997 return got_error_from_errno("asprintf");
5999 free(id_str);
6000 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6001 free(line);
6002 line = NULL;
6003 if (err)
6004 return err;
6005 waddwstr(view->window, wline);
6006 free(wline);
6007 wline = NULL;
6008 if (width < view->ncols - 1)
6009 waddch(view->window, '\n');
6011 s->eof = 0;
6012 view->maxx = 0;
6013 while (nprinted < view->nlines - 2) {
6014 linelen = getline(&line, &linesize, blame->f);
6015 if (linelen == -1) {
6016 if (feof(blame->f)) {
6017 s->eof = 1;
6018 break;
6020 free(line);
6021 return got_ferror(blame->f, GOT_ERR_IO);
6023 if (++lineno < s->first_displayed_line)
6024 continue;
6025 if (view->gline && !gotoline(view, &lineno, &nprinted))
6026 continue;
6028 /* Set view->maxx based on full line length. */
6029 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6030 if (err) {
6031 free(line);
6032 return err;
6034 free(wline);
6035 wline = NULL;
6036 view->maxx = MAX(view->maxx, width);
6038 if (nprinted == s->selected_line - 1)
6039 wstandout(view->window);
6041 if (blame->nlines > 0) {
6042 blame_line = &blame->lines[lineno - 1];
6043 if (blame_line->annotated && prev_id &&
6044 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6045 !(nprinted == s->selected_line - 1)) {
6046 waddstr(view->window, " ");
6047 } else if (blame_line->annotated) {
6048 char *id_str;
6049 err = got_object_id_str(&id_str,
6050 blame_line->id);
6051 if (err) {
6052 free(line);
6053 return err;
6055 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6056 if (tc)
6057 wattr_on(view->window,
6058 COLOR_PAIR(tc->colorpair), NULL);
6059 wprintw(view->window, "%.8s", id_str);
6060 if (tc)
6061 wattr_off(view->window,
6062 COLOR_PAIR(tc->colorpair), NULL);
6063 free(id_str);
6064 prev_id = blame_line->id;
6065 } else {
6066 waddstr(view->window, "........");
6067 prev_id = NULL;
6069 } else {
6070 waddstr(view->window, "........");
6071 prev_id = NULL;
6074 if (nprinted == s->selected_line - 1)
6075 wstandend(view->window);
6076 waddstr(view->window, " ");
6078 if (view->ncols <= 9) {
6079 width = 9;
6080 } else if (s->first_displayed_line + nprinted ==
6081 s->matched_line &&
6082 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6083 err = add_matched_line(&width, line, view->ncols - 9, 9,
6084 view->window, view->x, regmatch);
6085 if (err) {
6086 free(line);
6087 return err;
6089 width += 9;
6090 } else {
6091 int skip;
6092 err = format_line(&wline, &width, &skip, line,
6093 view->x, view->ncols - 9, 9, 1);
6094 if (err) {
6095 free(line);
6096 return err;
6098 waddwstr(view->window, &wline[skip]);
6099 width += 9;
6100 free(wline);
6101 wline = NULL;
6104 if (width <= view->ncols - 1)
6105 waddch(view->window, '\n');
6106 if (++nprinted == 1)
6107 s->first_displayed_line = lineno;
6109 free(line);
6110 s->last_displayed_line = lineno;
6112 view_border(view);
6114 return NULL;
6117 static const struct got_error *
6118 blame_cb(void *arg, int nlines, int lineno,
6119 struct got_commit_object *commit, struct got_object_id *id)
6121 const struct got_error *err = NULL;
6122 struct tog_blame_cb_args *a = arg;
6123 struct tog_blame_line *line;
6124 int errcode;
6126 if (nlines != a->nlines ||
6127 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6128 return got_error(GOT_ERR_RANGE);
6130 errcode = pthread_mutex_lock(&tog_mutex);
6131 if (errcode)
6132 return got_error_set_errno(errcode, "pthread_mutex_lock");
6134 if (*a->quit) { /* user has quit the blame view */
6135 err = got_error(GOT_ERR_ITER_COMPLETED);
6136 goto done;
6139 if (lineno == -1)
6140 goto done; /* no change in this commit */
6142 line = &a->lines[lineno - 1];
6143 if (line->annotated)
6144 goto done;
6146 line->id = got_object_id_dup(id);
6147 if (line->id == NULL) {
6148 err = got_error_from_errno("got_object_id_dup");
6149 goto done;
6151 line->annotated = 1;
6152 done:
6153 errcode = pthread_mutex_unlock(&tog_mutex);
6154 if (errcode)
6155 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6156 return err;
6159 static void *
6160 blame_thread(void *arg)
6162 const struct got_error *err, *close_err;
6163 struct tog_blame_thread_args *ta = arg;
6164 struct tog_blame_cb_args *a = ta->cb_args;
6165 int errcode, fd1 = -1, fd2 = -1;
6166 FILE *f1 = NULL, *f2 = NULL;
6168 fd1 = got_opentempfd();
6169 if (fd1 == -1)
6170 return (void *)got_error_from_errno("got_opentempfd");
6172 fd2 = got_opentempfd();
6173 if (fd2 == -1) {
6174 err = got_error_from_errno("got_opentempfd");
6175 goto done;
6178 f1 = got_opentemp();
6179 if (f1 == NULL) {
6180 err = (void *)got_error_from_errno("got_opentemp");
6181 goto done;
6183 f2 = got_opentemp();
6184 if (f2 == NULL) {
6185 err = (void *)got_error_from_errno("got_opentemp");
6186 goto done;
6189 err = block_signals_used_by_main_thread();
6190 if (err)
6191 goto done;
6193 err = got_blame(ta->path, a->commit_id, ta->repo,
6194 tog_diff_algo, blame_cb, ta->cb_args,
6195 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6196 if (err && err->code == GOT_ERR_CANCELLED)
6197 err = NULL;
6199 errcode = pthread_mutex_lock(&tog_mutex);
6200 if (errcode) {
6201 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6202 goto done;
6205 close_err = got_repo_close(ta->repo);
6206 if (err == NULL)
6207 err = close_err;
6208 ta->repo = NULL;
6209 *ta->complete = 1;
6211 errcode = pthread_mutex_unlock(&tog_mutex);
6212 if (errcode && err == NULL)
6213 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6215 done:
6216 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6217 err = got_error_from_errno("close");
6218 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6219 err = got_error_from_errno("close");
6220 if (f1 && fclose(f1) == EOF && err == NULL)
6221 err = got_error_from_errno("fclose");
6222 if (f2 && fclose(f2) == EOF && err == NULL)
6223 err = got_error_from_errno("fclose");
6225 return (void *)err;
6228 static struct got_object_id *
6229 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6230 int first_displayed_line, int selected_line)
6232 struct tog_blame_line *line;
6234 if (nlines <= 0)
6235 return NULL;
6237 line = &lines[first_displayed_line - 1 + selected_line - 1];
6238 if (!line->annotated)
6239 return NULL;
6241 return line->id;
6244 static struct got_object_id *
6245 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6246 int lineno)
6248 struct tog_blame_line *line;
6250 if (nlines <= 0 || lineno >= nlines)
6251 return NULL;
6253 line = &lines[lineno - 1];
6254 if (!line->annotated)
6255 return NULL;
6257 return line->id;
6260 static const struct got_error *
6261 stop_blame(struct tog_blame *blame)
6263 const struct got_error *err = NULL;
6264 int i;
6266 if (blame->thread) {
6267 int errcode;
6268 errcode = pthread_mutex_unlock(&tog_mutex);
6269 if (errcode)
6270 return got_error_set_errno(errcode,
6271 "pthread_mutex_unlock");
6272 errcode = pthread_join(blame->thread, (void **)&err);
6273 if (errcode)
6274 return got_error_set_errno(errcode, "pthread_join");
6275 errcode = pthread_mutex_lock(&tog_mutex);
6276 if (errcode)
6277 return got_error_set_errno(errcode,
6278 "pthread_mutex_lock");
6279 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6280 err = NULL;
6281 blame->thread = NULL;
6283 if (blame->thread_args.repo) {
6284 const struct got_error *close_err;
6285 close_err = got_repo_close(blame->thread_args.repo);
6286 if (err == NULL)
6287 err = close_err;
6288 blame->thread_args.repo = NULL;
6290 if (blame->f) {
6291 if (fclose(blame->f) == EOF && err == NULL)
6292 err = got_error_from_errno("fclose");
6293 blame->f = NULL;
6295 if (blame->lines) {
6296 for (i = 0; i < blame->nlines; i++)
6297 free(blame->lines[i].id);
6298 free(blame->lines);
6299 blame->lines = NULL;
6301 free(blame->cb_args.commit_id);
6302 blame->cb_args.commit_id = NULL;
6303 if (blame->pack_fds) {
6304 const struct got_error *pack_err =
6305 got_repo_pack_fds_close(blame->pack_fds);
6306 if (err == NULL)
6307 err = pack_err;
6308 blame->pack_fds = NULL;
6310 return err;
6313 static const struct got_error *
6314 cancel_blame_view(void *arg)
6316 const struct got_error *err = NULL;
6317 int *done = arg;
6318 int errcode;
6320 errcode = pthread_mutex_lock(&tog_mutex);
6321 if (errcode)
6322 return got_error_set_errno(errcode,
6323 "pthread_mutex_unlock");
6325 if (*done)
6326 err = got_error(GOT_ERR_CANCELLED);
6328 errcode = pthread_mutex_unlock(&tog_mutex);
6329 if (errcode)
6330 return got_error_set_errno(errcode,
6331 "pthread_mutex_lock");
6333 return err;
6336 static const struct got_error *
6337 run_blame(struct tog_view *view)
6339 struct tog_blame_view_state *s = &view->state.blame;
6340 struct tog_blame *blame = &s->blame;
6341 const struct got_error *err = NULL;
6342 struct got_commit_object *commit = NULL;
6343 struct got_blob_object *blob = NULL;
6344 struct got_repository *thread_repo = NULL;
6345 struct got_object_id *obj_id = NULL;
6346 int obj_type, fd = -1;
6347 int *pack_fds = NULL;
6349 err = got_object_open_as_commit(&commit, s->repo,
6350 &s->blamed_commit->id);
6351 if (err)
6352 return err;
6354 fd = got_opentempfd();
6355 if (fd == -1) {
6356 err = got_error_from_errno("got_opentempfd");
6357 goto done;
6360 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6361 if (err)
6362 goto done;
6364 err = got_object_get_type(&obj_type, s->repo, obj_id);
6365 if (err)
6366 goto done;
6368 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6369 err = got_error(GOT_ERR_OBJ_TYPE);
6370 goto done;
6373 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6374 if (err)
6375 goto done;
6376 blame->f = got_opentemp();
6377 if (blame->f == NULL) {
6378 err = got_error_from_errno("got_opentemp");
6379 goto done;
6381 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6382 &blame->line_offsets, blame->f, blob);
6383 if (err)
6384 goto done;
6385 if (blame->nlines == 0) {
6386 s->blame_complete = 1;
6387 goto done;
6390 /* Don't include \n at EOF in the blame line count. */
6391 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6392 blame->nlines--;
6394 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6395 if (blame->lines == NULL) {
6396 err = got_error_from_errno("calloc");
6397 goto done;
6400 err = got_repo_pack_fds_open(&pack_fds);
6401 if (err)
6402 goto done;
6403 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6404 pack_fds);
6405 if (err)
6406 goto done;
6408 blame->pack_fds = pack_fds;
6409 blame->cb_args.view = view;
6410 blame->cb_args.lines = blame->lines;
6411 blame->cb_args.nlines = blame->nlines;
6412 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6413 if (blame->cb_args.commit_id == NULL) {
6414 err = got_error_from_errno("got_object_id_dup");
6415 goto done;
6417 blame->cb_args.quit = &s->done;
6419 blame->thread_args.path = s->path;
6420 blame->thread_args.repo = thread_repo;
6421 blame->thread_args.cb_args = &blame->cb_args;
6422 blame->thread_args.complete = &s->blame_complete;
6423 blame->thread_args.cancel_cb = cancel_blame_view;
6424 blame->thread_args.cancel_arg = &s->done;
6425 s->blame_complete = 0;
6427 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6428 s->first_displayed_line = 1;
6429 s->last_displayed_line = view->nlines;
6430 s->selected_line = 1;
6432 s->matched_line = 0;
6434 done:
6435 if (commit)
6436 got_object_commit_close(commit);
6437 if (fd != -1 && close(fd) == -1 && err == NULL)
6438 err = got_error_from_errno("close");
6439 if (blob)
6440 got_object_blob_close(blob);
6441 free(obj_id);
6442 if (err)
6443 stop_blame(blame);
6444 return err;
6447 static const struct got_error *
6448 open_blame_view(struct tog_view *view, char *path,
6449 struct got_object_id *commit_id, struct got_repository *repo)
6451 const struct got_error *err = NULL;
6452 struct tog_blame_view_state *s = &view->state.blame;
6454 STAILQ_INIT(&s->blamed_commits);
6456 s->path = strdup(path);
6457 if (s->path == NULL)
6458 return got_error_from_errno("strdup");
6460 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6461 if (err) {
6462 free(s->path);
6463 return err;
6466 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6467 s->first_displayed_line = 1;
6468 s->last_displayed_line = view->nlines;
6469 s->selected_line = 1;
6470 s->blame_complete = 0;
6471 s->repo = repo;
6472 s->commit_id = commit_id;
6473 memset(&s->blame, 0, sizeof(s->blame));
6475 STAILQ_INIT(&s->colors);
6476 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6477 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6478 get_color_value("TOG_COLOR_COMMIT"));
6479 if (err)
6480 return err;
6483 view->show = show_blame_view;
6484 view->input = input_blame_view;
6485 view->reset = reset_blame_view;
6486 view->close = close_blame_view;
6487 view->search_start = search_start_blame_view;
6488 view->search_setup = search_setup_blame_view;
6489 view->search_next = search_next_view_match;
6491 return run_blame(view);
6494 static const struct got_error *
6495 close_blame_view(struct tog_view *view)
6497 const struct got_error *err = NULL;
6498 struct tog_blame_view_state *s = &view->state.blame;
6500 if (s->blame.thread)
6501 err = stop_blame(&s->blame);
6503 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6504 struct got_object_qid *blamed_commit;
6505 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6506 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6507 got_object_qid_free(blamed_commit);
6510 free(s->path);
6511 free_colors(&s->colors);
6512 return err;
6515 static const struct got_error *
6516 search_start_blame_view(struct tog_view *view)
6518 struct tog_blame_view_state *s = &view->state.blame;
6520 s->matched_line = 0;
6521 return NULL;
6524 static void
6525 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6526 size_t *nlines, int **first, int **last, int **match, int **selected)
6528 struct tog_blame_view_state *s = &view->state.blame;
6530 *f = s->blame.f;
6531 *nlines = s->blame.nlines;
6532 *line_offsets = s->blame.line_offsets;
6533 *match = &s->matched_line;
6534 *first = &s->first_displayed_line;
6535 *last = &s->last_displayed_line;
6536 *selected = &s->selected_line;
6539 static const struct got_error *
6540 show_blame_view(struct tog_view *view)
6542 const struct got_error *err = NULL;
6543 struct tog_blame_view_state *s = &view->state.blame;
6544 int errcode;
6546 if (s->blame.thread == NULL && !s->blame_complete) {
6547 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6548 &s->blame.thread_args);
6549 if (errcode)
6550 return got_error_set_errno(errcode, "pthread_create");
6552 if (!using_mock_io)
6553 halfdelay(1); /* fast refresh while annotating */
6556 if (s->blame_complete && !using_mock_io)
6557 halfdelay(10); /* disable fast refresh */
6559 err = draw_blame(view);
6561 view_border(view);
6562 return err;
6565 static const struct got_error *
6566 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6567 struct got_repository *repo, struct got_object_id *id)
6569 struct tog_view *log_view;
6570 const struct got_error *err = NULL;
6572 *new_view = NULL;
6574 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6575 if (log_view == NULL)
6576 return got_error_from_errno("view_open");
6578 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6579 if (err)
6580 view_close(log_view);
6581 else
6582 *new_view = log_view;
6584 return err;
6587 static const struct got_error *
6588 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6590 const struct got_error *err = NULL, *thread_err = NULL;
6591 struct tog_view *diff_view;
6592 struct tog_blame_view_state *s = &view->state.blame;
6593 int eos, nscroll, begin_y = 0, begin_x = 0;
6595 eos = nscroll = view->nlines - 2;
6596 if (view_is_hsplit_top(view))
6597 --eos; /* border */
6599 switch (ch) {
6600 case '0':
6601 case '$':
6602 case KEY_RIGHT:
6603 case 'l':
6604 case KEY_LEFT:
6605 case 'h':
6606 horizontal_scroll_input(view, ch);
6607 break;
6608 case 'q':
6609 s->done = 1;
6610 break;
6611 case 'g':
6612 case KEY_HOME:
6613 s->selected_line = 1;
6614 s->first_displayed_line = 1;
6615 view->count = 0;
6616 break;
6617 case 'G':
6618 case KEY_END:
6619 if (s->blame.nlines < eos) {
6620 s->selected_line = s->blame.nlines;
6621 s->first_displayed_line = 1;
6622 } else {
6623 s->selected_line = eos;
6624 s->first_displayed_line = s->blame.nlines - (eos - 1);
6626 view->count = 0;
6627 break;
6628 case 'k':
6629 case KEY_UP:
6630 case CTRL('p'):
6631 if (s->selected_line > 1)
6632 s->selected_line--;
6633 else if (s->selected_line == 1 &&
6634 s->first_displayed_line > 1)
6635 s->first_displayed_line--;
6636 else
6637 view->count = 0;
6638 break;
6639 case CTRL('u'):
6640 case 'u':
6641 nscroll /= 2;
6642 /* FALL THROUGH */
6643 case KEY_PPAGE:
6644 case CTRL('b'):
6645 case 'b':
6646 if (s->first_displayed_line == 1) {
6647 if (view->count > 1)
6648 nscroll += nscroll;
6649 s->selected_line = MAX(1, s->selected_line - nscroll);
6650 view->count = 0;
6651 break;
6653 if (s->first_displayed_line > nscroll)
6654 s->first_displayed_line -= nscroll;
6655 else
6656 s->first_displayed_line = 1;
6657 break;
6658 case 'j':
6659 case KEY_DOWN:
6660 case CTRL('n'):
6661 if (s->selected_line < eos && s->first_displayed_line +
6662 s->selected_line <= s->blame.nlines)
6663 s->selected_line++;
6664 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6665 s->first_displayed_line++;
6666 else
6667 view->count = 0;
6668 break;
6669 case 'c':
6670 case 'p': {
6671 struct got_object_id *id = NULL;
6673 view->count = 0;
6674 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6675 s->first_displayed_line, s->selected_line);
6676 if (id == NULL)
6677 break;
6678 if (ch == 'p') {
6679 struct got_commit_object *commit, *pcommit;
6680 struct got_object_qid *pid;
6681 struct got_object_id *blob_id = NULL;
6682 int obj_type;
6683 err = got_object_open_as_commit(&commit,
6684 s->repo, id);
6685 if (err)
6686 break;
6687 pid = STAILQ_FIRST(
6688 got_object_commit_get_parent_ids(commit));
6689 if (pid == NULL) {
6690 got_object_commit_close(commit);
6691 break;
6693 /* Check if path history ends here. */
6694 err = got_object_open_as_commit(&pcommit,
6695 s->repo, &pid->id);
6696 if (err)
6697 break;
6698 err = got_object_id_by_path(&blob_id, s->repo,
6699 pcommit, s->path);
6700 got_object_commit_close(pcommit);
6701 if (err) {
6702 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6703 err = NULL;
6704 got_object_commit_close(commit);
6705 break;
6707 err = got_object_get_type(&obj_type, s->repo,
6708 blob_id);
6709 free(blob_id);
6710 /* Can't blame non-blob type objects. */
6711 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6712 got_object_commit_close(commit);
6713 break;
6715 err = got_object_qid_alloc(&s->blamed_commit,
6716 &pid->id);
6717 got_object_commit_close(commit);
6718 } else {
6719 if (got_object_id_cmp(id,
6720 &s->blamed_commit->id) == 0)
6721 break;
6722 err = got_object_qid_alloc(&s->blamed_commit,
6723 id);
6725 if (err)
6726 break;
6727 s->done = 1;
6728 thread_err = stop_blame(&s->blame);
6729 s->done = 0;
6730 if (thread_err)
6731 break;
6732 STAILQ_INSERT_HEAD(&s->blamed_commits,
6733 s->blamed_commit, entry);
6734 err = run_blame(view);
6735 if (err)
6736 break;
6737 break;
6739 case 'C': {
6740 struct got_object_qid *first;
6742 view->count = 0;
6743 first = STAILQ_FIRST(&s->blamed_commits);
6744 if (!got_object_id_cmp(&first->id, s->commit_id))
6745 break;
6746 s->done = 1;
6747 thread_err = stop_blame(&s->blame);
6748 s->done = 0;
6749 if (thread_err)
6750 break;
6751 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6752 got_object_qid_free(s->blamed_commit);
6753 s->blamed_commit =
6754 STAILQ_FIRST(&s->blamed_commits);
6755 err = run_blame(view);
6756 if (err)
6757 break;
6758 break;
6760 case 'L':
6761 view->count = 0;
6762 s->id_to_log = get_selected_commit_id(s->blame.lines,
6763 s->blame.nlines, s->first_displayed_line, s->selected_line);
6764 if (s->id_to_log)
6765 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6766 break;
6767 case KEY_ENTER:
6768 case '\r': {
6769 struct got_object_id *id = NULL;
6770 struct got_object_qid *pid;
6771 struct got_commit_object *commit = NULL;
6773 view->count = 0;
6774 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6775 s->first_displayed_line, s->selected_line);
6776 if (id == NULL)
6777 break;
6778 err = got_object_open_as_commit(&commit, s->repo, id);
6779 if (err)
6780 break;
6781 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6782 if (*new_view) {
6783 /* traversed from diff view, release diff resources */
6784 err = close_diff_view(*new_view);
6785 if (err)
6786 break;
6787 diff_view = *new_view;
6788 } else {
6789 if (view_is_parent_view(view))
6790 view_get_split(view, &begin_y, &begin_x);
6792 diff_view = view_open(0, 0, begin_y, begin_x,
6793 TOG_VIEW_DIFF);
6794 if (diff_view == NULL) {
6795 got_object_commit_close(commit);
6796 err = got_error_from_errno("view_open");
6797 break;
6800 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6801 id, NULL, NULL, 3, 0, 0, view, s->repo);
6802 got_object_commit_close(commit);
6803 if (err) {
6804 view_close(diff_view);
6805 break;
6807 s->last_diffed_line = s->first_displayed_line - 1 +
6808 s->selected_line;
6809 if (*new_view)
6810 break; /* still open from active diff view */
6811 if (view_is_parent_view(view) &&
6812 view->mode == TOG_VIEW_SPLIT_HRZN) {
6813 err = view_init_hsplit(view, begin_y);
6814 if (err)
6815 break;
6818 view->focussed = 0;
6819 diff_view->focussed = 1;
6820 diff_view->mode = view->mode;
6821 diff_view->nlines = view->lines - begin_y;
6822 if (view_is_parent_view(view)) {
6823 view_transfer_size(diff_view, view);
6824 err = view_close_child(view);
6825 if (err)
6826 break;
6827 err = view_set_child(view, diff_view);
6828 if (err)
6829 break;
6830 view->focus_child = 1;
6831 } else
6832 *new_view = diff_view;
6833 if (err)
6834 break;
6835 break;
6837 case CTRL('d'):
6838 case 'd':
6839 nscroll /= 2;
6840 /* FALL THROUGH */
6841 case KEY_NPAGE:
6842 case CTRL('f'):
6843 case 'f':
6844 case ' ':
6845 if (s->last_displayed_line >= s->blame.nlines &&
6846 s->selected_line >= MIN(s->blame.nlines,
6847 view->nlines - 2)) {
6848 view->count = 0;
6849 break;
6851 if (s->last_displayed_line >= s->blame.nlines &&
6852 s->selected_line < view->nlines - 2) {
6853 s->selected_line +=
6854 MIN(nscroll, s->last_displayed_line -
6855 s->first_displayed_line - s->selected_line + 1);
6857 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6858 s->first_displayed_line += nscroll;
6859 else
6860 s->first_displayed_line =
6861 s->blame.nlines - (view->nlines - 3);
6862 break;
6863 case KEY_RESIZE:
6864 if (s->selected_line > view->nlines - 2) {
6865 s->selected_line = MIN(s->blame.nlines,
6866 view->nlines - 2);
6868 break;
6869 default:
6870 view->count = 0;
6871 break;
6873 return thread_err ? thread_err : err;
6876 static const struct got_error *
6877 reset_blame_view(struct tog_view *view)
6879 const struct got_error *err;
6880 struct tog_blame_view_state *s = &view->state.blame;
6882 view->count = 0;
6883 s->done = 1;
6884 err = stop_blame(&s->blame);
6885 s->done = 0;
6886 if (err)
6887 return err;
6888 return run_blame(view);
6891 static const struct got_error *
6892 cmd_blame(int argc, char *argv[])
6894 const struct got_error *io_err, *error;
6895 struct got_repository *repo = NULL;
6896 struct got_worktree *worktree = NULL;
6897 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6898 char *link_target = NULL;
6899 struct got_object_id *commit_id = NULL;
6900 struct got_commit_object *commit = NULL;
6901 char *commit_id_str = NULL;
6902 int ch;
6903 struct tog_view *view;
6904 int *pack_fds = NULL;
6906 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6907 switch (ch) {
6908 case 'c':
6909 commit_id_str = optarg;
6910 break;
6911 case 'r':
6912 repo_path = realpath(optarg, NULL);
6913 if (repo_path == NULL)
6914 return got_error_from_errno2("realpath",
6915 optarg);
6916 break;
6917 default:
6918 usage_blame();
6919 /* NOTREACHED */
6923 argc -= optind;
6924 argv += optind;
6926 if (argc != 1)
6927 usage_blame();
6929 error = got_repo_pack_fds_open(&pack_fds);
6930 if (error != NULL)
6931 goto done;
6933 if (repo_path == NULL) {
6934 cwd = getcwd(NULL, 0);
6935 if (cwd == NULL)
6936 return got_error_from_errno("getcwd");
6937 error = got_worktree_open(&worktree, cwd);
6938 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6939 goto done;
6940 if (worktree)
6941 repo_path =
6942 strdup(got_worktree_get_repo_path(worktree));
6943 else
6944 repo_path = strdup(cwd);
6945 if (repo_path == NULL) {
6946 error = got_error_from_errno("strdup");
6947 goto done;
6951 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6952 if (error != NULL)
6953 goto done;
6955 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6956 worktree);
6957 if (error)
6958 goto done;
6960 init_curses();
6962 error = apply_unveil(got_repo_get_path(repo), NULL);
6963 if (error)
6964 goto done;
6966 error = tog_load_refs(repo, 0);
6967 if (error)
6968 goto done;
6970 if (commit_id_str == NULL) {
6971 struct got_reference *head_ref;
6972 error = got_ref_open(&head_ref, repo, worktree ?
6973 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6974 if (error != NULL)
6975 goto done;
6976 error = got_ref_resolve(&commit_id, repo, head_ref);
6977 got_ref_close(head_ref);
6978 } else {
6979 error = got_repo_match_object_id(&commit_id, NULL,
6980 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6982 if (error != NULL)
6983 goto done;
6985 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6986 if (view == NULL) {
6987 error = got_error_from_errno("view_open");
6988 goto done;
6991 error = got_object_open_as_commit(&commit, repo, commit_id);
6992 if (error)
6993 goto done;
6995 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6996 commit, repo);
6997 if (error)
6998 goto done;
7000 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7001 commit_id, repo);
7002 if (error)
7003 goto done;
7004 if (worktree) {
7005 /* Release work tree lock. */
7006 got_worktree_close(worktree);
7007 worktree = NULL;
7009 error = view_loop(view);
7010 done:
7011 free(repo_path);
7012 free(in_repo_path);
7013 free(link_target);
7014 free(cwd);
7015 free(commit_id);
7016 if (commit)
7017 got_object_commit_close(commit);
7018 if (worktree)
7019 got_worktree_close(worktree);
7020 if (repo) {
7021 const struct got_error *close_err = got_repo_close(repo);
7022 if (error == NULL)
7023 error = close_err;
7025 if (pack_fds) {
7026 const struct got_error *pack_err =
7027 got_repo_pack_fds_close(pack_fds);
7028 if (error == NULL)
7029 error = pack_err;
7031 if (using_mock_io) {
7032 io_err = tog_io_close();
7033 if (error == NULL)
7034 error = io_err;
7036 tog_free_refs();
7037 return error;
7040 static const struct got_error *
7041 draw_tree_entries(struct tog_view *view, const char *parent_path)
7043 struct tog_tree_view_state *s = &view->state.tree;
7044 const struct got_error *err = NULL;
7045 struct got_tree_entry *te;
7046 wchar_t *wline;
7047 char *index = NULL;
7048 struct tog_color *tc;
7049 int width, n, nentries, scrollx, i = 1;
7050 int limit = view->nlines;
7052 s->ndisplayed = 0;
7053 if (view_is_hsplit_top(view))
7054 --limit; /* border */
7056 werase(view->window);
7058 if (limit == 0)
7059 return NULL;
7061 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7062 0, 0);
7063 if (err)
7064 return err;
7065 if (view_needs_focus_indication(view))
7066 wstandout(view->window);
7067 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7068 if (tc)
7069 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7070 waddwstr(view->window, wline);
7071 free(wline);
7072 wline = NULL;
7073 while (width++ < view->ncols)
7074 waddch(view->window, ' ');
7075 if (tc)
7076 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7077 if (view_needs_focus_indication(view))
7078 wstandend(view->window);
7079 if (--limit <= 0)
7080 return NULL;
7082 i += s->selected;
7083 if (s->first_displayed_entry) {
7084 i += got_tree_entry_get_index(s->first_displayed_entry);
7085 if (s->tree != s->root)
7086 ++i; /* account for ".." entry */
7088 nentries = got_object_tree_get_nentries(s->tree);
7089 if (asprintf(&index, "[%d/%d] %s",
7090 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7091 return got_error_from_errno("asprintf");
7092 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7093 free(index);
7094 if (err)
7095 return err;
7096 waddwstr(view->window, wline);
7097 free(wline);
7098 wline = NULL;
7099 if (width < view->ncols - 1)
7100 waddch(view->window, '\n');
7101 if (--limit <= 0)
7102 return NULL;
7103 waddch(view->window, '\n');
7104 if (--limit <= 0)
7105 return NULL;
7107 if (s->first_displayed_entry == NULL) {
7108 te = got_object_tree_get_first_entry(s->tree);
7109 if (s->selected == 0) {
7110 if (view->focussed)
7111 wstandout(view->window);
7112 s->selected_entry = NULL;
7114 waddstr(view->window, " ..\n"); /* parent directory */
7115 if (s->selected == 0 && view->focussed)
7116 wstandend(view->window);
7117 s->ndisplayed++;
7118 if (--limit <= 0)
7119 return NULL;
7120 n = 1;
7121 } else {
7122 n = 0;
7123 te = s->first_displayed_entry;
7126 view->maxx = 0;
7127 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7128 char *line = NULL, *id_str = NULL, *link_target = NULL;
7129 const char *modestr = "";
7130 mode_t mode;
7132 te = got_object_tree_get_entry(s->tree, i);
7133 mode = got_tree_entry_get_mode(te);
7135 if (s->show_ids) {
7136 err = got_object_id_str(&id_str,
7137 got_tree_entry_get_id(te));
7138 if (err)
7139 return got_error_from_errno(
7140 "got_object_id_str");
7142 if (got_object_tree_entry_is_submodule(te))
7143 modestr = "$";
7144 else if (S_ISLNK(mode)) {
7145 int i;
7147 err = got_tree_entry_get_symlink_target(&link_target,
7148 te, s->repo);
7149 if (err) {
7150 free(id_str);
7151 return err;
7153 for (i = 0; i < strlen(link_target); i++) {
7154 if (!isprint((unsigned char)link_target[i]))
7155 link_target[i] = '?';
7157 modestr = "@";
7159 else if (S_ISDIR(mode))
7160 modestr = "/";
7161 else if (mode & S_IXUSR)
7162 modestr = "*";
7163 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7164 got_tree_entry_get_name(te), modestr,
7165 link_target ? " -> ": "",
7166 link_target ? link_target : "") == -1) {
7167 free(id_str);
7168 free(link_target);
7169 return got_error_from_errno("asprintf");
7171 free(id_str);
7172 free(link_target);
7174 /* use full line width to determine view->maxx */
7175 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7176 if (err) {
7177 free(line);
7178 break;
7180 view->maxx = MAX(view->maxx, width);
7181 free(wline);
7182 wline = NULL;
7184 err = format_line(&wline, &width, &scrollx, line, view->x,
7185 view->ncols, 0, 0);
7186 if (err) {
7187 free(line);
7188 break;
7190 if (n == s->selected) {
7191 if (view->focussed)
7192 wstandout(view->window);
7193 s->selected_entry = te;
7195 tc = match_color(&s->colors, line);
7196 if (tc)
7197 wattr_on(view->window,
7198 COLOR_PAIR(tc->colorpair), NULL);
7199 waddwstr(view->window, &wline[scrollx]);
7200 if (tc)
7201 wattr_off(view->window,
7202 COLOR_PAIR(tc->colorpair), NULL);
7203 if (width < view->ncols)
7204 waddch(view->window, '\n');
7205 if (n == s->selected && view->focussed)
7206 wstandend(view->window);
7207 free(line);
7208 free(wline);
7209 wline = NULL;
7210 n++;
7211 s->ndisplayed++;
7212 s->last_displayed_entry = te;
7213 if (--limit <= 0)
7214 break;
7217 return err;
7220 static void
7221 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7223 struct got_tree_entry *te;
7224 int isroot = s->tree == s->root;
7225 int i = 0;
7227 if (s->first_displayed_entry == NULL)
7228 return;
7230 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7231 while (i++ < maxscroll) {
7232 if (te == NULL) {
7233 if (!isroot)
7234 s->first_displayed_entry = NULL;
7235 break;
7237 s->first_displayed_entry = te;
7238 te = got_tree_entry_get_prev(s->tree, te);
7242 static const struct got_error *
7243 tree_scroll_down(struct tog_view *view, int maxscroll)
7245 struct tog_tree_view_state *s = &view->state.tree;
7246 struct got_tree_entry *next, *last;
7247 int n = 0;
7249 if (s->first_displayed_entry)
7250 next = got_tree_entry_get_next(s->tree,
7251 s->first_displayed_entry);
7252 else
7253 next = got_object_tree_get_first_entry(s->tree);
7255 last = s->last_displayed_entry;
7256 while (next && n++ < maxscroll) {
7257 if (last) {
7258 s->last_displayed_entry = last;
7259 last = got_tree_entry_get_next(s->tree, last);
7261 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7262 s->first_displayed_entry = next;
7263 next = got_tree_entry_get_next(s->tree, next);
7267 return NULL;
7270 static const struct got_error *
7271 tree_entry_path(char **path, struct tog_parent_trees *parents,
7272 struct got_tree_entry *te)
7274 const struct got_error *err = NULL;
7275 struct tog_parent_tree *pt;
7276 size_t len = 2; /* for leading slash and NUL */
7278 TAILQ_FOREACH(pt, parents, entry)
7279 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7280 + 1 /* slash */;
7281 if (te)
7282 len += strlen(got_tree_entry_get_name(te));
7284 *path = calloc(1, len);
7285 if (path == NULL)
7286 return got_error_from_errno("calloc");
7288 (*path)[0] = '/';
7289 pt = TAILQ_LAST(parents, tog_parent_trees);
7290 while (pt) {
7291 const char *name = got_tree_entry_get_name(pt->selected_entry);
7292 if (strlcat(*path, name, len) >= len) {
7293 err = got_error(GOT_ERR_NO_SPACE);
7294 goto done;
7296 if (strlcat(*path, "/", len) >= len) {
7297 err = got_error(GOT_ERR_NO_SPACE);
7298 goto done;
7300 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7302 if (te) {
7303 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7304 err = got_error(GOT_ERR_NO_SPACE);
7305 goto done;
7308 done:
7309 if (err) {
7310 free(*path);
7311 *path = NULL;
7313 return err;
7316 static const struct got_error *
7317 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7318 struct got_tree_entry *te, struct tog_parent_trees *parents,
7319 struct got_object_id *commit_id, struct got_repository *repo)
7321 const struct got_error *err = NULL;
7322 char *path;
7323 struct tog_view *blame_view;
7325 *new_view = NULL;
7327 err = tree_entry_path(&path, parents, te);
7328 if (err)
7329 return err;
7331 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7332 if (blame_view == NULL) {
7333 err = got_error_from_errno("view_open");
7334 goto done;
7337 err = open_blame_view(blame_view, path, commit_id, repo);
7338 if (err) {
7339 if (err->code == GOT_ERR_CANCELLED)
7340 err = NULL;
7341 view_close(blame_view);
7342 } else
7343 *new_view = blame_view;
7344 done:
7345 free(path);
7346 return err;
7349 static const struct got_error *
7350 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7351 struct tog_tree_view_state *s)
7353 struct tog_view *log_view;
7354 const struct got_error *err = NULL;
7355 char *path;
7357 *new_view = NULL;
7359 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7360 if (log_view == NULL)
7361 return got_error_from_errno("view_open");
7363 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7364 if (err)
7365 return err;
7367 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7368 path, 0);
7369 if (err)
7370 view_close(log_view);
7371 else
7372 *new_view = log_view;
7373 free(path);
7374 return err;
7377 static const struct got_error *
7378 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7379 const char *head_ref_name, struct got_repository *repo)
7381 const struct got_error *err = NULL;
7382 char *commit_id_str = NULL;
7383 struct tog_tree_view_state *s = &view->state.tree;
7384 struct got_commit_object *commit = NULL;
7386 TAILQ_INIT(&s->parents);
7387 STAILQ_INIT(&s->colors);
7389 s->commit_id = got_object_id_dup(commit_id);
7390 if (s->commit_id == NULL)
7391 return got_error_from_errno("got_object_id_dup");
7393 err = got_object_open_as_commit(&commit, repo, commit_id);
7394 if (err)
7395 goto done;
7398 * The root is opened here and will be closed when the view is closed.
7399 * Any visited subtrees and their path-wise parents are opened and
7400 * closed on demand.
7402 err = got_object_open_as_tree(&s->root, repo,
7403 got_object_commit_get_tree_id(commit));
7404 if (err)
7405 goto done;
7406 s->tree = s->root;
7408 err = got_object_id_str(&commit_id_str, commit_id);
7409 if (err != NULL)
7410 goto done;
7412 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7413 err = got_error_from_errno("asprintf");
7414 goto done;
7417 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7418 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7419 if (head_ref_name) {
7420 s->head_ref_name = strdup(head_ref_name);
7421 if (s->head_ref_name == NULL) {
7422 err = got_error_from_errno("strdup");
7423 goto done;
7426 s->repo = repo;
7428 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7429 err = add_color(&s->colors, "\\$$",
7430 TOG_COLOR_TREE_SUBMODULE,
7431 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7432 if (err)
7433 goto done;
7434 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7435 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7436 if (err)
7437 goto done;
7438 err = add_color(&s->colors, "/$",
7439 TOG_COLOR_TREE_DIRECTORY,
7440 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7441 if (err)
7442 goto done;
7444 err = add_color(&s->colors, "\\*$",
7445 TOG_COLOR_TREE_EXECUTABLE,
7446 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7447 if (err)
7448 goto done;
7450 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7451 get_color_value("TOG_COLOR_COMMIT"));
7452 if (err)
7453 goto done;
7456 view->show = show_tree_view;
7457 view->input = input_tree_view;
7458 view->close = close_tree_view;
7459 view->search_start = search_start_tree_view;
7460 view->search_next = search_next_tree_view;
7461 done:
7462 free(commit_id_str);
7463 if (commit)
7464 got_object_commit_close(commit);
7465 if (err)
7466 close_tree_view(view);
7467 return err;
7470 static const struct got_error *
7471 close_tree_view(struct tog_view *view)
7473 struct tog_tree_view_state *s = &view->state.tree;
7475 free_colors(&s->colors);
7476 free(s->tree_label);
7477 s->tree_label = NULL;
7478 free(s->commit_id);
7479 s->commit_id = NULL;
7480 free(s->head_ref_name);
7481 s->head_ref_name = NULL;
7482 while (!TAILQ_EMPTY(&s->parents)) {
7483 struct tog_parent_tree *parent;
7484 parent = TAILQ_FIRST(&s->parents);
7485 TAILQ_REMOVE(&s->parents, parent, entry);
7486 if (parent->tree != s->root)
7487 got_object_tree_close(parent->tree);
7488 free(parent);
7491 if (s->tree != NULL && s->tree != s->root)
7492 got_object_tree_close(s->tree);
7493 if (s->root)
7494 got_object_tree_close(s->root);
7495 return NULL;
7498 static const struct got_error *
7499 search_start_tree_view(struct tog_view *view)
7501 struct tog_tree_view_state *s = &view->state.tree;
7503 s->matched_entry = NULL;
7504 return NULL;
7507 static int
7508 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7510 regmatch_t regmatch;
7512 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7513 0) == 0;
7516 static const struct got_error *
7517 search_next_tree_view(struct tog_view *view)
7519 struct tog_tree_view_state *s = &view->state.tree;
7520 struct got_tree_entry *te = NULL;
7522 if (!view->searching) {
7523 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7524 return NULL;
7527 if (s->matched_entry) {
7528 if (view->searching == TOG_SEARCH_FORWARD) {
7529 if (s->selected_entry)
7530 te = got_tree_entry_get_next(s->tree,
7531 s->selected_entry);
7532 else
7533 te = got_object_tree_get_first_entry(s->tree);
7534 } else {
7535 if (s->selected_entry == NULL)
7536 te = got_object_tree_get_last_entry(s->tree);
7537 else
7538 te = got_tree_entry_get_prev(s->tree,
7539 s->selected_entry);
7541 } else {
7542 if (s->selected_entry)
7543 te = s->selected_entry;
7544 else if (view->searching == TOG_SEARCH_FORWARD)
7545 te = got_object_tree_get_first_entry(s->tree);
7546 else
7547 te = got_object_tree_get_last_entry(s->tree);
7550 while (1) {
7551 if (te == NULL) {
7552 if (s->matched_entry == NULL) {
7553 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7554 return NULL;
7556 if (view->searching == TOG_SEARCH_FORWARD)
7557 te = got_object_tree_get_first_entry(s->tree);
7558 else
7559 te = got_object_tree_get_last_entry(s->tree);
7562 if (match_tree_entry(te, &view->regex)) {
7563 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7564 s->matched_entry = te;
7565 break;
7568 if (view->searching == TOG_SEARCH_FORWARD)
7569 te = got_tree_entry_get_next(s->tree, te);
7570 else
7571 te = got_tree_entry_get_prev(s->tree, te);
7574 if (s->matched_entry) {
7575 s->first_displayed_entry = s->matched_entry;
7576 s->selected = 0;
7579 return NULL;
7582 static const struct got_error *
7583 show_tree_view(struct tog_view *view)
7585 const struct got_error *err = NULL;
7586 struct tog_tree_view_state *s = &view->state.tree;
7587 char *parent_path;
7589 err = tree_entry_path(&parent_path, &s->parents, NULL);
7590 if (err)
7591 return err;
7593 err = draw_tree_entries(view, parent_path);
7594 free(parent_path);
7596 view_border(view);
7597 return err;
7600 static const struct got_error *
7601 tree_goto_line(struct tog_view *view, int nlines)
7603 const struct got_error *err = NULL;
7604 struct tog_tree_view_state *s = &view->state.tree;
7605 struct got_tree_entry **fte, **lte, **ste;
7606 int g, last, first = 1, i = 1;
7607 int root = s->tree == s->root;
7608 int off = root ? 1 : 2;
7610 g = view->gline;
7611 view->gline = 0;
7613 if (g == 0)
7614 g = 1;
7615 else if (g > got_object_tree_get_nentries(s->tree))
7616 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7618 fte = &s->first_displayed_entry;
7619 lte = &s->last_displayed_entry;
7620 ste = &s->selected_entry;
7622 if (*fte != NULL) {
7623 first = got_tree_entry_get_index(*fte);
7624 first += off; /* account for ".." */
7626 last = got_tree_entry_get_index(*lte);
7627 last += off;
7629 if (g >= first && g <= last && g - first < nlines) {
7630 s->selected = g - first;
7631 return NULL; /* gline is on the current page */
7634 if (*ste != NULL) {
7635 i = got_tree_entry_get_index(*ste);
7636 i += off;
7639 if (i < g) {
7640 err = tree_scroll_down(view, g - i);
7641 if (err)
7642 return err;
7643 if (got_tree_entry_get_index(*lte) >=
7644 got_object_tree_get_nentries(s->tree) - 1 &&
7645 first + s->selected < g &&
7646 s->selected < s->ndisplayed - 1) {
7647 first = got_tree_entry_get_index(*fte);
7648 first += off;
7649 s->selected = g - first;
7651 } else if (i > g)
7652 tree_scroll_up(s, i - g);
7654 if (g < nlines &&
7655 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7656 s->selected = g - 1;
7658 return NULL;
7661 static const struct got_error *
7662 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7664 const struct got_error *err = NULL;
7665 struct tog_tree_view_state *s = &view->state.tree;
7666 struct got_tree_entry *te;
7667 int n, nscroll = view->nlines - 3;
7669 if (view->gline)
7670 return tree_goto_line(view, nscroll);
7672 switch (ch) {
7673 case '0':
7674 case '$':
7675 case KEY_RIGHT:
7676 case 'l':
7677 case KEY_LEFT:
7678 case 'h':
7679 horizontal_scroll_input(view, ch);
7680 break;
7681 case 'i':
7682 s->show_ids = !s->show_ids;
7683 view->count = 0;
7684 break;
7685 case 'L':
7686 view->count = 0;
7687 if (!s->selected_entry)
7688 break;
7689 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7690 break;
7691 case 'R':
7692 view->count = 0;
7693 err = view_request_new(new_view, view, TOG_VIEW_REF);
7694 break;
7695 case 'g':
7696 case '=':
7697 case KEY_HOME:
7698 s->selected = 0;
7699 view->count = 0;
7700 if (s->tree == s->root)
7701 s->first_displayed_entry =
7702 got_object_tree_get_first_entry(s->tree);
7703 else
7704 s->first_displayed_entry = NULL;
7705 break;
7706 case 'G':
7707 case '*':
7708 case KEY_END: {
7709 int eos = view->nlines - 3;
7711 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7712 --eos; /* border */
7713 s->selected = 0;
7714 view->count = 0;
7715 te = got_object_tree_get_last_entry(s->tree);
7716 for (n = 0; n < eos; n++) {
7717 if (te == NULL) {
7718 if (s->tree != s->root) {
7719 s->first_displayed_entry = NULL;
7720 n++;
7722 break;
7724 s->first_displayed_entry = te;
7725 te = got_tree_entry_get_prev(s->tree, te);
7727 if (n > 0)
7728 s->selected = n - 1;
7729 break;
7731 case 'k':
7732 case KEY_UP:
7733 case CTRL('p'):
7734 if (s->selected > 0) {
7735 s->selected--;
7736 break;
7738 tree_scroll_up(s, 1);
7739 if (s->selected_entry == NULL ||
7740 (s->tree == s->root && s->selected_entry ==
7741 got_object_tree_get_first_entry(s->tree)))
7742 view->count = 0;
7743 break;
7744 case CTRL('u'):
7745 case 'u':
7746 nscroll /= 2;
7747 /* FALL THROUGH */
7748 case KEY_PPAGE:
7749 case CTRL('b'):
7750 case 'b':
7751 if (s->tree == s->root) {
7752 if (got_object_tree_get_first_entry(s->tree) ==
7753 s->first_displayed_entry)
7754 s->selected -= MIN(s->selected, nscroll);
7755 } else {
7756 if (s->first_displayed_entry == NULL)
7757 s->selected -= MIN(s->selected, nscroll);
7759 tree_scroll_up(s, MAX(0, nscroll));
7760 if (s->selected_entry == NULL ||
7761 (s->tree == s->root && s->selected_entry ==
7762 got_object_tree_get_first_entry(s->tree)))
7763 view->count = 0;
7764 break;
7765 case 'j':
7766 case KEY_DOWN:
7767 case CTRL('n'):
7768 if (s->selected < s->ndisplayed - 1) {
7769 s->selected++;
7770 break;
7772 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7773 == NULL) {
7774 /* can't scroll any further */
7775 view->count = 0;
7776 break;
7778 tree_scroll_down(view, 1);
7779 break;
7780 case CTRL('d'):
7781 case 'd':
7782 nscroll /= 2;
7783 /* FALL THROUGH */
7784 case KEY_NPAGE:
7785 case CTRL('f'):
7786 case 'f':
7787 case ' ':
7788 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7789 == NULL) {
7790 /* can't scroll any further; move cursor down */
7791 if (s->selected < s->ndisplayed - 1)
7792 s->selected += MIN(nscroll,
7793 s->ndisplayed - s->selected - 1);
7794 else
7795 view->count = 0;
7796 break;
7798 tree_scroll_down(view, nscroll);
7799 break;
7800 case KEY_ENTER:
7801 case '\r':
7802 case KEY_BACKSPACE:
7803 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7804 struct tog_parent_tree *parent;
7805 /* user selected '..' */
7806 if (s->tree == s->root) {
7807 view->count = 0;
7808 break;
7810 parent = TAILQ_FIRST(&s->parents);
7811 TAILQ_REMOVE(&s->parents, parent,
7812 entry);
7813 got_object_tree_close(s->tree);
7814 s->tree = parent->tree;
7815 s->first_displayed_entry =
7816 parent->first_displayed_entry;
7817 s->selected_entry =
7818 parent->selected_entry;
7819 s->selected = parent->selected;
7820 if (s->selected > view->nlines - 3) {
7821 err = offset_selection_down(view);
7822 if (err)
7823 break;
7825 free(parent);
7826 } else if (S_ISDIR(got_tree_entry_get_mode(
7827 s->selected_entry))) {
7828 struct got_tree_object *subtree;
7829 view->count = 0;
7830 err = got_object_open_as_tree(&subtree, s->repo,
7831 got_tree_entry_get_id(s->selected_entry));
7832 if (err)
7833 break;
7834 err = tree_view_visit_subtree(s, subtree);
7835 if (err) {
7836 got_object_tree_close(subtree);
7837 break;
7839 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7840 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7841 break;
7842 case KEY_RESIZE:
7843 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7844 s->selected = view->nlines - 4;
7845 view->count = 0;
7846 break;
7847 default:
7848 view->count = 0;
7849 break;
7852 return err;
7855 __dead static void
7856 usage_tree(void)
7858 endwin();
7859 fprintf(stderr,
7860 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7861 getprogname());
7862 exit(1);
7865 static const struct got_error *
7866 cmd_tree(int argc, char *argv[])
7868 const struct got_error *io_err, *error;
7869 struct got_repository *repo = NULL;
7870 struct got_worktree *worktree = NULL;
7871 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7872 struct got_object_id *commit_id = NULL;
7873 struct got_commit_object *commit = NULL;
7874 const char *commit_id_arg = NULL;
7875 char *label = NULL;
7876 struct got_reference *ref = NULL;
7877 const char *head_ref_name = NULL;
7878 int ch;
7879 struct tog_view *view;
7880 int *pack_fds = NULL;
7882 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7883 switch (ch) {
7884 case 'c':
7885 commit_id_arg = optarg;
7886 break;
7887 case 'r':
7888 repo_path = realpath(optarg, NULL);
7889 if (repo_path == NULL)
7890 return got_error_from_errno2("realpath",
7891 optarg);
7892 break;
7893 default:
7894 usage_tree();
7895 /* NOTREACHED */
7899 argc -= optind;
7900 argv += optind;
7902 if (argc > 1)
7903 usage_tree();
7905 error = got_repo_pack_fds_open(&pack_fds);
7906 if (error != NULL)
7907 goto done;
7909 if (repo_path == NULL) {
7910 cwd = getcwd(NULL, 0);
7911 if (cwd == NULL)
7912 return got_error_from_errno("getcwd");
7913 error = got_worktree_open(&worktree, cwd);
7914 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7915 goto done;
7916 if (worktree)
7917 repo_path =
7918 strdup(got_worktree_get_repo_path(worktree));
7919 else
7920 repo_path = strdup(cwd);
7921 if (repo_path == NULL) {
7922 error = got_error_from_errno("strdup");
7923 goto done;
7927 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7928 if (error != NULL)
7929 goto done;
7931 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7932 repo, worktree);
7933 if (error)
7934 goto done;
7936 init_curses();
7938 error = apply_unveil(got_repo_get_path(repo), NULL);
7939 if (error)
7940 goto done;
7942 error = tog_load_refs(repo, 0);
7943 if (error)
7944 goto done;
7946 if (commit_id_arg == NULL) {
7947 error = got_repo_match_object_id(&commit_id, &label,
7948 worktree ? got_worktree_get_head_ref_name(worktree) :
7949 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7950 if (error)
7951 goto done;
7952 head_ref_name = label;
7953 } else {
7954 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7955 if (error == NULL)
7956 head_ref_name = got_ref_get_name(ref);
7957 else if (error->code != GOT_ERR_NOT_REF)
7958 goto done;
7959 error = got_repo_match_object_id(&commit_id, NULL,
7960 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7961 if (error)
7962 goto done;
7965 error = got_object_open_as_commit(&commit, repo, commit_id);
7966 if (error)
7967 goto done;
7969 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7970 if (view == NULL) {
7971 error = got_error_from_errno("view_open");
7972 goto done;
7974 error = open_tree_view(view, commit_id, head_ref_name, repo);
7975 if (error)
7976 goto done;
7977 if (!got_path_is_root_dir(in_repo_path)) {
7978 error = tree_view_walk_path(&view->state.tree, commit,
7979 in_repo_path);
7980 if (error)
7981 goto done;
7984 if (worktree) {
7985 /* Release work tree lock. */
7986 got_worktree_close(worktree);
7987 worktree = NULL;
7989 error = view_loop(view);
7990 done:
7991 free(repo_path);
7992 free(cwd);
7993 free(commit_id);
7994 free(label);
7995 if (ref)
7996 got_ref_close(ref);
7997 if (repo) {
7998 const struct got_error *close_err = got_repo_close(repo);
7999 if (error == NULL)
8000 error = close_err;
8002 if (pack_fds) {
8003 const struct got_error *pack_err =
8004 got_repo_pack_fds_close(pack_fds);
8005 if (error == NULL)
8006 error = pack_err;
8008 if (using_mock_io) {
8009 io_err = tog_io_close();
8010 if (error == NULL)
8011 error = io_err;
8013 tog_free_refs();
8014 return error;
8017 static const struct got_error *
8018 ref_view_load_refs(struct tog_ref_view_state *s)
8020 struct got_reflist_entry *sre;
8021 struct tog_reflist_entry *re;
8023 s->nrefs = 0;
8024 TAILQ_FOREACH(sre, &tog_refs, entry) {
8025 if (strncmp(got_ref_get_name(sre->ref),
8026 "refs/got/", 9) == 0 &&
8027 strncmp(got_ref_get_name(sre->ref),
8028 "refs/got/backup/", 16) != 0)
8029 continue;
8031 re = malloc(sizeof(*re));
8032 if (re == NULL)
8033 return got_error_from_errno("malloc");
8035 re->ref = got_ref_dup(sre->ref);
8036 if (re->ref == NULL)
8037 return got_error_from_errno("got_ref_dup");
8038 re->idx = s->nrefs++;
8039 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8042 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8043 return NULL;
8046 static void
8047 ref_view_free_refs(struct tog_ref_view_state *s)
8049 struct tog_reflist_entry *re;
8051 while (!TAILQ_EMPTY(&s->refs)) {
8052 re = TAILQ_FIRST(&s->refs);
8053 TAILQ_REMOVE(&s->refs, re, entry);
8054 got_ref_close(re->ref);
8055 free(re);
8059 static const struct got_error *
8060 open_ref_view(struct tog_view *view, struct got_repository *repo)
8062 const struct got_error *err = NULL;
8063 struct tog_ref_view_state *s = &view->state.ref;
8065 s->selected_entry = 0;
8066 s->repo = repo;
8068 TAILQ_INIT(&s->refs);
8069 STAILQ_INIT(&s->colors);
8071 err = ref_view_load_refs(s);
8072 if (err)
8073 return err;
8075 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8076 err = add_color(&s->colors, "^refs/heads/",
8077 TOG_COLOR_REFS_HEADS,
8078 get_color_value("TOG_COLOR_REFS_HEADS"));
8079 if (err)
8080 goto done;
8082 err = add_color(&s->colors, "^refs/tags/",
8083 TOG_COLOR_REFS_TAGS,
8084 get_color_value("TOG_COLOR_REFS_TAGS"));
8085 if (err)
8086 goto done;
8088 err = add_color(&s->colors, "^refs/remotes/",
8089 TOG_COLOR_REFS_REMOTES,
8090 get_color_value("TOG_COLOR_REFS_REMOTES"));
8091 if (err)
8092 goto done;
8094 err = add_color(&s->colors, "^refs/got/backup/",
8095 TOG_COLOR_REFS_BACKUP,
8096 get_color_value("TOG_COLOR_REFS_BACKUP"));
8097 if (err)
8098 goto done;
8101 view->show = show_ref_view;
8102 view->input = input_ref_view;
8103 view->close = close_ref_view;
8104 view->search_start = search_start_ref_view;
8105 view->search_next = search_next_ref_view;
8106 done:
8107 if (err)
8108 free_colors(&s->colors);
8109 return err;
8112 static const struct got_error *
8113 close_ref_view(struct tog_view *view)
8115 struct tog_ref_view_state *s = &view->state.ref;
8117 ref_view_free_refs(s);
8118 free_colors(&s->colors);
8120 return NULL;
8123 static const struct got_error *
8124 resolve_reflist_entry(struct got_object_id **commit_id,
8125 struct tog_reflist_entry *re, struct got_repository *repo)
8127 const struct got_error *err = NULL;
8128 struct got_object_id *obj_id;
8129 struct got_tag_object *tag = NULL;
8130 int obj_type;
8132 *commit_id = NULL;
8134 err = got_ref_resolve(&obj_id, repo, re->ref);
8135 if (err)
8136 return err;
8138 err = got_object_get_type(&obj_type, repo, obj_id);
8139 if (err)
8140 goto done;
8142 switch (obj_type) {
8143 case GOT_OBJ_TYPE_COMMIT:
8144 *commit_id = obj_id;
8145 break;
8146 case GOT_OBJ_TYPE_TAG:
8147 err = got_object_open_as_tag(&tag, repo, obj_id);
8148 if (err)
8149 goto done;
8150 free(obj_id);
8151 err = got_object_get_type(&obj_type, repo,
8152 got_object_tag_get_object_id(tag));
8153 if (err)
8154 goto done;
8155 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8156 err = got_error(GOT_ERR_OBJ_TYPE);
8157 goto done;
8159 *commit_id = got_object_id_dup(
8160 got_object_tag_get_object_id(tag));
8161 if (*commit_id == NULL) {
8162 err = got_error_from_errno("got_object_id_dup");
8163 goto done;
8165 break;
8166 default:
8167 err = got_error(GOT_ERR_OBJ_TYPE);
8168 break;
8171 done:
8172 if (tag)
8173 got_object_tag_close(tag);
8174 if (err) {
8175 free(*commit_id);
8176 *commit_id = NULL;
8178 return err;
8181 static const struct got_error *
8182 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8183 struct tog_reflist_entry *re, struct got_repository *repo)
8185 struct tog_view *log_view;
8186 const struct got_error *err = NULL;
8187 struct got_object_id *commit_id = NULL;
8189 *new_view = NULL;
8191 err = resolve_reflist_entry(&commit_id, re, repo);
8192 if (err) {
8193 if (err->code != GOT_ERR_OBJ_TYPE)
8194 return err;
8195 else
8196 return NULL;
8199 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8200 if (log_view == NULL) {
8201 err = got_error_from_errno("view_open");
8202 goto done;
8205 err = open_log_view(log_view, commit_id, repo,
8206 got_ref_get_name(re->ref), "", 0);
8207 done:
8208 if (err)
8209 view_close(log_view);
8210 else
8211 *new_view = log_view;
8212 free(commit_id);
8213 return err;
8216 static void
8217 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8219 struct tog_reflist_entry *re;
8220 int i = 0;
8222 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8223 return;
8225 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8226 while (i++ < maxscroll) {
8227 if (re == NULL)
8228 break;
8229 s->first_displayed_entry = re;
8230 re = TAILQ_PREV(re, tog_reflist_head, entry);
8234 static const struct got_error *
8235 ref_scroll_down(struct tog_view *view, int maxscroll)
8237 struct tog_ref_view_state *s = &view->state.ref;
8238 struct tog_reflist_entry *next, *last;
8239 int n = 0;
8241 if (s->first_displayed_entry)
8242 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8243 else
8244 next = TAILQ_FIRST(&s->refs);
8246 last = s->last_displayed_entry;
8247 while (next && n++ < maxscroll) {
8248 if (last) {
8249 s->last_displayed_entry = last;
8250 last = TAILQ_NEXT(last, entry);
8252 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8253 s->first_displayed_entry = next;
8254 next = TAILQ_NEXT(next, entry);
8258 return NULL;
8261 static const struct got_error *
8262 search_start_ref_view(struct tog_view *view)
8264 struct tog_ref_view_state *s = &view->state.ref;
8266 s->matched_entry = NULL;
8267 return NULL;
8270 static int
8271 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8273 regmatch_t regmatch;
8275 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8276 0) == 0;
8279 static const struct got_error *
8280 search_next_ref_view(struct tog_view *view)
8282 struct tog_ref_view_state *s = &view->state.ref;
8283 struct tog_reflist_entry *re = NULL;
8285 if (!view->searching) {
8286 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8287 return NULL;
8290 if (s->matched_entry) {
8291 if (view->searching == TOG_SEARCH_FORWARD) {
8292 if (s->selected_entry)
8293 re = TAILQ_NEXT(s->selected_entry, entry);
8294 else
8295 re = TAILQ_PREV(s->selected_entry,
8296 tog_reflist_head, entry);
8297 } else {
8298 if (s->selected_entry == NULL)
8299 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8300 else
8301 re = TAILQ_PREV(s->selected_entry,
8302 tog_reflist_head, entry);
8304 } else {
8305 if (s->selected_entry)
8306 re = s->selected_entry;
8307 else if (view->searching == TOG_SEARCH_FORWARD)
8308 re = TAILQ_FIRST(&s->refs);
8309 else
8310 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8313 while (1) {
8314 if (re == NULL) {
8315 if (s->matched_entry == NULL) {
8316 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8317 return NULL;
8319 if (view->searching == TOG_SEARCH_FORWARD)
8320 re = TAILQ_FIRST(&s->refs);
8321 else
8322 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8325 if (match_reflist_entry(re, &view->regex)) {
8326 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8327 s->matched_entry = re;
8328 break;
8331 if (view->searching == TOG_SEARCH_FORWARD)
8332 re = TAILQ_NEXT(re, entry);
8333 else
8334 re = TAILQ_PREV(re, tog_reflist_head, entry);
8337 if (s->matched_entry) {
8338 s->first_displayed_entry = s->matched_entry;
8339 s->selected = 0;
8342 return NULL;
8345 static const struct got_error *
8346 show_ref_view(struct tog_view *view)
8348 const struct got_error *err = NULL;
8349 struct tog_ref_view_state *s = &view->state.ref;
8350 struct tog_reflist_entry *re;
8351 char *line = NULL;
8352 wchar_t *wline;
8353 struct tog_color *tc;
8354 int width, n, scrollx;
8355 int limit = view->nlines;
8357 werase(view->window);
8359 s->ndisplayed = 0;
8360 if (view_is_hsplit_top(view))
8361 --limit; /* border */
8363 if (limit == 0)
8364 return NULL;
8366 re = s->first_displayed_entry;
8368 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8369 s->nrefs) == -1)
8370 return got_error_from_errno("asprintf");
8372 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8373 if (err) {
8374 free(line);
8375 return err;
8377 if (view_needs_focus_indication(view))
8378 wstandout(view->window);
8379 waddwstr(view->window, wline);
8380 while (width++ < view->ncols)
8381 waddch(view->window, ' ');
8382 if (view_needs_focus_indication(view))
8383 wstandend(view->window);
8384 free(wline);
8385 wline = NULL;
8386 free(line);
8387 line = NULL;
8388 if (--limit <= 0)
8389 return NULL;
8391 n = 0;
8392 view->maxx = 0;
8393 while (re && limit > 0) {
8394 char *line = NULL;
8395 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8397 if (s->show_date) {
8398 struct got_commit_object *ci;
8399 struct got_tag_object *tag;
8400 struct got_object_id *id;
8401 struct tm tm;
8402 time_t t;
8404 err = got_ref_resolve(&id, s->repo, re->ref);
8405 if (err)
8406 return err;
8407 err = got_object_open_as_tag(&tag, s->repo, id);
8408 if (err) {
8409 if (err->code != GOT_ERR_OBJ_TYPE) {
8410 free(id);
8411 return err;
8413 err = got_object_open_as_commit(&ci, s->repo,
8414 id);
8415 if (err) {
8416 free(id);
8417 return err;
8419 t = got_object_commit_get_committer_time(ci);
8420 got_object_commit_close(ci);
8421 } else {
8422 t = got_object_tag_get_tagger_time(tag);
8423 got_object_tag_close(tag);
8425 free(id);
8426 if (gmtime_r(&t, &tm) == NULL)
8427 return got_error_from_errno("gmtime_r");
8428 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8429 return got_error(GOT_ERR_NO_SPACE);
8431 if (got_ref_is_symbolic(re->ref)) {
8432 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8433 ymd : "", got_ref_get_name(re->ref),
8434 got_ref_get_symref_target(re->ref)) == -1)
8435 return got_error_from_errno("asprintf");
8436 } else if (s->show_ids) {
8437 struct got_object_id *id;
8438 char *id_str;
8439 err = got_ref_resolve(&id, s->repo, re->ref);
8440 if (err)
8441 return err;
8442 err = got_object_id_str(&id_str, id);
8443 if (err) {
8444 free(id);
8445 return err;
8447 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8448 got_ref_get_name(re->ref), id_str) == -1) {
8449 err = got_error_from_errno("asprintf");
8450 free(id);
8451 free(id_str);
8452 return err;
8454 free(id);
8455 free(id_str);
8456 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8457 got_ref_get_name(re->ref)) == -1)
8458 return got_error_from_errno("asprintf");
8460 /* use full line width to determine view->maxx */
8461 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8462 if (err) {
8463 free(line);
8464 return err;
8466 view->maxx = MAX(view->maxx, width);
8467 free(wline);
8468 wline = NULL;
8470 err = format_line(&wline, &width, &scrollx, line, view->x,
8471 view->ncols, 0, 0);
8472 if (err) {
8473 free(line);
8474 return err;
8476 if (n == s->selected) {
8477 if (view->focussed)
8478 wstandout(view->window);
8479 s->selected_entry = re;
8481 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8482 if (tc)
8483 wattr_on(view->window,
8484 COLOR_PAIR(tc->colorpair), NULL);
8485 waddwstr(view->window, &wline[scrollx]);
8486 if (tc)
8487 wattr_off(view->window,
8488 COLOR_PAIR(tc->colorpair), NULL);
8489 if (width < view->ncols)
8490 waddch(view->window, '\n');
8491 if (n == s->selected && view->focussed)
8492 wstandend(view->window);
8493 free(line);
8494 free(wline);
8495 wline = NULL;
8496 n++;
8497 s->ndisplayed++;
8498 s->last_displayed_entry = re;
8500 limit--;
8501 re = TAILQ_NEXT(re, entry);
8504 view_border(view);
8505 return err;
8508 static const struct got_error *
8509 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8510 struct tog_reflist_entry *re, struct got_repository *repo)
8512 const struct got_error *err = NULL;
8513 struct got_object_id *commit_id = NULL;
8514 struct tog_view *tree_view;
8516 *new_view = NULL;
8518 err = resolve_reflist_entry(&commit_id, re, repo);
8519 if (err) {
8520 if (err->code != GOT_ERR_OBJ_TYPE)
8521 return err;
8522 else
8523 return NULL;
8527 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8528 if (tree_view == NULL) {
8529 err = got_error_from_errno("view_open");
8530 goto done;
8533 err = open_tree_view(tree_view, commit_id,
8534 got_ref_get_name(re->ref), repo);
8535 if (err)
8536 goto done;
8538 *new_view = tree_view;
8539 done:
8540 free(commit_id);
8541 return err;
8544 static const struct got_error *
8545 ref_goto_line(struct tog_view *view, int nlines)
8547 const struct got_error *err = NULL;
8548 struct tog_ref_view_state *s = &view->state.ref;
8549 int g, idx = s->selected_entry->idx;
8551 g = view->gline;
8552 view->gline = 0;
8554 if (g == 0)
8555 g = 1;
8556 else if (g > s->nrefs)
8557 g = s->nrefs;
8559 if (g >= s->first_displayed_entry->idx + 1 &&
8560 g <= s->last_displayed_entry->idx + 1 &&
8561 g - s->first_displayed_entry->idx - 1 < nlines) {
8562 s->selected = g - s->first_displayed_entry->idx - 1;
8563 return NULL;
8566 if (idx + 1 < g) {
8567 err = ref_scroll_down(view, g - idx - 1);
8568 if (err)
8569 return err;
8570 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8571 s->first_displayed_entry->idx + s->selected < g &&
8572 s->selected < s->ndisplayed - 1)
8573 s->selected = g - s->first_displayed_entry->idx - 1;
8574 } else if (idx + 1 > g)
8575 ref_scroll_up(s, idx - g + 1);
8577 if (g < nlines && s->first_displayed_entry->idx == 0)
8578 s->selected = g - 1;
8580 return NULL;
8584 static const struct got_error *
8585 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8587 const struct got_error *err = NULL;
8588 struct tog_ref_view_state *s = &view->state.ref;
8589 struct tog_reflist_entry *re;
8590 int n, nscroll = view->nlines - 1;
8592 if (view->gline)
8593 return ref_goto_line(view, nscroll);
8595 switch (ch) {
8596 case '0':
8597 case '$':
8598 case KEY_RIGHT:
8599 case 'l':
8600 case KEY_LEFT:
8601 case 'h':
8602 horizontal_scroll_input(view, ch);
8603 break;
8604 case 'i':
8605 s->show_ids = !s->show_ids;
8606 view->count = 0;
8607 break;
8608 case 'm':
8609 s->show_date = !s->show_date;
8610 view->count = 0;
8611 break;
8612 case 'o':
8613 s->sort_by_date = !s->sort_by_date;
8614 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8615 view->count = 0;
8616 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8617 got_ref_cmp_by_commit_timestamp_descending :
8618 tog_ref_cmp_by_name, s->repo);
8619 if (err)
8620 break;
8621 got_reflist_object_id_map_free(tog_refs_idmap);
8622 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8623 &tog_refs, s->repo);
8624 if (err)
8625 break;
8626 ref_view_free_refs(s);
8627 err = ref_view_load_refs(s);
8628 break;
8629 case KEY_ENTER:
8630 case '\r':
8631 view->count = 0;
8632 if (!s->selected_entry)
8633 break;
8634 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8635 break;
8636 case 'T':
8637 view->count = 0;
8638 if (!s->selected_entry)
8639 break;
8640 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8641 break;
8642 case 'g':
8643 case '=':
8644 case KEY_HOME:
8645 s->selected = 0;
8646 view->count = 0;
8647 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8648 break;
8649 case 'G':
8650 case '*':
8651 case KEY_END: {
8652 int eos = view->nlines - 1;
8654 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8655 --eos; /* border */
8656 s->selected = 0;
8657 view->count = 0;
8658 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8659 for (n = 0; n < eos; n++) {
8660 if (re == NULL)
8661 break;
8662 s->first_displayed_entry = re;
8663 re = TAILQ_PREV(re, tog_reflist_head, entry);
8665 if (n > 0)
8666 s->selected = n - 1;
8667 break;
8669 case 'k':
8670 case KEY_UP:
8671 case CTRL('p'):
8672 if (s->selected > 0) {
8673 s->selected--;
8674 break;
8676 ref_scroll_up(s, 1);
8677 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8678 view->count = 0;
8679 break;
8680 case CTRL('u'):
8681 case 'u':
8682 nscroll /= 2;
8683 /* FALL THROUGH */
8684 case KEY_PPAGE:
8685 case CTRL('b'):
8686 case 'b':
8687 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8688 s->selected -= MIN(nscroll, s->selected);
8689 ref_scroll_up(s, MAX(0, nscroll));
8690 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8691 view->count = 0;
8692 break;
8693 case 'j':
8694 case KEY_DOWN:
8695 case CTRL('n'):
8696 if (s->selected < s->ndisplayed - 1) {
8697 s->selected++;
8698 break;
8700 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8701 /* can't scroll any further */
8702 view->count = 0;
8703 break;
8705 ref_scroll_down(view, 1);
8706 break;
8707 case CTRL('d'):
8708 case 'd':
8709 nscroll /= 2;
8710 /* FALL THROUGH */
8711 case KEY_NPAGE:
8712 case CTRL('f'):
8713 case 'f':
8714 case ' ':
8715 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8716 /* can't scroll any further; move cursor down */
8717 if (s->selected < s->ndisplayed - 1)
8718 s->selected += MIN(nscroll,
8719 s->ndisplayed - s->selected - 1);
8720 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8721 s->selected += s->ndisplayed - s->selected - 1;
8722 view->count = 0;
8723 break;
8725 ref_scroll_down(view, nscroll);
8726 break;
8727 case CTRL('l'):
8728 view->count = 0;
8729 tog_free_refs();
8730 err = tog_load_refs(s->repo, s->sort_by_date);
8731 if (err)
8732 break;
8733 ref_view_free_refs(s);
8734 err = ref_view_load_refs(s);
8735 break;
8736 case KEY_RESIZE:
8737 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8738 s->selected = view->nlines - 2;
8739 break;
8740 default:
8741 view->count = 0;
8742 break;
8745 return err;
8748 __dead static void
8749 usage_ref(void)
8751 endwin();
8752 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8753 getprogname());
8754 exit(1);
8757 static const struct got_error *
8758 cmd_ref(int argc, char *argv[])
8760 const struct got_error *io_err, *error;
8761 struct got_repository *repo = NULL;
8762 struct got_worktree *worktree = NULL;
8763 char *cwd = NULL, *repo_path = NULL;
8764 int ch;
8765 struct tog_view *view;
8766 int *pack_fds = NULL;
8768 while ((ch = getopt(argc, argv, "r:")) != -1) {
8769 switch (ch) {
8770 case 'r':
8771 repo_path = realpath(optarg, NULL);
8772 if (repo_path == NULL)
8773 return got_error_from_errno2("realpath",
8774 optarg);
8775 break;
8776 default:
8777 usage_ref();
8778 /* NOTREACHED */
8782 argc -= optind;
8783 argv += optind;
8785 if (argc > 1)
8786 usage_ref();
8788 error = got_repo_pack_fds_open(&pack_fds);
8789 if (error != NULL)
8790 goto done;
8792 if (repo_path == NULL) {
8793 cwd = getcwd(NULL, 0);
8794 if (cwd == NULL)
8795 return got_error_from_errno("getcwd");
8796 error = got_worktree_open(&worktree, cwd);
8797 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8798 goto done;
8799 if (worktree)
8800 repo_path =
8801 strdup(got_worktree_get_repo_path(worktree));
8802 else
8803 repo_path = strdup(cwd);
8804 if (repo_path == NULL) {
8805 error = got_error_from_errno("strdup");
8806 goto done;
8810 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8811 if (error != NULL)
8812 goto done;
8814 init_curses();
8816 error = apply_unveil(got_repo_get_path(repo), NULL);
8817 if (error)
8818 goto done;
8820 error = tog_load_refs(repo, 0);
8821 if (error)
8822 goto done;
8824 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8825 if (view == NULL) {
8826 error = got_error_from_errno("view_open");
8827 goto done;
8830 error = open_ref_view(view, repo);
8831 if (error)
8832 goto done;
8834 if (worktree) {
8835 /* Release work tree lock. */
8836 got_worktree_close(worktree);
8837 worktree = NULL;
8839 error = view_loop(view);
8840 done:
8841 free(repo_path);
8842 free(cwd);
8843 if (repo) {
8844 const struct got_error *close_err = got_repo_close(repo);
8845 if (close_err)
8846 error = close_err;
8848 if (pack_fds) {
8849 const struct got_error *pack_err =
8850 got_repo_pack_fds_close(pack_fds);
8851 if (error == NULL)
8852 error = pack_err;
8854 if (using_mock_io) {
8855 io_err = tog_io_close();
8856 if (error == NULL)
8857 error = io_err;
8859 tog_free_refs();
8860 return error;
8863 static const struct got_error*
8864 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8865 const char *str)
8867 size_t len;
8869 if (win == NULL)
8870 win = stdscr;
8872 len = strlen(str);
8873 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8875 if (focus)
8876 wstandout(win);
8877 if (mvwprintw(win, y, x, "%s", str) == ERR)
8878 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8879 if (focus)
8880 wstandend(win);
8882 return NULL;
8885 static const struct got_error *
8886 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8888 off_t *p;
8890 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8891 if (p == NULL) {
8892 free(*line_offsets);
8893 *line_offsets = NULL;
8894 return got_error_from_errno("reallocarray");
8897 *line_offsets = p;
8898 (*line_offsets)[*nlines] = off;
8899 ++(*nlines);
8900 return NULL;
8903 static const struct got_error *
8904 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8906 *ret = 0;
8908 for (;n > 0; --n, ++km) {
8909 char *t0, *t, *k;
8910 size_t len = 1;
8912 if (km->keys == NULL)
8913 continue;
8915 t = t0 = strdup(km->keys);
8916 if (t0 == NULL)
8917 return got_error_from_errno("strdup");
8919 len += strlen(t);
8920 while ((k = strsep(&t, " ")) != NULL)
8921 len += strlen(k) > 1 ? 2 : 0;
8922 free(t0);
8923 *ret = MAX(*ret, len);
8926 return NULL;
8930 * Write keymap section headers, keys, and key info in km to f.
8931 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8932 * wrap control and symbolic keys in guillemets, else use <>.
8934 static const struct got_error *
8935 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8937 int n, len = width;
8939 if (km->keys) {
8940 static const char *u8_glyph[] = {
8941 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8942 "\xe2\x80\xba" /* U+203A (utf8 >) */
8944 char *t0, *t, *k;
8945 int cs, s, first = 1;
8947 cs = got_locale_is_utf8();
8949 t = t0 = strdup(km->keys);
8950 if (t0 == NULL)
8951 return got_error_from_errno("strdup");
8953 len = strlen(km->keys);
8954 while ((k = strsep(&t, " ")) != NULL) {
8955 s = strlen(k) > 1; /* control or symbolic key */
8956 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8957 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8958 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8959 if (n < 0) {
8960 free(t0);
8961 return got_error_from_errno("fprintf");
8963 first = 0;
8964 len += s ? 2 : 0;
8965 *off += n;
8967 free(t0);
8969 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8970 if (n < 0)
8971 return got_error_from_errno("fprintf");
8972 *off += n;
8974 return NULL;
8977 static const struct got_error *
8978 format_help(struct tog_help_view_state *s)
8980 const struct got_error *err = NULL;
8981 off_t off = 0;
8982 int i, max, n, show = s->all;
8983 static const struct tog_key_map km[] = {
8984 #define KEYMAP_(info, type) { NULL, (info), type }
8985 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8986 GENERATE_HELP
8987 #undef KEYMAP_
8988 #undef KEY_
8991 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8992 if (err)
8993 return err;
8995 n = nitems(km);
8996 err = max_key_str(&max, km, n);
8997 if (err)
8998 return err;
9000 for (i = 0; i < n; ++i) {
9001 if (km[i].keys == NULL) {
9002 show = s->all;
9003 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9004 km[i].type == s->type || s->all)
9005 show = 1;
9007 if (show) {
9008 err = format_help_line(&off, s->f, &km[i], max);
9009 if (err)
9010 return err;
9011 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9012 if (err)
9013 return err;
9016 fputc('\n', s->f);
9017 ++off;
9018 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9019 return err;
9022 static const struct got_error *
9023 create_help(struct tog_help_view_state *s)
9025 FILE *f;
9026 const struct got_error *err;
9028 free(s->line_offsets);
9029 s->line_offsets = NULL;
9030 s->nlines = 0;
9032 f = got_opentemp();
9033 if (f == NULL)
9034 return got_error_from_errno("got_opentemp");
9035 s->f = f;
9037 err = format_help(s);
9038 if (err)
9039 return err;
9041 if (s->f && fflush(s->f) != 0)
9042 return got_error_from_errno("fflush");
9044 return NULL;
9047 static const struct got_error *
9048 search_start_help_view(struct tog_view *view)
9050 view->state.help.matched_line = 0;
9051 return NULL;
9054 static void
9055 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9056 size_t *nlines, int **first, int **last, int **match, int **selected)
9058 struct tog_help_view_state *s = &view->state.help;
9060 *f = s->f;
9061 *nlines = s->nlines;
9062 *line_offsets = s->line_offsets;
9063 *match = &s->matched_line;
9064 *first = &s->first_displayed_line;
9065 *last = &s->last_displayed_line;
9066 *selected = &s->selected_line;
9069 static const struct got_error *
9070 show_help_view(struct tog_view *view)
9072 struct tog_help_view_state *s = &view->state.help;
9073 const struct got_error *err;
9074 regmatch_t *regmatch = &view->regmatch;
9075 wchar_t *wline;
9076 char *line;
9077 ssize_t linelen;
9078 size_t linesz = 0;
9079 int width, nprinted = 0, rc = 0;
9080 int eos = view->nlines;
9082 if (view_is_hsplit_top(view))
9083 --eos; /* account for border */
9085 s->lineno = 0;
9086 rewind(s->f);
9087 werase(view->window);
9089 if (view->gline > s->nlines - 1)
9090 view->gline = s->nlines - 1;
9092 err = win_draw_center(view->window, 0, 0, view->ncols,
9093 view_needs_focus_indication(view),
9094 "tog help (press q to return to tog)");
9095 if (err)
9096 return err;
9097 if (eos <= 1)
9098 return NULL;
9099 waddstr(view->window, "\n\n");
9100 eos -= 2;
9102 s->eof = 0;
9103 view->maxx = 0;
9104 line = NULL;
9105 while (eos > 0 && nprinted < eos) {
9106 attr_t attr = 0;
9108 linelen = getline(&line, &linesz, s->f);
9109 if (linelen == -1) {
9110 if (!feof(s->f)) {
9111 free(line);
9112 return got_ferror(s->f, GOT_ERR_IO);
9114 s->eof = 1;
9115 break;
9117 if (++s->lineno < s->first_displayed_line)
9118 continue;
9119 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9120 continue;
9121 if (s->lineno == view->hiline)
9122 attr = A_STANDOUT;
9124 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9125 view->x ? 1 : 0);
9126 if (err) {
9127 free(line);
9128 return err;
9130 view->maxx = MAX(view->maxx, width);
9131 free(wline);
9132 wline = NULL;
9134 if (attr)
9135 wattron(view->window, attr);
9136 if (s->first_displayed_line + nprinted == s->matched_line &&
9137 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9138 err = add_matched_line(&width, line, view->ncols - 1, 0,
9139 view->window, view->x, regmatch);
9140 if (err) {
9141 free(line);
9142 return err;
9144 } else {
9145 int skip;
9147 err = format_line(&wline, &width, &skip, line,
9148 view->x, view->ncols, 0, view->x ? 1 : 0);
9149 if (err) {
9150 free(line);
9151 return err;
9153 waddwstr(view->window, &wline[skip]);
9154 free(wline);
9155 wline = NULL;
9157 if (s->lineno == view->hiline) {
9158 while (width++ < view->ncols)
9159 waddch(view->window, ' ');
9160 } else {
9161 if (width < view->ncols)
9162 waddch(view->window, '\n');
9164 if (attr)
9165 wattroff(view->window, attr);
9166 if (++nprinted == 1)
9167 s->first_displayed_line = s->lineno;
9169 free(line);
9170 if (nprinted > 0)
9171 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9172 else
9173 s->last_displayed_line = s->first_displayed_line;
9175 view_border(view);
9177 if (s->eof) {
9178 rc = waddnstr(view->window,
9179 "See the tog(1) manual page for full documentation",
9180 view->ncols - 1);
9181 if (rc == ERR)
9182 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9183 } else {
9184 wmove(view->window, view->nlines - 1, 0);
9185 wclrtoeol(view->window);
9186 wstandout(view->window);
9187 rc = waddnstr(view->window, "scroll down for more...",
9188 view->ncols - 1);
9189 if (rc == ERR)
9190 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9191 if (getcurx(view->window) < view->ncols - 6) {
9192 rc = wprintw(view->window, "[%.0f%%]",
9193 100.00 * s->last_displayed_line / s->nlines);
9194 if (rc == ERR)
9195 return got_error_msg(GOT_ERR_IO, "wprintw");
9197 wstandend(view->window);
9200 return NULL;
9203 static const struct got_error *
9204 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9206 struct tog_help_view_state *s = &view->state.help;
9207 const struct got_error *err = NULL;
9208 char *line = NULL;
9209 ssize_t linelen;
9210 size_t linesz = 0;
9211 int eos, nscroll;
9213 eos = nscroll = view->nlines;
9214 if (view_is_hsplit_top(view))
9215 --eos; /* border */
9217 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9219 switch (ch) {
9220 case '0':
9221 case '$':
9222 case KEY_RIGHT:
9223 case 'l':
9224 case KEY_LEFT:
9225 case 'h':
9226 horizontal_scroll_input(view, ch);
9227 break;
9228 case 'g':
9229 case KEY_HOME:
9230 s->first_displayed_line = 1;
9231 view->count = 0;
9232 break;
9233 case 'G':
9234 case KEY_END:
9235 view->count = 0;
9236 if (s->eof)
9237 break;
9238 s->first_displayed_line = (s->nlines - eos) + 3;
9239 s->eof = 1;
9240 break;
9241 case 'k':
9242 case KEY_UP:
9243 if (s->first_displayed_line > 1)
9244 --s->first_displayed_line;
9245 else
9246 view->count = 0;
9247 break;
9248 case CTRL('u'):
9249 case 'u':
9250 nscroll /= 2;
9251 /* FALL THROUGH */
9252 case KEY_PPAGE:
9253 case CTRL('b'):
9254 case 'b':
9255 if (s->first_displayed_line == 1) {
9256 view->count = 0;
9257 break;
9259 while (--nscroll > 0 && s->first_displayed_line > 1)
9260 s->first_displayed_line--;
9261 break;
9262 case 'j':
9263 case KEY_DOWN:
9264 case CTRL('n'):
9265 if (!s->eof)
9266 ++s->first_displayed_line;
9267 else
9268 view->count = 0;
9269 break;
9270 case CTRL('d'):
9271 case 'd':
9272 nscroll /= 2;
9273 /* FALL THROUGH */
9274 case KEY_NPAGE:
9275 case CTRL('f'):
9276 case 'f':
9277 case ' ':
9278 if (s->eof) {
9279 view->count = 0;
9280 break;
9282 while (!s->eof && --nscroll > 0) {
9283 linelen = getline(&line, &linesz, s->f);
9284 s->first_displayed_line++;
9285 if (linelen == -1) {
9286 if (feof(s->f))
9287 s->eof = 1;
9288 else
9289 err = got_ferror(s->f, GOT_ERR_IO);
9290 break;
9293 free(line);
9294 break;
9295 default:
9296 view->count = 0;
9297 break;
9300 return err;
9303 static const struct got_error *
9304 close_help_view(struct tog_view *view)
9306 struct tog_help_view_state *s = &view->state.help;
9308 free(s->line_offsets);
9309 s->line_offsets = NULL;
9310 if (fclose(s->f) == EOF)
9311 return got_error_from_errno("fclose");
9313 return NULL;
9316 static const struct got_error *
9317 reset_help_view(struct tog_view *view)
9319 struct tog_help_view_state *s = &view->state.help;
9322 if (s->f && fclose(s->f) == EOF)
9323 return got_error_from_errno("fclose");
9325 wclear(view->window);
9326 view->count = 0;
9327 view->x = 0;
9328 s->all = !s->all;
9329 s->first_displayed_line = 1;
9330 s->last_displayed_line = view->nlines;
9331 s->matched_line = 0;
9333 return create_help(s);
9336 static const struct got_error *
9337 open_help_view(struct tog_view *view, struct tog_view *parent)
9339 const struct got_error *err = NULL;
9340 struct tog_help_view_state *s = &view->state.help;
9342 s->type = (enum tog_keymap_type)parent->type;
9343 s->first_displayed_line = 1;
9344 s->last_displayed_line = view->nlines;
9345 s->selected_line = 1;
9347 view->show = show_help_view;
9348 view->input = input_help_view;
9349 view->reset = reset_help_view;
9350 view->close = close_help_view;
9351 view->search_start = search_start_help_view;
9352 view->search_setup = search_setup_help_view;
9353 view->search_next = search_next_view_match;
9355 err = create_help(s);
9356 return err;
9359 static const struct got_error *
9360 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9361 enum tog_view_type request, int y, int x)
9363 const struct got_error *err = NULL;
9365 *new_view = NULL;
9367 switch (request) {
9368 case TOG_VIEW_DIFF:
9369 if (view->type == TOG_VIEW_LOG) {
9370 struct tog_log_view_state *s = &view->state.log;
9372 err = open_diff_view_for_commit(new_view, y, x,
9373 s->selected_entry->commit, s->selected_entry->id,
9374 view, s->repo);
9375 } else
9376 return got_error_msg(GOT_ERR_NOT_IMPL,
9377 "parent/child view pair not supported");
9378 break;
9379 case TOG_VIEW_BLAME:
9380 if (view->type == TOG_VIEW_TREE) {
9381 struct tog_tree_view_state *s = &view->state.tree;
9383 err = blame_tree_entry(new_view, y, x,
9384 s->selected_entry, &s->parents, s->commit_id,
9385 s->repo);
9386 } else
9387 return got_error_msg(GOT_ERR_NOT_IMPL,
9388 "parent/child view pair not supported");
9389 break;
9390 case TOG_VIEW_LOG:
9391 if (view->type == TOG_VIEW_BLAME)
9392 err = log_annotated_line(new_view, y, x,
9393 view->state.blame.repo, view->state.blame.id_to_log);
9394 else if (view->type == TOG_VIEW_TREE)
9395 err = log_selected_tree_entry(new_view, y, x,
9396 &view->state.tree);
9397 else if (view->type == TOG_VIEW_REF)
9398 err = log_ref_entry(new_view, y, x,
9399 view->state.ref.selected_entry,
9400 view->state.ref.repo);
9401 else
9402 return got_error_msg(GOT_ERR_NOT_IMPL,
9403 "parent/child view pair not supported");
9404 break;
9405 case TOG_VIEW_TREE:
9406 if (view->type == TOG_VIEW_LOG)
9407 err = browse_commit_tree(new_view, y, x,
9408 view->state.log.selected_entry,
9409 view->state.log.in_repo_path,
9410 view->state.log.head_ref_name,
9411 view->state.log.repo);
9412 else if (view->type == TOG_VIEW_REF)
9413 err = browse_ref_tree(new_view, y, x,
9414 view->state.ref.selected_entry,
9415 view->state.ref.repo);
9416 else
9417 return got_error_msg(GOT_ERR_NOT_IMPL,
9418 "parent/child view pair not supported");
9419 break;
9420 case TOG_VIEW_REF:
9421 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9422 if (*new_view == NULL)
9423 return got_error_from_errno("view_open");
9424 if (view->type == TOG_VIEW_LOG)
9425 err = open_ref_view(*new_view, view->state.log.repo);
9426 else if (view->type == TOG_VIEW_TREE)
9427 err = open_ref_view(*new_view, view->state.tree.repo);
9428 else
9429 err = got_error_msg(GOT_ERR_NOT_IMPL,
9430 "parent/child view pair not supported");
9431 if (err)
9432 view_close(*new_view);
9433 break;
9434 case TOG_VIEW_HELP:
9435 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9436 if (*new_view == NULL)
9437 return got_error_from_errno("view_open");
9438 err = open_help_view(*new_view, view);
9439 if (err)
9440 view_close(*new_view);
9441 break;
9442 default:
9443 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9446 return err;
9450 * If view was scrolled down to move the selected line into view when opening a
9451 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9453 static void
9454 offset_selection_up(struct tog_view *view)
9456 switch (view->type) {
9457 case TOG_VIEW_BLAME: {
9458 struct tog_blame_view_state *s = &view->state.blame;
9459 if (s->first_displayed_line == 1) {
9460 s->selected_line = MAX(s->selected_line - view->offset,
9461 1);
9462 break;
9464 if (s->first_displayed_line > view->offset)
9465 s->first_displayed_line -= view->offset;
9466 else
9467 s->first_displayed_line = 1;
9468 s->selected_line += view->offset;
9469 break;
9471 case TOG_VIEW_LOG:
9472 log_scroll_up(&view->state.log, view->offset);
9473 view->state.log.selected += view->offset;
9474 break;
9475 case TOG_VIEW_REF:
9476 ref_scroll_up(&view->state.ref, view->offset);
9477 view->state.ref.selected += view->offset;
9478 break;
9479 case TOG_VIEW_TREE:
9480 tree_scroll_up(&view->state.tree, view->offset);
9481 view->state.tree.selected += view->offset;
9482 break;
9483 default:
9484 break;
9487 view->offset = 0;
9491 * If the selected line is in the section of screen covered by the bottom split,
9492 * scroll down offset lines to move it into view and index its new position.
9494 static const struct got_error *
9495 offset_selection_down(struct tog_view *view)
9497 const struct got_error *err = NULL;
9498 const struct got_error *(*scrolld)(struct tog_view *, int);
9499 int *selected = NULL;
9500 int header, offset;
9502 switch (view->type) {
9503 case TOG_VIEW_BLAME: {
9504 struct tog_blame_view_state *s = &view->state.blame;
9505 header = 3;
9506 scrolld = NULL;
9507 if (s->selected_line > view->nlines - header) {
9508 offset = abs(view->nlines - s->selected_line - header);
9509 s->first_displayed_line += offset;
9510 s->selected_line -= offset;
9511 view->offset = offset;
9513 break;
9515 case TOG_VIEW_LOG: {
9516 struct tog_log_view_state *s = &view->state.log;
9517 scrolld = &log_scroll_down;
9518 header = view_is_parent_view(view) ? 3 : 2;
9519 selected = &s->selected;
9520 break;
9522 case TOG_VIEW_REF: {
9523 struct tog_ref_view_state *s = &view->state.ref;
9524 scrolld = &ref_scroll_down;
9525 header = 3;
9526 selected = &s->selected;
9527 break;
9529 case TOG_VIEW_TREE: {
9530 struct tog_tree_view_state *s = &view->state.tree;
9531 scrolld = &tree_scroll_down;
9532 header = 5;
9533 selected = &s->selected;
9534 break;
9536 default:
9537 selected = NULL;
9538 scrolld = NULL;
9539 header = 0;
9540 break;
9543 if (selected && *selected > view->nlines - header) {
9544 offset = abs(view->nlines - *selected - header);
9545 view->offset = offset;
9546 if (scrolld && offset) {
9547 err = scrolld(view, offset);
9548 *selected -= offset;
9552 return err;
9555 static void
9556 list_commands(FILE *fp)
9558 size_t i;
9560 fprintf(fp, "commands:");
9561 for (i = 0; i < nitems(tog_commands); i++) {
9562 const struct tog_cmd *cmd = &tog_commands[i];
9563 fprintf(fp, " %s", cmd->name);
9565 fputc('\n', fp);
9568 __dead static void
9569 usage(int hflag, int status)
9571 FILE *fp = (status == 0) ? stdout : stderr;
9573 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9574 getprogname());
9575 if (hflag) {
9576 fprintf(fp, "lazy usage: %s path\n", getprogname());
9577 list_commands(fp);
9579 exit(status);
9582 static char **
9583 make_argv(int argc, ...)
9585 va_list ap;
9586 char **argv;
9587 int i;
9589 va_start(ap, argc);
9591 argv = calloc(argc, sizeof(char *));
9592 if (argv == NULL)
9593 err(1, "calloc");
9594 for (i = 0; i < argc; i++) {
9595 argv[i] = strdup(va_arg(ap, char *));
9596 if (argv[i] == NULL)
9597 err(1, "strdup");
9600 va_end(ap);
9601 return argv;
9605 * Try to convert 'tog path' into a 'tog log path' command.
9606 * The user could simply have mistyped the command rather than knowingly
9607 * provided a path. So check whether argv[0] can in fact be resolved
9608 * to a path in the HEAD commit and print a special error if not.
9609 * This hack is for mpi@ <3
9611 static const struct got_error *
9612 tog_log_with_path(int argc, char *argv[])
9614 const struct got_error *error = NULL, *close_err;
9615 const struct tog_cmd *cmd = NULL;
9616 struct got_repository *repo = NULL;
9617 struct got_worktree *worktree = NULL;
9618 struct got_object_id *commit_id = NULL, *id = NULL;
9619 struct got_commit_object *commit = NULL;
9620 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9621 char *commit_id_str = NULL, **cmd_argv = NULL;
9622 int *pack_fds = NULL;
9624 cwd = getcwd(NULL, 0);
9625 if (cwd == NULL)
9626 return got_error_from_errno("getcwd");
9628 error = got_repo_pack_fds_open(&pack_fds);
9629 if (error != NULL)
9630 goto done;
9632 error = got_worktree_open(&worktree, cwd);
9633 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9634 goto done;
9636 if (worktree)
9637 repo_path = strdup(got_worktree_get_repo_path(worktree));
9638 else
9639 repo_path = strdup(cwd);
9640 if (repo_path == NULL) {
9641 error = got_error_from_errno("strdup");
9642 goto done;
9645 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9646 if (error != NULL)
9647 goto done;
9649 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9650 repo, worktree);
9651 if (error)
9652 goto done;
9654 error = tog_load_refs(repo, 0);
9655 if (error)
9656 goto done;
9657 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9658 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9659 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9660 if (error)
9661 goto done;
9663 if (worktree) {
9664 got_worktree_close(worktree);
9665 worktree = NULL;
9668 error = got_object_open_as_commit(&commit, repo, commit_id);
9669 if (error)
9670 goto done;
9672 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9673 if (error) {
9674 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9675 goto done;
9676 fprintf(stderr, "%s: '%s' is no known command or path\n",
9677 getprogname(), argv[0]);
9678 usage(1, 1);
9679 /* not reached */
9682 error = got_object_id_str(&commit_id_str, commit_id);
9683 if (error)
9684 goto done;
9686 cmd = &tog_commands[0]; /* log */
9687 argc = 4;
9688 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9689 error = cmd->cmd_main(argc, cmd_argv);
9690 done:
9691 if (repo) {
9692 close_err = got_repo_close(repo);
9693 if (error == NULL)
9694 error = close_err;
9696 if (commit)
9697 got_object_commit_close(commit);
9698 if (worktree)
9699 got_worktree_close(worktree);
9700 if (pack_fds) {
9701 const struct got_error *pack_err =
9702 got_repo_pack_fds_close(pack_fds);
9703 if (error == NULL)
9704 error = pack_err;
9706 free(id);
9707 free(commit_id_str);
9708 free(commit_id);
9709 free(cwd);
9710 free(repo_path);
9711 free(in_repo_path);
9712 if (cmd_argv) {
9713 int i;
9714 for (i = 0; i < argc; i++)
9715 free(cmd_argv[i]);
9716 free(cmd_argv);
9718 tog_free_refs();
9719 return error;
9722 int
9723 main(int argc, char *argv[])
9725 const struct got_error *error = NULL;
9726 const struct tog_cmd *cmd = NULL;
9727 int ch, hflag = 0, Vflag = 0;
9728 char **cmd_argv = NULL;
9729 static const struct option longopts[] = {
9730 { "version", no_argument, NULL, 'V' },
9731 { NULL, 0, NULL, 0}
9733 char *diff_algo_str = NULL;
9734 const char *test_script_path;
9736 setlocale(LC_CTYPE, "");
9739 * Test mode init must happen before pledge() because "tty" will
9740 * not allow TTY-related ioctls to occur via regular files.
9742 test_script_path = getenv("GOT_TOG_TEST");
9743 if (test_script_path != NULL) {
9744 error = init_mock_term(test_script_path);
9745 if (error) {
9746 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9747 return 1;
9751 #if !defined(PROFILE)
9752 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9753 NULL) == -1)
9754 err(1, "pledge");
9755 #endif
9757 if (!isatty(STDIN_FILENO))
9758 errx(1, "standard input is not a tty");
9760 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9761 switch (ch) {
9762 case 'h':
9763 hflag = 1;
9764 break;
9765 case 'V':
9766 Vflag = 1;
9767 break;
9768 default:
9769 usage(hflag, 1);
9770 /* NOTREACHED */
9774 argc -= optind;
9775 argv += optind;
9776 optind = 1;
9777 optreset = 1;
9779 if (Vflag) {
9780 got_version_print_str();
9781 return 0;
9784 if (argc == 0) {
9785 if (hflag)
9786 usage(hflag, 0);
9787 /* Build an argument vector which runs a default command. */
9788 cmd = &tog_commands[0];
9789 argc = 1;
9790 cmd_argv = make_argv(argc, cmd->name);
9791 } else {
9792 size_t i;
9794 /* Did the user specify a command? */
9795 for (i = 0; i < nitems(tog_commands); i++) {
9796 if (strncmp(tog_commands[i].name, argv[0],
9797 strlen(argv[0])) == 0) {
9798 cmd = &tog_commands[i];
9799 break;
9804 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9805 if (diff_algo_str) {
9806 if (strcasecmp(diff_algo_str, "patience") == 0)
9807 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9808 if (strcasecmp(diff_algo_str, "myers") == 0)
9809 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9812 if (cmd == NULL) {
9813 if (argc != 1)
9814 usage(0, 1);
9815 /* No command specified; try log with a path */
9816 error = tog_log_with_path(argc, argv);
9817 } else {
9818 if (hflag)
9819 cmd->cmd_usage();
9820 else
9821 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9824 endwin();
9825 if (cmd_argv) {
9826 int i;
9827 for (i = 0; i < argc; i++)
9828 free(cmd_argv[i]);
9829 free(cmd_argv);
9832 if (error && error->code != GOT_ERR_CANCELLED &&
9833 error->code != GOT_ERR_EOF &&
9834 error->code != GOT_ERR_PRIVSEP_EXIT &&
9835 error->code != GOT_ERR_PRIVSEP_PIPE &&
9836 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9837 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9838 return 0;