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_KEY_SCRDUMP SHRT_MIN
627 /*
628 * We implement two types of views: parent views and child views.
630 * The 'Tab' key switches focus between a parent view and its child view.
631 * Child views are shown side-by-side to their parent view, provided
632 * there is enough screen estate.
634 * When a new view is opened from within a parent view, this new view
635 * becomes a child view of the parent view, replacing any existing child.
637 * When a new view is opened from within a child view, this new view
638 * becomes a parent view which will obscure the views below until the
639 * user quits the new parent view by typing 'q'.
641 * This list of views contains parent views only.
642 * Child views are only pointed to by their parent view.
643 */
644 TAILQ_HEAD(tog_view_list_head, tog_view);
646 struct tog_view {
647 TAILQ_ENTRY(tog_view) entry;
648 WINDOW *window;
649 PANEL *panel;
650 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
651 int resized_y, resized_x; /* begin_y/x based on user resizing */
652 int maxx, x; /* max column and current start column */
653 int lines, cols; /* copies of LINES and COLS */
654 int nscrolled, offset; /* lines scrolled and hsplit line offset */
655 int gline, hiline; /* navigate to and highlight this nG line */
656 int ch, count; /* current keymap and count prefix */
657 int resized; /* set when in a resize event */
658 int focussed; /* Only set on one parent or child view at a time. */
659 int dying;
660 struct tog_view *parent;
661 struct tog_view *child;
663 /*
664 * This flag is initially set on parent views when a new child view
665 * is created. It gets toggled when the 'Tab' key switches focus
666 * between parent and child.
667 * The flag indicates whether focus should be passed on to our child
668 * view if this parent view gets picked for focus after another parent
669 * view was closed. This prevents child views from losing focus in such
670 * situations.
671 */
672 int focus_child;
674 enum tog_view_mode mode;
675 /* type-specific state */
676 enum tog_view_type type;
677 union {
678 struct tog_diff_view_state diff;
679 struct tog_log_view_state log;
680 struct tog_blame_view_state blame;
681 struct tog_tree_view_state tree;
682 struct tog_ref_view_state ref;
683 struct tog_help_view_state help;
684 } state;
686 const struct got_error *(*show)(struct tog_view *);
687 const struct got_error *(*input)(struct tog_view **,
688 struct tog_view *, int);
689 const struct got_error *(*reset)(struct tog_view *);
690 const struct got_error *(*resize)(struct tog_view *, int);
691 const struct got_error *(*close)(struct tog_view *);
693 const struct got_error *(*search_start)(struct tog_view *);
694 const struct got_error *(*search_next)(struct tog_view *);
695 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
696 int **, int **, int **, int **);
697 int search_started;
698 int searching;
699 #define TOG_SEARCH_FORWARD 1
700 #define TOG_SEARCH_BACKWARD 2
701 int search_next_done;
702 #define TOG_SEARCH_HAVE_MORE 1
703 #define TOG_SEARCH_NO_MORE 2
704 #define TOG_SEARCH_HAVE_NONE 3
705 regex_t regex;
706 regmatch_t regmatch;
707 const char *action;
708 };
710 static const struct got_error *open_diff_view(struct tog_view *,
711 struct got_object_id *, struct got_object_id *,
712 const char *, const char *, int, int, int, struct tog_view *,
713 struct got_repository *);
714 static const struct got_error *show_diff_view(struct tog_view *);
715 static const struct got_error *input_diff_view(struct tog_view **,
716 struct tog_view *, int);
717 static const struct got_error *reset_diff_view(struct tog_view *);
718 static const struct got_error* close_diff_view(struct tog_view *);
719 static const struct got_error *search_start_diff_view(struct tog_view *);
720 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
721 size_t *, int **, int **, int **, int **);
722 static const struct got_error *search_next_view_match(struct tog_view *);
724 static const struct got_error *open_log_view(struct tog_view *,
725 struct got_object_id *, struct got_repository *,
726 const char *, const char *, int);
727 static const struct got_error * show_log_view(struct tog_view *);
728 static const struct got_error *input_log_view(struct tog_view **,
729 struct tog_view *, int);
730 static const struct got_error *resize_log_view(struct tog_view *, int);
731 static const struct got_error *close_log_view(struct tog_view *);
732 static const struct got_error *search_start_log_view(struct tog_view *);
733 static const struct got_error *search_next_log_view(struct tog_view *);
735 static const struct got_error *open_blame_view(struct tog_view *, char *,
736 struct got_object_id *, struct got_repository *);
737 static const struct got_error *show_blame_view(struct tog_view *);
738 static const struct got_error *input_blame_view(struct tog_view **,
739 struct tog_view *, int);
740 static const struct got_error *reset_blame_view(struct tog_view *);
741 static const struct got_error *close_blame_view(struct tog_view *);
742 static const struct got_error *search_start_blame_view(struct tog_view *);
743 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
744 size_t *, int **, int **, int **, int **);
746 static const struct got_error *open_tree_view(struct tog_view *,
747 struct got_object_id *, const char *, struct got_repository *);
748 static const struct got_error *show_tree_view(struct tog_view *);
749 static const struct got_error *input_tree_view(struct tog_view **,
750 struct tog_view *, int);
751 static const struct got_error *close_tree_view(struct tog_view *);
752 static const struct got_error *search_start_tree_view(struct tog_view *);
753 static const struct got_error *search_next_tree_view(struct tog_view *);
755 static const struct got_error *open_ref_view(struct tog_view *,
756 struct got_repository *);
757 static const struct got_error *show_ref_view(struct tog_view *);
758 static const struct got_error *input_ref_view(struct tog_view **,
759 struct tog_view *, int);
760 static const struct got_error *close_ref_view(struct tog_view *);
761 static const struct got_error *search_start_ref_view(struct tog_view *);
762 static const struct got_error *search_next_ref_view(struct tog_view *);
764 static const struct got_error *open_help_view(struct tog_view *,
765 struct tog_view *);
766 static const struct got_error *show_help_view(struct tog_view *);
767 static const struct got_error *input_help_view(struct tog_view **,
768 struct tog_view *, int);
769 static const struct got_error *reset_help_view(struct tog_view *);
770 static const struct got_error* close_help_view(struct tog_view *);
771 static const struct got_error *search_start_help_view(struct tog_view *);
772 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
773 size_t *, int **, int **, int **, int **);
775 static volatile sig_atomic_t tog_sigwinch_received;
776 static volatile sig_atomic_t tog_sigpipe_received;
777 static volatile sig_atomic_t tog_sigcont_received;
778 static volatile sig_atomic_t tog_sigint_received;
779 static volatile sig_atomic_t tog_sigterm_received;
781 static void
782 tog_sigwinch(int signo)
784 tog_sigwinch_received = 1;
787 static void
788 tog_sigpipe(int signo)
790 tog_sigpipe_received = 1;
793 static void
794 tog_sigcont(int signo)
796 tog_sigcont_received = 1;
799 static void
800 tog_sigint(int signo)
802 tog_sigint_received = 1;
805 static void
806 tog_sigterm(int signo)
808 tog_sigterm_received = 1;
811 static int
812 tog_fatal_signal_received(void)
814 return (tog_sigpipe_received ||
815 tog_sigint_received || tog_sigterm_received);
818 static const struct got_error *
819 view_close(struct tog_view *view)
821 const struct got_error *err = NULL, *child_err = NULL;
823 if (view->child) {
824 child_err = view_close(view->child);
825 view->child = NULL;
827 if (view->close)
828 err = view->close(view);
829 if (view->panel)
830 del_panel(view->panel);
831 if (view->window)
832 delwin(view->window);
833 free(view);
834 return err ? err : child_err;
837 static struct tog_view *
838 view_open(int nlines, int ncols, int begin_y, int begin_x,
839 enum tog_view_type type)
841 struct tog_view *view = calloc(1, sizeof(*view));
843 if (view == NULL)
844 return NULL;
846 view->type = type;
847 view->lines = LINES;
848 view->cols = COLS;
849 view->nlines = nlines ? nlines : LINES - begin_y;
850 view->ncols = ncols ? ncols : COLS - begin_x;
851 view->begin_y = begin_y;
852 view->begin_x = begin_x;
853 view->window = newwin(nlines, ncols, begin_y, begin_x);
854 if (view->window == NULL) {
855 view_close(view);
856 return NULL;
858 view->panel = new_panel(view->window);
859 if (view->panel == NULL ||
860 set_panel_userptr(view->panel, view) != OK) {
861 view_close(view);
862 return NULL;
865 keypad(view->window, TRUE);
866 return view;
869 static int
870 view_split_begin_x(int begin_x)
872 if (begin_x > 0 || COLS < 120)
873 return 0;
874 return (COLS - MAX(COLS / 2, 80));
877 /* XXX Stub till we decide what to do. */
878 static int
879 view_split_begin_y(int lines)
881 return lines * HSPLIT_SCALE;
884 static const struct got_error *view_resize(struct tog_view *);
886 static const struct got_error *
887 view_splitscreen(struct tog_view *view)
889 const struct got_error *err = NULL;
891 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
892 if (view->resized_y && view->resized_y < view->lines)
893 view->begin_y = view->resized_y;
894 else
895 view->begin_y = view_split_begin_y(view->nlines);
896 view->begin_x = 0;
897 } else if (!view->resized) {
898 if (view->resized_x && view->resized_x < view->cols - 1 &&
899 view->cols > 119)
900 view->begin_x = view->resized_x;
901 else
902 view->begin_x = view_split_begin_x(0);
903 view->begin_y = 0;
905 view->nlines = LINES - view->begin_y;
906 view->ncols = COLS - view->begin_x;
907 view->lines = LINES;
908 view->cols = COLS;
909 err = view_resize(view);
910 if (err)
911 return err;
913 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
914 view->parent->nlines = view->begin_y;
916 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
917 return got_error_from_errno("mvwin");
919 return NULL;
922 static const struct got_error *
923 view_fullscreen(struct tog_view *view)
925 const struct got_error *err = NULL;
927 view->begin_x = 0;
928 view->begin_y = view->resized ? view->begin_y : 0;
929 view->nlines = view->resized ? view->nlines : LINES;
930 view->ncols = COLS;
931 view->lines = LINES;
932 view->cols = COLS;
933 err = view_resize(view);
934 if (err)
935 return err;
937 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
938 return got_error_from_errno("mvwin");
940 return NULL;
943 static int
944 view_is_parent_view(struct tog_view *view)
946 return view->parent == NULL;
949 static int
950 view_is_splitscreen(struct tog_view *view)
952 return view->begin_x > 0 || view->begin_y > 0;
955 static int
956 view_is_fullscreen(struct tog_view *view)
958 return view->nlines == LINES && view->ncols == COLS;
961 static int
962 view_is_hsplit_top(struct tog_view *view)
964 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
965 view_is_splitscreen(view->child);
968 static void
969 view_border(struct tog_view *view)
971 PANEL *panel;
972 const struct tog_view *view_above;
974 if (view->parent)
975 return view_border(view->parent);
977 panel = panel_above(view->panel);
978 if (panel == NULL)
979 return;
981 view_above = panel_userptr(panel);
982 if (view->mode == TOG_VIEW_SPLIT_HRZN)
983 mvwhline(view->window, view_above->begin_y - 1,
984 view->begin_x, got_locale_is_utf8() ?
985 ACS_HLINE : '-', view->ncols);
986 else
987 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
988 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
991 static const struct got_error *view_init_hsplit(struct tog_view *, int);
992 static const struct got_error *request_log_commits(struct tog_view *);
993 static const struct got_error *offset_selection_down(struct tog_view *);
994 static void offset_selection_up(struct tog_view *);
995 static void view_get_split(struct tog_view *, int *, int *);
997 static const struct got_error *
998 view_resize(struct tog_view *view)
1000 const struct got_error *err = NULL;
1001 int dif, nlines, ncols;
1003 dif = LINES - view->lines; /* line difference */
1005 if (view->lines > LINES)
1006 nlines = view->nlines - (view->lines - LINES);
1007 else
1008 nlines = view->nlines + (LINES - view->lines);
1009 if (view->cols > COLS)
1010 ncols = view->ncols - (view->cols - COLS);
1011 else
1012 ncols = view->ncols + (COLS - view->cols);
1014 if (view->child) {
1015 int hs = view->child->begin_y;
1017 if (!view_is_fullscreen(view))
1018 view->child->begin_x = view_split_begin_x(view->begin_x);
1019 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1020 view->child->begin_x == 0) {
1021 ncols = COLS;
1023 view_fullscreen(view->child);
1024 if (view->child->focussed)
1025 show_panel(view->child->panel);
1026 else
1027 show_panel(view->panel);
1028 } else {
1029 ncols = view->child->begin_x;
1031 view_splitscreen(view->child);
1032 show_panel(view->child->panel);
1035 * XXX This is ugly and needs to be moved into the above
1036 * logic but "works" for now and my attempts at moving it
1037 * break either 'tab' or 'F' key maps in horizontal splits.
1039 if (hs) {
1040 err = view_splitscreen(view->child);
1041 if (err)
1042 return err;
1043 if (dif < 0) { /* top split decreased */
1044 err = offset_selection_down(view);
1045 if (err)
1046 return err;
1048 view_border(view);
1049 update_panels();
1050 doupdate();
1051 show_panel(view->child->panel);
1052 nlines = view->nlines;
1054 } else if (view->parent == NULL)
1055 ncols = COLS;
1057 if (view->resize && dif > 0) {
1058 err = view->resize(view, dif);
1059 if (err)
1060 return err;
1063 if (wresize(view->window, nlines, ncols) == ERR)
1064 return got_error_from_errno("wresize");
1065 if (replace_panel(view->panel, view->window) == ERR)
1066 return got_error_from_errno("replace_panel");
1067 wclear(view->window);
1069 view->nlines = nlines;
1070 view->ncols = ncols;
1071 view->lines = LINES;
1072 view->cols = COLS;
1074 return NULL;
1077 static const struct got_error *
1078 resize_log_view(struct tog_view *view, int increase)
1080 struct tog_log_view_state *s = &view->state.log;
1081 const struct got_error *err = NULL;
1082 int n = 0;
1084 if (s->selected_entry)
1085 n = s->selected_entry->idx + view->lines - s->selected;
1088 * Request commits to account for the increased
1089 * height so we have enough to populate the view.
1091 if (s->commits->ncommits < n) {
1092 view->nscrolled = n - s->commits->ncommits + increase + 1;
1093 err = request_log_commits(view);
1096 return err;
1099 static void
1100 view_adjust_offset(struct tog_view *view, int n)
1102 if (n == 0)
1103 return;
1105 if (view->parent && view->parent->offset) {
1106 if (view->parent->offset + n >= 0)
1107 view->parent->offset += n;
1108 else
1109 view->parent->offset = 0;
1110 } else if (view->offset) {
1111 if (view->offset - n >= 0)
1112 view->offset -= n;
1113 else
1114 view->offset = 0;
1118 static const struct got_error *
1119 view_resize_split(struct tog_view *view, int resize)
1121 const struct got_error *err = NULL;
1122 struct tog_view *v = NULL;
1124 if (view->parent)
1125 v = view->parent;
1126 else
1127 v = view;
1129 if (!v->child || !view_is_splitscreen(v->child))
1130 return NULL;
1132 v->resized = v->child->resized = resize; /* lock for resize event */
1134 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1135 if (v->child->resized_y)
1136 v->child->begin_y = v->child->resized_y;
1137 if (view->parent)
1138 v->child->begin_y -= resize;
1139 else
1140 v->child->begin_y += resize;
1141 if (v->child->begin_y < 3) {
1142 view->count = 0;
1143 v->child->begin_y = 3;
1144 } else if (v->child->begin_y > LINES - 1) {
1145 view->count = 0;
1146 v->child->begin_y = LINES - 1;
1148 v->ncols = COLS;
1149 v->child->ncols = COLS;
1150 view_adjust_offset(view, resize);
1151 err = view_init_hsplit(v, v->child->begin_y);
1152 if (err)
1153 return err;
1154 v->child->resized_y = v->child->begin_y;
1155 } else {
1156 if (v->child->resized_x)
1157 v->child->begin_x = v->child->resized_x;
1158 if (view->parent)
1159 v->child->begin_x -= resize;
1160 else
1161 v->child->begin_x += resize;
1162 if (v->child->begin_x < 11) {
1163 view->count = 0;
1164 v->child->begin_x = 11;
1165 } else if (v->child->begin_x > COLS - 1) {
1166 view->count = 0;
1167 v->child->begin_x = COLS - 1;
1169 v->child->resized_x = v->child->begin_x;
1172 v->child->mode = v->mode;
1173 v->child->nlines = v->lines - v->child->begin_y;
1174 v->child->ncols = v->cols - v->child->begin_x;
1175 v->focus_child = 1;
1177 err = view_fullscreen(v);
1178 if (err)
1179 return err;
1180 err = view_splitscreen(v->child);
1181 if (err)
1182 return err;
1184 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1185 err = offset_selection_down(v->child);
1186 if (err)
1187 return err;
1190 if (v->resize)
1191 err = v->resize(v, 0);
1192 else if (v->child->resize)
1193 err = v->child->resize(v->child, 0);
1195 v->resized = v->child->resized = 0;
1197 return err;
1200 static void
1201 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1203 struct tog_view *v = src->child ? src->child : src;
1205 dst->resized_x = v->resized_x;
1206 dst->resized_y = v->resized_y;
1209 static const struct got_error *
1210 view_close_child(struct tog_view *view)
1212 const struct got_error *err = NULL;
1214 if (view->child == NULL)
1215 return NULL;
1217 err = view_close(view->child);
1218 view->child = NULL;
1219 return err;
1222 static const struct got_error *
1223 view_set_child(struct tog_view *view, struct tog_view *child)
1225 const struct got_error *err = NULL;
1227 view->child = child;
1228 child->parent = view;
1230 err = view_resize(view);
1231 if (err)
1232 return err;
1234 if (view->child->resized_x || view->child->resized_y)
1235 err = view_resize_split(view, 0);
1237 return err;
1240 static const struct got_error *view_dispatch_request(struct tog_view **,
1241 struct tog_view *, enum tog_view_type, int, int);
1243 static const struct got_error *
1244 view_request_new(struct tog_view **requested, struct tog_view *view,
1245 enum tog_view_type request)
1247 struct tog_view *new_view = NULL;
1248 const struct got_error *err;
1249 int y = 0, x = 0;
1251 *requested = NULL;
1253 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1254 view_get_split(view, &y, &x);
1256 err = view_dispatch_request(&new_view, view, request, y, x);
1257 if (err)
1258 return err;
1260 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1261 request != TOG_VIEW_HELP) {
1262 err = view_init_hsplit(view, y);
1263 if (err)
1264 return err;
1267 view->focussed = 0;
1268 new_view->focussed = 1;
1269 new_view->mode = view->mode;
1270 new_view->nlines = request == TOG_VIEW_HELP ?
1271 view->lines : view->lines - y;
1273 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1274 view_transfer_size(new_view, view);
1275 err = view_close_child(view);
1276 if (err)
1277 return err;
1278 err = view_set_child(view, new_view);
1279 if (err)
1280 return err;
1281 view->focus_child = 1;
1282 } else
1283 *requested = new_view;
1285 return NULL;
1288 static void
1289 tog_resizeterm(void)
1291 int cols, lines;
1292 struct winsize size;
1294 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1295 cols = 80; /* Default */
1296 lines = 24;
1297 } else {
1298 cols = size.ws_col;
1299 lines = size.ws_row;
1301 resize_term(lines, cols);
1304 static const struct got_error *
1305 view_search_start(struct tog_view *view, int fast_refresh)
1307 const struct got_error *err = NULL;
1308 struct tog_view *v = view;
1309 char pattern[1024];
1310 int ret;
1312 if (view->search_started) {
1313 regfree(&view->regex);
1314 view->searching = 0;
1315 memset(&view->regmatch, 0, sizeof(view->regmatch));
1317 view->search_started = 0;
1319 if (view->nlines < 1)
1320 return NULL;
1322 if (view_is_hsplit_top(view))
1323 v = view->child;
1324 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1325 v = view->parent;
1327 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1328 wclrtoeol(v->window);
1330 nodelay(v->window, FALSE); /* block for search term input */
1331 nocbreak();
1332 echo();
1333 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1334 wrefresh(v->window);
1335 cbreak();
1336 noecho();
1337 nodelay(v->window, TRUE);
1338 if (!fast_refresh && !using_mock_io)
1339 halfdelay(10);
1340 if (ret == ERR)
1341 return NULL;
1343 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1344 err = view->search_start(view);
1345 if (err) {
1346 regfree(&view->regex);
1347 return err;
1349 view->search_started = 1;
1350 view->searching = TOG_SEARCH_FORWARD;
1351 view->search_next_done = 0;
1352 view->search_next(view);
1355 return NULL;
1358 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1359 static const struct got_error *
1360 switch_split(struct tog_view *view)
1362 const struct got_error *err = NULL;
1363 struct tog_view *v = NULL;
1365 if (view->parent)
1366 v = view->parent;
1367 else
1368 v = view;
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1371 v->mode = TOG_VIEW_SPLIT_VERT;
1372 else
1373 v->mode = TOG_VIEW_SPLIT_HRZN;
1375 if (!v->child)
1376 return NULL;
1377 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1378 v->mode = TOG_VIEW_SPLIT_NONE;
1380 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1381 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1382 v->child->begin_y = v->child->resized_y;
1383 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1384 v->child->begin_x = v->child->resized_x;
1387 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1388 v->ncols = COLS;
1389 v->child->ncols = COLS;
1390 v->child->nscrolled = LINES - v->child->nlines;
1392 err = view_init_hsplit(v, v->child->begin_y);
1393 if (err)
1394 return err;
1396 v->child->mode = v->mode;
1397 v->child->nlines = v->lines - v->child->begin_y;
1398 v->focus_child = 1;
1400 err = view_fullscreen(v);
1401 if (err)
1402 return err;
1403 err = view_splitscreen(v->child);
1404 if (err)
1405 return err;
1407 if (v->mode == TOG_VIEW_SPLIT_NONE)
1408 v->mode = TOG_VIEW_SPLIT_VERT;
1409 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1410 err = offset_selection_down(v);
1411 if (err)
1412 return err;
1413 err = offset_selection_down(v->child);
1414 if (err)
1415 return err;
1416 } else {
1417 offset_selection_up(v);
1418 offset_selection_up(v->child);
1420 if (v->resize)
1421 err = v->resize(v, 0);
1422 else if (v->child->resize)
1423 err = v->child->resize(v->child, 0);
1425 return err;
1429 * Strip trailing whitespace from str starting at byte *n;
1430 * if *n < 0, use strlen(str). Return new str length in *n.
1432 static void
1433 strip_trailing_ws(char *str, int *n)
1435 size_t x = *n;
1437 if (str == NULL || *str == '\0')
1438 return;
1440 if (x < 0)
1441 x = strlen(str);
1443 while (x-- > 0 && isspace((unsigned char)str[x]))
1444 str[x] = '\0';
1446 *n = x + 1;
1450 * Extract visible substring of line y from the curses screen
1451 * and strip trailing whitespace. If vline is set, overwrite
1452 * line[vline] with '|' because the ACS_VLINE character is
1453 * written out as 'x'. Write the line to file f.
1455 static const struct got_error *
1456 view_write_line(FILE *f, int y, int vline)
1458 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1459 int r, w;
1461 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1462 if (r == ERR)
1463 return got_error_fmt(GOT_ERR_RANGE,
1464 "failed to extract line %d", y);
1467 * In some views, lines are padded with blanks to COLS width.
1468 * Strip them so we can diff without the -b flag when testing.
1470 strip_trailing_ws(line, &r);
1472 if (vline > 0)
1473 line[vline] = '|';
1475 w = fprintf(f, "%s\n", line);
1476 if (w != r + 1) /* \n */
1477 return got_ferror(f, GOT_ERR_IO);
1479 return NULL;
1483 * Capture the visible curses screen by writing each line to the
1484 * file at the path set via the TOG_SCR_DUMP environment variable.
1486 static const struct got_error *
1487 screendump(struct tog_view *view)
1489 const struct got_error *err;
1490 FILE *f = NULL;
1491 const char *path;
1492 int i;
1494 path = getenv("TOG_SCR_DUMP");
1495 if (path == NULL || *path == '\0')
1496 return got_error_msg(GOT_ERR_BAD_PATH,
1497 "TOG_SCR_DUMP path not set to capture screen dump");
1498 f = fopen(path, "wex");
1499 if (f == NULL)
1500 return got_error_from_errno_fmt("fopen: %s", path);
1502 if ((view->child && view->child->begin_x) ||
1503 (view->parent && view->begin_x)) {
1504 int ncols = view->child ? view->ncols : view->parent->ncols;
1506 /* vertical splitscreen */
1507 for (i = 0; i < view->nlines; ++i) {
1508 err = view_write_line(f, i, ncols - 1);
1509 if (err)
1510 goto done;
1512 } else {
1513 int hline = 0;
1515 /* fullscreen or horizontal splitscreen */
1516 if ((view->child && view->child->begin_y) ||
1517 (view->parent && view->begin_y)) /* hsplit */
1518 hline = view->child ?
1519 view->child->begin_y : view->begin_y;
1521 for (i = 0; i < view->lines; i++) {
1522 if (hline && i == hline - 1) {
1523 int c;
1525 /* ACS_HLINE writes out as 'q', overwrite it */
1526 for (c = 0; c < view->cols; ++c)
1527 fputc('-', f);
1528 fputc('\n', f);
1529 continue;
1532 err = view_write_line(f, i, 0);
1533 if (err)
1534 goto done;
1538 done:
1539 if (f && fclose(f) == EOF && err == NULL)
1540 err = got_ferror(f, GOT_ERR_IO);
1541 return err;
1545 * Compute view->count from numeric input. Assign total to view->count and
1546 * return first non-numeric key entered.
1548 static int
1549 get_compound_key(struct tog_view *view, int c)
1551 struct tog_view *v = view;
1552 int x, n = 0;
1554 if (view_is_hsplit_top(view))
1555 v = view->child;
1556 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1557 v = view->parent;
1559 view->count = 0;
1560 cbreak(); /* block for input */
1561 nodelay(view->window, FALSE);
1562 wmove(v->window, v->nlines - 1, 0);
1563 wclrtoeol(v->window);
1564 waddch(v->window, ':');
1566 do {
1567 x = getcurx(v->window);
1568 if (x != ERR && x < view->ncols) {
1569 waddch(v->window, c);
1570 wrefresh(v->window);
1574 * Don't overflow. Max valid request should be the greatest
1575 * between the longest and total lines; cap at 10 million.
1577 if (n >= 9999999)
1578 n = 9999999;
1579 else
1580 n = n * 10 + (c - '0');
1581 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1583 if (c == 'G' || c == 'g') { /* nG key map */
1584 view->gline = view->hiline = n;
1585 n = 0;
1586 c = 0;
1589 /* Massage excessive or inapplicable values at the input handler. */
1590 view->count = n;
1592 return c;
1595 static void
1596 action_report(struct tog_view *view)
1598 struct tog_view *v = view;
1600 if (view_is_hsplit_top(view))
1601 v = view->child;
1602 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1603 v = view->parent;
1605 wmove(v->window, v->nlines - 1, 0);
1606 wclrtoeol(v->window);
1607 wprintw(v->window, ":%s", view->action);
1608 wrefresh(v->window);
1611 * Clear action status report. Only clear in blame view
1612 * once annotating is complete, otherwise it's too fast.
1614 if (view->type == TOG_VIEW_BLAME) {
1615 if (view->state.blame.blame_complete)
1616 view->action = NULL;
1617 } else
1618 view->action = NULL;
1622 * Read the next line from the test script and assign
1623 * key instruction to *ch. If at EOF, set the *done flag.
1625 static const struct got_error *
1626 tog_read_script_key(FILE *script, int *ch, int *done)
1628 const struct got_error *err = NULL;
1629 char *line = NULL;
1630 size_t linesz = 0;
1632 *ch = -1;
1634 if (getline(&line, &linesz, script) == -1) {
1635 if (feof(script)) {
1636 *done = 1;
1637 goto done;
1638 } else {
1639 err = got_ferror(script, GOT_ERR_IO);
1640 goto done;
1644 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1645 tog_io.wait_for_ui = 1;
1646 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1647 *ch = KEY_ENTER;
1648 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1649 *ch = KEY_RIGHT;
1650 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1651 *ch = KEY_LEFT;
1652 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1653 *ch = KEY_DOWN;
1654 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1655 *ch = KEY_UP;
1656 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1657 *ch = TOG_KEY_SCRDUMP;
1658 else
1659 *ch = *line;
1661 done:
1662 free(line);
1663 return err;
1666 static const struct got_error *
1667 view_input(struct tog_view **new, int *done, struct tog_view *view,
1668 struct tog_view_list_head *views, int fast_refresh)
1670 const struct got_error *err = NULL;
1671 struct tog_view *v;
1672 int ch, errcode;
1674 *new = NULL;
1676 if (view->action)
1677 action_report(view);
1679 /* Clear "no matches" indicator. */
1680 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1681 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1682 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1683 view->count = 0;
1686 if (view->searching && !view->search_next_done) {
1687 errcode = pthread_mutex_unlock(&tog_mutex);
1688 if (errcode)
1689 return got_error_set_errno(errcode,
1690 "pthread_mutex_unlock");
1691 sched_yield();
1692 errcode = pthread_mutex_lock(&tog_mutex);
1693 if (errcode)
1694 return got_error_set_errno(errcode,
1695 "pthread_mutex_lock");
1696 view->search_next(view);
1697 return NULL;
1700 /* Allow threads to make progress while we are waiting for input. */
1701 errcode = pthread_mutex_unlock(&tog_mutex);
1702 if (errcode)
1703 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1705 if (using_mock_io) {
1706 err = tog_read_script_key(tog_io.f, &ch, done);
1707 if (err) {
1708 errcode = pthread_mutex_lock(&tog_mutex);
1709 return err;
1711 } else if (view->count && --view->count) {
1712 cbreak();
1713 nodelay(view->window, TRUE);
1714 ch = wgetch(view->window);
1715 /* let C-g or backspace abort unfinished count */
1716 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1717 view->count = 0;
1718 else
1719 ch = view->ch;
1720 } else {
1721 ch = wgetch(view->window);
1722 if (ch >= '1' && ch <= '9')
1723 view->ch = ch = get_compound_key(view, ch);
1725 if (view->hiline && ch != ERR && ch != 0)
1726 view->hiline = 0; /* key pressed, clear line highlight */
1727 nodelay(view->window, TRUE);
1728 errcode = pthread_mutex_lock(&tog_mutex);
1729 if (errcode)
1730 return got_error_set_errno(errcode, "pthread_mutex_lock");
1732 if (tog_sigwinch_received || tog_sigcont_received) {
1733 tog_resizeterm();
1734 tog_sigwinch_received = 0;
1735 tog_sigcont_received = 0;
1736 TAILQ_FOREACH(v, views, entry) {
1737 err = view_resize(v);
1738 if (err)
1739 return err;
1740 err = v->input(new, v, KEY_RESIZE);
1741 if (err)
1742 return err;
1743 if (v->child) {
1744 err = view_resize(v->child);
1745 if (err)
1746 return err;
1747 err = v->child->input(new, v->child,
1748 KEY_RESIZE);
1749 if (err)
1750 return err;
1751 if (v->child->resized_x || v->child->resized_y) {
1752 err = view_resize_split(v, 0);
1753 if (err)
1754 return err;
1760 switch (ch) {
1761 case '?':
1762 case 'H':
1763 case KEY_F(1):
1764 if (view->type == TOG_VIEW_HELP)
1765 err = view->reset(view);
1766 else
1767 err = view_request_new(new, view, TOG_VIEW_HELP);
1768 break;
1769 case '\t':
1770 view->count = 0;
1771 if (view->child) {
1772 view->focussed = 0;
1773 view->child->focussed = 1;
1774 view->focus_child = 1;
1775 } else if (view->parent) {
1776 view->focussed = 0;
1777 view->parent->focussed = 1;
1778 view->parent->focus_child = 0;
1779 if (!view_is_splitscreen(view)) {
1780 if (view->parent->resize) {
1781 err = view->parent->resize(view->parent,
1782 0);
1783 if (err)
1784 return err;
1786 offset_selection_up(view->parent);
1787 err = view_fullscreen(view->parent);
1788 if (err)
1789 return err;
1792 break;
1793 case 'q':
1794 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1795 if (view->parent->resize) {
1796 /* might need more commits to fill fullscreen */
1797 err = view->parent->resize(view->parent, 0);
1798 if (err)
1799 break;
1801 offset_selection_up(view->parent);
1803 err = view->input(new, view, ch);
1804 view->dying = 1;
1805 break;
1806 case 'Q':
1807 *done = 1;
1808 break;
1809 case 'F':
1810 view->count = 0;
1811 if (view_is_parent_view(view)) {
1812 if (view->child == NULL)
1813 break;
1814 if (view_is_splitscreen(view->child)) {
1815 view->focussed = 0;
1816 view->child->focussed = 1;
1817 err = view_fullscreen(view->child);
1818 } else {
1819 err = view_splitscreen(view->child);
1820 if (!err)
1821 err = view_resize_split(view, 0);
1823 if (err)
1824 break;
1825 err = view->child->input(new, view->child,
1826 KEY_RESIZE);
1827 } else {
1828 if (view_is_splitscreen(view)) {
1829 view->parent->focussed = 0;
1830 view->focussed = 1;
1831 err = view_fullscreen(view);
1832 } else {
1833 err = view_splitscreen(view);
1834 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1835 err = view_resize(view->parent);
1836 if (!err)
1837 err = view_resize_split(view, 0);
1839 if (err)
1840 break;
1841 err = view->input(new, view, KEY_RESIZE);
1843 if (err)
1844 break;
1845 if (view->resize) {
1846 err = view->resize(view, 0);
1847 if (err)
1848 break;
1850 if (view->parent)
1851 err = offset_selection_down(view->parent);
1852 if (!err)
1853 err = offset_selection_down(view);
1854 break;
1855 case 'S':
1856 view->count = 0;
1857 err = switch_split(view);
1858 break;
1859 case '-':
1860 err = view_resize_split(view, -1);
1861 break;
1862 case '+':
1863 err = view_resize_split(view, 1);
1864 break;
1865 case KEY_RESIZE:
1866 break;
1867 case '/':
1868 view->count = 0;
1869 if (view->search_start)
1870 view_search_start(view, fast_refresh);
1871 else
1872 err = view->input(new, view, ch);
1873 break;
1874 case 'N':
1875 case 'n':
1876 if (view->search_started && view->search_next) {
1877 view->searching = (ch == 'n' ?
1878 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1879 view->search_next_done = 0;
1880 view->search_next(view);
1881 } else
1882 err = view->input(new, view, ch);
1883 break;
1884 case 'A':
1885 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1886 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1887 view->action = "Patience diff algorithm";
1888 } else {
1889 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1890 view->action = "Myers diff algorithm";
1892 TAILQ_FOREACH(v, views, entry) {
1893 if (v->reset) {
1894 err = v->reset(v);
1895 if (err)
1896 return err;
1898 if (v->child && v->child->reset) {
1899 err = v->child->reset(v->child);
1900 if (err)
1901 return err;
1904 break;
1905 case TOG_KEY_SCRDUMP:
1906 err = screendump(view);
1907 break;
1908 default:
1909 err = view->input(new, view, ch);
1910 break;
1913 return err;
1916 static int
1917 view_needs_focus_indication(struct tog_view *view)
1919 if (view_is_parent_view(view)) {
1920 if (view->child == NULL || view->child->focussed)
1921 return 0;
1922 if (!view_is_splitscreen(view->child))
1923 return 0;
1924 } else if (!view_is_splitscreen(view))
1925 return 0;
1927 return view->focussed;
1930 static const struct got_error *
1931 tog_io_close(void)
1933 const struct got_error *err = NULL;
1935 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1936 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1937 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1938 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1939 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1940 err = got_ferror(tog_io.f, GOT_ERR_IO);
1942 return err;
1945 static const struct got_error *
1946 view_loop(struct tog_view *view)
1948 const struct got_error *err = NULL;
1949 struct tog_view_list_head views;
1950 struct tog_view *new_view;
1951 char *mode;
1952 int fast_refresh = 10;
1953 int done = 0, errcode;
1955 mode = getenv("TOG_VIEW_SPLIT_MODE");
1956 if (!mode || !(*mode == 'h' || *mode == 'H'))
1957 view->mode = TOG_VIEW_SPLIT_VERT;
1958 else
1959 view->mode = TOG_VIEW_SPLIT_HRZN;
1961 errcode = pthread_mutex_lock(&tog_mutex);
1962 if (errcode)
1963 return got_error_set_errno(errcode, "pthread_mutex_lock");
1965 TAILQ_INIT(&views);
1966 TAILQ_INSERT_HEAD(&views, view, entry);
1968 view->focussed = 1;
1969 err = view->show(view);
1970 if (err)
1971 return err;
1972 update_panels();
1973 doupdate();
1974 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1975 !tog_fatal_signal_received()) {
1976 /* Refresh fast during initialization, then become slower. */
1977 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1978 halfdelay(10); /* switch to once per second */
1980 err = view_input(&new_view, &done, view, &views, fast_refresh);
1981 if (err)
1982 break;
1984 if (view->dying && view == TAILQ_FIRST(&views) &&
1985 TAILQ_NEXT(view, entry) == NULL)
1986 done = 1;
1987 if (done) {
1988 struct tog_view *v;
1991 * When we quit, scroll the screen up a single line
1992 * so we don't lose any information.
1994 TAILQ_FOREACH(v, &views, entry) {
1995 wmove(v->window, 0, 0);
1996 wdeleteln(v->window);
1997 wnoutrefresh(v->window);
1998 if (v->child && !view_is_fullscreen(v)) {
1999 wmove(v->child->window, 0, 0);
2000 wdeleteln(v->child->window);
2001 wnoutrefresh(v->child->window);
2004 doupdate();
2007 if (view->dying) {
2008 struct tog_view *v, *prev = NULL;
2010 if (view_is_parent_view(view))
2011 prev = TAILQ_PREV(view, tog_view_list_head,
2012 entry);
2013 else if (view->parent)
2014 prev = view->parent;
2016 if (view->parent) {
2017 view->parent->child = NULL;
2018 view->parent->focus_child = 0;
2019 /* Restore fullscreen line height. */
2020 view->parent->nlines = view->parent->lines;
2021 err = view_resize(view->parent);
2022 if (err)
2023 break;
2024 /* Make resized splits persist. */
2025 view_transfer_size(view->parent, view);
2026 } else
2027 TAILQ_REMOVE(&views, view, entry);
2029 err = view_close(view);
2030 if (err)
2031 goto done;
2033 view = NULL;
2034 TAILQ_FOREACH(v, &views, entry) {
2035 if (v->focussed)
2036 break;
2038 if (view == NULL && new_view == NULL) {
2039 /* No view has focus. Try to pick one. */
2040 if (prev)
2041 view = prev;
2042 else if (!TAILQ_EMPTY(&views)) {
2043 view = TAILQ_LAST(&views,
2044 tog_view_list_head);
2046 if (view) {
2047 if (view->focus_child) {
2048 view->child->focussed = 1;
2049 view = view->child;
2050 } else
2051 view->focussed = 1;
2055 if (new_view) {
2056 struct tog_view *v, *t;
2057 /* Only allow one parent view per type. */
2058 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2059 if (v->type != new_view->type)
2060 continue;
2061 TAILQ_REMOVE(&views, v, entry);
2062 err = view_close(v);
2063 if (err)
2064 goto done;
2065 break;
2067 TAILQ_INSERT_TAIL(&views, new_view, entry);
2068 view = new_view;
2070 if (view && !done) {
2071 if (view_is_parent_view(view)) {
2072 if (view->child && view->child->focussed)
2073 view = view->child;
2074 } else {
2075 if (view->parent && view->parent->focussed)
2076 view = view->parent;
2078 show_panel(view->panel);
2079 if (view->child && view_is_splitscreen(view->child))
2080 show_panel(view->child->panel);
2081 if (view->parent && view_is_splitscreen(view)) {
2082 err = view->parent->show(view->parent);
2083 if (err)
2084 goto done;
2086 err = view->show(view);
2087 if (err)
2088 goto done;
2089 if (view->child) {
2090 err = view->child->show(view->child);
2091 if (err)
2092 goto done;
2094 update_panels();
2095 doupdate();
2098 done:
2099 while (!TAILQ_EMPTY(&views)) {
2100 const struct got_error *close_err;
2101 view = TAILQ_FIRST(&views);
2102 TAILQ_REMOVE(&views, view, entry);
2103 close_err = view_close(view);
2104 if (close_err && err == NULL)
2105 err = close_err;
2108 errcode = pthread_mutex_unlock(&tog_mutex);
2109 if (errcode && err == NULL)
2110 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2112 return err;
2115 __dead static void
2116 usage_log(void)
2118 endwin();
2119 fprintf(stderr,
2120 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2121 getprogname());
2122 exit(1);
2125 /* Create newly allocated wide-character string equivalent to a byte string. */
2126 static const struct got_error *
2127 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2129 char *vis = NULL;
2130 const struct got_error *err = NULL;
2132 *ws = NULL;
2133 *wlen = mbstowcs(NULL, s, 0);
2134 if (*wlen == (size_t)-1) {
2135 int vislen;
2136 if (errno != EILSEQ)
2137 return got_error_from_errno("mbstowcs");
2139 /* byte string invalid in current encoding; try to "fix" it */
2140 err = got_mbsavis(&vis, &vislen, s);
2141 if (err)
2142 return err;
2143 *wlen = mbstowcs(NULL, vis, 0);
2144 if (*wlen == (size_t)-1) {
2145 err = got_error_from_errno("mbstowcs"); /* give up */
2146 goto done;
2150 *ws = calloc(*wlen + 1, sizeof(**ws));
2151 if (*ws == NULL) {
2152 err = got_error_from_errno("calloc");
2153 goto done;
2156 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2157 err = got_error_from_errno("mbstowcs");
2158 done:
2159 free(vis);
2160 if (err) {
2161 free(*ws);
2162 *ws = NULL;
2163 *wlen = 0;
2165 return err;
2168 static const struct got_error *
2169 expand_tab(char **ptr, const char *src)
2171 char *dst;
2172 size_t len, n, idx = 0, sz = 0;
2174 *ptr = NULL;
2175 n = len = strlen(src);
2176 dst = malloc(n + 1);
2177 if (dst == NULL)
2178 return got_error_from_errno("malloc");
2180 while (idx < len && src[idx]) {
2181 const char c = src[idx];
2183 if (c == '\t') {
2184 size_t nb = TABSIZE - sz % TABSIZE;
2185 char *p;
2187 p = realloc(dst, n + nb);
2188 if (p == NULL) {
2189 free(dst);
2190 return got_error_from_errno("realloc");
2193 dst = p;
2194 n += nb;
2195 memset(dst + sz, ' ', nb);
2196 sz += nb;
2197 } else
2198 dst[sz++] = src[idx];
2199 ++idx;
2202 dst[sz] = '\0';
2203 *ptr = dst;
2204 return NULL;
2208 * Advance at most n columns from wline starting at offset off.
2209 * Return the index to the first character after the span operation.
2210 * Return the combined column width of all spanned wide character in
2211 * *rcol.
2213 static int
2214 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2216 int width, i, cols = 0;
2218 if (n == 0) {
2219 *rcol = cols;
2220 return off;
2223 for (i = off; wline[i] != L'\0'; ++i) {
2224 if (wline[i] == L'\t')
2225 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2226 else
2227 width = wcwidth(wline[i]);
2229 if (width == -1) {
2230 width = 1;
2231 wline[i] = L'.';
2234 if (cols + width > n)
2235 break;
2236 cols += width;
2239 *rcol = cols;
2240 return i;
2244 * Format a line for display, ensuring that it won't overflow a width limit.
2245 * With scrolling, the width returned refers to the scrolled version of the
2246 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2248 static const struct got_error *
2249 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2250 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2252 const struct got_error *err = NULL;
2253 int cols;
2254 wchar_t *wline = NULL;
2255 char *exstr = NULL;
2256 size_t wlen;
2257 int i, scrollx;
2259 *wlinep = NULL;
2260 *widthp = 0;
2262 if (expand) {
2263 err = expand_tab(&exstr, line);
2264 if (err)
2265 return err;
2268 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2269 free(exstr);
2270 if (err)
2271 return err;
2273 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2275 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2276 wline[wlen - 1] = L'\0';
2277 wlen--;
2279 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2280 wline[wlen - 1] = L'\0';
2281 wlen--;
2284 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2285 wline[i] = L'\0';
2287 if (widthp)
2288 *widthp = cols;
2289 if (scrollxp)
2290 *scrollxp = scrollx;
2291 if (err)
2292 free(wline);
2293 else
2294 *wlinep = wline;
2295 return err;
2298 static const struct got_error*
2299 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2300 struct got_object_id *id, struct got_repository *repo)
2302 static const struct got_error *err = NULL;
2303 struct got_reflist_entry *re;
2304 char *s;
2305 const char *name;
2307 *refs_str = NULL;
2309 TAILQ_FOREACH(re, refs, entry) {
2310 struct got_tag_object *tag = NULL;
2311 struct got_object_id *ref_id;
2312 int cmp;
2314 name = got_ref_get_name(re->ref);
2315 if (strcmp(name, GOT_REF_HEAD) == 0)
2316 continue;
2317 if (strncmp(name, "refs/", 5) == 0)
2318 name += 5;
2319 if (strncmp(name, "got/", 4) == 0 &&
2320 strncmp(name, "got/backup/", 11) != 0)
2321 continue;
2322 if (strncmp(name, "heads/", 6) == 0)
2323 name += 6;
2324 if (strncmp(name, "remotes/", 8) == 0) {
2325 name += 8;
2326 s = strstr(name, "/" GOT_REF_HEAD);
2327 if (s != NULL && s[strlen(s)] == '\0')
2328 continue;
2330 err = got_ref_resolve(&ref_id, repo, re->ref);
2331 if (err)
2332 break;
2333 if (strncmp(name, "tags/", 5) == 0) {
2334 err = got_object_open_as_tag(&tag, repo, ref_id);
2335 if (err) {
2336 if (err->code != GOT_ERR_OBJ_TYPE) {
2337 free(ref_id);
2338 break;
2340 /* Ref points at something other than a tag. */
2341 err = NULL;
2342 tag = NULL;
2345 cmp = got_object_id_cmp(tag ?
2346 got_object_tag_get_object_id(tag) : ref_id, id);
2347 free(ref_id);
2348 if (tag)
2349 got_object_tag_close(tag);
2350 if (cmp != 0)
2351 continue;
2352 s = *refs_str;
2353 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2354 s ? ", " : "", name) == -1) {
2355 err = got_error_from_errno("asprintf");
2356 free(s);
2357 *refs_str = NULL;
2358 break;
2360 free(s);
2363 return err;
2366 static const struct got_error *
2367 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2368 int col_tab_align)
2370 char *smallerthan;
2372 smallerthan = strchr(author, '<');
2373 if (smallerthan && smallerthan[1] != '\0')
2374 author = smallerthan + 1;
2375 author[strcspn(author, "@>")] = '\0';
2376 return format_line(wauthor, author_width, NULL, author, 0, limit,
2377 col_tab_align, 0);
2380 static const struct got_error *
2381 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2382 struct got_object_id *id, const size_t date_display_cols,
2383 int author_display_cols)
2385 struct tog_log_view_state *s = &view->state.log;
2386 const struct got_error *err = NULL;
2387 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2388 char *logmsg0 = NULL, *logmsg = NULL;
2389 char *author = NULL;
2390 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2391 int author_width, logmsg_width;
2392 char *newline, *line = NULL;
2393 int col, limit, scrollx;
2394 const int avail = view->ncols;
2395 struct tm tm;
2396 time_t committer_time;
2397 struct tog_color *tc;
2399 committer_time = got_object_commit_get_committer_time(commit);
2400 if (gmtime_r(&committer_time, &tm) == NULL)
2401 return got_error_from_errno("gmtime_r");
2402 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2403 return got_error(GOT_ERR_NO_SPACE);
2405 if (avail <= date_display_cols)
2406 limit = MIN(sizeof(datebuf) - 1, avail);
2407 else
2408 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2409 tc = get_color(&s->colors, TOG_COLOR_DATE);
2410 if (tc)
2411 wattr_on(view->window,
2412 COLOR_PAIR(tc->colorpair), NULL);
2413 waddnstr(view->window, datebuf, limit);
2414 if (tc)
2415 wattr_off(view->window,
2416 COLOR_PAIR(tc->colorpair), NULL);
2417 col = limit;
2418 if (col > avail)
2419 goto done;
2421 if (avail >= 120) {
2422 char *id_str;
2423 err = got_object_id_str(&id_str, id);
2424 if (err)
2425 goto done;
2426 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2427 if (tc)
2428 wattr_on(view->window,
2429 COLOR_PAIR(tc->colorpair), NULL);
2430 wprintw(view->window, "%.8s ", id_str);
2431 if (tc)
2432 wattr_off(view->window,
2433 COLOR_PAIR(tc->colorpair), NULL);
2434 free(id_str);
2435 col += 9;
2436 if (col > avail)
2437 goto done;
2440 if (s->use_committer)
2441 author = strdup(got_object_commit_get_committer(commit));
2442 else
2443 author = strdup(got_object_commit_get_author(commit));
2444 if (author == NULL) {
2445 err = got_error_from_errno("strdup");
2446 goto done;
2448 err = format_author(&wauthor, &author_width, author, avail - col, col);
2449 if (err)
2450 goto done;
2451 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2452 if (tc)
2453 wattr_on(view->window,
2454 COLOR_PAIR(tc->colorpair), NULL);
2455 waddwstr(view->window, wauthor);
2456 col += author_width;
2457 while (col < avail && author_width < author_display_cols + 2) {
2458 waddch(view->window, ' ');
2459 col++;
2460 author_width++;
2462 if (tc)
2463 wattr_off(view->window,
2464 COLOR_PAIR(tc->colorpair), NULL);
2465 if (col > avail)
2466 goto done;
2468 err = got_object_commit_get_logmsg(&logmsg0, commit);
2469 if (err)
2470 goto done;
2471 logmsg = logmsg0;
2472 while (*logmsg == '\n')
2473 logmsg++;
2474 newline = strchr(logmsg, '\n');
2475 if (newline)
2476 *newline = '\0';
2477 limit = avail - col;
2478 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2479 limit--; /* for the border */
2480 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2481 limit, col, 1);
2482 if (err)
2483 goto done;
2484 waddwstr(view->window, &wlogmsg[scrollx]);
2485 col += MAX(logmsg_width, 0);
2486 while (col < avail) {
2487 waddch(view->window, ' ');
2488 col++;
2490 done:
2491 free(logmsg0);
2492 free(wlogmsg);
2493 free(author);
2494 free(wauthor);
2495 free(line);
2496 return err;
2499 static struct commit_queue_entry *
2500 alloc_commit_queue_entry(struct got_commit_object *commit,
2501 struct got_object_id *id)
2503 struct commit_queue_entry *entry;
2504 struct got_object_id *dup;
2506 entry = calloc(1, sizeof(*entry));
2507 if (entry == NULL)
2508 return NULL;
2510 dup = got_object_id_dup(id);
2511 if (dup == NULL) {
2512 free(entry);
2513 return NULL;
2516 entry->id = dup;
2517 entry->commit = commit;
2518 return entry;
2521 static void
2522 pop_commit(struct commit_queue *commits)
2524 struct commit_queue_entry *entry;
2526 entry = TAILQ_FIRST(&commits->head);
2527 TAILQ_REMOVE(&commits->head, entry, entry);
2528 got_object_commit_close(entry->commit);
2529 commits->ncommits--;
2530 free(entry->id);
2531 free(entry);
2534 static void
2535 free_commits(struct commit_queue *commits)
2537 while (!TAILQ_EMPTY(&commits->head))
2538 pop_commit(commits);
2541 static const struct got_error *
2542 match_commit(int *have_match, struct got_object_id *id,
2543 struct got_commit_object *commit, regex_t *regex)
2545 const struct got_error *err = NULL;
2546 regmatch_t regmatch;
2547 char *id_str = NULL, *logmsg = NULL;
2549 *have_match = 0;
2551 err = got_object_id_str(&id_str, id);
2552 if (err)
2553 return err;
2555 err = got_object_commit_get_logmsg(&logmsg, commit);
2556 if (err)
2557 goto done;
2559 if (regexec(regex, got_object_commit_get_author(commit), 1,
2560 &regmatch, 0) == 0 ||
2561 regexec(regex, got_object_commit_get_committer(commit), 1,
2562 &regmatch, 0) == 0 ||
2563 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2564 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2565 *have_match = 1;
2566 done:
2567 free(id_str);
2568 free(logmsg);
2569 return err;
2572 static const struct got_error *
2573 queue_commits(struct tog_log_thread_args *a)
2575 const struct got_error *err = NULL;
2578 * We keep all commits open throughout the lifetime of the log
2579 * view in order to avoid having to re-fetch commits from disk
2580 * while updating the display.
2582 do {
2583 struct got_object_id id;
2584 struct got_commit_object *commit;
2585 struct commit_queue_entry *entry;
2586 int limit_match = 0;
2587 int errcode;
2589 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2590 NULL, NULL);
2591 if (err)
2592 break;
2594 err = got_object_open_as_commit(&commit, a->repo, &id);
2595 if (err)
2596 break;
2597 entry = alloc_commit_queue_entry(commit, &id);
2598 if (entry == NULL) {
2599 err = got_error_from_errno("alloc_commit_queue_entry");
2600 break;
2603 errcode = pthread_mutex_lock(&tog_mutex);
2604 if (errcode) {
2605 err = got_error_set_errno(errcode,
2606 "pthread_mutex_lock");
2607 break;
2610 entry->idx = a->real_commits->ncommits;
2611 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2612 a->real_commits->ncommits++;
2614 if (*a->limiting) {
2615 err = match_commit(&limit_match, &id, commit,
2616 a->limit_regex);
2617 if (err)
2618 break;
2620 if (limit_match) {
2621 struct commit_queue_entry *matched;
2623 matched = alloc_commit_queue_entry(
2624 entry->commit, entry->id);
2625 if (matched == NULL) {
2626 err = got_error_from_errno(
2627 "alloc_commit_queue_entry");
2628 break;
2630 matched->commit = entry->commit;
2631 got_object_commit_retain(entry->commit);
2633 matched->idx = a->limit_commits->ncommits;
2634 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2635 matched, entry);
2636 a->limit_commits->ncommits++;
2640 * This is how we signal log_thread() that we
2641 * have found a match, and that it should be
2642 * counted as a new entry for the view.
2644 a->limit_match = limit_match;
2647 if (*a->searching == TOG_SEARCH_FORWARD &&
2648 !*a->search_next_done) {
2649 int have_match;
2650 err = match_commit(&have_match, &id, commit, a->regex);
2651 if (err)
2652 break;
2654 if (*a->limiting) {
2655 if (limit_match && have_match)
2656 *a->search_next_done =
2657 TOG_SEARCH_HAVE_MORE;
2658 } else if (have_match)
2659 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2662 errcode = pthread_mutex_unlock(&tog_mutex);
2663 if (errcode && err == NULL)
2664 err = got_error_set_errno(errcode,
2665 "pthread_mutex_unlock");
2666 if (err)
2667 break;
2668 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2670 return err;
2673 static void
2674 select_commit(struct tog_log_view_state *s)
2676 struct commit_queue_entry *entry;
2677 int ncommits = 0;
2679 entry = s->first_displayed_entry;
2680 while (entry) {
2681 if (ncommits == s->selected) {
2682 s->selected_entry = entry;
2683 break;
2685 entry = TAILQ_NEXT(entry, entry);
2686 ncommits++;
2690 static const struct got_error *
2691 draw_commits(struct tog_view *view)
2693 const struct got_error *err = NULL;
2694 struct tog_log_view_state *s = &view->state.log;
2695 struct commit_queue_entry *entry = s->selected_entry;
2696 int limit = view->nlines;
2697 int width;
2698 int ncommits, author_cols = 4;
2699 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2700 char *refs_str = NULL;
2701 wchar_t *wline;
2702 struct tog_color *tc;
2703 static const size_t date_display_cols = 12;
2705 if (view_is_hsplit_top(view))
2706 --limit; /* account for border */
2708 if (s->selected_entry &&
2709 !(view->searching && view->search_next_done == 0)) {
2710 struct got_reflist_head *refs;
2711 err = got_object_id_str(&id_str, s->selected_entry->id);
2712 if (err)
2713 return err;
2714 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2715 s->selected_entry->id);
2716 if (refs) {
2717 err = build_refs_str(&refs_str, refs,
2718 s->selected_entry->id, s->repo);
2719 if (err)
2720 goto done;
2724 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2725 halfdelay(10); /* disable fast refresh */
2727 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2728 if (asprintf(&ncommits_str, " [%d/%d] %s",
2729 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2730 (view->searching && !view->search_next_done) ?
2731 "searching..." : "loading...") == -1) {
2732 err = got_error_from_errno("asprintf");
2733 goto done;
2735 } else {
2736 const char *search_str = NULL;
2737 const char *limit_str = NULL;
2739 if (view->searching) {
2740 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2741 search_str = "no more matches";
2742 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2743 search_str = "no matches found";
2744 else if (!view->search_next_done)
2745 search_str = "searching...";
2748 if (s->limit_view && s->commits->ncommits == 0)
2749 limit_str = "no matches found";
2751 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2752 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2753 search_str ? search_str : (refs_str ? refs_str : ""),
2754 limit_str ? limit_str : "") == -1) {
2755 err = got_error_from_errno("asprintf");
2756 goto done;
2760 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2761 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2762 "........................................",
2763 s->in_repo_path, ncommits_str) == -1) {
2764 err = got_error_from_errno("asprintf");
2765 header = NULL;
2766 goto done;
2768 } else if (asprintf(&header, "commit %s%s",
2769 id_str ? id_str : "........................................",
2770 ncommits_str) == -1) {
2771 err = got_error_from_errno("asprintf");
2772 header = NULL;
2773 goto done;
2775 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2776 if (err)
2777 goto done;
2779 werase(view->window);
2781 if (view_needs_focus_indication(view))
2782 wstandout(view->window);
2783 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2784 if (tc)
2785 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2786 waddwstr(view->window, wline);
2787 while (width < view->ncols) {
2788 waddch(view->window, ' ');
2789 width++;
2791 if (tc)
2792 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2793 if (view_needs_focus_indication(view))
2794 wstandend(view->window);
2795 free(wline);
2796 if (limit <= 1)
2797 goto done;
2799 /* Grow author column size if necessary, and set view->maxx. */
2800 entry = s->first_displayed_entry;
2801 ncommits = 0;
2802 view->maxx = 0;
2803 while (entry) {
2804 struct got_commit_object *c = entry->commit;
2805 char *author, *eol, *msg, *msg0;
2806 wchar_t *wauthor, *wmsg;
2807 int width;
2808 if (ncommits >= limit - 1)
2809 break;
2810 if (s->use_committer)
2811 author = strdup(got_object_commit_get_committer(c));
2812 else
2813 author = strdup(got_object_commit_get_author(c));
2814 if (author == NULL) {
2815 err = got_error_from_errno("strdup");
2816 goto done;
2818 err = format_author(&wauthor, &width, author, COLS,
2819 date_display_cols);
2820 if (author_cols < width)
2821 author_cols = width;
2822 free(wauthor);
2823 free(author);
2824 if (err)
2825 goto done;
2826 err = got_object_commit_get_logmsg(&msg0, c);
2827 if (err)
2828 goto done;
2829 msg = msg0;
2830 while (*msg == '\n')
2831 ++msg;
2832 if ((eol = strchr(msg, '\n')))
2833 *eol = '\0';
2834 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2835 date_display_cols + author_cols, 0);
2836 if (err)
2837 goto done;
2838 view->maxx = MAX(view->maxx, width);
2839 free(msg0);
2840 free(wmsg);
2841 ncommits++;
2842 entry = TAILQ_NEXT(entry, entry);
2845 entry = s->first_displayed_entry;
2846 s->last_displayed_entry = s->first_displayed_entry;
2847 ncommits = 0;
2848 while (entry) {
2849 if (ncommits >= limit - 1)
2850 break;
2851 if (ncommits == s->selected)
2852 wstandout(view->window);
2853 err = draw_commit(view, entry->commit, entry->id,
2854 date_display_cols, author_cols);
2855 if (ncommits == s->selected)
2856 wstandend(view->window);
2857 if (err)
2858 goto done;
2859 ncommits++;
2860 s->last_displayed_entry = entry;
2861 entry = TAILQ_NEXT(entry, entry);
2864 view_border(view);
2865 done:
2866 free(id_str);
2867 free(refs_str);
2868 free(ncommits_str);
2869 free(header);
2870 return err;
2873 static void
2874 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2876 struct commit_queue_entry *entry;
2877 int nscrolled = 0;
2879 entry = TAILQ_FIRST(&s->commits->head);
2880 if (s->first_displayed_entry == entry)
2881 return;
2883 entry = s->first_displayed_entry;
2884 while (entry && nscrolled < maxscroll) {
2885 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2886 if (entry) {
2887 s->first_displayed_entry = entry;
2888 nscrolled++;
2893 static const struct got_error *
2894 trigger_log_thread(struct tog_view *view, int wait)
2896 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2897 int errcode;
2899 if (!using_mock_io)
2900 halfdelay(1); /* fast refresh while loading commits */
2902 while (!ta->log_complete && !tog_thread_error &&
2903 (ta->commits_needed > 0 || ta->load_all)) {
2904 /* Wake the log thread. */
2905 errcode = pthread_cond_signal(&ta->need_commits);
2906 if (errcode)
2907 return got_error_set_errno(errcode,
2908 "pthread_cond_signal");
2911 * The mutex will be released while the view loop waits
2912 * in wgetch(), at which time the log thread will run.
2914 if (!wait)
2915 break;
2917 /* Display progress update in log view. */
2918 show_log_view(view);
2919 update_panels();
2920 doupdate();
2922 /* Wait right here while next commit is being loaded. */
2923 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2924 if (errcode)
2925 return got_error_set_errno(errcode,
2926 "pthread_cond_wait");
2928 /* Display progress update in log view. */
2929 show_log_view(view);
2930 update_panels();
2931 doupdate();
2934 return NULL;
2937 static const struct got_error *
2938 request_log_commits(struct tog_view *view)
2940 struct tog_log_view_state *state = &view->state.log;
2941 const struct got_error *err = NULL;
2943 if (state->thread_args.log_complete)
2944 return NULL;
2946 state->thread_args.commits_needed += view->nscrolled;
2947 err = trigger_log_thread(view, 1);
2948 view->nscrolled = 0;
2950 return err;
2953 static const struct got_error *
2954 log_scroll_down(struct tog_view *view, int maxscroll)
2956 struct tog_log_view_state *s = &view->state.log;
2957 const struct got_error *err = NULL;
2958 struct commit_queue_entry *pentry;
2959 int nscrolled = 0, ncommits_needed;
2961 if (s->last_displayed_entry == NULL)
2962 return NULL;
2964 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2965 if (s->commits->ncommits < ncommits_needed &&
2966 !s->thread_args.log_complete) {
2968 * Ask the log thread for required amount of commits.
2970 s->thread_args.commits_needed +=
2971 ncommits_needed - s->commits->ncommits;
2972 err = trigger_log_thread(view, 1);
2973 if (err)
2974 return err;
2977 do {
2978 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2979 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2980 break;
2982 s->last_displayed_entry = pentry ?
2983 pentry : s->last_displayed_entry;
2985 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2986 if (pentry == NULL)
2987 break;
2988 s->first_displayed_entry = pentry;
2989 } while (++nscrolled < maxscroll);
2991 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2992 view->nscrolled += nscrolled;
2993 else
2994 view->nscrolled = 0;
2996 return err;
2999 static const struct got_error *
3000 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3001 struct got_commit_object *commit, struct got_object_id *commit_id,
3002 struct tog_view *log_view, struct got_repository *repo)
3004 const struct got_error *err;
3005 struct got_object_qid *parent_id;
3006 struct tog_view *diff_view;
3008 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3009 if (diff_view == NULL)
3010 return got_error_from_errno("view_open");
3012 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3013 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3014 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3015 if (err == NULL)
3016 *new_view = diff_view;
3017 return err;
3020 static const struct got_error *
3021 tree_view_visit_subtree(struct tog_tree_view_state *s,
3022 struct got_tree_object *subtree)
3024 struct tog_parent_tree *parent;
3026 parent = calloc(1, sizeof(*parent));
3027 if (parent == NULL)
3028 return got_error_from_errno("calloc");
3030 parent->tree = s->tree;
3031 parent->first_displayed_entry = s->first_displayed_entry;
3032 parent->selected_entry = s->selected_entry;
3033 parent->selected = s->selected;
3034 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3035 s->tree = subtree;
3036 s->selected = 0;
3037 s->first_displayed_entry = NULL;
3038 return NULL;
3041 static const struct got_error *
3042 tree_view_walk_path(struct tog_tree_view_state *s,
3043 struct got_commit_object *commit, const char *path)
3045 const struct got_error *err = NULL;
3046 struct got_tree_object *tree = NULL;
3047 const char *p;
3048 char *slash, *subpath = NULL;
3050 /* Walk the path and open corresponding tree objects. */
3051 p = path;
3052 while (*p) {
3053 struct got_tree_entry *te;
3054 struct got_object_id *tree_id;
3055 char *te_name;
3057 while (p[0] == '/')
3058 p++;
3060 /* Ensure the correct subtree entry is selected. */
3061 slash = strchr(p, '/');
3062 if (slash == NULL)
3063 te_name = strdup(p);
3064 else
3065 te_name = strndup(p, slash - p);
3066 if (te_name == NULL) {
3067 err = got_error_from_errno("strndup");
3068 break;
3070 te = got_object_tree_find_entry(s->tree, te_name);
3071 if (te == NULL) {
3072 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3073 free(te_name);
3074 break;
3076 free(te_name);
3077 s->first_displayed_entry = s->selected_entry = te;
3079 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3080 break; /* jump to this file's entry */
3082 slash = strchr(p, '/');
3083 if (slash)
3084 subpath = strndup(path, slash - path);
3085 else
3086 subpath = strdup(path);
3087 if (subpath == NULL) {
3088 err = got_error_from_errno("strdup");
3089 break;
3092 err = got_object_id_by_path(&tree_id, s->repo, commit,
3093 subpath);
3094 if (err)
3095 break;
3097 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3098 free(tree_id);
3099 if (err)
3100 break;
3102 err = tree_view_visit_subtree(s, tree);
3103 if (err) {
3104 got_object_tree_close(tree);
3105 break;
3107 if (slash == NULL)
3108 break;
3109 free(subpath);
3110 subpath = NULL;
3111 p = slash;
3114 free(subpath);
3115 return err;
3118 static const struct got_error *
3119 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3120 struct commit_queue_entry *entry, const char *path,
3121 const char *head_ref_name, struct got_repository *repo)
3123 const struct got_error *err = NULL;
3124 struct tog_tree_view_state *s;
3125 struct tog_view *tree_view;
3127 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3128 if (tree_view == NULL)
3129 return got_error_from_errno("view_open");
3131 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3132 if (err)
3133 return err;
3134 s = &tree_view->state.tree;
3136 *new_view = tree_view;
3138 if (got_path_is_root_dir(path))
3139 return NULL;
3141 return tree_view_walk_path(s, entry->commit, path);
3144 static const struct got_error *
3145 block_signals_used_by_main_thread(void)
3147 sigset_t sigset;
3148 int errcode;
3150 if (sigemptyset(&sigset) == -1)
3151 return got_error_from_errno("sigemptyset");
3153 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3154 if (sigaddset(&sigset, SIGWINCH) == -1)
3155 return got_error_from_errno("sigaddset");
3156 if (sigaddset(&sigset, SIGCONT) == -1)
3157 return got_error_from_errno("sigaddset");
3158 if (sigaddset(&sigset, SIGINT) == -1)
3159 return got_error_from_errno("sigaddset");
3160 if (sigaddset(&sigset, SIGTERM) == -1)
3161 return got_error_from_errno("sigaddset");
3163 /* ncurses handles SIGTSTP */
3164 if (sigaddset(&sigset, SIGTSTP) == -1)
3165 return got_error_from_errno("sigaddset");
3167 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3168 if (errcode)
3169 return got_error_set_errno(errcode, "pthread_sigmask");
3171 return NULL;
3174 static void *
3175 log_thread(void *arg)
3177 const struct got_error *err = NULL;
3178 int errcode = 0;
3179 struct tog_log_thread_args *a = arg;
3180 int done = 0;
3183 * Sync startup with main thread such that we begin our
3184 * work once view_input() has released the mutex.
3186 errcode = pthread_mutex_lock(&tog_mutex);
3187 if (errcode) {
3188 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3189 return (void *)err;
3192 err = block_signals_used_by_main_thread();
3193 if (err) {
3194 pthread_mutex_unlock(&tog_mutex);
3195 goto done;
3198 while (!done && !err && !tog_fatal_signal_received()) {
3199 errcode = pthread_mutex_unlock(&tog_mutex);
3200 if (errcode) {
3201 err = got_error_set_errno(errcode,
3202 "pthread_mutex_unlock");
3203 goto done;
3205 err = queue_commits(a);
3206 if (err) {
3207 if (err->code != GOT_ERR_ITER_COMPLETED)
3208 goto done;
3209 err = NULL;
3210 done = 1;
3211 } else if (a->commits_needed > 0 && !a->load_all) {
3212 if (*a->limiting) {
3213 if (a->limit_match)
3214 a->commits_needed--;
3215 } else
3216 a->commits_needed--;
3219 errcode = pthread_mutex_lock(&tog_mutex);
3220 if (errcode) {
3221 err = got_error_set_errno(errcode,
3222 "pthread_mutex_lock");
3223 goto done;
3224 } else if (*a->quit)
3225 done = 1;
3226 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3227 *a->first_displayed_entry =
3228 TAILQ_FIRST(&a->limit_commits->head);
3229 *a->selected_entry = *a->first_displayed_entry;
3230 } else if (*a->first_displayed_entry == NULL) {
3231 *a->first_displayed_entry =
3232 TAILQ_FIRST(&a->real_commits->head);
3233 *a->selected_entry = *a->first_displayed_entry;
3236 errcode = pthread_cond_signal(&a->commit_loaded);
3237 if (errcode) {
3238 err = got_error_set_errno(errcode,
3239 "pthread_cond_signal");
3240 pthread_mutex_unlock(&tog_mutex);
3241 goto done;
3244 if (done)
3245 a->commits_needed = 0;
3246 else {
3247 if (a->commits_needed == 0 && !a->load_all) {
3248 errcode = pthread_cond_wait(&a->need_commits,
3249 &tog_mutex);
3250 if (errcode) {
3251 err = got_error_set_errno(errcode,
3252 "pthread_cond_wait");
3253 pthread_mutex_unlock(&tog_mutex);
3254 goto done;
3256 if (*a->quit)
3257 done = 1;
3261 a->log_complete = 1;
3262 errcode = pthread_mutex_unlock(&tog_mutex);
3263 if (errcode)
3264 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3265 done:
3266 if (err) {
3267 tog_thread_error = 1;
3268 pthread_cond_signal(&a->commit_loaded);
3270 return (void *)err;
3273 static const struct got_error *
3274 stop_log_thread(struct tog_log_view_state *s)
3276 const struct got_error *err = NULL, *thread_err = NULL;
3277 int errcode;
3279 if (s->thread) {
3280 s->quit = 1;
3281 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3282 if (errcode)
3283 return got_error_set_errno(errcode,
3284 "pthread_cond_signal");
3285 errcode = pthread_mutex_unlock(&tog_mutex);
3286 if (errcode)
3287 return got_error_set_errno(errcode,
3288 "pthread_mutex_unlock");
3289 errcode = pthread_join(s->thread, (void **)&thread_err);
3290 if (errcode)
3291 return got_error_set_errno(errcode, "pthread_join");
3292 errcode = pthread_mutex_lock(&tog_mutex);
3293 if (errcode)
3294 return got_error_set_errno(errcode,
3295 "pthread_mutex_lock");
3296 s->thread = NULL;
3299 if (s->thread_args.repo) {
3300 err = got_repo_close(s->thread_args.repo);
3301 s->thread_args.repo = NULL;
3304 if (s->thread_args.pack_fds) {
3305 const struct got_error *pack_err =
3306 got_repo_pack_fds_close(s->thread_args.pack_fds);
3307 if (err == NULL)
3308 err = pack_err;
3309 s->thread_args.pack_fds = NULL;
3312 if (s->thread_args.graph) {
3313 got_commit_graph_close(s->thread_args.graph);
3314 s->thread_args.graph = NULL;
3317 return err ? err : thread_err;
3320 static const struct got_error *
3321 close_log_view(struct tog_view *view)
3323 const struct got_error *err = NULL;
3324 struct tog_log_view_state *s = &view->state.log;
3325 int errcode;
3327 err = stop_log_thread(s);
3329 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3330 if (errcode && err == NULL)
3331 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3333 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3334 if (errcode && err == NULL)
3335 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3337 free_commits(&s->limit_commits);
3338 free_commits(&s->real_commits);
3339 free(s->in_repo_path);
3340 s->in_repo_path = NULL;
3341 free(s->start_id);
3342 s->start_id = NULL;
3343 free(s->head_ref_name);
3344 s->head_ref_name = NULL;
3345 return err;
3349 * We use two queues to implement the limit feature: first consists of
3350 * commits matching the current limit_regex; second is the real queue
3351 * of all known commits (real_commits). When the user starts limiting,
3352 * we swap queues such that all movement and displaying functionality
3353 * works with very slight change.
3355 static const struct got_error *
3356 limit_log_view(struct tog_view *view)
3358 struct tog_log_view_state *s = &view->state.log;
3359 struct commit_queue_entry *entry;
3360 struct tog_view *v = view;
3361 const struct got_error *err = NULL;
3362 char pattern[1024];
3363 int ret;
3365 if (view_is_hsplit_top(view))
3366 v = view->child;
3367 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3368 v = view->parent;
3370 /* Get the pattern */
3371 wmove(v->window, v->nlines - 1, 0);
3372 wclrtoeol(v->window);
3373 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3374 nodelay(v->window, FALSE);
3375 nocbreak();
3376 echo();
3377 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3378 cbreak();
3379 noecho();
3380 nodelay(v->window, TRUE);
3381 if (ret == ERR)
3382 return NULL;
3384 if (*pattern == '\0') {
3386 * Safety measure for the situation where the user
3387 * resets limit without previously limiting anything.
3389 if (!s->limit_view)
3390 return NULL;
3393 * User could have pressed Ctrl+L, which refreshed the
3394 * commit queues, it means we can't save previously
3395 * (before limit took place) displayed entries,
3396 * because they would point to already free'ed memory,
3397 * so we are forced to always select first entry of
3398 * the queue.
3400 s->commits = &s->real_commits;
3401 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3402 s->selected_entry = s->first_displayed_entry;
3403 s->selected = 0;
3404 s->limit_view = 0;
3406 return NULL;
3409 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3410 return NULL;
3412 s->limit_view = 1;
3414 /* Clear the screen while loading limit view */
3415 s->first_displayed_entry = NULL;
3416 s->last_displayed_entry = NULL;
3417 s->selected_entry = NULL;
3418 s->commits = &s->limit_commits;
3420 /* Prepare limit queue for new search */
3421 free_commits(&s->limit_commits);
3422 s->limit_commits.ncommits = 0;
3424 /* First process commits, which are in queue already */
3425 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3426 int have_match = 0;
3428 err = match_commit(&have_match, entry->id,
3429 entry->commit, &s->limit_regex);
3430 if (err)
3431 return err;
3433 if (have_match) {
3434 struct commit_queue_entry *matched;
3436 matched = alloc_commit_queue_entry(entry->commit,
3437 entry->id);
3438 if (matched == NULL) {
3439 err = got_error_from_errno(
3440 "alloc_commit_queue_entry");
3441 break;
3443 matched->commit = entry->commit;
3444 got_object_commit_retain(entry->commit);
3446 matched->idx = s->limit_commits.ncommits;
3447 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3448 matched, entry);
3449 s->limit_commits.ncommits++;
3453 /* Second process all the commits, until we fill the screen */
3454 if (s->limit_commits.ncommits < view->nlines - 1 &&
3455 !s->thread_args.log_complete) {
3456 s->thread_args.commits_needed +=
3457 view->nlines - s->limit_commits.ncommits - 1;
3458 err = trigger_log_thread(view, 1);
3459 if (err)
3460 return err;
3463 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3464 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3465 s->selected = 0;
3467 return NULL;
3470 static const struct got_error *
3471 search_start_log_view(struct tog_view *view)
3473 struct tog_log_view_state *s = &view->state.log;
3475 s->matched_entry = NULL;
3476 s->search_entry = NULL;
3477 return NULL;
3480 static const struct got_error *
3481 search_next_log_view(struct tog_view *view)
3483 const struct got_error *err = NULL;
3484 struct tog_log_view_state *s = &view->state.log;
3485 struct commit_queue_entry *entry;
3487 /* Display progress update in log view. */
3488 show_log_view(view);
3489 update_panels();
3490 doupdate();
3492 if (s->search_entry) {
3493 int errcode, ch;
3494 errcode = pthread_mutex_unlock(&tog_mutex);
3495 if (errcode)
3496 return got_error_set_errno(errcode,
3497 "pthread_mutex_unlock");
3498 ch = wgetch(view->window);
3499 errcode = pthread_mutex_lock(&tog_mutex);
3500 if (errcode)
3501 return got_error_set_errno(errcode,
3502 "pthread_mutex_lock");
3503 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3504 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3505 return NULL;
3507 if (view->searching == TOG_SEARCH_FORWARD)
3508 entry = TAILQ_NEXT(s->search_entry, entry);
3509 else
3510 entry = TAILQ_PREV(s->search_entry,
3511 commit_queue_head, entry);
3512 } else if (s->matched_entry) {
3514 * If the user has moved the cursor after we hit a match,
3515 * the position from where we should continue searching
3516 * might have changed.
3518 if (view->searching == TOG_SEARCH_FORWARD)
3519 entry = TAILQ_NEXT(s->selected_entry, entry);
3520 else
3521 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3522 entry);
3523 } else {
3524 entry = s->selected_entry;
3527 while (1) {
3528 int have_match = 0;
3530 if (entry == NULL) {
3531 if (s->thread_args.log_complete ||
3532 view->searching == TOG_SEARCH_BACKWARD) {
3533 view->search_next_done =
3534 (s->matched_entry == NULL ?
3535 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3536 s->search_entry = NULL;
3537 return NULL;
3540 * Poke the log thread for more commits and return,
3541 * allowing the main loop to make progress. Search
3542 * will resume at s->search_entry once we come back.
3544 s->thread_args.commits_needed++;
3545 return trigger_log_thread(view, 0);
3548 err = match_commit(&have_match, entry->id, entry->commit,
3549 &view->regex);
3550 if (err)
3551 break;
3552 if (have_match) {
3553 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3554 s->matched_entry = entry;
3555 break;
3558 s->search_entry = entry;
3559 if (view->searching == TOG_SEARCH_FORWARD)
3560 entry = TAILQ_NEXT(entry, entry);
3561 else
3562 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3565 if (s->matched_entry) {
3566 int cur = s->selected_entry->idx;
3567 while (cur < s->matched_entry->idx) {
3568 err = input_log_view(NULL, view, KEY_DOWN);
3569 if (err)
3570 return err;
3571 cur++;
3573 while (cur > s->matched_entry->idx) {
3574 err = input_log_view(NULL, view, KEY_UP);
3575 if (err)
3576 return err;
3577 cur--;
3581 s->search_entry = NULL;
3583 return NULL;
3586 static const struct got_error *
3587 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3588 struct got_repository *repo, const char *head_ref_name,
3589 const char *in_repo_path, int log_branches)
3591 const struct got_error *err = NULL;
3592 struct tog_log_view_state *s = &view->state.log;
3593 struct got_repository *thread_repo = NULL;
3594 struct got_commit_graph *thread_graph = NULL;
3595 int errcode;
3597 if (in_repo_path != s->in_repo_path) {
3598 free(s->in_repo_path);
3599 s->in_repo_path = strdup(in_repo_path);
3600 if (s->in_repo_path == NULL) {
3601 err = got_error_from_errno("strdup");
3602 goto done;
3606 /* The commit queue only contains commits being displayed. */
3607 TAILQ_INIT(&s->real_commits.head);
3608 s->real_commits.ncommits = 0;
3609 s->commits = &s->real_commits;
3611 TAILQ_INIT(&s->limit_commits.head);
3612 s->limit_view = 0;
3613 s->limit_commits.ncommits = 0;
3615 s->repo = repo;
3616 if (head_ref_name) {
3617 s->head_ref_name = strdup(head_ref_name);
3618 if (s->head_ref_name == NULL) {
3619 err = got_error_from_errno("strdup");
3620 goto done;
3623 s->start_id = got_object_id_dup(start_id);
3624 if (s->start_id == NULL) {
3625 err = got_error_from_errno("got_object_id_dup");
3626 goto done;
3628 s->log_branches = log_branches;
3629 s->use_committer = 1;
3631 STAILQ_INIT(&s->colors);
3632 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3633 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3634 get_color_value("TOG_COLOR_COMMIT"));
3635 if (err)
3636 goto done;
3637 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3638 get_color_value("TOG_COLOR_AUTHOR"));
3639 if (err) {
3640 free_colors(&s->colors);
3641 goto done;
3643 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3644 get_color_value("TOG_COLOR_DATE"));
3645 if (err) {
3646 free_colors(&s->colors);
3647 goto done;
3651 view->show = show_log_view;
3652 view->input = input_log_view;
3653 view->resize = resize_log_view;
3654 view->close = close_log_view;
3655 view->search_start = search_start_log_view;
3656 view->search_next = search_next_log_view;
3658 if (s->thread_args.pack_fds == NULL) {
3659 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3660 if (err)
3661 goto done;
3663 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3664 s->thread_args.pack_fds);
3665 if (err)
3666 goto done;
3667 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3668 !s->log_branches);
3669 if (err)
3670 goto done;
3671 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3672 s->repo, NULL, NULL);
3673 if (err)
3674 goto done;
3676 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3677 if (errcode) {
3678 err = got_error_set_errno(errcode, "pthread_cond_init");
3679 goto done;
3681 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3682 if (errcode) {
3683 err = got_error_set_errno(errcode, "pthread_cond_init");
3684 goto done;
3687 s->thread_args.commits_needed = view->nlines;
3688 s->thread_args.graph = thread_graph;
3689 s->thread_args.real_commits = &s->real_commits;
3690 s->thread_args.limit_commits = &s->limit_commits;
3691 s->thread_args.in_repo_path = s->in_repo_path;
3692 s->thread_args.start_id = s->start_id;
3693 s->thread_args.repo = thread_repo;
3694 s->thread_args.log_complete = 0;
3695 s->thread_args.quit = &s->quit;
3696 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3697 s->thread_args.selected_entry = &s->selected_entry;
3698 s->thread_args.searching = &view->searching;
3699 s->thread_args.search_next_done = &view->search_next_done;
3700 s->thread_args.regex = &view->regex;
3701 s->thread_args.limiting = &s->limit_view;
3702 s->thread_args.limit_regex = &s->limit_regex;
3703 s->thread_args.limit_commits = &s->limit_commits;
3704 done:
3705 if (err) {
3706 if (view->close == NULL)
3707 close_log_view(view);
3708 view_close(view);
3710 return err;
3713 static const struct got_error *
3714 show_log_view(struct tog_view *view)
3716 const struct got_error *err;
3717 struct tog_log_view_state *s = &view->state.log;
3719 if (s->thread == NULL) {
3720 int errcode = pthread_create(&s->thread, NULL, log_thread,
3721 &s->thread_args);
3722 if (errcode)
3723 return got_error_set_errno(errcode, "pthread_create");
3724 if (s->thread_args.commits_needed > 0) {
3725 err = trigger_log_thread(view, 1);
3726 if (err)
3727 return err;
3731 return draw_commits(view);
3734 static void
3735 log_move_cursor_up(struct tog_view *view, int page, int home)
3737 struct tog_log_view_state *s = &view->state.log;
3739 if (s->first_displayed_entry == NULL)
3740 return;
3741 if (s->selected_entry->idx == 0)
3742 view->count = 0;
3744 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3745 || home)
3746 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3748 if (!page && !home && s->selected > 0)
3749 --s->selected;
3750 else
3751 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3753 select_commit(s);
3754 return;
3757 static const struct got_error *
3758 log_move_cursor_down(struct tog_view *view, int page)
3760 struct tog_log_view_state *s = &view->state.log;
3761 const struct got_error *err = NULL;
3762 int eos = view->nlines - 2;
3764 if (s->first_displayed_entry == NULL)
3765 return NULL;
3767 if (s->thread_args.log_complete &&
3768 s->selected_entry->idx >= s->commits->ncommits - 1)
3769 return NULL;
3771 if (view_is_hsplit_top(view))
3772 --eos; /* border consumes the last line */
3774 if (!page) {
3775 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3776 ++s->selected;
3777 else
3778 err = log_scroll_down(view, 1);
3779 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3780 struct commit_queue_entry *entry;
3781 int n;
3783 s->selected = 0;
3784 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3785 s->last_displayed_entry = entry;
3786 for (n = 0; n <= eos; n++) {
3787 if (entry == NULL)
3788 break;
3789 s->first_displayed_entry = entry;
3790 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3792 if (n > 0)
3793 s->selected = n - 1;
3794 } else {
3795 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3796 s->thread_args.log_complete)
3797 s->selected += MIN(page,
3798 s->commits->ncommits - s->selected_entry->idx - 1);
3799 else
3800 err = log_scroll_down(view, page);
3802 if (err)
3803 return err;
3806 * We might necessarily overshoot in horizontal
3807 * splits; if so, select the last displayed commit.
3809 if (s->first_displayed_entry && s->last_displayed_entry) {
3810 s->selected = MIN(s->selected,
3811 s->last_displayed_entry->idx -
3812 s->first_displayed_entry->idx);
3815 select_commit(s);
3817 if (s->thread_args.log_complete &&
3818 s->selected_entry->idx == s->commits->ncommits - 1)
3819 view->count = 0;
3821 return NULL;
3824 static void
3825 view_get_split(struct tog_view *view, int *y, int *x)
3827 *x = 0;
3828 *y = 0;
3830 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3831 if (view->child && view->child->resized_y)
3832 *y = view->child->resized_y;
3833 else if (view->resized_y)
3834 *y = view->resized_y;
3835 else
3836 *y = view_split_begin_y(view->lines);
3837 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3838 if (view->child && view->child->resized_x)
3839 *x = view->child->resized_x;
3840 else if (view->resized_x)
3841 *x = view->resized_x;
3842 else
3843 *x = view_split_begin_x(view->begin_x);
3847 /* Split view horizontally at y and offset view->state->selected line. */
3848 static const struct got_error *
3849 view_init_hsplit(struct tog_view *view, int y)
3851 const struct got_error *err = NULL;
3853 view->nlines = y;
3854 view->ncols = COLS;
3855 err = view_resize(view);
3856 if (err)
3857 return err;
3859 err = offset_selection_down(view);
3861 return err;
3864 static const struct got_error *
3865 log_goto_line(struct tog_view *view, int nlines)
3867 const struct got_error *err = NULL;
3868 struct tog_log_view_state *s = &view->state.log;
3869 int g, idx = s->selected_entry->idx;
3871 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3872 return NULL;
3874 g = view->gline;
3875 view->gline = 0;
3877 if (g >= s->first_displayed_entry->idx + 1 &&
3878 g <= s->last_displayed_entry->idx + 1 &&
3879 g - s->first_displayed_entry->idx - 1 < nlines) {
3880 s->selected = g - s->first_displayed_entry->idx - 1;
3881 select_commit(s);
3882 return NULL;
3885 if (idx + 1 < g) {
3886 err = log_move_cursor_down(view, g - idx - 1);
3887 if (!err && g > s->selected_entry->idx + 1)
3888 err = log_move_cursor_down(view,
3889 g - s->first_displayed_entry->idx - 1);
3890 if (err)
3891 return err;
3892 } else if (idx + 1 > g)
3893 log_move_cursor_up(view, idx - g + 1, 0);
3895 if (g < nlines && s->first_displayed_entry->idx == 0)
3896 s->selected = g - 1;
3898 select_commit(s);
3899 return NULL;
3903 static void
3904 horizontal_scroll_input(struct tog_view *view, int ch)
3907 switch (ch) {
3908 case KEY_LEFT:
3909 case 'h':
3910 view->x -= MIN(view->x, 2);
3911 if (view->x <= 0)
3912 view->count = 0;
3913 break;
3914 case KEY_RIGHT:
3915 case 'l':
3916 if (view->x + view->ncols / 2 < view->maxx)
3917 view->x += 2;
3918 else
3919 view->count = 0;
3920 break;
3921 case '0':
3922 view->x = 0;
3923 break;
3924 case '$':
3925 view->x = MAX(view->maxx - view->ncols / 2, 0);
3926 view->count = 0;
3927 break;
3928 default:
3929 break;
3933 static const struct got_error *
3934 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3936 const struct got_error *err = NULL;
3937 struct tog_log_view_state *s = &view->state.log;
3938 int eos, nscroll;
3940 if (s->thread_args.load_all) {
3941 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3942 s->thread_args.load_all = 0;
3943 else if (s->thread_args.log_complete) {
3944 err = log_move_cursor_down(view, s->commits->ncommits);
3945 s->thread_args.load_all = 0;
3947 if (err)
3948 return err;
3951 eos = nscroll = view->nlines - 1;
3952 if (view_is_hsplit_top(view))
3953 --eos; /* border */
3955 if (view->gline)
3956 return log_goto_line(view, eos);
3958 switch (ch) {
3959 case '&':
3960 err = limit_log_view(view);
3961 break;
3962 case 'q':
3963 s->quit = 1;
3964 break;
3965 case '0':
3966 case '$':
3967 case KEY_RIGHT:
3968 case 'l':
3969 case KEY_LEFT:
3970 case 'h':
3971 horizontal_scroll_input(view, ch);
3972 break;
3973 case 'k':
3974 case KEY_UP:
3975 case '<':
3976 case ',':
3977 case CTRL('p'):
3978 log_move_cursor_up(view, 0, 0);
3979 break;
3980 case 'g':
3981 case '=':
3982 case KEY_HOME:
3983 log_move_cursor_up(view, 0, 1);
3984 view->count = 0;
3985 break;
3986 case CTRL('u'):
3987 case 'u':
3988 nscroll /= 2;
3989 /* FALL THROUGH */
3990 case KEY_PPAGE:
3991 case CTRL('b'):
3992 case 'b':
3993 log_move_cursor_up(view, nscroll, 0);
3994 break;
3995 case 'j':
3996 case KEY_DOWN:
3997 case '>':
3998 case '.':
3999 case CTRL('n'):
4000 err = log_move_cursor_down(view, 0);
4001 break;
4002 case '@':
4003 s->use_committer = !s->use_committer;
4004 view->action = s->use_committer ?
4005 "show committer" : "show commit author";
4006 break;
4007 case 'G':
4008 case '*':
4009 case KEY_END: {
4010 /* We don't know yet how many commits, so we're forced to
4011 * traverse them all. */
4012 view->count = 0;
4013 s->thread_args.load_all = 1;
4014 if (!s->thread_args.log_complete)
4015 return trigger_log_thread(view, 0);
4016 err = log_move_cursor_down(view, s->commits->ncommits);
4017 s->thread_args.load_all = 0;
4018 break;
4020 case CTRL('d'):
4021 case 'd':
4022 nscroll /= 2;
4023 /* FALL THROUGH */
4024 case KEY_NPAGE:
4025 case CTRL('f'):
4026 case 'f':
4027 case ' ':
4028 err = log_move_cursor_down(view, nscroll);
4029 break;
4030 case KEY_RESIZE:
4031 if (s->selected > view->nlines - 2)
4032 s->selected = view->nlines - 2;
4033 if (s->selected > s->commits->ncommits - 1)
4034 s->selected = s->commits->ncommits - 1;
4035 select_commit(s);
4036 if (s->commits->ncommits < view->nlines - 1 &&
4037 !s->thread_args.log_complete) {
4038 s->thread_args.commits_needed += (view->nlines - 1) -
4039 s->commits->ncommits;
4040 err = trigger_log_thread(view, 1);
4042 break;
4043 case KEY_ENTER:
4044 case '\r':
4045 view->count = 0;
4046 if (s->selected_entry == NULL)
4047 break;
4048 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4049 break;
4050 case 'T':
4051 view->count = 0;
4052 if (s->selected_entry == NULL)
4053 break;
4054 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4055 break;
4056 case KEY_BACKSPACE:
4057 case CTRL('l'):
4058 case 'B':
4059 view->count = 0;
4060 if (ch == KEY_BACKSPACE &&
4061 got_path_is_root_dir(s->in_repo_path))
4062 break;
4063 err = stop_log_thread(s);
4064 if (err)
4065 return err;
4066 if (ch == KEY_BACKSPACE) {
4067 char *parent_path;
4068 err = got_path_dirname(&parent_path, s->in_repo_path);
4069 if (err)
4070 return err;
4071 free(s->in_repo_path);
4072 s->in_repo_path = parent_path;
4073 s->thread_args.in_repo_path = s->in_repo_path;
4074 } else if (ch == CTRL('l')) {
4075 struct got_object_id *start_id;
4076 err = got_repo_match_object_id(&start_id, NULL,
4077 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4078 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4079 if (err) {
4080 if (s->head_ref_name == NULL ||
4081 err->code != GOT_ERR_NOT_REF)
4082 return err;
4083 /* Try to cope with deleted references. */
4084 free(s->head_ref_name);
4085 s->head_ref_name = NULL;
4086 err = got_repo_match_object_id(&start_id,
4087 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4088 &tog_refs, s->repo);
4089 if (err)
4090 return err;
4092 free(s->start_id);
4093 s->start_id = start_id;
4094 s->thread_args.start_id = s->start_id;
4095 } else /* 'B' */
4096 s->log_branches = !s->log_branches;
4098 if (s->thread_args.pack_fds == NULL) {
4099 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4100 if (err)
4101 return err;
4103 err = got_repo_open(&s->thread_args.repo,
4104 got_repo_get_path(s->repo), NULL,
4105 s->thread_args.pack_fds);
4106 if (err)
4107 return err;
4108 tog_free_refs();
4109 err = tog_load_refs(s->repo, 0);
4110 if (err)
4111 return err;
4112 err = got_commit_graph_open(&s->thread_args.graph,
4113 s->in_repo_path, !s->log_branches);
4114 if (err)
4115 return err;
4116 err = got_commit_graph_iter_start(s->thread_args.graph,
4117 s->start_id, s->repo, NULL, NULL);
4118 if (err)
4119 return err;
4120 free_commits(&s->real_commits);
4121 free_commits(&s->limit_commits);
4122 s->first_displayed_entry = NULL;
4123 s->last_displayed_entry = NULL;
4124 s->selected_entry = NULL;
4125 s->selected = 0;
4126 s->thread_args.log_complete = 0;
4127 s->quit = 0;
4128 s->thread_args.commits_needed = view->lines;
4129 s->matched_entry = NULL;
4130 s->search_entry = NULL;
4131 view->offset = 0;
4132 break;
4133 case 'R':
4134 view->count = 0;
4135 err = view_request_new(new_view, view, TOG_VIEW_REF);
4136 break;
4137 default:
4138 view->count = 0;
4139 break;
4142 return err;
4145 static const struct got_error *
4146 apply_unveil(const char *repo_path, const char *worktree_path)
4148 const struct got_error *error;
4150 #ifdef PROFILE
4151 if (unveil("gmon.out", "rwc") != 0)
4152 return got_error_from_errno2("unveil", "gmon.out");
4153 #endif
4154 if (repo_path && unveil(repo_path, "r") != 0)
4155 return got_error_from_errno2("unveil", repo_path);
4157 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4158 return got_error_from_errno2("unveil", worktree_path);
4160 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4161 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4163 error = got_privsep_unveil_exec_helpers();
4164 if (error != NULL)
4165 return error;
4167 if (unveil(NULL, NULL) != 0)
4168 return got_error_from_errno("unveil");
4170 return NULL;
4173 static const struct got_error *
4174 init_mock_term(const char *test_script_path)
4176 const struct got_error *err = NULL;
4178 if (test_script_path == NULL || *test_script_path == '\0')
4179 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4181 tog_io.f = fopen(test_script_path, "re");
4182 if (tog_io.f == NULL) {
4183 err = got_error_from_errno_fmt("fopen: %s",
4184 test_script_path);
4185 goto done;
4188 /* test mode, we don't want any output */
4189 tog_io.cout = fopen("/dev/null", "w+");
4190 if (tog_io.cout == NULL) {
4191 err = got_error_from_errno("fopen: /dev/null");
4192 goto done;
4195 tog_io.cin = fopen("/dev/tty", "r+");
4196 if (tog_io.cin == NULL) {
4197 err = got_error_from_errno("fopen: /dev/tty");
4198 goto done;
4201 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4202 err = got_error_from_errno("fseeko");
4203 goto done;
4206 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4207 err = got_error_msg(GOT_ERR_IO,
4208 "newterm: failed to initialise curses");
4210 using_mock_io = 1;
4212 done:
4213 if (err)
4214 tog_io_close();
4215 return err;
4218 static void
4219 init_curses(void)
4222 * Override default signal handlers before starting ncurses.
4223 * This should prevent ncurses from installing its own
4224 * broken cleanup() signal handler.
4226 signal(SIGWINCH, tog_sigwinch);
4227 signal(SIGPIPE, tog_sigpipe);
4228 signal(SIGCONT, tog_sigcont);
4229 signal(SIGINT, tog_sigint);
4230 signal(SIGTERM, tog_sigterm);
4232 if (using_mock_io) /* In test mode we use a fake terminal */
4233 return;
4235 initscr();
4237 cbreak();
4238 halfdelay(1); /* Fast refresh while initial view is loading. */
4239 noecho();
4240 nonl();
4241 intrflush(stdscr, FALSE);
4242 keypad(stdscr, TRUE);
4243 curs_set(0);
4244 if (getenv("TOG_COLORS") != NULL) {
4245 start_color();
4246 use_default_colors();
4249 return;
4252 static const struct got_error *
4253 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4254 struct got_repository *repo, struct got_worktree *worktree)
4256 const struct got_error *err = NULL;
4258 if (argc == 0) {
4259 *in_repo_path = strdup("/");
4260 if (*in_repo_path == NULL)
4261 return got_error_from_errno("strdup");
4262 return NULL;
4265 if (worktree) {
4266 const char *prefix = got_worktree_get_path_prefix(worktree);
4267 char *p;
4269 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4270 if (err)
4271 return err;
4272 if (asprintf(in_repo_path, "%s%s%s", prefix,
4273 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4274 p) == -1) {
4275 err = got_error_from_errno("asprintf");
4276 *in_repo_path = NULL;
4278 free(p);
4279 } else
4280 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4282 return err;
4285 static const struct got_error *
4286 cmd_log(int argc, char *argv[])
4288 const struct got_error *error;
4289 struct got_repository *repo = NULL;
4290 struct got_worktree *worktree = NULL;
4291 struct got_object_id *start_id = NULL;
4292 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4293 char *start_commit = NULL, *label = NULL;
4294 struct got_reference *ref = NULL;
4295 const char *head_ref_name = NULL;
4296 int ch, log_branches = 0;
4297 struct tog_view *view;
4298 int *pack_fds = NULL;
4300 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4301 switch (ch) {
4302 case 'b':
4303 log_branches = 1;
4304 break;
4305 case 'c':
4306 start_commit = optarg;
4307 break;
4308 case 'r':
4309 repo_path = realpath(optarg, NULL);
4310 if (repo_path == NULL)
4311 return got_error_from_errno2("realpath",
4312 optarg);
4313 break;
4314 default:
4315 usage_log();
4316 /* NOTREACHED */
4320 argc -= optind;
4321 argv += optind;
4323 if (argc > 1)
4324 usage_log();
4326 error = got_repo_pack_fds_open(&pack_fds);
4327 if (error != NULL)
4328 goto done;
4330 if (repo_path == NULL) {
4331 cwd = getcwd(NULL, 0);
4332 if (cwd == NULL)
4333 return got_error_from_errno("getcwd");
4334 error = got_worktree_open(&worktree, cwd);
4335 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4336 goto done;
4337 if (worktree)
4338 repo_path =
4339 strdup(got_worktree_get_repo_path(worktree));
4340 else
4341 repo_path = strdup(cwd);
4342 if (repo_path == NULL) {
4343 error = got_error_from_errno("strdup");
4344 goto done;
4348 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4349 if (error != NULL)
4350 goto done;
4352 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4353 repo, worktree);
4354 if (error)
4355 goto done;
4357 init_curses();
4359 error = apply_unveil(got_repo_get_path(repo),
4360 worktree ? got_worktree_get_root_path(worktree) : NULL);
4361 if (error)
4362 goto done;
4364 /* already loaded by tog_log_with_path()? */
4365 if (TAILQ_EMPTY(&tog_refs)) {
4366 error = tog_load_refs(repo, 0);
4367 if (error)
4368 goto done;
4371 if (start_commit == NULL) {
4372 error = got_repo_match_object_id(&start_id, &label,
4373 worktree ? got_worktree_get_head_ref_name(worktree) :
4374 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4375 if (error)
4376 goto done;
4377 head_ref_name = label;
4378 } else {
4379 error = got_ref_open(&ref, repo, start_commit, 0);
4380 if (error == NULL)
4381 head_ref_name = got_ref_get_name(ref);
4382 else if (error->code != GOT_ERR_NOT_REF)
4383 goto done;
4384 error = got_repo_match_object_id(&start_id, NULL,
4385 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4386 if (error)
4387 goto done;
4390 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4391 if (view == NULL) {
4392 error = got_error_from_errno("view_open");
4393 goto done;
4395 error = open_log_view(view, start_id, repo, head_ref_name,
4396 in_repo_path, log_branches);
4397 if (error)
4398 goto done;
4399 if (worktree) {
4400 /* Release work tree lock. */
4401 got_worktree_close(worktree);
4402 worktree = NULL;
4404 error = view_loop(view);
4405 done:
4406 free(in_repo_path);
4407 free(repo_path);
4408 free(cwd);
4409 free(start_id);
4410 free(label);
4411 if (ref)
4412 got_ref_close(ref);
4413 if (repo) {
4414 const struct got_error *close_err = got_repo_close(repo);
4415 if (error == NULL)
4416 error = close_err;
4418 if (worktree)
4419 got_worktree_close(worktree);
4420 if (pack_fds) {
4421 const struct got_error *pack_err =
4422 got_repo_pack_fds_close(pack_fds);
4423 if (error == NULL)
4424 error = pack_err;
4426 tog_free_refs();
4427 return error;
4430 __dead static void
4431 usage_diff(void)
4433 endwin();
4434 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4435 "object1 object2\n", getprogname());
4436 exit(1);
4439 static int
4440 match_line(const char *line, regex_t *regex, size_t nmatch,
4441 regmatch_t *regmatch)
4443 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4446 static struct tog_color *
4447 match_color(struct tog_colors *colors, const char *line)
4449 struct tog_color *tc = NULL;
4451 STAILQ_FOREACH(tc, colors, entry) {
4452 if (match_line(line, &tc->regex, 0, NULL))
4453 return tc;
4456 return NULL;
4459 static const struct got_error *
4460 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4461 WINDOW *window, int skipcol, regmatch_t *regmatch)
4463 const struct got_error *err = NULL;
4464 char *exstr = NULL;
4465 wchar_t *wline = NULL;
4466 int rme, rms, n, width, scrollx;
4467 int width0 = 0, width1 = 0, width2 = 0;
4468 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4470 *wtotal = 0;
4472 rms = regmatch->rm_so;
4473 rme = regmatch->rm_eo;
4475 err = expand_tab(&exstr, line);
4476 if (err)
4477 return err;
4479 /* Split the line into 3 segments, according to match offsets. */
4480 seg0 = strndup(exstr, rms);
4481 if (seg0 == NULL) {
4482 err = got_error_from_errno("strndup");
4483 goto done;
4485 seg1 = strndup(exstr + rms, rme - rms);
4486 if (seg1 == NULL) {
4487 err = got_error_from_errno("strndup");
4488 goto done;
4490 seg2 = strdup(exstr + rme);
4491 if (seg2 == NULL) {
4492 err = got_error_from_errno("strndup");
4493 goto done;
4496 /* draw up to matched token if we haven't scrolled past it */
4497 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4498 col_tab_align, 1);
4499 if (err)
4500 goto done;
4501 n = MAX(width0 - skipcol, 0);
4502 if (n) {
4503 free(wline);
4504 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4505 wlimit, col_tab_align, 1);
4506 if (err)
4507 goto done;
4508 waddwstr(window, &wline[scrollx]);
4509 wlimit -= width;
4510 *wtotal += width;
4513 if (wlimit > 0) {
4514 int i = 0, w = 0;
4515 size_t wlen;
4517 free(wline);
4518 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4519 col_tab_align, 1);
4520 if (err)
4521 goto done;
4522 wlen = wcslen(wline);
4523 while (i < wlen) {
4524 width = wcwidth(wline[i]);
4525 if (width == -1) {
4526 /* should not happen, tabs are expanded */
4527 err = got_error(GOT_ERR_RANGE);
4528 goto done;
4530 if (width0 + w + width > skipcol)
4531 break;
4532 w += width;
4533 i++;
4535 /* draw (visible part of) matched token (if scrolled into it) */
4536 if (width1 - w > 0) {
4537 wattron(window, A_STANDOUT);
4538 waddwstr(window, &wline[i]);
4539 wattroff(window, A_STANDOUT);
4540 wlimit -= (width1 - w);
4541 *wtotal += (width1 - w);
4545 if (wlimit > 0) { /* draw rest of line */
4546 free(wline);
4547 if (skipcol > width0 + width1) {
4548 err = format_line(&wline, &width2, &scrollx, seg2,
4549 skipcol - (width0 + width1), wlimit,
4550 col_tab_align, 1);
4551 if (err)
4552 goto done;
4553 waddwstr(window, &wline[scrollx]);
4554 } else {
4555 err = format_line(&wline, &width2, NULL, seg2, 0,
4556 wlimit, col_tab_align, 1);
4557 if (err)
4558 goto done;
4559 waddwstr(window, wline);
4561 *wtotal += width2;
4563 done:
4564 free(wline);
4565 free(exstr);
4566 free(seg0);
4567 free(seg1);
4568 free(seg2);
4569 return err;
4572 static int
4573 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4575 FILE *f = NULL;
4576 int *eof, *first, *selected;
4578 if (view->type == TOG_VIEW_DIFF) {
4579 struct tog_diff_view_state *s = &view->state.diff;
4581 first = &s->first_displayed_line;
4582 selected = first;
4583 eof = &s->eof;
4584 f = s->f;
4585 } else if (view->type == TOG_VIEW_HELP) {
4586 struct tog_help_view_state *s = &view->state.help;
4588 first = &s->first_displayed_line;
4589 selected = first;
4590 eof = &s->eof;
4591 f = s->f;
4592 } else if (view->type == TOG_VIEW_BLAME) {
4593 struct tog_blame_view_state *s = &view->state.blame;
4595 first = &s->first_displayed_line;
4596 selected = &s->selected_line;
4597 eof = &s->eof;
4598 f = s->blame.f;
4599 } else
4600 return 0;
4602 /* Center gline in the middle of the page like vi(1). */
4603 if (*lineno < view->gline - (view->nlines - 3) / 2)
4604 return 0;
4605 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4606 rewind(f);
4607 *eof = 0;
4608 *first = 1;
4609 *lineno = 0;
4610 *nprinted = 0;
4611 return 0;
4614 *selected = view->gline <= (view->nlines - 3) / 2 ?
4615 view->gline : (view->nlines - 3) / 2 + 1;
4616 view->gline = 0;
4618 return 1;
4621 static const struct got_error *
4622 draw_file(struct tog_view *view, const char *header)
4624 struct tog_diff_view_state *s = &view->state.diff;
4625 regmatch_t *regmatch = &view->regmatch;
4626 const struct got_error *err;
4627 int nprinted = 0;
4628 char *line;
4629 size_t linesize = 0;
4630 ssize_t linelen;
4631 wchar_t *wline;
4632 int width;
4633 int max_lines = view->nlines;
4634 int nlines = s->nlines;
4635 off_t line_offset;
4637 s->lineno = s->first_displayed_line - 1;
4638 line_offset = s->lines[s->first_displayed_line - 1].offset;
4639 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4640 return got_error_from_errno("fseek");
4642 werase(view->window);
4644 if (view->gline > s->nlines - 1)
4645 view->gline = s->nlines - 1;
4647 if (header) {
4648 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4649 1 : view->gline - (view->nlines - 3) / 2 :
4650 s->lineno + s->selected_line;
4652 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4653 return got_error_from_errno("asprintf");
4654 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4655 0, 0);
4656 free(line);
4657 if (err)
4658 return err;
4660 if (view_needs_focus_indication(view))
4661 wstandout(view->window);
4662 waddwstr(view->window, wline);
4663 free(wline);
4664 wline = NULL;
4665 while (width++ < view->ncols)
4666 waddch(view->window, ' ');
4667 if (view_needs_focus_indication(view))
4668 wstandend(view->window);
4670 if (max_lines <= 1)
4671 return NULL;
4672 max_lines--;
4675 s->eof = 0;
4676 view->maxx = 0;
4677 line = NULL;
4678 while (max_lines > 0 && nprinted < max_lines) {
4679 enum got_diff_line_type linetype;
4680 attr_t attr = 0;
4682 linelen = getline(&line, &linesize, s->f);
4683 if (linelen == -1) {
4684 if (feof(s->f)) {
4685 s->eof = 1;
4686 break;
4688 free(line);
4689 return got_ferror(s->f, GOT_ERR_IO);
4692 if (++s->lineno < s->first_displayed_line)
4693 continue;
4694 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4695 continue;
4696 if (s->lineno == view->hiline)
4697 attr = A_STANDOUT;
4699 /* Set view->maxx based on full line length. */
4700 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4701 view->x ? 1 : 0);
4702 if (err) {
4703 free(line);
4704 return err;
4706 view->maxx = MAX(view->maxx, width);
4707 free(wline);
4708 wline = NULL;
4710 linetype = s->lines[s->lineno].type;
4711 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4712 linetype < GOT_DIFF_LINE_CONTEXT)
4713 attr |= COLOR_PAIR(linetype);
4714 if (attr)
4715 wattron(view->window, attr);
4716 if (s->first_displayed_line + nprinted == s->matched_line &&
4717 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4718 err = add_matched_line(&width, line, view->ncols, 0,
4719 view->window, view->x, regmatch);
4720 if (err) {
4721 free(line);
4722 return err;
4724 } else {
4725 int skip;
4726 err = format_line(&wline, &width, &skip, line,
4727 view->x, view->ncols, 0, view->x ? 1 : 0);
4728 if (err) {
4729 free(line);
4730 return err;
4732 waddwstr(view->window, &wline[skip]);
4733 free(wline);
4734 wline = NULL;
4736 if (s->lineno == view->hiline) {
4737 /* highlight full gline length */
4738 while (width++ < view->ncols)
4739 waddch(view->window, ' ');
4740 } else {
4741 if (width <= view->ncols - 1)
4742 waddch(view->window, '\n');
4744 if (attr)
4745 wattroff(view->window, attr);
4746 if (++nprinted == 1)
4747 s->first_displayed_line = s->lineno;
4749 free(line);
4750 if (nprinted >= 1)
4751 s->last_displayed_line = s->first_displayed_line +
4752 (nprinted - 1);
4753 else
4754 s->last_displayed_line = s->first_displayed_line;
4756 view_border(view);
4758 if (s->eof) {
4759 while (nprinted < view->nlines) {
4760 waddch(view->window, '\n');
4761 nprinted++;
4764 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4765 view->ncols, 0, 0);
4766 if (err) {
4767 return err;
4770 wstandout(view->window);
4771 waddwstr(view->window, wline);
4772 free(wline);
4773 wline = NULL;
4774 wstandend(view->window);
4777 return NULL;
4780 static char *
4781 get_datestr(time_t *time, char *datebuf)
4783 struct tm mytm, *tm;
4784 char *p, *s;
4786 tm = gmtime_r(time, &mytm);
4787 if (tm == NULL)
4788 return NULL;
4789 s = asctime_r(tm, datebuf);
4790 if (s == NULL)
4791 return NULL;
4792 p = strchr(s, '\n');
4793 if (p)
4794 *p = '\0';
4795 return s;
4798 static const struct got_error *
4799 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4800 off_t off, uint8_t type)
4802 struct got_diff_line *p;
4804 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4805 if (p == NULL)
4806 return got_error_from_errno("reallocarray");
4807 *lines = p;
4808 (*lines)[*nlines].offset = off;
4809 (*lines)[*nlines].type = type;
4810 (*nlines)++;
4812 return NULL;
4815 static const struct got_error *
4816 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4817 struct got_diff_line *s_lines, size_t s_nlines)
4819 struct got_diff_line *p;
4820 char buf[BUFSIZ];
4821 size_t i, r;
4823 if (fseeko(src, 0L, SEEK_SET) == -1)
4824 return got_error_from_errno("fseeko");
4826 for (;;) {
4827 r = fread(buf, 1, sizeof(buf), src);
4828 if (r == 0) {
4829 if (ferror(src))
4830 return got_error_from_errno("fread");
4831 if (feof(src))
4832 break;
4834 if (fwrite(buf, 1, r, dst) != r)
4835 return got_ferror(dst, GOT_ERR_IO);
4838 if (s_nlines == 0 && *d_nlines == 0)
4839 return NULL;
4842 * If commit info was in dst, increment line offsets
4843 * of the appended diff content, but skip s_lines[0]
4844 * because offset zero is already in *d_lines.
4846 if (*d_nlines > 0) {
4847 for (i = 1; i < s_nlines; ++i)
4848 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4850 if (s_nlines > 0) {
4851 --s_nlines;
4852 ++s_lines;
4856 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4857 if (p == NULL) {
4858 /* d_lines is freed in close_diff_view() */
4859 return got_error_from_errno("reallocarray");
4862 *d_lines = p;
4864 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4865 *d_nlines += s_nlines;
4867 return NULL;
4870 static const struct got_error *
4871 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4872 struct got_object_id *commit_id, struct got_reflist_head *refs,
4873 struct got_repository *repo, int ignore_ws, int force_text_diff,
4874 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4876 const struct got_error *err = NULL;
4877 char datebuf[26], *datestr;
4878 struct got_commit_object *commit;
4879 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4880 time_t committer_time;
4881 const char *author, *committer;
4882 char *refs_str = NULL;
4883 struct got_pathlist_entry *pe;
4884 off_t outoff = 0;
4885 int n;
4887 if (refs) {
4888 err = build_refs_str(&refs_str, refs, commit_id, repo);
4889 if (err)
4890 return err;
4893 err = got_object_open_as_commit(&commit, repo, commit_id);
4894 if (err)
4895 return err;
4897 err = got_object_id_str(&id_str, commit_id);
4898 if (err) {
4899 err = got_error_from_errno("got_object_id_str");
4900 goto done;
4903 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4904 if (err)
4905 goto done;
4907 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4908 refs_str ? refs_str : "", refs_str ? ")" : "");
4909 if (n < 0) {
4910 err = got_error_from_errno("fprintf");
4911 goto done;
4913 outoff += n;
4914 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4915 if (err)
4916 goto done;
4918 n = fprintf(outfile, "from: %s\n",
4919 got_object_commit_get_author(commit));
4920 if (n < 0) {
4921 err = got_error_from_errno("fprintf");
4922 goto done;
4924 outoff += n;
4925 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4926 if (err)
4927 goto done;
4929 author = got_object_commit_get_author(commit);
4930 committer = got_object_commit_get_committer(commit);
4931 if (strcmp(author, committer) != 0) {
4932 n = fprintf(outfile, "via: %s\n", committer);
4933 if (n < 0) {
4934 err = got_error_from_errno("fprintf");
4935 goto done;
4937 outoff += n;
4938 err = add_line_metadata(lines, nlines, outoff,
4939 GOT_DIFF_LINE_AUTHOR);
4940 if (err)
4941 goto done;
4943 committer_time = got_object_commit_get_committer_time(commit);
4944 datestr = get_datestr(&committer_time, datebuf);
4945 if (datestr) {
4946 n = fprintf(outfile, "date: %s UTC\n", datestr);
4947 if (n < 0) {
4948 err = got_error_from_errno("fprintf");
4949 goto done;
4951 outoff += n;
4952 err = add_line_metadata(lines, nlines, outoff,
4953 GOT_DIFF_LINE_DATE);
4954 if (err)
4955 goto done;
4957 if (got_object_commit_get_nparents(commit) > 1) {
4958 const struct got_object_id_queue *parent_ids;
4959 struct got_object_qid *qid;
4960 int pn = 1;
4961 parent_ids = got_object_commit_get_parent_ids(commit);
4962 STAILQ_FOREACH(qid, parent_ids, entry) {
4963 err = got_object_id_str(&id_str, &qid->id);
4964 if (err)
4965 goto done;
4966 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4967 if (n < 0) {
4968 err = got_error_from_errno("fprintf");
4969 goto done;
4971 outoff += n;
4972 err = add_line_metadata(lines, nlines, outoff,
4973 GOT_DIFF_LINE_META);
4974 if (err)
4975 goto done;
4976 free(id_str);
4977 id_str = NULL;
4981 err = got_object_commit_get_logmsg(&logmsg, commit);
4982 if (err)
4983 goto done;
4984 s = logmsg;
4985 while ((line = strsep(&s, "\n")) != NULL) {
4986 n = fprintf(outfile, "%s\n", line);
4987 if (n < 0) {
4988 err = got_error_from_errno("fprintf");
4989 goto done;
4991 outoff += n;
4992 err = add_line_metadata(lines, nlines, outoff,
4993 GOT_DIFF_LINE_LOGMSG);
4994 if (err)
4995 goto done;
4998 TAILQ_FOREACH(pe, dsa->paths, entry) {
4999 struct got_diff_changed_path *cp = pe->data;
5000 int pad = dsa->max_path_len - pe->path_len + 1;
5002 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5003 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5004 dsa->rm_cols + 1, cp->rm);
5005 if (n < 0) {
5006 err = got_error_from_errno("fprintf");
5007 goto done;
5009 outoff += n;
5010 err = add_line_metadata(lines, nlines, outoff,
5011 GOT_DIFF_LINE_CHANGES);
5012 if (err)
5013 goto done;
5016 fputc('\n', outfile);
5017 outoff++;
5018 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5019 if (err)
5020 goto done;
5022 n = fprintf(outfile,
5023 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5024 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5025 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5026 if (n < 0) {
5027 err = got_error_from_errno("fprintf");
5028 goto done;
5030 outoff += n;
5031 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5032 if (err)
5033 goto done;
5035 fputc('\n', outfile);
5036 outoff++;
5037 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5038 done:
5039 free(id_str);
5040 free(logmsg);
5041 free(refs_str);
5042 got_object_commit_close(commit);
5043 if (err) {
5044 free(*lines);
5045 *lines = NULL;
5046 *nlines = 0;
5048 return err;
5051 static const struct got_error *
5052 create_diff(struct tog_diff_view_state *s)
5054 const struct got_error *err = NULL;
5055 FILE *f = NULL, *tmp_diff_file = NULL;
5056 int obj_type;
5057 struct got_diff_line *lines = NULL;
5058 struct got_pathlist_head changed_paths;
5060 TAILQ_INIT(&changed_paths);
5062 free(s->lines);
5063 s->lines = malloc(sizeof(*s->lines));
5064 if (s->lines == NULL)
5065 return got_error_from_errno("malloc");
5066 s->nlines = 0;
5068 f = got_opentemp();
5069 if (f == NULL) {
5070 err = got_error_from_errno("got_opentemp");
5071 goto done;
5073 tmp_diff_file = got_opentemp();
5074 if (tmp_diff_file == NULL) {
5075 err = got_error_from_errno("got_opentemp");
5076 goto done;
5078 if (s->f && fclose(s->f) == EOF) {
5079 err = got_error_from_errno("fclose");
5080 goto done;
5082 s->f = f;
5084 if (s->id1)
5085 err = got_object_get_type(&obj_type, s->repo, s->id1);
5086 else
5087 err = got_object_get_type(&obj_type, s->repo, s->id2);
5088 if (err)
5089 goto done;
5091 switch (obj_type) {
5092 case GOT_OBJ_TYPE_BLOB:
5093 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5094 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5095 s->label1, s->label2, tog_diff_algo, s->diff_context,
5096 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5097 s->f);
5098 break;
5099 case GOT_OBJ_TYPE_TREE:
5100 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5101 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5102 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5103 s->force_text_diff, NULL, s->repo, s->f);
5104 break;
5105 case GOT_OBJ_TYPE_COMMIT: {
5106 const struct got_object_id_queue *parent_ids;
5107 struct got_object_qid *pid;
5108 struct got_commit_object *commit2;
5109 struct got_reflist_head *refs;
5110 size_t nlines = 0;
5111 struct got_diffstat_cb_arg dsa = {
5112 0, 0, 0, 0, 0, 0,
5113 &changed_paths,
5114 s->ignore_whitespace,
5115 s->force_text_diff,
5116 tog_diff_algo
5119 lines = malloc(sizeof(*lines));
5120 if (lines == NULL) {
5121 err = got_error_from_errno("malloc");
5122 goto done;
5125 /* build diff first in tmp file then append to commit info */
5126 err = got_diff_objects_as_commits(&lines, &nlines,
5127 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5128 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5129 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5130 if (err)
5131 break;
5133 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5134 if (err)
5135 goto done;
5136 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5137 /* Show commit info if we're diffing to a parent/root commit. */
5138 if (s->id1 == NULL) {
5139 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5140 refs, s->repo, s->ignore_whitespace,
5141 s->force_text_diff, &dsa, s->f);
5142 if (err)
5143 goto done;
5144 } else {
5145 parent_ids = got_object_commit_get_parent_ids(commit2);
5146 STAILQ_FOREACH(pid, parent_ids, entry) {
5147 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5148 err = write_commit_info(&s->lines,
5149 &s->nlines, s->id2, refs, s->repo,
5150 s->ignore_whitespace,
5151 s->force_text_diff, &dsa, s->f);
5152 if (err)
5153 goto done;
5154 break;
5158 got_object_commit_close(commit2);
5160 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5161 lines, nlines);
5162 break;
5164 default:
5165 err = got_error(GOT_ERR_OBJ_TYPE);
5166 break;
5168 done:
5169 free(lines);
5170 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5171 if (s->f && fflush(s->f) != 0 && err == NULL)
5172 err = got_error_from_errno("fflush");
5173 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5174 err = got_error_from_errno("fclose");
5175 return err;
5178 static void
5179 diff_view_indicate_progress(struct tog_view *view)
5181 mvwaddstr(view->window, 0, 0, "diffing...");
5182 update_panels();
5183 doupdate();
5186 static const struct got_error *
5187 search_start_diff_view(struct tog_view *view)
5189 struct tog_diff_view_state *s = &view->state.diff;
5191 s->matched_line = 0;
5192 return NULL;
5195 static void
5196 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5197 size_t *nlines, int **first, int **last, int **match, int **selected)
5199 struct tog_diff_view_state *s = &view->state.diff;
5201 *f = s->f;
5202 *nlines = s->nlines;
5203 *line_offsets = NULL;
5204 *match = &s->matched_line;
5205 *first = &s->first_displayed_line;
5206 *last = &s->last_displayed_line;
5207 *selected = &s->selected_line;
5210 static const struct got_error *
5211 search_next_view_match(struct tog_view *view)
5213 const struct got_error *err = NULL;
5214 FILE *f;
5215 int lineno;
5216 char *line = NULL;
5217 size_t linesize = 0;
5218 ssize_t linelen;
5219 off_t *line_offsets;
5220 size_t nlines = 0;
5221 int *first, *last, *match, *selected;
5223 if (!view->search_setup)
5224 return got_error_msg(GOT_ERR_NOT_IMPL,
5225 "view search not supported");
5226 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5227 &match, &selected);
5229 if (!view->searching) {
5230 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5231 return NULL;
5234 if (*match) {
5235 if (view->searching == TOG_SEARCH_FORWARD)
5236 lineno = *first + 1;
5237 else
5238 lineno = *first - 1;
5239 } else
5240 lineno = *first - 1 + *selected;
5242 while (1) {
5243 off_t offset;
5245 if (lineno <= 0 || lineno > nlines) {
5246 if (*match == 0) {
5247 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5248 break;
5251 if (view->searching == TOG_SEARCH_FORWARD)
5252 lineno = 1;
5253 else
5254 lineno = nlines;
5257 offset = view->type == TOG_VIEW_DIFF ?
5258 view->state.diff.lines[lineno - 1].offset :
5259 line_offsets[lineno - 1];
5260 if (fseeko(f, offset, SEEK_SET) != 0) {
5261 free(line);
5262 return got_error_from_errno("fseeko");
5264 linelen = getline(&line, &linesize, f);
5265 if (linelen != -1) {
5266 char *exstr;
5267 err = expand_tab(&exstr, line);
5268 if (err)
5269 break;
5270 if (match_line(exstr, &view->regex, 1,
5271 &view->regmatch)) {
5272 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5273 *match = lineno;
5274 free(exstr);
5275 break;
5277 free(exstr);
5279 if (view->searching == TOG_SEARCH_FORWARD)
5280 lineno++;
5281 else
5282 lineno--;
5284 free(line);
5286 if (*match) {
5287 *first = *match;
5288 *selected = 1;
5291 return err;
5294 static const struct got_error *
5295 close_diff_view(struct tog_view *view)
5297 const struct got_error *err = NULL;
5298 struct tog_diff_view_state *s = &view->state.diff;
5300 free(s->id1);
5301 s->id1 = NULL;
5302 free(s->id2);
5303 s->id2 = NULL;
5304 if (s->f && fclose(s->f) == EOF)
5305 err = got_error_from_errno("fclose");
5306 s->f = NULL;
5307 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5308 err = got_error_from_errno("fclose");
5309 s->f1 = NULL;
5310 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5311 err = got_error_from_errno("fclose");
5312 s->f2 = NULL;
5313 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5314 err = got_error_from_errno("close");
5315 s->fd1 = -1;
5316 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5317 err = got_error_from_errno("close");
5318 s->fd2 = -1;
5319 free(s->lines);
5320 s->lines = NULL;
5321 s->nlines = 0;
5322 return err;
5325 static const struct got_error *
5326 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5327 struct got_object_id *id2, const char *label1, const char *label2,
5328 int diff_context, int ignore_whitespace, int force_text_diff,
5329 struct tog_view *parent_view, struct got_repository *repo)
5331 const struct got_error *err;
5332 struct tog_diff_view_state *s = &view->state.diff;
5334 memset(s, 0, sizeof(*s));
5335 s->fd1 = -1;
5336 s->fd2 = -1;
5338 if (id1 != NULL && id2 != NULL) {
5339 int type1, type2;
5341 err = got_object_get_type(&type1, repo, id1);
5342 if (err)
5343 goto done;
5344 err = got_object_get_type(&type2, repo, id2);
5345 if (err)
5346 goto done;
5348 if (type1 != type2) {
5349 err = got_error(GOT_ERR_OBJ_TYPE);
5350 goto done;
5353 s->first_displayed_line = 1;
5354 s->last_displayed_line = view->nlines;
5355 s->selected_line = 1;
5356 s->repo = repo;
5357 s->id1 = id1;
5358 s->id2 = id2;
5359 s->label1 = label1;
5360 s->label2 = label2;
5362 if (id1) {
5363 s->id1 = got_object_id_dup(id1);
5364 if (s->id1 == NULL) {
5365 err = got_error_from_errno("got_object_id_dup");
5366 goto done;
5368 } else
5369 s->id1 = NULL;
5371 s->id2 = got_object_id_dup(id2);
5372 if (s->id2 == NULL) {
5373 err = got_error_from_errno("got_object_id_dup");
5374 goto done;
5377 s->f1 = got_opentemp();
5378 if (s->f1 == NULL) {
5379 err = got_error_from_errno("got_opentemp");
5380 goto done;
5383 s->f2 = got_opentemp();
5384 if (s->f2 == NULL) {
5385 err = got_error_from_errno("got_opentemp");
5386 goto done;
5389 s->fd1 = got_opentempfd();
5390 if (s->fd1 == -1) {
5391 err = got_error_from_errno("got_opentempfd");
5392 goto done;
5395 s->fd2 = got_opentempfd();
5396 if (s->fd2 == -1) {
5397 err = got_error_from_errno("got_opentempfd");
5398 goto done;
5401 s->diff_context = diff_context;
5402 s->ignore_whitespace = ignore_whitespace;
5403 s->force_text_diff = force_text_diff;
5404 s->parent_view = parent_view;
5405 s->repo = repo;
5407 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5408 int rc;
5410 rc = init_pair(GOT_DIFF_LINE_MINUS,
5411 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5412 if (rc != ERR)
5413 rc = init_pair(GOT_DIFF_LINE_PLUS,
5414 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5415 if (rc != ERR)
5416 rc = init_pair(GOT_DIFF_LINE_HUNK,
5417 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5418 if (rc != ERR)
5419 rc = init_pair(GOT_DIFF_LINE_META,
5420 get_color_value("TOG_COLOR_DIFF_META"), -1);
5421 if (rc != ERR)
5422 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5423 get_color_value("TOG_COLOR_DIFF_META"), -1);
5424 if (rc != ERR)
5425 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5426 get_color_value("TOG_COLOR_DIFF_META"), -1);
5427 if (rc != ERR)
5428 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5429 get_color_value("TOG_COLOR_DIFF_META"), -1);
5430 if (rc != ERR)
5431 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5432 get_color_value("TOG_COLOR_AUTHOR"), -1);
5433 if (rc != ERR)
5434 rc = init_pair(GOT_DIFF_LINE_DATE,
5435 get_color_value("TOG_COLOR_DATE"), -1);
5436 if (rc == ERR) {
5437 err = got_error(GOT_ERR_RANGE);
5438 goto done;
5442 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5443 view_is_splitscreen(view))
5444 show_log_view(parent_view); /* draw border */
5445 diff_view_indicate_progress(view);
5447 err = create_diff(s);
5449 view->show = show_diff_view;
5450 view->input = input_diff_view;
5451 view->reset = reset_diff_view;
5452 view->close = close_diff_view;
5453 view->search_start = search_start_diff_view;
5454 view->search_setup = search_setup_diff_view;
5455 view->search_next = search_next_view_match;
5456 done:
5457 if (err) {
5458 if (view->close == NULL)
5459 close_diff_view(view);
5460 view_close(view);
5462 return err;
5465 static const struct got_error *
5466 show_diff_view(struct tog_view *view)
5468 const struct got_error *err;
5469 struct tog_diff_view_state *s = &view->state.diff;
5470 char *id_str1 = NULL, *id_str2, *header;
5471 const char *label1, *label2;
5473 if (s->id1) {
5474 err = got_object_id_str(&id_str1, s->id1);
5475 if (err)
5476 return err;
5477 label1 = s->label1 ? s->label1 : id_str1;
5478 } else
5479 label1 = "/dev/null";
5481 err = got_object_id_str(&id_str2, s->id2);
5482 if (err)
5483 return err;
5484 label2 = s->label2 ? s->label2 : id_str2;
5486 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5487 err = got_error_from_errno("asprintf");
5488 free(id_str1);
5489 free(id_str2);
5490 return err;
5492 free(id_str1);
5493 free(id_str2);
5495 err = draw_file(view, header);
5496 free(header);
5497 return err;
5500 static const struct got_error *
5501 set_selected_commit(struct tog_diff_view_state *s,
5502 struct commit_queue_entry *entry)
5504 const struct got_error *err;
5505 const struct got_object_id_queue *parent_ids;
5506 struct got_commit_object *selected_commit;
5507 struct got_object_qid *pid;
5509 free(s->id2);
5510 s->id2 = got_object_id_dup(entry->id);
5511 if (s->id2 == NULL)
5512 return got_error_from_errno("got_object_id_dup");
5514 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5515 if (err)
5516 return err;
5517 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5518 free(s->id1);
5519 pid = STAILQ_FIRST(parent_ids);
5520 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5521 got_object_commit_close(selected_commit);
5522 return NULL;
5525 static const struct got_error *
5526 reset_diff_view(struct tog_view *view)
5528 struct tog_diff_view_state *s = &view->state.diff;
5530 view->count = 0;
5531 wclear(view->window);
5532 s->first_displayed_line = 1;
5533 s->last_displayed_line = view->nlines;
5534 s->matched_line = 0;
5535 diff_view_indicate_progress(view);
5536 return create_diff(s);
5539 static void
5540 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5542 int start, i;
5544 i = start = s->first_displayed_line - 1;
5546 while (s->lines[i].type != type) {
5547 if (i == 0)
5548 i = s->nlines - 1;
5549 if (--i == start)
5550 return; /* do nothing, requested type not in file */
5553 s->selected_line = 1;
5554 s->first_displayed_line = i;
5557 static void
5558 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5560 int start, i;
5562 i = start = s->first_displayed_line + 1;
5564 while (s->lines[i].type != type) {
5565 if (i == s->nlines - 1)
5566 i = 0;
5567 if (++i == start)
5568 return; /* do nothing, requested type not in file */
5571 s->selected_line = 1;
5572 s->first_displayed_line = i;
5575 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5576 int, int, int);
5577 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5578 int, int);
5580 static const struct got_error *
5581 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5583 const struct got_error *err = NULL;
5584 struct tog_diff_view_state *s = &view->state.diff;
5585 struct tog_log_view_state *ls;
5586 struct commit_queue_entry *old_selected_entry;
5587 char *line = NULL;
5588 size_t linesize = 0;
5589 ssize_t linelen;
5590 int i, nscroll = view->nlines - 1, up = 0;
5592 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5594 switch (ch) {
5595 case '0':
5596 case '$':
5597 case KEY_RIGHT:
5598 case 'l':
5599 case KEY_LEFT:
5600 case 'h':
5601 horizontal_scroll_input(view, ch);
5602 break;
5603 case 'a':
5604 case 'w':
5605 if (ch == 'a') {
5606 s->force_text_diff = !s->force_text_diff;
5607 view->action = s->force_text_diff ?
5608 "force ASCII text enabled" :
5609 "force ASCII text disabled";
5611 else if (ch == 'w') {
5612 s->ignore_whitespace = !s->ignore_whitespace;
5613 view->action = s->ignore_whitespace ?
5614 "ignore whitespace enabled" :
5615 "ignore whitespace disabled";
5617 err = reset_diff_view(view);
5618 break;
5619 case 'g':
5620 case KEY_HOME:
5621 s->first_displayed_line = 1;
5622 view->count = 0;
5623 break;
5624 case 'G':
5625 case KEY_END:
5626 view->count = 0;
5627 if (s->eof)
5628 break;
5630 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5631 s->eof = 1;
5632 break;
5633 case 'k':
5634 case KEY_UP:
5635 case CTRL('p'):
5636 if (s->first_displayed_line > 1)
5637 s->first_displayed_line--;
5638 else
5639 view->count = 0;
5640 break;
5641 case CTRL('u'):
5642 case 'u':
5643 nscroll /= 2;
5644 /* FALL THROUGH */
5645 case KEY_PPAGE:
5646 case CTRL('b'):
5647 case 'b':
5648 if (s->first_displayed_line == 1) {
5649 view->count = 0;
5650 break;
5652 i = 0;
5653 while (i++ < nscroll && s->first_displayed_line > 1)
5654 s->first_displayed_line--;
5655 break;
5656 case 'j':
5657 case KEY_DOWN:
5658 case CTRL('n'):
5659 if (!s->eof)
5660 s->first_displayed_line++;
5661 else
5662 view->count = 0;
5663 break;
5664 case CTRL('d'):
5665 case 'd':
5666 nscroll /= 2;
5667 /* FALL THROUGH */
5668 case KEY_NPAGE:
5669 case CTRL('f'):
5670 case 'f':
5671 case ' ':
5672 if (s->eof) {
5673 view->count = 0;
5674 break;
5676 i = 0;
5677 while (!s->eof && i++ < nscroll) {
5678 linelen = getline(&line, &linesize, s->f);
5679 s->first_displayed_line++;
5680 if (linelen == -1) {
5681 if (feof(s->f)) {
5682 s->eof = 1;
5683 } else
5684 err = got_ferror(s->f, GOT_ERR_IO);
5685 break;
5688 free(line);
5689 break;
5690 case '(':
5691 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5692 break;
5693 case ')':
5694 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5695 break;
5696 case '{':
5697 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5698 break;
5699 case '}':
5700 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5701 break;
5702 case '[':
5703 if (s->diff_context > 0) {
5704 s->diff_context--;
5705 s->matched_line = 0;
5706 diff_view_indicate_progress(view);
5707 err = create_diff(s);
5708 if (s->first_displayed_line + view->nlines - 1 >
5709 s->nlines) {
5710 s->first_displayed_line = 1;
5711 s->last_displayed_line = view->nlines;
5713 } else
5714 view->count = 0;
5715 break;
5716 case ']':
5717 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5718 s->diff_context++;
5719 s->matched_line = 0;
5720 diff_view_indicate_progress(view);
5721 err = create_diff(s);
5722 } else
5723 view->count = 0;
5724 break;
5725 case '<':
5726 case ',':
5727 case 'K':
5728 up = 1;
5729 /* FALL THROUGH */
5730 case '>':
5731 case '.':
5732 case 'J':
5733 if (s->parent_view == NULL) {
5734 view->count = 0;
5735 break;
5737 s->parent_view->count = view->count;
5739 if (s->parent_view->type == TOG_VIEW_LOG) {
5740 ls = &s->parent_view->state.log;
5741 old_selected_entry = ls->selected_entry;
5743 err = input_log_view(NULL, s->parent_view,
5744 up ? KEY_UP : KEY_DOWN);
5745 if (err)
5746 break;
5747 view->count = s->parent_view->count;
5749 if (old_selected_entry == ls->selected_entry)
5750 break;
5752 err = set_selected_commit(s, ls->selected_entry);
5753 if (err)
5754 break;
5755 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5756 struct tog_blame_view_state *bs;
5757 struct got_object_id *id, *prev_id;
5759 bs = &s->parent_view->state.blame;
5760 prev_id = get_annotation_for_line(bs->blame.lines,
5761 bs->blame.nlines, bs->last_diffed_line);
5763 err = input_blame_view(&view, s->parent_view,
5764 up ? KEY_UP : KEY_DOWN);
5765 if (err)
5766 break;
5767 view->count = s->parent_view->count;
5769 if (prev_id == NULL)
5770 break;
5771 id = get_selected_commit_id(bs->blame.lines,
5772 bs->blame.nlines, bs->first_displayed_line,
5773 bs->selected_line);
5774 if (id == NULL)
5775 break;
5777 if (!got_object_id_cmp(prev_id, id))
5778 break;
5780 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5781 if (err)
5782 break;
5784 s->first_displayed_line = 1;
5785 s->last_displayed_line = view->nlines;
5786 s->matched_line = 0;
5787 view->x = 0;
5789 diff_view_indicate_progress(view);
5790 err = create_diff(s);
5791 break;
5792 default:
5793 view->count = 0;
5794 break;
5797 return err;
5800 static const struct got_error *
5801 cmd_diff(int argc, char *argv[])
5803 const struct got_error *error;
5804 struct got_repository *repo = NULL;
5805 struct got_worktree *worktree = NULL;
5806 struct got_object_id *id1 = NULL, *id2 = NULL;
5807 char *repo_path = NULL, *cwd = NULL;
5808 char *id_str1 = NULL, *id_str2 = NULL;
5809 char *label1 = NULL, *label2 = NULL;
5810 int diff_context = 3, ignore_whitespace = 0;
5811 int ch, force_text_diff = 0;
5812 const char *errstr;
5813 struct tog_view *view;
5814 int *pack_fds = NULL;
5816 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5817 switch (ch) {
5818 case 'a':
5819 force_text_diff = 1;
5820 break;
5821 case 'C':
5822 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5823 &errstr);
5824 if (errstr != NULL)
5825 errx(1, "number of context lines is %s: %s",
5826 errstr, errstr);
5827 break;
5828 case 'r':
5829 repo_path = realpath(optarg, NULL);
5830 if (repo_path == NULL)
5831 return got_error_from_errno2("realpath",
5832 optarg);
5833 got_path_strip_trailing_slashes(repo_path);
5834 break;
5835 case 'w':
5836 ignore_whitespace = 1;
5837 break;
5838 default:
5839 usage_diff();
5840 /* NOTREACHED */
5844 argc -= optind;
5845 argv += optind;
5847 if (argc == 0) {
5848 usage_diff(); /* TODO show local worktree changes */
5849 } else if (argc == 2) {
5850 id_str1 = argv[0];
5851 id_str2 = argv[1];
5852 } else
5853 usage_diff();
5855 error = got_repo_pack_fds_open(&pack_fds);
5856 if (error)
5857 goto done;
5859 if (repo_path == NULL) {
5860 cwd = getcwd(NULL, 0);
5861 if (cwd == NULL)
5862 return got_error_from_errno("getcwd");
5863 error = got_worktree_open(&worktree, cwd);
5864 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5865 goto done;
5866 if (worktree)
5867 repo_path =
5868 strdup(got_worktree_get_repo_path(worktree));
5869 else
5870 repo_path = strdup(cwd);
5871 if (repo_path == NULL) {
5872 error = got_error_from_errno("strdup");
5873 goto done;
5877 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5878 if (error)
5879 goto done;
5881 init_curses();
5883 error = apply_unveil(got_repo_get_path(repo), NULL);
5884 if (error)
5885 goto done;
5887 error = tog_load_refs(repo, 0);
5888 if (error)
5889 goto done;
5891 error = got_repo_match_object_id(&id1, &label1, id_str1,
5892 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5893 if (error)
5894 goto done;
5896 error = got_repo_match_object_id(&id2, &label2, id_str2,
5897 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5898 if (error)
5899 goto done;
5901 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5902 if (view == NULL) {
5903 error = got_error_from_errno("view_open");
5904 goto done;
5906 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5907 ignore_whitespace, force_text_diff, NULL, repo);
5908 if (error)
5909 goto done;
5910 error = view_loop(view);
5911 done:
5912 free(label1);
5913 free(label2);
5914 free(repo_path);
5915 free(cwd);
5916 if (repo) {
5917 const struct got_error *close_err = got_repo_close(repo);
5918 if (error == NULL)
5919 error = close_err;
5921 if (worktree)
5922 got_worktree_close(worktree);
5923 if (pack_fds) {
5924 const struct got_error *pack_err =
5925 got_repo_pack_fds_close(pack_fds);
5926 if (error == NULL)
5927 error = pack_err;
5929 tog_free_refs();
5930 return error;
5933 __dead static void
5934 usage_blame(void)
5936 endwin();
5937 fprintf(stderr,
5938 "usage: %s blame [-c commit] [-r repository-path] path\n",
5939 getprogname());
5940 exit(1);
5943 struct tog_blame_line {
5944 int annotated;
5945 struct got_object_id *id;
5948 static const struct got_error *
5949 draw_blame(struct tog_view *view)
5951 struct tog_blame_view_state *s = &view->state.blame;
5952 struct tog_blame *blame = &s->blame;
5953 regmatch_t *regmatch = &view->regmatch;
5954 const struct got_error *err;
5955 int lineno = 0, nprinted = 0;
5956 char *line = NULL;
5957 size_t linesize = 0;
5958 ssize_t linelen;
5959 wchar_t *wline;
5960 int width;
5961 struct tog_blame_line *blame_line;
5962 struct got_object_id *prev_id = NULL;
5963 char *id_str;
5964 struct tog_color *tc;
5966 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5967 if (err)
5968 return err;
5970 rewind(blame->f);
5971 werase(view->window);
5973 if (asprintf(&line, "commit %s", id_str) == -1) {
5974 err = got_error_from_errno("asprintf");
5975 free(id_str);
5976 return err;
5979 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5980 free(line);
5981 line = NULL;
5982 if (err)
5983 return err;
5984 if (view_needs_focus_indication(view))
5985 wstandout(view->window);
5986 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5987 if (tc)
5988 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5989 waddwstr(view->window, wline);
5990 while (width++ < view->ncols)
5991 waddch(view->window, ' ');
5992 if (tc)
5993 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5994 if (view_needs_focus_indication(view))
5995 wstandend(view->window);
5996 free(wline);
5997 wline = NULL;
5999 if (view->gline > blame->nlines)
6000 view->gline = blame->nlines;
6002 if (tog_io.wait_for_ui) {
6003 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6004 int rc;
6006 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6007 if (rc)
6008 return got_error_set_errno(rc, "pthread_cond_wait");
6009 tog_io.wait_for_ui = 0;
6012 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6013 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6014 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6015 free(id_str);
6016 return got_error_from_errno("asprintf");
6018 free(id_str);
6019 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6020 free(line);
6021 line = NULL;
6022 if (err)
6023 return err;
6024 waddwstr(view->window, wline);
6025 free(wline);
6026 wline = NULL;
6027 if (width < view->ncols - 1)
6028 waddch(view->window, '\n');
6030 s->eof = 0;
6031 view->maxx = 0;
6032 while (nprinted < view->nlines - 2) {
6033 linelen = getline(&line, &linesize, blame->f);
6034 if (linelen == -1) {
6035 if (feof(blame->f)) {
6036 s->eof = 1;
6037 break;
6039 free(line);
6040 return got_ferror(blame->f, GOT_ERR_IO);
6042 if (++lineno < s->first_displayed_line)
6043 continue;
6044 if (view->gline && !gotoline(view, &lineno, &nprinted))
6045 continue;
6047 /* Set view->maxx based on full line length. */
6048 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6049 if (err) {
6050 free(line);
6051 return err;
6053 free(wline);
6054 wline = NULL;
6055 view->maxx = MAX(view->maxx, width);
6057 if (nprinted == s->selected_line - 1)
6058 wstandout(view->window);
6060 if (blame->nlines > 0) {
6061 blame_line = &blame->lines[lineno - 1];
6062 if (blame_line->annotated && prev_id &&
6063 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6064 !(nprinted == s->selected_line - 1)) {
6065 waddstr(view->window, " ");
6066 } else if (blame_line->annotated) {
6067 char *id_str;
6068 err = got_object_id_str(&id_str,
6069 blame_line->id);
6070 if (err) {
6071 free(line);
6072 return err;
6074 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6075 if (tc)
6076 wattr_on(view->window,
6077 COLOR_PAIR(tc->colorpair), NULL);
6078 wprintw(view->window, "%.8s", id_str);
6079 if (tc)
6080 wattr_off(view->window,
6081 COLOR_PAIR(tc->colorpair), NULL);
6082 free(id_str);
6083 prev_id = blame_line->id;
6084 } else {
6085 waddstr(view->window, "........");
6086 prev_id = NULL;
6088 } else {
6089 waddstr(view->window, "........");
6090 prev_id = NULL;
6093 if (nprinted == s->selected_line - 1)
6094 wstandend(view->window);
6095 waddstr(view->window, " ");
6097 if (view->ncols <= 9) {
6098 width = 9;
6099 } else if (s->first_displayed_line + nprinted ==
6100 s->matched_line &&
6101 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6102 err = add_matched_line(&width, line, view->ncols - 9, 9,
6103 view->window, view->x, regmatch);
6104 if (err) {
6105 free(line);
6106 return err;
6108 width += 9;
6109 } else {
6110 int skip;
6111 err = format_line(&wline, &width, &skip, line,
6112 view->x, view->ncols - 9, 9, 1);
6113 if (err) {
6114 free(line);
6115 return err;
6117 waddwstr(view->window, &wline[skip]);
6118 width += 9;
6119 free(wline);
6120 wline = NULL;
6123 if (width <= view->ncols - 1)
6124 waddch(view->window, '\n');
6125 if (++nprinted == 1)
6126 s->first_displayed_line = lineno;
6128 free(line);
6129 s->last_displayed_line = lineno;
6131 view_border(view);
6133 return NULL;
6136 static const struct got_error *
6137 blame_cb(void *arg, int nlines, int lineno,
6138 struct got_commit_object *commit, struct got_object_id *id)
6140 const struct got_error *err = NULL;
6141 struct tog_blame_cb_args *a = arg;
6142 struct tog_blame_line *line;
6143 int errcode;
6145 if (nlines != a->nlines ||
6146 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6147 return got_error(GOT_ERR_RANGE);
6149 errcode = pthread_mutex_lock(&tog_mutex);
6150 if (errcode)
6151 return got_error_set_errno(errcode, "pthread_mutex_lock");
6153 if (*a->quit) { /* user has quit the blame view */
6154 err = got_error(GOT_ERR_ITER_COMPLETED);
6155 goto done;
6158 if (lineno == -1)
6159 goto done; /* no change in this commit */
6161 line = &a->lines[lineno - 1];
6162 if (line->annotated)
6163 goto done;
6165 line->id = got_object_id_dup(id);
6166 if (line->id == NULL) {
6167 err = got_error_from_errno("got_object_id_dup");
6168 goto done;
6170 line->annotated = 1;
6171 done:
6172 errcode = pthread_mutex_unlock(&tog_mutex);
6173 if (errcode)
6174 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6175 return err;
6178 static void *
6179 blame_thread(void *arg)
6181 const struct got_error *err, *close_err;
6182 struct tog_blame_thread_args *ta = arg;
6183 struct tog_blame_cb_args *a = ta->cb_args;
6184 int errcode, fd1 = -1, fd2 = -1;
6185 FILE *f1 = NULL, *f2 = NULL;
6187 fd1 = got_opentempfd();
6188 if (fd1 == -1)
6189 return (void *)got_error_from_errno("got_opentempfd");
6191 fd2 = got_opentempfd();
6192 if (fd2 == -1) {
6193 err = got_error_from_errno("got_opentempfd");
6194 goto done;
6197 f1 = got_opentemp();
6198 if (f1 == NULL) {
6199 err = (void *)got_error_from_errno("got_opentemp");
6200 goto done;
6202 f2 = got_opentemp();
6203 if (f2 == NULL) {
6204 err = (void *)got_error_from_errno("got_opentemp");
6205 goto done;
6208 err = block_signals_used_by_main_thread();
6209 if (err)
6210 goto done;
6212 err = got_blame(ta->path, a->commit_id, ta->repo,
6213 tog_diff_algo, blame_cb, ta->cb_args,
6214 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6215 if (err && err->code == GOT_ERR_CANCELLED)
6216 err = NULL;
6218 errcode = pthread_mutex_lock(&tog_mutex);
6219 if (errcode) {
6220 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6221 goto done;
6224 close_err = got_repo_close(ta->repo);
6225 if (err == NULL)
6226 err = close_err;
6227 ta->repo = NULL;
6228 *ta->complete = 1;
6230 if (tog_io.wait_for_ui) {
6231 errcode = pthread_cond_signal(&ta->blame_complete);
6232 if (errcode && err == NULL)
6233 err = got_error_set_errno(errcode,
6234 "pthread_cond_signal");
6237 errcode = pthread_mutex_unlock(&tog_mutex);
6238 if (errcode && err == NULL)
6239 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6241 done:
6242 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6243 err = got_error_from_errno("close");
6244 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6245 err = got_error_from_errno("close");
6246 if (f1 && fclose(f1) == EOF && err == NULL)
6247 err = got_error_from_errno("fclose");
6248 if (f2 && fclose(f2) == EOF && err == NULL)
6249 err = got_error_from_errno("fclose");
6251 return (void *)err;
6254 static struct got_object_id *
6255 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6256 int first_displayed_line, int selected_line)
6258 struct tog_blame_line *line;
6260 if (nlines <= 0)
6261 return NULL;
6263 line = &lines[first_displayed_line - 1 + selected_line - 1];
6264 if (!line->annotated)
6265 return NULL;
6267 return line->id;
6270 static struct got_object_id *
6271 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6272 int lineno)
6274 struct tog_blame_line *line;
6276 if (nlines <= 0 || lineno >= nlines)
6277 return NULL;
6279 line = &lines[lineno - 1];
6280 if (!line->annotated)
6281 return NULL;
6283 return line->id;
6286 static const struct got_error *
6287 stop_blame(struct tog_blame *blame)
6289 const struct got_error *err = NULL;
6290 int i;
6292 if (blame->thread) {
6293 int errcode;
6294 errcode = pthread_mutex_unlock(&tog_mutex);
6295 if (errcode)
6296 return got_error_set_errno(errcode,
6297 "pthread_mutex_unlock");
6298 errcode = pthread_join(blame->thread, (void **)&err);
6299 if (errcode)
6300 return got_error_set_errno(errcode, "pthread_join");
6301 errcode = pthread_mutex_lock(&tog_mutex);
6302 if (errcode)
6303 return got_error_set_errno(errcode,
6304 "pthread_mutex_lock");
6305 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6306 err = NULL;
6307 blame->thread = NULL;
6309 if (blame->thread_args.repo) {
6310 const struct got_error *close_err;
6311 close_err = got_repo_close(blame->thread_args.repo);
6312 if (err == NULL)
6313 err = close_err;
6314 blame->thread_args.repo = NULL;
6316 if (blame->f) {
6317 if (fclose(blame->f) == EOF && err == NULL)
6318 err = got_error_from_errno("fclose");
6319 blame->f = NULL;
6321 if (blame->lines) {
6322 for (i = 0; i < blame->nlines; i++)
6323 free(blame->lines[i].id);
6324 free(blame->lines);
6325 blame->lines = NULL;
6327 free(blame->cb_args.commit_id);
6328 blame->cb_args.commit_id = NULL;
6329 if (blame->pack_fds) {
6330 const struct got_error *pack_err =
6331 got_repo_pack_fds_close(blame->pack_fds);
6332 if (err == NULL)
6333 err = pack_err;
6334 blame->pack_fds = NULL;
6336 return err;
6339 static const struct got_error *
6340 cancel_blame_view(void *arg)
6342 const struct got_error *err = NULL;
6343 int *done = arg;
6344 int errcode;
6346 errcode = pthread_mutex_lock(&tog_mutex);
6347 if (errcode)
6348 return got_error_set_errno(errcode,
6349 "pthread_mutex_unlock");
6351 if (*done)
6352 err = got_error(GOT_ERR_CANCELLED);
6354 errcode = pthread_mutex_unlock(&tog_mutex);
6355 if (errcode)
6356 return got_error_set_errno(errcode,
6357 "pthread_mutex_lock");
6359 return err;
6362 static const struct got_error *
6363 run_blame(struct tog_view *view)
6365 struct tog_blame_view_state *s = &view->state.blame;
6366 struct tog_blame *blame = &s->blame;
6367 const struct got_error *err = NULL;
6368 struct got_commit_object *commit = NULL;
6369 struct got_blob_object *blob = NULL;
6370 struct got_repository *thread_repo = NULL;
6371 struct got_object_id *obj_id = NULL;
6372 int obj_type, fd = -1;
6373 int *pack_fds = NULL;
6375 err = got_object_open_as_commit(&commit, s->repo,
6376 &s->blamed_commit->id);
6377 if (err)
6378 return err;
6380 fd = got_opentempfd();
6381 if (fd == -1) {
6382 err = got_error_from_errno("got_opentempfd");
6383 goto done;
6386 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6387 if (err)
6388 goto done;
6390 err = got_object_get_type(&obj_type, s->repo, obj_id);
6391 if (err)
6392 goto done;
6394 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6395 err = got_error(GOT_ERR_OBJ_TYPE);
6396 goto done;
6399 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6400 if (err)
6401 goto done;
6402 blame->f = got_opentemp();
6403 if (blame->f == NULL) {
6404 err = got_error_from_errno("got_opentemp");
6405 goto done;
6407 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6408 &blame->line_offsets, blame->f, blob);
6409 if (err)
6410 goto done;
6411 if (blame->nlines == 0) {
6412 s->blame_complete = 1;
6413 goto done;
6416 /* Don't include \n at EOF in the blame line count. */
6417 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6418 blame->nlines--;
6420 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6421 if (blame->lines == NULL) {
6422 err = got_error_from_errno("calloc");
6423 goto done;
6426 err = got_repo_pack_fds_open(&pack_fds);
6427 if (err)
6428 goto done;
6429 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6430 pack_fds);
6431 if (err)
6432 goto done;
6434 blame->pack_fds = pack_fds;
6435 blame->cb_args.view = view;
6436 blame->cb_args.lines = blame->lines;
6437 blame->cb_args.nlines = blame->nlines;
6438 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6439 if (blame->cb_args.commit_id == NULL) {
6440 err = got_error_from_errno("got_object_id_dup");
6441 goto done;
6443 blame->cb_args.quit = &s->done;
6445 blame->thread_args.path = s->path;
6446 blame->thread_args.repo = thread_repo;
6447 blame->thread_args.cb_args = &blame->cb_args;
6448 blame->thread_args.complete = &s->blame_complete;
6449 blame->thread_args.cancel_cb = cancel_blame_view;
6450 blame->thread_args.cancel_arg = &s->done;
6451 s->blame_complete = 0;
6453 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6454 s->first_displayed_line = 1;
6455 s->last_displayed_line = view->nlines;
6456 s->selected_line = 1;
6458 s->matched_line = 0;
6460 done:
6461 if (commit)
6462 got_object_commit_close(commit);
6463 if (fd != -1 && close(fd) == -1 && err == NULL)
6464 err = got_error_from_errno("close");
6465 if (blob)
6466 got_object_blob_close(blob);
6467 free(obj_id);
6468 if (err)
6469 stop_blame(blame);
6470 return err;
6473 static const struct got_error *
6474 open_blame_view(struct tog_view *view, char *path,
6475 struct got_object_id *commit_id, struct got_repository *repo)
6477 const struct got_error *err = NULL;
6478 struct tog_blame_view_state *s = &view->state.blame;
6480 STAILQ_INIT(&s->blamed_commits);
6482 s->path = strdup(path);
6483 if (s->path == NULL)
6484 return got_error_from_errno("strdup");
6486 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6487 if (err) {
6488 free(s->path);
6489 return err;
6492 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6493 s->first_displayed_line = 1;
6494 s->last_displayed_line = view->nlines;
6495 s->selected_line = 1;
6496 s->blame_complete = 0;
6497 s->repo = repo;
6498 s->commit_id = commit_id;
6499 memset(&s->blame, 0, sizeof(s->blame));
6501 STAILQ_INIT(&s->colors);
6502 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6503 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6504 get_color_value("TOG_COLOR_COMMIT"));
6505 if (err)
6506 return err;
6509 view->show = show_blame_view;
6510 view->input = input_blame_view;
6511 view->reset = reset_blame_view;
6512 view->close = close_blame_view;
6513 view->search_start = search_start_blame_view;
6514 view->search_setup = search_setup_blame_view;
6515 view->search_next = search_next_view_match;
6517 if (using_mock_io) {
6518 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6519 int rc;
6521 rc = pthread_cond_init(&bta->blame_complete, NULL);
6522 if (rc)
6523 return got_error_set_errno(rc, "pthread_cond_init");
6526 return run_blame(view);
6529 static const struct got_error *
6530 close_blame_view(struct tog_view *view)
6532 const struct got_error *err = NULL;
6533 struct tog_blame_view_state *s = &view->state.blame;
6535 if (s->blame.thread)
6536 err = stop_blame(&s->blame);
6538 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6539 struct got_object_qid *blamed_commit;
6540 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6541 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6542 got_object_qid_free(blamed_commit);
6545 if (using_mock_io) {
6546 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6547 int rc;
6549 rc = pthread_cond_destroy(&bta->blame_complete);
6550 if (rc && err == NULL)
6551 err = got_error_set_errno(rc, "pthread_cond_destroy");
6554 free(s->path);
6555 free_colors(&s->colors);
6556 return err;
6559 static const struct got_error *
6560 search_start_blame_view(struct tog_view *view)
6562 struct tog_blame_view_state *s = &view->state.blame;
6564 s->matched_line = 0;
6565 return NULL;
6568 static void
6569 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6570 size_t *nlines, int **first, int **last, int **match, int **selected)
6572 struct tog_blame_view_state *s = &view->state.blame;
6574 *f = s->blame.f;
6575 *nlines = s->blame.nlines;
6576 *line_offsets = s->blame.line_offsets;
6577 *match = &s->matched_line;
6578 *first = &s->first_displayed_line;
6579 *last = &s->last_displayed_line;
6580 *selected = &s->selected_line;
6583 static const struct got_error *
6584 show_blame_view(struct tog_view *view)
6586 const struct got_error *err = NULL;
6587 struct tog_blame_view_state *s = &view->state.blame;
6588 int errcode;
6590 if (s->blame.thread == NULL && !s->blame_complete) {
6591 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6592 &s->blame.thread_args);
6593 if (errcode)
6594 return got_error_set_errno(errcode, "pthread_create");
6596 if (!using_mock_io)
6597 halfdelay(1); /* fast refresh while annotating */
6600 if (s->blame_complete && !using_mock_io)
6601 halfdelay(10); /* disable fast refresh */
6603 err = draw_blame(view);
6605 view_border(view);
6606 return err;
6609 static const struct got_error *
6610 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6611 struct got_repository *repo, struct got_object_id *id)
6613 struct tog_view *log_view;
6614 const struct got_error *err = NULL;
6616 *new_view = NULL;
6618 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6619 if (log_view == NULL)
6620 return got_error_from_errno("view_open");
6622 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6623 if (err)
6624 view_close(log_view);
6625 else
6626 *new_view = log_view;
6628 return err;
6631 static const struct got_error *
6632 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6634 const struct got_error *err = NULL, *thread_err = NULL;
6635 struct tog_view *diff_view;
6636 struct tog_blame_view_state *s = &view->state.blame;
6637 int eos, nscroll, begin_y = 0, begin_x = 0;
6639 eos = nscroll = view->nlines - 2;
6640 if (view_is_hsplit_top(view))
6641 --eos; /* border */
6643 switch (ch) {
6644 case '0':
6645 case '$':
6646 case KEY_RIGHT:
6647 case 'l':
6648 case KEY_LEFT:
6649 case 'h':
6650 horizontal_scroll_input(view, ch);
6651 break;
6652 case 'q':
6653 s->done = 1;
6654 break;
6655 case 'g':
6656 case KEY_HOME:
6657 s->selected_line = 1;
6658 s->first_displayed_line = 1;
6659 view->count = 0;
6660 break;
6661 case 'G':
6662 case KEY_END:
6663 if (s->blame.nlines < eos) {
6664 s->selected_line = s->blame.nlines;
6665 s->first_displayed_line = 1;
6666 } else {
6667 s->selected_line = eos;
6668 s->first_displayed_line = s->blame.nlines - (eos - 1);
6670 view->count = 0;
6671 break;
6672 case 'k':
6673 case KEY_UP:
6674 case CTRL('p'):
6675 if (s->selected_line > 1)
6676 s->selected_line--;
6677 else if (s->selected_line == 1 &&
6678 s->first_displayed_line > 1)
6679 s->first_displayed_line--;
6680 else
6681 view->count = 0;
6682 break;
6683 case CTRL('u'):
6684 case 'u':
6685 nscroll /= 2;
6686 /* FALL THROUGH */
6687 case KEY_PPAGE:
6688 case CTRL('b'):
6689 case 'b':
6690 if (s->first_displayed_line == 1) {
6691 if (view->count > 1)
6692 nscroll += nscroll;
6693 s->selected_line = MAX(1, s->selected_line - nscroll);
6694 view->count = 0;
6695 break;
6697 if (s->first_displayed_line > nscroll)
6698 s->first_displayed_line -= nscroll;
6699 else
6700 s->first_displayed_line = 1;
6701 break;
6702 case 'j':
6703 case KEY_DOWN:
6704 case CTRL('n'):
6705 if (s->selected_line < eos && s->first_displayed_line +
6706 s->selected_line <= s->blame.nlines)
6707 s->selected_line++;
6708 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6709 s->first_displayed_line++;
6710 else
6711 view->count = 0;
6712 break;
6713 case 'c':
6714 case 'p': {
6715 struct got_object_id *id = NULL;
6717 view->count = 0;
6718 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6719 s->first_displayed_line, s->selected_line);
6720 if (id == NULL)
6721 break;
6722 if (ch == 'p') {
6723 struct got_commit_object *commit, *pcommit;
6724 struct got_object_qid *pid;
6725 struct got_object_id *blob_id = NULL;
6726 int obj_type;
6727 err = got_object_open_as_commit(&commit,
6728 s->repo, id);
6729 if (err)
6730 break;
6731 pid = STAILQ_FIRST(
6732 got_object_commit_get_parent_ids(commit));
6733 if (pid == NULL) {
6734 got_object_commit_close(commit);
6735 break;
6737 /* Check if path history ends here. */
6738 err = got_object_open_as_commit(&pcommit,
6739 s->repo, &pid->id);
6740 if (err)
6741 break;
6742 err = got_object_id_by_path(&blob_id, s->repo,
6743 pcommit, s->path);
6744 got_object_commit_close(pcommit);
6745 if (err) {
6746 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6747 err = NULL;
6748 got_object_commit_close(commit);
6749 break;
6751 err = got_object_get_type(&obj_type, s->repo,
6752 blob_id);
6753 free(blob_id);
6754 /* Can't blame non-blob type objects. */
6755 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6756 got_object_commit_close(commit);
6757 break;
6759 err = got_object_qid_alloc(&s->blamed_commit,
6760 &pid->id);
6761 got_object_commit_close(commit);
6762 } else {
6763 if (got_object_id_cmp(id,
6764 &s->blamed_commit->id) == 0)
6765 break;
6766 err = got_object_qid_alloc(&s->blamed_commit,
6767 id);
6769 if (err)
6770 break;
6771 s->done = 1;
6772 thread_err = stop_blame(&s->blame);
6773 s->done = 0;
6774 if (thread_err)
6775 break;
6776 STAILQ_INSERT_HEAD(&s->blamed_commits,
6777 s->blamed_commit, entry);
6778 err = run_blame(view);
6779 if (err)
6780 break;
6781 break;
6783 case 'C': {
6784 struct got_object_qid *first;
6786 view->count = 0;
6787 first = STAILQ_FIRST(&s->blamed_commits);
6788 if (!got_object_id_cmp(&first->id, s->commit_id))
6789 break;
6790 s->done = 1;
6791 thread_err = stop_blame(&s->blame);
6792 s->done = 0;
6793 if (thread_err)
6794 break;
6795 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6796 got_object_qid_free(s->blamed_commit);
6797 s->blamed_commit =
6798 STAILQ_FIRST(&s->blamed_commits);
6799 err = run_blame(view);
6800 if (err)
6801 break;
6802 break;
6804 case 'L':
6805 view->count = 0;
6806 s->id_to_log = get_selected_commit_id(s->blame.lines,
6807 s->blame.nlines, s->first_displayed_line, s->selected_line);
6808 if (s->id_to_log)
6809 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6810 break;
6811 case KEY_ENTER:
6812 case '\r': {
6813 struct got_object_id *id = NULL;
6814 struct got_object_qid *pid;
6815 struct got_commit_object *commit = NULL;
6817 view->count = 0;
6818 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6819 s->first_displayed_line, s->selected_line);
6820 if (id == NULL)
6821 break;
6822 err = got_object_open_as_commit(&commit, s->repo, id);
6823 if (err)
6824 break;
6825 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6826 if (*new_view) {
6827 /* traversed from diff view, release diff resources */
6828 err = close_diff_view(*new_view);
6829 if (err)
6830 break;
6831 diff_view = *new_view;
6832 } else {
6833 if (view_is_parent_view(view))
6834 view_get_split(view, &begin_y, &begin_x);
6836 diff_view = view_open(0, 0, begin_y, begin_x,
6837 TOG_VIEW_DIFF);
6838 if (diff_view == NULL) {
6839 got_object_commit_close(commit);
6840 err = got_error_from_errno("view_open");
6841 break;
6844 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6845 id, NULL, NULL, 3, 0, 0, view, s->repo);
6846 got_object_commit_close(commit);
6847 if (err) {
6848 view_close(diff_view);
6849 break;
6851 s->last_diffed_line = s->first_displayed_line - 1 +
6852 s->selected_line;
6853 if (*new_view)
6854 break; /* still open from active diff view */
6855 if (view_is_parent_view(view) &&
6856 view->mode == TOG_VIEW_SPLIT_HRZN) {
6857 err = view_init_hsplit(view, begin_y);
6858 if (err)
6859 break;
6862 view->focussed = 0;
6863 diff_view->focussed = 1;
6864 diff_view->mode = view->mode;
6865 diff_view->nlines = view->lines - begin_y;
6866 if (view_is_parent_view(view)) {
6867 view_transfer_size(diff_view, view);
6868 err = view_close_child(view);
6869 if (err)
6870 break;
6871 err = view_set_child(view, diff_view);
6872 if (err)
6873 break;
6874 view->focus_child = 1;
6875 } else
6876 *new_view = diff_view;
6877 if (err)
6878 break;
6879 break;
6881 case CTRL('d'):
6882 case 'd':
6883 nscroll /= 2;
6884 /* FALL THROUGH */
6885 case KEY_NPAGE:
6886 case CTRL('f'):
6887 case 'f':
6888 case ' ':
6889 if (s->last_displayed_line >= s->blame.nlines &&
6890 s->selected_line >= MIN(s->blame.nlines,
6891 view->nlines - 2)) {
6892 view->count = 0;
6893 break;
6895 if (s->last_displayed_line >= s->blame.nlines &&
6896 s->selected_line < view->nlines - 2) {
6897 s->selected_line +=
6898 MIN(nscroll, s->last_displayed_line -
6899 s->first_displayed_line - s->selected_line + 1);
6901 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6902 s->first_displayed_line += nscroll;
6903 else
6904 s->first_displayed_line =
6905 s->blame.nlines - (view->nlines - 3);
6906 break;
6907 case KEY_RESIZE:
6908 if (s->selected_line > view->nlines - 2) {
6909 s->selected_line = MIN(s->blame.nlines,
6910 view->nlines - 2);
6912 break;
6913 default:
6914 view->count = 0;
6915 break;
6917 return thread_err ? thread_err : err;
6920 static const struct got_error *
6921 reset_blame_view(struct tog_view *view)
6923 const struct got_error *err;
6924 struct tog_blame_view_state *s = &view->state.blame;
6926 view->count = 0;
6927 s->done = 1;
6928 err = stop_blame(&s->blame);
6929 s->done = 0;
6930 if (err)
6931 return err;
6932 return run_blame(view);
6935 static const struct got_error *
6936 cmd_blame(int argc, char *argv[])
6938 const struct got_error *error;
6939 struct got_repository *repo = NULL;
6940 struct got_worktree *worktree = NULL;
6941 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6942 char *link_target = NULL;
6943 struct got_object_id *commit_id = NULL;
6944 struct got_commit_object *commit = NULL;
6945 char *commit_id_str = NULL;
6946 int ch;
6947 struct tog_view *view = NULL;
6948 int *pack_fds = NULL;
6950 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6951 switch (ch) {
6952 case 'c':
6953 commit_id_str = optarg;
6954 break;
6955 case 'r':
6956 repo_path = realpath(optarg, NULL);
6957 if (repo_path == NULL)
6958 return got_error_from_errno2("realpath",
6959 optarg);
6960 break;
6961 default:
6962 usage_blame();
6963 /* NOTREACHED */
6967 argc -= optind;
6968 argv += optind;
6970 if (argc != 1)
6971 usage_blame();
6973 error = got_repo_pack_fds_open(&pack_fds);
6974 if (error != NULL)
6975 goto done;
6977 if (repo_path == NULL) {
6978 cwd = getcwd(NULL, 0);
6979 if (cwd == NULL)
6980 return got_error_from_errno("getcwd");
6981 error = got_worktree_open(&worktree, cwd);
6982 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6983 goto done;
6984 if (worktree)
6985 repo_path =
6986 strdup(got_worktree_get_repo_path(worktree));
6987 else
6988 repo_path = strdup(cwd);
6989 if (repo_path == NULL) {
6990 error = got_error_from_errno("strdup");
6991 goto done;
6995 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6996 if (error != NULL)
6997 goto done;
6999 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7000 worktree);
7001 if (error)
7002 goto done;
7004 init_curses();
7006 error = apply_unveil(got_repo_get_path(repo), NULL);
7007 if (error)
7008 goto done;
7010 error = tog_load_refs(repo, 0);
7011 if (error)
7012 goto done;
7014 if (commit_id_str == NULL) {
7015 struct got_reference *head_ref;
7016 error = got_ref_open(&head_ref, repo, worktree ?
7017 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7018 if (error != NULL)
7019 goto done;
7020 error = got_ref_resolve(&commit_id, repo, head_ref);
7021 got_ref_close(head_ref);
7022 } else {
7023 error = got_repo_match_object_id(&commit_id, NULL,
7024 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7026 if (error != NULL)
7027 goto done;
7029 error = got_object_open_as_commit(&commit, repo, commit_id);
7030 if (error)
7031 goto done;
7033 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7034 commit, repo);
7035 if (error)
7036 goto done;
7038 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7039 if (view == NULL) {
7040 error = got_error_from_errno("view_open");
7041 goto done;
7043 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7044 commit_id, repo);
7045 if (error != NULL) {
7046 if (view->close == NULL)
7047 close_blame_view(view);
7048 view_close(view);
7049 goto done;
7051 if (worktree) {
7052 /* Release work tree lock. */
7053 got_worktree_close(worktree);
7054 worktree = NULL;
7056 error = view_loop(view);
7057 done:
7058 free(repo_path);
7059 free(in_repo_path);
7060 free(link_target);
7061 free(cwd);
7062 free(commit_id);
7063 if (commit)
7064 got_object_commit_close(commit);
7065 if (worktree)
7066 got_worktree_close(worktree);
7067 if (repo) {
7068 const struct got_error *close_err = got_repo_close(repo);
7069 if (error == NULL)
7070 error = close_err;
7072 if (pack_fds) {
7073 const struct got_error *pack_err =
7074 got_repo_pack_fds_close(pack_fds);
7075 if (error == NULL)
7076 error = pack_err;
7078 tog_free_refs();
7079 return error;
7082 static const struct got_error *
7083 draw_tree_entries(struct tog_view *view, const char *parent_path)
7085 struct tog_tree_view_state *s = &view->state.tree;
7086 const struct got_error *err = NULL;
7087 struct got_tree_entry *te;
7088 wchar_t *wline;
7089 char *index = NULL;
7090 struct tog_color *tc;
7091 int width, n, nentries, scrollx, i = 1;
7092 int limit = view->nlines;
7094 s->ndisplayed = 0;
7095 if (view_is_hsplit_top(view))
7096 --limit; /* border */
7098 werase(view->window);
7100 if (limit == 0)
7101 return NULL;
7103 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7104 0, 0);
7105 if (err)
7106 return err;
7107 if (view_needs_focus_indication(view))
7108 wstandout(view->window);
7109 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7110 if (tc)
7111 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7112 waddwstr(view->window, wline);
7113 free(wline);
7114 wline = NULL;
7115 while (width++ < view->ncols)
7116 waddch(view->window, ' ');
7117 if (tc)
7118 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7119 if (view_needs_focus_indication(view))
7120 wstandend(view->window);
7121 if (--limit <= 0)
7122 return NULL;
7124 i += s->selected;
7125 if (s->first_displayed_entry) {
7126 i += got_tree_entry_get_index(s->first_displayed_entry);
7127 if (s->tree != s->root)
7128 ++i; /* account for ".." entry */
7130 nentries = got_object_tree_get_nentries(s->tree);
7131 if (asprintf(&index, "[%d/%d] %s",
7132 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7133 return got_error_from_errno("asprintf");
7134 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7135 free(index);
7136 if (err)
7137 return err;
7138 waddwstr(view->window, wline);
7139 free(wline);
7140 wline = NULL;
7141 if (width < view->ncols - 1)
7142 waddch(view->window, '\n');
7143 if (--limit <= 0)
7144 return NULL;
7145 waddch(view->window, '\n');
7146 if (--limit <= 0)
7147 return NULL;
7149 if (s->first_displayed_entry == NULL) {
7150 te = got_object_tree_get_first_entry(s->tree);
7151 if (s->selected == 0) {
7152 if (view->focussed)
7153 wstandout(view->window);
7154 s->selected_entry = NULL;
7156 waddstr(view->window, " ..\n"); /* parent directory */
7157 if (s->selected == 0 && view->focussed)
7158 wstandend(view->window);
7159 s->ndisplayed++;
7160 if (--limit <= 0)
7161 return NULL;
7162 n = 1;
7163 } else {
7164 n = 0;
7165 te = s->first_displayed_entry;
7168 view->maxx = 0;
7169 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7170 char *line = NULL, *id_str = NULL, *link_target = NULL;
7171 const char *modestr = "";
7172 mode_t mode;
7174 te = got_object_tree_get_entry(s->tree, i);
7175 mode = got_tree_entry_get_mode(te);
7177 if (s->show_ids) {
7178 err = got_object_id_str(&id_str,
7179 got_tree_entry_get_id(te));
7180 if (err)
7181 return got_error_from_errno(
7182 "got_object_id_str");
7184 if (got_object_tree_entry_is_submodule(te))
7185 modestr = "$";
7186 else if (S_ISLNK(mode)) {
7187 int i;
7189 err = got_tree_entry_get_symlink_target(&link_target,
7190 te, s->repo);
7191 if (err) {
7192 free(id_str);
7193 return err;
7195 for (i = 0; i < strlen(link_target); i++) {
7196 if (!isprint((unsigned char)link_target[i]))
7197 link_target[i] = '?';
7199 modestr = "@";
7201 else if (S_ISDIR(mode))
7202 modestr = "/";
7203 else if (mode & S_IXUSR)
7204 modestr = "*";
7205 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7206 got_tree_entry_get_name(te), modestr,
7207 link_target ? " -> ": "",
7208 link_target ? link_target : "") == -1) {
7209 free(id_str);
7210 free(link_target);
7211 return got_error_from_errno("asprintf");
7213 free(id_str);
7214 free(link_target);
7216 /* use full line width to determine view->maxx */
7217 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7218 if (err) {
7219 free(line);
7220 break;
7222 view->maxx = MAX(view->maxx, width);
7223 free(wline);
7224 wline = NULL;
7226 err = format_line(&wline, &width, &scrollx, line, view->x,
7227 view->ncols, 0, 0);
7228 if (err) {
7229 free(line);
7230 break;
7232 if (n == s->selected) {
7233 if (view->focussed)
7234 wstandout(view->window);
7235 s->selected_entry = te;
7237 tc = match_color(&s->colors, line);
7238 if (tc)
7239 wattr_on(view->window,
7240 COLOR_PAIR(tc->colorpair), NULL);
7241 waddwstr(view->window, &wline[scrollx]);
7242 if (tc)
7243 wattr_off(view->window,
7244 COLOR_PAIR(tc->colorpair), NULL);
7245 if (width < view->ncols)
7246 waddch(view->window, '\n');
7247 if (n == s->selected && view->focussed)
7248 wstandend(view->window);
7249 free(line);
7250 free(wline);
7251 wline = NULL;
7252 n++;
7253 s->ndisplayed++;
7254 s->last_displayed_entry = te;
7255 if (--limit <= 0)
7256 break;
7259 return err;
7262 static void
7263 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7265 struct got_tree_entry *te;
7266 int isroot = s->tree == s->root;
7267 int i = 0;
7269 if (s->first_displayed_entry == NULL)
7270 return;
7272 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7273 while (i++ < maxscroll) {
7274 if (te == NULL) {
7275 if (!isroot)
7276 s->first_displayed_entry = NULL;
7277 break;
7279 s->first_displayed_entry = te;
7280 te = got_tree_entry_get_prev(s->tree, te);
7284 static const struct got_error *
7285 tree_scroll_down(struct tog_view *view, int maxscroll)
7287 struct tog_tree_view_state *s = &view->state.tree;
7288 struct got_tree_entry *next, *last;
7289 int n = 0;
7291 if (s->first_displayed_entry)
7292 next = got_tree_entry_get_next(s->tree,
7293 s->first_displayed_entry);
7294 else
7295 next = got_object_tree_get_first_entry(s->tree);
7297 last = s->last_displayed_entry;
7298 while (next && n++ < maxscroll) {
7299 if (last) {
7300 s->last_displayed_entry = last;
7301 last = got_tree_entry_get_next(s->tree, last);
7303 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7304 s->first_displayed_entry = next;
7305 next = got_tree_entry_get_next(s->tree, next);
7309 return NULL;
7312 static const struct got_error *
7313 tree_entry_path(char **path, struct tog_parent_trees *parents,
7314 struct got_tree_entry *te)
7316 const struct got_error *err = NULL;
7317 struct tog_parent_tree *pt;
7318 size_t len = 2; /* for leading slash and NUL */
7320 TAILQ_FOREACH(pt, parents, entry)
7321 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7322 + 1 /* slash */;
7323 if (te)
7324 len += strlen(got_tree_entry_get_name(te));
7326 *path = calloc(1, len);
7327 if (path == NULL)
7328 return got_error_from_errno("calloc");
7330 (*path)[0] = '/';
7331 pt = TAILQ_LAST(parents, tog_parent_trees);
7332 while (pt) {
7333 const char *name = got_tree_entry_get_name(pt->selected_entry);
7334 if (strlcat(*path, name, len) >= len) {
7335 err = got_error(GOT_ERR_NO_SPACE);
7336 goto done;
7338 if (strlcat(*path, "/", len) >= len) {
7339 err = got_error(GOT_ERR_NO_SPACE);
7340 goto done;
7342 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7344 if (te) {
7345 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7346 err = got_error(GOT_ERR_NO_SPACE);
7347 goto done;
7350 done:
7351 if (err) {
7352 free(*path);
7353 *path = NULL;
7355 return err;
7358 static const struct got_error *
7359 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7360 struct got_tree_entry *te, struct tog_parent_trees *parents,
7361 struct got_object_id *commit_id, struct got_repository *repo)
7363 const struct got_error *err = NULL;
7364 char *path;
7365 struct tog_view *blame_view;
7367 *new_view = NULL;
7369 err = tree_entry_path(&path, parents, te);
7370 if (err)
7371 return err;
7373 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7374 if (blame_view == NULL) {
7375 err = got_error_from_errno("view_open");
7376 goto done;
7379 err = open_blame_view(blame_view, path, commit_id, repo);
7380 if (err) {
7381 if (err->code == GOT_ERR_CANCELLED)
7382 err = NULL;
7383 view_close(blame_view);
7384 } else
7385 *new_view = blame_view;
7386 done:
7387 free(path);
7388 return err;
7391 static const struct got_error *
7392 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7393 struct tog_tree_view_state *s)
7395 struct tog_view *log_view;
7396 const struct got_error *err = NULL;
7397 char *path;
7399 *new_view = NULL;
7401 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7402 if (log_view == NULL)
7403 return got_error_from_errno("view_open");
7405 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7406 if (err)
7407 return err;
7409 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7410 path, 0);
7411 if (err)
7412 view_close(log_view);
7413 else
7414 *new_view = log_view;
7415 free(path);
7416 return err;
7419 static const struct got_error *
7420 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7421 const char *head_ref_name, struct got_repository *repo)
7423 const struct got_error *err = NULL;
7424 char *commit_id_str = NULL;
7425 struct tog_tree_view_state *s = &view->state.tree;
7426 struct got_commit_object *commit = NULL;
7428 TAILQ_INIT(&s->parents);
7429 STAILQ_INIT(&s->colors);
7431 s->commit_id = got_object_id_dup(commit_id);
7432 if (s->commit_id == NULL) {
7433 err = got_error_from_errno("got_object_id_dup");
7434 goto done;
7437 err = got_object_open_as_commit(&commit, repo, commit_id);
7438 if (err)
7439 goto done;
7442 * The root is opened here and will be closed when the view is closed.
7443 * Any visited subtrees and their path-wise parents are opened and
7444 * closed on demand.
7446 err = got_object_open_as_tree(&s->root, repo,
7447 got_object_commit_get_tree_id(commit));
7448 if (err)
7449 goto done;
7450 s->tree = s->root;
7452 err = got_object_id_str(&commit_id_str, commit_id);
7453 if (err != NULL)
7454 goto done;
7456 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7457 err = got_error_from_errno("asprintf");
7458 goto done;
7461 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7462 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7463 if (head_ref_name) {
7464 s->head_ref_name = strdup(head_ref_name);
7465 if (s->head_ref_name == NULL) {
7466 err = got_error_from_errno("strdup");
7467 goto done;
7470 s->repo = repo;
7472 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7473 err = add_color(&s->colors, "\\$$",
7474 TOG_COLOR_TREE_SUBMODULE,
7475 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7476 if (err)
7477 goto done;
7478 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7479 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7480 if (err)
7481 goto done;
7482 err = add_color(&s->colors, "/$",
7483 TOG_COLOR_TREE_DIRECTORY,
7484 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7485 if (err)
7486 goto done;
7488 err = add_color(&s->colors, "\\*$",
7489 TOG_COLOR_TREE_EXECUTABLE,
7490 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7491 if (err)
7492 goto done;
7494 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7495 get_color_value("TOG_COLOR_COMMIT"));
7496 if (err)
7497 goto done;
7500 view->show = show_tree_view;
7501 view->input = input_tree_view;
7502 view->close = close_tree_view;
7503 view->search_start = search_start_tree_view;
7504 view->search_next = search_next_tree_view;
7505 done:
7506 free(commit_id_str);
7507 if (commit)
7508 got_object_commit_close(commit);
7509 if (err) {
7510 if (view->close == NULL)
7511 close_tree_view(view);
7512 view_close(view);
7514 return err;
7517 static const struct got_error *
7518 close_tree_view(struct tog_view *view)
7520 struct tog_tree_view_state *s = &view->state.tree;
7522 free_colors(&s->colors);
7523 free(s->tree_label);
7524 s->tree_label = NULL;
7525 free(s->commit_id);
7526 s->commit_id = NULL;
7527 free(s->head_ref_name);
7528 s->head_ref_name = NULL;
7529 while (!TAILQ_EMPTY(&s->parents)) {
7530 struct tog_parent_tree *parent;
7531 parent = TAILQ_FIRST(&s->parents);
7532 TAILQ_REMOVE(&s->parents, parent, entry);
7533 if (parent->tree != s->root)
7534 got_object_tree_close(parent->tree);
7535 free(parent);
7538 if (s->tree != NULL && s->tree != s->root)
7539 got_object_tree_close(s->tree);
7540 if (s->root)
7541 got_object_tree_close(s->root);
7542 return NULL;
7545 static const struct got_error *
7546 search_start_tree_view(struct tog_view *view)
7548 struct tog_tree_view_state *s = &view->state.tree;
7550 s->matched_entry = NULL;
7551 return NULL;
7554 static int
7555 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7557 regmatch_t regmatch;
7559 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7560 0) == 0;
7563 static const struct got_error *
7564 search_next_tree_view(struct tog_view *view)
7566 struct tog_tree_view_state *s = &view->state.tree;
7567 struct got_tree_entry *te = NULL;
7569 if (!view->searching) {
7570 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7571 return NULL;
7574 if (s->matched_entry) {
7575 if (view->searching == TOG_SEARCH_FORWARD) {
7576 if (s->selected_entry)
7577 te = got_tree_entry_get_next(s->tree,
7578 s->selected_entry);
7579 else
7580 te = got_object_tree_get_first_entry(s->tree);
7581 } else {
7582 if (s->selected_entry == NULL)
7583 te = got_object_tree_get_last_entry(s->tree);
7584 else
7585 te = got_tree_entry_get_prev(s->tree,
7586 s->selected_entry);
7588 } else {
7589 if (s->selected_entry)
7590 te = s->selected_entry;
7591 else if (view->searching == TOG_SEARCH_FORWARD)
7592 te = got_object_tree_get_first_entry(s->tree);
7593 else
7594 te = got_object_tree_get_last_entry(s->tree);
7597 while (1) {
7598 if (te == NULL) {
7599 if (s->matched_entry == NULL) {
7600 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7601 return NULL;
7603 if (view->searching == TOG_SEARCH_FORWARD)
7604 te = got_object_tree_get_first_entry(s->tree);
7605 else
7606 te = got_object_tree_get_last_entry(s->tree);
7609 if (match_tree_entry(te, &view->regex)) {
7610 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7611 s->matched_entry = te;
7612 break;
7615 if (view->searching == TOG_SEARCH_FORWARD)
7616 te = got_tree_entry_get_next(s->tree, te);
7617 else
7618 te = got_tree_entry_get_prev(s->tree, te);
7621 if (s->matched_entry) {
7622 s->first_displayed_entry = s->matched_entry;
7623 s->selected = 0;
7626 return NULL;
7629 static const struct got_error *
7630 show_tree_view(struct tog_view *view)
7632 const struct got_error *err = NULL;
7633 struct tog_tree_view_state *s = &view->state.tree;
7634 char *parent_path;
7636 err = tree_entry_path(&parent_path, &s->parents, NULL);
7637 if (err)
7638 return err;
7640 err = draw_tree_entries(view, parent_path);
7641 free(parent_path);
7643 view_border(view);
7644 return err;
7647 static const struct got_error *
7648 tree_goto_line(struct tog_view *view, int nlines)
7650 const struct got_error *err = NULL;
7651 struct tog_tree_view_state *s = &view->state.tree;
7652 struct got_tree_entry **fte, **lte, **ste;
7653 int g, last, first = 1, i = 1;
7654 int root = s->tree == s->root;
7655 int off = root ? 1 : 2;
7657 g = view->gline;
7658 view->gline = 0;
7660 if (g == 0)
7661 g = 1;
7662 else if (g > got_object_tree_get_nentries(s->tree))
7663 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7665 fte = &s->first_displayed_entry;
7666 lte = &s->last_displayed_entry;
7667 ste = &s->selected_entry;
7669 if (*fte != NULL) {
7670 first = got_tree_entry_get_index(*fte);
7671 first += off; /* account for ".." */
7673 last = got_tree_entry_get_index(*lte);
7674 last += off;
7676 if (g >= first && g <= last && g - first < nlines) {
7677 s->selected = g - first;
7678 return NULL; /* gline is on the current page */
7681 if (*ste != NULL) {
7682 i = got_tree_entry_get_index(*ste);
7683 i += off;
7686 if (i < g) {
7687 err = tree_scroll_down(view, g - i);
7688 if (err)
7689 return err;
7690 if (got_tree_entry_get_index(*lte) >=
7691 got_object_tree_get_nentries(s->tree) - 1 &&
7692 first + s->selected < g &&
7693 s->selected < s->ndisplayed - 1) {
7694 first = got_tree_entry_get_index(*fte);
7695 first += off;
7696 s->selected = g - first;
7698 } else if (i > g)
7699 tree_scroll_up(s, i - g);
7701 if (g < nlines &&
7702 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7703 s->selected = g - 1;
7705 return NULL;
7708 static const struct got_error *
7709 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7711 const struct got_error *err = NULL;
7712 struct tog_tree_view_state *s = &view->state.tree;
7713 struct got_tree_entry *te;
7714 int n, nscroll = view->nlines - 3;
7716 if (view->gline)
7717 return tree_goto_line(view, nscroll);
7719 switch (ch) {
7720 case '0':
7721 case '$':
7722 case KEY_RIGHT:
7723 case 'l':
7724 case KEY_LEFT:
7725 case 'h':
7726 horizontal_scroll_input(view, ch);
7727 break;
7728 case 'i':
7729 s->show_ids = !s->show_ids;
7730 view->count = 0;
7731 break;
7732 case 'L':
7733 view->count = 0;
7734 if (!s->selected_entry)
7735 break;
7736 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7737 break;
7738 case 'R':
7739 view->count = 0;
7740 err = view_request_new(new_view, view, TOG_VIEW_REF);
7741 break;
7742 case 'g':
7743 case '=':
7744 case KEY_HOME:
7745 s->selected = 0;
7746 view->count = 0;
7747 if (s->tree == s->root)
7748 s->first_displayed_entry =
7749 got_object_tree_get_first_entry(s->tree);
7750 else
7751 s->first_displayed_entry = NULL;
7752 break;
7753 case 'G':
7754 case '*':
7755 case KEY_END: {
7756 int eos = view->nlines - 3;
7758 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7759 --eos; /* border */
7760 s->selected = 0;
7761 view->count = 0;
7762 te = got_object_tree_get_last_entry(s->tree);
7763 for (n = 0; n < eos; n++) {
7764 if (te == NULL) {
7765 if (s->tree != s->root) {
7766 s->first_displayed_entry = NULL;
7767 n++;
7769 break;
7771 s->first_displayed_entry = te;
7772 te = got_tree_entry_get_prev(s->tree, te);
7774 if (n > 0)
7775 s->selected = n - 1;
7776 break;
7778 case 'k':
7779 case KEY_UP:
7780 case CTRL('p'):
7781 if (s->selected > 0) {
7782 s->selected--;
7783 break;
7785 tree_scroll_up(s, 1);
7786 if (s->selected_entry == NULL ||
7787 (s->tree == s->root && s->selected_entry ==
7788 got_object_tree_get_first_entry(s->tree)))
7789 view->count = 0;
7790 break;
7791 case CTRL('u'):
7792 case 'u':
7793 nscroll /= 2;
7794 /* FALL THROUGH */
7795 case KEY_PPAGE:
7796 case CTRL('b'):
7797 case 'b':
7798 if (s->tree == s->root) {
7799 if (got_object_tree_get_first_entry(s->tree) ==
7800 s->first_displayed_entry)
7801 s->selected -= MIN(s->selected, nscroll);
7802 } else {
7803 if (s->first_displayed_entry == NULL)
7804 s->selected -= MIN(s->selected, nscroll);
7806 tree_scroll_up(s, MAX(0, nscroll));
7807 if (s->selected_entry == NULL ||
7808 (s->tree == s->root && s->selected_entry ==
7809 got_object_tree_get_first_entry(s->tree)))
7810 view->count = 0;
7811 break;
7812 case 'j':
7813 case KEY_DOWN:
7814 case CTRL('n'):
7815 if (s->selected < s->ndisplayed - 1) {
7816 s->selected++;
7817 break;
7819 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7820 == NULL) {
7821 /* can't scroll any further */
7822 view->count = 0;
7823 break;
7825 tree_scroll_down(view, 1);
7826 break;
7827 case CTRL('d'):
7828 case 'd':
7829 nscroll /= 2;
7830 /* FALL THROUGH */
7831 case KEY_NPAGE:
7832 case CTRL('f'):
7833 case 'f':
7834 case ' ':
7835 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7836 == NULL) {
7837 /* can't scroll any further; move cursor down */
7838 if (s->selected < s->ndisplayed - 1)
7839 s->selected += MIN(nscroll,
7840 s->ndisplayed - s->selected - 1);
7841 else
7842 view->count = 0;
7843 break;
7845 tree_scroll_down(view, nscroll);
7846 break;
7847 case KEY_ENTER:
7848 case '\r':
7849 case KEY_BACKSPACE:
7850 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7851 struct tog_parent_tree *parent;
7852 /* user selected '..' */
7853 if (s->tree == s->root) {
7854 view->count = 0;
7855 break;
7857 parent = TAILQ_FIRST(&s->parents);
7858 TAILQ_REMOVE(&s->parents, parent,
7859 entry);
7860 got_object_tree_close(s->tree);
7861 s->tree = parent->tree;
7862 s->first_displayed_entry =
7863 parent->first_displayed_entry;
7864 s->selected_entry =
7865 parent->selected_entry;
7866 s->selected = parent->selected;
7867 if (s->selected > view->nlines - 3) {
7868 err = offset_selection_down(view);
7869 if (err)
7870 break;
7872 free(parent);
7873 } else if (S_ISDIR(got_tree_entry_get_mode(
7874 s->selected_entry))) {
7875 struct got_tree_object *subtree;
7876 view->count = 0;
7877 err = got_object_open_as_tree(&subtree, s->repo,
7878 got_tree_entry_get_id(s->selected_entry));
7879 if (err)
7880 break;
7881 err = tree_view_visit_subtree(s, subtree);
7882 if (err) {
7883 got_object_tree_close(subtree);
7884 break;
7886 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7887 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7888 break;
7889 case KEY_RESIZE:
7890 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7891 s->selected = view->nlines - 4;
7892 view->count = 0;
7893 break;
7894 default:
7895 view->count = 0;
7896 break;
7899 return err;
7902 __dead static void
7903 usage_tree(void)
7905 endwin();
7906 fprintf(stderr,
7907 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7908 getprogname());
7909 exit(1);
7912 static const struct got_error *
7913 cmd_tree(int argc, char *argv[])
7915 const struct got_error *error;
7916 struct got_repository *repo = NULL;
7917 struct got_worktree *worktree = NULL;
7918 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7919 struct got_object_id *commit_id = NULL;
7920 struct got_commit_object *commit = NULL;
7921 const char *commit_id_arg = NULL;
7922 char *label = NULL;
7923 struct got_reference *ref = NULL;
7924 const char *head_ref_name = NULL;
7925 int ch;
7926 struct tog_view *view;
7927 int *pack_fds = NULL;
7929 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7930 switch (ch) {
7931 case 'c':
7932 commit_id_arg = optarg;
7933 break;
7934 case 'r':
7935 repo_path = realpath(optarg, NULL);
7936 if (repo_path == NULL)
7937 return got_error_from_errno2("realpath",
7938 optarg);
7939 break;
7940 default:
7941 usage_tree();
7942 /* NOTREACHED */
7946 argc -= optind;
7947 argv += optind;
7949 if (argc > 1)
7950 usage_tree();
7952 error = got_repo_pack_fds_open(&pack_fds);
7953 if (error != NULL)
7954 goto done;
7956 if (repo_path == NULL) {
7957 cwd = getcwd(NULL, 0);
7958 if (cwd == NULL)
7959 return got_error_from_errno("getcwd");
7960 error = got_worktree_open(&worktree, cwd);
7961 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7962 goto done;
7963 if (worktree)
7964 repo_path =
7965 strdup(got_worktree_get_repo_path(worktree));
7966 else
7967 repo_path = strdup(cwd);
7968 if (repo_path == NULL) {
7969 error = got_error_from_errno("strdup");
7970 goto done;
7974 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7975 if (error != NULL)
7976 goto done;
7978 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7979 repo, worktree);
7980 if (error)
7981 goto done;
7983 init_curses();
7985 error = apply_unveil(got_repo_get_path(repo), NULL);
7986 if (error)
7987 goto done;
7989 error = tog_load_refs(repo, 0);
7990 if (error)
7991 goto done;
7993 if (commit_id_arg == NULL) {
7994 error = got_repo_match_object_id(&commit_id, &label,
7995 worktree ? got_worktree_get_head_ref_name(worktree) :
7996 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7997 if (error)
7998 goto done;
7999 head_ref_name = label;
8000 } else {
8001 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8002 if (error == NULL)
8003 head_ref_name = got_ref_get_name(ref);
8004 else if (error->code != GOT_ERR_NOT_REF)
8005 goto done;
8006 error = got_repo_match_object_id(&commit_id, NULL,
8007 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8008 if (error)
8009 goto done;
8012 error = got_object_open_as_commit(&commit, repo, commit_id);
8013 if (error)
8014 goto done;
8016 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8017 if (view == NULL) {
8018 error = got_error_from_errno("view_open");
8019 goto done;
8021 error = open_tree_view(view, commit_id, head_ref_name, repo);
8022 if (error)
8023 goto done;
8024 if (!got_path_is_root_dir(in_repo_path)) {
8025 error = tree_view_walk_path(&view->state.tree, commit,
8026 in_repo_path);
8027 if (error)
8028 goto done;
8031 if (worktree) {
8032 /* Release work tree lock. */
8033 got_worktree_close(worktree);
8034 worktree = NULL;
8036 error = view_loop(view);
8037 done:
8038 free(repo_path);
8039 free(cwd);
8040 free(commit_id);
8041 free(label);
8042 if (ref)
8043 got_ref_close(ref);
8044 if (repo) {
8045 const struct got_error *close_err = got_repo_close(repo);
8046 if (error == NULL)
8047 error = close_err;
8049 if (pack_fds) {
8050 const struct got_error *pack_err =
8051 got_repo_pack_fds_close(pack_fds);
8052 if (error == NULL)
8053 error = pack_err;
8055 tog_free_refs();
8056 return error;
8059 static const struct got_error *
8060 ref_view_load_refs(struct tog_ref_view_state *s)
8062 struct got_reflist_entry *sre;
8063 struct tog_reflist_entry *re;
8065 s->nrefs = 0;
8066 TAILQ_FOREACH(sre, &tog_refs, entry) {
8067 if (strncmp(got_ref_get_name(sre->ref),
8068 "refs/got/", 9) == 0 &&
8069 strncmp(got_ref_get_name(sre->ref),
8070 "refs/got/backup/", 16) != 0)
8071 continue;
8073 re = malloc(sizeof(*re));
8074 if (re == NULL)
8075 return got_error_from_errno("malloc");
8077 re->ref = got_ref_dup(sre->ref);
8078 if (re->ref == NULL)
8079 return got_error_from_errno("got_ref_dup");
8080 re->idx = s->nrefs++;
8081 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8084 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8085 return NULL;
8088 static void
8089 ref_view_free_refs(struct tog_ref_view_state *s)
8091 struct tog_reflist_entry *re;
8093 while (!TAILQ_EMPTY(&s->refs)) {
8094 re = TAILQ_FIRST(&s->refs);
8095 TAILQ_REMOVE(&s->refs, re, entry);
8096 got_ref_close(re->ref);
8097 free(re);
8101 static const struct got_error *
8102 open_ref_view(struct tog_view *view, struct got_repository *repo)
8104 const struct got_error *err = NULL;
8105 struct tog_ref_view_state *s = &view->state.ref;
8107 s->selected_entry = 0;
8108 s->repo = repo;
8110 TAILQ_INIT(&s->refs);
8111 STAILQ_INIT(&s->colors);
8113 err = ref_view_load_refs(s);
8114 if (err)
8115 goto done;
8117 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8118 err = add_color(&s->colors, "^refs/heads/",
8119 TOG_COLOR_REFS_HEADS,
8120 get_color_value("TOG_COLOR_REFS_HEADS"));
8121 if (err)
8122 goto done;
8124 err = add_color(&s->colors, "^refs/tags/",
8125 TOG_COLOR_REFS_TAGS,
8126 get_color_value("TOG_COLOR_REFS_TAGS"));
8127 if (err)
8128 goto done;
8130 err = add_color(&s->colors, "^refs/remotes/",
8131 TOG_COLOR_REFS_REMOTES,
8132 get_color_value("TOG_COLOR_REFS_REMOTES"));
8133 if (err)
8134 goto done;
8136 err = add_color(&s->colors, "^refs/got/backup/",
8137 TOG_COLOR_REFS_BACKUP,
8138 get_color_value("TOG_COLOR_REFS_BACKUP"));
8139 if (err)
8140 goto done;
8143 view->show = show_ref_view;
8144 view->input = input_ref_view;
8145 view->close = close_ref_view;
8146 view->search_start = search_start_ref_view;
8147 view->search_next = search_next_ref_view;
8148 done:
8149 if (err) {
8150 if (view->close == NULL)
8151 close_ref_view(view);
8152 view_close(view);
8154 return err;
8157 static const struct got_error *
8158 close_ref_view(struct tog_view *view)
8160 struct tog_ref_view_state *s = &view->state.ref;
8162 ref_view_free_refs(s);
8163 free_colors(&s->colors);
8165 return NULL;
8168 static const struct got_error *
8169 resolve_reflist_entry(struct got_object_id **commit_id,
8170 struct tog_reflist_entry *re, struct got_repository *repo)
8172 const struct got_error *err = NULL;
8173 struct got_object_id *obj_id;
8174 struct got_tag_object *tag = NULL;
8175 int obj_type;
8177 *commit_id = NULL;
8179 err = got_ref_resolve(&obj_id, repo, re->ref);
8180 if (err)
8181 return err;
8183 err = got_object_get_type(&obj_type, repo, obj_id);
8184 if (err)
8185 goto done;
8187 switch (obj_type) {
8188 case GOT_OBJ_TYPE_COMMIT:
8189 *commit_id = obj_id;
8190 break;
8191 case GOT_OBJ_TYPE_TAG:
8192 err = got_object_open_as_tag(&tag, repo, obj_id);
8193 if (err)
8194 goto done;
8195 free(obj_id);
8196 err = got_object_get_type(&obj_type, repo,
8197 got_object_tag_get_object_id(tag));
8198 if (err)
8199 goto done;
8200 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8201 err = got_error(GOT_ERR_OBJ_TYPE);
8202 goto done;
8204 *commit_id = got_object_id_dup(
8205 got_object_tag_get_object_id(tag));
8206 if (*commit_id == NULL) {
8207 err = got_error_from_errno("got_object_id_dup");
8208 goto done;
8210 break;
8211 default:
8212 err = got_error(GOT_ERR_OBJ_TYPE);
8213 break;
8216 done:
8217 if (tag)
8218 got_object_tag_close(tag);
8219 if (err) {
8220 free(*commit_id);
8221 *commit_id = NULL;
8223 return err;
8226 static const struct got_error *
8227 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8228 struct tog_reflist_entry *re, struct got_repository *repo)
8230 struct tog_view *log_view;
8231 const struct got_error *err = NULL;
8232 struct got_object_id *commit_id = NULL;
8234 *new_view = NULL;
8236 err = resolve_reflist_entry(&commit_id, re, repo);
8237 if (err) {
8238 if (err->code != GOT_ERR_OBJ_TYPE)
8239 return err;
8240 else
8241 return NULL;
8244 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8245 if (log_view == NULL) {
8246 err = got_error_from_errno("view_open");
8247 goto done;
8250 err = open_log_view(log_view, commit_id, repo,
8251 got_ref_get_name(re->ref), "", 0);
8252 done:
8253 if (err)
8254 view_close(log_view);
8255 else
8256 *new_view = log_view;
8257 free(commit_id);
8258 return err;
8261 static void
8262 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8264 struct tog_reflist_entry *re;
8265 int i = 0;
8267 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8268 return;
8270 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8271 while (i++ < maxscroll) {
8272 if (re == NULL)
8273 break;
8274 s->first_displayed_entry = re;
8275 re = TAILQ_PREV(re, tog_reflist_head, entry);
8279 static const struct got_error *
8280 ref_scroll_down(struct tog_view *view, int maxscroll)
8282 struct tog_ref_view_state *s = &view->state.ref;
8283 struct tog_reflist_entry *next, *last;
8284 int n = 0;
8286 if (s->first_displayed_entry)
8287 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8288 else
8289 next = TAILQ_FIRST(&s->refs);
8291 last = s->last_displayed_entry;
8292 while (next && n++ < maxscroll) {
8293 if (last) {
8294 s->last_displayed_entry = last;
8295 last = TAILQ_NEXT(last, entry);
8297 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8298 s->first_displayed_entry = next;
8299 next = TAILQ_NEXT(next, entry);
8303 return NULL;
8306 static const struct got_error *
8307 search_start_ref_view(struct tog_view *view)
8309 struct tog_ref_view_state *s = &view->state.ref;
8311 s->matched_entry = NULL;
8312 return NULL;
8315 static int
8316 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8318 regmatch_t regmatch;
8320 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8321 0) == 0;
8324 static const struct got_error *
8325 search_next_ref_view(struct tog_view *view)
8327 struct tog_ref_view_state *s = &view->state.ref;
8328 struct tog_reflist_entry *re = NULL;
8330 if (!view->searching) {
8331 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8332 return NULL;
8335 if (s->matched_entry) {
8336 if (view->searching == TOG_SEARCH_FORWARD) {
8337 if (s->selected_entry)
8338 re = TAILQ_NEXT(s->selected_entry, entry);
8339 else
8340 re = TAILQ_PREV(s->selected_entry,
8341 tog_reflist_head, entry);
8342 } else {
8343 if (s->selected_entry == NULL)
8344 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8345 else
8346 re = TAILQ_PREV(s->selected_entry,
8347 tog_reflist_head, entry);
8349 } else {
8350 if (s->selected_entry)
8351 re = s->selected_entry;
8352 else if (view->searching == TOG_SEARCH_FORWARD)
8353 re = TAILQ_FIRST(&s->refs);
8354 else
8355 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8358 while (1) {
8359 if (re == NULL) {
8360 if (s->matched_entry == NULL) {
8361 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8362 return NULL;
8364 if (view->searching == TOG_SEARCH_FORWARD)
8365 re = TAILQ_FIRST(&s->refs);
8366 else
8367 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8370 if (match_reflist_entry(re, &view->regex)) {
8371 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8372 s->matched_entry = re;
8373 break;
8376 if (view->searching == TOG_SEARCH_FORWARD)
8377 re = TAILQ_NEXT(re, entry);
8378 else
8379 re = TAILQ_PREV(re, tog_reflist_head, entry);
8382 if (s->matched_entry) {
8383 s->first_displayed_entry = s->matched_entry;
8384 s->selected = 0;
8387 return NULL;
8390 static const struct got_error *
8391 show_ref_view(struct tog_view *view)
8393 const struct got_error *err = NULL;
8394 struct tog_ref_view_state *s = &view->state.ref;
8395 struct tog_reflist_entry *re;
8396 char *line = NULL;
8397 wchar_t *wline;
8398 struct tog_color *tc;
8399 int width, n, scrollx;
8400 int limit = view->nlines;
8402 werase(view->window);
8404 s->ndisplayed = 0;
8405 if (view_is_hsplit_top(view))
8406 --limit; /* border */
8408 if (limit == 0)
8409 return NULL;
8411 re = s->first_displayed_entry;
8413 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8414 s->nrefs) == -1)
8415 return got_error_from_errno("asprintf");
8417 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8418 if (err) {
8419 free(line);
8420 return err;
8422 if (view_needs_focus_indication(view))
8423 wstandout(view->window);
8424 waddwstr(view->window, wline);
8425 while (width++ < view->ncols)
8426 waddch(view->window, ' ');
8427 if (view_needs_focus_indication(view))
8428 wstandend(view->window);
8429 free(wline);
8430 wline = NULL;
8431 free(line);
8432 line = NULL;
8433 if (--limit <= 0)
8434 return NULL;
8436 n = 0;
8437 view->maxx = 0;
8438 while (re && limit > 0) {
8439 char *line = NULL;
8440 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8442 if (s->show_date) {
8443 struct got_commit_object *ci;
8444 struct got_tag_object *tag;
8445 struct got_object_id *id;
8446 struct tm tm;
8447 time_t t;
8449 err = got_ref_resolve(&id, s->repo, re->ref);
8450 if (err)
8451 return err;
8452 err = got_object_open_as_tag(&tag, s->repo, id);
8453 if (err) {
8454 if (err->code != GOT_ERR_OBJ_TYPE) {
8455 free(id);
8456 return err;
8458 err = got_object_open_as_commit(&ci, s->repo,
8459 id);
8460 if (err) {
8461 free(id);
8462 return err;
8464 t = got_object_commit_get_committer_time(ci);
8465 got_object_commit_close(ci);
8466 } else {
8467 t = got_object_tag_get_tagger_time(tag);
8468 got_object_tag_close(tag);
8470 free(id);
8471 if (gmtime_r(&t, &tm) == NULL)
8472 return got_error_from_errno("gmtime_r");
8473 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8474 return got_error(GOT_ERR_NO_SPACE);
8476 if (got_ref_is_symbolic(re->ref)) {
8477 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8478 ymd : "", got_ref_get_name(re->ref),
8479 got_ref_get_symref_target(re->ref)) == -1)
8480 return got_error_from_errno("asprintf");
8481 } else if (s->show_ids) {
8482 struct got_object_id *id;
8483 char *id_str;
8484 err = got_ref_resolve(&id, s->repo, re->ref);
8485 if (err)
8486 return err;
8487 err = got_object_id_str(&id_str, id);
8488 if (err) {
8489 free(id);
8490 return err;
8492 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8493 got_ref_get_name(re->ref), id_str) == -1) {
8494 err = got_error_from_errno("asprintf");
8495 free(id);
8496 free(id_str);
8497 return err;
8499 free(id);
8500 free(id_str);
8501 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8502 got_ref_get_name(re->ref)) == -1)
8503 return got_error_from_errno("asprintf");
8505 /* use full line width to determine view->maxx */
8506 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8507 if (err) {
8508 free(line);
8509 return err;
8511 view->maxx = MAX(view->maxx, width);
8512 free(wline);
8513 wline = NULL;
8515 err = format_line(&wline, &width, &scrollx, line, view->x,
8516 view->ncols, 0, 0);
8517 if (err) {
8518 free(line);
8519 return err;
8521 if (n == s->selected) {
8522 if (view->focussed)
8523 wstandout(view->window);
8524 s->selected_entry = re;
8526 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8527 if (tc)
8528 wattr_on(view->window,
8529 COLOR_PAIR(tc->colorpair), NULL);
8530 waddwstr(view->window, &wline[scrollx]);
8531 if (tc)
8532 wattr_off(view->window,
8533 COLOR_PAIR(tc->colorpair), NULL);
8534 if (width < view->ncols)
8535 waddch(view->window, '\n');
8536 if (n == s->selected && view->focussed)
8537 wstandend(view->window);
8538 free(line);
8539 free(wline);
8540 wline = NULL;
8541 n++;
8542 s->ndisplayed++;
8543 s->last_displayed_entry = re;
8545 limit--;
8546 re = TAILQ_NEXT(re, entry);
8549 view_border(view);
8550 return err;
8553 static const struct got_error *
8554 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8555 struct tog_reflist_entry *re, struct got_repository *repo)
8557 const struct got_error *err = NULL;
8558 struct got_object_id *commit_id = NULL;
8559 struct tog_view *tree_view;
8561 *new_view = NULL;
8563 err = resolve_reflist_entry(&commit_id, re, repo);
8564 if (err) {
8565 if (err->code != GOT_ERR_OBJ_TYPE)
8566 return err;
8567 else
8568 return NULL;
8572 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8573 if (tree_view == NULL) {
8574 err = got_error_from_errno("view_open");
8575 goto done;
8578 err = open_tree_view(tree_view, commit_id,
8579 got_ref_get_name(re->ref), repo);
8580 if (err)
8581 goto done;
8583 *new_view = tree_view;
8584 done:
8585 free(commit_id);
8586 return err;
8589 static const struct got_error *
8590 ref_goto_line(struct tog_view *view, int nlines)
8592 const struct got_error *err = NULL;
8593 struct tog_ref_view_state *s = &view->state.ref;
8594 int g, idx = s->selected_entry->idx;
8596 g = view->gline;
8597 view->gline = 0;
8599 if (g == 0)
8600 g = 1;
8601 else if (g > s->nrefs)
8602 g = s->nrefs;
8604 if (g >= s->first_displayed_entry->idx + 1 &&
8605 g <= s->last_displayed_entry->idx + 1 &&
8606 g - s->first_displayed_entry->idx - 1 < nlines) {
8607 s->selected = g - s->first_displayed_entry->idx - 1;
8608 return NULL;
8611 if (idx + 1 < g) {
8612 err = ref_scroll_down(view, g - idx - 1);
8613 if (err)
8614 return err;
8615 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8616 s->first_displayed_entry->idx + s->selected < g &&
8617 s->selected < s->ndisplayed - 1)
8618 s->selected = g - s->first_displayed_entry->idx - 1;
8619 } else if (idx + 1 > g)
8620 ref_scroll_up(s, idx - g + 1);
8622 if (g < nlines && s->first_displayed_entry->idx == 0)
8623 s->selected = g - 1;
8625 return NULL;
8629 static const struct got_error *
8630 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8632 const struct got_error *err = NULL;
8633 struct tog_ref_view_state *s = &view->state.ref;
8634 struct tog_reflist_entry *re;
8635 int n, nscroll = view->nlines - 1;
8637 if (view->gline)
8638 return ref_goto_line(view, nscroll);
8640 switch (ch) {
8641 case '0':
8642 case '$':
8643 case KEY_RIGHT:
8644 case 'l':
8645 case KEY_LEFT:
8646 case 'h':
8647 horizontal_scroll_input(view, ch);
8648 break;
8649 case 'i':
8650 s->show_ids = !s->show_ids;
8651 view->count = 0;
8652 break;
8653 case 'm':
8654 s->show_date = !s->show_date;
8655 view->count = 0;
8656 break;
8657 case 'o':
8658 s->sort_by_date = !s->sort_by_date;
8659 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8660 view->count = 0;
8661 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8662 got_ref_cmp_by_commit_timestamp_descending :
8663 tog_ref_cmp_by_name, s->repo);
8664 if (err)
8665 break;
8666 got_reflist_object_id_map_free(tog_refs_idmap);
8667 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8668 &tog_refs, s->repo);
8669 if (err)
8670 break;
8671 ref_view_free_refs(s);
8672 err = ref_view_load_refs(s);
8673 break;
8674 case KEY_ENTER:
8675 case '\r':
8676 view->count = 0;
8677 if (!s->selected_entry)
8678 break;
8679 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8680 break;
8681 case 'T':
8682 view->count = 0;
8683 if (!s->selected_entry)
8684 break;
8685 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8686 break;
8687 case 'g':
8688 case '=':
8689 case KEY_HOME:
8690 s->selected = 0;
8691 view->count = 0;
8692 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8693 break;
8694 case 'G':
8695 case '*':
8696 case KEY_END: {
8697 int eos = view->nlines - 1;
8699 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8700 --eos; /* border */
8701 s->selected = 0;
8702 view->count = 0;
8703 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8704 for (n = 0; n < eos; n++) {
8705 if (re == NULL)
8706 break;
8707 s->first_displayed_entry = re;
8708 re = TAILQ_PREV(re, tog_reflist_head, entry);
8710 if (n > 0)
8711 s->selected = n - 1;
8712 break;
8714 case 'k':
8715 case KEY_UP:
8716 case CTRL('p'):
8717 if (s->selected > 0) {
8718 s->selected--;
8719 break;
8721 ref_scroll_up(s, 1);
8722 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8723 view->count = 0;
8724 break;
8725 case CTRL('u'):
8726 case 'u':
8727 nscroll /= 2;
8728 /* FALL THROUGH */
8729 case KEY_PPAGE:
8730 case CTRL('b'):
8731 case 'b':
8732 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8733 s->selected -= MIN(nscroll, s->selected);
8734 ref_scroll_up(s, MAX(0, nscroll));
8735 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8736 view->count = 0;
8737 break;
8738 case 'j':
8739 case KEY_DOWN:
8740 case CTRL('n'):
8741 if (s->selected < s->ndisplayed - 1) {
8742 s->selected++;
8743 break;
8745 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8746 /* can't scroll any further */
8747 view->count = 0;
8748 break;
8750 ref_scroll_down(view, 1);
8751 break;
8752 case CTRL('d'):
8753 case 'd':
8754 nscroll /= 2;
8755 /* FALL THROUGH */
8756 case KEY_NPAGE:
8757 case CTRL('f'):
8758 case 'f':
8759 case ' ':
8760 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8761 /* can't scroll any further; move cursor down */
8762 if (s->selected < s->ndisplayed - 1)
8763 s->selected += MIN(nscroll,
8764 s->ndisplayed - s->selected - 1);
8765 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8766 s->selected += s->ndisplayed - s->selected - 1;
8767 view->count = 0;
8768 break;
8770 ref_scroll_down(view, nscroll);
8771 break;
8772 case CTRL('l'):
8773 view->count = 0;
8774 tog_free_refs();
8775 err = tog_load_refs(s->repo, s->sort_by_date);
8776 if (err)
8777 break;
8778 ref_view_free_refs(s);
8779 err = ref_view_load_refs(s);
8780 break;
8781 case KEY_RESIZE:
8782 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8783 s->selected = view->nlines - 2;
8784 break;
8785 default:
8786 view->count = 0;
8787 break;
8790 return err;
8793 __dead static void
8794 usage_ref(void)
8796 endwin();
8797 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8798 getprogname());
8799 exit(1);
8802 static const struct got_error *
8803 cmd_ref(int argc, char *argv[])
8805 const struct got_error *error;
8806 struct got_repository *repo = NULL;
8807 struct got_worktree *worktree = NULL;
8808 char *cwd = NULL, *repo_path = NULL;
8809 int ch;
8810 struct tog_view *view;
8811 int *pack_fds = NULL;
8813 while ((ch = getopt(argc, argv, "r:")) != -1) {
8814 switch (ch) {
8815 case 'r':
8816 repo_path = realpath(optarg, NULL);
8817 if (repo_path == NULL)
8818 return got_error_from_errno2("realpath",
8819 optarg);
8820 break;
8821 default:
8822 usage_ref();
8823 /* NOTREACHED */
8827 argc -= optind;
8828 argv += optind;
8830 if (argc > 1)
8831 usage_ref();
8833 error = got_repo_pack_fds_open(&pack_fds);
8834 if (error != NULL)
8835 goto done;
8837 if (repo_path == NULL) {
8838 cwd = getcwd(NULL, 0);
8839 if (cwd == NULL)
8840 return got_error_from_errno("getcwd");
8841 error = got_worktree_open(&worktree, cwd);
8842 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8843 goto done;
8844 if (worktree)
8845 repo_path =
8846 strdup(got_worktree_get_repo_path(worktree));
8847 else
8848 repo_path = strdup(cwd);
8849 if (repo_path == NULL) {
8850 error = got_error_from_errno("strdup");
8851 goto done;
8855 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8856 if (error != NULL)
8857 goto done;
8859 init_curses();
8861 error = apply_unveil(got_repo_get_path(repo), NULL);
8862 if (error)
8863 goto done;
8865 error = tog_load_refs(repo, 0);
8866 if (error)
8867 goto done;
8869 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8870 if (view == NULL) {
8871 error = got_error_from_errno("view_open");
8872 goto done;
8875 error = open_ref_view(view, repo);
8876 if (error)
8877 goto done;
8879 if (worktree) {
8880 /* Release work tree lock. */
8881 got_worktree_close(worktree);
8882 worktree = NULL;
8884 error = view_loop(view);
8885 done:
8886 free(repo_path);
8887 free(cwd);
8888 if (repo) {
8889 const struct got_error *close_err = got_repo_close(repo);
8890 if (close_err)
8891 error = close_err;
8893 if (pack_fds) {
8894 const struct got_error *pack_err =
8895 got_repo_pack_fds_close(pack_fds);
8896 if (error == NULL)
8897 error = pack_err;
8899 tog_free_refs();
8900 return error;
8903 static const struct got_error*
8904 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8905 const char *str)
8907 size_t len;
8909 if (win == NULL)
8910 win = stdscr;
8912 len = strlen(str);
8913 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8915 if (focus)
8916 wstandout(win);
8917 if (mvwprintw(win, y, x, "%s", str) == ERR)
8918 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8919 if (focus)
8920 wstandend(win);
8922 return NULL;
8925 static const struct got_error *
8926 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8928 off_t *p;
8930 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8931 if (p == NULL) {
8932 free(*line_offsets);
8933 *line_offsets = NULL;
8934 return got_error_from_errno("reallocarray");
8937 *line_offsets = p;
8938 (*line_offsets)[*nlines] = off;
8939 ++(*nlines);
8940 return NULL;
8943 static const struct got_error *
8944 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8946 *ret = 0;
8948 for (;n > 0; --n, ++km) {
8949 char *t0, *t, *k;
8950 size_t len = 1;
8952 if (km->keys == NULL)
8953 continue;
8955 t = t0 = strdup(km->keys);
8956 if (t0 == NULL)
8957 return got_error_from_errno("strdup");
8959 len += strlen(t);
8960 while ((k = strsep(&t, " ")) != NULL)
8961 len += strlen(k) > 1 ? 2 : 0;
8962 free(t0);
8963 *ret = MAX(*ret, len);
8966 return NULL;
8970 * Write keymap section headers, keys, and key info in km to f.
8971 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8972 * wrap control and symbolic keys in guillemets, else use <>.
8974 static const struct got_error *
8975 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8977 int n, len = width;
8979 if (km->keys) {
8980 static const char *u8_glyph[] = {
8981 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8982 "\xe2\x80\xba" /* U+203A (utf8 >) */
8984 char *t0, *t, *k;
8985 int cs, s, first = 1;
8987 cs = got_locale_is_utf8();
8989 t = t0 = strdup(km->keys);
8990 if (t0 == NULL)
8991 return got_error_from_errno("strdup");
8993 len = strlen(km->keys);
8994 while ((k = strsep(&t, " ")) != NULL) {
8995 s = strlen(k) > 1; /* control or symbolic key */
8996 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8997 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8998 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8999 if (n < 0) {
9000 free(t0);
9001 return got_error_from_errno("fprintf");
9003 first = 0;
9004 len += s ? 2 : 0;
9005 *off += n;
9007 free(t0);
9009 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9010 if (n < 0)
9011 return got_error_from_errno("fprintf");
9012 *off += n;
9014 return NULL;
9017 static const struct got_error *
9018 format_help(struct tog_help_view_state *s)
9020 const struct got_error *err = NULL;
9021 off_t off = 0;
9022 int i, max, n, show = s->all;
9023 static const struct tog_key_map km[] = {
9024 #define KEYMAP_(info, type) { NULL, (info), type }
9025 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9026 GENERATE_HELP
9027 #undef KEYMAP_
9028 #undef KEY_
9031 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9032 if (err)
9033 return err;
9035 n = nitems(km);
9036 err = max_key_str(&max, km, n);
9037 if (err)
9038 return err;
9040 for (i = 0; i < n; ++i) {
9041 if (km[i].keys == NULL) {
9042 show = s->all;
9043 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9044 km[i].type == s->type || s->all)
9045 show = 1;
9047 if (show) {
9048 err = format_help_line(&off, s->f, &km[i], max);
9049 if (err)
9050 return err;
9051 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9052 if (err)
9053 return err;
9056 fputc('\n', s->f);
9057 ++off;
9058 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9059 return err;
9062 static const struct got_error *
9063 create_help(struct tog_help_view_state *s)
9065 FILE *f;
9066 const struct got_error *err;
9068 free(s->line_offsets);
9069 s->line_offsets = NULL;
9070 s->nlines = 0;
9072 f = got_opentemp();
9073 if (f == NULL)
9074 return got_error_from_errno("got_opentemp");
9075 s->f = f;
9077 err = format_help(s);
9078 if (err)
9079 return err;
9081 if (s->f && fflush(s->f) != 0)
9082 return got_error_from_errno("fflush");
9084 return NULL;
9087 static const struct got_error *
9088 search_start_help_view(struct tog_view *view)
9090 view->state.help.matched_line = 0;
9091 return NULL;
9094 static void
9095 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9096 size_t *nlines, int **first, int **last, int **match, int **selected)
9098 struct tog_help_view_state *s = &view->state.help;
9100 *f = s->f;
9101 *nlines = s->nlines;
9102 *line_offsets = s->line_offsets;
9103 *match = &s->matched_line;
9104 *first = &s->first_displayed_line;
9105 *last = &s->last_displayed_line;
9106 *selected = &s->selected_line;
9109 static const struct got_error *
9110 show_help_view(struct tog_view *view)
9112 struct tog_help_view_state *s = &view->state.help;
9113 const struct got_error *err;
9114 regmatch_t *regmatch = &view->regmatch;
9115 wchar_t *wline;
9116 char *line;
9117 ssize_t linelen;
9118 size_t linesz = 0;
9119 int width, nprinted = 0, rc = 0;
9120 int eos = view->nlines;
9122 if (view_is_hsplit_top(view))
9123 --eos; /* account for border */
9125 s->lineno = 0;
9126 rewind(s->f);
9127 werase(view->window);
9129 if (view->gline > s->nlines - 1)
9130 view->gline = s->nlines - 1;
9132 err = win_draw_center(view->window, 0, 0, view->ncols,
9133 view_needs_focus_indication(view),
9134 "tog help (press q to return to tog)");
9135 if (err)
9136 return err;
9137 if (eos <= 1)
9138 return NULL;
9139 waddstr(view->window, "\n\n");
9140 eos -= 2;
9142 s->eof = 0;
9143 view->maxx = 0;
9144 line = NULL;
9145 while (eos > 0 && nprinted < eos) {
9146 attr_t attr = 0;
9148 linelen = getline(&line, &linesz, s->f);
9149 if (linelen == -1) {
9150 if (!feof(s->f)) {
9151 free(line);
9152 return got_ferror(s->f, GOT_ERR_IO);
9154 s->eof = 1;
9155 break;
9157 if (++s->lineno < s->first_displayed_line)
9158 continue;
9159 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9160 continue;
9161 if (s->lineno == view->hiline)
9162 attr = A_STANDOUT;
9164 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9165 view->x ? 1 : 0);
9166 if (err) {
9167 free(line);
9168 return err;
9170 view->maxx = MAX(view->maxx, width);
9171 free(wline);
9172 wline = NULL;
9174 if (attr)
9175 wattron(view->window, attr);
9176 if (s->first_displayed_line + nprinted == s->matched_line &&
9177 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9178 err = add_matched_line(&width, line, view->ncols - 1, 0,
9179 view->window, view->x, regmatch);
9180 if (err) {
9181 free(line);
9182 return err;
9184 } else {
9185 int skip;
9187 err = format_line(&wline, &width, &skip, line,
9188 view->x, view->ncols, 0, view->x ? 1 : 0);
9189 if (err) {
9190 free(line);
9191 return err;
9193 waddwstr(view->window, &wline[skip]);
9194 free(wline);
9195 wline = NULL;
9197 if (s->lineno == view->hiline) {
9198 while (width++ < view->ncols)
9199 waddch(view->window, ' ');
9200 } else {
9201 if (width < view->ncols)
9202 waddch(view->window, '\n');
9204 if (attr)
9205 wattroff(view->window, attr);
9206 if (++nprinted == 1)
9207 s->first_displayed_line = s->lineno;
9209 free(line);
9210 if (nprinted > 0)
9211 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9212 else
9213 s->last_displayed_line = s->first_displayed_line;
9215 view_border(view);
9217 if (s->eof) {
9218 rc = waddnstr(view->window,
9219 "See the tog(1) manual page for full documentation",
9220 view->ncols - 1);
9221 if (rc == ERR)
9222 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9223 } else {
9224 wmove(view->window, view->nlines - 1, 0);
9225 wclrtoeol(view->window);
9226 wstandout(view->window);
9227 rc = waddnstr(view->window, "scroll down for more...",
9228 view->ncols - 1);
9229 if (rc == ERR)
9230 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9231 if (getcurx(view->window) < view->ncols - 6) {
9232 rc = wprintw(view->window, "[%.0f%%]",
9233 100.00 * s->last_displayed_line / s->nlines);
9234 if (rc == ERR)
9235 return got_error_msg(GOT_ERR_IO, "wprintw");
9237 wstandend(view->window);
9240 return NULL;
9243 static const struct got_error *
9244 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9246 struct tog_help_view_state *s = &view->state.help;
9247 const struct got_error *err = NULL;
9248 char *line = NULL;
9249 ssize_t linelen;
9250 size_t linesz = 0;
9251 int eos, nscroll;
9253 eos = nscroll = view->nlines;
9254 if (view_is_hsplit_top(view))
9255 --eos; /* border */
9257 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9259 switch (ch) {
9260 case '0':
9261 case '$':
9262 case KEY_RIGHT:
9263 case 'l':
9264 case KEY_LEFT:
9265 case 'h':
9266 horizontal_scroll_input(view, ch);
9267 break;
9268 case 'g':
9269 case KEY_HOME:
9270 s->first_displayed_line = 1;
9271 view->count = 0;
9272 break;
9273 case 'G':
9274 case KEY_END:
9275 view->count = 0;
9276 if (s->eof)
9277 break;
9278 s->first_displayed_line = (s->nlines - eos) + 3;
9279 s->eof = 1;
9280 break;
9281 case 'k':
9282 case KEY_UP:
9283 if (s->first_displayed_line > 1)
9284 --s->first_displayed_line;
9285 else
9286 view->count = 0;
9287 break;
9288 case CTRL('u'):
9289 case 'u':
9290 nscroll /= 2;
9291 /* FALL THROUGH */
9292 case KEY_PPAGE:
9293 case CTRL('b'):
9294 case 'b':
9295 if (s->first_displayed_line == 1) {
9296 view->count = 0;
9297 break;
9299 while (--nscroll > 0 && s->first_displayed_line > 1)
9300 s->first_displayed_line--;
9301 break;
9302 case 'j':
9303 case KEY_DOWN:
9304 case CTRL('n'):
9305 if (!s->eof)
9306 ++s->first_displayed_line;
9307 else
9308 view->count = 0;
9309 break;
9310 case CTRL('d'):
9311 case 'd':
9312 nscroll /= 2;
9313 /* FALL THROUGH */
9314 case KEY_NPAGE:
9315 case CTRL('f'):
9316 case 'f':
9317 case ' ':
9318 if (s->eof) {
9319 view->count = 0;
9320 break;
9322 while (!s->eof && --nscroll > 0) {
9323 linelen = getline(&line, &linesz, s->f);
9324 s->first_displayed_line++;
9325 if (linelen == -1) {
9326 if (feof(s->f))
9327 s->eof = 1;
9328 else
9329 err = got_ferror(s->f, GOT_ERR_IO);
9330 break;
9333 free(line);
9334 break;
9335 default:
9336 view->count = 0;
9337 break;
9340 return err;
9343 static const struct got_error *
9344 close_help_view(struct tog_view *view)
9346 struct tog_help_view_state *s = &view->state.help;
9348 free(s->line_offsets);
9349 s->line_offsets = NULL;
9350 if (fclose(s->f) == EOF)
9351 return got_error_from_errno("fclose");
9353 return NULL;
9356 static const struct got_error *
9357 reset_help_view(struct tog_view *view)
9359 struct tog_help_view_state *s = &view->state.help;
9362 if (s->f && fclose(s->f) == EOF)
9363 return got_error_from_errno("fclose");
9365 wclear(view->window);
9366 view->count = 0;
9367 view->x = 0;
9368 s->all = !s->all;
9369 s->first_displayed_line = 1;
9370 s->last_displayed_line = view->nlines;
9371 s->matched_line = 0;
9373 return create_help(s);
9376 static const struct got_error *
9377 open_help_view(struct tog_view *view, struct tog_view *parent)
9379 const struct got_error *err = NULL;
9380 struct tog_help_view_state *s = &view->state.help;
9382 s->type = (enum tog_keymap_type)parent->type;
9383 s->first_displayed_line = 1;
9384 s->last_displayed_line = view->nlines;
9385 s->selected_line = 1;
9387 view->show = show_help_view;
9388 view->input = input_help_view;
9389 view->reset = reset_help_view;
9390 view->close = close_help_view;
9391 view->search_start = search_start_help_view;
9392 view->search_setup = search_setup_help_view;
9393 view->search_next = search_next_view_match;
9395 err = create_help(s);
9396 return err;
9399 static const struct got_error *
9400 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9401 enum tog_view_type request, int y, int x)
9403 const struct got_error *err = NULL;
9405 *new_view = NULL;
9407 switch (request) {
9408 case TOG_VIEW_DIFF:
9409 if (view->type == TOG_VIEW_LOG) {
9410 struct tog_log_view_state *s = &view->state.log;
9412 err = open_diff_view_for_commit(new_view, y, x,
9413 s->selected_entry->commit, s->selected_entry->id,
9414 view, s->repo);
9415 } else
9416 return got_error_msg(GOT_ERR_NOT_IMPL,
9417 "parent/child view pair not supported");
9418 break;
9419 case TOG_VIEW_BLAME:
9420 if (view->type == TOG_VIEW_TREE) {
9421 struct tog_tree_view_state *s = &view->state.tree;
9423 err = blame_tree_entry(new_view, y, x,
9424 s->selected_entry, &s->parents, s->commit_id,
9425 s->repo);
9426 } else
9427 return got_error_msg(GOT_ERR_NOT_IMPL,
9428 "parent/child view pair not supported");
9429 break;
9430 case TOG_VIEW_LOG:
9431 if (view->type == TOG_VIEW_BLAME)
9432 err = log_annotated_line(new_view, y, x,
9433 view->state.blame.repo, view->state.blame.id_to_log);
9434 else if (view->type == TOG_VIEW_TREE)
9435 err = log_selected_tree_entry(new_view, y, x,
9436 &view->state.tree);
9437 else if (view->type == TOG_VIEW_REF)
9438 err = log_ref_entry(new_view, y, x,
9439 view->state.ref.selected_entry,
9440 view->state.ref.repo);
9441 else
9442 return got_error_msg(GOT_ERR_NOT_IMPL,
9443 "parent/child view pair not supported");
9444 break;
9445 case TOG_VIEW_TREE:
9446 if (view->type == TOG_VIEW_LOG)
9447 err = browse_commit_tree(new_view, y, x,
9448 view->state.log.selected_entry,
9449 view->state.log.in_repo_path,
9450 view->state.log.head_ref_name,
9451 view->state.log.repo);
9452 else if (view->type == TOG_VIEW_REF)
9453 err = browse_ref_tree(new_view, y, x,
9454 view->state.ref.selected_entry,
9455 view->state.ref.repo);
9456 else
9457 return got_error_msg(GOT_ERR_NOT_IMPL,
9458 "parent/child view pair not supported");
9459 break;
9460 case TOG_VIEW_REF:
9461 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9462 if (*new_view == NULL)
9463 return got_error_from_errno("view_open");
9464 if (view->type == TOG_VIEW_LOG)
9465 err = open_ref_view(*new_view, view->state.log.repo);
9466 else if (view->type == TOG_VIEW_TREE)
9467 err = open_ref_view(*new_view, view->state.tree.repo);
9468 else
9469 err = got_error_msg(GOT_ERR_NOT_IMPL,
9470 "parent/child view pair not supported");
9471 if (err)
9472 view_close(*new_view);
9473 break;
9474 case TOG_VIEW_HELP:
9475 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9476 if (*new_view == NULL)
9477 return got_error_from_errno("view_open");
9478 err = open_help_view(*new_view, view);
9479 if (err)
9480 view_close(*new_view);
9481 break;
9482 default:
9483 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9486 return err;
9490 * If view was scrolled down to move the selected line into view when opening a
9491 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9493 static void
9494 offset_selection_up(struct tog_view *view)
9496 switch (view->type) {
9497 case TOG_VIEW_BLAME: {
9498 struct tog_blame_view_state *s = &view->state.blame;
9499 if (s->first_displayed_line == 1) {
9500 s->selected_line = MAX(s->selected_line - view->offset,
9501 1);
9502 break;
9504 if (s->first_displayed_line > view->offset)
9505 s->first_displayed_line -= view->offset;
9506 else
9507 s->first_displayed_line = 1;
9508 s->selected_line += view->offset;
9509 break;
9511 case TOG_VIEW_LOG:
9512 log_scroll_up(&view->state.log, view->offset);
9513 view->state.log.selected += view->offset;
9514 break;
9515 case TOG_VIEW_REF:
9516 ref_scroll_up(&view->state.ref, view->offset);
9517 view->state.ref.selected += view->offset;
9518 break;
9519 case TOG_VIEW_TREE:
9520 tree_scroll_up(&view->state.tree, view->offset);
9521 view->state.tree.selected += view->offset;
9522 break;
9523 default:
9524 break;
9527 view->offset = 0;
9531 * If the selected line is in the section of screen covered by the bottom split,
9532 * scroll down offset lines to move it into view and index its new position.
9534 static const struct got_error *
9535 offset_selection_down(struct tog_view *view)
9537 const struct got_error *err = NULL;
9538 const struct got_error *(*scrolld)(struct tog_view *, int);
9539 int *selected = NULL;
9540 int header, offset;
9542 switch (view->type) {
9543 case TOG_VIEW_BLAME: {
9544 struct tog_blame_view_state *s = &view->state.blame;
9545 header = 3;
9546 scrolld = NULL;
9547 if (s->selected_line > view->nlines - header) {
9548 offset = abs(view->nlines - s->selected_line - header);
9549 s->first_displayed_line += offset;
9550 s->selected_line -= offset;
9551 view->offset = offset;
9553 break;
9555 case TOG_VIEW_LOG: {
9556 struct tog_log_view_state *s = &view->state.log;
9557 scrolld = &log_scroll_down;
9558 header = view_is_parent_view(view) ? 3 : 2;
9559 selected = &s->selected;
9560 break;
9562 case TOG_VIEW_REF: {
9563 struct tog_ref_view_state *s = &view->state.ref;
9564 scrolld = &ref_scroll_down;
9565 header = 3;
9566 selected = &s->selected;
9567 break;
9569 case TOG_VIEW_TREE: {
9570 struct tog_tree_view_state *s = &view->state.tree;
9571 scrolld = &tree_scroll_down;
9572 header = 5;
9573 selected = &s->selected;
9574 break;
9576 default:
9577 selected = NULL;
9578 scrolld = NULL;
9579 header = 0;
9580 break;
9583 if (selected && *selected > view->nlines - header) {
9584 offset = abs(view->nlines - *selected - header);
9585 view->offset = offset;
9586 if (scrolld && offset) {
9587 err = scrolld(view, offset);
9588 *selected -= offset;
9592 return err;
9595 static void
9596 list_commands(FILE *fp)
9598 size_t i;
9600 fprintf(fp, "commands:");
9601 for (i = 0; i < nitems(tog_commands); i++) {
9602 const struct tog_cmd *cmd = &tog_commands[i];
9603 fprintf(fp, " %s", cmd->name);
9605 fputc('\n', fp);
9608 __dead static void
9609 usage(int hflag, int status)
9611 FILE *fp = (status == 0) ? stdout : stderr;
9613 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9614 getprogname());
9615 if (hflag) {
9616 fprintf(fp, "lazy usage: %s path\n", getprogname());
9617 list_commands(fp);
9619 exit(status);
9622 static char **
9623 make_argv(int argc, ...)
9625 va_list ap;
9626 char **argv;
9627 int i;
9629 va_start(ap, argc);
9631 argv = calloc(argc, sizeof(char *));
9632 if (argv == NULL)
9633 err(1, "calloc");
9634 for (i = 0; i < argc; i++) {
9635 argv[i] = strdup(va_arg(ap, char *));
9636 if (argv[i] == NULL)
9637 err(1, "strdup");
9640 va_end(ap);
9641 return argv;
9645 * Try to convert 'tog path' into a 'tog log path' command.
9646 * The user could simply have mistyped the command rather than knowingly
9647 * provided a path. So check whether argv[0] can in fact be resolved
9648 * to a path in the HEAD commit and print a special error if not.
9649 * This hack is for mpi@ <3
9651 static const struct got_error *
9652 tog_log_with_path(int argc, char *argv[])
9654 const struct got_error *error = NULL, *close_err;
9655 const struct tog_cmd *cmd = NULL;
9656 struct got_repository *repo = NULL;
9657 struct got_worktree *worktree = NULL;
9658 struct got_object_id *commit_id = NULL, *id = NULL;
9659 struct got_commit_object *commit = NULL;
9660 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9661 char *commit_id_str = NULL, **cmd_argv = NULL;
9662 int *pack_fds = NULL;
9664 cwd = getcwd(NULL, 0);
9665 if (cwd == NULL)
9666 return got_error_from_errno("getcwd");
9668 error = got_repo_pack_fds_open(&pack_fds);
9669 if (error != NULL)
9670 goto done;
9672 error = got_worktree_open(&worktree, cwd);
9673 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9674 goto done;
9676 if (worktree)
9677 repo_path = strdup(got_worktree_get_repo_path(worktree));
9678 else
9679 repo_path = strdup(cwd);
9680 if (repo_path == NULL) {
9681 error = got_error_from_errno("strdup");
9682 goto done;
9685 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9686 if (error != NULL)
9687 goto done;
9689 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9690 repo, worktree);
9691 if (error)
9692 goto done;
9694 error = tog_load_refs(repo, 0);
9695 if (error)
9696 goto done;
9697 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9698 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9699 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9700 if (error)
9701 goto done;
9703 if (worktree) {
9704 got_worktree_close(worktree);
9705 worktree = NULL;
9708 error = got_object_open_as_commit(&commit, repo, commit_id);
9709 if (error)
9710 goto done;
9712 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9713 if (error) {
9714 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9715 goto done;
9716 fprintf(stderr, "%s: '%s' is no known command or path\n",
9717 getprogname(), argv[0]);
9718 usage(1, 1);
9719 /* not reached */
9722 error = got_object_id_str(&commit_id_str, commit_id);
9723 if (error)
9724 goto done;
9726 cmd = &tog_commands[0]; /* log */
9727 argc = 4;
9728 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9729 error = cmd->cmd_main(argc, cmd_argv);
9730 done:
9731 if (repo) {
9732 close_err = got_repo_close(repo);
9733 if (error == NULL)
9734 error = close_err;
9736 if (commit)
9737 got_object_commit_close(commit);
9738 if (worktree)
9739 got_worktree_close(worktree);
9740 if (pack_fds) {
9741 const struct got_error *pack_err =
9742 got_repo_pack_fds_close(pack_fds);
9743 if (error == NULL)
9744 error = pack_err;
9746 free(id);
9747 free(commit_id_str);
9748 free(commit_id);
9749 free(cwd);
9750 free(repo_path);
9751 free(in_repo_path);
9752 if (cmd_argv) {
9753 int i;
9754 for (i = 0; i < argc; i++)
9755 free(cmd_argv[i]);
9756 free(cmd_argv);
9758 tog_free_refs();
9759 return error;
9762 int
9763 main(int argc, char *argv[])
9765 const struct got_error *io_err, *error = NULL;
9766 const struct tog_cmd *cmd = NULL;
9767 int ch, hflag = 0, Vflag = 0;
9768 char **cmd_argv = NULL;
9769 static const struct option longopts[] = {
9770 { "version", no_argument, NULL, 'V' },
9771 { NULL, 0, NULL, 0}
9773 char *diff_algo_str = NULL;
9774 const char *test_script_path;
9776 setlocale(LC_CTYPE, "");
9779 * Test mode init must happen before pledge() because "tty" will
9780 * not allow TTY-related ioctls to occur via regular files.
9782 test_script_path = getenv("TOG_TEST_SCRIPT");
9783 if (test_script_path != NULL) {
9784 error = init_mock_term(test_script_path);
9785 if (error) {
9786 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9787 return 1;
9791 #if !defined(PROFILE)
9792 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9793 NULL) == -1)
9794 err(1, "pledge");
9795 #endif
9797 if (!isatty(STDIN_FILENO))
9798 errx(1, "standard input is not a tty");
9800 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9801 switch (ch) {
9802 case 'h':
9803 hflag = 1;
9804 break;
9805 case 'V':
9806 Vflag = 1;
9807 break;
9808 default:
9809 usage(hflag, 1);
9810 /* NOTREACHED */
9814 argc -= optind;
9815 argv += optind;
9816 optind = 1;
9817 optreset = 1;
9819 if (Vflag) {
9820 got_version_print_str();
9821 return 0;
9824 if (argc == 0) {
9825 if (hflag)
9826 usage(hflag, 0);
9827 /* Build an argument vector which runs a default command. */
9828 cmd = &tog_commands[0];
9829 argc = 1;
9830 cmd_argv = make_argv(argc, cmd->name);
9831 } else {
9832 size_t i;
9834 /* Did the user specify a command? */
9835 for (i = 0; i < nitems(tog_commands); i++) {
9836 if (strncmp(tog_commands[i].name, argv[0],
9837 strlen(argv[0])) == 0) {
9838 cmd = &tog_commands[i];
9839 break;
9844 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9845 if (diff_algo_str) {
9846 if (strcasecmp(diff_algo_str, "patience") == 0)
9847 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9848 if (strcasecmp(diff_algo_str, "myers") == 0)
9849 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9852 if (cmd == NULL) {
9853 if (argc != 1)
9854 usage(0, 1);
9855 /* No command specified; try log with a path */
9856 error = tog_log_with_path(argc, argv);
9857 } else {
9858 if (hflag)
9859 cmd->cmd_usage();
9860 else
9861 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9864 if (using_mock_io) {
9865 io_err = tog_io_close();
9866 if (error == NULL)
9867 error = io_err;
9869 endwin();
9870 if (cmd_argv) {
9871 int i;
9872 for (i = 0; i < argc; i++)
9873 free(cmd_argv[i]);
9874 free(cmd_argv);
9877 if (error && error->code != GOT_ERR_CANCELLED &&
9878 error->code != GOT_ERR_EOF &&
9879 error->code != GOT_ERR_PRIVSEP_EXIT &&
9880 error->code != GOT_ERR_PRIVSEP_PIPE &&
9881 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9882 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9883 return 0;