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, ACS_HLINE, view->ncols);
985 else
986 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
987 ACS_VLINE, view->nlines);
990 static const struct got_error *view_init_hsplit(struct tog_view *, int);
991 static const struct got_error *request_log_commits(struct tog_view *);
992 static const struct got_error *offset_selection_down(struct tog_view *);
993 static void offset_selection_up(struct tog_view *);
994 static void view_get_split(struct tog_view *, int *, int *);
996 static const struct got_error *
997 view_resize(struct tog_view *view)
999 const struct got_error *err = NULL;
1000 int dif, nlines, ncols;
1002 dif = LINES - view->lines; /* line difference */
1004 if (view->lines > LINES)
1005 nlines = view->nlines - (view->lines - LINES);
1006 else
1007 nlines = view->nlines + (LINES - view->lines);
1008 if (view->cols > COLS)
1009 ncols = view->ncols - (view->cols - COLS);
1010 else
1011 ncols = view->ncols + (COLS - view->cols);
1013 if (view->child) {
1014 int hs = view->child->begin_y;
1016 if (!view_is_fullscreen(view))
1017 view->child->begin_x = view_split_begin_x(view->begin_x);
1018 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1019 view->child->begin_x == 0) {
1020 ncols = COLS;
1022 view_fullscreen(view->child);
1023 if (view->child->focussed)
1024 show_panel(view->child->panel);
1025 else
1026 show_panel(view->panel);
1027 } else {
1028 ncols = view->child->begin_x;
1030 view_splitscreen(view->child);
1031 show_panel(view->child->panel);
1034 * XXX This is ugly and needs to be moved into the above
1035 * logic but "works" for now and my attempts at moving it
1036 * break either 'tab' or 'F' key maps in horizontal splits.
1038 if (hs) {
1039 err = view_splitscreen(view->child);
1040 if (err)
1041 return err;
1042 if (dif < 0) { /* top split decreased */
1043 err = offset_selection_down(view);
1044 if (err)
1045 return err;
1047 view_border(view);
1048 update_panels();
1049 doupdate();
1050 show_panel(view->child->panel);
1051 nlines = view->nlines;
1053 } else if (view->parent == NULL)
1054 ncols = COLS;
1056 if (view->resize && dif > 0) {
1057 err = view->resize(view, dif);
1058 if (err)
1059 return err;
1062 if (wresize(view->window, nlines, ncols) == ERR)
1063 return got_error_from_errno("wresize");
1064 if (replace_panel(view->panel, view->window) == ERR)
1065 return got_error_from_errno("replace_panel");
1066 wclear(view->window);
1068 view->nlines = nlines;
1069 view->ncols = ncols;
1070 view->lines = LINES;
1071 view->cols = COLS;
1073 return NULL;
1076 static const struct got_error *
1077 resize_log_view(struct tog_view *view, int increase)
1079 struct tog_log_view_state *s = &view->state.log;
1080 const struct got_error *err = NULL;
1081 int n = 0;
1083 if (s->selected_entry)
1084 n = s->selected_entry->idx + view->lines - s->selected;
1087 * Request commits to account for the increased
1088 * height so we have enough to populate the view.
1090 if (s->commits->ncommits < n) {
1091 view->nscrolled = n - s->commits->ncommits + increase + 1;
1092 err = request_log_commits(view);
1095 return err;
1098 static void
1099 view_adjust_offset(struct tog_view *view, int n)
1101 if (n == 0)
1102 return;
1104 if (view->parent && view->parent->offset) {
1105 if (view->parent->offset + n >= 0)
1106 view->parent->offset += n;
1107 else
1108 view->parent->offset = 0;
1109 } else if (view->offset) {
1110 if (view->offset - n >= 0)
1111 view->offset -= n;
1112 else
1113 view->offset = 0;
1117 static const struct got_error *
1118 view_resize_split(struct tog_view *view, int resize)
1120 const struct got_error *err = NULL;
1121 struct tog_view *v = NULL;
1123 if (view->parent)
1124 v = view->parent;
1125 else
1126 v = view;
1128 if (!v->child || !view_is_splitscreen(v->child))
1129 return NULL;
1131 v->resized = v->child->resized = resize; /* lock for resize event */
1133 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1134 if (v->child->resized_y)
1135 v->child->begin_y = v->child->resized_y;
1136 if (view->parent)
1137 v->child->begin_y -= resize;
1138 else
1139 v->child->begin_y += resize;
1140 if (v->child->begin_y < 3) {
1141 view->count = 0;
1142 v->child->begin_y = 3;
1143 } else if (v->child->begin_y > LINES - 1) {
1144 view->count = 0;
1145 v->child->begin_y = LINES - 1;
1147 v->ncols = COLS;
1148 v->child->ncols = COLS;
1149 view_adjust_offset(view, resize);
1150 err = view_init_hsplit(v, v->child->begin_y);
1151 if (err)
1152 return err;
1153 v->child->resized_y = v->child->begin_y;
1154 } else {
1155 if (v->child->resized_x)
1156 v->child->begin_x = v->child->resized_x;
1157 if (view->parent)
1158 v->child->begin_x -= resize;
1159 else
1160 v->child->begin_x += resize;
1161 if (v->child->begin_x < 11) {
1162 view->count = 0;
1163 v->child->begin_x = 11;
1164 } else if (v->child->begin_x > COLS - 1) {
1165 view->count = 0;
1166 v->child->begin_x = COLS - 1;
1168 v->child->resized_x = v->child->begin_x;
1171 v->child->mode = v->mode;
1172 v->child->nlines = v->lines - v->child->begin_y;
1173 v->child->ncols = v->cols - v->child->begin_x;
1174 v->focus_child = 1;
1176 err = view_fullscreen(v);
1177 if (err)
1178 return err;
1179 err = view_splitscreen(v->child);
1180 if (err)
1181 return err;
1183 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1184 err = offset_selection_down(v->child);
1185 if (err)
1186 return err;
1189 if (v->resize)
1190 err = v->resize(v, 0);
1191 else if (v->child->resize)
1192 err = v->child->resize(v->child, 0);
1194 v->resized = v->child->resized = 0;
1196 return err;
1199 static void
1200 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1202 struct tog_view *v = src->child ? src->child : src;
1204 dst->resized_x = v->resized_x;
1205 dst->resized_y = v->resized_y;
1208 static const struct got_error *
1209 view_close_child(struct tog_view *view)
1211 const struct got_error *err = NULL;
1213 if (view->child == NULL)
1214 return NULL;
1216 err = view_close(view->child);
1217 view->child = NULL;
1218 return err;
1221 static const struct got_error *
1222 view_set_child(struct tog_view *view, struct tog_view *child)
1224 const struct got_error *err = NULL;
1226 view->child = child;
1227 child->parent = view;
1229 err = view_resize(view);
1230 if (err)
1231 return err;
1233 if (view->child->resized_x || view->child->resized_y)
1234 err = view_resize_split(view, 0);
1236 return err;
1239 static const struct got_error *view_dispatch_request(struct tog_view **,
1240 struct tog_view *, enum tog_view_type, int, int);
1242 static const struct got_error *
1243 view_request_new(struct tog_view **requested, struct tog_view *view,
1244 enum tog_view_type request)
1246 struct tog_view *new_view = NULL;
1247 const struct got_error *err;
1248 int y = 0, x = 0;
1250 *requested = NULL;
1252 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1253 view_get_split(view, &y, &x);
1255 err = view_dispatch_request(&new_view, view, request, y, x);
1256 if (err)
1257 return err;
1259 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1260 request != TOG_VIEW_HELP) {
1261 err = view_init_hsplit(view, y);
1262 if (err)
1263 return err;
1266 view->focussed = 0;
1267 new_view->focussed = 1;
1268 new_view->mode = view->mode;
1269 new_view->nlines = request == TOG_VIEW_HELP ?
1270 view->lines : view->lines - y;
1272 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1273 view_transfer_size(new_view, view);
1274 err = view_close_child(view);
1275 if (err)
1276 return err;
1277 err = view_set_child(view, new_view);
1278 if (err)
1279 return err;
1280 view->focus_child = 1;
1281 } else
1282 *requested = new_view;
1284 return NULL;
1287 static void
1288 tog_resizeterm(void)
1290 int cols, lines;
1291 struct winsize size;
1293 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1294 cols = 80; /* Default */
1295 lines = 24;
1296 } else {
1297 cols = size.ws_col;
1298 lines = size.ws_row;
1300 resize_term(lines, cols);
1303 static const struct got_error *
1304 view_search_start(struct tog_view *view, int fast_refresh)
1306 const struct got_error *err = NULL;
1307 struct tog_view *v = view;
1308 char pattern[1024];
1309 int ret;
1311 if (view->search_started) {
1312 regfree(&view->regex);
1313 view->searching = 0;
1314 memset(&view->regmatch, 0, sizeof(view->regmatch));
1316 view->search_started = 0;
1318 if (view->nlines < 1)
1319 return NULL;
1321 if (view_is_hsplit_top(view))
1322 v = view->child;
1323 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1324 v = view->parent;
1326 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1327 wclrtoeol(v->window);
1329 nodelay(v->window, FALSE); /* block for search term input */
1330 nocbreak();
1331 echo();
1332 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1333 wrefresh(v->window);
1334 cbreak();
1335 noecho();
1336 nodelay(v->window, TRUE);
1337 if (!fast_refresh && !using_mock_io)
1338 halfdelay(10);
1339 if (ret == ERR)
1340 return NULL;
1342 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1343 err = view->search_start(view);
1344 if (err) {
1345 regfree(&view->regex);
1346 return err;
1348 view->search_started = 1;
1349 view->searching = TOG_SEARCH_FORWARD;
1350 view->search_next_done = 0;
1351 view->search_next(view);
1354 return NULL;
1357 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1358 static const struct got_error *
1359 switch_split(struct tog_view *view)
1361 const struct got_error *err = NULL;
1362 struct tog_view *v = NULL;
1364 if (view->parent)
1365 v = view->parent;
1366 else
1367 v = view;
1369 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1370 v->mode = TOG_VIEW_SPLIT_VERT;
1371 else
1372 v->mode = TOG_VIEW_SPLIT_HRZN;
1374 if (!v->child)
1375 return NULL;
1376 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1377 v->mode = TOG_VIEW_SPLIT_NONE;
1379 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1380 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1381 v->child->begin_y = v->child->resized_y;
1382 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1383 v->child->begin_x = v->child->resized_x;
1386 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1387 v->ncols = COLS;
1388 v->child->ncols = COLS;
1389 v->child->nscrolled = LINES - v->child->nlines;
1391 err = view_init_hsplit(v, v->child->begin_y);
1392 if (err)
1393 return err;
1395 v->child->mode = v->mode;
1396 v->child->nlines = v->lines - v->child->begin_y;
1397 v->focus_child = 1;
1399 err = view_fullscreen(v);
1400 if (err)
1401 return err;
1402 err = view_splitscreen(v->child);
1403 if (err)
1404 return err;
1406 if (v->mode == TOG_VIEW_SPLIT_NONE)
1407 v->mode = TOG_VIEW_SPLIT_VERT;
1408 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1409 err = offset_selection_down(v);
1410 if (err)
1411 return err;
1412 err = offset_selection_down(v->child);
1413 if (err)
1414 return err;
1415 } else {
1416 offset_selection_up(v);
1417 offset_selection_up(v->child);
1419 if (v->resize)
1420 err = v->resize(v, 0);
1421 else if (v->child->resize)
1422 err = v->child->resize(v->child, 0);
1424 return err;
1428 * Strip trailing whitespace from str starting at byte *n;
1429 * if *n < 0, use strlen(str). Return new str length in *n.
1431 static void
1432 strip_trailing_ws(char *str, int *n)
1434 size_t x = *n;
1436 if (str == NULL || *str == '\0')
1437 return;
1439 if (x < 0)
1440 x = strlen(str);
1442 while (x-- > 0 && isspace((unsigned char)str[x]))
1443 str[x] = '\0';
1445 *n = x + 1;
1449 * Extract visible substring of line y from the curses screen
1450 * and strip trailing whitespace. If vline is set, overwrite
1451 * line[vline] with '|' because the ACS_VLINE character is
1452 * written out as 'x'. Write the line to file f.
1454 static const struct got_error *
1455 view_write_line(FILE *f, int y, int vline)
1457 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1458 int r, w;
1460 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1461 if (r == ERR)
1462 return got_error_fmt(GOT_ERR_RANGE,
1463 "failed to extract line %d", y);
1466 * In some views, lines are padded with blanks to COLS width.
1467 * Strip them so we can diff without the -b flag when testing.
1469 strip_trailing_ws(line, &r);
1471 if (vline > 0)
1472 line[vline] = '|';
1474 w = fprintf(f, "%s\n", line);
1475 if (w != r + 1) /* \n */
1476 return got_ferror(f, GOT_ERR_IO);
1478 return NULL;
1482 * Capture the visible curses screen by writing each line to the
1483 * file at the path set via the TOG_SCR_DUMP environment variable.
1485 static const struct got_error *
1486 screendump(struct tog_view *view)
1488 const struct got_error *err;
1489 FILE *f = NULL;
1490 const char *path;
1491 int i;
1493 path = getenv("TOG_SCR_DUMP");
1494 if (path == NULL || *path == '\0')
1495 return got_error_msg(GOT_ERR_BAD_PATH,
1496 "TOG_SCR_DUMP path not set to capture screen dump");
1497 f = fopen(path, "wex");
1498 if (f == NULL)
1499 return got_error_from_errno_fmt("fopen: %s", path);
1501 if ((view->child && view->child->begin_x) ||
1502 (view->parent && view->begin_x)) {
1503 int ncols = view->child ? view->ncols : view->parent->ncols;
1505 /* vertical splitscreen */
1506 for (i = 0; i < view->nlines; ++i) {
1507 err = view_write_line(f, i, ncols - 1);
1508 if (err)
1509 goto done;
1511 } else {
1512 int hline = 0;
1514 /* fullscreen or horizontal splitscreen */
1515 if ((view->child && view->child->begin_y) ||
1516 (view->parent && view->begin_y)) /* hsplit */
1517 hline = view->child ?
1518 view->child->begin_y : view->begin_y;
1520 for (i = 0; i < view->lines; i++) {
1521 if (hline && i == hline - 1) {
1522 int c;
1524 /* ACS_HLINE writes out as 'q', overwrite it */
1525 for (c = 0; c < view->cols; ++c)
1526 fputc('-', f);
1527 fputc('\n', f);
1528 continue;
1531 err = view_write_line(f, i, 0);
1532 if (err)
1533 goto done;
1537 done:
1538 if (f && fclose(f) == EOF && err == NULL)
1539 err = got_ferror(f, GOT_ERR_IO);
1540 return err;
1544 * Compute view->count from numeric input. Assign total to view->count and
1545 * return first non-numeric key entered.
1547 static int
1548 get_compound_key(struct tog_view *view, int c)
1550 struct tog_view *v = view;
1551 int x, n = 0;
1553 if (view_is_hsplit_top(view))
1554 v = view->child;
1555 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1556 v = view->parent;
1558 view->count = 0;
1559 cbreak(); /* block for input */
1560 nodelay(view->window, FALSE);
1561 wmove(v->window, v->nlines - 1, 0);
1562 wclrtoeol(v->window);
1563 waddch(v->window, ':');
1565 do {
1566 x = getcurx(v->window);
1567 if (x != ERR && x < view->ncols) {
1568 waddch(v->window, c);
1569 wrefresh(v->window);
1573 * Don't overflow. Max valid request should be the greatest
1574 * between the longest and total lines; cap at 10 million.
1576 if (n >= 9999999)
1577 n = 9999999;
1578 else
1579 n = n * 10 + (c - '0');
1580 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1582 if (c == 'G' || c == 'g') { /* nG key map */
1583 view->gline = view->hiline = n;
1584 n = 0;
1585 c = 0;
1588 /* Massage excessive or inapplicable values at the input handler. */
1589 view->count = n;
1591 return c;
1594 static void
1595 action_report(struct tog_view *view)
1597 struct tog_view *v = view;
1599 if (view_is_hsplit_top(view))
1600 v = view->child;
1601 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1602 v = view->parent;
1604 wmove(v->window, v->nlines - 1, 0);
1605 wclrtoeol(v->window);
1606 wprintw(v->window, ":%s", view->action);
1607 wrefresh(v->window);
1610 * Clear action status report. Only clear in blame view
1611 * once annotating is complete, otherwise it's too fast.
1613 if (view->type == TOG_VIEW_BLAME) {
1614 if (view->state.blame.blame_complete)
1615 view->action = NULL;
1616 } else
1617 view->action = NULL;
1621 * Read the next line from the test script and assign
1622 * key instruction to *ch. If at EOF, set the *done flag.
1624 static const struct got_error *
1625 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1627 const struct got_error *err = NULL;
1628 char *line = NULL;
1629 size_t linesz = 0;
1631 if (view->count && --view->count) {
1632 *ch = view->ch;
1633 return NULL;
1634 } else
1635 *ch = -1;
1637 if (getline(&line, &linesz, script) == -1) {
1638 if (feof(script)) {
1639 *done = 1;
1640 goto done;
1641 } else {
1642 err = got_ferror(script, GOT_ERR_IO);
1643 goto done;
1647 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1648 tog_io.wait_for_ui = 1;
1649 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1650 *ch = KEY_ENTER;
1651 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1652 *ch = KEY_RIGHT;
1653 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1654 *ch = KEY_LEFT;
1655 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1656 *ch = KEY_DOWN;
1657 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1658 *ch = KEY_UP;
1659 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1660 *ch = TOG_KEY_SCRDUMP;
1661 else if (isdigit((unsigned char)*line)) {
1662 char *t = line;
1664 while (isdigit((unsigned char)*t))
1665 ++t;
1666 view->ch = *ch = *t;
1667 *t = '\0';
1668 /* ignore error, view->count is 0 if instruction is invalid */
1669 view->count = strtonum(line, 0, INT_MAX, NULL);
1670 } else
1671 *ch = *line;
1673 done:
1674 free(line);
1675 return err;
1678 static const struct got_error *
1679 view_input(struct tog_view **new, int *done, struct tog_view *view,
1680 struct tog_view_list_head *views, int fast_refresh)
1682 const struct got_error *err = NULL;
1683 struct tog_view *v;
1684 int ch, errcode;
1686 *new = NULL;
1688 if (view->action)
1689 action_report(view);
1691 /* Clear "no matches" indicator. */
1692 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1693 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1694 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1695 view->count = 0;
1698 if (view->searching && !view->search_next_done) {
1699 errcode = pthread_mutex_unlock(&tog_mutex);
1700 if (errcode)
1701 return got_error_set_errno(errcode,
1702 "pthread_mutex_unlock");
1703 sched_yield();
1704 errcode = pthread_mutex_lock(&tog_mutex);
1705 if (errcode)
1706 return got_error_set_errno(errcode,
1707 "pthread_mutex_lock");
1708 view->search_next(view);
1709 return NULL;
1712 /* Allow threads to make progress while we are waiting for input. */
1713 errcode = pthread_mutex_unlock(&tog_mutex);
1714 if (errcode)
1715 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1717 if (using_mock_io) {
1718 err = tog_read_script_key(tog_io.f, view, &ch, done);
1719 if (err) {
1720 errcode = pthread_mutex_lock(&tog_mutex);
1721 return err;
1723 } else if (view->count && --view->count) {
1724 cbreak();
1725 nodelay(view->window, TRUE);
1726 ch = wgetch(view->window);
1727 /* let C-g or backspace abort unfinished count */
1728 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1729 view->count = 0;
1730 else
1731 ch = view->ch;
1732 } else {
1733 ch = wgetch(view->window);
1734 if (ch >= '1' && ch <= '9')
1735 view->ch = ch = get_compound_key(view, ch);
1737 if (view->hiline && ch != ERR && ch != 0)
1738 view->hiline = 0; /* key pressed, clear line highlight */
1739 nodelay(view->window, TRUE);
1740 errcode = pthread_mutex_lock(&tog_mutex);
1741 if (errcode)
1742 return got_error_set_errno(errcode, "pthread_mutex_lock");
1744 if (tog_sigwinch_received || tog_sigcont_received) {
1745 tog_resizeterm();
1746 tog_sigwinch_received = 0;
1747 tog_sigcont_received = 0;
1748 TAILQ_FOREACH(v, views, entry) {
1749 err = view_resize(v);
1750 if (err)
1751 return err;
1752 err = v->input(new, v, KEY_RESIZE);
1753 if (err)
1754 return err;
1755 if (v->child) {
1756 err = view_resize(v->child);
1757 if (err)
1758 return err;
1759 err = v->child->input(new, v->child,
1760 KEY_RESIZE);
1761 if (err)
1762 return err;
1763 if (v->child->resized_x || v->child->resized_y) {
1764 err = view_resize_split(v, 0);
1765 if (err)
1766 return err;
1772 switch (ch) {
1773 case '?':
1774 case 'H':
1775 case KEY_F(1):
1776 if (view->type == TOG_VIEW_HELP)
1777 err = view->reset(view);
1778 else
1779 err = view_request_new(new, view, TOG_VIEW_HELP);
1780 break;
1781 case '\t':
1782 view->count = 0;
1783 if (view->child) {
1784 view->focussed = 0;
1785 view->child->focussed = 1;
1786 view->focus_child = 1;
1787 } else if (view->parent) {
1788 view->focussed = 0;
1789 view->parent->focussed = 1;
1790 view->parent->focus_child = 0;
1791 if (!view_is_splitscreen(view)) {
1792 if (view->parent->resize) {
1793 err = view->parent->resize(view->parent,
1794 0);
1795 if (err)
1796 return err;
1798 offset_selection_up(view->parent);
1799 err = view_fullscreen(view->parent);
1800 if (err)
1801 return err;
1804 break;
1805 case 'q':
1806 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1807 if (view->parent->resize) {
1808 /* might need more commits to fill fullscreen */
1809 err = view->parent->resize(view->parent, 0);
1810 if (err)
1811 break;
1813 offset_selection_up(view->parent);
1815 err = view->input(new, view, ch);
1816 view->dying = 1;
1817 break;
1818 case 'Q':
1819 *done = 1;
1820 break;
1821 case 'F':
1822 view->count = 0;
1823 if (view_is_parent_view(view)) {
1824 if (view->child == NULL)
1825 break;
1826 if (view_is_splitscreen(view->child)) {
1827 view->focussed = 0;
1828 view->child->focussed = 1;
1829 err = view_fullscreen(view->child);
1830 } else {
1831 err = view_splitscreen(view->child);
1832 if (!err)
1833 err = view_resize_split(view, 0);
1835 if (err)
1836 break;
1837 err = view->child->input(new, view->child,
1838 KEY_RESIZE);
1839 } else {
1840 if (view_is_splitscreen(view)) {
1841 view->parent->focussed = 0;
1842 view->focussed = 1;
1843 err = view_fullscreen(view);
1844 } else {
1845 err = view_splitscreen(view);
1846 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1847 err = view_resize(view->parent);
1848 if (!err)
1849 err = view_resize_split(view, 0);
1851 if (err)
1852 break;
1853 err = view->input(new, view, KEY_RESIZE);
1855 if (err)
1856 break;
1857 if (view->resize) {
1858 err = view->resize(view, 0);
1859 if (err)
1860 break;
1862 if (view->parent)
1863 err = offset_selection_down(view->parent);
1864 if (!err)
1865 err = offset_selection_down(view);
1866 break;
1867 case 'S':
1868 view->count = 0;
1869 err = switch_split(view);
1870 break;
1871 case '-':
1872 err = view_resize_split(view, -1);
1873 break;
1874 case '+':
1875 err = view_resize_split(view, 1);
1876 break;
1877 case KEY_RESIZE:
1878 break;
1879 case '/':
1880 view->count = 0;
1881 if (view->search_start)
1882 view_search_start(view, fast_refresh);
1883 else
1884 err = view->input(new, view, ch);
1885 break;
1886 case 'N':
1887 case 'n':
1888 if (view->search_started && view->search_next) {
1889 view->searching = (ch == 'n' ?
1890 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1891 view->search_next_done = 0;
1892 view->search_next(view);
1893 } else
1894 err = view->input(new, view, ch);
1895 break;
1896 case 'A':
1897 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1898 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1899 view->action = "Patience diff algorithm";
1900 } else {
1901 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1902 view->action = "Myers diff algorithm";
1904 TAILQ_FOREACH(v, views, entry) {
1905 if (v->reset) {
1906 err = v->reset(v);
1907 if (err)
1908 return err;
1910 if (v->child && v->child->reset) {
1911 err = v->child->reset(v->child);
1912 if (err)
1913 return err;
1916 break;
1917 case TOG_KEY_SCRDUMP:
1918 err = screendump(view);
1919 break;
1920 default:
1921 err = view->input(new, view, ch);
1922 break;
1925 return err;
1928 static int
1929 view_needs_focus_indication(struct tog_view *view)
1931 if (view_is_parent_view(view)) {
1932 if (view->child == NULL || view->child->focussed)
1933 return 0;
1934 if (!view_is_splitscreen(view->child))
1935 return 0;
1936 } else if (!view_is_splitscreen(view))
1937 return 0;
1939 return view->focussed;
1942 static const struct got_error *
1943 tog_io_close(void)
1945 const struct got_error *err = NULL;
1947 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1948 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1949 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1950 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1951 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1952 err = got_ferror(tog_io.f, GOT_ERR_IO);
1954 return err;
1957 static const struct got_error *
1958 view_loop(struct tog_view *view)
1960 const struct got_error *err = NULL;
1961 struct tog_view_list_head views;
1962 struct tog_view *new_view;
1963 char *mode;
1964 int fast_refresh = 10;
1965 int done = 0, errcode;
1967 mode = getenv("TOG_VIEW_SPLIT_MODE");
1968 if (!mode || !(*mode == 'h' || *mode == 'H'))
1969 view->mode = TOG_VIEW_SPLIT_VERT;
1970 else
1971 view->mode = TOG_VIEW_SPLIT_HRZN;
1973 errcode = pthread_mutex_lock(&tog_mutex);
1974 if (errcode)
1975 return got_error_set_errno(errcode, "pthread_mutex_lock");
1977 TAILQ_INIT(&views);
1978 TAILQ_INSERT_HEAD(&views, view, entry);
1980 view->focussed = 1;
1981 err = view->show(view);
1982 if (err)
1983 return err;
1984 update_panels();
1985 doupdate();
1986 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1987 !tog_fatal_signal_received()) {
1988 /* Refresh fast during initialization, then become slower. */
1989 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1990 halfdelay(10); /* switch to once per second */
1992 err = view_input(&new_view, &done, view, &views, fast_refresh);
1993 if (err)
1994 break;
1996 if (view->dying && view == TAILQ_FIRST(&views) &&
1997 TAILQ_NEXT(view, entry) == NULL)
1998 done = 1;
1999 if (done) {
2000 struct tog_view *v;
2003 * When we quit, scroll the screen up a single line
2004 * so we don't lose any information.
2006 TAILQ_FOREACH(v, &views, entry) {
2007 wmove(v->window, 0, 0);
2008 wdeleteln(v->window);
2009 wnoutrefresh(v->window);
2010 if (v->child && !view_is_fullscreen(v)) {
2011 wmove(v->child->window, 0, 0);
2012 wdeleteln(v->child->window);
2013 wnoutrefresh(v->child->window);
2016 doupdate();
2019 if (view->dying) {
2020 struct tog_view *v, *prev = NULL;
2022 if (view_is_parent_view(view))
2023 prev = TAILQ_PREV(view, tog_view_list_head,
2024 entry);
2025 else if (view->parent)
2026 prev = view->parent;
2028 if (view->parent) {
2029 view->parent->child = NULL;
2030 view->parent->focus_child = 0;
2031 /* Restore fullscreen line height. */
2032 view->parent->nlines = view->parent->lines;
2033 err = view_resize(view->parent);
2034 if (err)
2035 break;
2036 /* Make resized splits persist. */
2037 view_transfer_size(view->parent, view);
2038 } else
2039 TAILQ_REMOVE(&views, view, entry);
2041 err = view_close(view);
2042 if (err)
2043 goto done;
2045 view = NULL;
2046 TAILQ_FOREACH(v, &views, entry) {
2047 if (v->focussed)
2048 break;
2050 if (view == NULL && new_view == NULL) {
2051 /* No view has focus. Try to pick one. */
2052 if (prev)
2053 view = prev;
2054 else if (!TAILQ_EMPTY(&views)) {
2055 view = TAILQ_LAST(&views,
2056 tog_view_list_head);
2058 if (view) {
2059 if (view->focus_child) {
2060 view->child->focussed = 1;
2061 view = view->child;
2062 } else
2063 view->focussed = 1;
2067 if (new_view) {
2068 struct tog_view *v, *t;
2069 /* Only allow one parent view per type. */
2070 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2071 if (v->type != new_view->type)
2072 continue;
2073 TAILQ_REMOVE(&views, v, entry);
2074 err = view_close(v);
2075 if (err)
2076 goto done;
2077 break;
2079 TAILQ_INSERT_TAIL(&views, new_view, entry);
2080 view = new_view;
2082 if (view && !done) {
2083 if (view_is_parent_view(view)) {
2084 if (view->child && view->child->focussed)
2085 view = view->child;
2086 } else {
2087 if (view->parent && view->parent->focussed)
2088 view = view->parent;
2090 show_panel(view->panel);
2091 if (view->child && view_is_splitscreen(view->child))
2092 show_panel(view->child->panel);
2093 if (view->parent && view_is_splitscreen(view)) {
2094 err = view->parent->show(view->parent);
2095 if (err)
2096 goto done;
2098 err = view->show(view);
2099 if (err)
2100 goto done;
2101 if (view->child) {
2102 err = view->child->show(view->child);
2103 if (err)
2104 goto done;
2106 update_panels();
2107 doupdate();
2110 done:
2111 while (!TAILQ_EMPTY(&views)) {
2112 const struct got_error *close_err;
2113 view = TAILQ_FIRST(&views);
2114 TAILQ_REMOVE(&views, view, entry);
2115 close_err = view_close(view);
2116 if (close_err && err == NULL)
2117 err = close_err;
2120 errcode = pthread_mutex_unlock(&tog_mutex);
2121 if (errcode && err == NULL)
2122 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2124 return err;
2127 __dead static void
2128 usage_log(void)
2130 endwin();
2131 fprintf(stderr,
2132 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2133 getprogname());
2134 exit(1);
2137 /* Create newly allocated wide-character string equivalent to a byte string. */
2138 static const struct got_error *
2139 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2141 char *vis = NULL;
2142 const struct got_error *err = NULL;
2144 *ws = NULL;
2145 *wlen = mbstowcs(NULL, s, 0);
2146 if (*wlen == (size_t)-1) {
2147 int vislen;
2148 if (errno != EILSEQ)
2149 return got_error_from_errno("mbstowcs");
2151 /* byte string invalid in current encoding; try to "fix" it */
2152 err = got_mbsavis(&vis, &vislen, s);
2153 if (err)
2154 return err;
2155 *wlen = mbstowcs(NULL, vis, 0);
2156 if (*wlen == (size_t)-1) {
2157 err = got_error_from_errno("mbstowcs"); /* give up */
2158 goto done;
2162 *ws = calloc(*wlen + 1, sizeof(**ws));
2163 if (*ws == NULL) {
2164 err = got_error_from_errno("calloc");
2165 goto done;
2168 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2169 err = got_error_from_errno("mbstowcs");
2170 done:
2171 free(vis);
2172 if (err) {
2173 free(*ws);
2174 *ws = NULL;
2175 *wlen = 0;
2177 return err;
2180 static const struct got_error *
2181 expand_tab(char **ptr, const char *src)
2183 char *dst;
2184 size_t len, n, idx = 0, sz = 0;
2186 *ptr = NULL;
2187 n = len = strlen(src);
2188 dst = malloc(n + 1);
2189 if (dst == NULL)
2190 return got_error_from_errno("malloc");
2192 while (idx < len && src[idx]) {
2193 const char c = src[idx];
2195 if (c == '\t') {
2196 size_t nb = TABSIZE - sz % TABSIZE;
2197 char *p;
2199 p = realloc(dst, n + nb);
2200 if (p == NULL) {
2201 free(dst);
2202 return got_error_from_errno("realloc");
2205 dst = p;
2206 n += nb;
2207 memset(dst + sz, ' ', nb);
2208 sz += nb;
2209 } else
2210 dst[sz++] = src[idx];
2211 ++idx;
2214 dst[sz] = '\0';
2215 *ptr = dst;
2216 return NULL;
2220 * Advance at most n columns from wline starting at offset off.
2221 * Return the index to the first character after the span operation.
2222 * Return the combined column width of all spanned wide character in
2223 * *rcol.
2225 static int
2226 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2228 int width, i, cols = 0;
2230 if (n == 0) {
2231 *rcol = cols;
2232 return off;
2235 for (i = off; wline[i] != L'\0'; ++i) {
2236 if (wline[i] == L'\t')
2237 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2238 else
2239 width = wcwidth(wline[i]);
2241 if (width == -1) {
2242 width = 1;
2243 wline[i] = L'.';
2246 if (cols + width > n)
2247 break;
2248 cols += width;
2251 *rcol = cols;
2252 return i;
2256 * Format a line for display, ensuring that it won't overflow a width limit.
2257 * With scrolling, the width returned refers to the scrolled version of the
2258 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2260 static const struct got_error *
2261 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2262 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2264 const struct got_error *err = NULL;
2265 int cols;
2266 wchar_t *wline = NULL;
2267 char *exstr = NULL;
2268 size_t wlen;
2269 int i, scrollx;
2271 *wlinep = NULL;
2272 *widthp = 0;
2274 if (expand) {
2275 err = expand_tab(&exstr, line);
2276 if (err)
2277 return err;
2280 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2281 free(exstr);
2282 if (err)
2283 return err;
2285 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2287 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2288 wline[wlen - 1] = L'\0';
2289 wlen--;
2291 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2292 wline[wlen - 1] = L'\0';
2293 wlen--;
2296 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2297 wline[i] = L'\0';
2299 if (widthp)
2300 *widthp = cols;
2301 if (scrollxp)
2302 *scrollxp = scrollx;
2303 if (err)
2304 free(wline);
2305 else
2306 *wlinep = wline;
2307 return err;
2310 static const struct got_error*
2311 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2312 struct got_object_id *id, struct got_repository *repo)
2314 static const struct got_error *err = NULL;
2315 struct got_reflist_entry *re;
2316 char *s;
2317 const char *name;
2319 *refs_str = NULL;
2321 TAILQ_FOREACH(re, refs, entry) {
2322 struct got_tag_object *tag = NULL;
2323 struct got_object_id *ref_id;
2324 int cmp;
2326 name = got_ref_get_name(re->ref);
2327 if (strcmp(name, GOT_REF_HEAD) == 0)
2328 continue;
2329 if (strncmp(name, "refs/", 5) == 0)
2330 name += 5;
2331 if (strncmp(name, "got/", 4) == 0 &&
2332 strncmp(name, "got/backup/", 11) != 0)
2333 continue;
2334 if (strncmp(name, "heads/", 6) == 0)
2335 name += 6;
2336 if (strncmp(name, "remotes/", 8) == 0) {
2337 name += 8;
2338 s = strstr(name, "/" GOT_REF_HEAD);
2339 if (s != NULL && s[strlen(s)] == '\0')
2340 continue;
2342 err = got_ref_resolve(&ref_id, repo, re->ref);
2343 if (err)
2344 break;
2345 if (strncmp(name, "tags/", 5) == 0) {
2346 err = got_object_open_as_tag(&tag, repo, ref_id);
2347 if (err) {
2348 if (err->code != GOT_ERR_OBJ_TYPE) {
2349 free(ref_id);
2350 break;
2352 /* Ref points at something other than a tag. */
2353 err = NULL;
2354 tag = NULL;
2357 cmp = got_object_id_cmp(tag ?
2358 got_object_tag_get_object_id(tag) : ref_id, id);
2359 free(ref_id);
2360 if (tag)
2361 got_object_tag_close(tag);
2362 if (cmp != 0)
2363 continue;
2364 s = *refs_str;
2365 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2366 s ? ", " : "", name) == -1) {
2367 err = got_error_from_errno("asprintf");
2368 free(s);
2369 *refs_str = NULL;
2370 break;
2372 free(s);
2375 return err;
2378 static const struct got_error *
2379 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2380 int col_tab_align)
2382 char *smallerthan;
2384 smallerthan = strchr(author, '<');
2385 if (smallerthan && smallerthan[1] != '\0')
2386 author = smallerthan + 1;
2387 author[strcspn(author, "@>")] = '\0';
2388 return format_line(wauthor, author_width, NULL, author, 0, limit,
2389 col_tab_align, 0);
2392 static const struct got_error *
2393 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2394 struct got_object_id *id, const size_t date_display_cols,
2395 int author_display_cols)
2397 struct tog_log_view_state *s = &view->state.log;
2398 const struct got_error *err = NULL;
2399 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2400 char *logmsg0 = NULL, *logmsg = NULL;
2401 char *author = NULL;
2402 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2403 int author_width, logmsg_width;
2404 char *newline, *line = NULL;
2405 int col, limit, scrollx;
2406 const int avail = view->ncols;
2407 struct tm tm;
2408 time_t committer_time;
2409 struct tog_color *tc;
2411 committer_time = got_object_commit_get_committer_time(commit);
2412 if (gmtime_r(&committer_time, &tm) == NULL)
2413 return got_error_from_errno("gmtime_r");
2414 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2415 return got_error(GOT_ERR_NO_SPACE);
2417 if (avail <= date_display_cols)
2418 limit = MIN(sizeof(datebuf) - 1, avail);
2419 else
2420 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2421 tc = get_color(&s->colors, TOG_COLOR_DATE);
2422 if (tc)
2423 wattr_on(view->window,
2424 COLOR_PAIR(tc->colorpair), NULL);
2425 waddnstr(view->window, datebuf, limit);
2426 if (tc)
2427 wattr_off(view->window,
2428 COLOR_PAIR(tc->colorpair), NULL);
2429 col = limit;
2430 if (col > avail)
2431 goto done;
2433 if (avail >= 120) {
2434 char *id_str;
2435 err = got_object_id_str(&id_str, id);
2436 if (err)
2437 goto done;
2438 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2439 if (tc)
2440 wattr_on(view->window,
2441 COLOR_PAIR(tc->colorpair), NULL);
2442 wprintw(view->window, "%.8s ", id_str);
2443 if (tc)
2444 wattr_off(view->window,
2445 COLOR_PAIR(tc->colorpair), NULL);
2446 free(id_str);
2447 col += 9;
2448 if (col > avail)
2449 goto done;
2452 if (s->use_committer)
2453 author = strdup(got_object_commit_get_committer(commit));
2454 else
2455 author = strdup(got_object_commit_get_author(commit));
2456 if (author == NULL) {
2457 err = got_error_from_errno("strdup");
2458 goto done;
2460 err = format_author(&wauthor, &author_width, author, avail - col, col);
2461 if (err)
2462 goto done;
2463 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2464 if (tc)
2465 wattr_on(view->window,
2466 COLOR_PAIR(tc->colorpair), NULL);
2467 waddwstr(view->window, wauthor);
2468 col += author_width;
2469 while (col < avail && author_width < author_display_cols + 2) {
2470 waddch(view->window, ' ');
2471 col++;
2472 author_width++;
2474 if (tc)
2475 wattr_off(view->window,
2476 COLOR_PAIR(tc->colorpair), NULL);
2477 if (col > avail)
2478 goto done;
2480 err = got_object_commit_get_logmsg(&logmsg0, commit);
2481 if (err)
2482 goto done;
2483 logmsg = logmsg0;
2484 while (*logmsg == '\n')
2485 logmsg++;
2486 newline = strchr(logmsg, '\n');
2487 if (newline)
2488 *newline = '\0';
2489 limit = avail - col;
2490 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2491 limit--; /* for the border */
2492 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2493 limit, col, 1);
2494 if (err)
2495 goto done;
2496 waddwstr(view->window, &wlogmsg[scrollx]);
2497 col += MAX(logmsg_width, 0);
2498 while (col < avail) {
2499 waddch(view->window, ' ');
2500 col++;
2502 done:
2503 free(logmsg0);
2504 free(wlogmsg);
2505 free(author);
2506 free(wauthor);
2507 free(line);
2508 return err;
2511 static struct commit_queue_entry *
2512 alloc_commit_queue_entry(struct got_commit_object *commit,
2513 struct got_object_id *id)
2515 struct commit_queue_entry *entry;
2516 struct got_object_id *dup;
2518 entry = calloc(1, sizeof(*entry));
2519 if (entry == NULL)
2520 return NULL;
2522 dup = got_object_id_dup(id);
2523 if (dup == NULL) {
2524 free(entry);
2525 return NULL;
2528 entry->id = dup;
2529 entry->commit = commit;
2530 return entry;
2533 static void
2534 pop_commit(struct commit_queue *commits)
2536 struct commit_queue_entry *entry;
2538 entry = TAILQ_FIRST(&commits->head);
2539 TAILQ_REMOVE(&commits->head, entry, entry);
2540 got_object_commit_close(entry->commit);
2541 commits->ncommits--;
2542 free(entry->id);
2543 free(entry);
2546 static void
2547 free_commits(struct commit_queue *commits)
2549 while (!TAILQ_EMPTY(&commits->head))
2550 pop_commit(commits);
2553 static const struct got_error *
2554 match_commit(int *have_match, struct got_object_id *id,
2555 struct got_commit_object *commit, regex_t *regex)
2557 const struct got_error *err = NULL;
2558 regmatch_t regmatch;
2559 char *id_str = NULL, *logmsg = NULL;
2561 *have_match = 0;
2563 err = got_object_id_str(&id_str, id);
2564 if (err)
2565 return err;
2567 err = got_object_commit_get_logmsg(&logmsg, commit);
2568 if (err)
2569 goto done;
2571 if (regexec(regex, got_object_commit_get_author(commit), 1,
2572 &regmatch, 0) == 0 ||
2573 regexec(regex, got_object_commit_get_committer(commit), 1,
2574 &regmatch, 0) == 0 ||
2575 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2576 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2577 *have_match = 1;
2578 done:
2579 free(id_str);
2580 free(logmsg);
2581 return err;
2584 static const struct got_error *
2585 queue_commits(struct tog_log_thread_args *a)
2587 const struct got_error *err = NULL;
2590 * We keep all commits open throughout the lifetime of the log
2591 * view in order to avoid having to re-fetch commits from disk
2592 * while updating the display.
2594 do {
2595 struct got_object_id id;
2596 struct got_commit_object *commit;
2597 struct commit_queue_entry *entry;
2598 int limit_match = 0;
2599 int errcode;
2601 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2602 NULL, NULL);
2603 if (err)
2604 break;
2606 err = got_object_open_as_commit(&commit, a->repo, &id);
2607 if (err)
2608 break;
2609 entry = alloc_commit_queue_entry(commit, &id);
2610 if (entry == NULL) {
2611 err = got_error_from_errno("alloc_commit_queue_entry");
2612 break;
2615 errcode = pthread_mutex_lock(&tog_mutex);
2616 if (errcode) {
2617 err = got_error_set_errno(errcode,
2618 "pthread_mutex_lock");
2619 break;
2622 entry->idx = a->real_commits->ncommits;
2623 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2624 a->real_commits->ncommits++;
2626 if (*a->limiting) {
2627 err = match_commit(&limit_match, &id, commit,
2628 a->limit_regex);
2629 if (err)
2630 break;
2632 if (limit_match) {
2633 struct commit_queue_entry *matched;
2635 matched = alloc_commit_queue_entry(
2636 entry->commit, entry->id);
2637 if (matched == NULL) {
2638 err = got_error_from_errno(
2639 "alloc_commit_queue_entry");
2640 break;
2642 matched->commit = entry->commit;
2643 got_object_commit_retain(entry->commit);
2645 matched->idx = a->limit_commits->ncommits;
2646 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2647 matched, entry);
2648 a->limit_commits->ncommits++;
2652 * This is how we signal log_thread() that we
2653 * have found a match, and that it should be
2654 * counted as a new entry for the view.
2656 a->limit_match = limit_match;
2659 if (*a->searching == TOG_SEARCH_FORWARD &&
2660 !*a->search_next_done) {
2661 int have_match;
2662 err = match_commit(&have_match, &id, commit, a->regex);
2663 if (err)
2664 break;
2666 if (*a->limiting) {
2667 if (limit_match && have_match)
2668 *a->search_next_done =
2669 TOG_SEARCH_HAVE_MORE;
2670 } else if (have_match)
2671 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2674 errcode = pthread_mutex_unlock(&tog_mutex);
2675 if (errcode && err == NULL)
2676 err = got_error_set_errno(errcode,
2677 "pthread_mutex_unlock");
2678 if (err)
2679 break;
2680 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2682 return err;
2685 static void
2686 select_commit(struct tog_log_view_state *s)
2688 struct commit_queue_entry *entry;
2689 int ncommits = 0;
2691 entry = s->first_displayed_entry;
2692 while (entry) {
2693 if (ncommits == s->selected) {
2694 s->selected_entry = entry;
2695 break;
2697 entry = TAILQ_NEXT(entry, entry);
2698 ncommits++;
2702 static const struct got_error *
2703 draw_commits(struct tog_view *view)
2705 const struct got_error *err = NULL;
2706 struct tog_log_view_state *s = &view->state.log;
2707 struct commit_queue_entry *entry = s->selected_entry;
2708 int limit = view->nlines;
2709 int width;
2710 int ncommits, author_cols = 4;
2711 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2712 char *refs_str = NULL;
2713 wchar_t *wline;
2714 struct tog_color *tc;
2715 static const size_t date_display_cols = 12;
2717 if (view_is_hsplit_top(view))
2718 --limit; /* account for border */
2720 if (s->selected_entry &&
2721 !(view->searching && view->search_next_done == 0)) {
2722 struct got_reflist_head *refs;
2723 err = got_object_id_str(&id_str, s->selected_entry->id);
2724 if (err)
2725 return err;
2726 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2727 s->selected_entry->id);
2728 if (refs) {
2729 err = build_refs_str(&refs_str, refs,
2730 s->selected_entry->id, s->repo);
2731 if (err)
2732 goto done;
2736 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2737 halfdelay(10); /* disable fast refresh */
2739 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2740 if (asprintf(&ncommits_str, " [%d/%d] %s",
2741 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2742 (view->searching && !view->search_next_done) ?
2743 "searching..." : "loading...") == -1) {
2744 err = got_error_from_errno("asprintf");
2745 goto done;
2747 } else {
2748 const char *search_str = NULL;
2749 const char *limit_str = NULL;
2751 if (view->searching) {
2752 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2753 search_str = "no more matches";
2754 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2755 search_str = "no matches found";
2756 else if (!view->search_next_done)
2757 search_str = "searching...";
2760 if (s->limit_view && s->commits->ncommits == 0)
2761 limit_str = "no matches found";
2763 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2764 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2765 search_str ? search_str : (refs_str ? refs_str : ""),
2766 limit_str ? limit_str : "") == -1) {
2767 err = got_error_from_errno("asprintf");
2768 goto done;
2772 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2773 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2774 "........................................",
2775 s->in_repo_path, ncommits_str) == -1) {
2776 err = got_error_from_errno("asprintf");
2777 header = NULL;
2778 goto done;
2780 } else if (asprintf(&header, "commit %s%s",
2781 id_str ? id_str : "........................................",
2782 ncommits_str) == -1) {
2783 err = got_error_from_errno("asprintf");
2784 header = NULL;
2785 goto done;
2787 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2788 if (err)
2789 goto done;
2791 werase(view->window);
2793 if (view_needs_focus_indication(view))
2794 wstandout(view->window);
2795 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2796 if (tc)
2797 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2798 waddwstr(view->window, wline);
2799 while (width < view->ncols) {
2800 waddch(view->window, ' ');
2801 width++;
2803 if (tc)
2804 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2805 if (view_needs_focus_indication(view))
2806 wstandend(view->window);
2807 free(wline);
2808 if (limit <= 1)
2809 goto done;
2811 /* Grow author column size if necessary, and set view->maxx. */
2812 entry = s->first_displayed_entry;
2813 ncommits = 0;
2814 view->maxx = 0;
2815 while (entry) {
2816 struct got_commit_object *c = entry->commit;
2817 char *author, *eol, *msg, *msg0;
2818 wchar_t *wauthor, *wmsg;
2819 int width;
2820 if (ncommits >= limit - 1)
2821 break;
2822 if (s->use_committer)
2823 author = strdup(got_object_commit_get_committer(c));
2824 else
2825 author = strdup(got_object_commit_get_author(c));
2826 if (author == NULL) {
2827 err = got_error_from_errno("strdup");
2828 goto done;
2830 err = format_author(&wauthor, &width, author, COLS,
2831 date_display_cols);
2832 if (author_cols < width)
2833 author_cols = width;
2834 free(wauthor);
2835 free(author);
2836 if (err)
2837 goto done;
2838 err = got_object_commit_get_logmsg(&msg0, c);
2839 if (err)
2840 goto done;
2841 msg = msg0;
2842 while (*msg == '\n')
2843 ++msg;
2844 if ((eol = strchr(msg, '\n')))
2845 *eol = '\0';
2846 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2847 date_display_cols + author_cols, 0);
2848 if (err)
2849 goto done;
2850 view->maxx = MAX(view->maxx, width);
2851 free(msg0);
2852 free(wmsg);
2853 ncommits++;
2854 entry = TAILQ_NEXT(entry, entry);
2857 entry = s->first_displayed_entry;
2858 s->last_displayed_entry = s->first_displayed_entry;
2859 ncommits = 0;
2860 while (entry) {
2861 if (ncommits >= limit - 1)
2862 break;
2863 if (ncommits == s->selected)
2864 wstandout(view->window);
2865 err = draw_commit(view, entry->commit, entry->id,
2866 date_display_cols, author_cols);
2867 if (ncommits == s->selected)
2868 wstandend(view->window);
2869 if (err)
2870 goto done;
2871 ncommits++;
2872 s->last_displayed_entry = entry;
2873 entry = TAILQ_NEXT(entry, entry);
2876 view_border(view);
2877 done:
2878 free(id_str);
2879 free(refs_str);
2880 free(ncommits_str);
2881 free(header);
2882 return err;
2885 static void
2886 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2888 struct commit_queue_entry *entry;
2889 int nscrolled = 0;
2891 entry = TAILQ_FIRST(&s->commits->head);
2892 if (s->first_displayed_entry == entry)
2893 return;
2895 entry = s->first_displayed_entry;
2896 while (entry && nscrolled < maxscroll) {
2897 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2898 if (entry) {
2899 s->first_displayed_entry = entry;
2900 nscrolled++;
2905 static const struct got_error *
2906 trigger_log_thread(struct tog_view *view, int wait)
2908 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2909 int errcode;
2911 if (!using_mock_io)
2912 halfdelay(1); /* fast refresh while loading commits */
2914 while (!ta->log_complete && !tog_thread_error &&
2915 (ta->commits_needed > 0 || ta->load_all)) {
2916 /* Wake the log thread. */
2917 errcode = pthread_cond_signal(&ta->need_commits);
2918 if (errcode)
2919 return got_error_set_errno(errcode,
2920 "pthread_cond_signal");
2923 * The mutex will be released while the view loop waits
2924 * in wgetch(), at which time the log thread will run.
2926 if (!wait)
2927 break;
2929 /* Display progress update in log view. */
2930 show_log_view(view);
2931 update_panels();
2932 doupdate();
2934 /* Wait right here while next commit is being loaded. */
2935 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2936 if (errcode)
2937 return got_error_set_errno(errcode,
2938 "pthread_cond_wait");
2940 /* Display progress update in log view. */
2941 show_log_view(view);
2942 update_panels();
2943 doupdate();
2946 return NULL;
2949 static const struct got_error *
2950 request_log_commits(struct tog_view *view)
2952 struct tog_log_view_state *state = &view->state.log;
2953 const struct got_error *err = NULL;
2955 if (state->thread_args.log_complete)
2956 return NULL;
2958 state->thread_args.commits_needed += view->nscrolled;
2959 err = trigger_log_thread(view, 1);
2960 view->nscrolled = 0;
2962 return err;
2965 static const struct got_error *
2966 log_scroll_down(struct tog_view *view, int maxscroll)
2968 struct tog_log_view_state *s = &view->state.log;
2969 const struct got_error *err = NULL;
2970 struct commit_queue_entry *pentry;
2971 int nscrolled = 0, ncommits_needed;
2973 if (s->last_displayed_entry == NULL)
2974 return NULL;
2976 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2977 if (s->commits->ncommits < ncommits_needed &&
2978 !s->thread_args.log_complete) {
2980 * Ask the log thread for required amount of commits.
2982 s->thread_args.commits_needed +=
2983 ncommits_needed - s->commits->ncommits;
2984 err = trigger_log_thread(view, 1);
2985 if (err)
2986 return err;
2989 do {
2990 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2991 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2992 break;
2994 s->last_displayed_entry = pentry ?
2995 pentry : s->last_displayed_entry;
2997 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2998 if (pentry == NULL)
2999 break;
3000 s->first_displayed_entry = pentry;
3001 } while (++nscrolled < maxscroll);
3003 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3004 view->nscrolled += nscrolled;
3005 else
3006 view->nscrolled = 0;
3008 return err;
3011 static const struct got_error *
3012 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3013 struct got_commit_object *commit, struct got_object_id *commit_id,
3014 struct tog_view *log_view, struct got_repository *repo)
3016 const struct got_error *err;
3017 struct got_object_qid *parent_id;
3018 struct tog_view *diff_view;
3020 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3021 if (diff_view == NULL)
3022 return got_error_from_errno("view_open");
3024 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3025 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3026 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3027 if (err == NULL)
3028 *new_view = diff_view;
3029 return err;
3032 static const struct got_error *
3033 tree_view_visit_subtree(struct tog_tree_view_state *s,
3034 struct got_tree_object *subtree)
3036 struct tog_parent_tree *parent;
3038 parent = calloc(1, sizeof(*parent));
3039 if (parent == NULL)
3040 return got_error_from_errno("calloc");
3042 parent->tree = s->tree;
3043 parent->first_displayed_entry = s->first_displayed_entry;
3044 parent->selected_entry = s->selected_entry;
3045 parent->selected = s->selected;
3046 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3047 s->tree = subtree;
3048 s->selected = 0;
3049 s->first_displayed_entry = NULL;
3050 return NULL;
3053 static const struct got_error *
3054 tree_view_walk_path(struct tog_tree_view_state *s,
3055 struct got_commit_object *commit, const char *path)
3057 const struct got_error *err = NULL;
3058 struct got_tree_object *tree = NULL;
3059 const char *p;
3060 char *slash, *subpath = NULL;
3062 /* Walk the path and open corresponding tree objects. */
3063 p = path;
3064 while (*p) {
3065 struct got_tree_entry *te;
3066 struct got_object_id *tree_id;
3067 char *te_name;
3069 while (p[0] == '/')
3070 p++;
3072 /* Ensure the correct subtree entry is selected. */
3073 slash = strchr(p, '/');
3074 if (slash == NULL)
3075 te_name = strdup(p);
3076 else
3077 te_name = strndup(p, slash - p);
3078 if (te_name == NULL) {
3079 err = got_error_from_errno("strndup");
3080 break;
3082 te = got_object_tree_find_entry(s->tree, te_name);
3083 if (te == NULL) {
3084 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3085 free(te_name);
3086 break;
3088 free(te_name);
3089 s->first_displayed_entry = s->selected_entry = te;
3091 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3092 break; /* jump to this file's entry */
3094 slash = strchr(p, '/');
3095 if (slash)
3096 subpath = strndup(path, slash - path);
3097 else
3098 subpath = strdup(path);
3099 if (subpath == NULL) {
3100 err = got_error_from_errno("strdup");
3101 break;
3104 err = got_object_id_by_path(&tree_id, s->repo, commit,
3105 subpath);
3106 if (err)
3107 break;
3109 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3110 free(tree_id);
3111 if (err)
3112 break;
3114 err = tree_view_visit_subtree(s, tree);
3115 if (err) {
3116 got_object_tree_close(tree);
3117 break;
3119 if (slash == NULL)
3120 break;
3121 free(subpath);
3122 subpath = NULL;
3123 p = slash;
3126 free(subpath);
3127 return err;
3130 static const struct got_error *
3131 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3132 struct commit_queue_entry *entry, const char *path,
3133 const char *head_ref_name, struct got_repository *repo)
3135 const struct got_error *err = NULL;
3136 struct tog_tree_view_state *s;
3137 struct tog_view *tree_view;
3139 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3140 if (tree_view == NULL)
3141 return got_error_from_errno("view_open");
3143 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3144 if (err)
3145 return err;
3146 s = &tree_view->state.tree;
3148 *new_view = tree_view;
3150 if (got_path_is_root_dir(path))
3151 return NULL;
3153 return tree_view_walk_path(s, entry->commit, path);
3156 static const struct got_error *
3157 block_signals_used_by_main_thread(void)
3159 sigset_t sigset;
3160 int errcode;
3162 if (sigemptyset(&sigset) == -1)
3163 return got_error_from_errno("sigemptyset");
3165 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3166 if (sigaddset(&sigset, SIGWINCH) == -1)
3167 return got_error_from_errno("sigaddset");
3168 if (sigaddset(&sigset, SIGCONT) == -1)
3169 return got_error_from_errno("sigaddset");
3170 if (sigaddset(&sigset, SIGINT) == -1)
3171 return got_error_from_errno("sigaddset");
3172 if (sigaddset(&sigset, SIGTERM) == -1)
3173 return got_error_from_errno("sigaddset");
3175 /* ncurses handles SIGTSTP */
3176 if (sigaddset(&sigset, SIGTSTP) == -1)
3177 return got_error_from_errno("sigaddset");
3179 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3180 if (errcode)
3181 return got_error_set_errno(errcode, "pthread_sigmask");
3183 return NULL;
3186 static void *
3187 log_thread(void *arg)
3189 const struct got_error *err = NULL;
3190 int errcode = 0;
3191 struct tog_log_thread_args *a = arg;
3192 int done = 0;
3195 * Sync startup with main thread such that we begin our
3196 * work once view_input() has released the mutex.
3198 errcode = pthread_mutex_lock(&tog_mutex);
3199 if (errcode) {
3200 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3201 return (void *)err;
3204 err = block_signals_used_by_main_thread();
3205 if (err) {
3206 pthread_mutex_unlock(&tog_mutex);
3207 goto done;
3210 while (!done && !err && !tog_fatal_signal_received()) {
3211 errcode = pthread_mutex_unlock(&tog_mutex);
3212 if (errcode) {
3213 err = got_error_set_errno(errcode,
3214 "pthread_mutex_unlock");
3215 goto done;
3217 err = queue_commits(a);
3218 if (err) {
3219 if (err->code != GOT_ERR_ITER_COMPLETED)
3220 goto done;
3221 err = NULL;
3222 done = 1;
3223 } else if (a->commits_needed > 0 && !a->load_all) {
3224 if (*a->limiting) {
3225 if (a->limit_match)
3226 a->commits_needed--;
3227 } else
3228 a->commits_needed--;
3231 errcode = pthread_mutex_lock(&tog_mutex);
3232 if (errcode) {
3233 err = got_error_set_errno(errcode,
3234 "pthread_mutex_lock");
3235 goto done;
3236 } else if (*a->quit)
3237 done = 1;
3238 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3239 *a->first_displayed_entry =
3240 TAILQ_FIRST(&a->limit_commits->head);
3241 *a->selected_entry = *a->first_displayed_entry;
3242 } else if (*a->first_displayed_entry == NULL) {
3243 *a->first_displayed_entry =
3244 TAILQ_FIRST(&a->real_commits->head);
3245 *a->selected_entry = *a->first_displayed_entry;
3248 errcode = pthread_cond_signal(&a->commit_loaded);
3249 if (errcode) {
3250 err = got_error_set_errno(errcode,
3251 "pthread_cond_signal");
3252 pthread_mutex_unlock(&tog_mutex);
3253 goto done;
3256 if (done)
3257 a->commits_needed = 0;
3258 else {
3259 if (a->commits_needed == 0 && !a->load_all) {
3260 errcode = pthread_cond_wait(&a->need_commits,
3261 &tog_mutex);
3262 if (errcode) {
3263 err = got_error_set_errno(errcode,
3264 "pthread_cond_wait");
3265 pthread_mutex_unlock(&tog_mutex);
3266 goto done;
3268 if (*a->quit)
3269 done = 1;
3273 a->log_complete = 1;
3274 errcode = pthread_mutex_unlock(&tog_mutex);
3275 if (errcode)
3276 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3277 done:
3278 if (err) {
3279 tog_thread_error = 1;
3280 pthread_cond_signal(&a->commit_loaded);
3282 return (void *)err;
3285 static const struct got_error *
3286 stop_log_thread(struct tog_log_view_state *s)
3288 const struct got_error *err = NULL, *thread_err = NULL;
3289 int errcode;
3291 if (s->thread) {
3292 s->quit = 1;
3293 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3294 if (errcode)
3295 return got_error_set_errno(errcode,
3296 "pthread_cond_signal");
3297 errcode = pthread_mutex_unlock(&tog_mutex);
3298 if (errcode)
3299 return got_error_set_errno(errcode,
3300 "pthread_mutex_unlock");
3301 errcode = pthread_join(s->thread, (void **)&thread_err);
3302 if (errcode)
3303 return got_error_set_errno(errcode, "pthread_join");
3304 errcode = pthread_mutex_lock(&tog_mutex);
3305 if (errcode)
3306 return got_error_set_errno(errcode,
3307 "pthread_mutex_lock");
3308 s->thread = NULL;
3311 if (s->thread_args.repo) {
3312 err = got_repo_close(s->thread_args.repo);
3313 s->thread_args.repo = NULL;
3316 if (s->thread_args.pack_fds) {
3317 const struct got_error *pack_err =
3318 got_repo_pack_fds_close(s->thread_args.pack_fds);
3319 if (err == NULL)
3320 err = pack_err;
3321 s->thread_args.pack_fds = NULL;
3324 if (s->thread_args.graph) {
3325 got_commit_graph_close(s->thread_args.graph);
3326 s->thread_args.graph = NULL;
3329 return err ? err : thread_err;
3332 static const struct got_error *
3333 close_log_view(struct tog_view *view)
3335 const struct got_error *err = NULL;
3336 struct tog_log_view_state *s = &view->state.log;
3337 int errcode;
3339 err = stop_log_thread(s);
3341 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3342 if (errcode && err == NULL)
3343 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3345 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3346 if (errcode && err == NULL)
3347 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3349 free_commits(&s->limit_commits);
3350 free_commits(&s->real_commits);
3351 free(s->in_repo_path);
3352 s->in_repo_path = NULL;
3353 free(s->start_id);
3354 s->start_id = NULL;
3355 free(s->head_ref_name);
3356 s->head_ref_name = NULL;
3357 return err;
3361 * We use two queues to implement the limit feature: first consists of
3362 * commits matching the current limit_regex; second is the real queue
3363 * of all known commits (real_commits). When the user starts limiting,
3364 * we swap queues such that all movement and displaying functionality
3365 * works with very slight change.
3367 static const struct got_error *
3368 limit_log_view(struct tog_view *view)
3370 struct tog_log_view_state *s = &view->state.log;
3371 struct commit_queue_entry *entry;
3372 struct tog_view *v = view;
3373 const struct got_error *err = NULL;
3374 char pattern[1024];
3375 int ret;
3377 if (view_is_hsplit_top(view))
3378 v = view->child;
3379 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3380 v = view->parent;
3382 /* Get the pattern */
3383 wmove(v->window, v->nlines - 1, 0);
3384 wclrtoeol(v->window);
3385 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3386 nodelay(v->window, FALSE);
3387 nocbreak();
3388 echo();
3389 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3390 cbreak();
3391 noecho();
3392 nodelay(v->window, TRUE);
3393 if (ret == ERR)
3394 return NULL;
3396 if (*pattern == '\0') {
3398 * Safety measure for the situation where the user
3399 * resets limit without previously limiting anything.
3401 if (!s->limit_view)
3402 return NULL;
3405 * User could have pressed Ctrl+L, which refreshed the
3406 * commit queues, it means we can't save previously
3407 * (before limit took place) displayed entries,
3408 * because they would point to already free'ed memory,
3409 * so we are forced to always select first entry of
3410 * the queue.
3412 s->commits = &s->real_commits;
3413 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3414 s->selected_entry = s->first_displayed_entry;
3415 s->selected = 0;
3416 s->limit_view = 0;
3418 return NULL;
3421 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3422 return NULL;
3424 s->limit_view = 1;
3426 /* Clear the screen while loading limit view */
3427 s->first_displayed_entry = NULL;
3428 s->last_displayed_entry = NULL;
3429 s->selected_entry = NULL;
3430 s->commits = &s->limit_commits;
3432 /* Prepare limit queue for new search */
3433 free_commits(&s->limit_commits);
3434 s->limit_commits.ncommits = 0;
3436 /* First process commits, which are in queue already */
3437 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3438 int have_match = 0;
3440 err = match_commit(&have_match, entry->id,
3441 entry->commit, &s->limit_regex);
3442 if (err)
3443 return err;
3445 if (have_match) {
3446 struct commit_queue_entry *matched;
3448 matched = alloc_commit_queue_entry(entry->commit,
3449 entry->id);
3450 if (matched == NULL) {
3451 err = got_error_from_errno(
3452 "alloc_commit_queue_entry");
3453 break;
3455 matched->commit = entry->commit;
3456 got_object_commit_retain(entry->commit);
3458 matched->idx = s->limit_commits.ncommits;
3459 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3460 matched, entry);
3461 s->limit_commits.ncommits++;
3465 /* Second process all the commits, until we fill the screen */
3466 if (s->limit_commits.ncommits < view->nlines - 1 &&
3467 !s->thread_args.log_complete) {
3468 s->thread_args.commits_needed +=
3469 view->nlines - s->limit_commits.ncommits - 1;
3470 err = trigger_log_thread(view, 1);
3471 if (err)
3472 return err;
3475 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3476 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3477 s->selected = 0;
3479 return NULL;
3482 static const struct got_error *
3483 search_start_log_view(struct tog_view *view)
3485 struct tog_log_view_state *s = &view->state.log;
3487 s->matched_entry = NULL;
3488 s->search_entry = NULL;
3489 return NULL;
3492 static const struct got_error *
3493 search_next_log_view(struct tog_view *view)
3495 const struct got_error *err = NULL;
3496 struct tog_log_view_state *s = &view->state.log;
3497 struct commit_queue_entry *entry;
3499 /* Display progress update in log view. */
3500 show_log_view(view);
3501 update_panels();
3502 doupdate();
3504 if (s->search_entry) {
3505 int errcode, ch;
3506 errcode = pthread_mutex_unlock(&tog_mutex);
3507 if (errcode)
3508 return got_error_set_errno(errcode,
3509 "pthread_mutex_unlock");
3510 ch = wgetch(view->window);
3511 errcode = pthread_mutex_lock(&tog_mutex);
3512 if (errcode)
3513 return got_error_set_errno(errcode,
3514 "pthread_mutex_lock");
3515 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3516 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3517 return NULL;
3519 if (view->searching == TOG_SEARCH_FORWARD)
3520 entry = TAILQ_NEXT(s->search_entry, entry);
3521 else
3522 entry = TAILQ_PREV(s->search_entry,
3523 commit_queue_head, entry);
3524 } else if (s->matched_entry) {
3526 * If the user has moved the cursor after we hit a match,
3527 * the position from where we should continue searching
3528 * might have changed.
3530 if (view->searching == TOG_SEARCH_FORWARD)
3531 entry = TAILQ_NEXT(s->selected_entry, entry);
3532 else
3533 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3534 entry);
3535 } else {
3536 entry = s->selected_entry;
3539 while (1) {
3540 int have_match = 0;
3542 if (entry == NULL) {
3543 if (s->thread_args.log_complete ||
3544 view->searching == TOG_SEARCH_BACKWARD) {
3545 view->search_next_done =
3546 (s->matched_entry == NULL ?
3547 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3548 s->search_entry = NULL;
3549 return NULL;
3552 * Poke the log thread for more commits and return,
3553 * allowing the main loop to make progress. Search
3554 * will resume at s->search_entry once we come back.
3556 s->thread_args.commits_needed++;
3557 return trigger_log_thread(view, 0);
3560 err = match_commit(&have_match, entry->id, entry->commit,
3561 &view->regex);
3562 if (err)
3563 break;
3564 if (have_match) {
3565 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3566 s->matched_entry = entry;
3567 break;
3570 s->search_entry = entry;
3571 if (view->searching == TOG_SEARCH_FORWARD)
3572 entry = TAILQ_NEXT(entry, entry);
3573 else
3574 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3577 if (s->matched_entry) {
3578 int cur = s->selected_entry->idx;
3579 while (cur < s->matched_entry->idx) {
3580 err = input_log_view(NULL, view, KEY_DOWN);
3581 if (err)
3582 return err;
3583 cur++;
3585 while (cur > s->matched_entry->idx) {
3586 err = input_log_view(NULL, view, KEY_UP);
3587 if (err)
3588 return err;
3589 cur--;
3593 s->search_entry = NULL;
3595 return NULL;
3598 static const struct got_error *
3599 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3600 struct got_repository *repo, const char *head_ref_name,
3601 const char *in_repo_path, int log_branches)
3603 const struct got_error *err = NULL;
3604 struct tog_log_view_state *s = &view->state.log;
3605 struct got_repository *thread_repo = NULL;
3606 struct got_commit_graph *thread_graph = NULL;
3607 int errcode;
3609 if (in_repo_path != s->in_repo_path) {
3610 free(s->in_repo_path);
3611 s->in_repo_path = strdup(in_repo_path);
3612 if (s->in_repo_path == NULL) {
3613 err = got_error_from_errno("strdup");
3614 goto done;
3618 /* The commit queue only contains commits being displayed. */
3619 TAILQ_INIT(&s->real_commits.head);
3620 s->real_commits.ncommits = 0;
3621 s->commits = &s->real_commits;
3623 TAILQ_INIT(&s->limit_commits.head);
3624 s->limit_view = 0;
3625 s->limit_commits.ncommits = 0;
3627 s->repo = repo;
3628 if (head_ref_name) {
3629 s->head_ref_name = strdup(head_ref_name);
3630 if (s->head_ref_name == NULL) {
3631 err = got_error_from_errno("strdup");
3632 goto done;
3635 s->start_id = got_object_id_dup(start_id);
3636 if (s->start_id == NULL) {
3637 err = got_error_from_errno("got_object_id_dup");
3638 goto done;
3640 s->log_branches = log_branches;
3641 s->use_committer = 1;
3643 STAILQ_INIT(&s->colors);
3644 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3645 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3646 get_color_value("TOG_COLOR_COMMIT"));
3647 if (err)
3648 goto done;
3649 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3650 get_color_value("TOG_COLOR_AUTHOR"));
3651 if (err) {
3652 free_colors(&s->colors);
3653 goto done;
3655 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3656 get_color_value("TOG_COLOR_DATE"));
3657 if (err) {
3658 free_colors(&s->colors);
3659 goto done;
3663 view->show = show_log_view;
3664 view->input = input_log_view;
3665 view->resize = resize_log_view;
3666 view->close = close_log_view;
3667 view->search_start = search_start_log_view;
3668 view->search_next = search_next_log_view;
3670 if (s->thread_args.pack_fds == NULL) {
3671 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3672 if (err)
3673 goto done;
3675 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3676 s->thread_args.pack_fds);
3677 if (err)
3678 goto done;
3679 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3680 !s->log_branches);
3681 if (err)
3682 goto done;
3683 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3684 s->repo, NULL, NULL);
3685 if (err)
3686 goto done;
3688 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3689 if (errcode) {
3690 err = got_error_set_errno(errcode, "pthread_cond_init");
3691 goto done;
3693 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3694 if (errcode) {
3695 err = got_error_set_errno(errcode, "pthread_cond_init");
3696 goto done;
3699 s->thread_args.commits_needed = view->nlines;
3700 s->thread_args.graph = thread_graph;
3701 s->thread_args.real_commits = &s->real_commits;
3702 s->thread_args.limit_commits = &s->limit_commits;
3703 s->thread_args.in_repo_path = s->in_repo_path;
3704 s->thread_args.start_id = s->start_id;
3705 s->thread_args.repo = thread_repo;
3706 s->thread_args.log_complete = 0;
3707 s->thread_args.quit = &s->quit;
3708 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3709 s->thread_args.selected_entry = &s->selected_entry;
3710 s->thread_args.searching = &view->searching;
3711 s->thread_args.search_next_done = &view->search_next_done;
3712 s->thread_args.regex = &view->regex;
3713 s->thread_args.limiting = &s->limit_view;
3714 s->thread_args.limit_regex = &s->limit_regex;
3715 s->thread_args.limit_commits = &s->limit_commits;
3716 done:
3717 if (err) {
3718 if (view->close == NULL)
3719 close_log_view(view);
3720 view_close(view);
3722 return err;
3725 static const struct got_error *
3726 show_log_view(struct tog_view *view)
3728 const struct got_error *err;
3729 struct tog_log_view_state *s = &view->state.log;
3731 if (s->thread == NULL) {
3732 int errcode = pthread_create(&s->thread, NULL, log_thread,
3733 &s->thread_args);
3734 if (errcode)
3735 return got_error_set_errno(errcode, "pthread_create");
3736 if (s->thread_args.commits_needed > 0) {
3737 err = trigger_log_thread(view, 1);
3738 if (err)
3739 return err;
3743 return draw_commits(view);
3746 static void
3747 log_move_cursor_up(struct tog_view *view, int page, int home)
3749 struct tog_log_view_state *s = &view->state.log;
3751 if (s->first_displayed_entry == NULL)
3752 return;
3753 if (s->selected_entry->idx == 0)
3754 view->count = 0;
3756 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3757 || home)
3758 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3760 if (!page && !home && s->selected > 0)
3761 --s->selected;
3762 else
3763 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3765 select_commit(s);
3766 return;
3769 static const struct got_error *
3770 log_move_cursor_down(struct tog_view *view, int page)
3772 struct tog_log_view_state *s = &view->state.log;
3773 const struct got_error *err = NULL;
3774 int eos = view->nlines - 2;
3776 if (s->first_displayed_entry == NULL)
3777 return NULL;
3779 if (s->thread_args.log_complete &&
3780 s->selected_entry->idx >= s->commits->ncommits - 1)
3781 return NULL;
3783 if (view_is_hsplit_top(view))
3784 --eos; /* border consumes the last line */
3786 if (!page) {
3787 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3788 ++s->selected;
3789 else
3790 err = log_scroll_down(view, 1);
3791 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3792 struct commit_queue_entry *entry;
3793 int n;
3795 s->selected = 0;
3796 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3797 s->last_displayed_entry = entry;
3798 for (n = 0; n <= eos; n++) {
3799 if (entry == NULL)
3800 break;
3801 s->first_displayed_entry = entry;
3802 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3804 if (n > 0)
3805 s->selected = n - 1;
3806 } else {
3807 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3808 s->thread_args.log_complete)
3809 s->selected += MIN(page,
3810 s->commits->ncommits - s->selected_entry->idx - 1);
3811 else
3812 err = log_scroll_down(view, page);
3814 if (err)
3815 return err;
3818 * We might necessarily overshoot in horizontal
3819 * splits; if so, select the last displayed commit.
3821 if (s->first_displayed_entry && s->last_displayed_entry) {
3822 s->selected = MIN(s->selected,
3823 s->last_displayed_entry->idx -
3824 s->first_displayed_entry->idx);
3827 select_commit(s);
3829 if (s->thread_args.log_complete &&
3830 s->selected_entry->idx == s->commits->ncommits - 1)
3831 view->count = 0;
3833 return NULL;
3836 static void
3837 view_get_split(struct tog_view *view, int *y, int *x)
3839 *x = 0;
3840 *y = 0;
3842 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3843 if (view->child && view->child->resized_y)
3844 *y = view->child->resized_y;
3845 else if (view->resized_y)
3846 *y = view->resized_y;
3847 else
3848 *y = view_split_begin_y(view->lines);
3849 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3850 if (view->child && view->child->resized_x)
3851 *x = view->child->resized_x;
3852 else if (view->resized_x)
3853 *x = view->resized_x;
3854 else
3855 *x = view_split_begin_x(view->begin_x);
3859 /* Split view horizontally at y and offset view->state->selected line. */
3860 static const struct got_error *
3861 view_init_hsplit(struct tog_view *view, int y)
3863 const struct got_error *err = NULL;
3865 view->nlines = y;
3866 view->ncols = COLS;
3867 err = view_resize(view);
3868 if (err)
3869 return err;
3871 err = offset_selection_down(view);
3873 return err;
3876 static const struct got_error *
3877 log_goto_line(struct tog_view *view, int nlines)
3879 const struct got_error *err = NULL;
3880 struct tog_log_view_state *s = &view->state.log;
3881 int g, idx = s->selected_entry->idx;
3883 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3884 return NULL;
3886 g = view->gline;
3887 view->gline = 0;
3889 if (g >= s->first_displayed_entry->idx + 1 &&
3890 g <= s->last_displayed_entry->idx + 1 &&
3891 g - s->first_displayed_entry->idx - 1 < nlines) {
3892 s->selected = g - s->first_displayed_entry->idx - 1;
3893 select_commit(s);
3894 return NULL;
3897 if (idx + 1 < g) {
3898 err = log_move_cursor_down(view, g - idx - 1);
3899 if (!err && g > s->selected_entry->idx + 1)
3900 err = log_move_cursor_down(view,
3901 g - s->first_displayed_entry->idx - 1);
3902 if (err)
3903 return err;
3904 } else if (idx + 1 > g)
3905 log_move_cursor_up(view, idx - g + 1, 0);
3907 if (g < nlines && s->first_displayed_entry->idx == 0)
3908 s->selected = g - 1;
3910 select_commit(s);
3911 return NULL;
3915 static void
3916 horizontal_scroll_input(struct tog_view *view, int ch)
3919 switch (ch) {
3920 case KEY_LEFT:
3921 case 'h':
3922 view->x -= MIN(view->x, 2);
3923 if (view->x <= 0)
3924 view->count = 0;
3925 break;
3926 case KEY_RIGHT:
3927 case 'l':
3928 if (view->x + view->ncols / 2 < view->maxx)
3929 view->x += 2;
3930 else
3931 view->count = 0;
3932 break;
3933 case '0':
3934 view->x = 0;
3935 break;
3936 case '$':
3937 view->x = MAX(view->maxx - view->ncols / 2, 0);
3938 view->count = 0;
3939 break;
3940 default:
3941 break;
3945 static const struct got_error *
3946 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3948 const struct got_error *err = NULL;
3949 struct tog_log_view_state *s = &view->state.log;
3950 int eos, nscroll;
3952 if (s->thread_args.load_all) {
3953 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3954 s->thread_args.load_all = 0;
3955 else if (s->thread_args.log_complete) {
3956 err = log_move_cursor_down(view, s->commits->ncommits);
3957 s->thread_args.load_all = 0;
3959 if (err)
3960 return err;
3963 eos = nscroll = view->nlines - 1;
3964 if (view_is_hsplit_top(view))
3965 --eos; /* border */
3967 if (view->gline)
3968 return log_goto_line(view, eos);
3970 switch (ch) {
3971 case '&':
3972 err = limit_log_view(view);
3973 break;
3974 case 'q':
3975 s->quit = 1;
3976 break;
3977 case '0':
3978 case '$':
3979 case KEY_RIGHT:
3980 case 'l':
3981 case KEY_LEFT:
3982 case 'h':
3983 horizontal_scroll_input(view, ch);
3984 break;
3985 case 'k':
3986 case KEY_UP:
3987 case '<':
3988 case ',':
3989 case CTRL('p'):
3990 log_move_cursor_up(view, 0, 0);
3991 break;
3992 case 'g':
3993 case '=':
3994 case KEY_HOME:
3995 log_move_cursor_up(view, 0, 1);
3996 view->count = 0;
3997 break;
3998 case CTRL('u'):
3999 case 'u':
4000 nscroll /= 2;
4001 /* FALL THROUGH */
4002 case KEY_PPAGE:
4003 case CTRL('b'):
4004 case 'b':
4005 log_move_cursor_up(view, nscroll, 0);
4006 break;
4007 case 'j':
4008 case KEY_DOWN:
4009 case '>':
4010 case '.':
4011 case CTRL('n'):
4012 err = log_move_cursor_down(view, 0);
4013 break;
4014 case '@':
4015 s->use_committer = !s->use_committer;
4016 view->action = s->use_committer ?
4017 "show committer" : "show commit author";
4018 break;
4019 case 'G':
4020 case '*':
4021 case KEY_END: {
4022 /* We don't know yet how many commits, so we're forced to
4023 * traverse them all. */
4024 view->count = 0;
4025 s->thread_args.load_all = 1;
4026 if (!s->thread_args.log_complete)
4027 return trigger_log_thread(view, 0);
4028 err = log_move_cursor_down(view, s->commits->ncommits);
4029 s->thread_args.load_all = 0;
4030 break;
4032 case CTRL('d'):
4033 case 'd':
4034 nscroll /= 2;
4035 /* FALL THROUGH */
4036 case KEY_NPAGE:
4037 case CTRL('f'):
4038 case 'f':
4039 case ' ':
4040 err = log_move_cursor_down(view, nscroll);
4041 break;
4042 case KEY_RESIZE:
4043 if (s->selected > view->nlines - 2)
4044 s->selected = view->nlines - 2;
4045 if (s->selected > s->commits->ncommits - 1)
4046 s->selected = s->commits->ncommits - 1;
4047 select_commit(s);
4048 if (s->commits->ncommits < view->nlines - 1 &&
4049 !s->thread_args.log_complete) {
4050 s->thread_args.commits_needed += (view->nlines - 1) -
4051 s->commits->ncommits;
4052 err = trigger_log_thread(view, 1);
4054 break;
4055 case KEY_ENTER:
4056 case '\r':
4057 view->count = 0;
4058 if (s->selected_entry == NULL)
4059 break;
4060 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4061 break;
4062 case 'T':
4063 view->count = 0;
4064 if (s->selected_entry == NULL)
4065 break;
4066 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4067 break;
4068 case KEY_BACKSPACE:
4069 case CTRL('l'):
4070 case 'B':
4071 view->count = 0;
4072 if (ch == KEY_BACKSPACE &&
4073 got_path_is_root_dir(s->in_repo_path))
4074 break;
4075 err = stop_log_thread(s);
4076 if (err)
4077 return err;
4078 if (ch == KEY_BACKSPACE) {
4079 char *parent_path;
4080 err = got_path_dirname(&parent_path, s->in_repo_path);
4081 if (err)
4082 return err;
4083 free(s->in_repo_path);
4084 s->in_repo_path = parent_path;
4085 s->thread_args.in_repo_path = s->in_repo_path;
4086 } else if (ch == CTRL('l')) {
4087 struct got_object_id *start_id;
4088 err = got_repo_match_object_id(&start_id, NULL,
4089 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4090 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4091 if (err) {
4092 if (s->head_ref_name == NULL ||
4093 err->code != GOT_ERR_NOT_REF)
4094 return err;
4095 /* Try to cope with deleted references. */
4096 free(s->head_ref_name);
4097 s->head_ref_name = NULL;
4098 err = got_repo_match_object_id(&start_id,
4099 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4100 &tog_refs, s->repo);
4101 if (err)
4102 return err;
4104 free(s->start_id);
4105 s->start_id = start_id;
4106 s->thread_args.start_id = s->start_id;
4107 } else /* 'B' */
4108 s->log_branches = !s->log_branches;
4110 if (s->thread_args.pack_fds == NULL) {
4111 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4112 if (err)
4113 return err;
4115 err = got_repo_open(&s->thread_args.repo,
4116 got_repo_get_path(s->repo), NULL,
4117 s->thread_args.pack_fds);
4118 if (err)
4119 return err;
4120 tog_free_refs();
4121 err = tog_load_refs(s->repo, 0);
4122 if (err)
4123 return err;
4124 err = got_commit_graph_open(&s->thread_args.graph,
4125 s->in_repo_path, !s->log_branches);
4126 if (err)
4127 return err;
4128 err = got_commit_graph_iter_start(s->thread_args.graph,
4129 s->start_id, s->repo, NULL, NULL);
4130 if (err)
4131 return err;
4132 free_commits(&s->real_commits);
4133 free_commits(&s->limit_commits);
4134 s->first_displayed_entry = NULL;
4135 s->last_displayed_entry = NULL;
4136 s->selected_entry = NULL;
4137 s->selected = 0;
4138 s->thread_args.log_complete = 0;
4139 s->quit = 0;
4140 s->thread_args.commits_needed = view->lines;
4141 s->matched_entry = NULL;
4142 s->search_entry = NULL;
4143 view->offset = 0;
4144 break;
4145 case 'R':
4146 view->count = 0;
4147 err = view_request_new(new_view, view, TOG_VIEW_REF);
4148 break;
4149 default:
4150 view->count = 0;
4151 break;
4154 return err;
4157 static const struct got_error *
4158 apply_unveil(const char *repo_path, const char *worktree_path)
4160 const struct got_error *error;
4162 #ifdef PROFILE
4163 if (unveil("gmon.out", "rwc") != 0)
4164 return got_error_from_errno2("unveil", "gmon.out");
4165 #endif
4166 if (repo_path && unveil(repo_path, "r") != 0)
4167 return got_error_from_errno2("unveil", repo_path);
4169 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4170 return got_error_from_errno2("unveil", worktree_path);
4172 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4173 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4175 error = got_privsep_unveil_exec_helpers();
4176 if (error != NULL)
4177 return error;
4179 if (unveil(NULL, NULL) != 0)
4180 return got_error_from_errno("unveil");
4182 return NULL;
4185 static const struct got_error *
4186 init_mock_term(const char *test_script_path)
4188 const struct got_error *err = NULL;
4189 int in;
4191 if (test_script_path == NULL || *test_script_path == '\0')
4192 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4194 tog_io.f = fopen(test_script_path, "re");
4195 if (tog_io.f == NULL) {
4196 err = got_error_from_errno_fmt("fopen: %s",
4197 test_script_path);
4198 goto done;
4201 /* test mode, we don't want any output */
4202 tog_io.cout = fopen("/dev/null", "w+");
4203 if (tog_io.cout == NULL) {
4204 err = got_error_from_errno2("fopen", "/dev/null");
4205 goto done;
4208 in = dup(fileno(tog_io.cout));
4209 if (in == -1) {
4210 err = got_error_from_errno("dup");
4211 goto done;
4213 tog_io.cin = fdopen(in, "r");
4214 if (tog_io.cin == NULL) {
4215 err = got_error_from_errno("fdopen");
4216 close(in);
4217 goto done;
4220 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4221 err = got_error_from_errno("fseeko");
4222 goto done;
4225 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4226 err = got_error_msg(GOT_ERR_IO,
4227 "newterm: failed to initialise curses");
4229 using_mock_io = 1;
4231 done:
4232 if (err)
4233 tog_io_close();
4234 return err;
4237 static void
4238 init_curses(void)
4241 * Override default signal handlers before starting ncurses.
4242 * This should prevent ncurses from installing its own
4243 * broken cleanup() signal handler.
4245 signal(SIGWINCH, tog_sigwinch);
4246 signal(SIGPIPE, tog_sigpipe);
4247 signal(SIGCONT, tog_sigcont);
4248 signal(SIGINT, tog_sigint);
4249 signal(SIGTERM, tog_sigterm);
4251 if (using_mock_io) /* In test mode we use a fake terminal */
4252 return;
4254 initscr();
4256 cbreak();
4257 halfdelay(1); /* Fast refresh while initial view is loading. */
4258 noecho();
4259 nonl();
4260 intrflush(stdscr, FALSE);
4261 keypad(stdscr, TRUE);
4262 curs_set(0);
4263 if (getenv("TOG_COLORS") != NULL) {
4264 start_color();
4265 use_default_colors();
4268 return;
4271 static const struct got_error *
4272 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4273 struct got_repository *repo, struct got_worktree *worktree)
4275 const struct got_error *err = NULL;
4277 if (argc == 0) {
4278 *in_repo_path = strdup("/");
4279 if (*in_repo_path == NULL)
4280 return got_error_from_errno("strdup");
4281 return NULL;
4284 if (worktree) {
4285 const char *prefix = got_worktree_get_path_prefix(worktree);
4286 char *p;
4288 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4289 if (err)
4290 return err;
4291 if (asprintf(in_repo_path, "%s%s%s", prefix,
4292 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4293 p) == -1) {
4294 err = got_error_from_errno("asprintf");
4295 *in_repo_path = NULL;
4297 free(p);
4298 } else
4299 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4301 return err;
4304 static const struct got_error *
4305 cmd_log(int argc, char *argv[])
4307 const struct got_error *error;
4308 struct got_repository *repo = NULL;
4309 struct got_worktree *worktree = NULL;
4310 struct got_object_id *start_id = NULL;
4311 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4312 char *start_commit = NULL, *label = NULL;
4313 struct got_reference *ref = NULL;
4314 const char *head_ref_name = NULL;
4315 int ch, log_branches = 0;
4316 struct tog_view *view;
4317 int *pack_fds = NULL;
4319 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4320 switch (ch) {
4321 case 'b':
4322 log_branches = 1;
4323 break;
4324 case 'c':
4325 start_commit = optarg;
4326 break;
4327 case 'r':
4328 repo_path = realpath(optarg, NULL);
4329 if (repo_path == NULL)
4330 return got_error_from_errno2("realpath",
4331 optarg);
4332 break;
4333 default:
4334 usage_log();
4335 /* NOTREACHED */
4339 argc -= optind;
4340 argv += optind;
4342 if (argc > 1)
4343 usage_log();
4345 error = got_repo_pack_fds_open(&pack_fds);
4346 if (error != NULL)
4347 goto done;
4349 if (repo_path == NULL) {
4350 cwd = getcwd(NULL, 0);
4351 if (cwd == NULL)
4352 return got_error_from_errno("getcwd");
4353 error = got_worktree_open(&worktree, cwd);
4354 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4355 goto done;
4356 if (worktree)
4357 repo_path =
4358 strdup(got_worktree_get_repo_path(worktree));
4359 else
4360 repo_path = strdup(cwd);
4361 if (repo_path == NULL) {
4362 error = got_error_from_errno("strdup");
4363 goto done;
4367 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4368 if (error != NULL)
4369 goto done;
4371 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4372 repo, worktree);
4373 if (error)
4374 goto done;
4376 init_curses();
4378 error = apply_unveil(got_repo_get_path(repo),
4379 worktree ? got_worktree_get_root_path(worktree) : NULL);
4380 if (error)
4381 goto done;
4383 /* already loaded by tog_log_with_path()? */
4384 if (TAILQ_EMPTY(&tog_refs)) {
4385 error = tog_load_refs(repo, 0);
4386 if (error)
4387 goto done;
4390 if (start_commit == NULL) {
4391 error = got_repo_match_object_id(&start_id, &label,
4392 worktree ? got_worktree_get_head_ref_name(worktree) :
4393 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4394 if (error)
4395 goto done;
4396 head_ref_name = label;
4397 } else {
4398 error = got_ref_open(&ref, repo, start_commit, 0);
4399 if (error == NULL)
4400 head_ref_name = got_ref_get_name(ref);
4401 else if (error->code != GOT_ERR_NOT_REF)
4402 goto done;
4403 error = got_repo_match_object_id(&start_id, NULL,
4404 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4405 if (error)
4406 goto done;
4409 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4410 if (view == NULL) {
4411 error = got_error_from_errno("view_open");
4412 goto done;
4414 error = open_log_view(view, start_id, repo, head_ref_name,
4415 in_repo_path, log_branches);
4416 if (error)
4417 goto done;
4418 if (worktree) {
4419 /* Release work tree lock. */
4420 got_worktree_close(worktree);
4421 worktree = NULL;
4423 error = view_loop(view);
4424 done:
4425 free(in_repo_path);
4426 free(repo_path);
4427 free(cwd);
4428 free(start_id);
4429 free(label);
4430 if (ref)
4431 got_ref_close(ref);
4432 if (repo) {
4433 const struct got_error *close_err = got_repo_close(repo);
4434 if (error == NULL)
4435 error = close_err;
4437 if (worktree)
4438 got_worktree_close(worktree);
4439 if (pack_fds) {
4440 const struct got_error *pack_err =
4441 got_repo_pack_fds_close(pack_fds);
4442 if (error == NULL)
4443 error = pack_err;
4445 tog_free_refs();
4446 return error;
4449 __dead static void
4450 usage_diff(void)
4452 endwin();
4453 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4454 "object1 object2\n", getprogname());
4455 exit(1);
4458 static int
4459 match_line(const char *line, regex_t *regex, size_t nmatch,
4460 regmatch_t *regmatch)
4462 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4465 static struct tog_color *
4466 match_color(struct tog_colors *colors, const char *line)
4468 struct tog_color *tc = NULL;
4470 STAILQ_FOREACH(tc, colors, entry) {
4471 if (match_line(line, &tc->regex, 0, NULL))
4472 return tc;
4475 return NULL;
4478 static const struct got_error *
4479 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4480 WINDOW *window, int skipcol, regmatch_t *regmatch)
4482 const struct got_error *err = NULL;
4483 char *exstr = NULL;
4484 wchar_t *wline = NULL;
4485 int rme, rms, n, width, scrollx;
4486 int width0 = 0, width1 = 0, width2 = 0;
4487 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4489 *wtotal = 0;
4491 rms = regmatch->rm_so;
4492 rme = regmatch->rm_eo;
4494 err = expand_tab(&exstr, line);
4495 if (err)
4496 return err;
4498 /* Split the line into 3 segments, according to match offsets. */
4499 seg0 = strndup(exstr, rms);
4500 if (seg0 == NULL) {
4501 err = got_error_from_errno("strndup");
4502 goto done;
4504 seg1 = strndup(exstr + rms, rme - rms);
4505 if (seg1 == NULL) {
4506 err = got_error_from_errno("strndup");
4507 goto done;
4509 seg2 = strdup(exstr + rme);
4510 if (seg2 == NULL) {
4511 err = got_error_from_errno("strndup");
4512 goto done;
4515 /* draw up to matched token if we haven't scrolled past it */
4516 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4517 col_tab_align, 1);
4518 if (err)
4519 goto done;
4520 n = MAX(width0 - skipcol, 0);
4521 if (n) {
4522 free(wline);
4523 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4524 wlimit, col_tab_align, 1);
4525 if (err)
4526 goto done;
4527 waddwstr(window, &wline[scrollx]);
4528 wlimit -= width;
4529 *wtotal += width;
4532 if (wlimit > 0) {
4533 int i = 0, w = 0;
4534 size_t wlen;
4536 free(wline);
4537 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4538 col_tab_align, 1);
4539 if (err)
4540 goto done;
4541 wlen = wcslen(wline);
4542 while (i < wlen) {
4543 width = wcwidth(wline[i]);
4544 if (width == -1) {
4545 /* should not happen, tabs are expanded */
4546 err = got_error(GOT_ERR_RANGE);
4547 goto done;
4549 if (width0 + w + width > skipcol)
4550 break;
4551 w += width;
4552 i++;
4554 /* draw (visible part of) matched token (if scrolled into it) */
4555 if (width1 - w > 0) {
4556 wattron(window, A_STANDOUT);
4557 waddwstr(window, &wline[i]);
4558 wattroff(window, A_STANDOUT);
4559 wlimit -= (width1 - w);
4560 *wtotal += (width1 - w);
4564 if (wlimit > 0) { /* draw rest of line */
4565 free(wline);
4566 if (skipcol > width0 + width1) {
4567 err = format_line(&wline, &width2, &scrollx, seg2,
4568 skipcol - (width0 + width1), wlimit,
4569 col_tab_align, 1);
4570 if (err)
4571 goto done;
4572 waddwstr(window, &wline[scrollx]);
4573 } else {
4574 err = format_line(&wline, &width2, NULL, seg2, 0,
4575 wlimit, col_tab_align, 1);
4576 if (err)
4577 goto done;
4578 waddwstr(window, wline);
4580 *wtotal += width2;
4582 done:
4583 free(wline);
4584 free(exstr);
4585 free(seg0);
4586 free(seg1);
4587 free(seg2);
4588 return err;
4591 static int
4592 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4594 FILE *f = NULL;
4595 int *eof, *first, *selected;
4597 if (view->type == TOG_VIEW_DIFF) {
4598 struct tog_diff_view_state *s = &view->state.diff;
4600 first = &s->first_displayed_line;
4601 selected = first;
4602 eof = &s->eof;
4603 f = s->f;
4604 } else if (view->type == TOG_VIEW_HELP) {
4605 struct tog_help_view_state *s = &view->state.help;
4607 first = &s->first_displayed_line;
4608 selected = first;
4609 eof = &s->eof;
4610 f = s->f;
4611 } else if (view->type == TOG_VIEW_BLAME) {
4612 struct tog_blame_view_state *s = &view->state.blame;
4614 first = &s->first_displayed_line;
4615 selected = &s->selected_line;
4616 eof = &s->eof;
4617 f = s->blame.f;
4618 } else
4619 return 0;
4621 /* Center gline in the middle of the page like vi(1). */
4622 if (*lineno < view->gline - (view->nlines - 3) / 2)
4623 return 0;
4624 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4625 rewind(f);
4626 *eof = 0;
4627 *first = 1;
4628 *lineno = 0;
4629 *nprinted = 0;
4630 return 0;
4633 *selected = view->gline <= (view->nlines - 3) / 2 ?
4634 view->gline : (view->nlines - 3) / 2 + 1;
4635 view->gline = 0;
4637 return 1;
4640 static const struct got_error *
4641 draw_file(struct tog_view *view, const char *header)
4643 struct tog_diff_view_state *s = &view->state.diff;
4644 regmatch_t *regmatch = &view->regmatch;
4645 const struct got_error *err;
4646 int nprinted = 0;
4647 char *line;
4648 size_t linesize = 0;
4649 ssize_t linelen;
4650 wchar_t *wline;
4651 int width;
4652 int max_lines = view->nlines;
4653 int nlines = s->nlines;
4654 off_t line_offset;
4656 s->lineno = s->first_displayed_line - 1;
4657 line_offset = s->lines[s->first_displayed_line - 1].offset;
4658 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4659 return got_error_from_errno("fseek");
4661 werase(view->window);
4663 if (view->gline > s->nlines - 1)
4664 view->gline = s->nlines - 1;
4666 if (header) {
4667 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4668 1 : view->gline - (view->nlines - 3) / 2 :
4669 s->lineno + s->selected_line;
4671 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4672 return got_error_from_errno("asprintf");
4673 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4674 0, 0);
4675 free(line);
4676 if (err)
4677 return err;
4679 if (view_needs_focus_indication(view))
4680 wstandout(view->window);
4681 waddwstr(view->window, wline);
4682 free(wline);
4683 wline = NULL;
4684 while (width++ < view->ncols)
4685 waddch(view->window, ' ');
4686 if (view_needs_focus_indication(view))
4687 wstandend(view->window);
4689 if (max_lines <= 1)
4690 return NULL;
4691 max_lines--;
4694 s->eof = 0;
4695 view->maxx = 0;
4696 line = NULL;
4697 while (max_lines > 0 && nprinted < max_lines) {
4698 enum got_diff_line_type linetype;
4699 attr_t attr = 0;
4701 linelen = getline(&line, &linesize, s->f);
4702 if (linelen == -1) {
4703 if (feof(s->f)) {
4704 s->eof = 1;
4705 break;
4707 free(line);
4708 return got_ferror(s->f, GOT_ERR_IO);
4711 if (++s->lineno < s->first_displayed_line)
4712 continue;
4713 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4714 continue;
4715 if (s->lineno == view->hiline)
4716 attr = A_STANDOUT;
4718 /* Set view->maxx based on full line length. */
4719 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4720 view->x ? 1 : 0);
4721 if (err) {
4722 free(line);
4723 return err;
4725 view->maxx = MAX(view->maxx, width);
4726 free(wline);
4727 wline = NULL;
4729 linetype = s->lines[s->lineno].type;
4730 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4731 linetype < GOT_DIFF_LINE_CONTEXT)
4732 attr |= COLOR_PAIR(linetype);
4733 if (attr)
4734 wattron(view->window, attr);
4735 if (s->first_displayed_line + nprinted == s->matched_line &&
4736 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4737 err = add_matched_line(&width, line, view->ncols, 0,
4738 view->window, view->x, regmatch);
4739 if (err) {
4740 free(line);
4741 return err;
4743 } else {
4744 int skip;
4745 err = format_line(&wline, &width, &skip, line,
4746 view->x, view->ncols, 0, view->x ? 1 : 0);
4747 if (err) {
4748 free(line);
4749 return err;
4751 waddwstr(view->window, &wline[skip]);
4752 free(wline);
4753 wline = NULL;
4755 if (s->lineno == view->hiline) {
4756 /* highlight full gline length */
4757 while (width++ < view->ncols)
4758 waddch(view->window, ' ');
4759 } else {
4760 if (width <= view->ncols - 1)
4761 waddch(view->window, '\n');
4763 if (attr)
4764 wattroff(view->window, attr);
4765 if (++nprinted == 1)
4766 s->first_displayed_line = s->lineno;
4768 free(line);
4769 if (nprinted >= 1)
4770 s->last_displayed_line = s->first_displayed_line +
4771 (nprinted - 1);
4772 else
4773 s->last_displayed_line = s->first_displayed_line;
4775 view_border(view);
4777 if (s->eof) {
4778 while (nprinted < view->nlines) {
4779 waddch(view->window, '\n');
4780 nprinted++;
4783 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4784 view->ncols, 0, 0);
4785 if (err) {
4786 return err;
4789 wstandout(view->window);
4790 waddwstr(view->window, wline);
4791 free(wline);
4792 wline = NULL;
4793 wstandend(view->window);
4796 return NULL;
4799 static char *
4800 get_datestr(time_t *time, char *datebuf)
4802 struct tm mytm, *tm;
4803 char *p, *s;
4805 tm = gmtime_r(time, &mytm);
4806 if (tm == NULL)
4807 return NULL;
4808 s = asctime_r(tm, datebuf);
4809 if (s == NULL)
4810 return NULL;
4811 p = strchr(s, '\n');
4812 if (p)
4813 *p = '\0';
4814 return s;
4817 static const struct got_error *
4818 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4819 off_t off, uint8_t type)
4821 struct got_diff_line *p;
4823 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4824 if (p == NULL)
4825 return got_error_from_errno("reallocarray");
4826 *lines = p;
4827 (*lines)[*nlines].offset = off;
4828 (*lines)[*nlines].type = type;
4829 (*nlines)++;
4831 return NULL;
4834 static const struct got_error *
4835 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4836 struct got_diff_line *s_lines, size_t s_nlines)
4838 struct got_diff_line *p;
4839 char buf[BUFSIZ];
4840 size_t i, r;
4842 if (fseeko(src, 0L, SEEK_SET) == -1)
4843 return got_error_from_errno("fseeko");
4845 for (;;) {
4846 r = fread(buf, 1, sizeof(buf), src);
4847 if (r == 0) {
4848 if (ferror(src))
4849 return got_error_from_errno("fread");
4850 if (feof(src))
4851 break;
4853 if (fwrite(buf, 1, r, dst) != r)
4854 return got_ferror(dst, GOT_ERR_IO);
4857 if (s_nlines == 0 && *d_nlines == 0)
4858 return NULL;
4861 * If commit info was in dst, increment line offsets
4862 * of the appended diff content, but skip s_lines[0]
4863 * because offset zero is already in *d_lines.
4865 if (*d_nlines > 0) {
4866 for (i = 1; i < s_nlines; ++i)
4867 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4869 if (s_nlines > 0) {
4870 --s_nlines;
4871 ++s_lines;
4875 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4876 if (p == NULL) {
4877 /* d_lines is freed in close_diff_view() */
4878 return got_error_from_errno("reallocarray");
4881 *d_lines = p;
4883 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4884 *d_nlines += s_nlines;
4886 return NULL;
4889 static const struct got_error *
4890 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4891 struct got_object_id *commit_id, struct got_reflist_head *refs,
4892 struct got_repository *repo, int ignore_ws, int force_text_diff,
4893 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4895 const struct got_error *err = NULL;
4896 char datebuf[26], *datestr;
4897 struct got_commit_object *commit;
4898 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4899 time_t committer_time;
4900 const char *author, *committer;
4901 char *refs_str = NULL;
4902 struct got_pathlist_entry *pe;
4903 off_t outoff = 0;
4904 int n;
4906 if (refs) {
4907 err = build_refs_str(&refs_str, refs, commit_id, repo);
4908 if (err)
4909 return err;
4912 err = got_object_open_as_commit(&commit, repo, commit_id);
4913 if (err)
4914 return err;
4916 err = got_object_id_str(&id_str, commit_id);
4917 if (err) {
4918 err = got_error_from_errno("got_object_id_str");
4919 goto done;
4922 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4923 if (err)
4924 goto done;
4926 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4927 refs_str ? refs_str : "", refs_str ? ")" : "");
4928 if (n < 0) {
4929 err = got_error_from_errno("fprintf");
4930 goto done;
4932 outoff += n;
4933 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4934 if (err)
4935 goto done;
4937 n = fprintf(outfile, "from: %s\n",
4938 got_object_commit_get_author(commit));
4939 if (n < 0) {
4940 err = got_error_from_errno("fprintf");
4941 goto done;
4943 outoff += n;
4944 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4945 if (err)
4946 goto done;
4948 author = got_object_commit_get_author(commit);
4949 committer = got_object_commit_get_committer(commit);
4950 if (strcmp(author, committer) != 0) {
4951 n = fprintf(outfile, "via: %s\n", committer);
4952 if (n < 0) {
4953 err = got_error_from_errno("fprintf");
4954 goto done;
4956 outoff += n;
4957 err = add_line_metadata(lines, nlines, outoff,
4958 GOT_DIFF_LINE_AUTHOR);
4959 if (err)
4960 goto done;
4962 committer_time = got_object_commit_get_committer_time(commit);
4963 datestr = get_datestr(&committer_time, datebuf);
4964 if (datestr) {
4965 n = fprintf(outfile, "date: %s UTC\n", datestr);
4966 if (n < 0) {
4967 err = got_error_from_errno("fprintf");
4968 goto done;
4970 outoff += n;
4971 err = add_line_metadata(lines, nlines, outoff,
4972 GOT_DIFF_LINE_DATE);
4973 if (err)
4974 goto done;
4976 if (got_object_commit_get_nparents(commit) > 1) {
4977 const struct got_object_id_queue *parent_ids;
4978 struct got_object_qid *qid;
4979 int pn = 1;
4980 parent_ids = got_object_commit_get_parent_ids(commit);
4981 STAILQ_FOREACH(qid, parent_ids, entry) {
4982 err = got_object_id_str(&id_str, &qid->id);
4983 if (err)
4984 goto done;
4985 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4986 if (n < 0) {
4987 err = got_error_from_errno("fprintf");
4988 goto done;
4990 outoff += n;
4991 err = add_line_metadata(lines, nlines, outoff,
4992 GOT_DIFF_LINE_META);
4993 if (err)
4994 goto done;
4995 free(id_str);
4996 id_str = NULL;
5000 err = got_object_commit_get_logmsg(&logmsg, commit);
5001 if (err)
5002 goto done;
5003 s = logmsg;
5004 while ((line = strsep(&s, "\n")) != NULL) {
5005 n = fprintf(outfile, "%s\n", line);
5006 if (n < 0) {
5007 err = got_error_from_errno("fprintf");
5008 goto done;
5010 outoff += n;
5011 err = add_line_metadata(lines, nlines, outoff,
5012 GOT_DIFF_LINE_LOGMSG);
5013 if (err)
5014 goto done;
5017 TAILQ_FOREACH(pe, dsa->paths, entry) {
5018 struct got_diff_changed_path *cp = pe->data;
5019 int pad = dsa->max_path_len - pe->path_len + 1;
5021 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5022 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5023 dsa->rm_cols + 1, cp->rm);
5024 if (n < 0) {
5025 err = got_error_from_errno("fprintf");
5026 goto done;
5028 outoff += n;
5029 err = add_line_metadata(lines, nlines, outoff,
5030 GOT_DIFF_LINE_CHANGES);
5031 if (err)
5032 goto done;
5035 fputc('\n', outfile);
5036 outoff++;
5037 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5038 if (err)
5039 goto done;
5041 n = fprintf(outfile,
5042 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5043 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5044 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5045 if (n < 0) {
5046 err = got_error_from_errno("fprintf");
5047 goto done;
5049 outoff += n;
5050 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5051 if (err)
5052 goto done;
5054 fputc('\n', outfile);
5055 outoff++;
5056 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5057 done:
5058 free(id_str);
5059 free(logmsg);
5060 free(refs_str);
5061 got_object_commit_close(commit);
5062 if (err) {
5063 free(*lines);
5064 *lines = NULL;
5065 *nlines = 0;
5067 return err;
5070 static const struct got_error *
5071 create_diff(struct tog_diff_view_state *s)
5073 const struct got_error *err = NULL;
5074 FILE *f = NULL, *tmp_diff_file = NULL;
5075 int obj_type;
5076 struct got_diff_line *lines = NULL;
5077 struct got_pathlist_head changed_paths;
5079 TAILQ_INIT(&changed_paths);
5081 free(s->lines);
5082 s->lines = malloc(sizeof(*s->lines));
5083 if (s->lines == NULL)
5084 return got_error_from_errno("malloc");
5085 s->nlines = 0;
5087 f = got_opentemp();
5088 if (f == NULL) {
5089 err = got_error_from_errno("got_opentemp");
5090 goto done;
5092 tmp_diff_file = got_opentemp();
5093 if (tmp_diff_file == NULL) {
5094 err = got_error_from_errno("got_opentemp");
5095 goto done;
5097 if (s->f && fclose(s->f) == EOF) {
5098 err = got_error_from_errno("fclose");
5099 goto done;
5101 s->f = f;
5103 if (s->id1)
5104 err = got_object_get_type(&obj_type, s->repo, s->id1);
5105 else
5106 err = got_object_get_type(&obj_type, s->repo, s->id2);
5107 if (err)
5108 goto done;
5110 switch (obj_type) {
5111 case GOT_OBJ_TYPE_BLOB:
5112 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5113 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5114 s->label1, s->label2, tog_diff_algo, s->diff_context,
5115 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5116 s->f);
5117 break;
5118 case GOT_OBJ_TYPE_TREE:
5119 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5120 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5121 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5122 s->force_text_diff, NULL, s->repo, s->f);
5123 break;
5124 case GOT_OBJ_TYPE_COMMIT: {
5125 const struct got_object_id_queue *parent_ids;
5126 struct got_object_qid *pid;
5127 struct got_commit_object *commit2;
5128 struct got_reflist_head *refs;
5129 size_t nlines = 0;
5130 struct got_diffstat_cb_arg dsa = {
5131 0, 0, 0, 0, 0, 0,
5132 &changed_paths,
5133 s->ignore_whitespace,
5134 s->force_text_diff,
5135 tog_diff_algo
5138 lines = malloc(sizeof(*lines));
5139 if (lines == NULL) {
5140 err = got_error_from_errno("malloc");
5141 goto done;
5144 /* build diff first in tmp file then append to commit info */
5145 err = got_diff_objects_as_commits(&lines, &nlines,
5146 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5147 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5148 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5149 if (err)
5150 break;
5152 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5153 if (err)
5154 goto done;
5155 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5156 /* Show commit info if we're diffing to a parent/root commit. */
5157 if (s->id1 == NULL) {
5158 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5159 refs, s->repo, s->ignore_whitespace,
5160 s->force_text_diff, &dsa, s->f);
5161 if (err)
5162 goto done;
5163 } else {
5164 parent_ids = got_object_commit_get_parent_ids(commit2);
5165 STAILQ_FOREACH(pid, parent_ids, entry) {
5166 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5167 err = write_commit_info(&s->lines,
5168 &s->nlines, s->id2, refs, s->repo,
5169 s->ignore_whitespace,
5170 s->force_text_diff, &dsa, s->f);
5171 if (err)
5172 goto done;
5173 break;
5177 got_object_commit_close(commit2);
5179 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5180 lines, nlines);
5181 break;
5183 default:
5184 err = got_error(GOT_ERR_OBJ_TYPE);
5185 break;
5187 done:
5188 free(lines);
5189 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5190 if (s->f && fflush(s->f) != 0 && err == NULL)
5191 err = got_error_from_errno("fflush");
5192 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5193 err = got_error_from_errno("fclose");
5194 return err;
5197 static void
5198 diff_view_indicate_progress(struct tog_view *view)
5200 mvwaddstr(view->window, 0, 0, "diffing...");
5201 update_panels();
5202 doupdate();
5205 static const struct got_error *
5206 search_start_diff_view(struct tog_view *view)
5208 struct tog_diff_view_state *s = &view->state.diff;
5210 s->matched_line = 0;
5211 return NULL;
5214 static void
5215 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5216 size_t *nlines, int **first, int **last, int **match, int **selected)
5218 struct tog_diff_view_state *s = &view->state.diff;
5220 *f = s->f;
5221 *nlines = s->nlines;
5222 *line_offsets = NULL;
5223 *match = &s->matched_line;
5224 *first = &s->first_displayed_line;
5225 *last = &s->last_displayed_line;
5226 *selected = &s->selected_line;
5229 static const struct got_error *
5230 search_next_view_match(struct tog_view *view)
5232 const struct got_error *err = NULL;
5233 FILE *f;
5234 int lineno;
5235 char *line = NULL;
5236 size_t linesize = 0;
5237 ssize_t linelen;
5238 off_t *line_offsets;
5239 size_t nlines = 0;
5240 int *first, *last, *match, *selected;
5242 if (!view->search_setup)
5243 return got_error_msg(GOT_ERR_NOT_IMPL,
5244 "view search not supported");
5245 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5246 &match, &selected);
5248 if (!view->searching) {
5249 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5250 return NULL;
5253 if (*match) {
5254 if (view->searching == TOG_SEARCH_FORWARD)
5255 lineno = *first + 1;
5256 else
5257 lineno = *first - 1;
5258 } else
5259 lineno = *first - 1 + *selected;
5261 while (1) {
5262 off_t offset;
5264 if (lineno <= 0 || lineno > nlines) {
5265 if (*match == 0) {
5266 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5267 break;
5270 if (view->searching == TOG_SEARCH_FORWARD)
5271 lineno = 1;
5272 else
5273 lineno = nlines;
5276 offset = view->type == TOG_VIEW_DIFF ?
5277 view->state.diff.lines[lineno - 1].offset :
5278 line_offsets[lineno - 1];
5279 if (fseeko(f, offset, SEEK_SET) != 0) {
5280 free(line);
5281 return got_error_from_errno("fseeko");
5283 linelen = getline(&line, &linesize, f);
5284 if (linelen != -1) {
5285 char *exstr;
5286 err = expand_tab(&exstr, line);
5287 if (err)
5288 break;
5289 if (match_line(exstr, &view->regex, 1,
5290 &view->regmatch)) {
5291 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5292 *match = lineno;
5293 free(exstr);
5294 break;
5296 free(exstr);
5298 if (view->searching == TOG_SEARCH_FORWARD)
5299 lineno++;
5300 else
5301 lineno--;
5303 free(line);
5305 if (*match) {
5306 *first = *match;
5307 *selected = 1;
5310 return err;
5313 static const struct got_error *
5314 close_diff_view(struct tog_view *view)
5316 const struct got_error *err = NULL;
5317 struct tog_diff_view_state *s = &view->state.diff;
5319 free(s->id1);
5320 s->id1 = NULL;
5321 free(s->id2);
5322 s->id2 = NULL;
5323 if (s->f && fclose(s->f) == EOF)
5324 err = got_error_from_errno("fclose");
5325 s->f = NULL;
5326 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5327 err = got_error_from_errno("fclose");
5328 s->f1 = NULL;
5329 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5330 err = got_error_from_errno("fclose");
5331 s->f2 = NULL;
5332 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5333 err = got_error_from_errno("close");
5334 s->fd1 = -1;
5335 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5336 err = got_error_from_errno("close");
5337 s->fd2 = -1;
5338 free(s->lines);
5339 s->lines = NULL;
5340 s->nlines = 0;
5341 return err;
5344 static const struct got_error *
5345 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5346 struct got_object_id *id2, const char *label1, const char *label2,
5347 int diff_context, int ignore_whitespace, int force_text_diff,
5348 struct tog_view *parent_view, struct got_repository *repo)
5350 const struct got_error *err;
5351 struct tog_diff_view_state *s = &view->state.diff;
5353 memset(s, 0, sizeof(*s));
5354 s->fd1 = -1;
5355 s->fd2 = -1;
5357 if (id1 != NULL && id2 != NULL) {
5358 int type1, type2;
5360 err = got_object_get_type(&type1, repo, id1);
5361 if (err)
5362 goto done;
5363 err = got_object_get_type(&type2, repo, id2);
5364 if (err)
5365 goto done;
5367 if (type1 != type2) {
5368 err = got_error(GOT_ERR_OBJ_TYPE);
5369 goto done;
5372 s->first_displayed_line = 1;
5373 s->last_displayed_line = view->nlines;
5374 s->selected_line = 1;
5375 s->repo = repo;
5376 s->id1 = id1;
5377 s->id2 = id2;
5378 s->label1 = label1;
5379 s->label2 = label2;
5381 if (id1) {
5382 s->id1 = got_object_id_dup(id1);
5383 if (s->id1 == NULL) {
5384 err = got_error_from_errno("got_object_id_dup");
5385 goto done;
5387 } else
5388 s->id1 = NULL;
5390 s->id2 = got_object_id_dup(id2);
5391 if (s->id2 == NULL) {
5392 err = got_error_from_errno("got_object_id_dup");
5393 goto done;
5396 s->f1 = got_opentemp();
5397 if (s->f1 == NULL) {
5398 err = got_error_from_errno("got_opentemp");
5399 goto done;
5402 s->f2 = got_opentemp();
5403 if (s->f2 == NULL) {
5404 err = got_error_from_errno("got_opentemp");
5405 goto done;
5408 s->fd1 = got_opentempfd();
5409 if (s->fd1 == -1) {
5410 err = got_error_from_errno("got_opentempfd");
5411 goto done;
5414 s->fd2 = got_opentempfd();
5415 if (s->fd2 == -1) {
5416 err = got_error_from_errno("got_opentempfd");
5417 goto done;
5420 s->diff_context = diff_context;
5421 s->ignore_whitespace = ignore_whitespace;
5422 s->force_text_diff = force_text_diff;
5423 s->parent_view = parent_view;
5424 s->repo = repo;
5426 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5427 int rc;
5429 rc = init_pair(GOT_DIFF_LINE_MINUS,
5430 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5431 if (rc != ERR)
5432 rc = init_pair(GOT_DIFF_LINE_PLUS,
5433 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5434 if (rc != ERR)
5435 rc = init_pair(GOT_DIFF_LINE_HUNK,
5436 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5437 if (rc != ERR)
5438 rc = init_pair(GOT_DIFF_LINE_META,
5439 get_color_value("TOG_COLOR_DIFF_META"), -1);
5440 if (rc != ERR)
5441 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5442 get_color_value("TOG_COLOR_DIFF_META"), -1);
5443 if (rc != ERR)
5444 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5445 get_color_value("TOG_COLOR_DIFF_META"), -1);
5446 if (rc != ERR)
5447 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5448 get_color_value("TOG_COLOR_DIFF_META"), -1);
5449 if (rc != ERR)
5450 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5451 get_color_value("TOG_COLOR_AUTHOR"), -1);
5452 if (rc != ERR)
5453 rc = init_pair(GOT_DIFF_LINE_DATE,
5454 get_color_value("TOG_COLOR_DATE"), -1);
5455 if (rc == ERR) {
5456 err = got_error(GOT_ERR_RANGE);
5457 goto done;
5461 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5462 view_is_splitscreen(view))
5463 show_log_view(parent_view); /* draw border */
5464 diff_view_indicate_progress(view);
5466 err = create_diff(s);
5468 view->show = show_diff_view;
5469 view->input = input_diff_view;
5470 view->reset = reset_diff_view;
5471 view->close = close_diff_view;
5472 view->search_start = search_start_diff_view;
5473 view->search_setup = search_setup_diff_view;
5474 view->search_next = search_next_view_match;
5475 done:
5476 if (err) {
5477 if (view->close == NULL)
5478 close_diff_view(view);
5479 view_close(view);
5481 return err;
5484 static const struct got_error *
5485 show_diff_view(struct tog_view *view)
5487 const struct got_error *err;
5488 struct tog_diff_view_state *s = &view->state.diff;
5489 char *id_str1 = NULL, *id_str2, *header;
5490 const char *label1, *label2;
5492 if (s->id1) {
5493 err = got_object_id_str(&id_str1, s->id1);
5494 if (err)
5495 return err;
5496 label1 = s->label1 ? s->label1 : id_str1;
5497 } else
5498 label1 = "/dev/null";
5500 err = got_object_id_str(&id_str2, s->id2);
5501 if (err)
5502 return err;
5503 label2 = s->label2 ? s->label2 : id_str2;
5505 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5506 err = got_error_from_errno("asprintf");
5507 free(id_str1);
5508 free(id_str2);
5509 return err;
5511 free(id_str1);
5512 free(id_str2);
5514 err = draw_file(view, header);
5515 free(header);
5516 return err;
5519 static const struct got_error *
5520 set_selected_commit(struct tog_diff_view_state *s,
5521 struct commit_queue_entry *entry)
5523 const struct got_error *err;
5524 const struct got_object_id_queue *parent_ids;
5525 struct got_commit_object *selected_commit;
5526 struct got_object_qid *pid;
5528 free(s->id2);
5529 s->id2 = got_object_id_dup(entry->id);
5530 if (s->id2 == NULL)
5531 return got_error_from_errno("got_object_id_dup");
5533 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5534 if (err)
5535 return err;
5536 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5537 free(s->id1);
5538 pid = STAILQ_FIRST(parent_ids);
5539 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5540 got_object_commit_close(selected_commit);
5541 return NULL;
5544 static const struct got_error *
5545 reset_diff_view(struct tog_view *view)
5547 struct tog_diff_view_state *s = &view->state.diff;
5549 view->count = 0;
5550 wclear(view->window);
5551 s->first_displayed_line = 1;
5552 s->last_displayed_line = view->nlines;
5553 s->matched_line = 0;
5554 diff_view_indicate_progress(view);
5555 return create_diff(s);
5558 static void
5559 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5561 int start, i;
5563 i = start = s->first_displayed_line - 1;
5565 while (s->lines[i].type != type) {
5566 if (i == 0)
5567 i = s->nlines - 1;
5568 if (--i == start)
5569 return; /* do nothing, requested type not in file */
5572 s->selected_line = 1;
5573 s->first_displayed_line = i;
5576 static void
5577 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5579 int start, i;
5581 i = start = s->first_displayed_line + 1;
5583 while (s->lines[i].type != type) {
5584 if (i == s->nlines - 1)
5585 i = 0;
5586 if (++i == start)
5587 return; /* do nothing, requested type not in file */
5590 s->selected_line = 1;
5591 s->first_displayed_line = i;
5594 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5595 int, int, int);
5596 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5597 int, int);
5599 static const struct got_error *
5600 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5602 const struct got_error *err = NULL;
5603 struct tog_diff_view_state *s = &view->state.diff;
5604 struct tog_log_view_state *ls;
5605 struct commit_queue_entry *old_selected_entry;
5606 char *line = NULL;
5607 size_t linesize = 0;
5608 ssize_t linelen;
5609 int i, nscroll = view->nlines - 1, up = 0;
5611 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5613 switch (ch) {
5614 case '0':
5615 case '$':
5616 case KEY_RIGHT:
5617 case 'l':
5618 case KEY_LEFT:
5619 case 'h':
5620 horizontal_scroll_input(view, ch);
5621 break;
5622 case 'a':
5623 case 'w':
5624 if (ch == 'a') {
5625 s->force_text_diff = !s->force_text_diff;
5626 view->action = s->force_text_diff ?
5627 "force ASCII text enabled" :
5628 "force ASCII text disabled";
5630 else if (ch == 'w') {
5631 s->ignore_whitespace = !s->ignore_whitespace;
5632 view->action = s->ignore_whitespace ?
5633 "ignore whitespace enabled" :
5634 "ignore whitespace disabled";
5636 err = reset_diff_view(view);
5637 break;
5638 case 'g':
5639 case KEY_HOME:
5640 s->first_displayed_line = 1;
5641 view->count = 0;
5642 break;
5643 case 'G':
5644 case KEY_END:
5645 view->count = 0;
5646 if (s->eof)
5647 break;
5649 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5650 s->eof = 1;
5651 break;
5652 case 'k':
5653 case KEY_UP:
5654 case CTRL('p'):
5655 if (s->first_displayed_line > 1)
5656 s->first_displayed_line--;
5657 else
5658 view->count = 0;
5659 break;
5660 case CTRL('u'):
5661 case 'u':
5662 nscroll /= 2;
5663 /* FALL THROUGH */
5664 case KEY_PPAGE:
5665 case CTRL('b'):
5666 case 'b':
5667 if (s->first_displayed_line == 1) {
5668 view->count = 0;
5669 break;
5671 i = 0;
5672 while (i++ < nscroll && s->first_displayed_line > 1)
5673 s->first_displayed_line--;
5674 break;
5675 case 'j':
5676 case KEY_DOWN:
5677 case CTRL('n'):
5678 if (!s->eof)
5679 s->first_displayed_line++;
5680 else
5681 view->count = 0;
5682 break;
5683 case CTRL('d'):
5684 case 'd':
5685 nscroll /= 2;
5686 /* FALL THROUGH */
5687 case KEY_NPAGE:
5688 case CTRL('f'):
5689 case 'f':
5690 case ' ':
5691 if (s->eof) {
5692 view->count = 0;
5693 break;
5695 i = 0;
5696 while (!s->eof && i++ < nscroll) {
5697 linelen = getline(&line, &linesize, s->f);
5698 s->first_displayed_line++;
5699 if (linelen == -1) {
5700 if (feof(s->f)) {
5701 s->eof = 1;
5702 } else
5703 err = got_ferror(s->f, GOT_ERR_IO);
5704 break;
5707 free(line);
5708 break;
5709 case '(':
5710 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5711 break;
5712 case ')':
5713 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5714 break;
5715 case '{':
5716 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5717 break;
5718 case '}':
5719 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5720 break;
5721 case '[':
5722 if (s->diff_context > 0) {
5723 s->diff_context--;
5724 s->matched_line = 0;
5725 diff_view_indicate_progress(view);
5726 err = create_diff(s);
5727 if (s->first_displayed_line + view->nlines - 1 >
5728 s->nlines) {
5729 s->first_displayed_line = 1;
5730 s->last_displayed_line = view->nlines;
5732 } else
5733 view->count = 0;
5734 break;
5735 case ']':
5736 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5737 s->diff_context++;
5738 s->matched_line = 0;
5739 diff_view_indicate_progress(view);
5740 err = create_diff(s);
5741 } else
5742 view->count = 0;
5743 break;
5744 case '<':
5745 case ',':
5746 case 'K':
5747 up = 1;
5748 /* FALL THROUGH */
5749 case '>':
5750 case '.':
5751 case 'J':
5752 if (s->parent_view == NULL) {
5753 view->count = 0;
5754 break;
5756 s->parent_view->count = view->count;
5758 if (s->parent_view->type == TOG_VIEW_LOG) {
5759 ls = &s->parent_view->state.log;
5760 old_selected_entry = ls->selected_entry;
5762 err = input_log_view(NULL, s->parent_view,
5763 up ? KEY_UP : KEY_DOWN);
5764 if (err)
5765 break;
5766 view->count = s->parent_view->count;
5768 if (old_selected_entry == ls->selected_entry)
5769 break;
5771 err = set_selected_commit(s, ls->selected_entry);
5772 if (err)
5773 break;
5774 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5775 struct tog_blame_view_state *bs;
5776 struct got_object_id *id, *prev_id;
5778 bs = &s->parent_view->state.blame;
5779 prev_id = get_annotation_for_line(bs->blame.lines,
5780 bs->blame.nlines, bs->last_diffed_line);
5782 err = input_blame_view(&view, s->parent_view,
5783 up ? KEY_UP : KEY_DOWN);
5784 if (err)
5785 break;
5786 view->count = s->parent_view->count;
5788 if (prev_id == NULL)
5789 break;
5790 id = get_selected_commit_id(bs->blame.lines,
5791 bs->blame.nlines, bs->first_displayed_line,
5792 bs->selected_line);
5793 if (id == NULL)
5794 break;
5796 if (!got_object_id_cmp(prev_id, id))
5797 break;
5799 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5800 if (err)
5801 break;
5803 s->first_displayed_line = 1;
5804 s->last_displayed_line = view->nlines;
5805 s->matched_line = 0;
5806 view->x = 0;
5808 diff_view_indicate_progress(view);
5809 err = create_diff(s);
5810 break;
5811 default:
5812 view->count = 0;
5813 break;
5816 return err;
5819 static const struct got_error *
5820 cmd_diff(int argc, char *argv[])
5822 const struct got_error *error;
5823 struct got_repository *repo = NULL;
5824 struct got_worktree *worktree = NULL;
5825 struct got_object_id *id1 = NULL, *id2 = NULL;
5826 char *repo_path = NULL, *cwd = NULL;
5827 char *id_str1 = NULL, *id_str2 = NULL;
5828 char *label1 = NULL, *label2 = NULL;
5829 int diff_context = 3, ignore_whitespace = 0;
5830 int ch, force_text_diff = 0;
5831 const char *errstr;
5832 struct tog_view *view;
5833 int *pack_fds = NULL;
5835 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5836 switch (ch) {
5837 case 'a':
5838 force_text_diff = 1;
5839 break;
5840 case 'C':
5841 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5842 &errstr);
5843 if (errstr != NULL)
5844 errx(1, "number of context lines is %s: %s",
5845 errstr, errstr);
5846 break;
5847 case 'r':
5848 repo_path = realpath(optarg, NULL);
5849 if (repo_path == NULL)
5850 return got_error_from_errno2("realpath",
5851 optarg);
5852 got_path_strip_trailing_slashes(repo_path);
5853 break;
5854 case 'w':
5855 ignore_whitespace = 1;
5856 break;
5857 default:
5858 usage_diff();
5859 /* NOTREACHED */
5863 argc -= optind;
5864 argv += optind;
5866 if (argc == 0) {
5867 usage_diff(); /* TODO show local worktree changes */
5868 } else if (argc == 2) {
5869 id_str1 = argv[0];
5870 id_str2 = argv[1];
5871 } else
5872 usage_diff();
5874 error = got_repo_pack_fds_open(&pack_fds);
5875 if (error)
5876 goto done;
5878 if (repo_path == NULL) {
5879 cwd = getcwd(NULL, 0);
5880 if (cwd == NULL)
5881 return got_error_from_errno("getcwd");
5882 error = got_worktree_open(&worktree, cwd);
5883 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5884 goto done;
5885 if (worktree)
5886 repo_path =
5887 strdup(got_worktree_get_repo_path(worktree));
5888 else
5889 repo_path = strdup(cwd);
5890 if (repo_path == NULL) {
5891 error = got_error_from_errno("strdup");
5892 goto done;
5896 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5897 if (error)
5898 goto done;
5900 init_curses();
5902 error = apply_unveil(got_repo_get_path(repo), NULL);
5903 if (error)
5904 goto done;
5906 error = tog_load_refs(repo, 0);
5907 if (error)
5908 goto done;
5910 error = got_repo_match_object_id(&id1, &label1, id_str1,
5911 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5912 if (error)
5913 goto done;
5915 error = got_repo_match_object_id(&id2, &label2, id_str2,
5916 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5917 if (error)
5918 goto done;
5920 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5921 if (view == NULL) {
5922 error = got_error_from_errno("view_open");
5923 goto done;
5925 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5926 ignore_whitespace, force_text_diff, NULL, repo);
5927 if (error)
5928 goto done;
5929 error = view_loop(view);
5930 done:
5931 free(label1);
5932 free(label2);
5933 free(repo_path);
5934 free(cwd);
5935 if (repo) {
5936 const struct got_error *close_err = got_repo_close(repo);
5937 if (error == NULL)
5938 error = close_err;
5940 if (worktree)
5941 got_worktree_close(worktree);
5942 if (pack_fds) {
5943 const struct got_error *pack_err =
5944 got_repo_pack_fds_close(pack_fds);
5945 if (error == NULL)
5946 error = pack_err;
5948 tog_free_refs();
5949 return error;
5952 __dead static void
5953 usage_blame(void)
5955 endwin();
5956 fprintf(stderr,
5957 "usage: %s blame [-c commit] [-r repository-path] path\n",
5958 getprogname());
5959 exit(1);
5962 struct tog_blame_line {
5963 int annotated;
5964 struct got_object_id *id;
5967 static const struct got_error *
5968 draw_blame(struct tog_view *view)
5970 struct tog_blame_view_state *s = &view->state.blame;
5971 struct tog_blame *blame = &s->blame;
5972 regmatch_t *regmatch = &view->regmatch;
5973 const struct got_error *err;
5974 int lineno = 0, nprinted = 0;
5975 char *line = NULL;
5976 size_t linesize = 0;
5977 ssize_t linelen;
5978 wchar_t *wline;
5979 int width;
5980 struct tog_blame_line *blame_line;
5981 struct got_object_id *prev_id = NULL;
5982 char *id_str;
5983 struct tog_color *tc;
5985 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5986 if (err)
5987 return err;
5989 rewind(blame->f);
5990 werase(view->window);
5992 if (asprintf(&line, "commit %s", id_str) == -1) {
5993 err = got_error_from_errno("asprintf");
5994 free(id_str);
5995 return err;
5998 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5999 free(line);
6000 line = NULL;
6001 if (err)
6002 return err;
6003 if (view_needs_focus_indication(view))
6004 wstandout(view->window);
6005 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6006 if (tc)
6007 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6008 waddwstr(view->window, wline);
6009 while (width++ < view->ncols)
6010 waddch(view->window, ' ');
6011 if (tc)
6012 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6013 if (view_needs_focus_indication(view))
6014 wstandend(view->window);
6015 free(wline);
6016 wline = NULL;
6018 if (view->gline > blame->nlines)
6019 view->gline = blame->nlines;
6021 if (tog_io.wait_for_ui) {
6022 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6023 int rc;
6025 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6026 if (rc)
6027 return got_error_set_errno(rc, "pthread_cond_wait");
6028 tog_io.wait_for_ui = 0;
6031 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6032 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6033 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6034 free(id_str);
6035 return got_error_from_errno("asprintf");
6037 free(id_str);
6038 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6039 free(line);
6040 line = NULL;
6041 if (err)
6042 return err;
6043 waddwstr(view->window, wline);
6044 free(wline);
6045 wline = NULL;
6046 if (width < view->ncols - 1)
6047 waddch(view->window, '\n');
6049 s->eof = 0;
6050 view->maxx = 0;
6051 while (nprinted < view->nlines - 2) {
6052 linelen = getline(&line, &linesize, blame->f);
6053 if (linelen == -1) {
6054 if (feof(blame->f)) {
6055 s->eof = 1;
6056 break;
6058 free(line);
6059 return got_ferror(blame->f, GOT_ERR_IO);
6061 if (++lineno < s->first_displayed_line)
6062 continue;
6063 if (view->gline && !gotoline(view, &lineno, &nprinted))
6064 continue;
6066 /* Set view->maxx based on full line length. */
6067 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6068 if (err) {
6069 free(line);
6070 return err;
6072 free(wline);
6073 wline = NULL;
6074 view->maxx = MAX(view->maxx, width);
6076 if (nprinted == s->selected_line - 1)
6077 wstandout(view->window);
6079 if (blame->nlines > 0) {
6080 blame_line = &blame->lines[lineno - 1];
6081 if (blame_line->annotated && prev_id &&
6082 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6083 !(nprinted == s->selected_line - 1)) {
6084 waddstr(view->window, " ");
6085 } else if (blame_line->annotated) {
6086 char *id_str;
6087 err = got_object_id_str(&id_str,
6088 blame_line->id);
6089 if (err) {
6090 free(line);
6091 return err;
6093 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6094 if (tc)
6095 wattr_on(view->window,
6096 COLOR_PAIR(tc->colorpair), NULL);
6097 wprintw(view->window, "%.8s", id_str);
6098 if (tc)
6099 wattr_off(view->window,
6100 COLOR_PAIR(tc->colorpair), NULL);
6101 free(id_str);
6102 prev_id = blame_line->id;
6103 } else {
6104 waddstr(view->window, "........");
6105 prev_id = NULL;
6107 } else {
6108 waddstr(view->window, "........");
6109 prev_id = NULL;
6112 if (nprinted == s->selected_line - 1)
6113 wstandend(view->window);
6114 waddstr(view->window, " ");
6116 if (view->ncols <= 9) {
6117 width = 9;
6118 } else if (s->first_displayed_line + nprinted ==
6119 s->matched_line &&
6120 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6121 err = add_matched_line(&width, line, view->ncols - 9, 9,
6122 view->window, view->x, regmatch);
6123 if (err) {
6124 free(line);
6125 return err;
6127 width += 9;
6128 } else {
6129 int skip;
6130 err = format_line(&wline, &width, &skip, line,
6131 view->x, view->ncols - 9, 9, 1);
6132 if (err) {
6133 free(line);
6134 return err;
6136 waddwstr(view->window, &wline[skip]);
6137 width += 9;
6138 free(wline);
6139 wline = NULL;
6142 if (width <= view->ncols - 1)
6143 waddch(view->window, '\n');
6144 if (++nprinted == 1)
6145 s->first_displayed_line = lineno;
6147 free(line);
6148 s->last_displayed_line = lineno;
6150 view_border(view);
6152 return NULL;
6155 static const struct got_error *
6156 blame_cb(void *arg, int nlines, int lineno,
6157 struct got_commit_object *commit, struct got_object_id *id)
6159 const struct got_error *err = NULL;
6160 struct tog_blame_cb_args *a = arg;
6161 struct tog_blame_line *line;
6162 int errcode;
6164 if (nlines != a->nlines ||
6165 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6166 return got_error(GOT_ERR_RANGE);
6168 errcode = pthread_mutex_lock(&tog_mutex);
6169 if (errcode)
6170 return got_error_set_errno(errcode, "pthread_mutex_lock");
6172 if (*a->quit) { /* user has quit the blame view */
6173 err = got_error(GOT_ERR_ITER_COMPLETED);
6174 goto done;
6177 if (lineno == -1)
6178 goto done; /* no change in this commit */
6180 line = &a->lines[lineno - 1];
6181 if (line->annotated)
6182 goto done;
6184 line->id = got_object_id_dup(id);
6185 if (line->id == NULL) {
6186 err = got_error_from_errno("got_object_id_dup");
6187 goto done;
6189 line->annotated = 1;
6190 done:
6191 errcode = pthread_mutex_unlock(&tog_mutex);
6192 if (errcode)
6193 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6194 return err;
6197 static void *
6198 blame_thread(void *arg)
6200 const struct got_error *err, *close_err;
6201 struct tog_blame_thread_args *ta = arg;
6202 struct tog_blame_cb_args *a = ta->cb_args;
6203 int errcode, fd1 = -1, fd2 = -1;
6204 FILE *f1 = NULL, *f2 = NULL;
6206 fd1 = got_opentempfd();
6207 if (fd1 == -1)
6208 return (void *)got_error_from_errno("got_opentempfd");
6210 fd2 = got_opentempfd();
6211 if (fd2 == -1) {
6212 err = got_error_from_errno("got_opentempfd");
6213 goto done;
6216 f1 = got_opentemp();
6217 if (f1 == NULL) {
6218 err = (void *)got_error_from_errno("got_opentemp");
6219 goto done;
6221 f2 = got_opentemp();
6222 if (f2 == NULL) {
6223 err = (void *)got_error_from_errno("got_opentemp");
6224 goto done;
6227 err = block_signals_used_by_main_thread();
6228 if (err)
6229 goto done;
6231 err = got_blame(ta->path, a->commit_id, ta->repo,
6232 tog_diff_algo, blame_cb, ta->cb_args,
6233 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6234 if (err && err->code == GOT_ERR_CANCELLED)
6235 err = NULL;
6237 errcode = pthread_mutex_lock(&tog_mutex);
6238 if (errcode) {
6239 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6240 goto done;
6243 close_err = got_repo_close(ta->repo);
6244 if (err == NULL)
6245 err = close_err;
6246 ta->repo = NULL;
6247 *ta->complete = 1;
6249 if (tog_io.wait_for_ui) {
6250 errcode = pthread_cond_signal(&ta->blame_complete);
6251 if (errcode && err == NULL)
6252 err = got_error_set_errno(errcode,
6253 "pthread_cond_signal");
6256 errcode = pthread_mutex_unlock(&tog_mutex);
6257 if (errcode && err == NULL)
6258 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6260 done:
6261 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6262 err = got_error_from_errno("close");
6263 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6264 err = got_error_from_errno("close");
6265 if (f1 && fclose(f1) == EOF && err == NULL)
6266 err = got_error_from_errno("fclose");
6267 if (f2 && fclose(f2) == EOF && err == NULL)
6268 err = got_error_from_errno("fclose");
6270 return (void *)err;
6273 static struct got_object_id *
6274 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6275 int first_displayed_line, int selected_line)
6277 struct tog_blame_line *line;
6279 if (nlines <= 0)
6280 return NULL;
6282 line = &lines[first_displayed_line - 1 + selected_line - 1];
6283 if (!line->annotated)
6284 return NULL;
6286 return line->id;
6289 static struct got_object_id *
6290 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6291 int lineno)
6293 struct tog_blame_line *line;
6295 if (nlines <= 0 || lineno >= nlines)
6296 return NULL;
6298 line = &lines[lineno - 1];
6299 if (!line->annotated)
6300 return NULL;
6302 return line->id;
6305 static const struct got_error *
6306 stop_blame(struct tog_blame *blame)
6308 const struct got_error *err = NULL;
6309 int i;
6311 if (blame->thread) {
6312 int errcode;
6313 errcode = pthread_mutex_unlock(&tog_mutex);
6314 if (errcode)
6315 return got_error_set_errno(errcode,
6316 "pthread_mutex_unlock");
6317 errcode = pthread_join(blame->thread, (void **)&err);
6318 if (errcode)
6319 return got_error_set_errno(errcode, "pthread_join");
6320 errcode = pthread_mutex_lock(&tog_mutex);
6321 if (errcode)
6322 return got_error_set_errno(errcode,
6323 "pthread_mutex_lock");
6324 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6325 err = NULL;
6326 blame->thread = NULL;
6328 if (blame->thread_args.repo) {
6329 const struct got_error *close_err;
6330 close_err = got_repo_close(blame->thread_args.repo);
6331 if (err == NULL)
6332 err = close_err;
6333 blame->thread_args.repo = NULL;
6335 if (blame->f) {
6336 if (fclose(blame->f) == EOF && err == NULL)
6337 err = got_error_from_errno("fclose");
6338 blame->f = NULL;
6340 if (blame->lines) {
6341 for (i = 0; i < blame->nlines; i++)
6342 free(blame->lines[i].id);
6343 free(blame->lines);
6344 blame->lines = NULL;
6346 free(blame->cb_args.commit_id);
6347 blame->cb_args.commit_id = NULL;
6348 if (blame->pack_fds) {
6349 const struct got_error *pack_err =
6350 got_repo_pack_fds_close(blame->pack_fds);
6351 if (err == NULL)
6352 err = pack_err;
6353 blame->pack_fds = NULL;
6355 return err;
6358 static const struct got_error *
6359 cancel_blame_view(void *arg)
6361 const struct got_error *err = NULL;
6362 int *done = arg;
6363 int errcode;
6365 errcode = pthread_mutex_lock(&tog_mutex);
6366 if (errcode)
6367 return got_error_set_errno(errcode,
6368 "pthread_mutex_unlock");
6370 if (*done)
6371 err = got_error(GOT_ERR_CANCELLED);
6373 errcode = pthread_mutex_unlock(&tog_mutex);
6374 if (errcode)
6375 return got_error_set_errno(errcode,
6376 "pthread_mutex_lock");
6378 return err;
6381 static const struct got_error *
6382 run_blame(struct tog_view *view)
6384 struct tog_blame_view_state *s = &view->state.blame;
6385 struct tog_blame *blame = &s->blame;
6386 const struct got_error *err = NULL;
6387 struct got_commit_object *commit = NULL;
6388 struct got_blob_object *blob = NULL;
6389 struct got_repository *thread_repo = NULL;
6390 struct got_object_id *obj_id = NULL;
6391 int obj_type, fd = -1;
6392 int *pack_fds = NULL;
6394 err = got_object_open_as_commit(&commit, s->repo,
6395 &s->blamed_commit->id);
6396 if (err)
6397 return err;
6399 fd = got_opentempfd();
6400 if (fd == -1) {
6401 err = got_error_from_errno("got_opentempfd");
6402 goto done;
6405 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6406 if (err)
6407 goto done;
6409 err = got_object_get_type(&obj_type, s->repo, obj_id);
6410 if (err)
6411 goto done;
6413 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6414 err = got_error(GOT_ERR_OBJ_TYPE);
6415 goto done;
6418 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6419 if (err)
6420 goto done;
6421 blame->f = got_opentemp();
6422 if (blame->f == NULL) {
6423 err = got_error_from_errno("got_opentemp");
6424 goto done;
6426 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6427 &blame->line_offsets, blame->f, blob);
6428 if (err)
6429 goto done;
6430 if (blame->nlines == 0) {
6431 s->blame_complete = 1;
6432 goto done;
6435 /* Don't include \n at EOF in the blame line count. */
6436 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6437 blame->nlines--;
6439 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6440 if (blame->lines == NULL) {
6441 err = got_error_from_errno("calloc");
6442 goto done;
6445 err = got_repo_pack_fds_open(&pack_fds);
6446 if (err)
6447 goto done;
6448 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6449 pack_fds);
6450 if (err)
6451 goto done;
6453 blame->pack_fds = pack_fds;
6454 blame->cb_args.view = view;
6455 blame->cb_args.lines = blame->lines;
6456 blame->cb_args.nlines = blame->nlines;
6457 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6458 if (blame->cb_args.commit_id == NULL) {
6459 err = got_error_from_errno("got_object_id_dup");
6460 goto done;
6462 blame->cb_args.quit = &s->done;
6464 blame->thread_args.path = s->path;
6465 blame->thread_args.repo = thread_repo;
6466 blame->thread_args.cb_args = &blame->cb_args;
6467 blame->thread_args.complete = &s->blame_complete;
6468 blame->thread_args.cancel_cb = cancel_blame_view;
6469 blame->thread_args.cancel_arg = &s->done;
6470 s->blame_complete = 0;
6472 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6473 s->first_displayed_line = 1;
6474 s->last_displayed_line = view->nlines;
6475 s->selected_line = 1;
6477 s->matched_line = 0;
6479 done:
6480 if (commit)
6481 got_object_commit_close(commit);
6482 if (fd != -1 && close(fd) == -1 && err == NULL)
6483 err = got_error_from_errno("close");
6484 if (blob)
6485 got_object_blob_close(blob);
6486 free(obj_id);
6487 if (err)
6488 stop_blame(blame);
6489 return err;
6492 static const struct got_error *
6493 open_blame_view(struct tog_view *view, char *path,
6494 struct got_object_id *commit_id, struct got_repository *repo)
6496 const struct got_error *err = NULL;
6497 struct tog_blame_view_state *s = &view->state.blame;
6499 STAILQ_INIT(&s->blamed_commits);
6501 s->path = strdup(path);
6502 if (s->path == NULL)
6503 return got_error_from_errno("strdup");
6505 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6506 if (err) {
6507 free(s->path);
6508 return err;
6511 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6512 s->first_displayed_line = 1;
6513 s->last_displayed_line = view->nlines;
6514 s->selected_line = 1;
6515 s->blame_complete = 0;
6516 s->repo = repo;
6517 s->commit_id = commit_id;
6518 memset(&s->blame, 0, sizeof(s->blame));
6520 STAILQ_INIT(&s->colors);
6521 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6522 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6523 get_color_value("TOG_COLOR_COMMIT"));
6524 if (err)
6525 return err;
6528 view->show = show_blame_view;
6529 view->input = input_blame_view;
6530 view->reset = reset_blame_view;
6531 view->close = close_blame_view;
6532 view->search_start = search_start_blame_view;
6533 view->search_setup = search_setup_blame_view;
6534 view->search_next = search_next_view_match;
6536 if (using_mock_io) {
6537 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6538 int rc;
6540 rc = pthread_cond_init(&bta->blame_complete, NULL);
6541 if (rc)
6542 return got_error_set_errno(rc, "pthread_cond_init");
6545 return run_blame(view);
6548 static const struct got_error *
6549 close_blame_view(struct tog_view *view)
6551 const struct got_error *err = NULL;
6552 struct tog_blame_view_state *s = &view->state.blame;
6554 if (s->blame.thread)
6555 err = stop_blame(&s->blame);
6557 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6558 struct got_object_qid *blamed_commit;
6559 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6560 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6561 got_object_qid_free(blamed_commit);
6564 if (using_mock_io) {
6565 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6566 int rc;
6568 rc = pthread_cond_destroy(&bta->blame_complete);
6569 if (rc && err == NULL)
6570 err = got_error_set_errno(rc, "pthread_cond_destroy");
6573 free(s->path);
6574 free_colors(&s->colors);
6575 return err;
6578 static const struct got_error *
6579 search_start_blame_view(struct tog_view *view)
6581 struct tog_blame_view_state *s = &view->state.blame;
6583 s->matched_line = 0;
6584 return NULL;
6587 static void
6588 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6589 size_t *nlines, int **first, int **last, int **match, int **selected)
6591 struct tog_blame_view_state *s = &view->state.blame;
6593 *f = s->blame.f;
6594 *nlines = s->blame.nlines;
6595 *line_offsets = s->blame.line_offsets;
6596 *match = &s->matched_line;
6597 *first = &s->first_displayed_line;
6598 *last = &s->last_displayed_line;
6599 *selected = &s->selected_line;
6602 static const struct got_error *
6603 show_blame_view(struct tog_view *view)
6605 const struct got_error *err = NULL;
6606 struct tog_blame_view_state *s = &view->state.blame;
6607 int errcode;
6609 if (s->blame.thread == NULL && !s->blame_complete) {
6610 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6611 &s->blame.thread_args);
6612 if (errcode)
6613 return got_error_set_errno(errcode, "pthread_create");
6615 if (!using_mock_io)
6616 halfdelay(1); /* fast refresh while annotating */
6619 if (s->blame_complete && !using_mock_io)
6620 halfdelay(10); /* disable fast refresh */
6622 err = draw_blame(view);
6624 view_border(view);
6625 return err;
6628 static const struct got_error *
6629 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6630 struct got_repository *repo, struct got_object_id *id)
6632 struct tog_view *log_view;
6633 const struct got_error *err = NULL;
6635 *new_view = NULL;
6637 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6638 if (log_view == NULL)
6639 return got_error_from_errno("view_open");
6641 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6642 if (err)
6643 view_close(log_view);
6644 else
6645 *new_view = log_view;
6647 return err;
6650 static const struct got_error *
6651 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6653 const struct got_error *err = NULL, *thread_err = NULL;
6654 struct tog_view *diff_view;
6655 struct tog_blame_view_state *s = &view->state.blame;
6656 int eos, nscroll, begin_y = 0, begin_x = 0;
6658 eos = nscroll = view->nlines - 2;
6659 if (view_is_hsplit_top(view))
6660 --eos; /* border */
6662 switch (ch) {
6663 case '0':
6664 case '$':
6665 case KEY_RIGHT:
6666 case 'l':
6667 case KEY_LEFT:
6668 case 'h':
6669 horizontal_scroll_input(view, ch);
6670 break;
6671 case 'q':
6672 s->done = 1;
6673 break;
6674 case 'g':
6675 case KEY_HOME:
6676 s->selected_line = 1;
6677 s->first_displayed_line = 1;
6678 view->count = 0;
6679 break;
6680 case 'G':
6681 case KEY_END:
6682 if (s->blame.nlines < eos) {
6683 s->selected_line = s->blame.nlines;
6684 s->first_displayed_line = 1;
6685 } else {
6686 s->selected_line = eos;
6687 s->first_displayed_line = s->blame.nlines - (eos - 1);
6689 view->count = 0;
6690 break;
6691 case 'k':
6692 case KEY_UP:
6693 case CTRL('p'):
6694 if (s->selected_line > 1)
6695 s->selected_line--;
6696 else if (s->selected_line == 1 &&
6697 s->first_displayed_line > 1)
6698 s->first_displayed_line--;
6699 else
6700 view->count = 0;
6701 break;
6702 case CTRL('u'):
6703 case 'u':
6704 nscroll /= 2;
6705 /* FALL THROUGH */
6706 case KEY_PPAGE:
6707 case CTRL('b'):
6708 case 'b':
6709 if (s->first_displayed_line == 1) {
6710 if (view->count > 1)
6711 nscroll += nscroll;
6712 s->selected_line = MAX(1, s->selected_line - nscroll);
6713 view->count = 0;
6714 break;
6716 if (s->first_displayed_line > nscroll)
6717 s->first_displayed_line -= nscroll;
6718 else
6719 s->first_displayed_line = 1;
6720 break;
6721 case 'j':
6722 case KEY_DOWN:
6723 case CTRL('n'):
6724 if (s->selected_line < eos && s->first_displayed_line +
6725 s->selected_line <= s->blame.nlines)
6726 s->selected_line++;
6727 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6728 s->first_displayed_line++;
6729 else
6730 view->count = 0;
6731 break;
6732 case 'c':
6733 case 'p': {
6734 struct got_object_id *id = NULL;
6736 view->count = 0;
6737 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6738 s->first_displayed_line, s->selected_line);
6739 if (id == NULL)
6740 break;
6741 if (ch == 'p') {
6742 struct got_commit_object *commit, *pcommit;
6743 struct got_object_qid *pid;
6744 struct got_object_id *blob_id = NULL;
6745 int obj_type;
6746 err = got_object_open_as_commit(&commit,
6747 s->repo, id);
6748 if (err)
6749 break;
6750 pid = STAILQ_FIRST(
6751 got_object_commit_get_parent_ids(commit));
6752 if (pid == NULL) {
6753 got_object_commit_close(commit);
6754 break;
6756 /* Check if path history ends here. */
6757 err = got_object_open_as_commit(&pcommit,
6758 s->repo, &pid->id);
6759 if (err)
6760 break;
6761 err = got_object_id_by_path(&blob_id, s->repo,
6762 pcommit, s->path);
6763 got_object_commit_close(pcommit);
6764 if (err) {
6765 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6766 err = NULL;
6767 got_object_commit_close(commit);
6768 break;
6770 err = got_object_get_type(&obj_type, s->repo,
6771 blob_id);
6772 free(blob_id);
6773 /* Can't blame non-blob type objects. */
6774 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6775 got_object_commit_close(commit);
6776 break;
6778 err = got_object_qid_alloc(&s->blamed_commit,
6779 &pid->id);
6780 got_object_commit_close(commit);
6781 } else {
6782 if (got_object_id_cmp(id,
6783 &s->blamed_commit->id) == 0)
6784 break;
6785 err = got_object_qid_alloc(&s->blamed_commit,
6786 id);
6788 if (err)
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_INSERT_HEAD(&s->blamed_commits,
6796 s->blamed_commit, entry);
6797 err = run_blame(view);
6798 if (err)
6799 break;
6800 break;
6802 case 'C': {
6803 struct got_object_qid *first;
6805 view->count = 0;
6806 first = STAILQ_FIRST(&s->blamed_commits);
6807 if (!got_object_id_cmp(&first->id, s->commit_id))
6808 break;
6809 s->done = 1;
6810 thread_err = stop_blame(&s->blame);
6811 s->done = 0;
6812 if (thread_err)
6813 break;
6814 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6815 got_object_qid_free(s->blamed_commit);
6816 s->blamed_commit =
6817 STAILQ_FIRST(&s->blamed_commits);
6818 err = run_blame(view);
6819 if (err)
6820 break;
6821 break;
6823 case 'L':
6824 view->count = 0;
6825 s->id_to_log = get_selected_commit_id(s->blame.lines,
6826 s->blame.nlines, s->first_displayed_line, s->selected_line);
6827 if (s->id_to_log)
6828 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6829 break;
6830 case KEY_ENTER:
6831 case '\r': {
6832 struct got_object_id *id = NULL;
6833 struct got_object_qid *pid;
6834 struct got_commit_object *commit = NULL;
6836 view->count = 0;
6837 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6838 s->first_displayed_line, s->selected_line);
6839 if (id == NULL)
6840 break;
6841 err = got_object_open_as_commit(&commit, s->repo, id);
6842 if (err)
6843 break;
6844 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6845 if (*new_view) {
6846 /* traversed from diff view, release diff resources */
6847 err = close_diff_view(*new_view);
6848 if (err)
6849 break;
6850 diff_view = *new_view;
6851 } else {
6852 if (view_is_parent_view(view))
6853 view_get_split(view, &begin_y, &begin_x);
6855 diff_view = view_open(0, 0, begin_y, begin_x,
6856 TOG_VIEW_DIFF);
6857 if (diff_view == NULL) {
6858 got_object_commit_close(commit);
6859 err = got_error_from_errno("view_open");
6860 break;
6863 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6864 id, NULL, NULL, 3, 0, 0, view, s->repo);
6865 got_object_commit_close(commit);
6866 if (err) {
6867 view_close(diff_view);
6868 break;
6870 s->last_diffed_line = s->first_displayed_line - 1 +
6871 s->selected_line;
6872 if (*new_view)
6873 break; /* still open from active diff view */
6874 if (view_is_parent_view(view) &&
6875 view->mode == TOG_VIEW_SPLIT_HRZN) {
6876 err = view_init_hsplit(view, begin_y);
6877 if (err)
6878 break;
6881 view->focussed = 0;
6882 diff_view->focussed = 1;
6883 diff_view->mode = view->mode;
6884 diff_view->nlines = view->lines - begin_y;
6885 if (view_is_parent_view(view)) {
6886 view_transfer_size(diff_view, view);
6887 err = view_close_child(view);
6888 if (err)
6889 break;
6890 err = view_set_child(view, diff_view);
6891 if (err)
6892 break;
6893 view->focus_child = 1;
6894 } else
6895 *new_view = diff_view;
6896 if (err)
6897 break;
6898 break;
6900 case CTRL('d'):
6901 case 'd':
6902 nscroll /= 2;
6903 /* FALL THROUGH */
6904 case KEY_NPAGE:
6905 case CTRL('f'):
6906 case 'f':
6907 case ' ':
6908 if (s->last_displayed_line >= s->blame.nlines &&
6909 s->selected_line >= MIN(s->blame.nlines,
6910 view->nlines - 2)) {
6911 view->count = 0;
6912 break;
6914 if (s->last_displayed_line >= s->blame.nlines &&
6915 s->selected_line < view->nlines - 2) {
6916 s->selected_line +=
6917 MIN(nscroll, s->last_displayed_line -
6918 s->first_displayed_line - s->selected_line + 1);
6920 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6921 s->first_displayed_line += nscroll;
6922 else
6923 s->first_displayed_line =
6924 s->blame.nlines - (view->nlines - 3);
6925 break;
6926 case KEY_RESIZE:
6927 if (s->selected_line > view->nlines - 2) {
6928 s->selected_line = MIN(s->blame.nlines,
6929 view->nlines - 2);
6931 break;
6932 default:
6933 view->count = 0;
6934 break;
6936 return thread_err ? thread_err : err;
6939 static const struct got_error *
6940 reset_blame_view(struct tog_view *view)
6942 const struct got_error *err;
6943 struct tog_blame_view_state *s = &view->state.blame;
6945 view->count = 0;
6946 s->done = 1;
6947 err = stop_blame(&s->blame);
6948 s->done = 0;
6949 if (err)
6950 return err;
6951 return run_blame(view);
6954 static const struct got_error *
6955 cmd_blame(int argc, char *argv[])
6957 const struct got_error *error;
6958 struct got_repository *repo = NULL;
6959 struct got_worktree *worktree = NULL;
6960 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6961 char *link_target = NULL;
6962 struct got_object_id *commit_id = NULL;
6963 struct got_commit_object *commit = NULL;
6964 char *commit_id_str = NULL;
6965 int ch;
6966 struct tog_view *view = NULL;
6967 int *pack_fds = NULL;
6969 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6970 switch (ch) {
6971 case 'c':
6972 commit_id_str = optarg;
6973 break;
6974 case 'r':
6975 repo_path = realpath(optarg, NULL);
6976 if (repo_path == NULL)
6977 return got_error_from_errno2("realpath",
6978 optarg);
6979 break;
6980 default:
6981 usage_blame();
6982 /* NOTREACHED */
6986 argc -= optind;
6987 argv += optind;
6989 if (argc != 1)
6990 usage_blame();
6992 error = got_repo_pack_fds_open(&pack_fds);
6993 if (error != NULL)
6994 goto done;
6996 if (repo_path == NULL) {
6997 cwd = getcwd(NULL, 0);
6998 if (cwd == NULL)
6999 return got_error_from_errno("getcwd");
7000 error = got_worktree_open(&worktree, cwd);
7001 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7002 goto done;
7003 if (worktree)
7004 repo_path =
7005 strdup(got_worktree_get_repo_path(worktree));
7006 else
7007 repo_path = strdup(cwd);
7008 if (repo_path == NULL) {
7009 error = got_error_from_errno("strdup");
7010 goto done;
7014 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7015 if (error != NULL)
7016 goto done;
7018 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7019 worktree);
7020 if (error)
7021 goto done;
7023 init_curses();
7025 error = apply_unveil(got_repo_get_path(repo), NULL);
7026 if (error)
7027 goto done;
7029 error = tog_load_refs(repo, 0);
7030 if (error)
7031 goto done;
7033 if (commit_id_str == NULL) {
7034 struct got_reference *head_ref;
7035 error = got_ref_open(&head_ref, repo, worktree ?
7036 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7037 if (error != NULL)
7038 goto done;
7039 error = got_ref_resolve(&commit_id, repo, head_ref);
7040 got_ref_close(head_ref);
7041 } else {
7042 error = got_repo_match_object_id(&commit_id, NULL,
7043 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7045 if (error != NULL)
7046 goto done;
7048 error = got_object_open_as_commit(&commit, repo, commit_id);
7049 if (error)
7050 goto done;
7052 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7053 commit, repo);
7054 if (error)
7055 goto done;
7057 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7058 if (view == NULL) {
7059 error = got_error_from_errno("view_open");
7060 goto done;
7062 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7063 commit_id, repo);
7064 if (error != NULL) {
7065 if (view->close == NULL)
7066 close_blame_view(view);
7067 view_close(view);
7068 goto done;
7070 if (worktree) {
7071 /* Release work tree lock. */
7072 got_worktree_close(worktree);
7073 worktree = NULL;
7075 error = view_loop(view);
7076 done:
7077 free(repo_path);
7078 free(in_repo_path);
7079 free(link_target);
7080 free(cwd);
7081 free(commit_id);
7082 if (commit)
7083 got_object_commit_close(commit);
7084 if (worktree)
7085 got_worktree_close(worktree);
7086 if (repo) {
7087 const struct got_error *close_err = got_repo_close(repo);
7088 if (error == NULL)
7089 error = close_err;
7091 if (pack_fds) {
7092 const struct got_error *pack_err =
7093 got_repo_pack_fds_close(pack_fds);
7094 if (error == NULL)
7095 error = pack_err;
7097 tog_free_refs();
7098 return error;
7101 static const struct got_error *
7102 draw_tree_entries(struct tog_view *view, const char *parent_path)
7104 struct tog_tree_view_state *s = &view->state.tree;
7105 const struct got_error *err = NULL;
7106 struct got_tree_entry *te;
7107 wchar_t *wline;
7108 char *index = NULL;
7109 struct tog_color *tc;
7110 int width, n, nentries, scrollx, i = 1;
7111 int limit = view->nlines;
7113 s->ndisplayed = 0;
7114 if (view_is_hsplit_top(view))
7115 --limit; /* border */
7117 werase(view->window);
7119 if (limit == 0)
7120 return NULL;
7122 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7123 0, 0);
7124 if (err)
7125 return err;
7126 if (view_needs_focus_indication(view))
7127 wstandout(view->window);
7128 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7129 if (tc)
7130 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7131 waddwstr(view->window, wline);
7132 free(wline);
7133 wline = NULL;
7134 while (width++ < view->ncols)
7135 waddch(view->window, ' ');
7136 if (tc)
7137 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7138 if (view_needs_focus_indication(view))
7139 wstandend(view->window);
7140 if (--limit <= 0)
7141 return NULL;
7143 i += s->selected;
7144 if (s->first_displayed_entry) {
7145 i += got_tree_entry_get_index(s->first_displayed_entry);
7146 if (s->tree != s->root)
7147 ++i; /* account for ".." entry */
7149 nentries = got_object_tree_get_nentries(s->tree);
7150 if (asprintf(&index, "[%d/%d] %s",
7151 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7152 return got_error_from_errno("asprintf");
7153 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7154 free(index);
7155 if (err)
7156 return err;
7157 waddwstr(view->window, wline);
7158 free(wline);
7159 wline = NULL;
7160 if (width < view->ncols - 1)
7161 waddch(view->window, '\n');
7162 if (--limit <= 0)
7163 return NULL;
7164 waddch(view->window, '\n');
7165 if (--limit <= 0)
7166 return NULL;
7168 if (s->first_displayed_entry == NULL) {
7169 te = got_object_tree_get_first_entry(s->tree);
7170 if (s->selected == 0) {
7171 if (view->focussed)
7172 wstandout(view->window);
7173 s->selected_entry = NULL;
7175 waddstr(view->window, " ..\n"); /* parent directory */
7176 if (s->selected == 0 && view->focussed)
7177 wstandend(view->window);
7178 s->ndisplayed++;
7179 if (--limit <= 0)
7180 return NULL;
7181 n = 1;
7182 } else {
7183 n = 0;
7184 te = s->first_displayed_entry;
7187 view->maxx = 0;
7188 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7189 char *line = NULL, *id_str = NULL, *link_target = NULL;
7190 const char *modestr = "";
7191 mode_t mode;
7193 te = got_object_tree_get_entry(s->tree, i);
7194 mode = got_tree_entry_get_mode(te);
7196 if (s->show_ids) {
7197 err = got_object_id_str(&id_str,
7198 got_tree_entry_get_id(te));
7199 if (err)
7200 return got_error_from_errno(
7201 "got_object_id_str");
7203 if (got_object_tree_entry_is_submodule(te))
7204 modestr = "$";
7205 else if (S_ISLNK(mode)) {
7206 int i;
7208 err = got_tree_entry_get_symlink_target(&link_target,
7209 te, s->repo);
7210 if (err) {
7211 free(id_str);
7212 return err;
7214 for (i = 0; i < strlen(link_target); i++) {
7215 if (!isprint((unsigned char)link_target[i]))
7216 link_target[i] = '?';
7218 modestr = "@";
7220 else if (S_ISDIR(mode))
7221 modestr = "/";
7222 else if (mode & S_IXUSR)
7223 modestr = "*";
7224 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7225 got_tree_entry_get_name(te), modestr,
7226 link_target ? " -> ": "",
7227 link_target ? link_target : "") == -1) {
7228 free(id_str);
7229 free(link_target);
7230 return got_error_from_errno("asprintf");
7232 free(id_str);
7233 free(link_target);
7235 /* use full line width to determine view->maxx */
7236 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7237 if (err) {
7238 free(line);
7239 break;
7241 view->maxx = MAX(view->maxx, width);
7242 free(wline);
7243 wline = NULL;
7245 err = format_line(&wline, &width, &scrollx, line, view->x,
7246 view->ncols, 0, 0);
7247 if (err) {
7248 free(line);
7249 break;
7251 if (n == s->selected) {
7252 if (view->focussed)
7253 wstandout(view->window);
7254 s->selected_entry = te;
7256 tc = match_color(&s->colors, line);
7257 if (tc)
7258 wattr_on(view->window,
7259 COLOR_PAIR(tc->colorpair), NULL);
7260 waddwstr(view->window, &wline[scrollx]);
7261 if (tc)
7262 wattr_off(view->window,
7263 COLOR_PAIR(tc->colorpair), NULL);
7264 if (width < view->ncols)
7265 waddch(view->window, '\n');
7266 if (n == s->selected && view->focussed)
7267 wstandend(view->window);
7268 free(line);
7269 free(wline);
7270 wline = NULL;
7271 n++;
7272 s->ndisplayed++;
7273 s->last_displayed_entry = te;
7274 if (--limit <= 0)
7275 break;
7278 return err;
7281 static void
7282 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7284 struct got_tree_entry *te;
7285 int isroot = s->tree == s->root;
7286 int i = 0;
7288 if (s->first_displayed_entry == NULL)
7289 return;
7291 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7292 while (i++ < maxscroll) {
7293 if (te == NULL) {
7294 if (!isroot)
7295 s->first_displayed_entry = NULL;
7296 break;
7298 s->first_displayed_entry = te;
7299 te = got_tree_entry_get_prev(s->tree, te);
7303 static const struct got_error *
7304 tree_scroll_down(struct tog_view *view, int maxscroll)
7306 struct tog_tree_view_state *s = &view->state.tree;
7307 struct got_tree_entry *next, *last;
7308 int n = 0;
7310 if (s->first_displayed_entry)
7311 next = got_tree_entry_get_next(s->tree,
7312 s->first_displayed_entry);
7313 else
7314 next = got_object_tree_get_first_entry(s->tree);
7316 last = s->last_displayed_entry;
7317 while (next && n++ < maxscroll) {
7318 if (last) {
7319 s->last_displayed_entry = last;
7320 last = got_tree_entry_get_next(s->tree, last);
7322 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7323 s->first_displayed_entry = next;
7324 next = got_tree_entry_get_next(s->tree, next);
7328 return NULL;
7331 static const struct got_error *
7332 tree_entry_path(char **path, struct tog_parent_trees *parents,
7333 struct got_tree_entry *te)
7335 const struct got_error *err = NULL;
7336 struct tog_parent_tree *pt;
7337 size_t len = 2; /* for leading slash and NUL */
7339 TAILQ_FOREACH(pt, parents, entry)
7340 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7341 + 1 /* slash */;
7342 if (te)
7343 len += strlen(got_tree_entry_get_name(te));
7345 *path = calloc(1, len);
7346 if (path == NULL)
7347 return got_error_from_errno("calloc");
7349 (*path)[0] = '/';
7350 pt = TAILQ_LAST(parents, tog_parent_trees);
7351 while (pt) {
7352 const char *name = got_tree_entry_get_name(pt->selected_entry);
7353 if (strlcat(*path, name, len) >= len) {
7354 err = got_error(GOT_ERR_NO_SPACE);
7355 goto done;
7357 if (strlcat(*path, "/", len) >= len) {
7358 err = got_error(GOT_ERR_NO_SPACE);
7359 goto done;
7361 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7363 if (te) {
7364 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7365 err = got_error(GOT_ERR_NO_SPACE);
7366 goto done;
7369 done:
7370 if (err) {
7371 free(*path);
7372 *path = NULL;
7374 return err;
7377 static const struct got_error *
7378 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7379 struct got_tree_entry *te, struct tog_parent_trees *parents,
7380 struct got_object_id *commit_id, struct got_repository *repo)
7382 const struct got_error *err = NULL;
7383 char *path;
7384 struct tog_view *blame_view;
7386 *new_view = NULL;
7388 err = tree_entry_path(&path, parents, te);
7389 if (err)
7390 return err;
7392 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7393 if (blame_view == NULL) {
7394 err = got_error_from_errno("view_open");
7395 goto done;
7398 err = open_blame_view(blame_view, path, commit_id, repo);
7399 if (err) {
7400 if (err->code == GOT_ERR_CANCELLED)
7401 err = NULL;
7402 view_close(blame_view);
7403 } else
7404 *new_view = blame_view;
7405 done:
7406 free(path);
7407 return err;
7410 static const struct got_error *
7411 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7412 struct tog_tree_view_state *s)
7414 struct tog_view *log_view;
7415 const struct got_error *err = NULL;
7416 char *path;
7418 *new_view = NULL;
7420 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7421 if (log_view == NULL)
7422 return got_error_from_errno("view_open");
7424 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7425 if (err)
7426 return err;
7428 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7429 path, 0);
7430 if (err)
7431 view_close(log_view);
7432 else
7433 *new_view = log_view;
7434 free(path);
7435 return err;
7438 static const struct got_error *
7439 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7440 const char *head_ref_name, struct got_repository *repo)
7442 const struct got_error *err = NULL;
7443 char *commit_id_str = NULL;
7444 struct tog_tree_view_state *s = &view->state.tree;
7445 struct got_commit_object *commit = NULL;
7447 TAILQ_INIT(&s->parents);
7448 STAILQ_INIT(&s->colors);
7450 s->commit_id = got_object_id_dup(commit_id);
7451 if (s->commit_id == NULL) {
7452 err = got_error_from_errno("got_object_id_dup");
7453 goto done;
7456 err = got_object_open_as_commit(&commit, repo, commit_id);
7457 if (err)
7458 goto done;
7461 * The root is opened here and will be closed when the view is closed.
7462 * Any visited subtrees and their path-wise parents are opened and
7463 * closed on demand.
7465 err = got_object_open_as_tree(&s->root, repo,
7466 got_object_commit_get_tree_id(commit));
7467 if (err)
7468 goto done;
7469 s->tree = s->root;
7471 err = got_object_id_str(&commit_id_str, commit_id);
7472 if (err != NULL)
7473 goto done;
7475 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7476 err = got_error_from_errno("asprintf");
7477 goto done;
7480 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7481 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7482 if (head_ref_name) {
7483 s->head_ref_name = strdup(head_ref_name);
7484 if (s->head_ref_name == NULL) {
7485 err = got_error_from_errno("strdup");
7486 goto done;
7489 s->repo = repo;
7491 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7492 err = add_color(&s->colors, "\\$$",
7493 TOG_COLOR_TREE_SUBMODULE,
7494 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7495 if (err)
7496 goto done;
7497 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7498 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7499 if (err)
7500 goto done;
7501 err = add_color(&s->colors, "/$",
7502 TOG_COLOR_TREE_DIRECTORY,
7503 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7504 if (err)
7505 goto done;
7507 err = add_color(&s->colors, "\\*$",
7508 TOG_COLOR_TREE_EXECUTABLE,
7509 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7510 if (err)
7511 goto done;
7513 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7514 get_color_value("TOG_COLOR_COMMIT"));
7515 if (err)
7516 goto done;
7519 view->show = show_tree_view;
7520 view->input = input_tree_view;
7521 view->close = close_tree_view;
7522 view->search_start = search_start_tree_view;
7523 view->search_next = search_next_tree_view;
7524 done:
7525 free(commit_id_str);
7526 if (commit)
7527 got_object_commit_close(commit);
7528 if (err) {
7529 if (view->close == NULL)
7530 close_tree_view(view);
7531 view_close(view);
7533 return err;
7536 static const struct got_error *
7537 close_tree_view(struct tog_view *view)
7539 struct tog_tree_view_state *s = &view->state.tree;
7541 free_colors(&s->colors);
7542 free(s->tree_label);
7543 s->tree_label = NULL;
7544 free(s->commit_id);
7545 s->commit_id = NULL;
7546 free(s->head_ref_name);
7547 s->head_ref_name = NULL;
7548 while (!TAILQ_EMPTY(&s->parents)) {
7549 struct tog_parent_tree *parent;
7550 parent = TAILQ_FIRST(&s->parents);
7551 TAILQ_REMOVE(&s->parents, parent, entry);
7552 if (parent->tree != s->root)
7553 got_object_tree_close(parent->tree);
7554 free(parent);
7557 if (s->tree != NULL && s->tree != s->root)
7558 got_object_tree_close(s->tree);
7559 if (s->root)
7560 got_object_tree_close(s->root);
7561 return NULL;
7564 static const struct got_error *
7565 search_start_tree_view(struct tog_view *view)
7567 struct tog_tree_view_state *s = &view->state.tree;
7569 s->matched_entry = NULL;
7570 return NULL;
7573 static int
7574 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7576 regmatch_t regmatch;
7578 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7579 0) == 0;
7582 static const struct got_error *
7583 search_next_tree_view(struct tog_view *view)
7585 struct tog_tree_view_state *s = &view->state.tree;
7586 struct got_tree_entry *te = NULL;
7588 if (!view->searching) {
7589 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7590 return NULL;
7593 if (s->matched_entry) {
7594 if (view->searching == TOG_SEARCH_FORWARD) {
7595 if (s->selected_entry)
7596 te = got_tree_entry_get_next(s->tree,
7597 s->selected_entry);
7598 else
7599 te = got_object_tree_get_first_entry(s->tree);
7600 } else {
7601 if (s->selected_entry == NULL)
7602 te = got_object_tree_get_last_entry(s->tree);
7603 else
7604 te = got_tree_entry_get_prev(s->tree,
7605 s->selected_entry);
7607 } else {
7608 if (s->selected_entry)
7609 te = s->selected_entry;
7610 else if (view->searching == TOG_SEARCH_FORWARD)
7611 te = got_object_tree_get_first_entry(s->tree);
7612 else
7613 te = got_object_tree_get_last_entry(s->tree);
7616 while (1) {
7617 if (te == NULL) {
7618 if (s->matched_entry == NULL) {
7619 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7620 return NULL;
7622 if (view->searching == TOG_SEARCH_FORWARD)
7623 te = got_object_tree_get_first_entry(s->tree);
7624 else
7625 te = got_object_tree_get_last_entry(s->tree);
7628 if (match_tree_entry(te, &view->regex)) {
7629 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7630 s->matched_entry = te;
7631 break;
7634 if (view->searching == TOG_SEARCH_FORWARD)
7635 te = got_tree_entry_get_next(s->tree, te);
7636 else
7637 te = got_tree_entry_get_prev(s->tree, te);
7640 if (s->matched_entry) {
7641 s->first_displayed_entry = s->matched_entry;
7642 s->selected = 0;
7645 return NULL;
7648 static const struct got_error *
7649 show_tree_view(struct tog_view *view)
7651 const struct got_error *err = NULL;
7652 struct tog_tree_view_state *s = &view->state.tree;
7653 char *parent_path;
7655 err = tree_entry_path(&parent_path, &s->parents, NULL);
7656 if (err)
7657 return err;
7659 err = draw_tree_entries(view, parent_path);
7660 free(parent_path);
7662 view_border(view);
7663 return err;
7666 static const struct got_error *
7667 tree_goto_line(struct tog_view *view, int nlines)
7669 const struct got_error *err = NULL;
7670 struct tog_tree_view_state *s = &view->state.tree;
7671 struct got_tree_entry **fte, **lte, **ste;
7672 int g, last, first = 1, i = 1;
7673 int root = s->tree == s->root;
7674 int off = root ? 1 : 2;
7676 g = view->gline;
7677 view->gline = 0;
7679 if (g == 0)
7680 g = 1;
7681 else if (g > got_object_tree_get_nentries(s->tree))
7682 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7684 fte = &s->first_displayed_entry;
7685 lte = &s->last_displayed_entry;
7686 ste = &s->selected_entry;
7688 if (*fte != NULL) {
7689 first = got_tree_entry_get_index(*fte);
7690 first += off; /* account for ".." */
7692 last = got_tree_entry_get_index(*lte);
7693 last += off;
7695 if (g >= first && g <= last && g - first < nlines) {
7696 s->selected = g - first;
7697 return NULL; /* gline is on the current page */
7700 if (*ste != NULL) {
7701 i = got_tree_entry_get_index(*ste);
7702 i += off;
7705 if (i < g) {
7706 err = tree_scroll_down(view, g - i);
7707 if (err)
7708 return err;
7709 if (got_tree_entry_get_index(*lte) >=
7710 got_object_tree_get_nentries(s->tree) - 1 &&
7711 first + s->selected < g &&
7712 s->selected < s->ndisplayed - 1) {
7713 first = got_tree_entry_get_index(*fte);
7714 first += off;
7715 s->selected = g - first;
7717 } else if (i > g)
7718 tree_scroll_up(s, i - g);
7720 if (g < nlines &&
7721 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7722 s->selected = g - 1;
7724 return NULL;
7727 static const struct got_error *
7728 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7730 const struct got_error *err = NULL;
7731 struct tog_tree_view_state *s = &view->state.tree;
7732 struct got_tree_entry *te;
7733 int n, nscroll = view->nlines - 3;
7735 if (view->gline)
7736 return tree_goto_line(view, nscroll);
7738 switch (ch) {
7739 case '0':
7740 case '$':
7741 case KEY_RIGHT:
7742 case 'l':
7743 case KEY_LEFT:
7744 case 'h':
7745 horizontal_scroll_input(view, ch);
7746 break;
7747 case 'i':
7748 s->show_ids = !s->show_ids;
7749 view->count = 0;
7750 break;
7751 case 'L':
7752 view->count = 0;
7753 if (!s->selected_entry)
7754 break;
7755 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7756 break;
7757 case 'R':
7758 view->count = 0;
7759 err = view_request_new(new_view, view, TOG_VIEW_REF);
7760 break;
7761 case 'g':
7762 case '=':
7763 case KEY_HOME:
7764 s->selected = 0;
7765 view->count = 0;
7766 if (s->tree == s->root)
7767 s->first_displayed_entry =
7768 got_object_tree_get_first_entry(s->tree);
7769 else
7770 s->first_displayed_entry = NULL;
7771 break;
7772 case 'G':
7773 case '*':
7774 case KEY_END: {
7775 int eos = view->nlines - 3;
7777 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7778 --eos; /* border */
7779 s->selected = 0;
7780 view->count = 0;
7781 te = got_object_tree_get_last_entry(s->tree);
7782 for (n = 0; n < eos; n++) {
7783 if (te == NULL) {
7784 if (s->tree != s->root) {
7785 s->first_displayed_entry = NULL;
7786 n++;
7788 break;
7790 s->first_displayed_entry = te;
7791 te = got_tree_entry_get_prev(s->tree, te);
7793 if (n > 0)
7794 s->selected = n - 1;
7795 break;
7797 case 'k':
7798 case KEY_UP:
7799 case CTRL('p'):
7800 if (s->selected > 0) {
7801 s->selected--;
7802 break;
7804 tree_scroll_up(s, 1);
7805 if (s->selected_entry == NULL ||
7806 (s->tree == s->root && s->selected_entry ==
7807 got_object_tree_get_first_entry(s->tree)))
7808 view->count = 0;
7809 break;
7810 case CTRL('u'):
7811 case 'u':
7812 nscroll /= 2;
7813 /* FALL THROUGH */
7814 case KEY_PPAGE:
7815 case CTRL('b'):
7816 case 'b':
7817 if (s->tree == s->root) {
7818 if (got_object_tree_get_first_entry(s->tree) ==
7819 s->first_displayed_entry)
7820 s->selected -= MIN(s->selected, nscroll);
7821 } else {
7822 if (s->first_displayed_entry == NULL)
7823 s->selected -= MIN(s->selected, nscroll);
7825 tree_scroll_up(s, MAX(0, nscroll));
7826 if (s->selected_entry == NULL ||
7827 (s->tree == s->root && s->selected_entry ==
7828 got_object_tree_get_first_entry(s->tree)))
7829 view->count = 0;
7830 break;
7831 case 'j':
7832 case KEY_DOWN:
7833 case CTRL('n'):
7834 if (s->selected < s->ndisplayed - 1) {
7835 s->selected++;
7836 break;
7838 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7839 == NULL) {
7840 /* can't scroll any further */
7841 view->count = 0;
7842 break;
7844 tree_scroll_down(view, 1);
7845 break;
7846 case CTRL('d'):
7847 case 'd':
7848 nscroll /= 2;
7849 /* FALL THROUGH */
7850 case KEY_NPAGE:
7851 case CTRL('f'):
7852 case 'f':
7853 case ' ':
7854 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7855 == NULL) {
7856 /* can't scroll any further; move cursor down */
7857 if (s->selected < s->ndisplayed - 1)
7858 s->selected += MIN(nscroll,
7859 s->ndisplayed - s->selected - 1);
7860 else
7861 view->count = 0;
7862 break;
7864 tree_scroll_down(view, nscroll);
7865 break;
7866 case KEY_ENTER:
7867 case '\r':
7868 case KEY_BACKSPACE:
7869 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7870 struct tog_parent_tree *parent;
7871 /* user selected '..' */
7872 if (s->tree == s->root) {
7873 view->count = 0;
7874 break;
7876 parent = TAILQ_FIRST(&s->parents);
7877 TAILQ_REMOVE(&s->parents, parent,
7878 entry);
7879 got_object_tree_close(s->tree);
7880 s->tree = parent->tree;
7881 s->first_displayed_entry =
7882 parent->first_displayed_entry;
7883 s->selected_entry =
7884 parent->selected_entry;
7885 s->selected = parent->selected;
7886 if (s->selected > view->nlines - 3) {
7887 err = offset_selection_down(view);
7888 if (err)
7889 break;
7891 free(parent);
7892 } else if (S_ISDIR(got_tree_entry_get_mode(
7893 s->selected_entry))) {
7894 struct got_tree_object *subtree;
7895 view->count = 0;
7896 err = got_object_open_as_tree(&subtree, s->repo,
7897 got_tree_entry_get_id(s->selected_entry));
7898 if (err)
7899 break;
7900 err = tree_view_visit_subtree(s, subtree);
7901 if (err) {
7902 got_object_tree_close(subtree);
7903 break;
7905 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7906 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7907 break;
7908 case KEY_RESIZE:
7909 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7910 s->selected = view->nlines - 4;
7911 view->count = 0;
7912 break;
7913 default:
7914 view->count = 0;
7915 break;
7918 return err;
7921 __dead static void
7922 usage_tree(void)
7924 endwin();
7925 fprintf(stderr,
7926 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7927 getprogname());
7928 exit(1);
7931 static const struct got_error *
7932 cmd_tree(int argc, char *argv[])
7934 const struct got_error *error;
7935 struct got_repository *repo = NULL;
7936 struct got_worktree *worktree = NULL;
7937 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7938 struct got_object_id *commit_id = NULL;
7939 struct got_commit_object *commit = NULL;
7940 const char *commit_id_arg = NULL;
7941 char *label = NULL;
7942 struct got_reference *ref = NULL;
7943 const char *head_ref_name = NULL;
7944 int ch;
7945 struct tog_view *view;
7946 int *pack_fds = NULL;
7948 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7949 switch (ch) {
7950 case 'c':
7951 commit_id_arg = optarg;
7952 break;
7953 case 'r':
7954 repo_path = realpath(optarg, NULL);
7955 if (repo_path == NULL)
7956 return got_error_from_errno2("realpath",
7957 optarg);
7958 break;
7959 default:
7960 usage_tree();
7961 /* NOTREACHED */
7965 argc -= optind;
7966 argv += optind;
7968 if (argc > 1)
7969 usage_tree();
7971 error = got_repo_pack_fds_open(&pack_fds);
7972 if (error != NULL)
7973 goto done;
7975 if (repo_path == NULL) {
7976 cwd = getcwd(NULL, 0);
7977 if (cwd == NULL)
7978 return got_error_from_errno("getcwd");
7979 error = got_worktree_open(&worktree, cwd);
7980 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7981 goto done;
7982 if (worktree)
7983 repo_path =
7984 strdup(got_worktree_get_repo_path(worktree));
7985 else
7986 repo_path = strdup(cwd);
7987 if (repo_path == NULL) {
7988 error = got_error_from_errno("strdup");
7989 goto done;
7993 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7994 if (error != NULL)
7995 goto done;
7997 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7998 repo, worktree);
7999 if (error)
8000 goto done;
8002 init_curses();
8004 error = apply_unveil(got_repo_get_path(repo), NULL);
8005 if (error)
8006 goto done;
8008 error = tog_load_refs(repo, 0);
8009 if (error)
8010 goto done;
8012 if (commit_id_arg == NULL) {
8013 error = got_repo_match_object_id(&commit_id, &label,
8014 worktree ? got_worktree_get_head_ref_name(worktree) :
8015 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8016 if (error)
8017 goto done;
8018 head_ref_name = label;
8019 } else {
8020 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8021 if (error == NULL)
8022 head_ref_name = got_ref_get_name(ref);
8023 else if (error->code != GOT_ERR_NOT_REF)
8024 goto done;
8025 error = got_repo_match_object_id(&commit_id, NULL,
8026 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8027 if (error)
8028 goto done;
8031 error = got_object_open_as_commit(&commit, repo, commit_id);
8032 if (error)
8033 goto done;
8035 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8036 if (view == NULL) {
8037 error = got_error_from_errno("view_open");
8038 goto done;
8040 error = open_tree_view(view, commit_id, head_ref_name, repo);
8041 if (error)
8042 goto done;
8043 if (!got_path_is_root_dir(in_repo_path)) {
8044 error = tree_view_walk_path(&view->state.tree, commit,
8045 in_repo_path);
8046 if (error)
8047 goto done;
8050 if (worktree) {
8051 /* Release work tree lock. */
8052 got_worktree_close(worktree);
8053 worktree = NULL;
8055 error = view_loop(view);
8056 done:
8057 free(repo_path);
8058 free(cwd);
8059 free(commit_id);
8060 free(label);
8061 if (ref)
8062 got_ref_close(ref);
8063 if (repo) {
8064 const struct got_error *close_err = got_repo_close(repo);
8065 if (error == NULL)
8066 error = close_err;
8068 if (pack_fds) {
8069 const struct got_error *pack_err =
8070 got_repo_pack_fds_close(pack_fds);
8071 if (error == NULL)
8072 error = pack_err;
8074 tog_free_refs();
8075 return error;
8078 static const struct got_error *
8079 ref_view_load_refs(struct tog_ref_view_state *s)
8081 struct got_reflist_entry *sre;
8082 struct tog_reflist_entry *re;
8084 s->nrefs = 0;
8085 TAILQ_FOREACH(sre, &tog_refs, entry) {
8086 if (strncmp(got_ref_get_name(sre->ref),
8087 "refs/got/", 9) == 0 &&
8088 strncmp(got_ref_get_name(sre->ref),
8089 "refs/got/backup/", 16) != 0)
8090 continue;
8092 re = malloc(sizeof(*re));
8093 if (re == NULL)
8094 return got_error_from_errno("malloc");
8096 re->ref = got_ref_dup(sre->ref);
8097 if (re->ref == NULL)
8098 return got_error_from_errno("got_ref_dup");
8099 re->idx = s->nrefs++;
8100 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8103 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8104 return NULL;
8107 static void
8108 ref_view_free_refs(struct tog_ref_view_state *s)
8110 struct tog_reflist_entry *re;
8112 while (!TAILQ_EMPTY(&s->refs)) {
8113 re = TAILQ_FIRST(&s->refs);
8114 TAILQ_REMOVE(&s->refs, re, entry);
8115 got_ref_close(re->ref);
8116 free(re);
8120 static const struct got_error *
8121 open_ref_view(struct tog_view *view, struct got_repository *repo)
8123 const struct got_error *err = NULL;
8124 struct tog_ref_view_state *s = &view->state.ref;
8126 s->selected_entry = 0;
8127 s->repo = repo;
8129 TAILQ_INIT(&s->refs);
8130 STAILQ_INIT(&s->colors);
8132 err = ref_view_load_refs(s);
8133 if (err)
8134 goto done;
8136 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8137 err = add_color(&s->colors, "^refs/heads/",
8138 TOG_COLOR_REFS_HEADS,
8139 get_color_value("TOG_COLOR_REFS_HEADS"));
8140 if (err)
8141 goto done;
8143 err = add_color(&s->colors, "^refs/tags/",
8144 TOG_COLOR_REFS_TAGS,
8145 get_color_value("TOG_COLOR_REFS_TAGS"));
8146 if (err)
8147 goto done;
8149 err = add_color(&s->colors, "^refs/remotes/",
8150 TOG_COLOR_REFS_REMOTES,
8151 get_color_value("TOG_COLOR_REFS_REMOTES"));
8152 if (err)
8153 goto done;
8155 err = add_color(&s->colors, "^refs/got/backup/",
8156 TOG_COLOR_REFS_BACKUP,
8157 get_color_value("TOG_COLOR_REFS_BACKUP"));
8158 if (err)
8159 goto done;
8162 view->show = show_ref_view;
8163 view->input = input_ref_view;
8164 view->close = close_ref_view;
8165 view->search_start = search_start_ref_view;
8166 view->search_next = search_next_ref_view;
8167 done:
8168 if (err) {
8169 if (view->close == NULL)
8170 close_ref_view(view);
8171 view_close(view);
8173 return err;
8176 static const struct got_error *
8177 close_ref_view(struct tog_view *view)
8179 struct tog_ref_view_state *s = &view->state.ref;
8181 ref_view_free_refs(s);
8182 free_colors(&s->colors);
8184 return NULL;
8187 static const struct got_error *
8188 resolve_reflist_entry(struct got_object_id **commit_id,
8189 struct tog_reflist_entry *re, struct got_repository *repo)
8191 const struct got_error *err = NULL;
8192 struct got_object_id *obj_id;
8193 struct got_tag_object *tag = NULL;
8194 int obj_type;
8196 *commit_id = NULL;
8198 err = got_ref_resolve(&obj_id, repo, re->ref);
8199 if (err)
8200 return err;
8202 err = got_object_get_type(&obj_type, repo, obj_id);
8203 if (err)
8204 goto done;
8206 switch (obj_type) {
8207 case GOT_OBJ_TYPE_COMMIT:
8208 *commit_id = obj_id;
8209 break;
8210 case GOT_OBJ_TYPE_TAG:
8211 err = got_object_open_as_tag(&tag, repo, obj_id);
8212 if (err)
8213 goto done;
8214 free(obj_id);
8215 err = got_object_get_type(&obj_type, repo,
8216 got_object_tag_get_object_id(tag));
8217 if (err)
8218 goto done;
8219 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8220 err = got_error(GOT_ERR_OBJ_TYPE);
8221 goto done;
8223 *commit_id = got_object_id_dup(
8224 got_object_tag_get_object_id(tag));
8225 if (*commit_id == NULL) {
8226 err = got_error_from_errno("got_object_id_dup");
8227 goto done;
8229 break;
8230 default:
8231 err = got_error(GOT_ERR_OBJ_TYPE);
8232 break;
8235 done:
8236 if (tag)
8237 got_object_tag_close(tag);
8238 if (err) {
8239 free(*commit_id);
8240 *commit_id = NULL;
8242 return err;
8245 static const struct got_error *
8246 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8247 struct tog_reflist_entry *re, struct got_repository *repo)
8249 struct tog_view *log_view;
8250 const struct got_error *err = NULL;
8251 struct got_object_id *commit_id = NULL;
8253 *new_view = NULL;
8255 err = resolve_reflist_entry(&commit_id, re, repo);
8256 if (err) {
8257 if (err->code != GOT_ERR_OBJ_TYPE)
8258 return err;
8259 else
8260 return NULL;
8263 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8264 if (log_view == NULL) {
8265 err = got_error_from_errno("view_open");
8266 goto done;
8269 err = open_log_view(log_view, commit_id, repo,
8270 got_ref_get_name(re->ref), "", 0);
8271 done:
8272 if (err)
8273 view_close(log_view);
8274 else
8275 *new_view = log_view;
8276 free(commit_id);
8277 return err;
8280 static void
8281 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8283 struct tog_reflist_entry *re;
8284 int i = 0;
8286 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8287 return;
8289 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8290 while (i++ < maxscroll) {
8291 if (re == NULL)
8292 break;
8293 s->first_displayed_entry = re;
8294 re = TAILQ_PREV(re, tog_reflist_head, entry);
8298 static const struct got_error *
8299 ref_scroll_down(struct tog_view *view, int maxscroll)
8301 struct tog_ref_view_state *s = &view->state.ref;
8302 struct tog_reflist_entry *next, *last;
8303 int n = 0;
8305 if (s->first_displayed_entry)
8306 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8307 else
8308 next = TAILQ_FIRST(&s->refs);
8310 last = s->last_displayed_entry;
8311 while (next && n++ < maxscroll) {
8312 if (last) {
8313 s->last_displayed_entry = last;
8314 last = TAILQ_NEXT(last, entry);
8316 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8317 s->first_displayed_entry = next;
8318 next = TAILQ_NEXT(next, entry);
8322 return NULL;
8325 static const struct got_error *
8326 search_start_ref_view(struct tog_view *view)
8328 struct tog_ref_view_state *s = &view->state.ref;
8330 s->matched_entry = NULL;
8331 return NULL;
8334 static int
8335 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8337 regmatch_t regmatch;
8339 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8340 0) == 0;
8343 static const struct got_error *
8344 search_next_ref_view(struct tog_view *view)
8346 struct tog_ref_view_state *s = &view->state.ref;
8347 struct tog_reflist_entry *re = NULL;
8349 if (!view->searching) {
8350 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8351 return NULL;
8354 if (s->matched_entry) {
8355 if (view->searching == TOG_SEARCH_FORWARD) {
8356 if (s->selected_entry)
8357 re = TAILQ_NEXT(s->selected_entry, entry);
8358 else
8359 re = TAILQ_PREV(s->selected_entry,
8360 tog_reflist_head, entry);
8361 } else {
8362 if (s->selected_entry == NULL)
8363 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8364 else
8365 re = TAILQ_PREV(s->selected_entry,
8366 tog_reflist_head, entry);
8368 } else {
8369 if (s->selected_entry)
8370 re = s->selected_entry;
8371 else if (view->searching == TOG_SEARCH_FORWARD)
8372 re = TAILQ_FIRST(&s->refs);
8373 else
8374 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8377 while (1) {
8378 if (re == NULL) {
8379 if (s->matched_entry == NULL) {
8380 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8381 return NULL;
8383 if (view->searching == TOG_SEARCH_FORWARD)
8384 re = TAILQ_FIRST(&s->refs);
8385 else
8386 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8389 if (match_reflist_entry(re, &view->regex)) {
8390 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8391 s->matched_entry = re;
8392 break;
8395 if (view->searching == TOG_SEARCH_FORWARD)
8396 re = TAILQ_NEXT(re, entry);
8397 else
8398 re = TAILQ_PREV(re, tog_reflist_head, entry);
8401 if (s->matched_entry) {
8402 s->first_displayed_entry = s->matched_entry;
8403 s->selected = 0;
8406 return NULL;
8409 static const struct got_error *
8410 show_ref_view(struct tog_view *view)
8412 const struct got_error *err = NULL;
8413 struct tog_ref_view_state *s = &view->state.ref;
8414 struct tog_reflist_entry *re;
8415 char *line = NULL;
8416 wchar_t *wline;
8417 struct tog_color *tc;
8418 int width, n, scrollx;
8419 int limit = view->nlines;
8421 werase(view->window);
8423 s->ndisplayed = 0;
8424 if (view_is_hsplit_top(view))
8425 --limit; /* border */
8427 if (limit == 0)
8428 return NULL;
8430 re = s->first_displayed_entry;
8432 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8433 s->nrefs) == -1)
8434 return got_error_from_errno("asprintf");
8436 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8437 if (err) {
8438 free(line);
8439 return err;
8441 if (view_needs_focus_indication(view))
8442 wstandout(view->window);
8443 waddwstr(view->window, wline);
8444 while (width++ < view->ncols)
8445 waddch(view->window, ' ');
8446 if (view_needs_focus_indication(view))
8447 wstandend(view->window);
8448 free(wline);
8449 wline = NULL;
8450 free(line);
8451 line = NULL;
8452 if (--limit <= 0)
8453 return NULL;
8455 n = 0;
8456 view->maxx = 0;
8457 while (re && limit > 0) {
8458 char *line = NULL;
8459 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8461 if (s->show_date) {
8462 struct got_commit_object *ci;
8463 struct got_tag_object *tag;
8464 struct got_object_id *id;
8465 struct tm tm;
8466 time_t t;
8468 err = got_ref_resolve(&id, s->repo, re->ref);
8469 if (err)
8470 return err;
8471 err = got_object_open_as_tag(&tag, s->repo, id);
8472 if (err) {
8473 if (err->code != GOT_ERR_OBJ_TYPE) {
8474 free(id);
8475 return err;
8477 err = got_object_open_as_commit(&ci, s->repo,
8478 id);
8479 if (err) {
8480 free(id);
8481 return err;
8483 t = got_object_commit_get_committer_time(ci);
8484 got_object_commit_close(ci);
8485 } else {
8486 t = got_object_tag_get_tagger_time(tag);
8487 got_object_tag_close(tag);
8489 free(id);
8490 if (gmtime_r(&t, &tm) == NULL)
8491 return got_error_from_errno("gmtime_r");
8492 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8493 return got_error(GOT_ERR_NO_SPACE);
8495 if (got_ref_is_symbolic(re->ref)) {
8496 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8497 ymd : "", got_ref_get_name(re->ref),
8498 got_ref_get_symref_target(re->ref)) == -1)
8499 return got_error_from_errno("asprintf");
8500 } else if (s->show_ids) {
8501 struct got_object_id *id;
8502 char *id_str;
8503 err = got_ref_resolve(&id, s->repo, re->ref);
8504 if (err)
8505 return err;
8506 err = got_object_id_str(&id_str, id);
8507 if (err) {
8508 free(id);
8509 return err;
8511 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8512 got_ref_get_name(re->ref), id_str) == -1) {
8513 err = got_error_from_errno("asprintf");
8514 free(id);
8515 free(id_str);
8516 return err;
8518 free(id);
8519 free(id_str);
8520 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8521 got_ref_get_name(re->ref)) == -1)
8522 return got_error_from_errno("asprintf");
8524 /* use full line width to determine view->maxx */
8525 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8526 if (err) {
8527 free(line);
8528 return err;
8530 view->maxx = MAX(view->maxx, width);
8531 free(wline);
8532 wline = NULL;
8534 err = format_line(&wline, &width, &scrollx, line, view->x,
8535 view->ncols, 0, 0);
8536 if (err) {
8537 free(line);
8538 return err;
8540 if (n == s->selected) {
8541 if (view->focussed)
8542 wstandout(view->window);
8543 s->selected_entry = re;
8545 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8546 if (tc)
8547 wattr_on(view->window,
8548 COLOR_PAIR(tc->colorpair), NULL);
8549 waddwstr(view->window, &wline[scrollx]);
8550 if (tc)
8551 wattr_off(view->window,
8552 COLOR_PAIR(tc->colorpair), NULL);
8553 if (width < view->ncols)
8554 waddch(view->window, '\n');
8555 if (n == s->selected && view->focussed)
8556 wstandend(view->window);
8557 free(line);
8558 free(wline);
8559 wline = NULL;
8560 n++;
8561 s->ndisplayed++;
8562 s->last_displayed_entry = re;
8564 limit--;
8565 re = TAILQ_NEXT(re, entry);
8568 view_border(view);
8569 return err;
8572 static const struct got_error *
8573 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8574 struct tog_reflist_entry *re, struct got_repository *repo)
8576 const struct got_error *err = NULL;
8577 struct got_object_id *commit_id = NULL;
8578 struct tog_view *tree_view;
8580 *new_view = NULL;
8582 err = resolve_reflist_entry(&commit_id, re, repo);
8583 if (err) {
8584 if (err->code != GOT_ERR_OBJ_TYPE)
8585 return err;
8586 else
8587 return NULL;
8591 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8592 if (tree_view == NULL) {
8593 err = got_error_from_errno("view_open");
8594 goto done;
8597 err = open_tree_view(tree_view, commit_id,
8598 got_ref_get_name(re->ref), repo);
8599 if (err)
8600 goto done;
8602 *new_view = tree_view;
8603 done:
8604 free(commit_id);
8605 return err;
8608 static const struct got_error *
8609 ref_goto_line(struct tog_view *view, int nlines)
8611 const struct got_error *err = NULL;
8612 struct tog_ref_view_state *s = &view->state.ref;
8613 int g, idx = s->selected_entry->idx;
8615 g = view->gline;
8616 view->gline = 0;
8618 if (g == 0)
8619 g = 1;
8620 else if (g > s->nrefs)
8621 g = s->nrefs;
8623 if (g >= s->first_displayed_entry->idx + 1 &&
8624 g <= s->last_displayed_entry->idx + 1 &&
8625 g - s->first_displayed_entry->idx - 1 < nlines) {
8626 s->selected = g - s->first_displayed_entry->idx - 1;
8627 return NULL;
8630 if (idx + 1 < g) {
8631 err = ref_scroll_down(view, g - idx - 1);
8632 if (err)
8633 return err;
8634 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8635 s->first_displayed_entry->idx + s->selected < g &&
8636 s->selected < s->ndisplayed - 1)
8637 s->selected = g - s->first_displayed_entry->idx - 1;
8638 } else if (idx + 1 > g)
8639 ref_scroll_up(s, idx - g + 1);
8641 if (g < nlines && s->first_displayed_entry->idx == 0)
8642 s->selected = g - 1;
8644 return NULL;
8648 static const struct got_error *
8649 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8651 const struct got_error *err = NULL;
8652 struct tog_ref_view_state *s = &view->state.ref;
8653 struct tog_reflist_entry *re;
8654 int n, nscroll = view->nlines - 1;
8656 if (view->gline)
8657 return ref_goto_line(view, nscroll);
8659 switch (ch) {
8660 case '0':
8661 case '$':
8662 case KEY_RIGHT:
8663 case 'l':
8664 case KEY_LEFT:
8665 case 'h':
8666 horizontal_scroll_input(view, ch);
8667 break;
8668 case 'i':
8669 s->show_ids = !s->show_ids;
8670 view->count = 0;
8671 break;
8672 case 'm':
8673 s->show_date = !s->show_date;
8674 view->count = 0;
8675 break;
8676 case 'o':
8677 s->sort_by_date = !s->sort_by_date;
8678 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8679 view->count = 0;
8680 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8681 got_ref_cmp_by_commit_timestamp_descending :
8682 tog_ref_cmp_by_name, s->repo);
8683 if (err)
8684 break;
8685 got_reflist_object_id_map_free(tog_refs_idmap);
8686 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8687 &tog_refs, s->repo);
8688 if (err)
8689 break;
8690 ref_view_free_refs(s);
8691 err = ref_view_load_refs(s);
8692 break;
8693 case KEY_ENTER:
8694 case '\r':
8695 view->count = 0;
8696 if (!s->selected_entry)
8697 break;
8698 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8699 break;
8700 case 'T':
8701 view->count = 0;
8702 if (!s->selected_entry)
8703 break;
8704 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8705 break;
8706 case 'g':
8707 case '=':
8708 case KEY_HOME:
8709 s->selected = 0;
8710 view->count = 0;
8711 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8712 break;
8713 case 'G':
8714 case '*':
8715 case KEY_END: {
8716 int eos = view->nlines - 1;
8718 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8719 --eos; /* border */
8720 s->selected = 0;
8721 view->count = 0;
8722 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8723 for (n = 0; n < eos; n++) {
8724 if (re == NULL)
8725 break;
8726 s->first_displayed_entry = re;
8727 re = TAILQ_PREV(re, tog_reflist_head, entry);
8729 if (n > 0)
8730 s->selected = n - 1;
8731 break;
8733 case 'k':
8734 case KEY_UP:
8735 case CTRL('p'):
8736 if (s->selected > 0) {
8737 s->selected--;
8738 break;
8740 ref_scroll_up(s, 1);
8741 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8742 view->count = 0;
8743 break;
8744 case CTRL('u'):
8745 case 'u':
8746 nscroll /= 2;
8747 /* FALL THROUGH */
8748 case KEY_PPAGE:
8749 case CTRL('b'):
8750 case 'b':
8751 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8752 s->selected -= MIN(nscroll, s->selected);
8753 ref_scroll_up(s, MAX(0, nscroll));
8754 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8755 view->count = 0;
8756 break;
8757 case 'j':
8758 case KEY_DOWN:
8759 case CTRL('n'):
8760 if (s->selected < s->ndisplayed - 1) {
8761 s->selected++;
8762 break;
8764 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8765 /* can't scroll any further */
8766 view->count = 0;
8767 break;
8769 ref_scroll_down(view, 1);
8770 break;
8771 case CTRL('d'):
8772 case 'd':
8773 nscroll /= 2;
8774 /* FALL THROUGH */
8775 case KEY_NPAGE:
8776 case CTRL('f'):
8777 case 'f':
8778 case ' ':
8779 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8780 /* can't scroll any further; move cursor down */
8781 if (s->selected < s->ndisplayed - 1)
8782 s->selected += MIN(nscroll,
8783 s->ndisplayed - s->selected - 1);
8784 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8785 s->selected += s->ndisplayed - s->selected - 1;
8786 view->count = 0;
8787 break;
8789 ref_scroll_down(view, nscroll);
8790 break;
8791 case CTRL('l'):
8792 view->count = 0;
8793 tog_free_refs();
8794 err = tog_load_refs(s->repo, s->sort_by_date);
8795 if (err)
8796 break;
8797 ref_view_free_refs(s);
8798 err = ref_view_load_refs(s);
8799 break;
8800 case KEY_RESIZE:
8801 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8802 s->selected = view->nlines - 2;
8803 break;
8804 default:
8805 view->count = 0;
8806 break;
8809 return err;
8812 __dead static void
8813 usage_ref(void)
8815 endwin();
8816 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8817 getprogname());
8818 exit(1);
8821 static const struct got_error *
8822 cmd_ref(int argc, char *argv[])
8824 const struct got_error *error;
8825 struct got_repository *repo = NULL;
8826 struct got_worktree *worktree = NULL;
8827 char *cwd = NULL, *repo_path = NULL;
8828 int ch;
8829 struct tog_view *view;
8830 int *pack_fds = NULL;
8832 while ((ch = getopt(argc, argv, "r:")) != -1) {
8833 switch (ch) {
8834 case 'r':
8835 repo_path = realpath(optarg, NULL);
8836 if (repo_path == NULL)
8837 return got_error_from_errno2("realpath",
8838 optarg);
8839 break;
8840 default:
8841 usage_ref();
8842 /* NOTREACHED */
8846 argc -= optind;
8847 argv += optind;
8849 if (argc > 1)
8850 usage_ref();
8852 error = got_repo_pack_fds_open(&pack_fds);
8853 if (error != NULL)
8854 goto done;
8856 if (repo_path == NULL) {
8857 cwd = getcwd(NULL, 0);
8858 if (cwd == NULL)
8859 return got_error_from_errno("getcwd");
8860 error = got_worktree_open(&worktree, cwd);
8861 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8862 goto done;
8863 if (worktree)
8864 repo_path =
8865 strdup(got_worktree_get_repo_path(worktree));
8866 else
8867 repo_path = strdup(cwd);
8868 if (repo_path == NULL) {
8869 error = got_error_from_errno("strdup");
8870 goto done;
8874 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8875 if (error != NULL)
8876 goto done;
8878 init_curses();
8880 error = apply_unveil(got_repo_get_path(repo), NULL);
8881 if (error)
8882 goto done;
8884 error = tog_load_refs(repo, 0);
8885 if (error)
8886 goto done;
8888 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8889 if (view == NULL) {
8890 error = got_error_from_errno("view_open");
8891 goto done;
8894 error = open_ref_view(view, repo);
8895 if (error)
8896 goto done;
8898 if (worktree) {
8899 /* Release work tree lock. */
8900 got_worktree_close(worktree);
8901 worktree = NULL;
8903 error = view_loop(view);
8904 done:
8905 free(repo_path);
8906 free(cwd);
8907 if (repo) {
8908 const struct got_error *close_err = got_repo_close(repo);
8909 if (close_err)
8910 error = close_err;
8912 if (pack_fds) {
8913 const struct got_error *pack_err =
8914 got_repo_pack_fds_close(pack_fds);
8915 if (error == NULL)
8916 error = pack_err;
8918 tog_free_refs();
8919 return error;
8922 static const struct got_error*
8923 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8924 const char *str)
8926 size_t len;
8928 if (win == NULL)
8929 win = stdscr;
8931 len = strlen(str);
8932 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8934 if (focus)
8935 wstandout(win);
8936 if (mvwprintw(win, y, x, "%s", str) == ERR)
8937 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8938 if (focus)
8939 wstandend(win);
8941 return NULL;
8944 static const struct got_error *
8945 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8947 off_t *p;
8949 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8950 if (p == NULL) {
8951 free(*line_offsets);
8952 *line_offsets = NULL;
8953 return got_error_from_errno("reallocarray");
8956 *line_offsets = p;
8957 (*line_offsets)[*nlines] = off;
8958 ++(*nlines);
8959 return NULL;
8962 static const struct got_error *
8963 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8965 *ret = 0;
8967 for (;n > 0; --n, ++km) {
8968 char *t0, *t, *k;
8969 size_t len = 1;
8971 if (km->keys == NULL)
8972 continue;
8974 t = t0 = strdup(km->keys);
8975 if (t0 == NULL)
8976 return got_error_from_errno("strdup");
8978 len += strlen(t);
8979 while ((k = strsep(&t, " ")) != NULL)
8980 len += strlen(k) > 1 ? 2 : 0;
8981 free(t0);
8982 *ret = MAX(*ret, len);
8985 return NULL;
8989 * Write keymap section headers, keys, and key info in km to f.
8990 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8991 * wrap control and symbolic keys in guillemets, else use <>.
8993 static const struct got_error *
8994 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8996 int n, len = width;
8998 if (km->keys) {
8999 static const char *u8_glyph[] = {
9000 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9001 "\xe2\x80\xba" /* U+203A (utf8 >) */
9003 char *t0, *t, *k;
9004 int cs, s, first = 1;
9006 cs = got_locale_is_utf8();
9008 t = t0 = strdup(km->keys);
9009 if (t0 == NULL)
9010 return got_error_from_errno("strdup");
9012 len = strlen(km->keys);
9013 while ((k = strsep(&t, " ")) != NULL) {
9014 s = strlen(k) > 1; /* control or symbolic key */
9015 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9016 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9017 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9018 if (n < 0) {
9019 free(t0);
9020 return got_error_from_errno("fprintf");
9022 first = 0;
9023 len += s ? 2 : 0;
9024 *off += n;
9026 free(t0);
9028 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9029 if (n < 0)
9030 return got_error_from_errno("fprintf");
9031 *off += n;
9033 return NULL;
9036 static const struct got_error *
9037 format_help(struct tog_help_view_state *s)
9039 const struct got_error *err = NULL;
9040 off_t off = 0;
9041 int i, max, n, show = s->all;
9042 static const struct tog_key_map km[] = {
9043 #define KEYMAP_(info, type) { NULL, (info), type }
9044 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9045 GENERATE_HELP
9046 #undef KEYMAP_
9047 #undef KEY_
9050 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9051 if (err)
9052 return err;
9054 n = nitems(km);
9055 err = max_key_str(&max, km, n);
9056 if (err)
9057 return err;
9059 for (i = 0; i < n; ++i) {
9060 if (km[i].keys == NULL) {
9061 show = s->all;
9062 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9063 km[i].type == s->type || s->all)
9064 show = 1;
9066 if (show) {
9067 err = format_help_line(&off, s->f, &km[i], max);
9068 if (err)
9069 return err;
9070 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9071 if (err)
9072 return err;
9075 fputc('\n', s->f);
9076 ++off;
9077 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9078 return err;
9081 static const struct got_error *
9082 create_help(struct tog_help_view_state *s)
9084 FILE *f;
9085 const struct got_error *err;
9087 free(s->line_offsets);
9088 s->line_offsets = NULL;
9089 s->nlines = 0;
9091 f = got_opentemp();
9092 if (f == NULL)
9093 return got_error_from_errno("got_opentemp");
9094 s->f = f;
9096 err = format_help(s);
9097 if (err)
9098 return err;
9100 if (s->f && fflush(s->f) != 0)
9101 return got_error_from_errno("fflush");
9103 return NULL;
9106 static const struct got_error *
9107 search_start_help_view(struct tog_view *view)
9109 view->state.help.matched_line = 0;
9110 return NULL;
9113 static void
9114 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9115 size_t *nlines, int **first, int **last, int **match, int **selected)
9117 struct tog_help_view_state *s = &view->state.help;
9119 *f = s->f;
9120 *nlines = s->nlines;
9121 *line_offsets = s->line_offsets;
9122 *match = &s->matched_line;
9123 *first = &s->first_displayed_line;
9124 *last = &s->last_displayed_line;
9125 *selected = &s->selected_line;
9128 static const struct got_error *
9129 show_help_view(struct tog_view *view)
9131 struct tog_help_view_state *s = &view->state.help;
9132 const struct got_error *err;
9133 regmatch_t *regmatch = &view->regmatch;
9134 wchar_t *wline;
9135 char *line;
9136 ssize_t linelen;
9137 size_t linesz = 0;
9138 int width, nprinted = 0, rc = 0;
9139 int eos = view->nlines;
9141 if (view_is_hsplit_top(view))
9142 --eos; /* account for border */
9144 s->lineno = 0;
9145 rewind(s->f);
9146 werase(view->window);
9148 if (view->gline > s->nlines - 1)
9149 view->gline = s->nlines - 1;
9151 err = win_draw_center(view->window, 0, 0, view->ncols,
9152 view_needs_focus_indication(view),
9153 "tog help (press q to return to tog)");
9154 if (err)
9155 return err;
9156 if (eos <= 1)
9157 return NULL;
9158 waddstr(view->window, "\n\n");
9159 eos -= 2;
9161 s->eof = 0;
9162 view->maxx = 0;
9163 line = NULL;
9164 while (eos > 0 && nprinted < eos) {
9165 attr_t attr = 0;
9167 linelen = getline(&line, &linesz, s->f);
9168 if (linelen == -1) {
9169 if (!feof(s->f)) {
9170 free(line);
9171 return got_ferror(s->f, GOT_ERR_IO);
9173 s->eof = 1;
9174 break;
9176 if (++s->lineno < s->first_displayed_line)
9177 continue;
9178 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9179 continue;
9180 if (s->lineno == view->hiline)
9181 attr = A_STANDOUT;
9183 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9184 view->x ? 1 : 0);
9185 if (err) {
9186 free(line);
9187 return err;
9189 view->maxx = MAX(view->maxx, width);
9190 free(wline);
9191 wline = NULL;
9193 if (attr)
9194 wattron(view->window, attr);
9195 if (s->first_displayed_line + nprinted == s->matched_line &&
9196 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9197 err = add_matched_line(&width, line, view->ncols - 1, 0,
9198 view->window, view->x, regmatch);
9199 if (err) {
9200 free(line);
9201 return err;
9203 } else {
9204 int skip;
9206 err = format_line(&wline, &width, &skip, line,
9207 view->x, view->ncols, 0, view->x ? 1 : 0);
9208 if (err) {
9209 free(line);
9210 return err;
9212 waddwstr(view->window, &wline[skip]);
9213 free(wline);
9214 wline = NULL;
9216 if (s->lineno == view->hiline) {
9217 while (width++ < view->ncols)
9218 waddch(view->window, ' ');
9219 } else {
9220 if (width < view->ncols)
9221 waddch(view->window, '\n');
9223 if (attr)
9224 wattroff(view->window, attr);
9225 if (++nprinted == 1)
9226 s->first_displayed_line = s->lineno;
9228 free(line);
9229 if (nprinted > 0)
9230 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9231 else
9232 s->last_displayed_line = s->first_displayed_line;
9234 view_border(view);
9236 if (s->eof) {
9237 rc = waddnstr(view->window,
9238 "See the tog(1) manual page for full documentation",
9239 view->ncols - 1);
9240 if (rc == ERR)
9241 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9242 } else {
9243 wmove(view->window, view->nlines - 1, 0);
9244 wclrtoeol(view->window);
9245 wstandout(view->window);
9246 rc = waddnstr(view->window, "scroll down for more...",
9247 view->ncols - 1);
9248 if (rc == ERR)
9249 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9250 if (getcurx(view->window) < view->ncols - 6) {
9251 rc = wprintw(view->window, "[%.0f%%]",
9252 100.00 * s->last_displayed_line / s->nlines);
9253 if (rc == ERR)
9254 return got_error_msg(GOT_ERR_IO, "wprintw");
9256 wstandend(view->window);
9259 return NULL;
9262 static const struct got_error *
9263 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9265 struct tog_help_view_state *s = &view->state.help;
9266 const struct got_error *err = NULL;
9267 char *line = NULL;
9268 ssize_t linelen;
9269 size_t linesz = 0;
9270 int eos, nscroll;
9272 eos = nscroll = view->nlines;
9273 if (view_is_hsplit_top(view))
9274 --eos; /* border */
9276 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9278 switch (ch) {
9279 case '0':
9280 case '$':
9281 case KEY_RIGHT:
9282 case 'l':
9283 case KEY_LEFT:
9284 case 'h':
9285 horizontal_scroll_input(view, ch);
9286 break;
9287 case 'g':
9288 case KEY_HOME:
9289 s->first_displayed_line = 1;
9290 view->count = 0;
9291 break;
9292 case 'G':
9293 case KEY_END:
9294 view->count = 0;
9295 if (s->eof)
9296 break;
9297 s->first_displayed_line = (s->nlines - eos) + 3;
9298 s->eof = 1;
9299 break;
9300 case 'k':
9301 case KEY_UP:
9302 if (s->first_displayed_line > 1)
9303 --s->first_displayed_line;
9304 else
9305 view->count = 0;
9306 break;
9307 case CTRL('u'):
9308 case 'u':
9309 nscroll /= 2;
9310 /* FALL THROUGH */
9311 case KEY_PPAGE:
9312 case CTRL('b'):
9313 case 'b':
9314 if (s->first_displayed_line == 1) {
9315 view->count = 0;
9316 break;
9318 while (--nscroll > 0 && s->first_displayed_line > 1)
9319 s->first_displayed_line--;
9320 break;
9321 case 'j':
9322 case KEY_DOWN:
9323 case CTRL('n'):
9324 if (!s->eof)
9325 ++s->first_displayed_line;
9326 else
9327 view->count = 0;
9328 break;
9329 case CTRL('d'):
9330 case 'd':
9331 nscroll /= 2;
9332 /* FALL THROUGH */
9333 case KEY_NPAGE:
9334 case CTRL('f'):
9335 case 'f':
9336 case ' ':
9337 if (s->eof) {
9338 view->count = 0;
9339 break;
9341 while (!s->eof && --nscroll > 0) {
9342 linelen = getline(&line, &linesz, s->f);
9343 s->first_displayed_line++;
9344 if (linelen == -1) {
9345 if (feof(s->f))
9346 s->eof = 1;
9347 else
9348 err = got_ferror(s->f, GOT_ERR_IO);
9349 break;
9352 free(line);
9353 break;
9354 default:
9355 view->count = 0;
9356 break;
9359 return err;
9362 static const struct got_error *
9363 close_help_view(struct tog_view *view)
9365 struct tog_help_view_state *s = &view->state.help;
9367 free(s->line_offsets);
9368 s->line_offsets = NULL;
9369 if (fclose(s->f) == EOF)
9370 return got_error_from_errno("fclose");
9372 return NULL;
9375 static const struct got_error *
9376 reset_help_view(struct tog_view *view)
9378 struct tog_help_view_state *s = &view->state.help;
9381 if (s->f && fclose(s->f) == EOF)
9382 return got_error_from_errno("fclose");
9384 wclear(view->window);
9385 view->count = 0;
9386 view->x = 0;
9387 s->all = !s->all;
9388 s->first_displayed_line = 1;
9389 s->last_displayed_line = view->nlines;
9390 s->matched_line = 0;
9392 return create_help(s);
9395 static const struct got_error *
9396 open_help_view(struct tog_view *view, struct tog_view *parent)
9398 const struct got_error *err = NULL;
9399 struct tog_help_view_state *s = &view->state.help;
9401 s->type = (enum tog_keymap_type)parent->type;
9402 s->first_displayed_line = 1;
9403 s->last_displayed_line = view->nlines;
9404 s->selected_line = 1;
9406 view->show = show_help_view;
9407 view->input = input_help_view;
9408 view->reset = reset_help_view;
9409 view->close = close_help_view;
9410 view->search_start = search_start_help_view;
9411 view->search_setup = search_setup_help_view;
9412 view->search_next = search_next_view_match;
9414 err = create_help(s);
9415 return err;
9418 static const struct got_error *
9419 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9420 enum tog_view_type request, int y, int x)
9422 const struct got_error *err = NULL;
9424 *new_view = NULL;
9426 switch (request) {
9427 case TOG_VIEW_DIFF:
9428 if (view->type == TOG_VIEW_LOG) {
9429 struct tog_log_view_state *s = &view->state.log;
9431 err = open_diff_view_for_commit(new_view, y, x,
9432 s->selected_entry->commit, s->selected_entry->id,
9433 view, s->repo);
9434 } else
9435 return got_error_msg(GOT_ERR_NOT_IMPL,
9436 "parent/child view pair not supported");
9437 break;
9438 case TOG_VIEW_BLAME:
9439 if (view->type == TOG_VIEW_TREE) {
9440 struct tog_tree_view_state *s = &view->state.tree;
9442 err = blame_tree_entry(new_view, y, x,
9443 s->selected_entry, &s->parents, s->commit_id,
9444 s->repo);
9445 } else
9446 return got_error_msg(GOT_ERR_NOT_IMPL,
9447 "parent/child view pair not supported");
9448 break;
9449 case TOG_VIEW_LOG:
9450 if (view->type == TOG_VIEW_BLAME)
9451 err = log_annotated_line(new_view, y, x,
9452 view->state.blame.repo, view->state.blame.id_to_log);
9453 else if (view->type == TOG_VIEW_TREE)
9454 err = log_selected_tree_entry(new_view, y, x,
9455 &view->state.tree);
9456 else if (view->type == TOG_VIEW_REF)
9457 err = log_ref_entry(new_view, y, x,
9458 view->state.ref.selected_entry,
9459 view->state.ref.repo);
9460 else
9461 return got_error_msg(GOT_ERR_NOT_IMPL,
9462 "parent/child view pair not supported");
9463 break;
9464 case TOG_VIEW_TREE:
9465 if (view->type == TOG_VIEW_LOG)
9466 err = browse_commit_tree(new_view, y, x,
9467 view->state.log.selected_entry,
9468 view->state.log.in_repo_path,
9469 view->state.log.head_ref_name,
9470 view->state.log.repo);
9471 else if (view->type == TOG_VIEW_REF)
9472 err = browse_ref_tree(new_view, y, x,
9473 view->state.ref.selected_entry,
9474 view->state.ref.repo);
9475 else
9476 return got_error_msg(GOT_ERR_NOT_IMPL,
9477 "parent/child view pair not supported");
9478 break;
9479 case TOG_VIEW_REF:
9480 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9481 if (*new_view == NULL)
9482 return got_error_from_errno("view_open");
9483 if (view->type == TOG_VIEW_LOG)
9484 err = open_ref_view(*new_view, view->state.log.repo);
9485 else if (view->type == TOG_VIEW_TREE)
9486 err = open_ref_view(*new_view, view->state.tree.repo);
9487 else
9488 err = got_error_msg(GOT_ERR_NOT_IMPL,
9489 "parent/child view pair not supported");
9490 if (err)
9491 view_close(*new_view);
9492 break;
9493 case TOG_VIEW_HELP:
9494 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9495 if (*new_view == NULL)
9496 return got_error_from_errno("view_open");
9497 err = open_help_view(*new_view, view);
9498 if (err)
9499 view_close(*new_view);
9500 break;
9501 default:
9502 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9505 return err;
9509 * If view was scrolled down to move the selected line into view when opening a
9510 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9512 static void
9513 offset_selection_up(struct tog_view *view)
9515 switch (view->type) {
9516 case TOG_VIEW_BLAME: {
9517 struct tog_blame_view_state *s = &view->state.blame;
9518 if (s->first_displayed_line == 1) {
9519 s->selected_line = MAX(s->selected_line - view->offset,
9520 1);
9521 break;
9523 if (s->first_displayed_line > view->offset)
9524 s->first_displayed_line -= view->offset;
9525 else
9526 s->first_displayed_line = 1;
9527 s->selected_line += view->offset;
9528 break;
9530 case TOG_VIEW_LOG:
9531 log_scroll_up(&view->state.log, view->offset);
9532 view->state.log.selected += view->offset;
9533 break;
9534 case TOG_VIEW_REF:
9535 ref_scroll_up(&view->state.ref, view->offset);
9536 view->state.ref.selected += view->offset;
9537 break;
9538 case TOG_VIEW_TREE:
9539 tree_scroll_up(&view->state.tree, view->offset);
9540 view->state.tree.selected += view->offset;
9541 break;
9542 default:
9543 break;
9546 view->offset = 0;
9550 * If the selected line is in the section of screen covered by the bottom split,
9551 * scroll down offset lines to move it into view and index its new position.
9553 static const struct got_error *
9554 offset_selection_down(struct tog_view *view)
9556 const struct got_error *err = NULL;
9557 const struct got_error *(*scrolld)(struct tog_view *, int);
9558 int *selected = NULL;
9559 int header, offset;
9561 switch (view->type) {
9562 case TOG_VIEW_BLAME: {
9563 struct tog_blame_view_state *s = &view->state.blame;
9564 header = 3;
9565 scrolld = NULL;
9566 if (s->selected_line > view->nlines - header) {
9567 offset = abs(view->nlines - s->selected_line - header);
9568 s->first_displayed_line += offset;
9569 s->selected_line -= offset;
9570 view->offset = offset;
9572 break;
9574 case TOG_VIEW_LOG: {
9575 struct tog_log_view_state *s = &view->state.log;
9576 scrolld = &log_scroll_down;
9577 header = view_is_parent_view(view) ? 3 : 2;
9578 selected = &s->selected;
9579 break;
9581 case TOG_VIEW_REF: {
9582 struct tog_ref_view_state *s = &view->state.ref;
9583 scrolld = &ref_scroll_down;
9584 header = 3;
9585 selected = &s->selected;
9586 break;
9588 case TOG_VIEW_TREE: {
9589 struct tog_tree_view_state *s = &view->state.tree;
9590 scrolld = &tree_scroll_down;
9591 header = 5;
9592 selected = &s->selected;
9593 break;
9595 default:
9596 selected = NULL;
9597 scrolld = NULL;
9598 header = 0;
9599 break;
9602 if (selected && *selected > view->nlines - header) {
9603 offset = abs(view->nlines - *selected - header);
9604 view->offset = offset;
9605 if (scrolld && offset) {
9606 err = scrolld(view, offset);
9607 *selected -= offset;
9611 return err;
9614 static void
9615 list_commands(FILE *fp)
9617 size_t i;
9619 fprintf(fp, "commands:");
9620 for (i = 0; i < nitems(tog_commands); i++) {
9621 const struct tog_cmd *cmd = &tog_commands[i];
9622 fprintf(fp, " %s", cmd->name);
9624 fputc('\n', fp);
9627 __dead static void
9628 usage(int hflag, int status)
9630 FILE *fp = (status == 0) ? stdout : stderr;
9632 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9633 getprogname());
9634 if (hflag) {
9635 fprintf(fp, "lazy usage: %s path\n", getprogname());
9636 list_commands(fp);
9638 exit(status);
9641 static char **
9642 make_argv(int argc, ...)
9644 va_list ap;
9645 char **argv;
9646 int i;
9648 va_start(ap, argc);
9650 argv = calloc(argc, sizeof(char *));
9651 if (argv == NULL)
9652 err(1, "calloc");
9653 for (i = 0; i < argc; i++) {
9654 argv[i] = strdup(va_arg(ap, char *));
9655 if (argv[i] == NULL)
9656 err(1, "strdup");
9659 va_end(ap);
9660 return argv;
9664 * Try to convert 'tog path' into a 'tog log path' command.
9665 * The user could simply have mistyped the command rather than knowingly
9666 * provided a path. So check whether argv[0] can in fact be resolved
9667 * to a path in the HEAD commit and print a special error if not.
9668 * This hack is for mpi@ <3
9670 static const struct got_error *
9671 tog_log_with_path(int argc, char *argv[])
9673 const struct got_error *error = NULL, *close_err;
9674 const struct tog_cmd *cmd = NULL;
9675 struct got_repository *repo = NULL;
9676 struct got_worktree *worktree = NULL;
9677 struct got_object_id *commit_id = NULL, *id = NULL;
9678 struct got_commit_object *commit = NULL;
9679 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9680 char *commit_id_str = NULL, **cmd_argv = NULL;
9681 int *pack_fds = NULL;
9683 cwd = getcwd(NULL, 0);
9684 if (cwd == NULL)
9685 return got_error_from_errno("getcwd");
9687 error = got_repo_pack_fds_open(&pack_fds);
9688 if (error != NULL)
9689 goto done;
9691 error = got_worktree_open(&worktree, cwd);
9692 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9693 goto done;
9695 if (worktree)
9696 repo_path = strdup(got_worktree_get_repo_path(worktree));
9697 else
9698 repo_path = strdup(cwd);
9699 if (repo_path == NULL) {
9700 error = got_error_from_errno("strdup");
9701 goto done;
9704 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9705 if (error != NULL)
9706 goto done;
9708 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9709 repo, worktree);
9710 if (error)
9711 goto done;
9713 error = tog_load_refs(repo, 0);
9714 if (error)
9715 goto done;
9716 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9717 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9718 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9719 if (error)
9720 goto done;
9722 if (worktree) {
9723 got_worktree_close(worktree);
9724 worktree = NULL;
9727 error = got_object_open_as_commit(&commit, repo, commit_id);
9728 if (error)
9729 goto done;
9731 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9732 if (error) {
9733 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9734 goto done;
9735 fprintf(stderr, "%s: '%s' is no known command or path\n",
9736 getprogname(), argv[0]);
9737 usage(1, 1);
9738 /* not reached */
9741 error = got_object_id_str(&commit_id_str, commit_id);
9742 if (error)
9743 goto done;
9745 cmd = &tog_commands[0]; /* log */
9746 argc = 4;
9747 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9748 error = cmd->cmd_main(argc, cmd_argv);
9749 done:
9750 if (repo) {
9751 close_err = got_repo_close(repo);
9752 if (error == NULL)
9753 error = close_err;
9755 if (commit)
9756 got_object_commit_close(commit);
9757 if (worktree)
9758 got_worktree_close(worktree);
9759 if (pack_fds) {
9760 const struct got_error *pack_err =
9761 got_repo_pack_fds_close(pack_fds);
9762 if (error == NULL)
9763 error = pack_err;
9765 free(id);
9766 free(commit_id_str);
9767 free(commit_id);
9768 free(cwd);
9769 free(repo_path);
9770 free(in_repo_path);
9771 if (cmd_argv) {
9772 int i;
9773 for (i = 0; i < argc; i++)
9774 free(cmd_argv[i]);
9775 free(cmd_argv);
9777 tog_free_refs();
9778 return error;
9781 int
9782 main(int argc, char *argv[])
9784 const struct got_error *io_err, *error = NULL;
9785 const struct tog_cmd *cmd = NULL;
9786 int ch, hflag = 0, Vflag = 0;
9787 char **cmd_argv = NULL;
9788 static const struct option longopts[] = {
9789 { "version", no_argument, NULL, 'V' },
9790 { NULL, 0, NULL, 0}
9792 char *diff_algo_str = NULL;
9793 const char *test_script_path;
9795 setlocale(LC_CTYPE, "");
9798 * Test mode init must happen before pledge() because "tty" will
9799 * not allow TTY-related ioctls to occur via regular files.
9801 test_script_path = getenv("TOG_TEST_SCRIPT");
9802 if (test_script_path != NULL) {
9803 error = init_mock_term(test_script_path);
9804 if (error) {
9805 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9806 return 1;
9808 } else if (!isatty(STDIN_FILENO))
9809 errx(1, "standard input is not a tty");
9811 #if !defined(PROFILE)
9812 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9813 NULL) == -1)
9814 err(1, "pledge");
9815 #endif
9817 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9818 switch (ch) {
9819 case 'h':
9820 hflag = 1;
9821 break;
9822 case 'V':
9823 Vflag = 1;
9824 break;
9825 default:
9826 usage(hflag, 1);
9827 /* NOTREACHED */
9831 argc -= optind;
9832 argv += optind;
9833 optind = 1;
9834 optreset = 1;
9836 if (Vflag) {
9837 got_version_print_str();
9838 return 0;
9841 if (argc == 0) {
9842 if (hflag)
9843 usage(hflag, 0);
9844 /* Build an argument vector which runs a default command. */
9845 cmd = &tog_commands[0];
9846 argc = 1;
9847 cmd_argv = make_argv(argc, cmd->name);
9848 } else {
9849 size_t i;
9851 /* Did the user specify a command? */
9852 for (i = 0; i < nitems(tog_commands); i++) {
9853 if (strncmp(tog_commands[i].name, argv[0],
9854 strlen(argv[0])) == 0) {
9855 cmd = &tog_commands[i];
9856 break;
9861 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9862 if (diff_algo_str) {
9863 if (strcasecmp(diff_algo_str, "patience") == 0)
9864 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9865 if (strcasecmp(diff_algo_str, "myers") == 0)
9866 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9869 if (cmd == NULL) {
9870 if (argc != 1)
9871 usage(0, 1);
9872 /* No command specified; try log with a path */
9873 error = tog_log_with_path(argc, argv);
9874 } else {
9875 if (hflag)
9876 cmd->cmd_usage();
9877 else
9878 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9881 if (using_mock_io) {
9882 io_err = tog_io_close();
9883 if (error == NULL)
9884 error = io_err;
9886 endwin();
9887 if (cmd_argv) {
9888 int i;
9889 for (i = 0; i < argc; i++)
9890 free(cmd_argv[i]);
9891 free(cmd_argv);
9894 if (error && error->code != GOT_ERR_CANCELLED &&
9895 error->code != GOT_ERR_EOF &&
9896 error->code != GOT_ERR_PRIVSEP_EXIT &&
9897 error->code != GOT_ERR_PRIVSEP_PIPE &&
9898 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9899 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9900 return 0;