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 pthread_cond_t blame_complete;
436 };
438 struct tog_blame {
439 FILE *f;
440 off_t filesize;
441 struct tog_blame_line *lines;
442 int nlines;
443 off_t *line_offsets;
444 pthread_t thread;
445 struct tog_blame_thread_args thread_args;
446 struct tog_blame_cb_args cb_args;
447 const char *path;
448 int *pack_fds;
449 };
451 struct tog_blame_view_state {
452 int first_displayed_line;
453 int last_displayed_line;
454 int selected_line;
455 int last_diffed_line;
456 int blame_complete;
457 int eof;
458 int done;
459 struct got_object_id_queue blamed_commits;
460 struct got_object_qid *blamed_commit;
461 char *path;
462 struct got_repository *repo;
463 struct got_object_id *commit_id;
464 struct got_object_id *id_to_log;
465 struct tog_blame blame;
466 int matched_line;
467 struct tog_colors colors;
468 };
470 struct tog_parent_tree {
471 TAILQ_ENTRY(tog_parent_tree) entry;
472 struct got_tree_object *tree;
473 struct got_tree_entry *first_displayed_entry;
474 struct got_tree_entry *selected_entry;
475 int selected;
476 };
478 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
480 struct tog_tree_view_state {
481 char *tree_label;
482 struct got_object_id *commit_id;/* commit which this tree belongs to */
483 struct got_tree_object *root; /* the commit's root tree entry */
484 struct got_tree_object *tree; /* currently displayed (sub-)tree */
485 struct got_tree_entry *first_displayed_entry;
486 struct got_tree_entry *last_displayed_entry;
487 struct got_tree_entry *selected_entry;
488 int ndisplayed, selected, show_ids;
489 struct tog_parent_trees parents; /* parent trees of current sub-tree */
490 char *head_ref_name;
491 struct got_repository *repo;
492 struct got_tree_entry *matched_entry;
493 struct tog_colors colors;
494 };
496 struct tog_reflist_entry {
497 TAILQ_ENTRY(tog_reflist_entry) entry;
498 struct got_reference *ref;
499 int idx;
500 };
502 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
504 struct tog_ref_view_state {
505 struct tog_reflist_head refs;
506 struct tog_reflist_entry *first_displayed_entry;
507 struct tog_reflist_entry *last_displayed_entry;
508 struct tog_reflist_entry *selected_entry;
509 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
510 struct got_repository *repo;
511 struct tog_reflist_entry *matched_entry;
512 struct tog_colors colors;
513 };
515 struct tog_help_view_state {
516 FILE *f;
517 off_t *line_offsets;
518 size_t nlines;
519 int lineno;
520 int first_displayed_line;
521 int last_displayed_line;
522 int eof;
523 int matched_line;
524 int selected_line;
525 int all;
526 enum tog_keymap_type type;
527 };
529 #define GENERATE_HELP \
530 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
531 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
532 KEY_("k C-p Up", "Move cursor or page up one line"), \
533 KEY_("j C-n Down", "Move cursor or page down one line"), \
534 KEY_("C-b b PgUp", "Scroll the view up one page"), \
535 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
536 KEY_("C-u u", "Scroll the view up one half page"), \
537 KEY_("C-d d", "Scroll the view down one half page"), \
538 KEY_("g", "Go to line N (default: first line)"), \
539 KEY_("Home =", "Go to the first line"), \
540 KEY_("G", "Go to line N (default: last line)"), \
541 KEY_("End *", "Go to the last line"), \
542 KEY_("l Right", "Scroll the view right"), \
543 KEY_("h Left", "Scroll the view left"), \
544 KEY_("$", "Scroll view to the rightmost position"), \
545 KEY_("0", "Scroll view to the leftmost position"), \
546 KEY_("-", "Decrease size of the focussed split"), \
547 KEY_("+", "Increase size of the focussed split"), \
548 KEY_("Tab", "Switch focus between views"), \
549 KEY_("F", "Toggle fullscreen mode"), \
550 KEY_("S", "Switch split-screen layout"), \
551 KEY_("/", "Open prompt to enter search term"), \
552 KEY_("n", "Find next line/token matching the current search term"), \
553 KEY_("N", "Find previous line/token matching the current search term"),\
554 KEY_("q", "Quit the focussed view; Quit help screen"), \
555 KEY_("Q", "Quit tog"), \
557 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
558 KEY_("< ,", "Move cursor up one commit"), \
559 KEY_("> .", "Move cursor down one commit"), \
560 KEY_("Enter", "Open diff view of the selected commit"), \
561 KEY_("B", "Reload the log view and toggle display of merged commits"), \
562 KEY_("R", "Open ref view of all repository references"), \
563 KEY_("T", "Display tree view of the repository from the selected" \
564 " commit"), \
565 KEY_("@", "Toggle between displaying author and committer name"), \
566 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
567 KEY_("C-g Backspace", "Cancel current search or log operation"), \
568 KEY_("C-l", "Reload the log view with new commits in the repository"), \
570 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
571 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
572 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
573 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
574 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
575 " data"), \
576 KEY_("(", "Go to the previous file in the diff"), \
577 KEY_(")", "Go to the next file in the diff"), \
578 KEY_("{", "Go to the previous hunk in the diff"), \
579 KEY_("}", "Go to the next hunk in the diff"), \
580 KEY_("[", "Decrease the number of context lines"), \
581 KEY_("]", "Increase the number of context lines"), \
582 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
584 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
585 KEY_("Enter", "Display diff view of the selected line's commit"), \
586 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
587 KEY_("L", "Open log view for the currently selected annotated line"), \
588 KEY_("C", "Reload view with the previously blamed commit"), \
589 KEY_("c", "Reload view with the version of the file found in the" \
590 " selected line's commit"), \
591 KEY_("p", "Reload view with the version of the file found in the" \
592 " selected line's parent commit"), \
594 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
595 KEY_("Enter", "Enter selected directory or open blame view of the" \
596 " selected file"), \
597 KEY_("L", "Open log view for the selected entry"), \
598 KEY_("R", "Open ref view of all repository references"), \
599 KEY_("i", "Show object IDs for all tree entries"), \
600 KEY_("Backspace", "Return to the parent directory"), \
602 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
603 KEY_("Enter", "Display log view of the selected reference"), \
604 KEY_("T", "Display tree view of the selected reference"), \
605 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
606 KEY_("m", "Toggle display of last modified date for each reference"), \
607 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
608 KEY_("C-l", "Reload view with all repository references")
610 struct tog_key_map {
611 const char *keys;
612 const char *info;
613 enum tog_keymap_type type;
614 };
616 /* curses io for tog regress */
617 struct tog_io {
618 FILE *cin;
619 FILE *cout;
620 FILE *f;
621 int wait_for_ui;
622 } tog_io;
623 static int using_mock_io;
625 #define TOG_SCREEN_DUMP "SCREENDUMP"
626 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
627 #define TOG_KEY_SCRDUMP SHRT_MIN
629 /*
630 * We implement two types of views: parent views and child views.
632 * The 'Tab' key switches focus between a parent view and its child view.
633 * Child views are shown side-by-side to their parent view, provided
634 * there is enough screen estate.
636 * When a new view is opened from within a parent view, this new view
637 * becomes a child view of the parent view, replacing any existing child.
639 * When a new view is opened from within a child view, this new view
640 * becomes a parent view which will obscure the views below until the
641 * user quits the new parent view by typing 'q'.
643 * This list of views contains parent views only.
644 * Child views are only pointed to by their parent view.
645 */
646 TAILQ_HEAD(tog_view_list_head, tog_view);
648 struct tog_view {
649 TAILQ_ENTRY(tog_view) entry;
650 WINDOW *window;
651 PANEL *panel;
652 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
653 int resized_y, resized_x; /* begin_y/x based on user resizing */
654 int maxx, x; /* max column and current start column */
655 int lines, cols; /* copies of LINES and COLS */
656 int nscrolled, offset; /* lines scrolled and hsplit line offset */
657 int gline, hiline; /* navigate to and highlight this nG line */
658 int ch, count; /* current keymap and count prefix */
659 int resized; /* set when in a resize event */
660 int focussed; /* Only set on one parent or child view at a time. */
661 int dying;
662 struct tog_view *parent;
663 struct tog_view *child;
665 /*
666 * This flag is initially set on parent views when a new child view
667 * is created. It gets toggled when the 'Tab' key switches focus
668 * between parent and child.
669 * The flag indicates whether focus should be passed on to our child
670 * view if this parent view gets picked for focus after another parent
671 * view was closed. This prevents child views from losing focus in such
672 * situations.
673 */
674 int focus_child;
676 enum tog_view_mode mode;
677 /* type-specific state */
678 enum tog_view_type type;
679 union {
680 struct tog_diff_view_state diff;
681 struct tog_log_view_state log;
682 struct tog_blame_view_state blame;
683 struct tog_tree_view_state tree;
684 struct tog_ref_view_state ref;
685 struct tog_help_view_state help;
686 } state;
688 const struct got_error *(*show)(struct tog_view *);
689 const struct got_error *(*input)(struct tog_view **,
690 struct tog_view *, int);
691 const struct got_error *(*reset)(struct tog_view *);
692 const struct got_error *(*resize)(struct tog_view *, int);
693 const struct got_error *(*close)(struct tog_view *);
695 const struct got_error *(*search_start)(struct tog_view *);
696 const struct got_error *(*search_next)(struct tog_view *);
697 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
698 int **, int **, int **, int **);
699 int search_started;
700 int searching;
701 #define TOG_SEARCH_FORWARD 1
702 #define TOG_SEARCH_BACKWARD 2
703 int search_next_done;
704 #define TOG_SEARCH_HAVE_MORE 1
705 #define TOG_SEARCH_NO_MORE 2
706 #define TOG_SEARCH_HAVE_NONE 3
707 regex_t regex;
708 regmatch_t regmatch;
709 const char *action;
710 };
712 static const struct got_error *open_diff_view(struct tog_view *,
713 struct got_object_id *, struct got_object_id *,
714 const char *, const char *, int, int, int, struct tog_view *,
715 struct got_repository *);
716 static const struct got_error *show_diff_view(struct tog_view *);
717 static const struct got_error *input_diff_view(struct tog_view **,
718 struct tog_view *, int);
719 static const struct got_error *reset_diff_view(struct tog_view *);
720 static const struct got_error* close_diff_view(struct tog_view *);
721 static const struct got_error *search_start_diff_view(struct tog_view *);
722 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
723 size_t *, int **, int **, int **, int **);
724 static const struct got_error *search_next_view_match(struct tog_view *);
726 static const struct got_error *open_log_view(struct tog_view *,
727 struct got_object_id *, struct got_repository *,
728 const char *, const char *, int);
729 static const struct got_error * show_log_view(struct tog_view *);
730 static const struct got_error *input_log_view(struct tog_view **,
731 struct tog_view *, int);
732 static const struct got_error *resize_log_view(struct tog_view *, int);
733 static const struct got_error *close_log_view(struct tog_view *);
734 static const struct got_error *search_start_log_view(struct tog_view *);
735 static const struct got_error *search_next_log_view(struct tog_view *);
737 static const struct got_error *open_blame_view(struct tog_view *, char *,
738 struct got_object_id *, struct got_repository *);
739 static const struct got_error *show_blame_view(struct tog_view *);
740 static const struct got_error *input_blame_view(struct tog_view **,
741 struct tog_view *, int);
742 static const struct got_error *reset_blame_view(struct tog_view *);
743 static const struct got_error *close_blame_view(struct tog_view *);
744 static const struct got_error *search_start_blame_view(struct tog_view *);
745 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
746 size_t *, int **, int **, int **, int **);
748 static const struct got_error *open_tree_view(struct tog_view *,
749 struct got_object_id *, const char *, struct got_repository *);
750 static const struct got_error *show_tree_view(struct tog_view *);
751 static const struct got_error *input_tree_view(struct tog_view **,
752 struct tog_view *, int);
753 static const struct got_error *close_tree_view(struct tog_view *);
754 static const struct got_error *search_start_tree_view(struct tog_view *);
755 static const struct got_error *search_next_tree_view(struct tog_view *);
757 static const struct got_error *open_ref_view(struct tog_view *,
758 struct got_repository *);
759 static const struct got_error *show_ref_view(struct tog_view *);
760 static const struct got_error *input_ref_view(struct tog_view **,
761 struct tog_view *, int);
762 static const struct got_error *close_ref_view(struct tog_view *);
763 static const struct got_error *search_start_ref_view(struct tog_view *);
764 static const struct got_error *search_next_ref_view(struct tog_view *);
766 static const struct got_error *open_help_view(struct tog_view *,
767 struct tog_view *);
768 static const struct got_error *show_help_view(struct tog_view *);
769 static const struct got_error *input_help_view(struct tog_view **,
770 struct tog_view *, int);
771 static const struct got_error *reset_help_view(struct tog_view *);
772 static const struct got_error* close_help_view(struct tog_view *);
773 static const struct got_error *search_start_help_view(struct tog_view *);
774 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
775 size_t *, int **, int **, int **, int **);
777 static volatile sig_atomic_t tog_sigwinch_received;
778 static volatile sig_atomic_t tog_sigpipe_received;
779 static volatile sig_atomic_t tog_sigcont_received;
780 static volatile sig_atomic_t tog_sigint_received;
781 static volatile sig_atomic_t tog_sigterm_received;
783 static void
784 tog_sigwinch(int signo)
786 tog_sigwinch_received = 1;
789 static void
790 tog_sigpipe(int signo)
792 tog_sigpipe_received = 1;
795 static void
796 tog_sigcont(int signo)
798 tog_sigcont_received = 1;
801 static void
802 tog_sigint(int signo)
804 tog_sigint_received = 1;
807 static void
808 tog_sigterm(int signo)
810 tog_sigterm_received = 1;
813 static int
814 tog_fatal_signal_received(void)
816 return (tog_sigpipe_received ||
817 tog_sigint_received || tog_sigterm_received);
820 static const struct got_error *
821 view_close(struct tog_view *view)
823 const struct got_error *err = NULL, *child_err = NULL;
825 if (view->child) {
826 child_err = view_close(view->child);
827 view->child = NULL;
829 if (view->close)
830 err = view->close(view);
831 if (view->panel)
832 del_panel(view->panel);
833 if (view->window)
834 delwin(view->window);
835 free(view);
836 return err ? err : child_err;
839 static struct tog_view *
840 view_open(int nlines, int ncols, int begin_y, int begin_x,
841 enum tog_view_type type)
843 struct tog_view *view = calloc(1, sizeof(*view));
845 if (view == NULL)
846 return NULL;
848 view->type = type;
849 view->lines = LINES;
850 view->cols = COLS;
851 view->nlines = nlines ? nlines : LINES - begin_y;
852 view->ncols = ncols ? ncols : COLS - begin_x;
853 view->begin_y = begin_y;
854 view->begin_x = begin_x;
855 view->window = newwin(nlines, ncols, begin_y, begin_x);
856 if (view->window == NULL) {
857 view_close(view);
858 return NULL;
860 view->panel = new_panel(view->window);
861 if (view->panel == NULL ||
862 set_panel_userptr(view->panel, view) != OK) {
863 view_close(view);
864 return NULL;
867 keypad(view->window, TRUE);
868 return view;
871 static int
872 view_split_begin_x(int begin_x)
874 if (begin_x > 0 || COLS < 120)
875 return 0;
876 return (COLS - MAX(COLS / 2, 80));
879 /* XXX Stub till we decide what to do. */
880 static int
881 view_split_begin_y(int lines)
883 return lines * HSPLIT_SCALE;
886 static const struct got_error *view_resize(struct tog_view *);
888 static const struct got_error *
889 view_splitscreen(struct tog_view *view)
891 const struct got_error *err = NULL;
893 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
894 if (view->resized_y && view->resized_y < view->lines)
895 view->begin_y = view->resized_y;
896 else
897 view->begin_y = view_split_begin_y(view->nlines);
898 view->begin_x = 0;
899 } else if (!view->resized) {
900 if (view->resized_x && view->resized_x < view->cols - 1 &&
901 view->cols > 119)
902 view->begin_x = view->resized_x;
903 else
904 view->begin_x = view_split_begin_x(0);
905 view->begin_y = 0;
907 view->nlines = LINES - view->begin_y;
908 view->ncols = COLS - view->begin_x;
909 view->lines = LINES;
910 view->cols = COLS;
911 err = view_resize(view);
912 if (err)
913 return err;
915 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
916 view->parent->nlines = view->begin_y;
918 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
919 return got_error_from_errno("mvwin");
921 return NULL;
924 static const struct got_error *
925 view_fullscreen(struct tog_view *view)
927 const struct got_error *err = NULL;
929 view->begin_x = 0;
930 view->begin_y = view->resized ? view->begin_y : 0;
931 view->nlines = view->resized ? view->nlines : LINES;
932 view->ncols = COLS;
933 view->lines = LINES;
934 view->cols = COLS;
935 err = view_resize(view);
936 if (err)
937 return err;
939 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
940 return got_error_from_errno("mvwin");
942 return NULL;
945 static int
946 view_is_parent_view(struct tog_view *view)
948 return view->parent == NULL;
951 static int
952 view_is_splitscreen(struct tog_view *view)
954 return view->begin_x > 0 || view->begin_y > 0;
957 static int
958 view_is_fullscreen(struct tog_view *view)
960 return view->nlines == LINES && view->ncols == COLS;
963 static int
964 view_is_hsplit_top(struct tog_view *view)
966 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
967 view_is_splitscreen(view->child);
970 static void
971 view_border(struct tog_view *view)
973 PANEL *panel;
974 const struct tog_view *view_above;
976 if (view->parent)
977 return view_border(view->parent);
979 panel = panel_above(view->panel);
980 if (panel == NULL)
981 return;
983 view_above = panel_userptr(panel);
984 if (view->mode == TOG_VIEW_SPLIT_HRZN)
985 mvwhline(view->window, view_above->begin_y - 1,
986 view->begin_x, got_locale_is_utf8() ?
987 ACS_HLINE : '-', view->ncols);
988 else
989 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
990 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
993 static const struct got_error *view_init_hsplit(struct tog_view *, int);
994 static const struct got_error *request_log_commits(struct tog_view *);
995 static const struct got_error *offset_selection_down(struct tog_view *);
996 static void offset_selection_up(struct tog_view *);
997 static void view_get_split(struct tog_view *, int *, int *);
999 static const struct got_error *
1000 view_resize(struct tog_view *view)
1002 const struct got_error *err = NULL;
1003 int dif, nlines, ncols;
1005 dif = LINES - view->lines; /* line difference */
1007 if (view->lines > LINES)
1008 nlines = view->nlines - (view->lines - LINES);
1009 else
1010 nlines = view->nlines + (LINES - view->lines);
1011 if (view->cols > COLS)
1012 ncols = view->ncols - (view->cols - COLS);
1013 else
1014 ncols = view->ncols + (COLS - view->cols);
1016 if (view->child) {
1017 int hs = view->child->begin_y;
1019 if (!view_is_fullscreen(view))
1020 view->child->begin_x = view_split_begin_x(view->begin_x);
1021 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1022 view->child->begin_x == 0) {
1023 ncols = COLS;
1025 view_fullscreen(view->child);
1026 if (view->child->focussed)
1027 show_panel(view->child->panel);
1028 else
1029 show_panel(view->panel);
1030 } else {
1031 ncols = view->child->begin_x;
1033 view_splitscreen(view->child);
1034 show_panel(view->child->panel);
1037 * XXX This is ugly and needs to be moved into the above
1038 * logic but "works" for now and my attempts at moving it
1039 * break either 'tab' or 'F' key maps in horizontal splits.
1041 if (hs) {
1042 err = view_splitscreen(view->child);
1043 if (err)
1044 return err;
1045 if (dif < 0) { /* top split decreased */
1046 err = offset_selection_down(view);
1047 if (err)
1048 return err;
1050 view_border(view);
1051 update_panels();
1052 doupdate();
1053 show_panel(view->child->panel);
1054 nlines = view->nlines;
1056 } else if (view->parent == NULL)
1057 ncols = COLS;
1059 if (view->resize && dif > 0) {
1060 err = view->resize(view, dif);
1061 if (err)
1062 return err;
1065 if (wresize(view->window, nlines, ncols) == ERR)
1066 return got_error_from_errno("wresize");
1067 if (replace_panel(view->panel, view->window) == ERR)
1068 return got_error_from_errno("replace_panel");
1069 wclear(view->window);
1071 view->nlines = nlines;
1072 view->ncols = ncols;
1073 view->lines = LINES;
1074 view->cols = COLS;
1076 return NULL;
1079 static const struct got_error *
1080 resize_log_view(struct tog_view *view, int increase)
1082 struct tog_log_view_state *s = &view->state.log;
1083 const struct got_error *err = NULL;
1084 int n = 0;
1086 if (s->selected_entry)
1087 n = s->selected_entry->idx + view->lines - s->selected;
1090 * Request commits to account for the increased
1091 * height so we have enough to populate the view.
1093 if (s->commits->ncommits < n) {
1094 view->nscrolled = n - s->commits->ncommits + increase + 1;
1095 err = request_log_commits(view);
1098 return err;
1101 static void
1102 view_adjust_offset(struct tog_view *view, int n)
1104 if (n == 0)
1105 return;
1107 if (view->parent && view->parent->offset) {
1108 if (view->parent->offset + n >= 0)
1109 view->parent->offset += n;
1110 else
1111 view->parent->offset = 0;
1112 } else if (view->offset) {
1113 if (view->offset - n >= 0)
1114 view->offset -= n;
1115 else
1116 view->offset = 0;
1120 static const struct got_error *
1121 view_resize_split(struct tog_view *view, int resize)
1123 const struct got_error *err = NULL;
1124 struct tog_view *v = NULL;
1126 if (view->parent)
1127 v = view->parent;
1128 else
1129 v = view;
1131 if (!v->child || !view_is_splitscreen(v->child))
1132 return NULL;
1134 v->resized = v->child->resized = resize; /* lock for resize event */
1136 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1137 if (v->child->resized_y)
1138 v->child->begin_y = v->child->resized_y;
1139 if (view->parent)
1140 v->child->begin_y -= resize;
1141 else
1142 v->child->begin_y += resize;
1143 if (v->child->begin_y < 3) {
1144 view->count = 0;
1145 v->child->begin_y = 3;
1146 } else if (v->child->begin_y > LINES - 1) {
1147 view->count = 0;
1148 v->child->begin_y = LINES - 1;
1150 v->ncols = COLS;
1151 v->child->ncols = COLS;
1152 view_adjust_offset(view, resize);
1153 err = view_init_hsplit(v, v->child->begin_y);
1154 if (err)
1155 return err;
1156 v->child->resized_y = v->child->begin_y;
1157 } else {
1158 if (v->child->resized_x)
1159 v->child->begin_x = v->child->resized_x;
1160 if (view->parent)
1161 v->child->begin_x -= resize;
1162 else
1163 v->child->begin_x += resize;
1164 if (v->child->begin_x < 11) {
1165 view->count = 0;
1166 v->child->begin_x = 11;
1167 } else if (v->child->begin_x > COLS - 1) {
1168 view->count = 0;
1169 v->child->begin_x = COLS - 1;
1171 v->child->resized_x = v->child->begin_x;
1174 v->child->mode = v->mode;
1175 v->child->nlines = v->lines - v->child->begin_y;
1176 v->child->ncols = v->cols - v->child->begin_x;
1177 v->focus_child = 1;
1179 err = view_fullscreen(v);
1180 if (err)
1181 return err;
1182 err = view_splitscreen(v->child);
1183 if (err)
1184 return err;
1186 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1187 err = offset_selection_down(v->child);
1188 if (err)
1189 return err;
1192 if (v->resize)
1193 err = v->resize(v, 0);
1194 else if (v->child->resize)
1195 err = v->child->resize(v->child, 0);
1197 v->resized = v->child->resized = 0;
1199 return err;
1202 static void
1203 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1205 struct tog_view *v = src->child ? src->child : src;
1207 dst->resized_x = v->resized_x;
1208 dst->resized_y = v->resized_y;
1211 static const struct got_error *
1212 view_close_child(struct tog_view *view)
1214 const struct got_error *err = NULL;
1216 if (view->child == NULL)
1217 return NULL;
1219 err = view_close(view->child);
1220 view->child = NULL;
1221 return err;
1224 static const struct got_error *
1225 view_set_child(struct tog_view *view, struct tog_view *child)
1227 const struct got_error *err = NULL;
1229 view->child = child;
1230 child->parent = view;
1232 err = view_resize(view);
1233 if (err)
1234 return err;
1236 if (view->child->resized_x || view->child->resized_y)
1237 err = view_resize_split(view, 0);
1239 return err;
1242 static const struct got_error *view_dispatch_request(struct tog_view **,
1243 struct tog_view *, enum tog_view_type, int, int);
1245 static const struct got_error *
1246 view_request_new(struct tog_view **requested, struct tog_view *view,
1247 enum tog_view_type request)
1249 struct tog_view *new_view = NULL;
1250 const struct got_error *err;
1251 int y = 0, x = 0;
1253 *requested = NULL;
1255 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1256 view_get_split(view, &y, &x);
1258 err = view_dispatch_request(&new_view, view, request, y, x);
1259 if (err)
1260 return err;
1262 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1263 request != TOG_VIEW_HELP) {
1264 err = view_init_hsplit(view, y);
1265 if (err)
1266 return err;
1269 view->focussed = 0;
1270 new_view->focussed = 1;
1271 new_view->mode = view->mode;
1272 new_view->nlines = request == TOG_VIEW_HELP ?
1273 view->lines : view->lines - y;
1275 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1276 view_transfer_size(new_view, view);
1277 err = view_close_child(view);
1278 if (err)
1279 return err;
1280 err = view_set_child(view, new_view);
1281 if (err)
1282 return err;
1283 view->focus_child = 1;
1284 } else
1285 *requested = new_view;
1287 return NULL;
1290 static void
1291 tog_resizeterm(void)
1293 int cols, lines;
1294 struct winsize size;
1296 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1297 cols = 80; /* Default */
1298 lines = 24;
1299 } else {
1300 cols = size.ws_col;
1301 lines = size.ws_row;
1303 resize_term(lines, cols);
1306 static const struct got_error *
1307 view_search_start(struct tog_view *view, int fast_refresh)
1309 const struct got_error *err = NULL;
1310 struct tog_view *v = view;
1311 char pattern[1024];
1312 int ret;
1314 if (view->search_started) {
1315 regfree(&view->regex);
1316 view->searching = 0;
1317 memset(&view->regmatch, 0, sizeof(view->regmatch));
1319 view->search_started = 0;
1321 if (view->nlines < 1)
1322 return NULL;
1324 if (view_is_hsplit_top(view))
1325 v = view->child;
1326 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1327 v = view->parent;
1329 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1330 wclrtoeol(v->window);
1332 nodelay(v->window, FALSE); /* block for search term input */
1333 nocbreak();
1334 echo();
1335 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1336 wrefresh(v->window);
1337 cbreak();
1338 noecho();
1339 nodelay(v->window, TRUE);
1340 if (!fast_refresh && !using_mock_io)
1341 halfdelay(10);
1342 if (ret == ERR)
1343 return NULL;
1345 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1346 err = view->search_start(view);
1347 if (err) {
1348 regfree(&view->regex);
1349 return err;
1351 view->search_started = 1;
1352 view->searching = TOG_SEARCH_FORWARD;
1353 view->search_next_done = 0;
1354 view->search_next(view);
1357 return NULL;
1360 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1361 static const struct got_error *
1362 switch_split(struct tog_view *view)
1364 const struct got_error *err = NULL;
1365 struct tog_view *v = NULL;
1367 if (view->parent)
1368 v = view->parent;
1369 else
1370 v = view;
1372 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1373 v->mode = TOG_VIEW_SPLIT_VERT;
1374 else
1375 v->mode = TOG_VIEW_SPLIT_HRZN;
1377 if (!v->child)
1378 return NULL;
1379 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1380 v->mode = TOG_VIEW_SPLIT_NONE;
1382 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1383 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1384 v->child->begin_y = v->child->resized_y;
1385 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1386 v->child->begin_x = v->child->resized_x;
1389 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1390 v->ncols = COLS;
1391 v->child->ncols = COLS;
1392 v->child->nscrolled = LINES - v->child->nlines;
1394 err = view_init_hsplit(v, v->child->begin_y);
1395 if (err)
1396 return err;
1398 v->child->mode = v->mode;
1399 v->child->nlines = v->lines - v->child->begin_y;
1400 v->focus_child = 1;
1402 err = view_fullscreen(v);
1403 if (err)
1404 return err;
1405 err = view_splitscreen(v->child);
1406 if (err)
1407 return err;
1409 if (v->mode == TOG_VIEW_SPLIT_NONE)
1410 v->mode = TOG_VIEW_SPLIT_VERT;
1411 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1412 err = offset_selection_down(v);
1413 if (err)
1414 return err;
1415 err = offset_selection_down(v->child);
1416 if (err)
1417 return err;
1418 } else {
1419 offset_selection_up(v);
1420 offset_selection_up(v->child);
1422 if (v->resize)
1423 err = v->resize(v, 0);
1424 else if (v->child->resize)
1425 err = v->child->resize(v->child, 0);
1427 return err;
1431 * Strip trailing whitespace from str starting at byte *n;
1432 * if *n < 0, use strlen(str). Return new str length in *n.
1434 static void
1435 strip_trailing_ws(char *str, int *n)
1437 size_t x = *n;
1439 if (str == NULL || *str == '\0')
1440 return;
1442 if (x < 0)
1443 x = strlen(str);
1445 while (x-- > 0 && isspace((unsigned char)str[x]))
1446 str[x] = '\0';
1448 *n = x + 1;
1452 * Extract visible substring of line y from the curses screen
1453 * and strip trailing whitespace. If vline is set and locale is
1454 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1455 * character is written out as 'x'. Write the line to file f.
1457 static const struct got_error *
1458 view_write_line(FILE *f, int y, int vline)
1460 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1461 int r, w;
1463 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1464 if (r == ERR)
1465 return got_error_fmt(GOT_ERR_RANGE,
1466 "failed to extract line %d", y);
1469 * In some views, lines are padded with blanks to COLS width.
1470 * Strip them so we can diff without the -b flag when testing.
1472 strip_trailing_ws(line, &r);
1474 if (vline > 0 && got_locale_is_utf8())
1475 line[vline] = '|';
1477 w = fprintf(f, "%s\n", line);
1478 if (w != r + 1) /* \n */
1479 return got_ferror(f, GOT_ERR_IO);
1481 return NULL;
1485 * Capture the visible curses screen by writing each line to the
1486 * file at the path set via the TOG_SCR_DUMP environment variable.
1488 static const struct got_error *
1489 screendump(struct tog_view *view)
1491 const struct got_error *err;
1492 FILE *f = NULL;
1493 const char *path;
1494 int i;
1496 path = getenv("TOG_SCR_DUMP");
1497 if (path == NULL || *path == '\0')
1498 return got_error_msg(GOT_ERR_BAD_PATH,
1499 "TOG_SCR_DUMP path not set to capture screen dump");
1500 f = fopen(path, "wex");
1501 if (f == NULL)
1502 return got_error_from_errno_fmt("fopen: %s", path);
1504 if ((view->child && view->child->begin_x) ||
1505 (view->parent && view->begin_x)) {
1506 int ncols = view->child ? view->ncols : view->parent->ncols;
1508 /* vertical splitscreen */
1509 for (i = 0; i < view->nlines; ++i) {
1510 err = view_write_line(f, i, ncols - 1);
1511 if (err)
1512 goto done;
1514 } else {
1515 int hline = 0;
1517 /* fullscreen or horizontal splitscreen */
1518 if ((view->child && view->child->begin_y) ||
1519 (view->parent && view->begin_y)) /* hsplit */
1520 hline = view->child ?
1521 view->child->begin_y : view->begin_y;
1523 for (i = 0; i < view->lines; i++) {
1524 if (hline && got_locale_is_utf8() && i == hline - 1) {
1525 int c;
1527 /* ACS_HLINE writes out as 'q', overwrite it */
1528 for (c = 0; c < view->cols; ++c)
1529 fputc('-', f);
1530 fputc('\n', f);
1531 continue;
1534 err = view_write_line(f, i, 0);
1535 if (err)
1536 goto done;
1540 done:
1541 if (f && fclose(f) == EOF && err == NULL)
1542 err = got_ferror(f, GOT_ERR_IO);
1543 return err;
1547 * Compute view->count from numeric input. Assign total to view->count and
1548 * return first non-numeric key entered.
1550 static int
1551 get_compound_key(struct tog_view *view, int c)
1553 struct tog_view *v = view;
1554 int x, n = 0;
1556 if (view_is_hsplit_top(view))
1557 v = view->child;
1558 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1559 v = view->parent;
1561 view->count = 0;
1562 cbreak(); /* block for input */
1563 nodelay(view->window, FALSE);
1564 wmove(v->window, v->nlines - 1, 0);
1565 wclrtoeol(v->window);
1566 waddch(v->window, ':');
1568 do {
1569 x = getcurx(v->window);
1570 if (x != ERR && x < view->ncols) {
1571 waddch(v->window, c);
1572 wrefresh(v->window);
1576 * Don't overflow. Max valid request should be the greatest
1577 * between the longest and total lines; cap at 10 million.
1579 if (n >= 9999999)
1580 n = 9999999;
1581 else
1582 n = n * 10 + (c - '0');
1583 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1585 if (c == 'G' || c == 'g') { /* nG key map */
1586 view->gline = view->hiline = n;
1587 n = 0;
1588 c = 0;
1591 /* Massage excessive or inapplicable values at the input handler. */
1592 view->count = n;
1594 return c;
1597 static void
1598 action_report(struct tog_view *view)
1600 struct tog_view *v = view;
1602 if (view_is_hsplit_top(view))
1603 v = view->child;
1604 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1605 v = view->parent;
1607 wmove(v->window, v->nlines - 1, 0);
1608 wclrtoeol(v->window);
1609 wprintw(v->window, ":%s", view->action);
1610 wrefresh(v->window);
1613 * Clear action status report. Only clear in blame view
1614 * once annotating is complete, otherwise it's too fast.
1616 if (view->type == TOG_VIEW_BLAME) {
1617 if (view->state.blame.blame_complete)
1618 view->action = NULL;
1619 } else
1620 view->action = NULL;
1624 * Read the next line from the test script and assign
1625 * key instruction to *ch. If at EOF, set the *done flag.
1627 static const struct got_error *
1628 tog_read_script_key(FILE *script, int *ch, int *done)
1630 const struct got_error *err = NULL;
1631 char *line = NULL;
1632 size_t linesz = 0;
1634 *ch = -1;
1636 if (getline(&line, &linesz, script) == -1) {
1637 if (feof(script)) {
1638 *done = 1;
1639 goto done;
1640 } else {
1641 err = got_ferror(script, GOT_ERR_IO);
1642 goto done;
1646 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1647 tog_io.wait_for_ui = 1;
1648 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1649 *ch = KEY_ENTER;
1650 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1651 *ch = KEY_RIGHT;
1652 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1653 *ch = KEY_LEFT;
1654 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1655 *ch = KEY_DOWN;
1656 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1657 *ch = KEY_UP;
1658 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1659 *ch = TOG_KEY_SCRDUMP;
1660 else
1661 *ch = *line;
1663 done:
1664 free(line);
1665 return err;
1668 static const struct got_error *
1669 view_input(struct tog_view **new, int *done, struct tog_view *view,
1670 struct tog_view_list_head *views, int fast_refresh)
1672 const struct got_error *err = NULL;
1673 struct tog_view *v;
1674 int ch, errcode;
1676 *new = NULL;
1678 if (view->action)
1679 action_report(view);
1681 /* Clear "no matches" indicator. */
1682 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1683 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1684 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1685 view->count = 0;
1688 if (view->searching && !view->search_next_done) {
1689 errcode = pthread_mutex_unlock(&tog_mutex);
1690 if (errcode)
1691 return got_error_set_errno(errcode,
1692 "pthread_mutex_unlock");
1693 sched_yield();
1694 errcode = pthread_mutex_lock(&tog_mutex);
1695 if (errcode)
1696 return got_error_set_errno(errcode,
1697 "pthread_mutex_lock");
1698 view->search_next(view);
1699 return NULL;
1702 /* Allow threads to make progress while we are waiting for input. */
1703 errcode = pthread_mutex_unlock(&tog_mutex);
1704 if (errcode)
1705 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1707 if (using_mock_io) {
1708 err = tog_read_script_key(tog_io.f, &ch, done);
1709 if (err) {
1710 errcode = pthread_mutex_lock(&tog_mutex);
1711 return err;
1713 } else if (view->count && --view->count) {
1714 cbreak();
1715 nodelay(view->window, TRUE);
1716 ch = wgetch(view->window);
1717 /* let C-g or backspace abort unfinished count */
1718 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1719 view->count = 0;
1720 else
1721 ch = view->ch;
1722 } else {
1723 ch = wgetch(view->window);
1724 if (ch >= '1' && ch <= '9')
1725 view->ch = ch = get_compound_key(view, ch);
1727 if (view->hiline && ch != ERR && ch != 0)
1728 view->hiline = 0; /* key pressed, clear line highlight */
1729 nodelay(view->window, TRUE);
1730 errcode = pthread_mutex_lock(&tog_mutex);
1731 if (errcode)
1732 return got_error_set_errno(errcode, "pthread_mutex_lock");
1734 if (tog_sigwinch_received || tog_sigcont_received) {
1735 tog_resizeterm();
1736 tog_sigwinch_received = 0;
1737 tog_sigcont_received = 0;
1738 TAILQ_FOREACH(v, views, entry) {
1739 err = view_resize(v);
1740 if (err)
1741 return err;
1742 err = v->input(new, v, KEY_RESIZE);
1743 if (err)
1744 return err;
1745 if (v->child) {
1746 err = view_resize(v->child);
1747 if (err)
1748 return err;
1749 err = v->child->input(new, v->child,
1750 KEY_RESIZE);
1751 if (err)
1752 return err;
1753 if (v->child->resized_x || v->child->resized_y) {
1754 err = view_resize_split(v, 0);
1755 if (err)
1756 return err;
1762 switch (ch) {
1763 case '?':
1764 case 'H':
1765 case KEY_F(1):
1766 if (view->type == TOG_VIEW_HELP)
1767 err = view->reset(view);
1768 else
1769 err = view_request_new(new, view, TOG_VIEW_HELP);
1770 break;
1771 case '\t':
1772 view->count = 0;
1773 if (view->child) {
1774 view->focussed = 0;
1775 view->child->focussed = 1;
1776 view->focus_child = 1;
1777 } else if (view->parent) {
1778 view->focussed = 0;
1779 view->parent->focussed = 1;
1780 view->parent->focus_child = 0;
1781 if (!view_is_splitscreen(view)) {
1782 if (view->parent->resize) {
1783 err = view->parent->resize(view->parent,
1784 0);
1785 if (err)
1786 return err;
1788 offset_selection_up(view->parent);
1789 err = view_fullscreen(view->parent);
1790 if (err)
1791 return err;
1794 break;
1795 case 'q':
1796 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1797 if (view->parent->resize) {
1798 /* might need more commits to fill fullscreen */
1799 err = view->parent->resize(view->parent, 0);
1800 if (err)
1801 break;
1803 offset_selection_up(view->parent);
1805 err = view->input(new, view, ch);
1806 view->dying = 1;
1807 break;
1808 case 'Q':
1809 *done = 1;
1810 break;
1811 case 'F':
1812 view->count = 0;
1813 if (view_is_parent_view(view)) {
1814 if (view->child == NULL)
1815 break;
1816 if (view_is_splitscreen(view->child)) {
1817 view->focussed = 0;
1818 view->child->focussed = 1;
1819 err = view_fullscreen(view->child);
1820 } else {
1821 err = view_splitscreen(view->child);
1822 if (!err)
1823 err = view_resize_split(view, 0);
1825 if (err)
1826 break;
1827 err = view->child->input(new, view->child,
1828 KEY_RESIZE);
1829 } else {
1830 if (view_is_splitscreen(view)) {
1831 view->parent->focussed = 0;
1832 view->focussed = 1;
1833 err = view_fullscreen(view);
1834 } else {
1835 err = view_splitscreen(view);
1836 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1837 err = view_resize(view->parent);
1838 if (!err)
1839 err = view_resize_split(view, 0);
1841 if (err)
1842 break;
1843 err = view->input(new, view, KEY_RESIZE);
1845 if (err)
1846 break;
1847 if (view->resize) {
1848 err = view->resize(view, 0);
1849 if (err)
1850 break;
1852 if (view->parent)
1853 err = offset_selection_down(view->parent);
1854 if (!err)
1855 err = offset_selection_down(view);
1856 break;
1857 case 'S':
1858 view->count = 0;
1859 err = switch_split(view);
1860 break;
1861 case '-':
1862 err = view_resize_split(view, -1);
1863 break;
1864 case '+':
1865 err = view_resize_split(view, 1);
1866 break;
1867 case KEY_RESIZE:
1868 break;
1869 case '/':
1870 view->count = 0;
1871 if (view->search_start)
1872 view_search_start(view, fast_refresh);
1873 else
1874 err = view->input(new, view, ch);
1875 break;
1876 case 'N':
1877 case 'n':
1878 if (view->search_started && view->search_next) {
1879 view->searching = (ch == 'n' ?
1880 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1881 view->search_next_done = 0;
1882 view->search_next(view);
1883 } else
1884 err = view->input(new, view, ch);
1885 break;
1886 case 'A':
1887 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1888 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1889 view->action = "Patience diff algorithm";
1890 } else {
1891 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1892 view->action = "Myers diff algorithm";
1894 TAILQ_FOREACH(v, views, entry) {
1895 if (v->reset) {
1896 err = v->reset(v);
1897 if (err)
1898 return err;
1900 if (v->child && v->child->reset) {
1901 err = v->child->reset(v->child);
1902 if (err)
1903 return err;
1906 break;
1907 case TOG_KEY_SCRDUMP:
1908 err = screendump(view);
1909 break;
1910 default:
1911 err = view->input(new, view, ch);
1912 break;
1915 return err;
1918 static int
1919 view_needs_focus_indication(struct tog_view *view)
1921 if (view_is_parent_view(view)) {
1922 if (view->child == NULL || view->child->focussed)
1923 return 0;
1924 if (!view_is_splitscreen(view->child))
1925 return 0;
1926 } else if (!view_is_splitscreen(view))
1927 return 0;
1929 return view->focussed;
1932 static const struct got_error *
1933 tog_io_close(void)
1935 const struct got_error *err = NULL;
1937 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1938 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1939 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1940 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1941 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1942 err = got_ferror(tog_io.f, GOT_ERR_IO);
1944 return err;
1947 static const struct got_error *
1948 view_loop(struct tog_view *view)
1950 const struct got_error *err = NULL;
1951 struct tog_view_list_head views;
1952 struct tog_view *new_view;
1953 char *mode;
1954 int fast_refresh = 10;
1955 int done = 0, errcode;
1957 mode = getenv("TOG_VIEW_SPLIT_MODE");
1958 if (!mode || !(*mode == 'h' || *mode == 'H'))
1959 view->mode = TOG_VIEW_SPLIT_VERT;
1960 else
1961 view->mode = TOG_VIEW_SPLIT_HRZN;
1963 errcode = pthread_mutex_lock(&tog_mutex);
1964 if (errcode)
1965 return got_error_set_errno(errcode, "pthread_mutex_lock");
1967 TAILQ_INIT(&views);
1968 TAILQ_INSERT_HEAD(&views, view, entry);
1970 view->focussed = 1;
1971 err = view->show(view);
1972 if (err)
1973 return err;
1974 update_panels();
1975 doupdate();
1976 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1977 !tog_fatal_signal_received()) {
1978 /* Refresh fast during initialization, then become slower. */
1979 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1980 halfdelay(10); /* switch to once per second */
1982 err = view_input(&new_view, &done, view, &views, fast_refresh);
1983 if (err)
1984 break;
1986 if (view->dying && view == TAILQ_FIRST(&views) &&
1987 TAILQ_NEXT(view, entry) == NULL)
1988 done = 1;
1989 if (done) {
1990 struct tog_view *v;
1993 * When we quit, scroll the screen up a single line
1994 * so we don't lose any information.
1996 TAILQ_FOREACH(v, &views, entry) {
1997 wmove(v->window, 0, 0);
1998 wdeleteln(v->window);
1999 wnoutrefresh(v->window);
2000 if (v->child && !view_is_fullscreen(v)) {
2001 wmove(v->child->window, 0, 0);
2002 wdeleteln(v->child->window);
2003 wnoutrefresh(v->child->window);
2006 doupdate();
2009 if (view->dying) {
2010 struct tog_view *v, *prev = NULL;
2012 if (view_is_parent_view(view))
2013 prev = TAILQ_PREV(view, tog_view_list_head,
2014 entry);
2015 else if (view->parent)
2016 prev = view->parent;
2018 if (view->parent) {
2019 view->parent->child = NULL;
2020 view->parent->focus_child = 0;
2021 /* Restore fullscreen line height. */
2022 view->parent->nlines = view->parent->lines;
2023 err = view_resize(view->parent);
2024 if (err)
2025 break;
2026 /* Make resized splits persist. */
2027 view_transfer_size(view->parent, view);
2028 } else
2029 TAILQ_REMOVE(&views, view, entry);
2031 err = view_close(view);
2032 if (err)
2033 goto done;
2035 view = NULL;
2036 TAILQ_FOREACH(v, &views, entry) {
2037 if (v->focussed)
2038 break;
2040 if (view == NULL && new_view == NULL) {
2041 /* No view has focus. Try to pick one. */
2042 if (prev)
2043 view = prev;
2044 else if (!TAILQ_EMPTY(&views)) {
2045 view = TAILQ_LAST(&views,
2046 tog_view_list_head);
2048 if (view) {
2049 if (view->focus_child) {
2050 view->child->focussed = 1;
2051 view = view->child;
2052 } else
2053 view->focussed = 1;
2057 if (new_view) {
2058 struct tog_view *v, *t;
2059 /* Only allow one parent view per type. */
2060 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2061 if (v->type != new_view->type)
2062 continue;
2063 TAILQ_REMOVE(&views, v, entry);
2064 err = view_close(v);
2065 if (err)
2066 goto done;
2067 break;
2069 TAILQ_INSERT_TAIL(&views, new_view, entry);
2070 view = new_view;
2072 if (view && !done) {
2073 if (view_is_parent_view(view)) {
2074 if (view->child && view->child->focussed)
2075 view = view->child;
2076 } else {
2077 if (view->parent && view->parent->focussed)
2078 view = view->parent;
2080 show_panel(view->panel);
2081 if (view->child && view_is_splitscreen(view->child))
2082 show_panel(view->child->panel);
2083 if (view->parent && view_is_splitscreen(view)) {
2084 err = view->parent->show(view->parent);
2085 if (err)
2086 goto done;
2088 err = view->show(view);
2089 if (err)
2090 goto done;
2091 if (view->child) {
2092 err = view->child->show(view->child);
2093 if (err)
2094 goto done;
2096 update_panels();
2097 doupdate();
2100 done:
2101 while (!TAILQ_EMPTY(&views)) {
2102 const struct got_error *close_err;
2103 view = TAILQ_FIRST(&views);
2104 TAILQ_REMOVE(&views, view, entry);
2105 close_err = view_close(view);
2106 if (close_err && err == NULL)
2107 err = close_err;
2110 errcode = pthread_mutex_unlock(&tog_mutex);
2111 if (errcode && err == NULL)
2112 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2114 return err;
2117 __dead static void
2118 usage_log(void)
2120 endwin();
2121 fprintf(stderr,
2122 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2123 getprogname());
2124 exit(1);
2127 /* Create newly allocated wide-character string equivalent to a byte string. */
2128 static const struct got_error *
2129 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2131 char *vis = NULL;
2132 const struct got_error *err = NULL;
2134 *ws = NULL;
2135 *wlen = mbstowcs(NULL, s, 0);
2136 if (*wlen == (size_t)-1) {
2137 int vislen;
2138 if (errno != EILSEQ)
2139 return got_error_from_errno("mbstowcs");
2141 /* byte string invalid in current encoding; try to "fix" it */
2142 err = got_mbsavis(&vis, &vislen, s);
2143 if (err)
2144 return err;
2145 *wlen = mbstowcs(NULL, vis, 0);
2146 if (*wlen == (size_t)-1) {
2147 err = got_error_from_errno("mbstowcs"); /* give up */
2148 goto done;
2152 *ws = calloc(*wlen + 1, sizeof(**ws));
2153 if (*ws == NULL) {
2154 err = got_error_from_errno("calloc");
2155 goto done;
2158 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2159 err = got_error_from_errno("mbstowcs");
2160 done:
2161 free(vis);
2162 if (err) {
2163 free(*ws);
2164 *ws = NULL;
2165 *wlen = 0;
2167 return err;
2170 static const struct got_error *
2171 expand_tab(char **ptr, const char *src)
2173 char *dst;
2174 size_t len, n, idx = 0, sz = 0;
2176 *ptr = NULL;
2177 n = len = strlen(src);
2178 dst = malloc(n + 1);
2179 if (dst == NULL)
2180 return got_error_from_errno("malloc");
2182 while (idx < len && src[idx]) {
2183 const char c = src[idx];
2185 if (c == '\t') {
2186 size_t nb = TABSIZE - sz % TABSIZE;
2187 char *p;
2189 p = realloc(dst, n + nb);
2190 if (p == NULL) {
2191 free(dst);
2192 return got_error_from_errno("realloc");
2195 dst = p;
2196 n += nb;
2197 memset(dst + sz, ' ', nb);
2198 sz += nb;
2199 } else
2200 dst[sz++] = src[idx];
2201 ++idx;
2204 dst[sz] = '\0';
2205 *ptr = dst;
2206 return NULL;
2210 * Advance at most n columns from wline starting at offset off.
2211 * Return the index to the first character after the span operation.
2212 * Return the combined column width of all spanned wide character in
2213 * *rcol.
2215 static int
2216 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2218 int width, i, cols = 0;
2220 if (n == 0) {
2221 *rcol = cols;
2222 return off;
2225 for (i = off; wline[i] != L'\0'; ++i) {
2226 if (wline[i] == L'\t')
2227 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2228 else
2229 width = wcwidth(wline[i]);
2231 if (width == -1) {
2232 width = 1;
2233 wline[i] = L'.';
2236 if (cols + width > n)
2237 break;
2238 cols += width;
2241 *rcol = cols;
2242 return i;
2246 * Format a line for display, ensuring that it won't overflow a width limit.
2247 * With scrolling, the width returned refers to the scrolled version of the
2248 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2250 static const struct got_error *
2251 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2252 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2254 const struct got_error *err = NULL;
2255 int cols;
2256 wchar_t *wline = NULL;
2257 char *exstr = NULL;
2258 size_t wlen;
2259 int i, scrollx;
2261 *wlinep = NULL;
2262 *widthp = 0;
2264 if (expand) {
2265 err = expand_tab(&exstr, line);
2266 if (err)
2267 return err;
2270 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2271 free(exstr);
2272 if (err)
2273 return err;
2275 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2277 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2278 wline[wlen - 1] = L'\0';
2279 wlen--;
2281 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2282 wline[wlen - 1] = L'\0';
2283 wlen--;
2286 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2287 wline[i] = L'\0';
2289 if (widthp)
2290 *widthp = cols;
2291 if (scrollxp)
2292 *scrollxp = scrollx;
2293 if (err)
2294 free(wline);
2295 else
2296 *wlinep = wline;
2297 return err;
2300 static const struct got_error*
2301 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2302 struct got_object_id *id, struct got_repository *repo)
2304 static const struct got_error *err = NULL;
2305 struct got_reflist_entry *re;
2306 char *s;
2307 const char *name;
2309 *refs_str = NULL;
2311 TAILQ_FOREACH(re, refs, entry) {
2312 struct got_tag_object *tag = NULL;
2313 struct got_object_id *ref_id;
2314 int cmp;
2316 name = got_ref_get_name(re->ref);
2317 if (strcmp(name, GOT_REF_HEAD) == 0)
2318 continue;
2319 if (strncmp(name, "refs/", 5) == 0)
2320 name += 5;
2321 if (strncmp(name, "got/", 4) == 0 &&
2322 strncmp(name, "got/backup/", 11) != 0)
2323 continue;
2324 if (strncmp(name, "heads/", 6) == 0)
2325 name += 6;
2326 if (strncmp(name, "remotes/", 8) == 0) {
2327 name += 8;
2328 s = strstr(name, "/" GOT_REF_HEAD);
2329 if (s != NULL && s[strlen(s)] == '\0')
2330 continue;
2332 err = got_ref_resolve(&ref_id, repo, re->ref);
2333 if (err)
2334 break;
2335 if (strncmp(name, "tags/", 5) == 0) {
2336 err = got_object_open_as_tag(&tag, repo, ref_id);
2337 if (err) {
2338 if (err->code != GOT_ERR_OBJ_TYPE) {
2339 free(ref_id);
2340 break;
2342 /* Ref points at something other than a tag. */
2343 err = NULL;
2344 tag = NULL;
2347 cmp = got_object_id_cmp(tag ?
2348 got_object_tag_get_object_id(tag) : ref_id, id);
2349 free(ref_id);
2350 if (tag)
2351 got_object_tag_close(tag);
2352 if (cmp != 0)
2353 continue;
2354 s = *refs_str;
2355 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2356 s ? ", " : "", name) == -1) {
2357 err = got_error_from_errno("asprintf");
2358 free(s);
2359 *refs_str = NULL;
2360 break;
2362 free(s);
2365 return err;
2368 static const struct got_error *
2369 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2370 int col_tab_align)
2372 char *smallerthan;
2374 smallerthan = strchr(author, '<');
2375 if (smallerthan && smallerthan[1] != '\0')
2376 author = smallerthan + 1;
2377 author[strcspn(author, "@>")] = '\0';
2378 return format_line(wauthor, author_width, NULL, author, 0, limit,
2379 col_tab_align, 0);
2382 static const struct got_error *
2383 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2384 struct got_object_id *id, const size_t date_display_cols,
2385 int author_display_cols)
2387 struct tog_log_view_state *s = &view->state.log;
2388 const struct got_error *err = NULL;
2389 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2390 char *logmsg0 = NULL, *logmsg = NULL;
2391 char *author = NULL;
2392 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2393 int author_width, logmsg_width;
2394 char *newline, *line = NULL;
2395 int col, limit, scrollx;
2396 const int avail = view->ncols;
2397 struct tm tm;
2398 time_t committer_time;
2399 struct tog_color *tc;
2401 committer_time = got_object_commit_get_committer_time(commit);
2402 if (gmtime_r(&committer_time, &tm) == NULL)
2403 return got_error_from_errno("gmtime_r");
2404 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2405 return got_error(GOT_ERR_NO_SPACE);
2407 if (avail <= date_display_cols)
2408 limit = MIN(sizeof(datebuf) - 1, avail);
2409 else
2410 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2411 tc = get_color(&s->colors, TOG_COLOR_DATE);
2412 if (tc)
2413 wattr_on(view->window,
2414 COLOR_PAIR(tc->colorpair), NULL);
2415 waddnstr(view->window, datebuf, limit);
2416 if (tc)
2417 wattr_off(view->window,
2418 COLOR_PAIR(tc->colorpair), NULL);
2419 col = limit;
2420 if (col > avail)
2421 goto done;
2423 if (avail >= 120) {
2424 char *id_str;
2425 err = got_object_id_str(&id_str, id);
2426 if (err)
2427 goto done;
2428 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2429 if (tc)
2430 wattr_on(view->window,
2431 COLOR_PAIR(tc->colorpair), NULL);
2432 wprintw(view->window, "%.8s ", id_str);
2433 if (tc)
2434 wattr_off(view->window,
2435 COLOR_PAIR(tc->colorpair), NULL);
2436 free(id_str);
2437 col += 9;
2438 if (col > avail)
2439 goto done;
2442 if (s->use_committer)
2443 author = strdup(got_object_commit_get_committer(commit));
2444 else
2445 author = strdup(got_object_commit_get_author(commit));
2446 if (author == NULL) {
2447 err = got_error_from_errno("strdup");
2448 goto done;
2450 err = format_author(&wauthor, &author_width, author, avail - col, col);
2451 if (err)
2452 goto done;
2453 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2454 if (tc)
2455 wattr_on(view->window,
2456 COLOR_PAIR(tc->colorpair), NULL);
2457 waddwstr(view->window, wauthor);
2458 col += author_width;
2459 while (col < avail && author_width < author_display_cols + 2) {
2460 waddch(view->window, ' ');
2461 col++;
2462 author_width++;
2464 if (tc)
2465 wattr_off(view->window,
2466 COLOR_PAIR(tc->colorpair), NULL);
2467 if (col > avail)
2468 goto done;
2470 err = got_object_commit_get_logmsg(&logmsg0, commit);
2471 if (err)
2472 goto done;
2473 logmsg = logmsg0;
2474 while (*logmsg == '\n')
2475 logmsg++;
2476 newline = strchr(logmsg, '\n');
2477 if (newline)
2478 *newline = '\0';
2479 limit = avail - col;
2480 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2481 limit--; /* for the border */
2482 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2483 limit, col, 1);
2484 if (err)
2485 goto done;
2486 waddwstr(view->window, &wlogmsg[scrollx]);
2487 col += MAX(logmsg_width, 0);
2488 while (col < avail) {
2489 waddch(view->window, ' ');
2490 col++;
2492 done:
2493 free(logmsg0);
2494 free(wlogmsg);
2495 free(author);
2496 free(wauthor);
2497 free(line);
2498 return err;
2501 static struct commit_queue_entry *
2502 alloc_commit_queue_entry(struct got_commit_object *commit,
2503 struct got_object_id *id)
2505 struct commit_queue_entry *entry;
2506 struct got_object_id *dup;
2508 entry = calloc(1, sizeof(*entry));
2509 if (entry == NULL)
2510 return NULL;
2512 dup = got_object_id_dup(id);
2513 if (dup == NULL) {
2514 free(entry);
2515 return NULL;
2518 entry->id = dup;
2519 entry->commit = commit;
2520 return entry;
2523 static void
2524 pop_commit(struct commit_queue *commits)
2526 struct commit_queue_entry *entry;
2528 entry = TAILQ_FIRST(&commits->head);
2529 TAILQ_REMOVE(&commits->head, entry, entry);
2530 got_object_commit_close(entry->commit);
2531 commits->ncommits--;
2532 free(entry->id);
2533 free(entry);
2536 static void
2537 free_commits(struct commit_queue *commits)
2539 while (!TAILQ_EMPTY(&commits->head))
2540 pop_commit(commits);
2543 static const struct got_error *
2544 match_commit(int *have_match, struct got_object_id *id,
2545 struct got_commit_object *commit, regex_t *regex)
2547 const struct got_error *err = NULL;
2548 regmatch_t regmatch;
2549 char *id_str = NULL, *logmsg = NULL;
2551 *have_match = 0;
2553 err = got_object_id_str(&id_str, id);
2554 if (err)
2555 return err;
2557 err = got_object_commit_get_logmsg(&logmsg, commit);
2558 if (err)
2559 goto done;
2561 if (regexec(regex, got_object_commit_get_author(commit), 1,
2562 &regmatch, 0) == 0 ||
2563 regexec(regex, got_object_commit_get_committer(commit), 1,
2564 &regmatch, 0) == 0 ||
2565 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2566 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2567 *have_match = 1;
2568 done:
2569 free(id_str);
2570 free(logmsg);
2571 return err;
2574 static const struct got_error *
2575 queue_commits(struct tog_log_thread_args *a)
2577 const struct got_error *err = NULL;
2580 * We keep all commits open throughout the lifetime of the log
2581 * view in order to avoid having to re-fetch commits from disk
2582 * while updating the display.
2584 do {
2585 struct got_object_id id;
2586 struct got_commit_object *commit;
2587 struct commit_queue_entry *entry;
2588 int limit_match = 0;
2589 int errcode;
2591 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2592 NULL, NULL);
2593 if (err)
2594 break;
2596 err = got_object_open_as_commit(&commit, a->repo, &id);
2597 if (err)
2598 break;
2599 entry = alloc_commit_queue_entry(commit, &id);
2600 if (entry == NULL) {
2601 err = got_error_from_errno("alloc_commit_queue_entry");
2602 break;
2605 errcode = pthread_mutex_lock(&tog_mutex);
2606 if (errcode) {
2607 err = got_error_set_errno(errcode,
2608 "pthread_mutex_lock");
2609 break;
2612 entry->idx = a->real_commits->ncommits;
2613 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2614 a->real_commits->ncommits++;
2616 if (*a->limiting) {
2617 err = match_commit(&limit_match, &id, commit,
2618 a->limit_regex);
2619 if (err)
2620 break;
2622 if (limit_match) {
2623 struct commit_queue_entry *matched;
2625 matched = alloc_commit_queue_entry(
2626 entry->commit, entry->id);
2627 if (matched == NULL) {
2628 err = got_error_from_errno(
2629 "alloc_commit_queue_entry");
2630 break;
2632 matched->commit = entry->commit;
2633 got_object_commit_retain(entry->commit);
2635 matched->idx = a->limit_commits->ncommits;
2636 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2637 matched, entry);
2638 a->limit_commits->ncommits++;
2642 * This is how we signal log_thread() that we
2643 * have found a match, and that it should be
2644 * counted as a new entry for the view.
2646 a->limit_match = limit_match;
2649 if (*a->searching == TOG_SEARCH_FORWARD &&
2650 !*a->search_next_done) {
2651 int have_match;
2652 err = match_commit(&have_match, &id, commit, a->regex);
2653 if (err)
2654 break;
2656 if (*a->limiting) {
2657 if (limit_match && have_match)
2658 *a->search_next_done =
2659 TOG_SEARCH_HAVE_MORE;
2660 } else if (have_match)
2661 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2664 errcode = pthread_mutex_unlock(&tog_mutex);
2665 if (errcode && err == NULL)
2666 err = got_error_set_errno(errcode,
2667 "pthread_mutex_unlock");
2668 if (err)
2669 break;
2670 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2672 return err;
2675 static void
2676 select_commit(struct tog_log_view_state *s)
2678 struct commit_queue_entry *entry;
2679 int ncommits = 0;
2681 entry = s->first_displayed_entry;
2682 while (entry) {
2683 if (ncommits == s->selected) {
2684 s->selected_entry = entry;
2685 break;
2687 entry = TAILQ_NEXT(entry, entry);
2688 ncommits++;
2692 static const struct got_error *
2693 draw_commits(struct tog_view *view)
2695 const struct got_error *err = NULL;
2696 struct tog_log_view_state *s = &view->state.log;
2697 struct commit_queue_entry *entry = s->selected_entry;
2698 int limit = view->nlines;
2699 int width;
2700 int ncommits, author_cols = 4;
2701 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2702 char *refs_str = NULL;
2703 wchar_t *wline;
2704 struct tog_color *tc;
2705 static const size_t date_display_cols = 12;
2707 if (view_is_hsplit_top(view))
2708 --limit; /* account for border */
2710 if (s->selected_entry &&
2711 !(view->searching && view->search_next_done == 0)) {
2712 struct got_reflist_head *refs;
2713 err = got_object_id_str(&id_str, s->selected_entry->id);
2714 if (err)
2715 return err;
2716 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2717 s->selected_entry->id);
2718 if (refs) {
2719 err = build_refs_str(&refs_str, refs,
2720 s->selected_entry->id, s->repo);
2721 if (err)
2722 goto done;
2726 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2727 halfdelay(10); /* disable fast refresh */
2729 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2730 if (asprintf(&ncommits_str, " [%d/%d] %s",
2731 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2732 (view->searching && !view->search_next_done) ?
2733 "searching..." : "loading...") == -1) {
2734 err = got_error_from_errno("asprintf");
2735 goto done;
2737 } else {
2738 const char *search_str = NULL;
2739 const char *limit_str = NULL;
2741 if (view->searching) {
2742 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2743 search_str = "no more matches";
2744 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2745 search_str = "no matches found";
2746 else if (!view->search_next_done)
2747 search_str = "searching...";
2750 if (s->limit_view && s->commits->ncommits == 0)
2751 limit_str = "no matches found";
2753 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2754 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2755 search_str ? search_str : (refs_str ? refs_str : ""),
2756 limit_str ? limit_str : "") == -1) {
2757 err = got_error_from_errno("asprintf");
2758 goto done;
2762 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2763 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2764 "........................................",
2765 s->in_repo_path, ncommits_str) == -1) {
2766 err = got_error_from_errno("asprintf");
2767 header = NULL;
2768 goto done;
2770 } else if (asprintf(&header, "commit %s%s",
2771 id_str ? id_str : "........................................",
2772 ncommits_str) == -1) {
2773 err = got_error_from_errno("asprintf");
2774 header = NULL;
2775 goto done;
2777 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2778 if (err)
2779 goto done;
2781 werase(view->window);
2783 if (view_needs_focus_indication(view))
2784 wstandout(view->window);
2785 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2786 if (tc)
2787 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2788 waddwstr(view->window, wline);
2789 while (width < view->ncols) {
2790 waddch(view->window, ' ');
2791 width++;
2793 if (tc)
2794 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2795 if (view_needs_focus_indication(view))
2796 wstandend(view->window);
2797 free(wline);
2798 if (limit <= 1)
2799 goto done;
2801 /* Grow author column size if necessary, and set view->maxx. */
2802 entry = s->first_displayed_entry;
2803 ncommits = 0;
2804 view->maxx = 0;
2805 while (entry) {
2806 struct got_commit_object *c = entry->commit;
2807 char *author, *eol, *msg, *msg0;
2808 wchar_t *wauthor, *wmsg;
2809 int width;
2810 if (ncommits >= limit - 1)
2811 break;
2812 if (s->use_committer)
2813 author = strdup(got_object_commit_get_committer(c));
2814 else
2815 author = strdup(got_object_commit_get_author(c));
2816 if (author == NULL) {
2817 err = got_error_from_errno("strdup");
2818 goto done;
2820 err = format_author(&wauthor, &width, author, COLS,
2821 date_display_cols);
2822 if (author_cols < width)
2823 author_cols = width;
2824 free(wauthor);
2825 free(author);
2826 if (err)
2827 goto done;
2828 err = got_object_commit_get_logmsg(&msg0, c);
2829 if (err)
2830 goto done;
2831 msg = msg0;
2832 while (*msg == '\n')
2833 ++msg;
2834 if ((eol = strchr(msg, '\n')))
2835 *eol = '\0';
2836 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2837 date_display_cols + author_cols, 0);
2838 if (err)
2839 goto done;
2840 view->maxx = MAX(view->maxx, width);
2841 free(msg0);
2842 free(wmsg);
2843 ncommits++;
2844 entry = TAILQ_NEXT(entry, entry);
2847 entry = s->first_displayed_entry;
2848 s->last_displayed_entry = s->first_displayed_entry;
2849 ncommits = 0;
2850 while (entry) {
2851 if (ncommits >= limit - 1)
2852 break;
2853 if (ncommits == s->selected)
2854 wstandout(view->window);
2855 err = draw_commit(view, entry->commit, entry->id,
2856 date_display_cols, author_cols);
2857 if (ncommits == s->selected)
2858 wstandend(view->window);
2859 if (err)
2860 goto done;
2861 ncommits++;
2862 s->last_displayed_entry = entry;
2863 entry = TAILQ_NEXT(entry, entry);
2866 view_border(view);
2867 done:
2868 free(id_str);
2869 free(refs_str);
2870 free(ncommits_str);
2871 free(header);
2872 return err;
2875 static void
2876 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2878 struct commit_queue_entry *entry;
2879 int nscrolled = 0;
2881 entry = TAILQ_FIRST(&s->commits->head);
2882 if (s->first_displayed_entry == entry)
2883 return;
2885 entry = s->first_displayed_entry;
2886 while (entry && nscrolled < maxscroll) {
2887 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2888 if (entry) {
2889 s->first_displayed_entry = entry;
2890 nscrolled++;
2895 static const struct got_error *
2896 trigger_log_thread(struct tog_view *view, int wait)
2898 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2899 int errcode;
2901 if (!using_mock_io)
2902 halfdelay(1); /* fast refresh while loading commits */
2904 while (!ta->log_complete && !tog_thread_error &&
2905 (ta->commits_needed > 0 || ta->load_all)) {
2906 /* Wake the log thread. */
2907 errcode = pthread_cond_signal(&ta->need_commits);
2908 if (errcode)
2909 return got_error_set_errno(errcode,
2910 "pthread_cond_signal");
2913 * The mutex will be released while the view loop waits
2914 * in wgetch(), at which time the log thread will run.
2916 if (!wait)
2917 break;
2919 /* Display progress update in log view. */
2920 show_log_view(view);
2921 update_panels();
2922 doupdate();
2924 /* Wait right here while next commit is being loaded. */
2925 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2926 if (errcode)
2927 return got_error_set_errno(errcode,
2928 "pthread_cond_wait");
2930 /* Display progress update in log view. */
2931 show_log_view(view);
2932 update_panels();
2933 doupdate();
2936 return NULL;
2939 static const struct got_error *
2940 request_log_commits(struct tog_view *view)
2942 struct tog_log_view_state *state = &view->state.log;
2943 const struct got_error *err = NULL;
2945 if (state->thread_args.log_complete)
2946 return NULL;
2948 state->thread_args.commits_needed += view->nscrolled;
2949 err = trigger_log_thread(view, 1);
2950 view->nscrolled = 0;
2952 return err;
2955 static const struct got_error *
2956 log_scroll_down(struct tog_view *view, int maxscroll)
2958 struct tog_log_view_state *s = &view->state.log;
2959 const struct got_error *err = NULL;
2960 struct commit_queue_entry *pentry;
2961 int nscrolled = 0, ncommits_needed;
2963 if (s->last_displayed_entry == NULL)
2964 return NULL;
2966 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2967 if (s->commits->ncommits < ncommits_needed &&
2968 !s->thread_args.log_complete) {
2970 * Ask the log thread for required amount of commits.
2972 s->thread_args.commits_needed +=
2973 ncommits_needed - s->commits->ncommits;
2974 err = trigger_log_thread(view, 1);
2975 if (err)
2976 return err;
2979 do {
2980 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2981 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2982 break;
2984 s->last_displayed_entry = pentry ?
2985 pentry : s->last_displayed_entry;
2987 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2988 if (pentry == NULL)
2989 break;
2990 s->first_displayed_entry = pentry;
2991 } while (++nscrolled < maxscroll);
2993 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2994 view->nscrolled += nscrolled;
2995 else
2996 view->nscrolled = 0;
2998 return err;
3001 static const struct got_error *
3002 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3003 struct got_commit_object *commit, struct got_object_id *commit_id,
3004 struct tog_view *log_view, struct got_repository *repo)
3006 const struct got_error *err;
3007 struct got_object_qid *parent_id;
3008 struct tog_view *diff_view;
3010 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3011 if (diff_view == NULL)
3012 return got_error_from_errno("view_open");
3014 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3015 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3016 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3017 if (err == NULL)
3018 *new_view = diff_view;
3019 return err;
3022 static const struct got_error *
3023 tree_view_visit_subtree(struct tog_tree_view_state *s,
3024 struct got_tree_object *subtree)
3026 struct tog_parent_tree *parent;
3028 parent = calloc(1, sizeof(*parent));
3029 if (parent == NULL)
3030 return got_error_from_errno("calloc");
3032 parent->tree = s->tree;
3033 parent->first_displayed_entry = s->first_displayed_entry;
3034 parent->selected_entry = s->selected_entry;
3035 parent->selected = s->selected;
3036 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3037 s->tree = subtree;
3038 s->selected = 0;
3039 s->first_displayed_entry = NULL;
3040 return NULL;
3043 static const struct got_error *
3044 tree_view_walk_path(struct tog_tree_view_state *s,
3045 struct got_commit_object *commit, const char *path)
3047 const struct got_error *err = NULL;
3048 struct got_tree_object *tree = NULL;
3049 const char *p;
3050 char *slash, *subpath = NULL;
3052 /* Walk the path and open corresponding tree objects. */
3053 p = path;
3054 while (*p) {
3055 struct got_tree_entry *te;
3056 struct got_object_id *tree_id;
3057 char *te_name;
3059 while (p[0] == '/')
3060 p++;
3062 /* Ensure the correct subtree entry is selected. */
3063 slash = strchr(p, '/');
3064 if (slash == NULL)
3065 te_name = strdup(p);
3066 else
3067 te_name = strndup(p, slash - p);
3068 if (te_name == NULL) {
3069 err = got_error_from_errno("strndup");
3070 break;
3072 te = got_object_tree_find_entry(s->tree, te_name);
3073 if (te == NULL) {
3074 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3075 free(te_name);
3076 break;
3078 free(te_name);
3079 s->first_displayed_entry = s->selected_entry = te;
3081 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3082 break; /* jump to this file's entry */
3084 slash = strchr(p, '/');
3085 if (slash)
3086 subpath = strndup(path, slash - path);
3087 else
3088 subpath = strdup(path);
3089 if (subpath == NULL) {
3090 err = got_error_from_errno("strdup");
3091 break;
3094 err = got_object_id_by_path(&tree_id, s->repo, commit,
3095 subpath);
3096 if (err)
3097 break;
3099 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3100 free(tree_id);
3101 if (err)
3102 break;
3104 err = tree_view_visit_subtree(s, tree);
3105 if (err) {
3106 got_object_tree_close(tree);
3107 break;
3109 if (slash == NULL)
3110 break;
3111 free(subpath);
3112 subpath = NULL;
3113 p = slash;
3116 free(subpath);
3117 return err;
3120 static const struct got_error *
3121 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3122 struct commit_queue_entry *entry, const char *path,
3123 const char *head_ref_name, struct got_repository *repo)
3125 const struct got_error *err = NULL;
3126 struct tog_tree_view_state *s;
3127 struct tog_view *tree_view;
3129 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3130 if (tree_view == NULL)
3131 return got_error_from_errno("view_open");
3133 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3134 if (err)
3135 return err;
3136 s = &tree_view->state.tree;
3138 *new_view = tree_view;
3140 if (got_path_is_root_dir(path))
3141 return NULL;
3143 return tree_view_walk_path(s, entry->commit, path);
3146 static const struct got_error *
3147 block_signals_used_by_main_thread(void)
3149 sigset_t sigset;
3150 int errcode;
3152 if (sigemptyset(&sigset) == -1)
3153 return got_error_from_errno("sigemptyset");
3155 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3156 if (sigaddset(&sigset, SIGWINCH) == -1)
3157 return got_error_from_errno("sigaddset");
3158 if (sigaddset(&sigset, SIGCONT) == -1)
3159 return got_error_from_errno("sigaddset");
3160 if (sigaddset(&sigset, SIGINT) == -1)
3161 return got_error_from_errno("sigaddset");
3162 if (sigaddset(&sigset, SIGTERM) == -1)
3163 return got_error_from_errno("sigaddset");
3165 /* ncurses handles SIGTSTP */
3166 if (sigaddset(&sigset, SIGTSTP) == -1)
3167 return got_error_from_errno("sigaddset");
3169 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3170 if (errcode)
3171 return got_error_set_errno(errcode, "pthread_sigmask");
3173 return NULL;
3176 static void *
3177 log_thread(void *arg)
3179 const struct got_error *err = NULL;
3180 int errcode = 0;
3181 struct tog_log_thread_args *a = arg;
3182 int done = 0;
3185 * Sync startup with main thread such that we begin our
3186 * work once view_input() has released the mutex.
3188 errcode = pthread_mutex_lock(&tog_mutex);
3189 if (errcode) {
3190 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3191 return (void *)err;
3194 err = block_signals_used_by_main_thread();
3195 if (err) {
3196 pthread_mutex_unlock(&tog_mutex);
3197 goto done;
3200 while (!done && !err && !tog_fatal_signal_received()) {
3201 errcode = pthread_mutex_unlock(&tog_mutex);
3202 if (errcode) {
3203 err = got_error_set_errno(errcode,
3204 "pthread_mutex_unlock");
3205 goto done;
3207 err = queue_commits(a);
3208 if (err) {
3209 if (err->code != GOT_ERR_ITER_COMPLETED)
3210 goto done;
3211 err = NULL;
3212 done = 1;
3213 } else if (a->commits_needed > 0 && !a->load_all) {
3214 if (*a->limiting) {
3215 if (a->limit_match)
3216 a->commits_needed--;
3217 } else
3218 a->commits_needed--;
3221 errcode = pthread_mutex_lock(&tog_mutex);
3222 if (errcode) {
3223 err = got_error_set_errno(errcode,
3224 "pthread_mutex_lock");
3225 goto done;
3226 } else if (*a->quit)
3227 done = 1;
3228 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3229 *a->first_displayed_entry =
3230 TAILQ_FIRST(&a->limit_commits->head);
3231 *a->selected_entry = *a->first_displayed_entry;
3232 } else if (*a->first_displayed_entry == NULL) {
3233 *a->first_displayed_entry =
3234 TAILQ_FIRST(&a->real_commits->head);
3235 *a->selected_entry = *a->first_displayed_entry;
3238 errcode = pthread_cond_signal(&a->commit_loaded);
3239 if (errcode) {
3240 err = got_error_set_errno(errcode,
3241 "pthread_cond_signal");
3242 pthread_mutex_unlock(&tog_mutex);
3243 goto done;
3246 if (done)
3247 a->commits_needed = 0;
3248 else {
3249 if (a->commits_needed == 0 && !a->load_all) {
3250 errcode = pthread_cond_wait(&a->need_commits,
3251 &tog_mutex);
3252 if (errcode) {
3253 err = got_error_set_errno(errcode,
3254 "pthread_cond_wait");
3255 pthread_mutex_unlock(&tog_mutex);
3256 goto done;
3258 if (*a->quit)
3259 done = 1;
3263 a->log_complete = 1;
3264 errcode = pthread_mutex_unlock(&tog_mutex);
3265 if (errcode)
3266 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3267 done:
3268 if (err) {
3269 tog_thread_error = 1;
3270 pthread_cond_signal(&a->commit_loaded);
3272 return (void *)err;
3275 static const struct got_error *
3276 stop_log_thread(struct tog_log_view_state *s)
3278 const struct got_error *err = NULL, *thread_err = NULL;
3279 int errcode;
3281 if (s->thread) {
3282 s->quit = 1;
3283 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3284 if (errcode)
3285 return got_error_set_errno(errcode,
3286 "pthread_cond_signal");
3287 errcode = pthread_mutex_unlock(&tog_mutex);
3288 if (errcode)
3289 return got_error_set_errno(errcode,
3290 "pthread_mutex_unlock");
3291 errcode = pthread_join(s->thread, (void **)&thread_err);
3292 if (errcode)
3293 return got_error_set_errno(errcode, "pthread_join");
3294 errcode = pthread_mutex_lock(&tog_mutex);
3295 if (errcode)
3296 return got_error_set_errno(errcode,
3297 "pthread_mutex_lock");
3298 s->thread = NULL;
3301 if (s->thread_args.repo) {
3302 err = got_repo_close(s->thread_args.repo);
3303 s->thread_args.repo = NULL;
3306 if (s->thread_args.pack_fds) {
3307 const struct got_error *pack_err =
3308 got_repo_pack_fds_close(s->thread_args.pack_fds);
3309 if (err == NULL)
3310 err = pack_err;
3311 s->thread_args.pack_fds = NULL;
3314 if (s->thread_args.graph) {
3315 got_commit_graph_close(s->thread_args.graph);
3316 s->thread_args.graph = NULL;
3319 return err ? err : thread_err;
3322 static const struct got_error *
3323 close_log_view(struct tog_view *view)
3325 const struct got_error *err = NULL;
3326 struct tog_log_view_state *s = &view->state.log;
3327 int errcode;
3329 err = stop_log_thread(s);
3331 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3332 if (errcode && err == NULL)
3333 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3335 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3336 if (errcode && err == NULL)
3337 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3339 free_commits(&s->limit_commits);
3340 free_commits(&s->real_commits);
3341 free(s->in_repo_path);
3342 s->in_repo_path = NULL;
3343 free(s->start_id);
3344 s->start_id = NULL;
3345 free(s->head_ref_name);
3346 s->head_ref_name = NULL;
3347 return err;
3351 * We use two queues to implement the limit feature: first consists of
3352 * commits matching the current limit_regex; second is the real queue
3353 * of all known commits (real_commits). When the user starts limiting,
3354 * we swap queues such that all movement and displaying functionality
3355 * works with very slight change.
3357 static const struct got_error *
3358 limit_log_view(struct tog_view *view)
3360 struct tog_log_view_state *s = &view->state.log;
3361 struct commit_queue_entry *entry;
3362 struct tog_view *v = view;
3363 const struct got_error *err = NULL;
3364 char pattern[1024];
3365 int ret;
3367 if (view_is_hsplit_top(view))
3368 v = view->child;
3369 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3370 v = view->parent;
3372 /* Get the pattern */
3373 wmove(v->window, v->nlines - 1, 0);
3374 wclrtoeol(v->window);
3375 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3376 nodelay(v->window, FALSE);
3377 nocbreak();
3378 echo();
3379 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3380 cbreak();
3381 noecho();
3382 nodelay(v->window, TRUE);
3383 if (ret == ERR)
3384 return NULL;
3386 if (*pattern == '\0') {
3388 * Safety measure for the situation where the user
3389 * resets limit without previously limiting anything.
3391 if (!s->limit_view)
3392 return NULL;
3395 * User could have pressed Ctrl+L, which refreshed the
3396 * commit queues, it means we can't save previously
3397 * (before limit took place) displayed entries,
3398 * because they would point to already free'ed memory,
3399 * so we are forced to always select first entry of
3400 * the queue.
3402 s->commits = &s->real_commits;
3403 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3404 s->selected_entry = s->first_displayed_entry;
3405 s->selected = 0;
3406 s->limit_view = 0;
3408 return NULL;
3411 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3412 return NULL;
3414 s->limit_view = 1;
3416 /* Clear the screen while loading limit view */
3417 s->first_displayed_entry = NULL;
3418 s->last_displayed_entry = NULL;
3419 s->selected_entry = NULL;
3420 s->commits = &s->limit_commits;
3422 /* Prepare limit queue for new search */
3423 free_commits(&s->limit_commits);
3424 s->limit_commits.ncommits = 0;
3426 /* First process commits, which are in queue already */
3427 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3428 int have_match = 0;
3430 err = match_commit(&have_match, entry->id,
3431 entry->commit, &s->limit_regex);
3432 if (err)
3433 return err;
3435 if (have_match) {
3436 struct commit_queue_entry *matched;
3438 matched = alloc_commit_queue_entry(entry->commit,
3439 entry->id);
3440 if (matched == NULL) {
3441 err = got_error_from_errno(
3442 "alloc_commit_queue_entry");
3443 break;
3445 matched->commit = entry->commit;
3446 got_object_commit_retain(entry->commit);
3448 matched->idx = s->limit_commits.ncommits;
3449 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3450 matched, entry);
3451 s->limit_commits.ncommits++;
3455 /* Second process all the commits, until we fill the screen */
3456 if (s->limit_commits.ncommits < view->nlines - 1 &&
3457 !s->thread_args.log_complete) {
3458 s->thread_args.commits_needed +=
3459 view->nlines - s->limit_commits.ncommits - 1;
3460 err = trigger_log_thread(view, 1);
3461 if (err)
3462 return err;
3465 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3466 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3467 s->selected = 0;
3469 return NULL;
3472 static const struct got_error *
3473 search_start_log_view(struct tog_view *view)
3475 struct tog_log_view_state *s = &view->state.log;
3477 s->matched_entry = NULL;
3478 s->search_entry = NULL;
3479 return NULL;
3482 static const struct got_error *
3483 search_next_log_view(struct tog_view *view)
3485 const struct got_error *err = NULL;
3486 struct tog_log_view_state *s = &view->state.log;
3487 struct commit_queue_entry *entry;
3489 /* Display progress update in log view. */
3490 show_log_view(view);
3491 update_panels();
3492 doupdate();
3494 if (s->search_entry) {
3495 int errcode, ch;
3496 errcode = pthread_mutex_unlock(&tog_mutex);
3497 if (errcode)
3498 return got_error_set_errno(errcode,
3499 "pthread_mutex_unlock");
3500 ch = wgetch(view->window);
3501 errcode = pthread_mutex_lock(&tog_mutex);
3502 if (errcode)
3503 return got_error_set_errno(errcode,
3504 "pthread_mutex_lock");
3505 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3506 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3507 return NULL;
3509 if (view->searching == TOG_SEARCH_FORWARD)
3510 entry = TAILQ_NEXT(s->search_entry, entry);
3511 else
3512 entry = TAILQ_PREV(s->search_entry,
3513 commit_queue_head, entry);
3514 } else if (s->matched_entry) {
3516 * If the user has moved the cursor after we hit a match,
3517 * the position from where we should continue searching
3518 * might have changed.
3520 if (view->searching == TOG_SEARCH_FORWARD)
3521 entry = TAILQ_NEXT(s->selected_entry, entry);
3522 else
3523 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3524 entry);
3525 } else {
3526 entry = s->selected_entry;
3529 while (1) {
3530 int have_match = 0;
3532 if (entry == NULL) {
3533 if (s->thread_args.log_complete ||
3534 view->searching == TOG_SEARCH_BACKWARD) {
3535 view->search_next_done =
3536 (s->matched_entry == NULL ?
3537 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3538 s->search_entry = NULL;
3539 return NULL;
3542 * Poke the log thread for more commits and return,
3543 * allowing the main loop to make progress. Search
3544 * will resume at s->search_entry once we come back.
3546 s->thread_args.commits_needed++;
3547 return trigger_log_thread(view, 0);
3550 err = match_commit(&have_match, entry->id, entry->commit,
3551 &view->regex);
3552 if (err)
3553 break;
3554 if (have_match) {
3555 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3556 s->matched_entry = entry;
3557 break;
3560 s->search_entry = entry;
3561 if (view->searching == TOG_SEARCH_FORWARD)
3562 entry = TAILQ_NEXT(entry, entry);
3563 else
3564 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3567 if (s->matched_entry) {
3568 int cur = s->selected_entry->idx;
3569 while (cur < s->matched_entry->idx) {
3570 err = input_log_view(NULL, view, KEY_DOWN);
3571 if (err)
3572 return err;
3573 cur++;
3575 while (cur > s->matched_entry->idx) {
3576 err = input_log_view(NULL, view, KEY_UP);
3577 if (err)
3578 return err;
3579 cur--;
3583 s->search_entry = NULL;
3585 return NULL;
3588 static const struct got_error *
3589 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3590 struct got_repository *repo, const char *head_ref_name,
3591 const char *in_repo_path, int log_branches)
3593 const struct got_error *err = NULL;
3594 struct tog_log_view_state *s = &view->state.log;
3595 struct got_repository *thread_repo = NULL;
3596 struct got_commit_graph *thread_graph = NULL;
3597 int errcode;
3599 if (in_repo_path != s->in_repo_path) {
3600 free(s->in_repo_path);
3601 s->in_repo_path = strdup(in_repo_path);
3602 if (s->in_repo_path == NULL) {
3603 err = got_error_from_errno("strdup");
3604 goto done;
3608 /* The commit queue only contains commits being displayed. */
3609 TAILQ_INIT(&s->real_commits.head);
3610 s->real_commits.ncommits = 0;
3611 s->commits = &s->real_commits;
3613 TAILQ_INIT(&s->limit_commits.head);
3614 s->limit_view = 0;
3615 s->limit_commits.ncommits = 0;
3617 s->repo = repo;
3618 if (head_ref_name) {
3619 s->head_ref_name = strdup(head_ref_name);
3620 if (s->head_ref_name == NULL) {
3621 err = got_error_from_errno("strdup");
3622 goto done;
3625 s->start_id = got_object_id_dup(start_id);
3626 if (s->start_id == NULL) {
3627 err = got_error_from_errno("got_object_id_dup");
3628 goto done;
3630 s->log_branches = log_branches;
3631 s->use_committer = 1;
3633 STAILQ_INIT(&s->colors);
3634 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3635 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3636 get_color_value("TOG_COLOR_COMMIT"));
3637 if (err)
3638 goto done;
3639 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3640 get_color_value("TOG_COLOR_AUTHOR"));
3641 if (err) {
3642 free_colors(&s->colors);
3643 goto done;
3645 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3646 get_color_value("TOG_COLOR_DATE"));
3647 if (err) {
3648 free_colors(&s->colors);
3649 goto done;
3653 view->show = show_log_view;
3654 view->input = input_log_view;
3655 view->resize = resize_log_view;
3656 view->close = close_log_view;
3657 view->search_start = search_start_log_view;
3658 view->search_next = search_next_log_view;
3660 if (s->thread_args.pack_fds == NULL) {
3661 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3662 if (err)
3663 goto done;
3665 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3666 s->thread_args.pack_fds);
3667 if (err)
3668 goto done;
3669 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3670 !s->log_branches);
3671 if (err)
3672 goto done;
3673 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3674 s->repo, NULL, NULL);
3675 if (err)
3676 goto done;
3678 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3679 if (errcode) {
3680 err = got_error_set_errno(errcode, "pthread_cond_init");
3681 goto done;
3683 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3684 if (errcode) {
3685 err = got_error_set_errno(errcode, "pthread_cond_init");
3686 goto done;
3689 s->thread_args.commits_needed = view->nlines;
3690 s->thread_args.graph = thread_graph;
3691 s->thread_args.real_commits = &s->real_commits;
3692 s->thread_args.limit_commits = &s->limit_commits;
3693 s->thread_args.in_repo_path = s->in_repo_path;
3694 s->thread_args.start_id = s->start_id;
3695 s->thread_args.repo = thread_repo;
3696 s->thread_args.log_complete = 0;
3697 s->thread_args.quit = &s->quit;
3698 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3699 s->thread_args.selected_entry = &s->selected_entry;
3700 s->thread_args.searching = &view->searching;
3701 s->thread_args.search_next_done = &view->search_next_done;
3702 s->thread_args.regex = &view->regex;
3703 s->thread_args.limiting = &s->limit_view;
3704 s->thread_args.limit_regex = &s->limit_regex;
3705 s->thread_args.limit_commits = &s->limit_commits;
3706 done:
3707 if (err) {
3708 if (view->close == NULL)
3709 close_log_view(view);
3710 view_close(view);
3712 return err;
3715 static const struct got_error *
3716 show_log_view(struct tog_view *view)
3718 const struct got_error *err;
3719 struct tog_log_view_state *s = &view->state.log;
3721 if (s->thread == NULL) {
3722 int errcode = pthread_create(&s->thread, NULL, log_thread,
3723 &s->thread_args);
3724 if (errcode)
3725 return got_error_set_errno(errcode, "pthread_create");
3726 if (s->thread_args.commits_needed > 0) {
3727 err = trigger_log_thread(view, 1);
3728 if (err)
3729 return err;
3733 return draw_commits(view);
3736 static void
3737 log_move_cursor_up(struct tog_view *view, int page, int home)
3739 struct tog_log_view_state *s = &view->state.log;
3741 if (s->first_displayed_entry == NULL)
3742 return;
3743 if (s->selected_entry->idx == 0)
3744 view->count = 0;
3746 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3747 || home)
3748 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3750 if (!page && !home && s->selected > 0)
3751 --s->selected;
3752 else
3753 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3755 select_commit(s);
3756 return;
3759 static const struct got_error *
3760 log_move_cursor_down(struct tog_view *view, int page)
3762 struct tog_log_view_state *s = &view->state.log;
3763 const struct got_error *err = NULL;
3764 int eos = view->nlines - 2;
3766 if (s->first_displayed_entry == NULL)
3767 return NULL;
3769 if (s->thread_args.log_complete &&
3770 s->selected_entry->idx >= s->commits->ncommits - 1)
3771 return NULL;
3773 if (view_is_hsplit_top(view))
3774 --eos; /* border consumes the last line */
3776 if (!page) {
3777 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3778 ++s->selected;
3779 else
3780 err = log_scroll_down(view, 1);
3781 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3782 struct commit_queue_entry *entry;
3783 int n;
3785 s->selected = 0;
3786 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3787 s->last_displayed_entry = entry;
3788 for (n = 0; n <= eos; n++) {
3789 if (entry == NULL)
3790 break;
3791 s->first_displayed_entry = entry;
3792 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3794 if (n > 0)
3795 s->selected = n - 1;
3796 } else {
3797 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3798 s->thread_args.log_complete)
3799 s->selected += MIN(page,
3800 s->commits->ncommits - s->selected_entry->idx - 1);
3801 else
3802 err = log_scroll_down(view, page);
3804 if (err)
3805 return err;
3808 * We might necessarily overshoot in horizontal
3809 * splits; if so, select the last displayed commit.
3811 if (s->first_displayed_entry && s->last_displayed_entry) {
3812 s->selected = MIN(s->selected,
3813 s->last_displayed_entry->idx -
3814 s->first_displayed_entry->idx);
3817 select_commit(s);
3819 if (s->thread_args.log_complete &&
3820 s->selected_entry->idx == s->commits->ncommits - 1)
3821 view->count = 0;
3823 return NULL;
3826 static void
3827 view_get_split(struct tog_view *view, int *y, int *x)
3829 *x = 0;
3830 *y = 0;
3832 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3833 if (view->child && view->child->resized_y)
3834 *y = view->child->resized_y;
3835 else if (view->resized_y)
3836 *y = view->resized_y;
3837 else
3838 *y = view_split_begin_y(view->lines);
3839 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3840 if (view->child && view->child->resized_x)
3841 *x = view->child->resized_x;
3842 else if (view->resized_x)
3843 *x = view->resized_x;
3844 else
3845 *x = view_split_begin_x(view->begin_x);
3849 /* Split view horizontally at y and offset view->state->selected line. */
3850 static const struct got_error *
3851 view_init_hsplit(struct tog_view *view, int y)
3853 const struct got_error *err = NULL;
3855 view->nlines = y;
3856 view->ncols = COLS;
3857 err = view_resize(view);
3858 if (err)
3859 return err;
3861 err = offset_selection_down(view);
3863 return err;
3866 static const struct got_error *
3867 log_goto_line(struct tog_view *view, int nlines)
3869 const struct got_error *err = NULL;
3870 struct tog_log_view_state *s = &view->state.log;
3871 int g, idx = s->selected_entry->idx;
3873 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3874 return NULL;
3876 g = view->gline;
3877 view->gline = 0;
3879 if (g >= s->first_displayed_entry->idx + 1 &&
3880 g <= s->last_displayed_entry->idx + 1 &&
3881 g - s->first_displayed_entry->idx - 1 < nlines) {
3882 s->selected = g - s->first_displayed_entry->idx - 1;
3883 select_commit(s);
3884 return NULL;
3887 if (idx + 1 < g) {
3888 err = log_move_cursor_down(view, g - idx - 1);
3889 if (!err && g > s->selected_entry->idx + 1)
3890 err = log_move_cursor_down(view,
3891 g - s->first_displayed_entry->idx - 1);
3892 if (err)
3893 return err;
3894 } else if (idx + 1 > g)
3895 log_move_cursor_up(view, idx - g + 1, 0);
3897 if (g < nlines && s->first_displayed_entry->idx == 0)
3898 s->selected = g - 1;
3900 select_commit(s);
3901 return NULL;
3905 static void
3906 horizontal_scroll_input(struct tog_view *view, int ch)
3909 switch (ch) {
3910 case KEY_LEFT:
3911 case 'h':
3912 view->x -= MIN(view->x, 2);
3913 if (view->x <= 0)
3914 view->count = 0;
3915 break;
3916 case KEY_RIGHT:
3917 case 'l':
3918 if (view->x + view->ncols / 2 < view->maxx)
3919 view->x += 2;
3920 else
3921 view->count = 0;
3922 break;
3923 case '0':
3924 view->x = 0;
3925 break;
3926 case '$':
3927 view->x = MAX(view->maxx - view->ncols / 2, 0);
3928 view->count = 0;
3929 break;
3930 default:
3931 break;
3935 static const struct got_error *
3936 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3938 const struct got_error *err = NULL;
3939 struct tog_log_view_state *s = &view->state.log;
3940 int eos, nscroll;
3942 if (s->thread_args.load_all) {
3943 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3944 s->thread_args.load_all = 0;
3945 else if (s->thread_args.log_complete) {
3946 err = log_move_cursor_down(view, s->commits->ncommits);
3947 s->thread_args.load_all = 0;
3949 if (err)
3950 return err;
3953 eos = nscroll = view->nlines - 1;
3954 if (view_is_hsplit_top(view))
3955 --eos; /* border */
3957 if (view->gline)
3958 return log_goto_line(view, eos);
3960 switch (ch) {
3961 case '&':
3962 err = limit_log_view(view);
3963 break;
3964 case 'q':
3965 s->quit = 1;
3966 break;
3967 case '0':
3968 case '$':
3969 case KEY_RIGHT:
3970 case 'l':
3971 case KEY_LEFT:
3972 case 'h':
3973 horizontal_scroll_input(view, ch);
3974 break;
3975 case 'k':
3976 case KEY_UP:
3977 case '<':
3978 case ',':
3979 case CTRL('p'):
3980 log_move_cursor_up(view, 0, 0);
3981 break;
3982 case 'g':
3983 case '=':
3984 case KEY_HOME:
3985 log_move_cursor_up(view, 0, 1);
3986 view->count = 0;
3987 break;
3988 case CTRL('u'):
3989 case 'u':
3990 nscroll /= 2;
3991 /* FALL THROUGH */
3992 case KEY_PPAGE:
3993 case CTRL('b'):
3994 case 'b':
3995 log_move_cursor_up(view, nscroll, 0);
3996 break;
3997 case 'j':
3998 case KEY_DOWN:
3999 case '>':
4000 case '.':
4001 case CTRL('n'):
4002 err = log_move_cursor_down(view, 0);
4003 break;
4004 case '@':
4005 s->use_committer = !s->use_committer;
4006 view->action = s->use_committer ?
4007 "show committer" : "show commit author";
4008 break;
4009 case 'G':
4010 case '*':
4011 case KEY_END: {
4012 /* We don't know yet how many commits, so we're forced to
4013 * traverse them all. */
4014 view->count = 0;
4015 s->thread_args.load_all = 1;
4016 if (!s->thread_args.log_complete)
4017 return trigger_log_thread(view, 0);
4018 err = log_move_cursor_down(view, s->commits->ncommits);
4019 s->thread_args.load_all = 0;
4020 break;
4022 case CTRL('d'):
4023 case 'd':
4024 nscroll /= 2;
4025 /* FALL THROUGH */
4026 case KEY_NPAGE:
4027 case CTRL('f'):
4028 case 'f':
4029 case ' ':
4030 err = log_move_cursor_down(view, nscroll);
4031 break;
4032 case KEY_RESIZE:
4033 if (s->selected > view->nlines - 2)
4034 s->selected = view->nlines - 2;
4035 if (s->selected > s->commits->ncommits - 1)
4036 s->selected = s->commits->ncommits - 1;
4037 select_commit(s);
4038 if (s->commits->ncommits < view->nlines - 1 &&
4039 !s->thread_args.log_complete) {
4040 s->thread_args.commits_needed += (view->nlines - 1) -
4041 s->commits->ncommits;
4042 err = trigger_log_thread(view, 1);
4044 break;
4045 case KEY_ENTER:
4046 case '\r':
4047 view->count = 0;
4048 if (s->selected_entry == NULL)
4049 break;
4050 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4051 break;
4052 case 'T':
4053 view->count = 0;
4054 if (s->selected_entry == NULL)
4055 break;
4056 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4057 break;
4058 case KEY_BACKSPACE:
4059 case CTRL('l'):
4060 case 'B':
4061 view->count = 0;
4062 if (ch == KEY_BACKSPACE &&
4063 got_path_is_root_dir(s->in_repo_path))
4064 break;
4065 err = stop_log_thread(s);
4066 if (err)
4067 return err;
4068 if (ch == KEY_BACKSPACE) {
4069 char *parent_path;
4070 err = got_path_dirname(&parent_path, s->in_repo_path);
4071 if (err)
4072 return err;
4073 free(s->in_repo_path);
4074 s->in_repo_path = parent_path;
4075 s->thread_args.in_repo_path = s->in_repo_path;
4076 } else if (ch == CTRL('l')) {
4077 struct got_object_id *start_id;
4078 err = got_repo_match_object_id(&start_id, NULL,
4079 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4080 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4081 if (err) {
4082 if (s->head_ref_name == NULL ||
4083 err->code != GOT_ERR_NOT_REF)
4084 return err;
4085 /* Try to cope with deleted references. */
4086 free(s->head_ref_name);
4087 s->head_ref_name = NULL;
4088 err = got_repo_match_object_id(&start_id,
4089 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4090 &tog_refs, s->repo);
4091 if (err)
4092 return err;
4094 free(s->start_id);
4095 s->start_id = start_id;
4096 s->thread_args.start_id = s->start_id;
4097 } else /* 'B' */
4098 s->log_branches = !s->log_branches;
4100 if (s->thread_args.pack_fds == NULL) {
4101 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4102 if (err)
4103 return err;
4105 err = got_repo_open(&s->thread_args.repo,
4106 got_repo_get_path(s->repo), NULL,
4107 s->thread_args.pack_fds);
4108 if (err)
4109 return err;
4110 tog_free_refs();
4111 err = tog_load_refs(s->repo, 0);
4112 if (err)
4113 return err;
4114 err = got_commit_graph_open(&s->thread_args.graph,
4115 s->in_repo_path, !s->log_branches);
4116 if (err)
4117 return err;
4118 err = got_commit_graph_iter_start(s->thread_args.graph,
4119 s->start_id, s->repo, NULL, NULL);
4120 if (err)
4121 return err;
4122 free_commits(&s->real_commits);
4123 free_commits(&s->limit_commits);
4124 s->first_displayed_entry = NULL;
4125 s->last_displayed_entry = NULL;
4126 s->selected_entry = NULL;
4127 s->selected = 0;
4128 s->thread_args.log_complete = 0;
4129 s->quit = 0;
4130 s->thread_args.commits_needed = view->lines;
4131 s->matched_entry = NULL;
4132 s->search_entry = NULL;
4133 view->offset = 0;
4134 break;
4135 case 'R':
4136 view->count = 0;
4137 err = view_request_new(new_view, view, TOG_VIEW_REF);
4138 break;
4139 default:
4140 view->count = 0;
4141 break;
4144 return err;
4147 static const struct got_error *
4148 apply_unveil(const char *repo_path, const char *worktree_path)
4150 const struct got_error *error;
4152 #ifdef PROFILE
4153 if (unveil("gmon.out", "rwc") != 0)
4154 return got_error_from_errno2("unveil", "gmon.out");
4155 #endif
4156 if (repo_path && unveil(repo_path, "r") != 0)
4157 return got_error_from_errno2("unveil", repo_path);
4159 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4160 return got_error_from_errno2("unveil", worktree_path);
4162 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4163 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4165 error = got_privsep_unveil_exec_helpers();
4166 if (error != NULL)
4167 return error;
4169 if (unveil(NULL, NULL) != 0)
4170 return got_error_from_errno("unveil");
4172 return NULL;
4175 static const struct got_error *
4176 init_mock_term(const char *test_script_path)
4178 const struct got_error *err = NULL;
4180 if (test_script_path == NULL || *test_script_path == '\0')
4181 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4183 tog_io.f = fopen(test_script_path, "re");
4184 if (tog_io.f == NULL) {
4185 err = got_error_from_errno_fmt("fopen: %s",
4186 test_script_path);
4187 goto done;
4190 /* test mode, we don't want any output */
4191 tog_io.cout = fopen("/dev/null", "w+");
4192 if (tog_io.cout == NULL) {
4193 err = got_error_from_errno("fopen: /dev/null");
4194 goto done;
4197 tog_io.cin = fopen("/dev/tty", "r+");
4198 if (tog_io.cin == NULL) {
4199 err = got_error_from_errno("fopen: /dev/tty");
4200 goto done;
4203 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4204 err = got_error_from_errno("fseeko");
4205 goto done;
4208 /* use local TERM so we test in different environments */
4209 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4210 err = got_error_msg(GOT_ERR_IO,
4211 "newterm: failed to initialise curses");
4213 using_mock_io = 1;
4215 done:
4216 if (err)
4217 tog_io_close();
4218 return err;
4221 static void
4222 init_curses(void)
4225 * Override default signal handlers before starting ncurses.
4226 * This should prevent ncurses from installing its own
4227 * broken cleanup() signal handler.
4229 signal(SIGWINCH, tog_sigwinch);
4230 signal(SIGPIPE, tog_sigpipe);
4231 signal(SIGCONT, tog_sigcont);
4232 signal(SIGINT, tog_sigint);
4233 signal(SIGTERM, tog_sigterm);
4235 if (using_mock_io) /* In test mode we use a fake terminal */
4236 return;
4238 initscr();
4240 cbreak();
4241 halfdelay(1); /* Fast refresh while initial view is loading. */
4242 noecho();
4243 nonl();
4244 intrflush(stdscr, FALSE);
4245 keypad(stdscr, TRUE);
4246 curs_set(0);
4247 if (getenv("TOG_COLORS") != NULL) {
4248 start_color();
4249 use_default_colors();
4252 return;
4255 static const struct got_error *
4256 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4257 struct got_repository *repo, struct got_worktree *worktree)
4259 const struct got_error *err = NULL;
4261 if (argc == 0) {
4262 *in_repo_path = strdup("/");
4263 if (*in_repo_path == NULL)
4264 return got_error_from_errno("strdup");
4265 return NULL;
4268 if (worktree) {
4269 const char *prefix = got_worktree_get_path_prefix(worktree);
4270 char *p;
4272 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4273 if (err)
4274 return err;
4275 if (asprintf(in_repo_path, "%s%s%s", prefix,
4276 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4277 p) == -1) {
4278 err = got_error_from_errno("asprintf");
4279 *in_repo_path = NULL;
4281 free(p);
4282 } else
4283 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4285 return err;
4288 static const struct got_error *
4289 cmd_log(int argc, char *argv[])
4291 const struct got_error *error;
4292 struct got_repository *repo = NULL;
4293 struct got_worktree *worktree = NULL;
4294 struct got_object_id *start_id = NULL;
4295 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4296 char *start_commit = NULL, *label = NULL;
4297 struct got_reference *ref = NULL;
4298 const char *head_ref_name = NULL;
4299 int ch, log_branches = 0;
4300 struct tog_view *view;
4301 int *pack_fds = NULL;
4303 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4304 switch (ch) {
4305 case 'b':
4306 log_branches = 1;
4307 break;
4308 case 'c':
4309 start_commit = optarg;
4310 break;
4311 case 'r':
4312 repo_path = realpath(optarg, NULL);
4313 if (repo_path == NULL)
4314 return got_error_from_errno2("realpath",
4315 optarg);
4316 break;
4317 default:
4318 usage_log();
4319 /* NOTREACHED */
4323 argc -= optind;
4324 argv += optind;
4326 if (argc > 1)
4327 usage_log();
4329 error = got_repo_pack_fds_open(&pack_fds);
4330 if (error != NULL)
4331 goto done;
4333 if (repo_path == NULL) {
4334 cwd = getcwd(NULL, 0);
4335 if (cwd == NULL)
4336 return got_error_from_errno("getcwd");
4337 error = got_worktree_open(&worktree, cwd);
4338 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4339 goto done;
4340 if (worktree)
4341 repo_path =
4342 strdup(got_worktree_get_repo_path(worktree));
4343 else
4344 repo_path = strdup(cwd);
4345 if (repo_path == NULL) {
4346 error = got_error_from_errno("strdup");
4347 goto done;
4351 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4352 if (error != NULL)
4353 goto done;
4355 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4356 repo, worktree);
4357 if (error)
4358 goto done;
4360 init_curses();
4362 error = apply_unveil(got_repo_get_path(repo),
4363 worktree ? got_worktree_get_root_path(worktree) : NULL);
4364 if (error)
4365 goto done;
4367 /* already loaded by tog_log_with_path()? */
4368 if (TAILQ_EMPTY(&tog_refs)) {
4369 error = tog_load_refs(repo, 0);
4370 if (error)
4371 goto done;
4374 if (start_commit == NULL) {
4375 error = got_repo_match_object_id(&start_id, &label,
4376 worktree ? got_worktree_get_head_ref_name(worktree) :
4377 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4378 if (error)
4379 goto done;
4380 head_ref_name = label;
4381 } else {
4382 error = got_ref_open(&ref, repo, start_commit, 0);
4383 if (error == NULL)
4384 head_ref_name = got_ref_get_name(ref);
4385 else if (error->code != GOT_ERR_NOT_REF)
4386 goto done;
4387 error = got_repo_match_object_id(&start_id, NULL,
4388 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4389 if (error)
4390 goto done;
4393 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4394 if (view == NULL) {
4395 error = got_error_from_errno("view_open");
4396 goto done;
4398 error = open_log_view(view, start_id, repo, head_ref_name,
4399 in_repo_path, log_branches);
4400 if (error)
4401 goto done;
4402 if (worktree) {
4403 /* Release work tree lock. */
4404 got_worktree_close(worktree);
4405 worktree = NULL;
4407 error = view_loop(view);
4408 done:
4409 free(in_repo_path);
4410 free(repo_path);
4411 free(cwd);
4412 free(start_id);
4413 free(label);
4414 if (ref)
4415 got_ref_close(ref);
4416 if (repo) {
4417 const struct got_error *close_err = got_repo_close(repo);
4418 if (error == NULL)
4419 error = close_err;
4421 if (worktree)
4422 got_worktree_close(worktree);
4423 if (pack_fds) {
4424 const struct got_error *pack_err =
4425 got_repo_pack_fds_close(pack_fds);
4426 if (error == NULL)
4427 error = pack_err;
4429 tog_free_refs();
4430 return error;
4433 __dead static void
4434 usage_diff(void)
4436 endwin();
4437 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4438 "object1 object2\n", getprogname());
4439 exit(1);
4442 static int
4443 match_line(const char *line, regex_t *regex, size_t nmatch,
4444 regmatch_t *regmatch)
4446 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4449 static struct tog_color *
4450 match_color(struct tog_colors *colors, const char *line)
4452 struct tog_color *tc = NULL;
4454 STAILQ_FOREACH(tc, colors, entry) {
4455 if (match_line(line, &tc->regex, 0, NULL))
4456 return tc;
4459 return NULL;
4462 static const struct got_error *
4463 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4464 WINDOW *window, int skipcol, regmatch_t *regmatch)
4466 const struct got_error *err = NULL;
4467 char *exstr = NULL;
4468 wchar_t *wline = NULL;
4469 int rme, rms, n, width, scrollx;
4470 int width0 = 0, width1 = 0, width2 = 0;
4471 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4473 *wtotal = 0;
4475 rms = regmatch->rm_so;
4476 rme = regmatch->rm_eo;
4478 err = expand_tab(&exstr, line);
4479 if (err)
4480 return err;
4482 /* Split the line into 3 segments, according to match offsets. */
4483 seg0 = strndup(exstr, rms);
4484 if (seg0 == NULL) {
4485 err = got_error_from_errno("strndup");
4486 goto done;
4488 seg1 = strndup(exstr + rms, rme - rms);
4489 if (seg1 == NULL) {
4490 err = got_error_from_errno("strndup");
4491 goto done;
4493 seg2 = strdup(exstr + rme);
4494 if (seg2 == NULL) {
4495 err = got_error_from_errno("strndup");
4496 goto done;
4499 /* draw up to matched token if we haven't scrolled past it */
4500 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4501 col_tab_align, 1);
4502 if (err)
4503 goto done;
4504 n = MAX(width0 - skipcol, 0);
4505 if (n) {
4506 free(wline);
4507 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4508 wlimit, col_tab_align, 1);
4509 if (err)
4510 goto done;
4511 waddwstr(window, &wline[scrollx]);
4512 wlimit -= width;
4513 *wtotal += width;
4516 if (wlimit > 0) {
4517 int i = 0, w = 0;
4518 size_t wlen;
4520 free(wline);
4521 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4522 col_tab_align, 1);
4523 if (err)
4524 goto done;
4525 wlen = wcslen(wline);
4526 while (i < wlen) {
4527 width = wcwidth(wline[i]);
4528 if (width == -1) {
4529 /* should not happen, tabs are expanded */
4530 err = got_error(GOT_ERR_RANGE);
4531 goto done;
4533 if (width0 + w + width > skipcol)
4534 break;
4535 w += width;
4536 i++;
4538 /* draw (visible part of) matched token (if scrolled into it) */
4539 if (width1 - w > 0) {
4540 wattron(window, A_STANDOUT);
4541 waddwstr(window, &wline[i]);
4542 wattroff(window, A_STANDOUT);
4543 wlimit -= (width1 - w);
4544 *wtotal += (width1 - w);
4548 if (wlimit > 0) { /* draw rest of line */
4549 free(wline);
4550 if (skipcol > width0 + width1) {
4551 err = format_line(&wline, &width2, &scrollx, seg2,
4552 skipcol - (width0 + width1), wlimit,
4553 col_tab_align, 1);
4554 if (err)
4555 goto done;
4556 waddwstr(window, &wline[scrollx]);
4557 } else {
4558 err = format_line(&wline, &width2, NULL, seg2, 0,
4559 wlimit, col_tab_align, 1);
4560 if (err)
4561 goto done;
4562 waddwstr(window, wline);
4564 *wtotal += width2;
4566 done:
4567 free(wline);
4568 free(exstr);
4569 free(seg0);
4570 free(seg1);
4571 free(seg2);
4572 return err;
4575 static int
4576 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4578 FILE *f = NULL;
4579 int *eof, *first, *selected;
4581 if (view->type == TOG_VIEW_DIFF) {
4582 struct tog_diff_view_state *s = &view->state.diff;
4584 first = &s->first_displayed_line;
4585 selected = first;
4586 eof = &s->eof;
4587 f = s->f;
4588 } else if (view->type == TOG_VIEW_HELP) {
4589 struct tog_help_view_state *s = &view->state.help;
4591 first = &s->first_displayed_line;
4592 selected = first;
4593 eof = &s->eof;
4594 f = s->f;
4595 } else if (view->type == TOG_VIEW_BLAME) {
4596 struct tog_blame_view_state *s = &view->state.blame;
4598 first = &s->first_displayed_line;
4599 selected = &s->selected_line;
4600 eof = &s->eof;
4601 f = s->blame.f;
4602 } else
4603 return 0;
4605 /* Center gline in the middle of the page like vi(1). */
4606 if (*lineno < view->gline - (view->nlines - 3) / 2)
4607 return 0;
4608 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4609 rewind(f);
4610 *eof = 0;
4611 *first = 1;
4612 *lineno = 0;
4613 *nprinted = 0;
4614 return 0;
4617 *selected = view->gline <= (view->nlines - 3) / 2 ?
4618 view->gline : (view->nlines - 3) / 2 + 1;
4619 view->gline = 0;
4621 return 1;
4624 static const struct got_error *
4625 draw_file(struct tog_view *view, const char *header)
4627 struct tog_diff_view_state *s = &view->state.diff;
4628 regmatch_t *regmatch = &view->regmatch;
4629 const struct got_error *err;
4630 int nprinted = 0;
4631 char *line;
4632 size_t linesize = 0;
4633 ssize_t linelen;
4634 wchar_t *wline;
4635 int width;
4636 int max_lines = view->nlines;
4637 int nlines = s->nlines;
4638 off_t line_offset;
4640 s->lineno = s->first_displayed_line - 1;
4641 line_offset = s->lines[s->first_displayed_line - 1].offset;
4642 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4643 return got_error_from_errno("fseek");
4645 werase(view->window);
4647 if (view->gline > s->nlines - 1)
4648 view->gline = s->nlines - 1;
4650 if (header) {
4651 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4652 1 : view->gline - (view->nlines - 3) / 2 :
4653 s->lineno + s->selected_line;
4655 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4656 return got_error_from_errno("asprintf");
4657 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4658 0, 0);
4659 free(line);
4660 if (err)
4661 return err;
4663 if (view_needs_focus_indication(view))
4664 wstandout(view->window);
4665 waddwstr(view->window, wline);
4666 free(wline);
4667 wline = NULL;
4668 while (width++ < view->ncols)
4669 waddch(view->window, ' ');
4670 if (view_needs_focus_indication(view))
4671 wstandend(view->window);
4673 if (max_lines <= 1)
4674 return NULL;
4675 max_lines--;
4678 s->eof = 0;
4679 view->maxx = 0;
4680 line = NULL;
4681 while (max_lines > 0 && nprinted < max_lines) {
4682 enum got_diff_line_type linetype;
4683 attr_t attr = 0;
4685 linelen = getline(&line, &linesize, s->f);
4686 if (linelen == -1) {
4687 if (feof(s->f)) {
4688 s->eof = 1;
4689 break;
4691 free(line);
4692 return got_ferror(s->f, GOT_ERR_IO);
4695 if (++s->lineno < s->first_displayed_line)
4696 continue;
4697 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4698 continue;
4699 if (s->lineno == view->hiline)
4700 attr = A_STANDOUT;
4702 /* Set view->maxx based on full line length. */
4703 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4704 view->x ? 1 : 0);
4705 if (err) {
4706 free(line);
4707 return err;
4709 view->maxx = MAX(view->maxx, width);
4710 free(wline);
4711 wline = NULL;
4713 linetype = s->lines[s->lineno].type;
4714 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4715 linetype < GOT_DIFF_LINE_CONTEXT)
4716 attr |= COLOR_PAIR(linetype);
4717 if (attr)
4718 wattron(view->window, attr);
4719 if (s->first_displayed_line + nprinted == s->matched_line &&
4720 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4721 err = add_matched_line(&width, line, view->ncols, 0,
4722 view->window, view->x, regmatch);
4723 if (err) {
4724 free(line);
4725 return err;
4727 } else {
4728 int skip;
4729 err = format_line(&wline, &width, &skip, line,
4730 view->x, view->ncols, 0, view->x ? 1 : 0);
4731 if (err) {
4732 free(line);
4733 return err;
4735 waddwstr(view->window, &wline[skip]);
4736 free(wline);
4737 wline = NULL;
4739 if (s->lineno == view->hiline) {
4740 /* highlight full gline length */
4741 while (width++ < view->ncols)
4742 waddch(view->window, ' ');
4743 } else {
4744 if (width <= view->ncols - 1)
4745 waddch(view->window, '\n');
4747 if (attr)
4748 wattroff(view->window, attr);
4749 if (++nprinted == 1)
4750 s->first_displayed_line = s->lineno;
4752 free(line);
4753 if (nprinted >= 1)
4754 s->last_displayed_line = s->first_displayed_line +
4755 (nprinted - 1);
4756 else
4757 s->last_displayed_line = s->first_displayed_line;
4759 view_border(view);
4761 if (s->eof) {
4762 while (nprinted < view->nlines) {
4763 waddch(view->window, '\n');
4764 nprinted++;
4767 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4768 view->ncols, 0, 0);
4769 if (err) {
4770 return err;
4773 wstandout(view->window);
4774 waddwstr(view->window, wline);
4775 free(wline);
4776 wline = NULL;
4777 wstandend(view->window);
4780 return NULL;
4783 static char *
4784 get_datestr(time_t *time, char *datebuf)
4786 struct tm mytm, *tm;
4787 char *p, *s;
4789 tm = gmtime_r(time, &mytm);
4790 if (tm == NULL)
4791 return NULL;
4792 s = asctime_r(tm, datebuf);
4793 if (s == NULL)
4794 return NULL;
4795 p = strchr(s, '\n');
4796 if (p)
4797 *p = '\0';
4798 return s;
4801 static const struct got_error *
4802 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4803 off_t off, uint8_t type)
4805 struct got_diff_line *p;
4807 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4808 if (p == NULL)
4809 return got_error_from_errno("reallocarray");
4810 *lines = p;
4811 (*lines)[*nlines].offset = off;
4812 (*lines)[*nlines].type = type;
4813 (*nlines)++;
4815 return NULL;
4818 static const struct got_error *
4819 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4820 struct got_diff_line *s_lines, size_t s_nlines)
4822 struct got_diff_line *p;
4823 char buf[BUFSIZ];
4824 size_t i, r;
4826 if (fseeko(src, 0L, SEEK_SET) == -1)
4827 return got_error_from_errno("fseeko");
4829 for (;;) {
4830 r = fread(buf, 1, sizeof(buf), src);
4831 if (r == 0) {
4832 if (ferror(src))
4833 return got_error_from_errno("fread");
4834 if (feof(src))
4835 break;
4837 if (fwrite(buf, 1, r, dst) != r)
4838 return got_ferror(dst, GOT_ERR_IO);
4841 if (s_nlines == 0 && *d_nlines == 0)
4842 return NULL;
4845 * If commit info was in dst, increment line offsets
4846 * of the appended diff content, but skip s_lines[0]
4847 * because offset zero is already in *d_lines.
4849 if (*d_nlines > 0) {
4850 for (i = 1; i < s_nlines; ++i)
4851 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4853 if (s_nlines > 0) {
4854 --s_nlines;
4855 ++s_lines;
4859 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4860 if (p == NULL) {
4861 /* d_lines is freed in close_diff_view() */
4862 return got_error_from_errno("reallocarray");
4865 *d_lines = p;
4867 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4868 *d_nlines += s_nlines;
4870 return NULL;
4873 static const struct got_error *
4874 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4875 struct got_object_id *commit_id, struct got_reflist_head *refs,
4876 struct got_repository *repo, int ignore_ws, int force_text_diff,
4877 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4879 const struct got_error *err = NULL;
4880 char datebuf[26], *datestr;
4881 struct got_commit_object *commit;
4882 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4883 time_t committer_time;
4884 const char *author, *committer;
4885 char *refs_str = NULL;
4886 struct got_pathlist_entry *pe;
4887 off_t outoff = 0;
4888 int n;
4890 if (refs) {
4891 err = build_refs_str(&refs_str, refs, commit_id, repo);
4892 if (err)
4893 return err;
4896 err = got_object_open_as_commit(&commit, repo, commit_id);
4897 if (err)
4898 return err;
4900 err = got_object_id_str(&id_str, commit_id);
4901 if (err) {
4902 err = got_error_from_errno("got_object_id_str");
4903 goto done;
4906 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4907 if (err)
4908 goto done;
4910 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4911 refs_str ? refs_str : "", refs_str ? ")" : "");
4912 if (n < 0) {
4913 err = got_error_from_errno("fprintf");
4914 goto done;
4916 outoff += n;
4917 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4918 if (err)
4919 goto done;
4921 n = fprintf(outfile, "from: %s\n",
4922 got_object_commit_get_author(commit));
4923 if (n < 0) {
4924 err = got_error_from_errno("fprintf");
4925 goto done;
4927 outoff += n;
4928 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4929 if (err)
4930 goto done;
4932 author = got_object_commit_get_author(commit);
4933 committer = got_object_commit_get_committer(commit);
4934 if (strcmp(author, committer) != 0) {
4935 n = fprintf(outfile, "via: %s\n", committer);
4936 if (n < 0) {
4937 err = got_error_from_errno("fprintf");
4938 goto done;
4940 outoff += n;
4941 err = add_line_metadata(lines, nlines, outoff,
4942 GOT_DIFF_LINE_AUTHOR);
4943 if (err)
4944 goto done;
4946 committer_time = got_object_commit_get_committer_time(commit);
4947 datestr = get_datestr(&committer_time, datebuf);
4948 if (datestr) {
4949 n = fprintf(outfile, "date: %s UTC\n", datestr);
4950 if (n < 0) {
4951 err = got_error_from_errno("fprintf");
4952 goto done;
4954 outoff += n;
4955 err = add_line_metadata(lines, nlines, outoff,
4956 GOT_DIFF_LINE_DATE);
4957 if (err)
4958 goto done;
4960 if (got_object_commit_get_nparents(commit) > 1) {
4961 const struct got_object_id_queue *parent_ids;
4962 struct got_object_qid *qid;
4963 int pn = 1;
4964 parent_ids = got_object_commit_get_parent_ids(commit);
4965 STAILQ_FOREACH(qid, parent_ids, entry) {
4966 err = got_object_id_str(&id_str, &qid->id);
4967 if (err)
4968 goto done;
4969 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4970 if (n < 0) {
4971 err = got_error_from_errno("fprintf");
4972 goto done;
4974 outoff += n;
4975 err = add_line_metadata(lines, nlines, outoff,
4976 GOT_DIFF_LINE_META);
4977 if (err)
4978 goto done;
4979 free(id_str);
4980 id_str = NULL;
4984 err = got_object_commit_get_logmsg(&logmsg, commit);
4985 if (err)
4986 goto done;
4987 s = logmsg;
4988 while ((line = strsep(&s, "\n")) != NULL) {
4989 n = fprintf(outfile, "%s\n", line);
4990 if (n < 0) {
4991 err = got_error_from_errno("fprintf");
4992 goto done;
4994 outoff += n;
4995 err = add_line_metadata(lines, nlines, outoff,
4996 GOT_DIFF_LINE_LOGMSG);
4997 if (err)
4998 goto done;
5001 TAILQ_FOREACH(pe, dsa->paths, entry) {
5002 struct got_diff_changed_path *cp = pe->data;
5003 int pad = dsa->max_path_len - pe->path_len + 1;
5005 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5006 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5007 dsa->rm_cols + 1, cp->rm);
5008 if (n < 0) {
5009 err = got_error_from_errno("fprintf");
5010 goto done;
5012 outoff += n;
5013 err = add_line_metadata(lines, nlines, outoff,
5014 GOT_DIFF_LINE_CHANGES);
5015 if (err)
5016 goto done;
5019 fputc('\n', outfile);
5020 outoff++;
5021 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5022 if (err)
5023 goto done;
5025 n = fprintf(outfile,
5026 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5027 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5028 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5029 if (n < 0) {
5030 err = got_error_from_errno("fprintf");
5031 goto done;
5033 outoff += n;
5034 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5035 if (err)
5036 goto done;
5038 fputc('\n', outfile);
5039 outoff++;
5040 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5041 done:
5042 free(id_str);
5043 free(logmsg);
5044 free(refs_str);
5045 got_object_commit_close(commit);
5046 if (err) {
5047 free(*lines);
5048 *lines = NULL;
5049 *nlines = 0;
5051 return err;
5054 static const struct got_error *
5055 create_diff(struct tog_diff_view_state *s)
5057 const struct got_error *err = NULL;
5058 FILE *f = NULL, *tmp_diff_file = NULL;
5059 int obj_type;
5060 struct got_diff_line *lines = NULL;
5061 struct got_pathlist_head changed_paths;
5063 TAILQ_INIT(&changed_paths);
5065 free(s->lines);
5066 s->lines = malloc(sizeof(*s->lines));
5067 if (s->lines == NULL)
5068 return got_error_from_errno("malloc");
5069 s->nlines = 0;
5071 f = got_opentemp();
5072 if (f == NULL) {
5073 err = got_error_from_errno("got_opentemp");
5074 goto done;
5076 tmp_diff_file = got_opentemp();
5077 if (tmp_diff_file == NULL) {
5078 err = got_error_from_errno("got_opentemp");
5079 goto done;
5081 if (s->f && fclose(s->f) == EOF) {
5082 err = got_error_from_errno("fclose");
5083 goto done;
5085 s->f = f;
5087 if (s->id1)
5088 err = got_object_get_type(&obj_type, s->repo, s->id1);
5089 else
5090 err = got_object_get_type(&obj_type, s->repo, s->id2);
5091 if (err)
5092 goto done;
5094 switch (obj_type) {
5095 case GOT_OBJ_TYPE_BLOB:
5096 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5097 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5098 s->label1, s->label2, tog_diff_algo, s->diff_context,
5099 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5100 s->f);
5101 break;
5102 case GOT_OBJ_TYPE_TREE:
5103 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5104 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5105 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5106 s->force_text_diff, NULL, s->repo, s->f);
5107 break;
5108 case GOT_OBJ_TYPE_COMMIT: {
5109 const struct got_object_id_queue *parent_ids;
5110 struct got_object_qid *pid;
5111 struct got_commit_object *commit2;
5112 struct got_reflist_head *refs;
5113 size_t nlines = 0;
5114 struct got_diffstat_cb_arg dsa = {
5115 0, 0, 0, 0, 0, 0,
5116 &changed_paths,
5117 s->ignore_whitespace,
5118 s->force_text_diff,
5119 tog_diff_algo
5122 lines = malloc(sizeof(*lines));
5123 if (lines == NULL) {
5124 err = got_error_from_errno("malloc");
5125 goto done;
5128 /* build diff first in tmp file then append to commit info */
5129 err = got_diff_objects_as_commits(&lines, &nlines,
5130 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5131 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5132 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5133 if (err)
5134 break;
5136 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5137 if (err)
5138 goto done;
5139 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5140 /* Show commit info if we're diffing to a parent/root commit. */
5141 if (s->id1 == NULL) {
5142 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5143 refs, s->repo, s->ignore_whitespace,
5144 s->force_text_diff, &dsa, s->f);
5145 if (err)
5146 goto done;
5147 } else {
5148 parent_ids = got_object_commit_get_parent_ids(commit2);
5149 STAILQ_FOREACH(pid, parent_ids, entry) {
5150 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5151 err = write_commit_info(&s->lines,
5152 &s->nlines, s->id2, refs, s->repo,
5153 s->ignore_whitespace,
5154 s->force_text_diff, &dsa, s->f);
5155 if (err)
5156 goto done;
5157 break;
5161 got_object_commit_close(commit2);
5163 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5164 lines, nlines);
5165 break;
5167 default:
5168 err = got_error(GOT_ERR_OBJ_TYPE);
5169 break;
5171 done:
5172 free(lines);
5173 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5174 if (s->f && fflush(s->f) != 0 && err == NULL)
5175 err = got_error_from_errno("fflush");
5176 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5177 err = got_error_from_errno("fclose");
5178 return err;
5181 static void
5182 diff_view_indicate_progress(struct tog_view *view)
5184 mvwaddstr(view->window, 0, 0, "diffing...");
5185 update_panels();
5186 doupdate();
5189 static const struct got_error *
5190 search_start_diff_view(struct tog_view *view)
5192 struct tog_diff_view_state *s = &view->state.diff;
5194 s->matched_line = 0;
5195 return NULL;
5198 static void
5199 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5200 size_t *nlines, int **first, int **last, int **match, int **selected)
5202 struct tog_diff_view_state *s = &view->state.diff;
5204 *f = s->f;
5205 *nlines = s->nlines;
5206 *line_offsets = NULL;
5207 *match = &s->matched_line;
5208 *first = &s->first_displayed_line;
5209 *last = &s->last_displayed_line;
5210 *selected = &s->selected_line;
5213 static const struct got_error *
5214 search_next_view_match(struct tog_view *view)
5216 const struct got_error *err = NULL;
5217 FILE *f;
5218 int lineno;
5219 char *line = NULL;
5220 size_t linesize = 0;
5221 ssize_t linelen;
5222 off_t *line_offsets;
5223 size_t nlines = 0;
5224 int *first, *last, *match, *selected;
5226 if (!view->search_setup)
5227 return got_error_msg(GOT_ERR_NOT_IMPL,
5228 "view search not supported");
5229 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5230 &match, &selected);
5232 if (!view->searching) {
5233 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5234 return NULL;
5237 if (*match) {
5238 if (view->searching == TOG_SEARCH_FORWARD)
5239 lineno = *first + 1;
5240 else
5241 lineno = *first - 1;
5242 } else
5243 lineno = *first - 1 + *selected;
5245 while (1) {
5246 off_t offset;
5248 if (lineno <= 0 || lineno > nlines) {
5249 if (*match == 0) {
5250 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5251 break;
5254 if (view->searching == TOG_SEARCH_FORWARD)
5255 lineno = 1;
5256 else
5257 lineno = nlines;
5260 offset = view->type == TOG_VIEW_DIFF ?
5261 view->state.diff.lines[lineno - 1].offset :
5262 line_offsets[lineno - 1];
5263 if (fseeko(f, offset, SEEK_SET) != 0) {
5264 free(line);
5265 return got_error_from_errno("fseeko");
5267 linelen = getline(&line, &linesize, f);
5268 if (linelen != -1) {
5269 char *exstr;
5270 err = expand_tab(&exstr, line);
5271 if (err)
5272 break;
5273 if (match_line(exstr, &view->regex, 1,
5274 &view->regmatch)) {
5275 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5276 *match = lineno;
5277 free(exstr);
5278 break;
5280 free(exstr);
5282 if (view->searching == TOG_SEARCH_FORWARD)
5283 lineno++;
5284 else
5285 lineno--;
5287 free(line);
5289 if (*match) {
5290 *first = *match;
5291 *selected = 1;
5294 return err;
5297 static const struct got_error *
5298 close_diff_view(struct tog_view *view)
5300 const struct got_error *err = NULL;
5301 struct tog_diff_view_state *s = &view->state.diff;
5303 free(s->id1);
5304 s->id1 = NULL;
5305 free(s->id2);
5306 s->id2 = NULL;
5307 if (s->f && fclose(s->f) == EOF)
5308 err = got_error_from_errno("fclose");
5309 s->f = NULL;
5310 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5311 err = got_error_from_errno("fclose");
5312 s->f1 = NULL;
5313 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5314 err = got_error_from_errno("fclose");
5315 s->f2 = NULL;
5316 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5317 err = got_error_from_errno("close");
5318 s->fd1 = -1;
5319 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5320 err = got_error_from_errno("close");
5321 s->fd2 = -1;
5322 free(s->lines);
5323 s->lines = NULL;
5324 s->nlines = 0;
5325 return err;
5328 static const struct got_error *
5329 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5330 struct got_object_id *id2, const char *label1, const char *label2,
5331 int diff_context, int ignore_whitespace, int force_text_diff,
5332 struct tog_view *parent_view, struct got_repository *repo)
5334 const struct got_error *err;
5335 struct tog_diff_view_state *s = &view->state.diff;
5337 memset(s, 0, sizeof(*s));
5338 s->fd1 = -1;
5339 s->fd2 = -1;
5341 if (id1 != NULL && id2 != NULL) {
5342 int type1, type2;
5344 err = got_object_get_type(&type1, repo, id1);
5345 if (err)
5346 goto done;
5347 err = got_object_get_type(&type2, repo, id2);
5348 if (err)
5349 goto done;
5351 if (type1 != type2) {
5352 err = got_error(GOT_ERR_OBJ_TYPE);
5353 goto done;
5356 s->first_displayed_line = 1;
5357 s->last_displayed_line = view->nlines;
5358 s->selected_line = 1;
5359 s->repo = repo;
5360 s->id1 = id1;
5361 s->id2 = id2;
5362 s->label1 = label1;
5363 s->label2 = label2;
5365 if (id1) {
5366 s->id1 = got_object_id_dup(id1);
5367 if (s->id1 == NULL) {
5368 err = got_error_from_errno("got_object_id_dup");
5369 goto done;
5371 } else
5372 s->id1 = NULL;
5374 s->id2 = got_object_id_dup(id2);
5375 if (s->id2 == NULL) {
5376 err = got_error_from_errno("got_object_id_dup");
5377 goto done;
5380 s->f1 = got_opentemp();
5381 if (s->f1 == NULL) {
5382 err = got_error_from_errno("got_opentemp");
5383 goto done;
5386 s->f2 = got_opentemp();
5387 if (s->f2 == NULL) {
5388 err = got_error_from_errno("got_opentemp");
5389 goto done;
5392 s->fd1 = got_opentempfd();
5393 if (s->fd1 == -1) {
5394 err = got_error_from_errno("got_opentempfd");
5395 goto done;
5398 s->fd2 = got_opentempfd();
5399 if (s->fd2 == -1) {
5400 err = got_error_from_errno("got_opentempfd");
5401 goto done;
5404 s->diff_context = diff_context;
5405 s->ignore_whitespace = ignore_whitespace;
5406 s->force_text_diff = force_text_diff;
5407 s->parent_view = parent_view;
5408 s->repo = repo;
5410 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5411 int rc;
5413 rc = init_pair(GOT_DIFF_LINE_MINUS,
5414 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5415 if (rc != ERR)
5416 rc = init_pair(GOT_DIFF_LINE_PLUS,
5417 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5418 if (rc != ERR)
5419 rc = init_pair(GOT_DIFF_LINE_HUNK,
5420 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5421 if (rc != ERR)
5422 rc = init_pair(GOT_DIFF_LINE_META,
5423 get_color_value("TOG_COLOR_DIFF_META"), -1);
5424 if (rc != ERR)
5425 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5426 get_color_value("TOG_COLOR_DIFF_META"), -1);
5427 if (rc != ERR)
5428 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5429 get_color_value("TOG_COLOR_DIFF_META"), -1);
5430 if (rc != ERR)
5431 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5432 get_color_value("TOG_COLOR_DIFF_META"), -1);
5433 if (rc != ERR)
5434 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5435 get_color_value("TOG_COLOR_AUTHOR"), -1);
5436 if (rc != ERR)
5437 rc = init_pair(GOT_DIFF_LINE_DATE,
5438 get_color_value("TOG_COLOR_DATE"), -1);
5439 if (rc == ERR) {
5440 err = got_error(GOT_ERR_RANGE);
5441 goto done;
5445 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5446 view_is_splitscreen(view))
5447 show_log_view(parent_view); /* draw border */
5448 diff_view_indicate_progress(view);
5450 err = create_diff(s);
5452 view->show = show_diff_view;
5453 view->input = input_diff_view;
5454 view->reset = reset_diff_view;
5455 view->close = close_diff_view;
5456 view->search_start = search_start_diff_view;
5457 view->search_setup = search_setup_diff_view;
5458 view->search_next = search_next_view_match;
5459 done:
5460 if (err) {
5461 if (view->close == NULL)
5462 close_diff_view(view);
5463 view_close(view);
5465 return err;
5468 static const struct got_error *
5469 show_diff_view(struct tog_view *view)
5471 const struct got_error *err;
5472 struct tog_diff_view_state *s = &view->state.diff;
5473 char *id_str1 = NULL, *id_str2, *header;
5474 const char *label1, *label2;
5476 if (s->id1) {
5477 err = got_object_id_str(&id_str1, s->id1);
5478 if (err)
5479 return err;
5480 label1 = s->label1 ? s->label1 : id_str1;
5481 } else
5482 label1 = "/dev/null";
5484 err = got_object_id_str(&id_str2, s->id2);
5485 if (err)
5486 return err;
5487 label2 = s->label2 ? s->label2 : id_str2;
5489 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5490 err = got_error_from_errno("asprintf");
5491 free(id_str1);
5492 free(id_str2);
5493 return err;
5495 free(id_str1);
5496 free(id_str2);
5498 err = draw_file(view, header);
5499 free(header);
5500 return err;
5503 static const struct got_error *
5504 set_selected_commit(struct tog_diff_view_state *s,
5505 struct commit_queue_entry *entry)
5507 const struct got_error *err;
5508 const struct got_object_id_queue *parent_ids;
5509 struct got_commit_object *selected_commit;
5510 struct got_object_qid *pid;
5512 free(s->id2);
5513 s->id2 = got_object_id_dup(entry->id);
5514 if (s->id2 == NULL)
5515 return got_error_from_errno("got_object_id_dup");
5517 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5518 if (err)
5519 return err;
5520 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5521 free(s->id1);
5522 pid = STAILQ_FIRST(parent_ids);
5523 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5524 got_object_commit_close(selected_commit);
5525 return NULL;
5528 static const struct got_error *
5529 reset_diff_view(struct tog_view *view)
5531 struct tog_diff_view_state *s = &view->state.diff;
5533 view->count = 0;
5534 wclear(view->window);
5535 s->first_displayed_line = 1;
5536 s->last_displayed_line = view->nlines;
5537 s->matched_line = 0;
5538 diff_view_indicate_progress(view);
5539 return create_diff(s);
5542 static void
5543 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5545 int start, i;
5547 i = start = s->first_displayed_line - 1;
5549 while (s->lines[i].type != type) {
5550 if (i == 0)
5551 i = s->nlines - 1;
5552 if (--i == start)
5553 return; /* do nothing, requested type not in file */
5556 s->selected_line = 1;
5557 s->first_displayed_line = i;
5560 static void
5561 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5563 int start, i;
5565 i = start = s->first_displayed_line + 1;
5567 while (s->lines[i].type != type) {
5568 if (i == s->nlines - 1)
5569 i = 0;
5570 if (++i == start)
5571 return; /* do nothing, requested type not in file */
5574 s->selected_line = 1;
5575 s->first_displayed_line = i;
5578 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5579 int, int, int);
5580 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5581 int, int);
5583 static const struct got_error *
5584 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5586 const struct got_error *err = NULL;
5587 struct tog_diff_view_state *s = &view->state.diff;
5588 struct tog_log_view_state *ls;
5589 struct commit_queue_entry *old_selected_entry;
5590 char *line = NULL;
5591 size_t linesize = 0;
5592 ssize_t linelen;
5593 int i, nscroll = view->nlines - 1, up = 0;
5595 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5597 switch (ch) {
5598 case '0':
5599 case '$':
5600 case KEY_RIGHT:
5601 case 'l':
5602 case KEY_LEFT:
5603 case 'h':
5604 horizontal_scroll_input(view, ch);
5605 break;
5606 case 'a':
5607 case 'w':
5608 if (ch == 'a') {
5609 s->force_text_diff = !s->force_text_diff;
5610 view->action = s->force_text_diff ?
5611 "force ASCII text enabled" :
5612 "force ASCII text disabled";
5614 else if (ch == 'w') {
5615 s->ignore_whitespace = !s->ignore_whitespace;
5616 view->action = s->ignore_whitespace ?
5617 "ignore whitespace enabled" :
5618 "ignore whitespace disabled";
5620 err = reset_diff_view(view);
5621 break;
5622 case 'g':
5623 case KEY_HOME:
5624 s->first_displayed_line = 1;
5625 view->count = 0;
5626 break;
5627 case 'G':
5628 case KEY_END:
5629 view->count = 0;
5630 if (s->eof)
5631 break;
5633 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5634 s->eof = 1;
5635 break;
5636 case 'k':
5637 case KEY_UP:
5638 case CTRL('p'):
5639 if (s->first_displayed_line > 1)
5640 s->first_displayed_line--;
5641 else
5642 view->count = 0;
5643 break;
5644 case CTRL('u'):
5645 case 'u':
5646 nscroll /= 2;
5647 /* FALL THROUGH */
5648 case KEY_PPAGE:
5649 case CTRL('b'):
5650 case 'b':
5651 if (s->first_displayed_line == 1) {
5652 view->count = 0;
5653 break;
5655 i = 0;
5656 while (i++ < nscroll && s->first_displayed_line > 1)
5657 s->first_displayed_line--;
5658 break;
5659 case 'j':
5660 case KEY_DOWN:
5661 case CTRL('n'):
5662 if (!s->eof)
5663 s->first_displayed_line++;
5664 else
5665 view->count = 0;
5666 break;
5667 case CTRL('d'):
5668 case 'd':
5669 nscroll /= 2;
5670 /* FALL THROUGH */
5671 case KEY_NPAGE:
5672 case CTRL('f'):
5673 case 'f':
5674 case ' ':
5675 if (s->eof) {
5676 view->count = 0;
5677 break;
5679 i = 0;
5680 while (!s->eof && i++ < nscroll) {
5681 linelen = getline(&line, &linesize, s->f);
5682 s->first_displayed_line++;
5683 if (linelen == -1) {
5684 if (feof(s->f)) {
5685 s->eof = 1;
5686 } else
5687 err = got_ferror(s->f, GOT_ERR_IO);
5688 break;
5691 free(line);
5692 break;
5693 case '(':
5694 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5695 break;
5696 case ')':
5697 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5698 break;
5699 case '{':
5700 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5701 break;
5702 case '}':
5703 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5704 break;
5705 case '[':
5706 if (s->diff_context > 0) {
5707 s->diff_context--;
5708 s->matched_line = 0;
5709 diff_view_indicate_progress(view);
5710 err = create_diff(s);
5711 if (s->first_displayed_line + view->nlines - 1 >
5712 s->nlines) {
5713 s->first_displayed_line = 1;
5714 s->last_displayed_line = view->nlines;
5716 } else
5717 view->count = 0;
5718 break;
5719 case ']':
5720 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5721 s->diff_context++;
5722 s->matched_line = 0;
5723 diff_view_indicate_progress(view);
5724 err = create_diff(s);
5725 } else
5726 view->count = 0;
5727 break;
5728 case '<':
5729 case ',':
5730 case 'K':
5731 up = 1;
5732 /* FALL THROUGH */
5733 case '>':
5734 case '.':
5735 case 'J':
5736 if (s->parent_view == NULL) {
5737 view->count = 0;
5738 break;
5740 s->parent_view->count = view->count;
5742 if (s->parent_view->type == TOG_VIEW_LOG) {
5743 ls = &s->parent_view->state.log;
5744 old_selected_entry = ls->selected_entry;
5746 err = input_log_view(NULL, s->parent_view,
5747 up ? KEY_UP : KEY_DOWN);
5748 if (err)
5749 break;
5750 view->count = s->parent_view->count;
5752 if (old_selected_entry == ls->selected_entry)
5753 break;
5755 err = set_selected_commit(s, ls->selected_entry);
5756 if (err)
5757 break;
5758 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5759 struct tog_blame_view_state *bs;
5760 struct got_object_id *id, *prev_id;
5762 bs = &s->parent_view->state.blame;
5763 prev_id = get_annotation_for_line(bs->blame.lines,
5764 bs->blame.nlines, bs->last_diffed_line);
5766 err = input_blame_view(&view, s->parent_view,
5767 up ? KEY_UP : KEY_DOWN);
5768 if (err)
5769 break;
5770 view->count = s->parent_view->count;
5772 if (prev_id == NULL)
5773 break;
5774 id = get_selected_commit_id(bs->blame.lines,
5775 bs->blame.nlines, bs->first_displayed_line,
5776 bs->selected_line);
5777 if (id == NULL)
5778 break;
5780 if (!got_object_id_cmp(prev_id, id))
5781 break;
5783 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5784 if (err)
5785 break;
5787 s->first_displayed_line = 1;
5788 s->last_displayed_line = view->nlines;
5789 s->matched_line = 0;
5790 view->x = 0;
5792 diff_view_indicate_progress(view);
5793 err = create_diff(s);
5794 break;
5795 default:
5796 view->count = 0;
5797 break;
5800 return err;
5803 static const struct got_error *
5804 cmd_diff(int argc, char *argv[])
5806 const struct got_error *error;
5807 struct got_repository *repo = NULL;
5808 struct got_worktree *worktree = NULL;
5809 struct got_object_id *id1 = NULL, *id2 = NULL;
5810 char *repo_path = NULL, *cwd = NULL;
5811 char *id_str1 = NULL, *id_str2 = NULL;
5812 char *label1 = NULL, *label2 = NULL;
5813 int diff_context = 3, ignore_whitespace = 0;
5814 int ch, force_text_diff = 0;
5815 const char *errstr;
5816 struct tog_view *view;
5817 int *pack_fds = NULL;
5819 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5820 switch (ch) {
5821 case 'a':
5822 force_text_diff = 1;
5823 break;
5824 case 'C':
5825 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5826 &errstr);
5827 if (errstr != NULL)
5828 errx(1, "number of context lines is %s: %s",
5829 errstr, errstr);
5830 break;
5831 case 'r':
5832 repo_path = realpath(optarg, NULL);
5833 if (repo_path == NULL)
5834 return got_error_from_errno2("realpath",
5835 optarg);
5836 got_path_strip_trailing_slashes(repo_path);
5837 break;
5838 case 'w':
5839 ignore_whitespace = 1;
5840 break;
5841 default:
5842 usage_diff();
5843 /* NOTREACHED */
5847 argc -= optind;
5848 argv += optind;
5850 if (argc == 0) {
5851 usage_diff(); /* TODO show local worktree changes */
5852 } else if (argc == 2) {
5853 id_str1 = argv[0];
5854 id_str2 = argv[1];
5855 } else
5856 usage_diff();
5858 error = got_repo_pack_fds_open(&pack_fds);
5859 if (error)
5860 goto done;
5862 if (repo_path == NULL) {
5863 cwd = getcwd(NULL, 0);
5864 if (cwd == NULL)
5865 return got_error_from_errno("getcwd");
5866 error = got_worktree_open(&worktree, cwd);
5867 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5868 goto done;
5869 if (worktree)
5870 repo_path =
5871 strdup(got_worktree_get_repo_path(worktree));
5872 else
5873 repo_path = strdup(cwd);
5874 if (repo_path == NULL) {
5875 error = got_error_from_errno("strdup");
5876 goto done;
5880 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5881 if (error)
5882 goto done;
5884 init_curses();
5886 error = apply_unveil(got_repo_get_path(repo), NULL);
5887 if (error)
5888 goto done;
5890 error = tog_load_refs(repo, 0);
5891 if (error)
5892 goto done;
5894 error = got_repo_match_object_id(&id1, &label1, id_str1,
5895 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5896 if (error)
5897 goto done;
5899 error = got_repo_match_object_id(&id2, &label2, id_str2,
5900 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5901 if (error)
5902 goto done;
5904 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5905 if (view == NULL) {
5906 error = got_error_from_errno("view_open");
5907 goto done;
5909 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5910 ignore_whitespace, force_text_diff, NULL, repo);
5911 if (error)
5912 goto done;
5913 error = view_loop(view);
5914 done:
5915 free(label1);
5916 free(label2);
5917 free(repo_path);
5918 free(cwd);
5919 if (repo) {
5920 const struct got_error *close_err = got_repo_close(repo);
5921 if (error == NULL)
5922 error = close_err;
5924 if (worktree)
5925 got_worktree_close(worktree);
5926 if (pack_fds) {
5927 const struct got_error *pack_err =
5928 got_repo_pack_fds_close(pack_fds);
5929 if (error == NULL)
5930 error = pack_err;
5932 tog_free_refs();
5933 return error;
5936 __dead static void
5937 usage_blame(void)
5939 endwin();
5940 fprintf(stderr,
5941 "usage: %s blame [-c commit] [-r repository-path] path\n",
5942 getprogname());
5943 exit(1);
5946 struct tog_blame_line {
5947 int annotated;
5948 struct got_object_id *id;
5951 static const struct got_error *
5952 draw_blame(struct tog_view *view)
5954 struct tog_blame_view_state *s = &view->state.blame;
5955 struct tog_blame *blame = &s->blame;
5956 regmatch_t *regmatch = &view->regmatch;
5957 const struct got_error *err;
5958 int lineno = 0, nprinted = 0;
5959 char *line = NULL;
5960 size_t linesize = 0;
5961 ssize_t linelen;
5962 wchar_t *wline;
5963 int width;
5964 struct tog_blame_line *blame_line;
5965 struct got_object_id *prev_id = NULL;
5966 char *id_str;
5967 struct tog_color *tc;
5969 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5970 if (err)
5971 return err;
5973 rewind(blame->f);
5974 werase(view->window);
5976 if (asprintf(&line, "commit %s", id_str) == -1) {
5977 err = got_error_from_errno("asprintf");
5978 free(id_str);
5979 return err;
5982 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5983 free(line);
5984 line = NULL;
5985 if (err)
5986 return err;
5987 if (view_needs_focus_indication(view))
5988 wstandout(view->window);
5989 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5990 if (tc)
5991 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5992 waddwstr(view->window, wline);
5993 while (width++ < view->ncols)
5994 waddch(view->window, ' ');
5995 if (tc)
5996 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5997 if (view_needs_focus_indication(view))
5998 wstandend(view->window);
5999 free(wline);
6000 wline = NULL;
6002 if (view->gline > blame->nlines)
6003 view->gline = blame->nlines;
6005 if (tog_io.wait_for_ui) {
6006 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6007 int rc;
6009 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6010 if (rc)
6011 return got_error_set_errno(rc, "pthread_cond_wait");
6012 tog_io.wait_for_ui = 0;
6015 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6016 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6017 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6018 free(id_str);
6019 return got_error_from_errno("asprintf");
6021 free(id_str);
6022 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6023 free(line);
6024 line = NULL;
6025 if (err)
6026 return err;
6027 waddwstr(view->window, wline);
6028 free(wline);
6029 wline = NULL;
6030 if (width < view->ncols - 1)
6031 waddch(view->window, '\n');
6033 s->eof = 0;
6034 view->maxx = 0;
6035 while (nprinted < view->nlines - 2) {
6036 linelen = getline(&line, &linesize, blame->f);
6037 if (linelen == -1) {
6038 if (feof(blame->f)) {
6039 s->eof = 1;
6040 break;
6042 free(line);
6043 return got_ferror(blame->f, GOT_ERR_IO);
6045 if (++lineno < s->first_displayed_line)
6046 continue;
6047 if (view->gline && !gotoline(view, &lineno, &nprinted))
6048 continue;
6050 /* Set view->maxx based on full line length. */
6051 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6052 if (err) {
6053 free(line);
6054 return err;
6056 free(wline);
6057 wline = NULL;
6058 view->maxx = MAX(view->maxx, width);
6060 if (nprinted == s->selected_line - 1)
6061 wstandout(view->window);
6063 if (blame->nlines > 0) {
6064 blame_line = &blame->lines[lineno - 1];
6065 if (blame_line->annotated && prev_id &&
6066 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6067 !(nprinted == s->selected_line - 1)) {
6068 waddstr(view->window, " ");
6069 } else if (blame_line->annotated) {
6070 char *id_str;
6071 err = got_object_id_str(&id_str,
6072 blame_line->id);
6073 if (err) {
6074 free(line);
6075 return err;
6077 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6078 if (tc)
6079 wattr_on(view->window,
6080 COLOR_PAIR(tc->colorpair), NULL);
6081 wprintw(view->window, "%.8s", id_str);
6082 if (tc)
6083 wattr_off(view->window,
6084 COLOR_PAIR(tc->colorpair), NULL);
6085 free(id_str);
6086 prev_id = blame_line->id;
6087 } else {
6088 waddstr(view->window, "........");
6089 prev_id = NULL;
6091 } else {
6092 waddstr(view->window, "........");
6093 prev_id = NULL;
6096 if (nprinted == s->selected_line - 1)
6097 wstandend(view->window);
6098 waddstr(view->window, " ");
6100 if (view->ncols <= 9) {
6101 width = 9;
6102 } else if (s->first_displayed_line + nprinted ==
6103 s->matched_line &&
6104 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6105 err = add_matched_line(&width, line, view->ncols - 9, 9,
6106 view->window, view->x, regmatch);
6107 if (err) {
6108 free(line);
6109 return err;
6111 width += 9;
6112 } else {
6113 int skip;
6114 err = format_line(&wline, &width, &skip, line,
6115 view->x, view->ncols - 9, 9, 1);
6116 if (err) {
6117 free(line);
6118 return err;
6120 waddwstr(view->window, &wline[skip]);
6121 width += 9;
6122 free(wline);
6123 wline = NULL;
6126 if (width <= view->ncols - 1)
6127 waddch(view->window, '\n');
6128 if (++nprinted == 1)
6129 s->first_displayed_line = lineno;
6131 free(line);
6132 s->last_displayed_line = lineno;
6134 view_border(view);
6136 return NULL;
6139 static const struct got_error *
6140 blame_cb(void *arg, int nlines, int lineno,
6141 struct got_commit_object *commit, struct got_object_id *id)
6143 const struct got_error *err = NULL;
6144 struct tog_blame_cb_args *a = arg;
6145 struct tog_blame_line *line;
6146 int errcode;
6148 if (nlines != a->nlines ||
6149 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6150 return got_error(GOT_ERR_RANGE);
6152 errcode = pthread_mutex_lock(&tog_mutex);
6153 if (errcode)
6154 return got_error_set_errno(errcode, "pthread_mutex_lock");
6156 if (*a->quit) { /* user has quit the blame view */
6157 err = got_error(GOT_ERR_ITER_COMPLETED);
6158 goto done;
6161 if (lineno == -1)
6162 goto done; /* no change in this commit */
6164 line = &a->lines[lineno - 1];
6165 if (line->annotated)
6166 goto done;
6168 line->id = got_object_id_dup(id);
6169 if (line->id == NULL) {
6170 err = got_error_from_errno("got_object_id_dup");
6171 goto done;
6173 line->annotated = 1;
6174 done:
6175 errcode = pthread_mutex_unlock(&tog_mutex);
6176 if (errcode)
6177 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6178 return err;
6181 static void *
6182 blame_thread(void *arg)
6184 const struct got_error *err, *close_err;
6185 struct tog_blame_thread_args *ta = arg;
6186 struct tog_blame_cb_args *a = ta->cb_args;
6187 int errcode, fd1 = -1, fd2 = -1;
6188 FILE *f1 = NULL, *f2 = NULL;
6190 fd1 = got_opentempfd();
6191 if (fd1 == -1)
6192 return (void *)got_error_from_errno("got_opentempfd");
6194 fd2 = got_opentempfd();
6195 if (fd2 == -1) {
6196 err = got_error_from_errno("got_opentempfd");
6197 goto done;
6200 f1 = got_opentemp();
6201 if (f1 == NULL) {
6202 err = (void *)got_error_from_errno("got_opentemp");
6203 goto done;
6205 f2 = got_opentemp();
6206 if (f2 == NULL) {
6207 err = (void *)got_error_from_errno("got_opentemp");
6208 goto done;
6211 err = block_signals_used_by_main_thread();
6212 if (err)
6213 goto done;
6215 err = got_blame(ta->path, a->commit_id, ta->repo,
6216 tog_diff_algo, blame_cb, ta->cb_args,
6217 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6218 if (err && err->code == GOT_ERR_CANCELLED)
6219 err = NULL;
6221 errcode = pthread_mutex_lock(&tog_mutex);
6222 if (errcode) {
6223 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6224 goto done;
6227 close_err = got_repo_close(ta->repo);
6228 if (err == NULL)
6229 err = close_err;
6230 ta->repo = NULL;
6231 *ta->complete = 1;
6233 if (tog_io.wait_for_ui) {
6234 errcode = pthread_cond_signal(&ta->blame_complete);
6235 if (errcode && err == NULL)
6236 err = got_error_set_errno(errcode,
6237 "pthread_cond_signal");
6240 errcode = pthread_mutex_unlock(&tog_mutex);
6241 if (errcode && err == NULL)
6242 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6244 done:
6245 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6246 err = got_error_from_errno("close");
6247 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6248 err = got_error_from_errno("close");
6249 if (f1 && fclose(f1) == EOF && err == NULL)
6250 err = got_error_from_errno("fclose");
6251 if (f2 && fclose(f2) == EOF && err == NULL)
6252 err = got_error_from_errno("fclose");
6254 return (void *)err;
6257 static struct got_object_id *
6258 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6259 int first_displayed_line, int selected_line)
6261 struct tog_blame_line *line;
6263 if (nlines <= 0)
6264 return NULL;
6266 line = &lines[first_displayed_line - 1 + selected_line - 1];
6267 if (!line->annotated)
6268 return NULL;
6270 return line->id;
6273 static struct got_object_id *
6274 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6275 int lineno)
6277 struct tog_blame_line *line;
6279 if (nlines <= 0 || lineno >= nlines)
6280 return NULL;
6282 line = &lines[lineno - 1];
6283 if (!line->annotated)
6284 return NULL;
6286 return line->id;
6289 static const struct got_error *
6290 stop_blame(struct tog_blame *blame)
6292 const struct got_error *err = NULL;
6293 int i;
6295 if (blame->thread) {
6296 int errcode;
6297 errcode = pthread_mutex_unlock(&tog_mutex);
6298 if (errcode)
6299 return got_error_set_errno(errcode,
6300 "pthread_mutex_unlock");
6301 errcode = pthread_join(blame->thread, (void **)&err);
6302 if (errcode)
6303 return got_error_set_errno(errcode, "pthread_join");
6304 errcode = pthread_mutex_lock(&tog_mutex);
6305 if (errcode)
6306 return got_error_set_errno(errcode,
6307 "pthread_mutex_lock");
6308 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6309 err = NULL;
6310 blame->thread = NULL;
6312 if (blame->thread_args.repo) {
6313 const struct got_error *close_err;
6314 close_err = got_repo_close(blame->thread_args.repo);
6315 if (err == NULL)
6316 err = close_err;
6317 blame->thread_args.repo = NULL;
6319 if (blame->f) {
6320 if (fclose(blame->f) == EOF && err == NULL)
6321 err = got_error_from_errno("fclose");
6322 blame->f = NULL;
6324 if (blame->lines) {
6325 for (i = 0; i < blame->nlines; i++)
6326 free(blame->lines[i].id);
6327 free(blame->lines);
6328 blame->lines = NULL;
6330 free(blame->cb_args.commit_id);
6331 blame->cb_args.commit_id = NULL;
6332 if (blame->pack_fds) {
6333 const struct got_error *pack_err =
6334 got_repo_pack_fds_close(blame->pack_fds);
6335 if (err == NULL)
6336 err = pack_err;
6337 blame->pack_fds = NULL;
6339 return err;
6342 static const struct got_error *
6343 cancel_blame_view(void *arg)
6345 const struct got_error *err = NULL;
6346 int *done = arg;
6347 int errcode;
6349 errcode = pthread_mutex_lock(&tog_mutex);
6350 if (errcode)
6351 return got_error_set_errno(errcode,
6352 "pthread_mutex_unlock");
6354 if (*done)
6355 err = got_error(GOT_ERR_CANCELLED);
6357 errcode = pthread_mutex_unlock(&tog_mutex);
6358 if (errcode)
6359 return got_error_set_errno(errcode,
6360 "pthread_mutex_lock");
6362 return err;
6365 static const struct got_error *
6366 run_blame(struct tog_view *view)
6368 struct tog_blame_view_state *s = &view->state.blame;
6369 struct tog_blame *blame = &s->blame;
6370 const struct got_error *err = NULL;
6371 struct got_commit_object *commit = NULL;
6372 struct got_blob_object *blob = NULL;
6373 struct got_repository *thread_repo = NULL;
6374 struct got_object_id *obj_id = NULL;
6375 int obj_type, fd = -1;
6376 int *pack_fds = NULL;
6378 err = got_object_open_as_commit(&commit, s->repo,
6379 &s->blamed_commit->id);
6380 if (err)
6381 return err;
6383 fd = got_opentempfd();
6384 if (fd == -1) {
6385 err = got_error_from_errno("got_opentempfd");
6386 goto done;
6389 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6390 if (err)
6391 goto done;
6393 err = got_object_get_type(&obj_type, s->repo, obj_id);
6394 if (err)
6395 goto done;
6397 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6398 err = got_error(GOT_ERR_OBJ_TYPE);
6399 goto done;
6402 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6403 if (err)
6404 goto done;
6405 blame->f = got_opentemp();
6406 if (blame->f == NULL) {
6407 err = got_error_from_errno("got_opentemp");
6408 goto done;
6410 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6411 &blame->line_offsets, blame->f, blob);
6412 if (err)
6413 goto done;
6414 if (blame->nlines == 0) {
6415 s->blame_complete = 1;
6416 goto done;
6419 /* Don't include \n at EOF in the blame line count. */
6420 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6421 blame->nlines--;
6423 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6424 if (blame->lines == NULL) {
6425 err = got_error_from_errno("calloc");
6426 goto done;
6429 err = got_repo_pack_fds_open(&pack_fds);
6430 if (err)
6431 goto done;
6432 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6433 pack_fds);
6434 if (err)
6435 goto done;
6437 blame->pack_fds = pack_fds;
6438 blame->cb_args.view = view;
6439 blame->cb_args.lines = blame->lines;
6440 blame->cb_args.nlines = blame->nlines;
6441 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6442 if (blame->cb_args.commit_id == NULL) {
6443 err = got_error_from_errno("got_object_id_dup");
6444 goto done;
6446 blame->cb_args.quit = &s->done;
6448 blame->thread_args.path = s->path;
6449 blame->thread_args.repo = thread_repo;
6450 blame->thread_args.cb_args = &blame->cb_args;
6451 blame->thread_args.complete = &s->blame_complete;
6452 blame->thread_args.cancel_cb = cancel_blame_view;
6453 blame->thread_args.cancel_arg = &s->done;
6454 s->blame_complete = 0;
6456 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6457 s->first_displayed_line = 1;
6458 s->last_displayed_line = view->nlines;
6459 s->selected_line = 1;
6461 s->matched_line = 0;
6463 done:
6464 if (commit)
6465 got_object_commit_close(commit);
6466 if (fd != -1 && close(fd) == -1 && err == NULL)
6467 err = got_error_from_errno("close");
6468 if (blob)
6469 got_object_blob_close(blob);
6470 free(obj_id);
6471 if (err)
6472 stop_blame(blame);
6473 return err;
6476 static const struct got_error *
6477 open_blame_view(struct tog_view *view, char *path,
6478 struct got_object_id *commit_id, struct got_repository *repo)
6480 const struct got_error *err = NULL;
6481 struct tog_blame_view_state *s = &view->state.blame;
6483 STAILQ_INIT(&s->blamed_commits);
6485 s->path = strdup(path);
6486 if (s->path == NULL)
6487 return got_error_from_errno("strdup");
6489 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6490 if (err) {
6491 free(s->path);
6492 return err;
6495 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6496 s->first_displayed_line = 1;
6497 s->last_displayed_line = view->nlines;
6498 s->selected_line = 1;
6499 s->blame_complete = 0;
6500 s->repo = repo;
6501 s->commit_id = commit_id;
6502 memset(&s->blame, 0, sizeof(s->blame));
6504 STAILQ_INIT(&s->colors);
6505 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6506 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6507 get_color_value("TOG_COLOR_COMMIT"));
6508 if (err)
6509 return err;
6512 view->show = show_blame_view;
6513 view->input = input_blame_view;
6514 view->reset = reset_blame_view;
6515 view->close = close_blame_view;
6516 view->search_start = search_start_blame_view;
6517 view->search_setup = search_setup_blame_view;
6518 view->search_next = search_next_view_match;
6520 if (using_mock_io) {
6521 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6522 int rc;
6524 rc = pthread_cond_init(&bta->blame_complete, NULL);
6525 if (rc)
6526 return got_error_set_errno(rc, "pthread_cond_init");
6529 return run_blame(view);
6532 static const struct got_error *
6533 close_blame_view(struct tog_view *view)
6535 const struct got_error *err = NULL;
6536 struct tog_blame_view_state *s = &view->state.blame;
6538 if (s->blame.thread)
6539 err = stop_blame(&s->blame);
6541 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6542 struct got_object_qid *blamed_commit;
6543 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6544 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6545 got_object_qid_free(blamed_commit);
6548 if (using_mock_io) {
6549 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6550 int rc;
6552 rc = pthread_cond_destroy(&bta->blame_complete);
6553 if (rc && err == NULL)
6554 err = got_error_set_errno(rc, "pthread_cond_destroy");
6557 free(s->path);
6558 free_colors(&s->colors);
6559 return err;
6562 static const struct got_error *
6563 search_start_blame_view(struct tog_view *view)
6565 struct tog_blame_view_state *s = &view->state.blame;
6567 s->matched_line = 0;
6568 return NULL;
6571 static void
6572 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6573 size_t *nlines, int **first, int **last, int **match, int **selected)
6575 struct tog_blame_view_state *s = &view->state.blame;
6577 *f = s->blame.f;
6578 *nlines = s->blame.nlines;
6579 *line_offsets = s->blame.line_offsets;
6580 *match = &s->matched_line;
6581 *first = &s->first_displayed_line;
6582 *last = &s->last_displayed_line;
6583 *selected = &s->selected_line;
6586 static const struct got_error *
6587 show_blame_view(struct tog_view *view)
6589 const struct got_error *err = NULL;
6590 struct tog_blame_view_state *s = &view->state.blame;
6591 int errcode;
6593 if (s->blame.thread == NULL && !s->blame_complete) {
6594 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6595 &s->blame.thread_args);
6596 if (errcode)
6597 return got_error_set_errno(errcode, "pthread_create");
6599 if (!using_mock_io)
6600 halfdelay(1); /* fast refresh while annotating */
6603 if (s->blame_complete && !using_mock_io)
6604 halfdelay(10); /* disable fast refresh */
6606 err = draw_blame(view);
6608 view_border(view);
6609 return err;
6612 static const struct got_error *
6613 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6614 struct got_repository *repo, struct got_object_id *id)
6616 struct tog_view *log_view;
6617 const struct got_error *err = NULL;
6619 *new_view = NULL;
6621 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6622 if (log_view == NULL)
6623 return got_error_from_errno("view_open");
6625 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6626 if (err)
6627 view_close(log_view);
6628 else
6629 *new_view = log_view;
6631 return err;
6634 static const struct got_error *
6635 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6637 const struct got_error *err = NULL, *thread_err = NULL;
6638 struct tog_view *diff_view;
6639 struct tog_blame_view_state *s = &view->state.blame;
6640 int eos, nscroll, begin_y = 0, begin_x = 0;
6642 eos = nscroll = view->nlines - 2;
6643 if (view_is_hsplit_top(view))
6644 --eos; /* border */
6646 switch (ch) {
6647 case '0':
6648 case '$':
6649 case KEY_RIGHT:
6650 case 'l':
6651 case KEY_LEFT:
6652 case 'h':
6653 horizontal_scroll_input(view, ch);
6654 break;
6655 case 'q':
6656 s->done = 1;
6657 break;
6658 case 'g':
6659 case KEY_HOME:
6660 s->selected_line = 1;
6661 s->first_displayed_line = 1;
6662 view->count = 0;
6663 break;
6664 case 'G':
6665 case KEY_END:
6666 if (s->blame.nlines < eos) {
6667 s->selected_line = s->blame.nlines;
6668 s->first_displayed_line = 1;
6669 } else {
6670 s->selected_line = eos;
6671 s->first_displayed_line = s->blame.nlines - (eos - 1);
6673 view->count = 0;
6674 break;
6675 case 'k':
6676 case KEY_UP:
6677 case CTRL('p'):
6678 if (s->selected_line > 1)
6679 s->selected_line--;
6680 else if (s->selected_line == 1 &&
6681 s->first_displayed_line > 1)
6682 s->first_displayed_line--;
6683 else
6684 view->count = 0;
6685 break;
6686 case CTRL('u'):
6687 case 'u':
6688 nscroll /= 2;
6689 /* FALL THROUGH */
6690 case KEY_PPAGE:
6691 case CTRL('b'):
6692 case 'b':
6693 if (s->first_displayed_line == 1) {
6694 if (view->count > 1)
6695 nscroll += nscroll;
6696 s->selected_line = MAX(1, s->selected_line - nscroll);
6697 view->count = 0;
6698 break;
6700 if (s->first_displayed_line > nscroll)
6701 s->first_displayed_line -= nscroll;
6702 else
6703 s->first_displayed_line = 1;
6704 break;
6705 case 'j':
6706 case KEY_DOWN:
6707 case CTRL('n'):
6708 if (s->selected_line < eos && s->first_displayed_line +
6709 s->selected_line <= s->blame.nlines)
6710 s->selected_line++;
6711 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6712 s->first_displayed_line++;
6713 else
6714 view->count = 0;
6715 break;
6716 case 'c':
6717 case 'p': {
6718 struct got_object_id *id = NULL;
6720 view->count = 0;
6721 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6722 s->first_displayed_line, s->selected_line);
6723 if (id == NULL)
6724 break;
6725 if (ch == 'p') {
6726 struct got_commit_object *commit, *pcommit;
6727 struct got_object_qid *pid;
6728 struct got_object_id *blob_id = NULL;
6729 int obj_type;
6730 err = got_object_open_as_commit(&commit,
6731 s->repo, id);
6732 if (err)
6733 break;
6734 pid = STAILQ_FIRST(
6735 got_object_commit_get_parent_ids(commit));
6736 if (pid == NULL) {
6737 got_object_commit_close(commit);
6738 break;
6740 /* Check if path history ends here. */
6741 err = got_object_open_as_commit(&pcommit,
6742 s->repo, &pid->id);
6743 if (err)
6744 break;
6745 err = got_object_id_by_path(&blob_id, s->repo,
6746 pcommit, s->path);
6747 got_object_commit_close(pcommit);
6748 if (err) {
6749 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6750 err = NULL;
6751 got_object_commit_close(commit);
6752 break;
6754 err = got_object_get_type(&obj_type, s->repo,
6755 blob_id);
6756 free(blob_id);
6757 /* Can't blame non-blob type objects. */
6758 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6759 got_object_commit_close(commit);
6760 break;
6762 err = got_object_qid_alloc(&s->blamed_commit,
6763 &pid->id);
6764 got_object_commit_close(commit);
6765 } else {
6766 if (got_object_id_cmp(id,
6767 &s->blamed_commit->id) == 0)
6768 break;
6769 err = got_object_qid_alloc(&s->blamed_commit,
6770 id);
6772 if (err)
6773 break;
6774 s->done = 1;
6775 thread_err = stop_blame(&s->blame);
6776 s->done = 0;
6777 if (thread_err)
6778 break;
6779 STAILQ_INSERT_HEAD(&s->blamed_commits,
6780 s->blamed_commit, entry);
6781 err = run_blame(view);
6782 if (err)
6783 break;
6784 break;
6786 case 'C': {
6787 struct got_object_qid *first;
6789 view->count = 0;
6790 first = STAILQ_FIRST(&s->blamed_commits);
6791 if (!got_object_id_cmp(&first->id, s->commit_id))
6792 break;
6793 s->done = 1;
6794 thread_err = stop_blame(&s->blame);
6795 s->done = 0;
6796 if (thread_err)
6797 break;
6798 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6799 got_object_qid_free(s->blamed_commit);
6800 s->blamed_commit =
6801 STAILQ_FIRST(&s->blamed_commits);
6802 err = run_blame(view);
6803 if (err)
6804 break;
6805 break;
6807 case 'L':
6808 view->count = 0;
6809 s->id_to_log = get_selected_commit_id(s->blame.lines,
6810 s->blame.nlines, s->first_displayed_line, s->selected_line);
6811 if (s->id_to_log)
6812 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6813 break;
6814 case KEY_ENTER:
6815 case '\r': {
6816 struct got_object_id *id = NULL;
6817 struct got_object_qid *pid;
6818 struct got_commit_object *commit = NULL;
6820 view->count = 0;
6821 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6822 s->first_displayed_line, s->selected_line);
6823 if (id == NULL)
6824 break;
6825 err = got_object_open_as_commit(&commit, s->repo, id);
6826 if (err)
6827 break;
6828 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6829 if (*new_view) {
6830 /* traversed from diff view, release diff resources */
6831 err = close_diff_view(*new_view);
6832 if (err)
6833 break;
6834 diff_view = *new_view;
6835 } else {
6836 if (view_is_parent_view(view))
6837 view_get_split(view, &begin_y, &begin_x);
6839 diff_view = view_open(0, 0, begin_y, begin_x,
6840 TOG_VIEW_DIFF);
6841 if (diff_view == NULL) {
6842 got_object_commit_close(commit);
6843 err = got_error_from_errno("view_open");
6844 break;
6847 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6848 id, NULL, NULL, 3, 0, 0, view, s->repo);
6849 got_object_commit_close(commit);
6850 if (err) {
6851 view_close(diff_view);
6852 break;
6854 s->last_diffed_line = s->first_displayed_line - 1 +
6855 s->selected_line;
6856 if (*new_view)
6857 break; /* still open from active diff view */
6858 if (view_is_parent_view(view) &&
6859 view->mode == TOG_VIEW_SPLIT_HRZN) {
6860 err = view_init_hsplit(view, begin_y);
6861 if (err)
6862 break;
6865 view->focussed = 0;
6866 diff_view->focussed = 1;
6867 diff_view->mode = view->mode;
6868 diff_view->nlines = view->lines - begin_y;
6869 if (view_is_parent_view(view)) {
6870 view_transfer_size(diff_view, view);
6871 err = view_close_child(view);
6872 if (err)
6873 break;
6874 err = view_set_child(view, diff_view);
6875 if (err)
6876 break;
6877 view->focus_child = 1;
6878 } else
6879 *new_view = diff_view;
6880 if (err)
6881 break;
6882 break;
6884 case CTRL('d'):
6885 case 'd':
6886 nscroll /= 2;
6887 /* FALL THROUGH */
6888 case KEY_NPAGE:
6889 case CTRL('f'):
6890 case 'f':
6891 case ' ':
6892 if (s->last_displayed_line >= s->blame.nlines &&
6893 s->selected_line >= MIN(s->blame.nlines,
6894 view->nlines - 2)) {
6895 view->count = 0;
6896 break;
6898 if (s->last_displayed_line >= s->blame.nlines &&
6899 s->selected_line < view->nlines - 2) {
6900 s->selected_line +=
6901 MIN(nscroll, s->last_displayed_line -
6902 s->first_displayed_line - s->selected_line + 1);
6904 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6905 s->first_displayed_line += nscroll;
6906 else
6907 s->first_displayed_line =
6908 s->blame.nlines - (view->nlines - 3);
6909 break;
6910 case KEY_RESIZE:
6911 if (s->selected_line > view->nlines - 2) {
6912 s->selected_line = MIN(s->blame.nlines,
6913 view->nlines - 2);
6915 break;
6916 default:
6917 view->count = 0;
6918 break;
6920 return thread_err ? thread_err : err;
6923 static const struct got_error *
6924 reset_blame_view(struct tog_view *view)
6926 const struct got_error *err;
6927 struct tog_blame_view_state *s = &view->state.blame;
6929 view->count = 0;
6930 s->done = 1;
6931 err = stop_blame(&s->blame);
6932 s->done = 0;
6933 if (err)
6934 return err;
6935 return run_blame(view);
6938 static const struct got_error *
6939 cmd_blame(int argc, char *argv[])
6941 const struct got_error *error;
6942 struct got_repository *repo = NULL;
6943 struct got_worktree *worktree = NULL;
6944 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6945 char *link_target = NULL;
6946 struct got_object_id *commit_id = NULL;
6947 struct got_commit_object *commit = NULL;
6948 char *commit_id_str = NULL;
6949 int ch;
6950 struct tog_view *view = NULL;
6951 int *pack_fds = NULL;
6953 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6954 switch (ch) {
6955 case 'c':
6956 commit_id_str = optarg;
6957 break;
6958 case 'r':
6959 repo_path = realpath(optarg, NULL);
6960 if (repo_path == NULL)
6961 return got_error_from_errno2("realpath",
6962 optarg);
6963 break;
6964 default:
6965 usage_blame();
6966 /* NOTREACHED */
6970 argc -= optind;
6971 argv += optind;
6973 if (argc != 1)
6974 usage_blame();
6976 error = got_repo_pack_fds_open(&pack_fds);
6977 if (error != NULL)
6978 goto done;
6980 if (repo_path == NULL) {
6981 cwd = getcwd(NULL, 0);
6982 if (cwd == NULL)
6983 return got_error_from_errno("getcwd");
6984 error = got_worktree_open(&worktree, cwd);
6985 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6986 goto done;
6987 if (worktree)
6988 repo_path =
6989 strdup(got_worktree_get_repo_path(worktree));
6990 else
6991 repo_path = strdup(cwd);
6992 if (repo_path == NULL) {
6993 error = got_error_from_errno("strdup");
6994 goto done;
6998 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6999 if (error != NULL)
7000 goto done;
7002 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7003 worktree);
7004 if (error)
7005 goto done;
7007 init_curses();
7009 error = apply_unveil(got_repo_get_path(repo), NULL);
7010 if (error)
7011 goto done;
7013 error = tog_load_refs(repo, 0);
7014 if (error)
7015 goto done;
7017 if (commit_id_str == NULL) {
7018 struct got_reference *head_ref;
7019 error = got_ref_open(&head_ref, repo, worktree ?
7020 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7021 if (error != NULL)
7022 goto done;
7023 error = got_ref_resolve(&commit_id, repo, head_ref);
7024 got_ref_close(head_ref);
7025 } else {
7026 error = got_repo_match_object_id(&commit_id, NULL,
7027 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7029 if (error != NULL)
7030 goto done;
7032 error = got_object_open_as_commit(&commit, repo, commit_id);
7033 if (error)
7034 goto done;
7036 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7037 commit, repo);
7038 if (error)
7039 goto done;
7041 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7042 if (view == NULL) {
7043 error = got_error_from_errno("view_open");
7044 goto done;
7046 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7047 commit_id, repo);
7048 if (error != NULL) {
7049 if (view->close == NULL)
7050 close_blame_view(view);
7051 view_close(view);
7052 goto done;
7054 if (worktree) {
7055 /* Release work tree lock. */
7056 got_worktree_close(worktree);
7057 worktree = NULL;
7059 error = view_loop(view);
7060 done:
7061 free(repo_path);
7062 free(in_repo_path);
7063 free(link_target);
7064 free(cwd);
7065 free(commit_id);
7066 if (commit)
7067 got_object_commit_close(commit);
7068 if (worktree)
7069 got_worktree_close(worktree);
7070 if (repo) {
7071 const struct got_error *close_err = got_repo_close(repo);
7072 if (error == NULL)
7073 error = close_err;
7075 if (pack_fds) {
7076 const struct got_error *pack_err =
7077 got_repo_pack_fds_close(pack_fds);
7078 if (error == NULL)
7079 error = pack_err;
7081 tog_free_refs();
7082 return error;
7085 static const struct got_error *
7086 draw_tree_entries(struct tog_view *view, const char *parent_path)
7088 struct tog_tree_view_state *s = &view->state.tree;
7089 const struct got_error *err = NULL;
7090 struct got_tree_entry *te;
7091 wchar_t *wline;
7092 char *index = NULL;
7093 struct tog_color *tc;
7094 int width, n, nentries, scrollx, i = 1;
7095 int limit = view->nlines;
7097 s->ndisplayed = 0;
7098 if (view_is_hsplit_top(view))
7099 --limit; /* border */
7101 werase(view->window);
7103 if (limit == 0)
7104 return NULL;
7106 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7107 0, 0);
7108 if (err)
7109 return err;
7110 if (view_needs_focus_indication(view))
7111 wstandout(view->window);
7112 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7113 if (tc)
7114 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7115 waddwstr(view->window, wline);
7116 free(wline);
7117 wline = NULL;
7118 while (width++ < view->ncols)
7119 waddch(view->window, ' ');
7120 if (tc)
7121 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7122 if (view_needs_focus_indication(view))
7123 wstandend(view->window);
7124 if (--limit <= 0)
7125 return NULL;
7127 i += s->selected;
7128 if (s->first_displayed_entry) {
7129 i += got_tree_entry_get_index(s->first_displayed_entry);
7130 if (s->tree != s->root)
7131 ++i; /* account for ".." entry */
7133 nentries = got_object_tree_get_nentries(s->tree);
7134 if (asprintf(&index, "[%d/%d] %s",
7135 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7136 return got_error_from_errno("asprintf");
7137 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7138 free(index);
7139 if (err)
7140 return err;
7141 waddwstr(view->window, wline);
7142 free(wline);
7143 wline = NULL;
7144 if (width < view->ncols - 1)
7145 waddch(view->window, '\n');
7146 if (--limit <= 0)
7147 return NULL;
7148 waddch(view->window, '\n');
7149 if (--limit <= 0)
7150 return NULL;
7152 if (s->first_displayed_entry == NULL) {
7153 te = got_object_tree_get_first_entry(s->tree);
7154 if (s->selected == 0) {
7155 if (view->focussed)
7156 wstandout(view->window);
7157 s->selected_entry = NULL;
7159 waddstr(view->window, " ..\n"); /* parent directory */
7160 if (s->selected == 0 && view->focussed)
7161 wstandend(view->window);
7162 s->ndisplayed++;
7163 if (--limit <= 0)
7164 return NULL;
7165 n = 1;
7166 } else {
7167 n = 0;
7168 te = s->first_displayed_entry;
7171 view->maxx = 0;
7172 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7173 char *line = NULL, *id_str = NULL, *link_target = NULL;
7174 const char *modestr = "";
7175 mode_t mode;
7177 te = got_object_tree_get_entry(s->tree, i);
7178 mode = got_tree_entry_get_mode(te);
7180 if (s->show_ids) {
7181 err = got_object_id_str(&id_str,
7182 got_tree_entry_get_id(te));
7183 if (err)
7184 return got_error_from_errno(
7185 "got_object_id_str");
7187 if (got_object_tree_entry_is_submodule(te))
7188 modestr = "$";
7189 else if (S_ISLNK(mode)) {
7190 int i;
7192 err = got_tree_entry_get_symlink_target(&link_target,
7193 te, s->repo);
7194 if (err) {
7195 free(id_str);
7196 return err;
7198 for (i = 0; i < strlen(link_target); i++) {
7199 if (!isprint((unsigned char)link_target[i]))
7200 link_target[i] = '?';
7202 modestr = "@";
7204 else if (S_ISDIR(mode))
7205 modestr = "/";
7206 else if (mode & S_IXUSR)
7207 modestr = "*";
7208 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7209 got_tree_entry_get_name(te), modestr,
7210 link_target ? " -> ": "",
7211 link_target ? link_target : "") == -1) {
7212 free(id_str);
7213 free(link_target);
7214 return got_error_from_errno("asprintf");
7216 free(id_str);
7217 free(link_target);
7219 /* use full line width to determine view->maxx */
7220 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7221 if (err) {
7222 free(line);
7223 break;
7225 view->maxx = MAX(view->maxx, width);
7226 free(wline);
7227 wline = NULL;
7229 err = format_line(&wline, &width, &scrollx, line, view->x,
7230 view->ncols, 0, 0);
7231 if (err) {
7232 free(line);
7233 break;
7235 if (n == s->selected) {
7236 if (view->focussed)
7237 wstandout(view->window);
7238 s->selected_entry = te;
7240 tc = match_color(&s->colors, line);
7241 if (tc)
7242 wattr_on(view->window,
7243 COLOR_PAIR(tc->colorpair), NULL);
7244 waddwstr(view->window, &wline[scrollx]);
7245 if (tc)
7246 wattr_off(view->window,
7247 COLOR_PAIR(tc->colorpair), NULL);
7248 if (width < view->ncols)
7249 waddch(view->window, '\n');
7250 if (n == s->selected && view->focussed)
7251 wstandend(view->window);
7252 free(line);
7253 free(wline);
7254 wline = NULL;
7255 n++;
7256 s->ndisplayed++;
7257 s->last_displayed_entry = te;
7258 if (--limit <= 0)
7259 break;
7262 return err;
7265 static void
7266 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7268 struct got_tree_entry *te;
7269 int isroot = s->tree == s->root;
7270 int i = 0;
7272 if (s->first_displayed_entry == NULL)
7273 return;
7275 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7276 while (i++ < maxscroll) {
7277 if (te == NULL) {
7278 if (!isroot)
7279 s->first_displayed_entry = NULL;
7280 break;
7282 s->first_displayed_entry = te;
7283 te = got_tree_entry_get_prev(s->tree, te);
7287 static const struct got_error *
7288 tree_scroll_down(struct tog_view *view, int maxscroll)
7290 struct tog_tree_view_state *s = &view->state.tree;
7291 struct got_tree_entry *next, *last;
7292 int n = 0;
7294 if (s->first_displayed_entry)
7295 next = got_tree_entry_get_next(s->tree,
7296 s->first_displayed_entry);
7297 else
7298 next = got_object_tree_get_first_entry(s->tree);
7300 last = s->last_displayed_entry;
7301 while (next && n++ < maxscroll) {
7302 if (last) {
7303 s->last_displayed_entry = last;
7304 last = got_tree_entry_get_next(s->tree, last);
7306 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7307 s->first_displayed_entry = next;
7308 next = got_tree_entry_get_next(s->tree, next);
7312 return NULL;
7315 static const struct got_error *
7316 tree_entry_path(char **path, struct tog_parent_trees *parents,
7317 struct got_tree_entry *te)
7319 const struct got_error *err = NULL;
7320 struct tog_parent_tree *pt;
7321 size_t len = 2; /* for leading slash and NUL */
7323 TAILQ_FOREACH(pt, parents, entry)
7324 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7325 + 1 /* slash */;
7326 if (te)
7327 len += strlen(got_tree_entry_get_name(te));
7329 *path = calloc(1, len);
7330 if (path == NULL)
7331 return got_error_from_errno("calloc");
7333 (*path)[0] = '/';
7334 pt = TAILQ_LAST(parents, tog_parent_trees);
7335 while (pt) {
7336 const char *name = got_tree_entry_get_name(pt->selected_entry);
7337 if (strlcat(*path, name, len) >= len) {
7338 err = got_error(GOT_ERR_NO_SPACE);
7339 goto done;
7341 if (strlcat(*path, "/", len) >= len) {
7342 err = got_error(GOT_ERR_NO_SPACE);
7343 goto done;
7345 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7347 if (te) {
7348 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7349 err = got_error(GOT_ERR_NO_SPACE);
7350 goto done;
7353 done:
7354 if (err) {
7355 free(*path);
7356 *path = NULL;
7358 return err;
7361 static const struct got_error *
7362 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7363 struct got_tree_entry *te, struct tog_parent_trees *parents,
7364 struct got_object_id *commit_id, struct got_repository *repo)
7366 const struct got_error *err = NULL;
7367 char *path;
7368 struct tog_view *blame_view;
7370 *new_view = NULL;
7372 err = tree_entry_path(&path, parents, te);
7373 if (err)
7374 return err;
7376 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7377 if (blame_view == NULL) {
7378 err = got_error_from_errno("view_open");
7379 goto done;
7382 err = open_blame_view(blame_view, path, commit_id, repo);
7383 if (err) {
7384 if (err->code == GOT_ERR_CANCELLED)
7385 err = NULL;
7386 view_close(blame_view);
7387 } else
7388 *new_view = blame_view;
7389 done:
7390 free(path);
7391 return err;
7394 static const struct got_error *
7395 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7396 struct tog_tree_view_state *s)
7398 struct tog_view *log_view;
7399 const struct got_error *err = NULL;
7400 char *path;
7402 *new_view = NULL;
7404 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7405 if (log_view == NULL)
7406 return got_error_from_errno("view_open");
7408 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7409 if (err)
7410 return err;
7412 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7413 path, 0);
7414 if (err)
7415 view_close(log_view);
7416 else
7417 *new_view = log_view;
7418 free(path);
7419 return err;
7422 static const struct got_error *
7423 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7424 const char *head_ref_name, struct got_repository *repo)
7426 const struct got_error *err = NULL;
7427 char *commit_id_str = NULL;
7428 struct tog_tree_view_state *s = &view->state.tree;
7429 struct got_commit_object *commit = NULL;
7431 TAILQ_INIT(&s->parents);
7432 STAILQ_INIT(&s->colors);
7434 s->commit_id = got_object_id_dup(commit_id);
7435 if (s->commit_id == NULL) {
7436 err = got_error_from_errno("got_object_id_dup");
7437 goto done;
7440 err = got_object_open_as_commit(&commit, repo, commit_id);
7441 if (err)
7442 goto done;
7445 * The root is opened here and will be closed when the view is closed.
7446 * Any visited subtrees and their path-wise parents are opened and
7447 * closed on demand.
7449 err = got_object_open_as_tree(&s->root, repo,
7450 got_object_commit_get_tree_id(commit));
7451 if (err)
7452 goto done;
7453 s->tree = s->root;
7455 err = got_object_id_str(&commit_id_str, commit_id);
7456 if (err != NULL)
7457 goto done;
7459 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7460 err = got_error_from_errno("asprintf");
7461 goto done;
7464 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7465 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7466 if (head_ref_name) {
7467 s->head_ref_name = strdup(head_ref_name);
7468 if (s->head_ref_name == NULL) {
7469 err = got_error_from_errno("strdup");
7470 goto done;
7473 s->repo = repo;
7475 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7476 err = add_color(&s->colors, "\\$$",
7477 TOG_COLOR_TREE_SUBMODULE,
7478 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7479 if (err)
7480 goto done;
7481 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7482 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7483 if (err)
7484 goto done;
7485 err = add_color(&s->colors, "/$",
7486 TOG_COLOR_TREE_DIRECTORY,
7487 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7488 if (err)
7489 goto done;
7491 err = add_color(&s->colors, "\\*$",
7492 TOG_COLOR_TREE_EXECUTABLE,
7493 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7494 if (err)
7495 goto done;
7497 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7498 get_color_value("TOG_COLOR_COMMIT"));
7499 if (err)
7500 goto done;
7503 view->show = show_tree_view;
7504 view->input = input_tree_view;
7505 view->close = close_tree_view;
7506 view->search_start = search_start_tree_view;
7507 view->search_next = search_next_tree_view;
7508 done:
7509 free(commit_id_str);
7510 if (commit)
7511 got_object_commit_close(commit);
7512 if (err) {
7513 if (view->close == NULL)
7514 close_tree_view(view);
7515 view_close(view);
7517 return err;
7520 static const struct got_error *
7521 close_tree_view(struct tog_view *view)
7523 struct tog_tree_view_state *s = &view->state.tree;
7525 free_colors(&s->colors);
7526 free(s->tree_label);
7527 s->tree_label = NULL;
7528 free(s->commit_id);
7529 s->commit_id = NULL;
7530 free(s->head_ref_name);
7531 s->head_ref_name = NULL;
7532 while (!TAILQ_EMPTY(&s->parents)) {
7533 struct tog_parent_tree *parent;
7534 parent = TAILQ_FIRST(&s->parents);
7535 TAILQ_REMOVE(&s->parents, parent, entry);
7536 if (parent->tree != s->root)
7537 got_object_tree_close(parent->tree);
7538 free(parent);
7541 if (s->tree != NULL && s->tree != s->root)
7542 got_object_tree_close(s->tree);
7543 if (s->root)
7544 got_object_tree_close(s->root);
7545 return NULL;
7548 static const struct got_error *
7549 search_start_tree_view(struct tog_view *view)
7551 struct tog_tree_view_state *s = &view->state.tree;
7553 s->matched_entry = NULL;
7554 return NULL;
7557 static int
7558 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7560 regmatch_t regmatch;
7562 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7563 0) == 0;
7566 static const struct got_error *
7567 search_next_tree_view(struct tog_view *view)
7569 struct tog_tree_view_state *s = &view->state.tree;
7570 struct got_tree_entry *te = NULL;
7572 if (!view->searching) {
7573 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7574 return NULL;
7577 if (s->matched_entry) {
7578 if (view->searching == TOG_SEARCH_FORWARD) {
7579 if (s->selected_entry)
7580 te = got_tree_entry_get_next(s->tree,
7581 s->selected_entry);
7582 else
7583 te = got_object_tree_get_first_entry(s->tree);
7584 } else {
7585 if (s->selected_entry == NULL)
7586 te = got_object_tree_get_last_entry(s->tree);
7587 else
7588 te = got_tree_entry_get_prev(s->tree,
7589 s->selected_entry);
7591 } else {
7592 if (s->selected_entry)
7593 te = s->selected_entry;
7594 else if (view->searching == TOG_SEARCH_FORWARD)
7595 te = got_object_tree_get_first_entry(s->tree);
7596 else
7597 te = got_object_tree_get_last_entry(s->tree);
7600 while (1) {
7601 if (te == NULL) {
7602 if (s->matched_entry == NULL) {
7603 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7604 return NULL;
7606 if (view->searching == TOG_SEARCH_FORWARD)
7607 te = got_object_tree_get_first_entry(s->tree);
7608 else
7609 te = got_object_tree_get_last_entry(s->tree);
7612 if (match_tree_entry(te, &view->regex)) {
7613 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7614 s->matched_entry = te;
7615 break;
7618 if (view->searching == TOG_SEARCH_FORWARD)
7619 te = got_tree_entry_get_next(s->tree, te);
7620 else
7621 te = got_tree_entry_get_prev(s->tree, te);
7624 if (s->matched_entry) {
7625 s->first_displayed_entry = s->matched_entry;
7626 s->selected = 0;
7629 return NULL;
7632 static const struct got_error *
7633 show_tree_view(struct tog_view *view)
7635 const struct got_error *err = NULL;
7636 struct tog_tree_view_state *s = &view->state.tree;
7637 char *parent_path;
7639 err = tree_entry_path(&parent_path, &s->parents, NULL);
7640 if (err)
7641 return err;
7643 err = draw_tree_entries(view, parent_path);
7644 free(parent_path);
7646 view_border(view);
7647 return err;
7650 static const struct got_error *
7651 tree_goto_line(struct tog_view *view, int nlines)
7653 const struct got_error *err = NULL;
7654 struct tog_tree_view_state *s = &view->state.tree;
7655 struct got_tree_entry **fte, **lte, **ste;
7656 int g, last, first = 1, i = 1;
7657 int root = s->tree == s->root;
7658 int off = root ? 1 : 2;
7660 g = view->gline;
7661 view->gline = 0;
7663 if (g == 0)
7664 g = 1;
7665 else if (g > got_object_tree_get_nentries(s->tree))
7666 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7668 fte = &s->first_displayed_entry;
7669 lte = &s->last_displayed_entry;
7670 ste = &s->selected_entry;
7672 if (*fte != NULL) {
7673 first = got_tree_entry_get_index(*fte);
7674 first += off; /* account for ".." */
7676 last = got_tree_entry_get_index(*lte);
7677 last += off;
7679 if (g >= first && g <= last && g - first < nlines) {
7680 s->selected = g - first;
7681 return NULL; /* gline is on the current page */
7684 if (*ste != NULL) {
7685 i = got_tree_entry_get_index(*ste);
7686 i += off;
7689 if (i < g) {
7690 err = tree_scroll_down(view, g - i);
7691 if (err)
7692 return err;
7693 if (got_tree_entry_get_index(*lte) >=
7694 got_object_tree_get_nentries(s->tree) - 1 &&
7695 first + s->selected < g &&
7696 s->selected < s->ndisplayed - 1) {
7697 first = got_tree_entry_get_index(*fte);
7698 first += off;
7699 s->selected = g - first;
7701 } else if (i > g)
7702 tree_scroll_up(s, i - g);
7704 if (g < nlines &&
7705 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7706 s->selected = g - 1;
7708 return NULL;
7711 static const struct got_error *
7712 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7714 const struct got_error *err = NULL;
7715 struct tog_tree_view_state *s = &view->state.tree;
7716 struct got_tree_entry *te;
7717 int n, nscroll = view->nlines - 3;
7719 if (view->gline)
7720 return tree_goto_line(view, nscroll);
7722 switch (ch) {
7723 case '0':
7724 case '$':
7725 case KEY_RIGHT:
7726 case 'l':
7727 case KEY_LEFT:
7728 case 'h':
7729 horizontal_scroll_input(view, ch);
7730 break;
7731 case 'i':
7732 s->show_ids = !s->show_ids;
7733 view->count = 0;
7734 break;
7735 case 'L':
7736 view->count = 0;
7737 if (!s->selected_entry)
7738 break;
7739 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7740 break;
7741 case 'R':
7742 view->count = 0;
7743 err = view_request_new(new_view, view, TOG_VIEW_REF);
7744 break;
7745 case 'g':
7746 case '=':
7747 case KEY_HOME:
7748 s->selected = 0;
7749 view->count = 0;
7750 if (s->tree == s->root)
7751 s->first_displayed_entry =
7752 got_object_tree_get_first_entry(s->tree);
7753 else
7754 s->first_displayed_entry = NULL;
7755 break;
7756 case 'G':
7757 case '*':
7758 case KEY_END: {
7759 int eos = view->nlines - 3;
7761 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7762 --eos; /* border */
7763 s->selected = 0;
7764 view->count = 0;
7765 te = got_object_tree_get_last_entry(s->tree);
7766 for (n = 0; n < eos; n++) {
7767 if (te == NULL) {
7768 if (s->tree != s->root) {
7769 s->first_displayed_entry = NULL;
7770 n++;
7772 break;
7774 s->first_displayed_entry = te;
7775 te = got_tree_entry_get_prev(s->tree, te);
7777 if (n > 0)
7778 s->selected = n - 1;
7779 break;
7781 case 'k':
7782 case KEY_UP:
7783 case CTRL('p'):
7784 if (s->selected > 0) {
7785 s->selected--;
7786 break;
7788 tree_scroll_up(s, 1);
7789 if (s->selected_entry == NULL ||
7790 (s->tree == s->root && s->selected_entry ==
7791 got_object_tree_get_first_entry(s->tree)))
7792 view->count = 0;
7793 break;
7794 case CTRL('u'):
7795 case 'u':
7796 nscroll /= 2;
7797 /* FALL THROUGH */
7798 case KEY_PPAGE:
7799 case CTRL('b'):
7800 case 'b':
7801 if (s->tree == s->root) {
7802 if (got_object_tree_get_first_entry(s->tree) ==
7803 s->first_displayed_entry)
7804 s->selected -= MIN(s->selected, nscroll);
7805 } else {
7806 if (s->first_displayed_entry == NULL)
7807 s->selected -= MIN(s->selected, nscroll);
7809 tree_scroll_up(s, MAX(0, nscroll));
7810 if (s->selected_entry == NULL ||
7811 (s->tree == s->root && s->selected_entry ==
7812 got_object_tree_get_first_entry(s->tree)))
7813 view->count = 0;
7814 break;
7815 case 'j':
7816 case KEY_DOWN:
7817 case CTRL('n'):
7818 if (s->selected < s->ndisplayed - 1) {
7819 s->selected++;
7820 break;
7822 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7823 == NULL) {
7824 /* can't scroll any further */
7825 view->count = 0;
7826 break;
7828 tree_scroll_down(view, 1);
7829 break;
7830 case CTRL('d'):
7831 case 'd':
7832 nscroll /= 2;
7833 /* FALL THROUGH */
7834 case KEY_NPAGE:
7835 case CTRL('f'):
7836 case 'f':
7837 case ' ':
7838 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7839 == NULL) {
7840 /* can't scroll any further; move cursor down */
7841 if (s->selected < s->ndisplayed - 1)
7842 s->selected += MIN(nscroll,
7843 s->ndisplayed - s->selected - 1);
7844 else
7845 view->count = 0;
7846 break;
7848 tree_scroll_down(view, nscroll);
7849 break;
7850 case KEY_ENTER:
7851 case '\r':
7852 case KEY_BACKSPACE:
7853 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7854 struct tog_parent_tree *parent;
7855 /* user selected '..' */
7856 if (s->tree == s->root) {
7857 view->count = 0;
7858 break;
7860 parent = TAILQ_FIRST(&s->parents);
7861 TAILQ_REMOVE(&s->parents, parent,
7862 entry);
7863 got_object_tree_close(s->tree);
7864 s->tree = parent->tree;
7865 s->first_displayed_entry =
7866 parent->first_displayed_entry;
7867 s->selected_entry =
7868 parent->selected_entry;
7869 s->selected = parent->selected;
7870 if (s->selected > view->nlines - 3) {
7871 err = offset_selection_down(view);
7872 if (err)
7873 break;
7875 free(parent);
7876 } else if (S_ISDIR(got_tree_entry_get_mode(
7877 s->selected_entry))) {
7878 struct got_tree_object *subtree;
7879 view->count = 0;
7880 err = got_object_open_as_tree(&subtree, s->repo,
7881 got_tree_entry_get_id(s->selected_entry));
7882 if (err)
7883 break;
7884 err = tree_view_visit_subtree(s, subtree);
7885 if (err) {
7886 got_object_tree_close(subtree);
7887 break;
7889 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7890 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7891 break;
7892 case KEY_RESIZE:
7893 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7894 s->selected = view->nlines - 4;
7895 view->count = 0;
7896 break;
7897 default:
7898 view->count = 0;
7899 break;
7902 return err;
7905 __dead static void
7906 usage_tree(void)
7908 endwin();
7909 fprintf(stderr,
7910 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7911 getprogname());
7912 exit(1);
7915 static const struct got_error *
7916 cmd_tree(int argc, char *argv[])
7918 const struct got_error *error;
7919 struct got_repository *repo = NULL;
7920 struct got_worktree *worktree = NULL;
7921 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7922 struct got_object_id *commit_id = NULL;
7923 struct got_commit_object *commit = NULL;
7924 const char *commit_id_arg = NULL;
7925 char *label = NULL;
7926 struct got_reference *ref = NULL;
7927 const char *head_ref_name = NULL;
7928 int ch;
7929 struct tog_view *view;
7930 int *pack_fds = NULL;
7932 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7933 switch (ch) {
7934 case 'c':
7935 commit_id_arg = optarg;
7936 break;
7937 case 'r':
7938 repo_path = realpath(optarg, NULL);
7939 if (repo_path == NULL)
7940 return got_error_from_errno2("realpath",
7941 optarg);
7942 break;
7943 default:
7944 usage_tree();
7945 /* NOTREACHED */
7949 argc -= optind;
7950 argv += optind;
7952 if (argc > 1)
7953 usage_tree();
7955 error = got_repo_pack_fds_open(&pack_fds);
7956 if (error != NULL)
7957 goto done;
7959 if (repo_path == NULL) {
7960 cwd = getcwd(NULL, 0);
7961 if (cwd == NULL)
7962 return got_error_from_errno("getcwd");
7963 error = got_worktree_open(&worktree, cwd);
7964 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7965 goto done;
7966 if (worktree)
7967 repo_path =
7968 strdup(got_worktree_get_repo_path(worktree));
7969 else
7970 repo_path = strdup(cwd);
7971 if (repo_path == NULL) {
7972 error = got_error_from_errno("strdup");
7973 goto done;
7977 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7978 if (error != NULL)
7979 goto done;
7981 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7982 repo, worktree);
7983 if (error)
7984 goto done;
7986 init_curses();
7988 error = apply_unveil(got_repo_get_path(repo), NULL);
7989 if (error)
7990 goto done;
7992 error = tog_load_refs(repo, 0);
7993 if (error)
7994 goto done;
7996 if (commit_id_arg == NULL) {
7997 error = got_repo_match_object_id(&commit_id, &label,
7998 worktree ? got_worktree_get_head_ref_name(worktree) :
7999 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8000 if (error)
8001 goto done;
8002 head_ref_name = label;
8003 } else {
8004 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8005 if (error == NULL)
8006 head_ref_name = got_ref_get_name(ref);
8007 else if (error->code != GOT_ERR_NOT_REF)
8008 goto done;
8009 error = got_repo_match_object_id(&commit_id, NULL,
8010 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8011 if (error)
8012 goto done;
8015 error = got_object_open_as_commit(&commit, repo, commit_id);
8016 if (error)
8017 goto done;
8019 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8020 if (view == NULL) {
8021 error = got_error_from_errno("view_open");
8022 goto done;
8024 error = open_tree_view(view, commit_id, head_ref_name, repo);
8025 if (error)
8026 goto done;
8027 if (!got_path_is_root_dir(in_repo_path)) {
8028 error = tree_view_walk_path(&view->state.tree, commit,
8029 in_repo_path);
8030 if (error)
8031 goto done;
8034 if (worktree) {
8035 /* Release work tree lock. */
8036 got_worktree_close(worktree);
8037 worktree = NULL;
8039 error = view_loop(view);
8040 done:
8041 free(repo_path);
8042 free(cwd);
8043 free(commit_id);
8044 free(label);
8045 if (ref)
8046 got_ref_close(ref);
8047 if (repo) {
8048 const struct got_error *close_err = got_repo_close(repo);
8049 if (error == NULL)
8050 error = close_err;
8052 if (pack_fds) {
8053 const struct got_error *pack_err =
8054 got_repo_pack_fds_close(pack_fds);
8055 if (error == NULL)
8056 error = pack_err;
8058 tog_free_refs();
8059 return error;
8062 static const struct got_error *
8063 ref_view_load_refs(struct tog_ref_view_state *s)
8065 struct got_reflist_entry *sre;
8066 struct tog_reflist_entry *re;
8068 s->nrefs = 0;
8069 TAILQ_FOREACH(sre, &tog_refs, entry) {
8070 if (strncmp(got_ref_get_name(sre->ref),
8071 "refs/got/", 9) == 0 &&
8072 strncmp(got_ref_get_name(sre->ref),
8073 "refs/got/backup/", 16) != 0)
8074 continue;
8076 re = malloc(sizeof(*re));
8077 if (re == NULL)
8078 return got_error_from_errno("malloc");
8080 re->ref = got_ref_dup(sre->ref);
8081 if (re->ref == NULL)
8082 return got_error_from_errno("got_ref_dup");
8083 re->idx = s->nrefs++;
8084 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8087 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8088 return NULL;
8091 static void
8092 ref_view_free_refs(struct tog_ref_view_state *s)
8094 struct tog_reflist_entry *re;
8096 while (!TAILQ_EMPTY(&s->refs)) {
8097 re = TAILQ_FIRST(&s->refs);
8098 TAILQ_REMOVE(&s->refs, re, entry);
8099 got_ref_close(re->ref);
8100 free(re);
8104 static const struct got_error *
8105 open_ref_view(struct tog_view *view, struct got_repository *repo)
8107 const struct got_error *err = NULL;
8108 struct tog_ref_view_state *s = &view->state.ref;
8110 s->selected_entry = 0;
8111 s->repo = repo;
8113 TAILQ_INIT(&s->refs);
8114 STAILQ_INIT(&s->colors);
8116 err = ref_view_load_refs(s);
8117 if (err)
8118 goto done;
8120 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8121 err = add_color(&s->colors, "^refs/heads/",
8122 TOG_COLOR_REFS_HEADS,
8123 get_color_value("TOG_COLOR_REFS_HEADS"));
8124 if (err)
8125 goto done;
8127 err = add_color(&s->colors, "^refs/tags/",
8128 TOG_COLOR_REFS_TAGS,
8129 get_color_value("TOG_COLOR_REFS_TAGS"));
8130 if (err)
8131 goto done;
8133 err = add_color(&s->colors, "^refs/remotes/",
8134 TOG_COLOR_REFS_REMOTES,
8135 get_color_value("TOG_COLOR_REFS_REMOTES"));
8136 if (err)
8137 goto done;
8139 err = add_color(&s->colors, "^refs/got/backup/",
8140 TOG_COLOR_REFS_BACKUP,
8141 get_color_value("TOG_COLOR_REFS_BACKUP"));
8142 if (err)
8143 goto done;
8146 view->show = show_ref_view;
8147 view->input = input_ref_view;
8148 view->close = close_ref_view;
8149 view->search_start = search_start_ref_view;
8150 view->search_next = search_next_ref_view;
8151 done:
8152 if (err) {
8153 if (view->close == NULL)
8154 close_ref_view(view);
8155 view_close(view);
8157 return err;
8160 static const struct got_error *
8161 close_ref_view(struct tog_view *view)
8163 struct tog_ref_view_state *s = &view->state.ref;
8165 ref_view_free_refs(s);
8166 free_colors(&s->colors);
8168 return NULL;
8171 static const struct got_error *
8172 resolve_reflist_entry(struct got_object_id **commit_id,
8173 struct tog_reflist_entry *re, struct got_repository *repo)
8175 const struct got_error *err = NULL;
8176 struct got_object_id *obj_id;
8177 struct got_tag_object *tag = NULL;
8178 int obj_type;
8180 *commit_id = NULL;
8182 err = got_ref_resolve(&obj_id, repo, re->ref);
8183 if (err)
8184 return err;
8186 err = got_object_get_type(&obj_type, repo, obj_id);
8187 if (err)
8188 goto done;
8190 switch (obj_type) {
8191 case GOT_OBJ_TYPE_COMMIT:
8192 *commit_id = obj_id;
8193 break;
8194 case GOT_OBJ_TYPE_TAG:
8195 err = got_object_open_as_tag(&tag, repo, obj_id);
8196 if (err)
8197 goto done;
8198 free(obj_id);
8199 err = got_object_get_type(&obj_type, repo,
8200 got_object_tag_get_object_id(tag));
8201 if (err)
8202 goto done;
8203 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8204 err = got_error(GOT_ERR_OBJ_TYPE);
8205 goto done;
8207 *commit_id = got_object_id_dup(
8208 got_object_tag_get_object_id(tag));
8209 if (*commit_id == NULL) {
8210 err = got_error_from_errno("got_object_id_dup");
8211 goto done;
8213 break;
8214 default:
8215 err = got_error(GOT_ERR_OBJ_TYPE);
8216 break;
8219 done:
8220 if (tag)
8221 got_object_tag_close(tag);
8222 if (err) {
8223 free(*commit_id);
8224 *commit_id = NULL;
8226 return err;
8229 static const struct got_error *
8230 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8231 struct tog_reflist_entry *re, struct got_repository *repo)
8233 struct tog_view *log_view;
8234 const struct got_error *err = NULL;
8235 struct got_object_id *commit_id = NULL;
8237 *new_view = NULL;
8239 err = resolve_reflist_entry(&commit_id, re, repo);
8240 if (err) {
8241 if (err->code != GOT_ERR_OBJ_TYPE)
8242 return err;
8243 else
8244 return NULL;
8247 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8248 if (log_view == NULL) {
8249 err = got_error_from_errno("view_open");
8250 goto done;
8253 err = open_log_view(log_view, commit_id, repo,
8254 got_ref_get_name(re->ref), "", 0);
8255 done:
8256 if (err)
8257 view_close(log_view);
8258 else
8259 *new_view = log_view;
8260 free(commit_id);
8261 return err;
8264 static void
8265 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8267 struct tog_reflist_entry *re;
8268 int i = 0;
8270 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8271 return;
8273 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8274 while (i++ < maxscroll) {
8275 if (re == NULL)
8276 break;
8277 s->first_displayed_entry = re;
8278 re = TAILQ_PREV(re, tog_reflist_head, entry);
8282 static const struct got_error *
8283 ref_scroll_down(struct tog_view *view, int maxscroll)
8285 struct tog_ref_view_state *s = &view->state.ref;
8286 struct tog_reflist_entry *next, *last;
8287 int n = 0;
8289 if (s->first_displayed_entry)
8290 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8291 else
8292 next = TAILQ_FIRST(&s->refs);
8294 last = s->last_displayed_entry;
8295 while (next && n++ < maxscroll) {
8296 if (last) {
8297 s->last_displayed_entry = last;
8298 last = TAILQ_NEXT(last, entry);
8300 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8301 s->first_displayed_entry = next;
8302 next = TAILQ_NEXT(next, entry);
8306 return NULL;
8309 static const struct got_error *
8310 search_start_ref_view(struct tog_view *view)
8312 struct tog_ref_view_state *s = &view->state.ref;
8314 s->matched_entry = NULL;
8315 return NULL;
8318 static int
8319 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8321 regmatch_t regmatch;
8323 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8324 0) == 0;
8327 static const struct got_error *
8328 search_next_ref_view(struct tog_view *view)
8330 struct tog_ref_view_state *s = &view->state.ref;
8331 struct tog_reflist_entry *re = NULL;
8333 if (!view->searching) {
8334 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8335 return NULL;
8338 if (s->matched_entry) {
8339 if (view->searching == TOG_SEARCH_FORWARD) {
8340 if (s->selected_entry)
8341 re = TAILQ_NEXT(s->selected_entry, entry);
8342 else
8343 re = TAILQ_PREV(s->selected_entry,
8344 tog_reflist_head, entry);
8345 } else {
8346 if (s->selected_entry == NULL)
8347 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8348 else
8349 re = TAILQ_PREV(s->selected_entry,
8350 tog_reflist_head, entry);
8352 } else {
8353 if (s->selected_entry)
8354 re = s->selected_entry;
8355 else if (view->searching == TOG_SEARCH_FORWARD)
8356 re = TAILQ_FIRST(&s->refs);
8357 else
8358 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8361 while (1) {
8362 if (re == NULL) {
8363 if (s->matched_entry == NULL) {
8364 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8365 return NULL;
8367 if (view->searching == TOG_SEARCH_FORWARD)
8368 re = TAILQ_FIRST(&s->refs);
8369 else
8370 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8373 if (match_reflist_entry(re, &view->regex)) {
8374 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8375 s->matched_entry = re;
8376 break;
8379 if (view->searching == TOG_SEARCH_FORWARD)
8380 re = TAILQ_NEXT(re, entry);
8381 else
8382 re = TAILQ_PREV(re, tog_reflist_head, entry);
8385 if (s->matched_entry) {
8386 s->first_displayed_entry = s->matched_entry;
8387 s->selected = 0;
8390 return NULL;
8393 static const struct got_error *
8394 show_ref_view(struct tog_view *view)
8396 const struct got_error *err = NULL;
8397 struct tog_ref_view_state *s = &view->state.ref;
8398 struct tog_reflist_entry *re;
8399 char *line = NULL;
8400 wchar_t *wline;
8401 struct tog_color *tc;
8402 int width, n, scrollx;
8403 int limit = view->nlines;
8405 werase(view->window);
8407 s->ndisplayed = 0;
8408 if (view_is_hsplit_top(view))
8409 --limit; /* border */
8411 if (limit == 0)
8412 return NULL;
8414 re = s->first_displayed_entry;
8416 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8417 s->nrefs) == -1)
8418 return got_error_from_errno("asprintf");
8420 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8421 if (err) {
8422 free(line);
8423 return err;
8425 if (view_needs_focus_indication(view))
8426 wstandout(view->window);
8427 waddwstr(view->window, wline);
8428 while (width++ < view->ncols)
8429 waddch(view->window, ' ');
8430 if (view_needs_focus_indication(view))
8431 wstandend(view->window);
8432 free(wline);
8433 wline = NULL;
8434 free(line);
8435 line = NULL;
8436 if (--limit <= 0)
8437 return NULL;
8439 n = 0;
8440 view->maxx = 0;
8441 while (re && limit > 0) {
8442 char *line = NULL;
8443 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8445 if (s->show_date) {
8446 struct got_commit_object *ci;
8447 struct got_tag_object *tag;
8448 struct got_object_id *id;
8449 struct tm tm;
8450 time_t t;
8452 err = got_ref_resolve(&id, s->repo, re->ref);
8453 if (err)
8454 return err;
8455 err = got_object_open_as_tag(&tag, s->repo, id);
8456 if (err) {
8457 if (err->code != GOT_ERR_OBJ_TYPE) {
8458 free(id);
8459 return err;
8461 err = got_object_open_as_commit(&ci, s->repo,
8462 id);
8463 if (err) {
8464 free(id);
8465 return err;
8467 t = got_object_commit_get_committer_time(ci);
8468 got_object_commit_close(ci);
8469 } else {
8470 t = got_object_tag_get_tagger_time(tag);
8471 got_object_tag_close(tag);
8473 free(id);
8474 if (gmtime_r(&t, &tm) == NULL)
8475 return got_error_from_errno("gmtime_r");
8476 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8477 return got_error(GOT_ERR_NO_SPACE);
8479 if (got_ref_is_symbolic(re->ref)) {
8480 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8481 ymd : "", got_ref_get_name(re->ref),
8482 got_ref_get_symref_target(re->ref)) == -1)
8483 return got_error_from_errno("asprintf");
8484 } else if (s->show_ids) {
8485 struct got_object_id *id;
8486 char *id_str;
8487 err = got_ref_resolve(&id, s->repo, re->ref);
8488 if (err)
8489 return err;
8490 err = got_object_id_str(&id_str, id);
8491 if (err) {
8492 free(id);
8493 return err;
8495 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8496 got_ref_get_name(re->ref), id_str) == -1) {
8497 err = got_error_from_errno("asprintf");
8498 free(id);
8499 free(id_str);
8500 return err;
8502 free(id);
8503 free(id_str);
8504 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8505 got_ref_get_name(re->ref)) == -1)
8506 return got_error_from_errno("asprintf");
8508 /* use full line width to determine view->maxx */
8509 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8510 if (err) {
8511 free(line);
8512 return err;
8514 view->maxx = MAX(view->maxx, width);
8515 free(wline);
8516 wline = NULL;
8518 err = format_line(&wline, &width, &scrollx, line, view->x,
8519 view->ncols, 0, 0);
8520 if (err) {
8521 free(line);
8522 return err;
8524 if (n == s->selected) {
8525 if (view->focussed)
8526 wstandout(view->window);
8527 s->selected_entry = re;
8529 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8530 if (tc)
8531 wattr_on(view->window,
8532 COLOR_PAIR(tc->colorpair), NULL);
8533 waddwstr(view->window, &wline[scrollx]);
8534 if (tc)
8535 wattr_off(view->window,
8536 COLOR_PAIR(tc->colorpair), NULL);
8537 if (width < view->ncols)
8538 waddch(view->window, '\n');
8539 if (n == s->selected && view->focussed)
8540 wstandend(view->window);
8541 free(line);
8542 free(wline);
8543 wline = NULL;
8544 n++;
8545 s->ndisplayed++;
8546 s->last_displayed_entry = re;
8548 limit--;
8549 re = TAILQ_NEXT(re, entry);
8552 view_border(view);
8553 return err;
8556 static const struct got_error *
8557 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8558 struct tog_reflist_entry *re, struct got_repository *repo)
8560 const struct got_error *err = NULL;
8561 struct got_object_id *commit_id = NULL;
8562 struct tog_view *tree_view;
8564 *new_view = NULL;
8566 err = resolve_reflist_entry(&commit_id, re, repo);
8567 if (err) {
8568 if (err->code != GOT_ERR_OBJ_TYPE)
8569 return err;
8570 else
8571 return NULL;
8575 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8576 if (tree_view == NULL) {
8577 err = got_error_from_errno("view_open");
8578 goto done;
8581 err = open_tree_view(tree_view, commit_id,
8582 got_ref_get_name(re->ref), repo);
8583 if (err)
8584 goto done;
8586 *new_view = tree_view;
8587 done:
8588 free(commit_id);
8589 return err;
8592 static const struct got_error *
8593 ref_goto_line(struct tog_view *view, int nlines)
8595 const struct got_error *err = NULL;
8596 struct tog_ref_view_state *s = &view->state.ref;
8597 int g, idx = s->selected_entry->idx;
8599 g = view->gline;
8600 view->gline = 0;
8602 if (g == 0)
8603 g = 1;
8604 else if (g > s->nrefs)
8605 g = s->nrefs;
8607 if (g >= s->first_displayed_entry->idx + 1 &&
8608 g <= s->last_displayed_entry->idx + 1 &&
8609 g - s->first_displayed_entry->idx - 1 < nlines) {
8610 s->selected = g - s->first_displayed_entry->idx - 1;
8611 return NULL;
8614 if (idx + 1 < g) {
8615 err = ref_scroll_down(view, g - idx - 1);
8616 if (err)
8617 return err;
8618 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8619 s->first_displayed_entry->idx + s->selected < g &&
8620 s->selected < s->ndisplayed - 1)
8621 s->selected = g - s->first_displayed_entry->idx - 1;
8622 } else if (idx + 1 > g)
8623 ref_scroll_up(s, idx - g + 1);
8625 if (g < nlines && s->first_displayed_entry->idx == 0)
8626 s->selected = g - 1;
8628 return NULL;
8632 static const struct got_error *
8633 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8635 const struct got_error *err = NULL;
8636 struct tog_ref_view_state *s = &view->state.ref;
8637 struct tog_reflist_entry *re;
8638 int n, nscroll = view->nlines - 1;
8640 if (view->gline)
8641 return ref_goto_line(view, nscroll);
8643 switch (ch) {
8644 case '0':
8645 case '$':
8646 case KEY_RIGHT:
8647 case 'l':
8648 case KEY_LEFT:
8649 case 'h':
8650 horizontal_scroll_input(view, ch);
8651 break;
8652 case 'i':
8653 s->show_ids = !s->show_ids;
8654 view->count = 0;
8655 break;
8656 case 'm':
8657 s->show_date = !s->show_date;
8658 view->count = 0;
8659 break;
8660 case 'o':
8661 s->sort_by_date = !s->sort_by_date;
8662 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8663 view->count = 0;
8664 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8665 got_ref_cmp_by_commit_timestamp_descending :
8666 tog_ref_cmp_by_name, s->repo);
8667 if (err)
8668 break;
8669 got_reflist_object_id_map_free(tog_refs_idmap);
8670 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8671 &tog_refs, s->repo);
8672 if (err)
8673 break;
8674 ref_view_free_refs(s);
8675 err = ref_view_load_refs(s);
8676 break;
8677 case KEY_ENTER:
8678 case '\r':
8679 view->count = 0;
8680 if (!s->selected_entry)
8681 break;
8682 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8683 break;
8684 case 'T':
8685 view->count = 0;
8686 if (!s->selected_entry)
8687 break;
8688 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8689 break;
8690 case 'g':
8691 case '=':
8692 case KEY_HOME:
8693 s->selected = 0;
8694 view->count = 0;
8695 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8696 break;
8697 case 'G':
8698 case '*':
8699 case KEY_END: {
8700 int eos = view->nlines - 1;
8702 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8703 --eos; /* border */
8704 s->selected = 0;
8705 view->count = 0;
8706 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8707 for (n = 0; n < eos; n++) {
8708 if (re == NULL)
8709 break;
8710 s->first_displayed_entry = re;
8711 re = TAILQ_PREV(re, tog_reflist_head, entry);
8713 if (n > 0)
8714 s->selected = n - 1;
8715 break;
8717 case 'k':
8718 case KEY_UP:
8719 case CTRL('p'):
8720 if (s->selected > 0) {
8721 s->selected--;
8722 break;
8724 ref_scroll_up(s, 1);
8725 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8726 view->count = 0;
8727 break;
8728 case CTRL('u'):
8729 case 'u':
8730 nscroll /= 2;
8731 /* FALL THROUGH */
8732 case KEY_PPAGE:
8733 case CTRL('b'):
8734 case 'b':
8735 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8736 s->selected -= MIN(nscroll, s->selected);
8737 ref_scroll_up(s, MAX(0, nscroll));
8738 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8739 view->count = 0;
8740 break;
8741 case 'j':
8742 case KEY_DOWN:
8743 case CTRL('n'):
8744 if (s->selected < s->ndisplayed - 1) {
8745 s->selected++;
8746 break;
8748 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8749 /* can't scroll any further */
8750 view->count = 0;
8751 break;
8753 ref_scroll_down(view, 1);
8754 break;
8755 case CTRL('d'):
8756 case 'd':
8757 nscroll /= 2;
8758 /* FALL THROUGH */
8759 case KEY_NPAGE:
8760 case CTRL('f'):
8761 case 'f':
8762 case ' ':
8763 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8764 /* can't scroll any further; move cursor down */
8765 if (s->selected < s->ndisplayed - 1)
8766 s->selected += MIN(nscroll,
8767 s->ndisplayed - s->selected - 1);
8768 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8769 s->selected += s->ndisplayed - s->selected - 1;
8770 view->count = 0;
8771 break;
8773 ref_scroll_down(view, nscroll);
8774 break;
8775 case CTRL('l'):
8776 view->count = 0;
8777 tog_free_refs();
8778 err = tog_load_refs(s->repo, s->sort_by_date);
8779 if (err)
8780 break;
8781 ref_view_free_refs(s);
8782 err = ref_view_load_refs(s);
8783 break;
8784 case KEY_RESIZE:
8785 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8786 s->selected = view->nlines - 2;
8787 break;
8788 default:
8789 view->count = 0;
8790 break;
8793 return err;
8796 __dead static void
8797 usage_ref(void)
8799 endwin();
8800 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8801 getprogname());
8802 exit(1);
8805 static const struct got_error *
8806 cmd_ref(int argc, char *argv[])
8808 const struct got_error *error;
8809 struct got_repository *repo = NULL;
8810 struct got_worktree *worktree = NULL;
8811 char *cwd = NULL, *repo_path = NULL;
8812 int ch;
8813 struct tog_view *view;
8814 int *pack_fds = NULL;
8816 while ((ch = getopt(argc, argv, "r:")) != -1) {
8817 switch (ch) {
8818 case 'r':
8819 repo_path = realpath(optarg, NULL);
8820 if (repo_path == NULL)
8821 return got_error_from_errno2("realpath",
8822 optarg);
8823 break;
8824 default:
8825 usage_ref();
8826 /* NOTREACHED */
8830 argc -= optind;
8831 argv += optind;
8833 if (argc > 1)
8834 usage_ref();
8836 error = got_repo_pack_fds_open(&pack_fds);
8837 if (error != NULL)
8838 goto done;
8840 if (repo_path == NULL) {
8841 cwd = getcwd(NULL, 0);
8842 if (cwd == NULL)
8843 return got_error_from_errno("getcwd");
8844 error = got_worktree_open(&worktree, cwd);
8845 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8846 goto done;
8847 if (worktree)
8848 repo_path =
8849 strdup(got_worktree_get_repo_path(worktree));
8850 else
8851 repo_path = strdup(cwd);
8852 if (repo_path == NULL) {
8853 error = got_error_from_errno("strdup");
8854 goto done;
8858 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8859 if (error != NULL)
8860 goto done;
8862 init_curses();
8864 error = apply_unveil(got_repo_get_path(repo), NULL);
8865 if (error)
8866 goto done;
8868 error = tog_load_refs(repo, 0);
8869 if (error)
8870 goto done;
8872 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8873 if (view == NULL) {
8874 error = got_error_from_errno("view_open");
8875 goto done;
8878 error = open_ref_view(view, repo);
8879 if (error)
8880 goto done;
8882 if (worktree) {
8883 /* Release work tree lock. */
8884 got_worktree_close(worktree);
8885 worktree = NULL;
8887 error = view_loop(view);
8888 done:
8889 free(repo_path);
8890 free(cwd);
8891 if (repo) {
8892 const struct got_error *close_err = got_repo_close(repo);
8893 if (close_err)
8894 error = close_err;
8896 if (pack_fds) {
8897 const struct got_error *pack_err =
8898 got_repo_pack_fds_close(pack_fds);
8899 if (error == NULL)
8900 error = pack_err;
8902 tog_free_refs();
8903 return error;
8906 static const struct got_error*
8907 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8908 const char *str)
8910 size_t len;
8912 if (win == NULL)
8913 win = stdscr;
8915 len = strlen(str);
8916 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8918 if (focus)
8919 wstandout(win);
8920 if (mvwprintw(win, y, x, "%s", str) == ERR)
8921 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8922 if (focus)
8923 wstandend(win);
8925 return NULL;
8928 static const struct got_error *
8929 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8931 off_t *p;
8933 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8934 if (p == NULL) {
8935 free(*line_offsets);
8936 *line_offsets = NULL;
8937 return got_error_from_errno("reallocarray");
8940 *line_offsets = p;
8941 (*line_offsets)[*nlines] = off;
8942 ++(*nlines);
8943 return NULL;
8946 static const struct got_error *
8947 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8949 *ret = 0;
8951 for (;n > 0; --n, ++km) {
8952 char *t0, *t, *k;
8953 size_t len = 1;
8955 if (km->keys == NULL)
8956 continue;
8958 t = t0 = strdup(km->keys);
8959 if (t0 == NULL)
8960 return got_error_from_errno("strdup");
8962 len += strlen(t);
8963 while ((k = strsep(&t, " ")) != NULL)
8964 len += strlen(k) > 1 ? 2 : 0;
8965 free(t0);
8966 *ret = MAX(*ret, len);
8969 return NULL;
8973 * Write keymap section headers, keys, and key info in km to f.
8974 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8975 * wrap control and symbolic keys in guillemets, else use <>.
8977 static const struct got_error *
8978 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8980 int n, len = width;
8982 if (km->keys) {
8983 static const char *u8_glyph[] = {
8984 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8985 "\xe2\x80\xba" /* U+203A (utf8 >) */
8987 char *t0, *t, *k;
8988 int cs, s, first = 1;
8990 cs = got_locale_is_utf8();
8992 t = t0 = strdup(km->keys);
8993 if (t0 == NULL)
8994 return got_error_from_errno("strdup");
8996 len = strlen(km->keys);
8997 while ((k = strsep(&t, " ")) != NULL) {
8998 s = strlen(k) > 1; /* control or symbolic key */
8999 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9000 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9001 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9002 if (n < 0) {
9003 free(t0);
9004 return got_error_from_errno("fprintf");
9006 first = 0;
9007 len += s ? 2 : 0;
9008 *off += n;
9010 free(t0);
9012 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9013 if (n < 0)
9014 return got_error_from_errno("fprintf");
9015 *off += n;
9017 return NULL;
9020 static const struct got_error *
9021 format_help(struct tog_help_view_state *s)
9023 const struct got_error *err = NULL;
9024 off_t off = 0;
9025 int i, max, n, show = s->all;
9026 static const struct tog_key_map km[] = {
9027 #define KEYMAP_(info, type) { NULL, (info), type }
9028 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9029 GENERATE_HELP
9030 #undef KEYMAP_
9031 #undef KEY_
9034 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9035 if (err)
9036 return err;
9038 n = nitems(km);
9039 err = max_key_str(&max, km, n);
9040 if (err)
9041 return err;
9043 for (i = 0; i < n; ++i) {
9044 if (km[i].keys == NULL) {
9045 show = s->all;
9046 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9047 km[i].type == s->type || s->all)
9048 show = 1;
9050 if (show) {
9051 err = format_help_line(&off, s->f, &km[i], max);
9052 if (err)
9053 return err;
9054 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9055 if (err)
9056 return err;
9059 fputc('\n', s->f);
9060 ++off;
9061 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9062 return err;
9065 static const struct got_error *
9066 create_help(struct tog_help_view_state *s)
9068 FILE *f;
9069 const struct got_error *err;
9071 free(s->line_offsets);
9072 s->line_offsets = NULL;
9073 s->nlines = 0;
9075 f = got_opentemp();
9076 if (f == NULL)
9077 return got_error_from_errno("got_opentemp");
9078 s->f = f;
9080 err = format_help(s);
9081 if (err)
9082 return err;
9084 if (s->f && fflush(s->f) != 0)
9085 return got_error_from_errno("fflush");
9087 return NULL;
9090 static const struct got_error *
9091 search_start_help_view(struct tog_view *view)
9093 view->state.help.matched_line = 0;
9094 return NULL;
9097 static void
9098 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9099 size_t *nlines, int **first, int **last, int **match, int **selected)
9101 struct tog_help_view_state *s = &view->state.help;
9103 *f = s->f;
9104 *nlines = s->nlines;
9105 *line_offsets = s->line_offsets;
9106 *match = &s->matched_line;
9107 *first = &s->first_displayed_line;
9108 *last = &s->last_displayed_line;
9109 *selected = &s->selected_line;
9112 static const struct got_error *
9113 show_help_view(struct tog_view *view)
9115 struct tog_help_view_state *s = &view->state.help;
9116 const struct got_error *err;
9117 regmatch_t *regmatch = &view->regmatch;
9118 wchar_t *wline;
9119 char *line;
9120 ssize_t linelen;
9121 size_t linesz = 0;
9122 int width, nprinted = 0, rc = 0;
9123 int eos = view->nlines;
9125 if (view_is_hsplit_top(view))
9126 --eos; /* account for border */
9128 s->lineno = 0;
9129 rewind(s->f);
9130 werase(view->window);
9132 if (view->gline > s->nlines - 1)
9133 view->gline = s->nlines - 1;
9135 err = win_draw_center(view->window, 0, 0, view->ncols,
9136 view_needs_focus_indication(view),
9137 "tog help (press q to return to tog)");
9138 if (err)
9139 return err;
9140 if (eos <= 1)
9141 return NULL;
9142 waddstr(view->window, "\n\n");
9143 eos -= 2;
9145 s->eof = 0;
9146 view->maxx = 0;
9147 line = NULL;
9148 while (eos > 0 && nprinted < eos) {
9149 attr_t attr = 0;
9151 linelen = getline(&line, &linesz, s->f);
9152 if (linelen == -1) {
9153 if (!feof(s->f)) {
9154 free(line);
9155 return got_ferror(s->f, GOT_ERR_IO);
9157 s->eof = 1;
9158 break;
9160 if (++s->lineno < s->first_displayed_line)
9161 continue;
9162 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9163 continue;
9164 if (s->lineno == view->hiline)
9165 attr = A_STANDOUT;
9167 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9168 view->x ? 1 : 0);
9169 if (err) {
9170 free(line);
9171 return err;
9173 view->maxx = MAX(view->maxx, width);
9174 free(wline);
9175 wline = NULL;
9177 if (attr)
9178 wattron(view->window, attr);
9179 if (s->first_displayed_line + nprinted == s->matched_line &&
9180 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9181 err = add_matched_line(&width, line, view->ncols - 1, 0,
9182 view->window, view->x, regmatch);
9183 if (err) {
9184 free(line);
9185 return err;
9187 } else {
9188 int skip;
9190 err = format_line(&wline, &width, &skip, line,
9191 view->x, view->ncols, 0, view->x ? 1 : 0);
9192 if (err) {
9193 free(line);
9194 return err;
9196 waddwstr(view->window, &wline[skip]);
9197 free(wline);
9198 wline = NULL;
9200 if (s->lineno == view->hiline) {
9201 while (width++ < view->ncols)
9202 waddch(view->window, ' ');
9203 } else {
9204 if (width < view->ncols)
9205 waddch(view->window, '\n');
9207 if (attr)
9208 wattroff(view->window, attr);
9209 if (++nprinted == 1)
9210 s->first_displayed_line = s->lineno;
9212 free(line);
9213 if (nprinted > 0)
9214 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9215 else
9216 s->last_displayed_line = s->first_displayed_line;
9218 view_border(view);
9220 if (s->eof) {
9221 rc = waddnstr(view->window,
9222 "See the tog(1) manual page for full documentation",
9223 view->ncols - 1);
9224 if (rc == ERR)
9225 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9226 } else {
9227 wmove(view->window, view->nlines - 1, 0);
9228 wclrtoeol(view->window);
9229 wstandout(view->window);
9230 rc = waddnstr(view->window, "scroll down for more...",
9231 view->ncols - 1);
9232 if (rc == ERR)
9233 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9234 if (getcurx(view->window) < view->ncols - 6) {
9235 rc = wprintw(view->window, "[%.0f%%]",
9236 100.00 * s->last_displayed_line / s->nlines);
9237 if (rc == ERR)
9238 return got_error_msg(GOT_ERR_IO, "wprintw");
9240 wstandend(view->window);
9243 return NULL;
9246 static const struct got_error *
9247 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9249 struct tog_help_view_state *s = &view->state.help;
9250 const struct got_error *err = NULL;
9251 char *line = NULL;
9252 ssize_t linelen;
9253 size_t linesz = 0;
9254 int eos, nscroll;
9256 eos = nscroll = view->nlines;
9257 if (view_is_hsplit_top(view))
9258 --eos; /* border */
9260 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9262 switch (ch) {
9263 case '0':
9264 case '$':
9265 case KEY_RIGHT:
9266 case 'l':
9267 case KEY_LEFT:
9268 case 'h':
9269 horizontal_scroll_input(view, ch);
9270 break;
9271 case 'g':
9272 case KEY_HOME:
9273 s->first_displayed_line = 1;
9274 view->count = 0;
9275 break;
9276 case 'G':
9277 case KEY_END:
9278 view->count = 0;
9279 if (s->eof)
9280 break;
9281 s->first_displayed_line = (s->nlines - eos) + 3;
9282 s->eof = 1;
9283 break;
9284 case 'k':
9285 case KEY_UP:
9286 if (s->first_displayed_line > 1)
9287 --s->first_displayed_line;
9288 else
9289 view->count = 0;
9290 break;
9291 case CTRL('u'):
9292 case 'u':
9293 nscroll /= 2;
9294 /* FALL THROUGH */
9295 case KEY_PPAGE:
9296 case CTRL('b'):
9297 case 'b':
9298 if (s->first_displayed_line == 1) {
9299 view->count = 0;
9300 break;
9302 while (--nscroll > 0 && s->first_displayed_line > 1)
9303 s->first_displayed_line--;
9304 break;
9305 case 'j':
9306 case KEY_DOWN:
9307 case CTRL('n'):
9308 if (!s->eof)
9309 ++s->first_displayed_line;
9310 else
9311 view->count = 0;
9312 break;
9313 case CTRL('d'):
9314 case 'd':
9315 nscroll /= 2;
9316 /* FALL THROUGH */
9317 case KEY_NPAGE:
9318 case CTRL('f'):
9319 case 'f':
9320 case ' ':
9321 if (s->eof) {
9322 view->count = 0;
9323 break;
9325 while (!s->eof && --nscroll > 0) {
9326 linelen = getline(&line, &linesz, s->f);
9327 s->first_displayed_line++;
9328 if (linelen == -1) {
9329 if (feof(s->f))
9330 s->eof = 1;
9331 else
9332 err = got_ferror(s->f, GOT_ERR_IO);
9333 break;
9336 free(line);
9337 break;
9338 default:
9339 view->count = 0;
9340 break;
9343 return err;
9346 static const struct got_error *
9347 close_help_view(struct tog_view *view)
9349 struct tog_help_view_state *s = &view->state.help;
9351 free(s->line_offsets);
9352 s->line_offsets = NULL;
9353 if (fclose(s->f) == EOF)
9354 return got_error_from_errno("fclose");
9356 return NULL;
9359 static const struct got_error *
9360 reset_help_view(struct tog_view *view)
9362 struct tog_help_view_state *s = &view->state.help;
9365 if (s->f && fclose(s->f) == EOF)
9366 return got_error_from_errno("fclose");
9368 wclear(view->window);
9369 view->count = 0;
9370 view->x = 0;
9371 s->all = !s->all;
9372 s->first_displayed_line = 1;
9373 s->last_displayed_line = view->nlines;
9374 s->matched_line = 0;
9376 return create_help(s);
9379 static const struct got_error *
9380 open_help_view(struct tog_view *view, struct tog_view *parent)
9382 const struct got_error *err = NULL;
9383 struct tog_help_view_state *s = &view->state.help;
9385 s->type = (enum tog_keymap_type)parent->type;
9386 s->first_displayed_line = 1;
9387 s->last_displayed_line = view->nlines;
9388 s->selected_line = 1;
9390 view->show = show_help_view;
9391 view->input = input_help_view;
9392 view->reset = reset_help_view;
9393 view->close = close_help_view;
9394 view->search_start = search_start_help_view;
9395 view->search_setup = search_setup_help_view;
9396 view->search_next = search_next_view_match;
9398 err = create_help(s);
9399 return err;
9402 static const struct got_error *
9403 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9404 enum tog_view_type request, int y, int x)
9406 const struct got_error *err = NULL;
9408 *new_view = NULL;
9410 switch (request) {
9411 case TOG_VIEW_DIFF:
9412 if (view->type == TOG_VIEW_LOG) {
9413 struct tog_log_view_state *s = &view->state.log;
9415 err = open_diff_view_for_commit(new_view, y, x,
9416 s->selected_entry->commit, s->selected_entry->id,
9417 view, s->repo);
9418 } else
9419 return got_error_msg(GOT_ERR_NOT_IMPL,
9420 "parent/child view pair not supported");
9421 break;
9422 case TOG_VIEW_BLAME:
9423 if (view->type == TOG_VIEW_TREE) {
9424 struct tog_tree_view_state *s = &view->state.tree;
9426 err = blame_tree_entry(new_view, y, x,
9427 s->selected_entry, &s->parents, s->commit_id,
9428 s->repo);
9429 } else
9430 return got_error_msg(GOT_ERR_NOT_IMPL,
9431 "parent/child view pair not supported");
9432 break;
9433 case TOG_VIEW_LOG:
9434 if (view->type == TOG_VIEW_BLAME)
9435 err = log_annotated_line(new_view, y, x,
9436 view->state.blame.repo, view->state.blame.id_to_log);
9437 else if (view->type == TOG_VIEW_TREE)
9438 err = log_selected_tree_entry(new_view, y, x,
9439 &view->state.tree);
9440 else if (view->type == TOG_VIEW_REF)
9441 err = log_ref_entry(new_view, y, x,
9442 view->state.ref.selected_entry,
9443 view->state.ref.repo);
9444 else
9445 return got_error_msg(GOT_ERR_NOT_IMPL,
9446 "parent/child view pair not supported");
9447 break;
9448 case TOG_VIEW_TREE:
9449 if (view->type == TOG_VIEW_LOG)
9450 err = browse_commit_tree(new_view, y, x,
9451 view->state.log.selected_entry,
9452 view->state.log.in_repo_path,
9453 view->state.log.head_ref_name,
9454 view->state.log.repo);
9455 else if (view->type == TOG_VIEW_REF)
9456 err = browse_ref_tree(new_view, y, x,
9457 view->state.ref.selected_entry,
9458 view->state.ref.repo);
9459 else
9460 return got_error_msg(GOT_ERR_NOT_IMPL,
9461 "parent/child view pair not supported");
9462 break;
9463 case TOG_VIEW_REF:
9464 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9465 if (*new_view == NULL)
9466 return got_error_from_errno("view_open");
9467 if (view->type == TOG_VIEW_LOG)
9468 err = open_ref_view(*new_view, view->state.log.repo);
9469 else if (view->type == TOG_VIEW_TREE)
9470 err = open_ref_view(*new_view, view->state.tree.repo);
9471 else
9472 err = got_error_msg(GOT_ERR_NOT_IMPL,
9473 "parent/child view pair not supported");
9474 if (err)
9475 view_close(*new_view);
9476 break;
9477 case TOG_VIEW_HELP:
9478 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9479 if (*new_view == NULL)
9480 return got_error_from_errno("view_open");
9481 err = open_help_view(*new_view, view);
9482 if (err)
9483 view_close(*new_view);
9484 break;
9485 default:
9486 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9489 return err;
9493 * If view was scrolled down to move the selected line into view when opening a
9494 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9496 static void
9497 offset_selection_up(struct tog_view *view)
9499 switch (view->type) {
9500 case TOG_VIEW_BLAME: {
9501 struct tog_blame_view_state *s = &view->state.blame;
9502 if (s->first_displayed_line == 1) {
9503 s->selected_line = MAX(s->selected_line - view->offset,
9504 1);
9505 break;
9507 if (s->first_displayed_line > view->offset)
9508 s->first_displayed_line -= view->offset;
9509 else
9510 s->first_displayed_line = 1;
9511 s->selected_line += view->offset;
9512 break;
9514 case TOG_VIEW_LOG:
9515 log_scroll_up(&view->state.log, view->offset);
9516 view->state.log.selected += view->offset;
9517 break;
9518 case TOG_VIEW_REF:
9519 ref_scroll_up(&view->state.ref, view->offset);
9520 view->state.ref.selected += view->offset;
9521 break;
9522 case TOG_VIEW_TREE:
9523 tree_scroll_up(&view->state.tree, view->offset);
9524 view->state.tree.selected += view->offset;
9525 break;
9526 default:
9527 break;
9530 view->offset = 0;
9534 * If the selected line is in the section of screen covered by the bottom split,
9535 * scroll down offset lines to move it into view and index its new position.
9537 static const struct got_error *
9538 offset_selection_down(struct tog_view *view)
9540 const struct got_error *err = NULL;
9541 const struct got_error *(*scrolld)(struct tog_view *, int);
9542 int *selected = NULL;
9543 int header, offset;
9545 switch (view->type) {
9546 case TOG_VIEW_BLAME: {
9547 struct tog_blame_view_state *s = &view->state.blame;
9548 header = 3;
9549 scrolld = NULL;
9550 if (s->selected_line > view->nlines - header) {
9551 offset = abs(view->nlines - s->selected_line - header);
9552 s->first_displayed_line += offset;
9553 s->selected_line -= offset;
9554 view->offset = offset;
9556 break;
9558 case TOG_VIEW_LOG: {
9559 struct tog_log_view_state *s = &view->state.log;
9560 scrolld = &log_scroll_down;
9561 header = view_is_parent_view(view) ? 3 : 2;
9562 selected = &s->selected;
9563 break;
9565 case TOG_VIEW_REF: {
9566 struct tog_ref_view_state *s = &view->state.ref;
9567 scrolld = &ref_scroll_down;
9568 header = 3;
9569 selected = &s->selected;
9570 break;
9572 case TOG_VIEW_TREE: {
9573 struct tog_tree_view_state *s = &view->state.tree;
9574 scrolld = &tree_scroll_down;
9575 header = 5;
9576 selected = &s->selected;
9577 break;
9579 default:
9580 selected = NULL;
9581 scrolld = NULL;
9582 header = 0;
9583 break;
9586 if (selected && *selected > view->nlines - header) {
9587 offset = abs(view->nlines - *selected - header);
9588 view->offset = offset;
9589 if (scrolld && offset) {
9590 err = scrolld(view, offset);
9591 *selected -= offset;
9595 return err;
9598 static void
9599 list_commands(FILE *fp)
9601 size_t i;
9603 fprintf(fp, "commands:");
9604 for (i = 0; i < nitems(tog_commands); i++) {
9605 const struct tog_cmd *cmd = &tog_commands[i];
9606 fprintf(fp, " %s", cmd->name);
9608 fputc('\n', fp);
9611 __dead static void
9612 usage(int hflag, int status)
9614 FILE *fp = (status == 0) ? stdout : stderr;
9616 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9617 getprogname());
9618 if (hflag) {
9619 fprintf(fp, "lazy usage: %s path\n", getprogname());
9620 list_commands(fp);
9622 exit(status);
9625 static char **
9626 make_argv(int argc, ...)
9628 va_list ap;
9629 char **argv;
9630 int i;
9632 va_start(ap, argc);
9634 argv = calloc(argc, sizeof(char *));
9635 if (argv == NULL)
9636 err(1, "calloc");
9637 for (i = 0; i < argc; i++) {
9638 argv[i] = strdup(va_arg(ap, char *));
9639 if (argv[i] == NULL)
9640 err(1, "strdup");
9643 va_end(ap);
9644 return argv;
9648 * Try to convert 'tog path' into a 'tog log path' command.
9649 * The user could simply have mistyped the command rather than knowingly
9650 * provided a path. So check whether argv[0] can in fact be resolved
9651 * to a path in the HEAD commit and print a special error if not.
9652 * This hack is for mpi@ <3
9654 static const struct got_error *
9655 tog_log_with_path(int argc, char *argv[])
9657 const struct got_error *error = NULL, *close_err;
9658 const struct tog_cmd *cmd = NULL;
9659 struct got_repository *repo = NULL;
9660 struct got_worktree *worktree = NULL;
9661 struct got_object_id *commit_id = NULL, *id = NULL;
9662 struct got_commit_object *commit = NULL;
9663 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9664 char *commit_id_str = NULL, **cmd_argv = NULL;
9665 int *pack_fds = NULL;
9667 cwd = getcwd(NULL, 0);
9668 if (cwd == NULL)
9669 return got_error_from_errno("getcwd");
9671 error = got_repo_pack_fds_open(&pack_fds);
9672 if (error != NULL)
9673 goto done;
9675 error = got_worktree_open(&worktree, cwd);
9676 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9677 goto done;
9679 if (worktree)
9680 repo_path = strdup(got_worktree_get_repo_path(worktree));
9681 else
9682 repo_path = strdup(cwd);
9683 if (repo_path == NULL) {
9684 error = got_error_from_errno("strdup");
9685 goto done;
9688 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9689 if (error != NULL)
9690 goto done;
9692 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9693 repo, worktree);
9694 if (error)
9695 goto done;
9697 error = tog_load_refs(repo, 0);
9698 if (error)
9699 goto done;
9700 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9701 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9702 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9703 if (error)
9704 goto done;
9706 if (worktree) {
9707 got_worktree_close(worktree);
9708 worktree = NULL;
9711 error = got_object_open_as_commit(&commit, repo, commit_id);
9712 if (error)
9713 goto done;
9715 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9716 if (error) {
9717 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9718 goto done;
9719 fprintf(stderr, "%s: '%s' is no known command or path\n",
9720 getprogname(), argv[0]);
9721 usage(1, 1);
9722 /* not reached */
9725 error = got_object_id_str(&commit_id_str, commit_id);
9726 if (error)
9727 goto done;
9729 cmd = &tog_commands[0]; /* log */
9730 argc = 4;
9731 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9732 error = cmd->cmd_main(argc, cmd_argv);
9733 done:
9734 if (repo) {
9735 close_err = got_repo_close(repo);
9736 if (error == NULL)
9737 error = close_err;
9739 if (commit)
9740 got_object_commit_close(commit);
9741 if (worktree)
9742 got_worktree_close(worktree);
9743 if (pack_fds) {
9744 const struct got_error *pack_err =
9745 got_repo_pack_fds_close(pack_fds);
9746 if (error == NULL)
9747 error = pack_err;
9749 free(id);
9750 free(commit_id_str);
9751 free(commit_id);
9752 free(cwd);
9753 free(repo_path);
9754 free(in_repo_path);
9755 if (cmd_argv) {
9756 int i;
9757 for (i = 0; i < argc; i++)
9758 free(cmd_argv[i]);
9759 free(cmd_argv);
9761 tog_free_refs();
9762 return error;
9765 int
9766 main(int argc, char *argv[])
9768 const struct got_error *io_err, *error = NULL;
9769 const struct tog_cmd *cmd = NULL;
9770 int ch, hflag = 0, Vflag = 0;
9771 char **cmd_argv = NULL;
9772 static const struct option longopts[] = {
9773 { "version", no_argument, NULL, 'V' },
9774 { NULL, 0, NULL, 0}
9776 char *diff_algo_str = NULL;
9777 const char *test_script_path;
9779 setlocale(LC_CTYPE, "");
9782 * Test mode init must happen before pledge() because "tty" will
9783 * not allow TTY-related ioctls to occur via regular files.
9785 test_script_path = getenv("TOG_TEST_SCRIPT");
9786 if (test_script_path != NULL) {
9787 error = init_mock_term(test_script_path);
9788 if (error) {
9789 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9790 return 1;
9794 #if !defined(PROFILE)
9795 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9796 NULL) == -1)
9797 err(1, "pledge");
9798 #endif
9800 if (!isatty(STDIN_FILENO))
9801 errx(1, "standard input is not a tty");
9803 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9804 switch (ch) {
9805 case 'h':
9806 hflag = 1;
9807 break;
9808 case 'V':
9809 Vflag = 1;
9810 break;
9811 default:
9812 usage(hflag, 1);
9813 /* NOTREACHED */
9817 argc -= optind;
9818 argv += optind;
9819 optind = 1;
9820 optreset = 1;
9822 if (Vflag) {
9823 got_version_print_str();
9824 return 0;
9827 if (argc == 0) {
9828 if (hflag)
9829 usage(hflag, 0);
9830 /* Build an argument vector which runs a default command. */
9831 cmd = &tog_commands[0];
9832 argc = 1;
9833 cmd_argv = make_argv(argc, cmd->name);
9834 } else {
9835 size_t i;
9837 /* Did the user specify a command? */
9838 for (i = 0; i < nitems(tog_commands); i++) {
9839 if (strncmp(tog_commands[i].name, argv[0],
9840 strlen(argv[0])) == 0) {
9841 cmd = &tog_commands[i];
9842 break;
9847 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9848 if (diff_algo_str) {
9849 if (strcasecmp(diff_algo_str, "patience") == 0)
9850 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9851 if (strcasecmp(diff_algo_str, "myers") == 0)
9852 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9855 if (cmd == NULL) {
9856 if (argc != 1)
9857 usage(0, 1);
9858 /* No command specified; try log with a path */
9859 error = tog_log_with_path(argc, argv);
9860 } else {
9861 if (hflag)
9862 cmd->cmd_usage();
9863 else
9864 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9867 if (using_mock_io) {
9868 io_err = tog_io_close();
9869 if (error == NULL)
9870 error = io_err;
9872 endwin();
9873 if (cmd_argv) {
9874 int i;
9875 for (i = 0; i < argc; i++)
9876 free(cmd_argv[i]);
9877 free(cmd_argv);
9880 if (error && error->code != GOT_ERR_CANCELLED &&
9881 error->code != GOT_ERR_EOF &&
9882 error->code != GOT_ERR_PRIVSEP_EXIT &&
9883 error->code != GOT_ERR_PRIVSEP_PIPE &&
9884 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9885 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9886 return 0;