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;
4190 if (test_script_path == NULL || *test_script_path == '\0')
4191 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4193 tog_io.f = fopen(test_script_path, "re");
4194 if (tog_io.f == NULL) {
4195 err = got_error_from_errno_fmt("fopen: %s",
4196 test_script_path);
4197 goto done;
4200 /* test mode, we don't want any output */
4201 tog_io.cout = fopen("/dev/null", "w+");
4202 if (tog_io.cout == NULL) {
4203 err = got_error_from_errno("fopen: /dev/null");
4204 goto done;
4207 tog_io.cin = fopen("/dev/tty", "r+");
4208 if (tog_io.cin == NULL) {
4209 err = got_error_from_errno("fopen: /dev/tty");
4210 goto done;
4213 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4214 err = got_error_from_errno("fseeko");
4215 goto done;
4218 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4219 err = got_error_msg(GOT_ERR_IO,
4220 "newterm: failed to initialise curses");
4222 using_mock_io = 1;
4224 done:
4225 if (err)
4226 tog_io_close();
4227 return err;
4230 static void
4231 init_curses(void)
4234 * Override default signal handlers before starting ncurses.
4235 * This should prevent ncurses from installing its own
4236 * broken cleanup() signal handler.
4238 signal(SIGWINCH, tog_sigwinch);
4239 signal(SIGPIPE, tog_sigpipe);
4240 signal(SIGCONT, tog_sigcont);
4241 signal(SIGINT, tog_sigint);
4242 signal(SIGTERM, tog_sigterm);
4244 if (using_mock_io) /* In test mode we use a fake terminal */
4245 return;
4247 initscr();
4249 cbreak();
4250 halfdelay(1); /* Fast refresh while initial view is loading. */
4251 noecho();
4252 nonl();
4253 intrflush(stdscr, FALSE);
4254 keypad(stdscr, TRUE);
4255 curs_set(0);
4256 if (getenv("TOG_COLORS") != NULL) {
4257 start_color();
4258 use_default_colors();
4261 return;
4264 static const struct got_error *
4265 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4266 struct got_repository *repo, struct got_worktree *worktree)
4268 const struct got_error *err = NULL;
4270 if (argc == 0) {
4271 *in_repo_path = strdup("/");
4272 if (*in_repo_path == NULL)
4273 return got_error_from_errno("strdup");
4274 return NULL;
4277 if (worktree) {
4278 const char *prefix = got_worktree_get_path_prefix(worktree);
4279 char *p;
4281 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4282 if (err)
4283 return err;
4284 if (asprintf(in_repo_path, "%s%s%s", prefix,
4285 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4286 p) == -1) {
4287 err = got_error_from_errno("asprintf");
4288 *in_repo_path = NULL;
4290 free(p);
4291 } else
4292 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4294 return err;
4297 static const struct got_error *
4298 cmd_log(int argc, char *argv[])
4300 const struct got_error *error;
4301 struct got_repository *repo = NULL;
4302 struct got_worktree *worktree = NULL;
4303 struct got_object_id *start_id = NULL;
4304 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4305 char *start_commit = NULL, *label = NULL;
4306 struct got_reference *ref = NULL;
4307 const char *head_ref_name = NULL;
4308 int ch, log_branches = 0;
4309 struct tog_view *view;
4310 int *pack_fds = NULL;
4312 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4313 switch (ch) {
4314 case 'b':
4315 log_branches = 1;
4316 break;
4317 case 'c':
4318 start_commit = optarg;
4319 break;
4320 case 'r':
4321 repo_path = realpath(optarg, NULL);
4322 if (repo_path == NULL)
4323 return got_error_from_errno2("realpath",
4324 optarg);
4325 break;
4326 default:
4327 usage_log();
4328 /* NOTREACHED */
4332 argc -= optind;
4333 argv += optind;
4335 if (argc > 1)
4336 usage_log();
4338 error = got_repo_pack_fds_open(&pack_fds);
4339 if (error != NULL)
4340 goto done;
4342 if (repo_path == NULL) {
4343 cwd = getcwd(NULL, 0);
4344 if (cwd == NULL)
4345 return got_error_from_errno("getcwd");
4346 error = got_worktree_open(&worktree, cwd);
4347 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4348 goto done;
4349 if (worktree)
4350 repo_path =
4351 strdup(got_worktree_get_repo_path(worktree));
4352 else
4353 repo_path = strdup(cwd);
4354 if (repo_path == NULL) {
4355 error = got_error_from_errno("strdup");
4356 goto done;
4360 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4361 if (error != NULL)
4362 goto done;
4364 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4365 repo, worktree);
4366 if (error)
4367 goto done;
4369 init_curses();
4371 error = apply_unveil(got_repo_get_path(repo),
4372 worktree ? got_worktree_get_root_path(worktree) : NULL);
4373 if (error)
4374 goto done;
4376 /* already loaded by tog_log_with_path()? */
4377 if (TAILQ_EMPTY(&tog_refs)) {
4378 error = tog_load_refs(repo, 0);
4379 if (error)
4380 goto done;
4383 if (start_commit == NULL) {
4384 error = got_repo_match_object_id(&start_id, &label,
4385 worktree ? got_worktree_get_head_ref_name(worktree) :
4386 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4387 if (error)
4388 goto done;
4389 head_ref_name = label;
4390 } else {
4391 error = got_ref_open(&ref, repo, start_commit, 0);
4392 if (error == NULL)
4393 head_ref_name = got_ref_get_name(ref);
4394 else if (error->code != GOT_ERR_NOT_REF)
4395 goto done;
4396 error = got_repo_match_object_id(&start_id, NULL,
4397 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4398 if (error)
4399 goto done;
4402 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4403 if (view == NULL) {
4404 error = got_error_from_errno("view_open");
4405 goto done;
4407 error = open_log_view(view, start_id, repo, head_ref_name,
4408 in_repo_path, log_branches);
4409 if (error)
4410 goto done;
4411 if (worktree) {
4412 /* Release work tree lock. */
4413 got_worktree_close(worktree);
4414 worktree = NULL;
4416 error = view_loop(view);
4417 done:
4418 free(in_repo_path);
4419 free(repo_path);
4420 free(cwd);
4421 free(start_id);
4422 free(label);
4423 if (ref)
4424 got_ref_close(ref);
4425 if (repo) {
4426 const struct got_error *close_err = got_repo_close(repo);
4427 if (error == NULL)
4428 error = close_err;
4430 if (worktree)
4431 got_worktree_close(worktree);
4432 if (pack_fds) {
4433 const struct got_error *pack_err =
4434 got_repo_pack_fds_close(pack_fds);
4435 if (error == NULL)
4436 error = pack_err;
4438 tog_free_refs();
4439 return error;
4442 __dead static void
4443 usage_diff(void)
4445 endwin();
4446 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4447 "object1 object2\n", getprogname());
4448 exit(1);
4451 static int
4452 match_line(const char *line, regex_t *regex, size_t nmatch,
4453 regmatch_t *regmatch)
4455 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4458 static struct tog_color *
4459 match_color(struct tog_colors *colors, const char *line)
4461 struct tog_color *tc = NULL;
4463 STAILQ_FOREACH(tc, colors, entry) {
4464 if (match_line(line, &tc->regex, 0, NULL))
4465 return tc;
4468 return NULL;
4471 static const struct got_error *
4472 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4473 WINDOW *window, int skipcol, regmatch_t *regmatch)
4475 const struct got_error *err = NULL;
4476 char *exstr = NULL;
4477 wchar_t *wline = NULL;
4478 int rme, rms, n, width, scrollx;
4479 int width0 = 0, width1 = 0, width2 = 0;
4480 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4482 *wtotal = 0;
4484 rms = regmatch->rm_so;
4485 rme = regmatch->rm_eo;
4487 err = expand_tab(&exstr, line);
4488 if (err)
4489 return err;
4491 /* Split the line into 3 segments, according to match offsets. */
4492 seg0 = strndup(exstr, rms);
4493 if (seg0 == NULL) {
4494 err = got_error_from_errno("strndup");
4495 goto done;
4497 seg1 = strndup(exstr + rms, rme - rms);
4498 if (seg1 == NULL) {
4499 err = got_error_from_errno("strndup");
4500 goto done;
4502 seg2 = strdup(exstr + rme);
4503 if (seg2 == NULL) {
4504 err = got_error_from_errno("strndup");
4505 goto done;
4508 /* draw up to matched token if we haven't scrolled past it */
4509 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4510 col_tab_align, 1);
4511 if (err)
4512 goto done;
4513 n = MAX(width0 - skipcol, 0);
4514 if (n) {
4515 free(wline);
4516 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4517 wlimit, col_tab_align, 1);
4518 if (err)
4519 goto done;
4520 waddwstr(window, &wline[scrollx]);
4521 wlimit -= width;
4522 *wtotal += width;
4525 if (wlimit > 0) {
4526 int i = 0, w = 0;
4527 size_t wlen;
4529 free(wline);
4530 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4531 col_tab_align, 1);
4532 if (err)
4533 goto done;
4534 wlen = wcslen(wline);
4535 while (i < wlen) {
4536 width = wcwidth(wline[i]);
4537 if (width == -1) {
4538 /* should not happen, tabs are expanded */
4539 err = got_error(GOT_ERR_RANGE);
4540 goto done;
4542 if (width0 + w + width > skipcol)
4543 break;
4544 w += width;
4545 i++;
4547 /* draw (visible part of) matched token (if scrolled into it) */
4548 if (width1 - w > 0) {
4549 wattron(window, A_STANDOUT);
4550 waddwstr(window, &wline[i]);
4551 wattroff(window, A_STANDOUT);
4552 wlimit -= (width1 - w);
4553 *wtotal += (width1 - w);
4557 if (wlimit > 0) { /* draw rest of line */
4558 free(wline);
4559 if (skipcol > width0 + width1) {
4560 err = format_line(&wline, &width2, &scrollx, seg2,
4561 skipcol - (width0 + width1), wlimit,
4562 col_tab_align, 1);
4563 if (err)
4564 goto done;
4565 waddwstr(window, &wline[scrollx]);
4566 } else {
4567 err = format_line(&wline, &width2, NULL, seg2, 0,
4568 wlimit, col_tab_align, 1);
4569 if (err)
4570 goto done;
4571 waddwstr(window, wline);
4573 *wtotal += width2;
4575 done:
4576 free(wline);
4577 free(exstr);
4578 free(seg0);
4579 free(seg1);
4580 free(seg2);
4581 return err;
4584 static int
4585 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4587 FILE *f = NULL;
4588 int *eof, *first, *selected;
4590 if (view->type == TOG_VIEW_DIFF) {
4591 struct tog_diff_view_state *s = &view->state.diff;
4593 first = &s->first_displayed_line;
4594 selected = first;
4595 eof = &s->eof;
4596 f = s->f;
4597 } else if (view->type == TOG_VIEW_HELP) {
4598 struct tog_help_view_state *s = &view->state.help;
4600 first = &s->first_displayed_line;
4601 selected = first;
4602 eof = &s->eof;
4603 f = s->f;
4604 } else if (view->type == TOG_VIEW_BLAME) {
4605 struct tog_blame_view_state *s = &view->state.blame;
4607 first = &s->first_displayed_line;
4608 selected = &s->selected_line;
4609 eof = &s->eof;
4610 f = s->blame.f;
4611 } else
4612 return 0;
4614 /* Center gline in the middle of the page like vi(1). */
4615 if (*lineno < view->gline - (view->nlines - 3) / 2)
4616 return 0;
4617 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4618 rewind(f);
4619 *eof = 0;
4620 *first = 1;
4621 *lineno = 0;
4622 *nprinted = 0;
4623 return 0;
4626 *selected = view->gline <= (view->nlines - 3) / 2 ?
4627 view->gline : (view->nlines - 3) / 2 + 1;
4628 view->gline = 0;
4630 return 1;
4633 static const struct got_error *
4634 draw_file(struct tog_view *view, const char *header)
4636 struct tog_diff_view_state *s = &view->state.diff;
4637 regmatch_t *regmatch = &view->regmatch;
4638 const struct got_error *err;
4639 int nprinted = 0;
4640 char *line;
4641 size_t linesize = 0;
4642 ssize_t linelen;
4643 wchar_t *wline;
4644 int width;
4645 int max_lines = view->nlines;
4646 int nlines = s->nlines;
4647 off_t line_offset;
4649 s->lineno = s->first_displayed_line - 1;
4650 line_offset = s->lines[s->first_displayed_line - 1].offset;
4651 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4652 return got_error_from_errno("fseek");
4654 werase(view->window);
4656 if (view->gline > s->nlines - 1)
4657 view->gline = s->nlines - 1;
4659 if (header) {
4660 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4661 1 : view->gline - (view->nlines - 3) / 2 :
4662 s->lineno + s->selected_line;
4664 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4665 return got_error_from_errno("asprintf");
4666 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4667 0, 0);
4668 free(line);
4669 if (err)
4670 return err;
4672 if (view_needs_focus_indication(view))
4673 wstandout(view->window);
4674 waddwstr(view->window, wline);
4675 free(wline);
4676 wline = NULL;
4677 while (width++ < view->ncols)
4678 waddch(view->window, ' ');
4679 if (view_needs_focus_indication(view))
4680 wstandend(view->window);
4682 if (max_lines <= 1)
4683 return NULL;
4684 max_lines--;
4687 s->eof = 0;
4688 view->maxx = 0;
4689 line = NULL;
4690 while (max_lines > 0 && nprinted < max_lines) {
4691 enum got_diff_line_type linetype;
4692 attr_t attr = 0;
4694 linelen = getline(&line, &linesize, s->f);
4695 if (linelen == -1) {
4696 if (feof(s->f)) {
4697 s->eof = 1;
4698 break;
4700 free(line);
4701 return got_ferror(s->f, GOT_ERR_IO);
4704 if (++s->lineno < s->first_displayed_line)
4705 continue;
4706 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4707 continue;
4708 if (s->lineno == view->hiline)
4709 attr = A_STANDOUT;
4711 /* Set view->maxx based on full line length. */
4712 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4713 view->x ? 1 : 0);
4714 if (err) {
4715 free(line);
4716 return err;
4718 view->maxx = MAX(view->maxx, width);
4719 free(wline);
4720 wline = NULL;
4722 linetype = s->lines[s->lineno].type;
4723 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4724 linetype < GOT_DIFF_LINE_CONTEXT)
4725 attr |= COLOR_PAIR(linetype);
4726 if (attr)
4727 wattron(view->window, attr);
4728 if (s->first_displayed_line + nprinted == s->matched_line &&
4729 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4730 err = add_matched_line(&width, line, view->ncols, 0,
4731 view->window, view->x, regmatch);
4732 if (err) {
4733 free(line);
4734 return err;
4736 } else {
4737 int skip;
4738 err = format_line(&wline, &width, &skip, line,
4739 view->x, view->ncols, 0, view->x ? 1 : 0);
4740 if (err) {
4741 free(line);
4742 return err;
4744 waddwstr(view->window, &wline[skip]);
4745 free(wline);
4746 wline = NULL;
4748 if (s->lineno == view->hiline) {
4749 /* highlight full gline length */
4750 while (width++ < view->ncols)
4751 waddch(view->window, ' ');
4752 } else {
4753 if (width <= view->ncols - 1)
4754 waddch(view->window, '\n');
4756 if (attr)
4757 wattroff(view->window, attr);
4758 if (++nprinted == 1)
4759 s->first_displayed_line = s->lineno;
4761 free(line);
4762 if (nprinted >= 1)
4763 s->last_displayed_line = s->first_displayed_line +
4764 (nprinted - 1);
4765 else
4766 s->last_displayed_line = s->first_displayed_line;
4768 view_border(view);
4770 if (s->eof) {
4771 while (nprinted < view->nlines) {
4772 waddch(view->window, '\n');
4773 nprinted++;
4776 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4777 view->ncols, 0, 0);
4778 if (err) {
4779 return err;
4782 wstandout(view->window);
4783 waddwstr(view->window, wline);
4784 free(wline);
4785 wline = NULL;
4786 wstandend(view->window);
4789 return NULL;
4792 static char *
4793 get_datestr(time_t *time, char *datebuf)
4795 struct tm mytm, *tm;
4796 char *p, *s;
4798 tm = gmtime_r(time, &mytm);
4799 if (tm == NULL)
4800 return NULL;
4801 s = asctime_r(tm, datebuf);
4802 if (s == NULL)
4803 return NULL;
4804 p = strchr(s, '\n');
4805 if (p)
4806 *p = '\0';
4807 return s;
4810 static const struct got_error *
4811 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4812 off_t off, uint8_t type)
4814 struct got_diff_line *p;
4816 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4817 if (p == NULL)
4818 return got_error_from_errno("reallocarray");
4819 *lines = p;
4820 (*lines)[*nlines].offset = off;
4821 (*lines)[*nlines].type = type;
4822 (*nlines)++;
4824 return NULL;
4827 static const struct got_error *
4828 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4829 struct got_diff_line *s_lines, size_t s_nlines)
4831 struct got_diff_line *p;
4832 char buf[BUFSIZ];
4833 size_t i, r;
4835 if (fseeko(src, 0L, SEEK_SET) == -1)
4836 return got_error_from_errno("fseeko");
4838 for (;;) {
4839 r = fread(buf, 1, sizeof(buf), src);
4840 if (r == 0) {
4841 if (ferror(src))
4842 return got_error_from_errno("fread");
4843 if (feof(src))
4844 break;
4846 if (fwrite(buf, 1, r, dst) != r)
4847 return got_ferror(dst, GOT_ERR_IO);
4850 if (s_nlines == 0 && *d_nlines == 0)
4851 return NULL;
4854 * If commit info was in dst, increment line offsets
4855 * of the appended diff content, but skip s_lines[0]
4856 * because offset zero is already in *d_lines.
4858 if (*d_nlines > 0) {
4859 for (i = 1; i < s_nlines; ++i)
4860 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4862 if (s_nlines > 0) {
4863 --s_nlines;
4864 ++s_lines;
4868 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4869 if (p == NULL) {
4870 /* d_lines is freed in close_diff_view() */
4871 return got_error_from_errno("reallocarray");
4874 *d_lines = p;
4876 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4877 *d_nlines += s_nlines;
4879 return NULL;
4882 static const struct got_error *
4883 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4884 struct got_object_id *commit_id, struct got_reflist_head *refs,
4885 struct got_repository *repo, int ignore_ws, int force_text_diff,
4886 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4888 const struct got_error *err = NULL;
4889 char datebuf[26], *datestr;
4890 struct got_commit_object *commit;
4891 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4892 time_t committer_time;
4893 const char *author, *committer;
4894 char *refs_str = NULL;
4895 struct got_pathlist_entry *pe;
4896 off_t outoff = 0;
4897 int n;
4899 if (refs) {
4900 err = build_refs_str(&refs_str, refs, commit_id, repo);
4901 if (err)
4902 return err;
4905 err = got_object_open_as_commit(&commit, repo, commit_id);
4906 if (err)
4907 return err;
4909 err = got_object_id_str(&id_str, commit_id);
4910 if (err) {
4911 err = got_error_from_errno("got_object_id_str");
4912 goto done;
4915 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4916 if (err)
4917 goto done;
4919 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4920 refs_str ? refs_str : "", refs_str ? ")" : "");
4921 if (n < 0) {
4922 err = got_error_from_errno("fprintf");
4923 goto done;
4925 outoff += n;
4926 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4927 if (err)
4928 goto done;
4930 n = fprintf(outfile, "from: %s\n",
4931 got_object_commit_get_author(commit));
4932 if (n < 0) {
4933 err = got_error_from_errno("fprintf");
4934 goto done;
4936 outoff += n;
4937 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4938 if (err)
4939 goto done;
4941 author = got_object_commit_get_author(commit);
4942 committer = got_object_commit_get_committer(commit);
4943 if (strcmp(author, committer) != 0) {
4944 n = fprintf(outfile, "via: %s\n", committer);
4945 if (n < 0) {
4946 err = got_error_from_errno("fprintf");
4947 goto done;
4949 outoff += n;
4950 err = add_line_metadata(lines, nlines, outoff,
4951 GOT_DIFF_LINE_AUTHOR);
4952 if (err)
4953 goto done;
4955 committer_time = got_object_commit_get_committer_time(commit);
4956 datestr = get_datestr(&committer_time, datebuf);
4957 if (datestr) {
4958 n = fprintf(outfile, "date: %s UTC\n", datestr);
4959 if (n < 0) {
4960 err = got_error_from_errno("fprintf");
4961 goto done;
4963 outoff += n;
4964 err = add_line_metadata(lines, nlines, outoff,
4965 GOT_DIFF_LINE_DATE);
4966 if (err)
4967 goto done;
4969 if (got_object_commit_get_nparents(commit) > 1) {
4970 const struct got_object_id_queue *parent_ids;
4971 struct got_object_qid *qid;
4972 int pn = 1;
4973 parent_ids = got_object_commit_get_parent_ids(commit);
4974 STAILQ_FOREACH(qid, parent_ids, entry) {
4975 err = got_object_id_str(&id_str, &qid->id);
4976 if (err)
4977 goto done;
4978 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4979 if (n < 0) {
4980 err = got_error_from_errno("fprintf");
4981 goto done;
4983 outoff += n;
4984 err = add_line_metadata(lines, nlines, outoff,
4985 GOT_DIFF_LINE_META);
4986 if (err)
4987 goto done;
4988 free(id_str);
4989 id_str = NULL;
4993 err = got_object_commit_get_logmsg(&logmsg, commit);
4994 if (err)
4995 goto done;
4996 s = logmsg;
4997 while ((line = strsep(&s, "\n")) != NULL) {
4998 n = fprintf(outfile, "%s\n", line);
4999 if (n < 0) {
5000 err = got_error_from_errno("fprintf");
5001 goto done;
5003 outoff += n;
5004 err = add_line_metadata(lines, nlines, outoff,
5005 GOT_DIFF_LINE_LOGMSG);
5006 if (err)
5007 goto done;
5010 TAILQ_FOREACH(pe, dsa->paths, entry) {
5011 struct got_diff_changed_path *cp = pe->data;
5012 int pad = dsa->max_path_len - pe->path_len + 1;
5014 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5015 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5016 dsa->rm_cols + 1, cp->rm);
5017 if (n < 0) {
5018 err = got_error_from_errno("fprintf");
5019 goto done;
5021 outoff += n;
5022 err = add_line_metadata(lines, nlines, outoff,
5023 GOT_DIFF_LINE_CHANGES);
5024 if (err)
5025 goto done;
5028 fputc('\n', outfile);
5029 outoff++;
5030 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5031 if (err)
5032 goto done;
5034 n = fprintf(outfile,
5035 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5036 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5037 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5038 if (n < 0) {
5039 err = got_error_from_errno("fprintf");
5040 goto done;
5042 outoff += n;
5043 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5044 if (err)
5045 goto done;
5047 fputc('\n', outfile);
5048 outoff++;
5049 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5050 done:
5051 free(id_str);
5052 free(logmsg);
5053 free(refs_str);
5054 got_object_commit_close(commit);
5055 if (err) {
5056 free(*lines);
5057 *lines = NULL;
5058 *nlines = 0;
5060 return err;
5063 static const struct got_error *
5064 create_diff(struct tog_diff_view_state *s)
5066 const struct got_error *err = NULL;
5067 FILE *f = NULL, *tmp_diff_file = NULL;
5068 int obj_type;
5069 struct got_diff_line *lines = NULL;
5070 struct got_pathlist_head changed_paths;
5072 TAILQ_INIT(&changed_paths);
5074 free(s->lines);
5075 s->lines = malloc(sizeof(*s->lines));
5076 if (s->lines == NULL)
5077 return got_error_from_errno("malloc");
5078 s->nlines = 0;
5080 f = got_opentemp();
5081 if (f == NULL) {
5082 err = got_error_from_errno("got_opentemp");
5083 goto done;
5085 tmp_diff_file = got_opentemp();
5086 if (tmp_diff_file == NULL) {
5087 err = got_error_from_errno("got_opentemp");
5088 goto done;
5090 if (s->f && fclose(s->f) == EOF) {
5091 err = got_error_from_errno("fclose");
5092 goto done;
5094 s->f = f;
5096 if (s->id1)
5097 err = got_object_get_type(&obj_type, s->repo, s->id1);
5098 else
5099 err = got_object_get_type(&obj_type, s->repo, s->id2);
5100 if (err)
5101 goto done;
5103 switch (obj_type) {
5104 case GOT_OBJ_TYPE_BLOB:
5105 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5106 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5107 s->label1, s->label2, tog_diff_algo, s->diff_context,
5108 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5109 s->f);
5110 break;
5111 case GOT_OBJ_TYPE_TREE:
5112 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5113 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5114 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5115 s->force_text_diff, NULL, s->repo, s->f);
5116 break;
5117 case GOT_OBJ_TYPE_COMMIT: {
5118 const struct got_object_id_queue *parent_ids;
5119 struct got_object_qid *pid;
5120 struct got_commit_object *commit2;
5121 struct got_reflist_head *refs;
5122 size_t nlines = 0;
5123 struct got_diffstat_cb_arg dsa = {
5124 0, 0, 0, 0, 0, 0,
5125 &changed_paths,
5126 s->ignore_whitespace,
5127 s->force_text_diff,
5128 tog_diff_algo
5131 lines = malloc(sizeof(*lines));
5132 if (lines == NULL) {
5133 err = got_error_from_errno("malloc");
5134 goto done;
5137 /* build diff first in tmp file then append to commit info */
5138 err = got_diff_objects_as_commits(&lines, &nlines,
5139 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5140 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5141 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5142 if (err)
5143 break;
5145 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5146 if (err)
5147 goto done;
5148 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5149 /* Show commit info if we're diffing to a parent/root commit. */
5150 if (s->id1 == NULL) {
5151 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5152 refs, s->repo, s->ignore_whitespace,
5153 s->force_text_diff, &dsa, s->f);
5154 if (err)
5155 goto done;
5156 } else {
5157 parent_ids = got_object_commit_get_parent_ids(commit2);
5158 STAILQ_FOREACH(pid, parent_ids, entry) {
5159 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5160 err = write_commit_info(&s->lines,
5161 &s->nlines, s->id2, refs, s->repo,
5162 s->ignore_whitespace,
5163 s->force_text_diff, &dsa, s->f);
5164 if (err)
5165 goto done;
5166 break;
5170 got_object_commit_close(commit2);
5172 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5173 lines, nlines);
5174 break;
5176 default:
5177 err = got_error(GOT_ERR_OBJ_TYPE);
5178 break;
5180 done:
5181 free(lines);
5182 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5183 if (s->f && fflush(s->f) != 0 && err == NULL)
5184 err = got_error_from_errno("fflush");
5185 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5186 err = got_error_from_errno("fclose");
5187 return err;
5190 static void
5191 diff_view_indicate_progress(struct tog_view *view)
5193 mvwaddstr(view->window, 0, 0, "diffing...");
5194 update_panels();
5195 doupdate();
5198 static const struct got_error *
5199 search_start_diff_view(struct tog_view *view)
5201 struct tog_diff_view_state *s = &view->state.diff;
5203 s->matched_line = 0;
5204 return NULL;
5207 static void
5208 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5209 size_t *nlines, int **first, int **last, int **match, int **selected)
5211 struct tog_diff_view_state *s = &view->state.diff;
5213 *f = s->f;
5214 *nlines = s->nlines;
5215 *line_offsets = NULL;
5216 *match = &s->matched_line;
5217 *first = &s->first_displayed_line;
5218 *last = &s->last_displayed_line;
5219 *selected = &s->selected_line;
5222 static const struct got_error *
5223 search_next_view_match(struct tog_view *view)
5225 const struct got_error *err = NULL;
5226 FILE *f;
5227 int lineno;
5228 char *line = NULL;
5229 size_t linesize = 0;
5230 ssize_t linelen;
5231 off_t *line_offsets;
5232 size_t nlines = 0;
5233 int *first, *last, *match, *selected;
5235 if (!view->search_setup)
5236 return got_error_msg(GOT_ERR_NOT_IMPL,
5237 "view search not supported");
5238 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5239 &match, &selected);
5241 if (!view->searching) {
5242 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5243 return NULL;
5246 if (*match) {
5247 if (view->searching == TOG_SEARCH_FORWARD)
5248 lineno = *first + 1;
5249 else
5250 lineno = *first - 1;
5251 } else
5252 lineno = *first - 1 + *selected;
5254 while (1) {
5255 off_t offset;
5257 if (lineno <= 0 || lineno > nlines) {
5258 if (*match == 0) {
5259 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5260 break;
5263 if (view->searching == TOG_SEARCH_FORWARD)
5264 lineno = 1;
5265 else
5266 lineno = nlines;
5269 offset = view->type == TOG_VIEW_DIFF ?
5270 view->state.diff.lines[lineno - 1].offset :
5271 line_offsets[lineno - 1];
5272 if (fseeko(f, offset, SEEK_SET) != 0) {
5273 free(line);
5274 return got_error_from_errno("fseeko");
5276 linelen = getline(&line, &linesize, f);
5277 if (linelen != -1) {
5278 char *exstr;
5279 err = expand_tab(&exstr, line);
5280 if (err)
5281 break;
5282 if (match_line(exstr, &view->regex, 1,
5283 &view->regmatch)) {
5284 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5285 *match = lineno;
5286 free(exstr);
5287 break;
5289 free(exstr);
5291 if (view->searching == TOG_SEARCH_FORWARD)
5292 lineno++;
5293 else
5294 lineno--;
5296 free(line);
5298 if (*match) {
5299 *first = *match;
5300 *selected = 1;
5303 return err;
5306 static const struct got_error *
5307 close_diff_view(struct tog_view *view)
5309 const struct got_error *err = NULL;
5310 struct tog_diff_view_state *s = &view->state.diff;
5312 free(s->id1);
5313 s->id1 = NULL;
5314 free(s->id2);
5315 s->id2 = NULL;
5316 if (s->f && fclose(s->f) == EOF)
5317 err = got_error_from_errno("fclose");
5318 s->f = NULL;
5319 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5320 err = got_error_from_errno("fclose");
5321 s->f1 = NULL;
5322 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5323 err = got_error_from_errno("fclose");
5324 s->f2 = NULL;
5325 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5326 err = got_error_from_errno("close");
5327 s->fd1 = -1;
5328 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5329 err = got_error_from_errno("close");
5330 s->fd2 = -1;
5331 free(s->lines);
5332 s->lines = NULL;
5333 s->nlines = 0;
5334 return err;
5337 static const struct got_error *
5338 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5339 struct got_object_id *id2, const char *label1, const char *label2,
5340 int diff_context, int ignore_whitespace, int force_text_diff,
5341 struct tog_view *parent_view, struct got_repository *repo)
5343 const struct got_error *err;
5344 struct tog_diff_view_state *s = &view->state.diff;
5346 memset(s, 0, sizeof(*s));
5347 s->fd1 = -1;
5348 s->fd2 = -1;
5350 if (id1 != NULL && id2 != NULL) {
5351 int type1, type2;
5353 err = got_object_get_type(&type1, repo, id1);
5354 if (err)
5355 goto done;
5356 err = got_object_get_type(&type2, repo, id2);
5357 if (err)
5358 goto done;
5360 if (type1 != type2) {
5361 err = got_error(GOT_ERR_OBJ_TYPE);
5362 goto done;
5365 s->first_displayed_line = 1;
5366 s->last_displayed_line = view->nlines;
5367 s->selected_line = 1;
5368 s->repo = repo;
5369 s->id1 = id1;
5370 s->id2 = id2;
5371 s->label1 = label1;
5372 s->label2 = label2;
5374 if (id1) {
5375 s->id1 = got_object_id_dup(id1);
5376 if (s->id1 == NULL) {
5377 err = got_error_from_errno("got_object_id_dup");
5378 goto done;
5380 } else
5381 s->id1 = NULL;
5383 s->id2 = got_object_id_dup(id2);
5384 if (s->id2 == NULL) {
5385 err = got_error_from_errno("got_object_id_dup");
5386 goto done;
5389 s->f1 = got_opentemp();
5390 if (s->f1 == NULL) {
5391 err = got_error_from_errno("got_opentemp");
5392 goto done;
5395 s->f2 = got_opentemp();
5396 if (s->f2 == NULL) {
5397 err = got_error_from_errno("got_opentemp");
5398 goto done;
5401 s->fd1 = got_opentempfd();
5402 if (s->fd1 == -1) {
5403 err = got_error_from_errno("got_opentempfd");
5404 goto done;
5407 s->fd2 = got_opentempfd();
5408 if (s->fd2 == -1) {
5409 err = got_error_from_errno("got_opentempfd");
5410 goto done;
5413 s->diff_context = diff_context;
5414 s->ignore_whitespace = ignore_whitespace;
5415 s->force_text_diff = force_text_diff;
5416 s->parent_view = parent_view;
5417 s->repo = repo;
5419 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5420 int rc;
5422 rc = init_pair(GOT_DIFF_LINE_MINUS,
5423 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5424 if (rc != ERR)
5425 rc = init_pair(GOT_DIFF_LINE_PLUS,
5426 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5427 if (rc != ERR)
5428 rc = init_pair(GOT_DIFF_LINE_HUNK,
5429 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5430 if (rc != ERR)
5431 rc = init_pair(GOT_DIFF_LINE_META,
5432 get_color_value("TOG_COLOR_DIFF_META"), -1);
5433 if (rc != ERR)
5434 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5435 get_color_value("TOG_COLOR_DIFF_META"), -1);
5436 if (rc != ERR)
5437 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5438 get_color_value("TOG_COLOR_DIFF_META"), -1);
5439 if (rc != ERR)
5440 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5441 get_color_value("TOG_COLOR_DIFF_META"), -1);
5442 if (rc != ERR)
5443 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5444 get_color_value("TOG_COLOR_AUTHOR"), -1);
5445 if (rc != ERR)
5446 rc = init_pair(GOT_DIFF_LINE_DATE,
5447 get_color_value("TOG_COLOR_DATE"), -1);
5448 if (rc == ERR) {
5449 err = got_error(GOT_ERR_RANGE);
5450 goto done;
5454 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5455 view_is_splitscreen(view))
5456 show_log_view(parent_view); /* draw border */
5457 diff_view_indicate_progress(view);
5459 err = create_diff(s);
5461 view->show = show_diff_view;
5462 view->input = input_diff_view;
5463 view->reset = reset_diff_view;
5464 view->close = close_diff_view;
5465 view->search_start = search_start_diff_view;
5466 view->search_setup = search_setup_diff_view;
5467 view->search_next = search_next_view_match;
5468 done:
5469 if (err) {
5470 if (view->close == NULL)
5471 close_diff_view(view);
5472 view_close(view);
5474 return err;
5477 static const struct got_error *
5478 show_diff_view(struct tog_view *view)
5480 const struct got_error *err;
5481 struct tog_diff_view_state *s = &view->state.diff;
5482 char *id_str1 = NULL, *id_str2, *header;
5483 const char *label1, *label2;
5485 if (s->id1) {
5486 err = got_object_id_str(&id_str1, s->id1);
5487 if (err)
5488 return err;
5489 label1 = s->label1 ? s->label1 : id_str1;
5490 } else
5491 label1 = "/dev/null";
5493 err = got_object_id_str(&id_str2, s->id2);
5494 if (err)
5495 return err;
5496 label2 = s->label2 ? s->label2 : id_str2;
5498 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5499 err = got_error_from_errno("asprintf");
5500 free(id_str1);
5501 free(id_str2);
5502 return err;
5504 free(id_str1);
5505 free(id_str2);
5507 err = draw_file(view, header);
5508 free(header);
5509 return err;
5512 static const struct got_error *
5513 set_selected_commit(struct tog_diff_view_state *s,
5514 struct commit_queue_entry *entry)
5516 const struct got_error *err;
5517 const struct got_object_id_queue *parent_ids;
5518 struct got_commit_object *selected_commit;
5519 struct got_object_qid *pid;
5521 free(s->id2);
5522 s->id2 = got_object_id_dup(entry->id);
5523 if (s->id2 == NULL)
5524 return got_error_from_errno("got_object_id_dup");
5526 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5527 if (err)
5528 return err;
5529 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5530 free(s->id1);
5531 pid = STAILQ_FIRST(parent_ids);
5532 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5533 got_object_commit_close(selected_commit);
5534 return NULL;
5537 static const struct got_error *
5538 reset_diff_view(struct tog_view *view)
5540 struct tog_diff_view_state *s = &view->state.diff;
5542 view->count = 0;
5543 wclear(view->window);
5544 s->first_displayed_line = 1;
5545 s->last_displayed_line = view->nlines;
5546 s->matched_line = 0;
5547 diff_view_indicate_progress(view);
5548 return create_diff(s);
5551 static void
5552 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5554 int start, i;
5556 i = start = s->first_displayed_line - 1;
5558 while (s->lines[i].type != type) {
5559 if (i == 0)
5560 i = s->nlines - 1;
5561 if (--i == start)
5562 return; /* do nothing, requested type not in file */
5565 s->selected_line = 1;
5566 s->first_displayed_line = i;
5569 static void
5570 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5572 int start, i;
5574 i = start = s->first_displayed_line + 1;
5576 while (s->lines[i].type != type) {
5577 if (i == s->nlines - 1)
5578 i = 0;
5579 if (++i == start)
5580 return; /* do nothing, requested type not in file */
5583 s->selected_line = 1;
5584 s->first_displayed_line = i;
5587 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5588 int, int, int);
5589 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5590 int, int);
5592 static const struct got_error *
5593 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5595 const struct got_error *err = NULL;
5596 struct tog_diff_view_state *s = &view->state.diff;
5597 struct tog_log_view_state *ls;
5598 struct commit_queue_entry *old_selected_entry;
5599 char *line = NULL;
5600 size_t linesize = 0;
5601 ssize_t linelen;
5602 int i, nscroll = view->nlines - 1, up = 0;
5604 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5606 switch (ch) {
5607 case '0':
5608 case '$':
5609 case KEY_RIGHT:
5610 case 'l':
5611 case KEY_LEFT:
5612 case 'h':
5613 horizontal_scroll_input(view, ch);
5614 break;
5615 case 'a':
5616 case 'w':
5617 if (ch == 'a') {
5618 s->force_text_diff = !s->force_text_diff;
5619 view->action = s->force_text_diff ?
5620 "force ASCII text enabled" :
5621 "force ASCII text disabled";
5623 else if (ch == 'w') {
5624 s->ignore_whitespace = !s->ignore_whitespace;
5625 view->action = s->ignore_whitespace ?
5626 "ignore whitespace enabled" :
5627 "ignore whitespace disabled";
5629 err = reset_diff_view(view);
5630 break;
5631 case 'g':
5632 case KEY_HOME:
5633 s->first_displayed_line = 1;
5634 view->count = 0;
5635 break;
5636 case 'G':
5637 case KEY_END:
5638 view->count = 0;
5639 if (s->eof)
5640 break;
5642 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5643 s->eof = 1;
5644 break;
5645 case 'k':
5646 case KEY_UP:
5647 case CTRL('p'):
5648 if (s->first_displayed_line > 1)
5649 s->first_displayed_line--;
5650 else
5651 view->count = 0;
5652 break;
5653 case CTRL('u'):
5654 case 'u':
5655 nscroll /= 2;
5656 /* FALL THROUGH */
5657 case KEY_PPAGE:
5658 case CTRL('b'):
5659 case 'b':
5660 if (s->first_displayed_line == 1) {
5661 view->count = 0;
5662 break;
5664 i = 0;
5665 while (i++ < nscroll && s->first_displayed_line > 1)
5666 s->first_displayed_line--;
5667 break;
5668 case 'j':
5669 case KEY_DOWN:
5670 case CTRL('n'):
5671 if (!s->eof)
5672 s->first_displayed_line++;
5673 else
5674 view->count = 0;
5675 break;
5676 case CTRL('d'):
5677 case 'd':
5678 nscroll /= 2;
5679 /* FALL THROUGH */
5680 case KEY_NPAGE:
5681 case CTRL('f'):
5682 case 'f':
5683 case ' ':
5684 if (s->eof) {
5685 view->count = 0;
5686 break;
5688 i = 0;
5689 while (!s->eof && i++ < nscroll) {
5690 linelen = getline(&line, &linesize, s->f);
5691 s->first_displayed_line++;
5692 if (linelen == -1) {
5693 if (feof(s->f)) {
5694 s->eof = 1;
5695 } else
5696 err = got_ferror(s->f, GOT_ERR_IO);
5697 break;
5700 free(line);
5701 break;
5702 case '(':
5703 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5704 break;
5705 case ')':
5706 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5707 break;
5708 case '{':
5709 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5710 break;
5711 case '}':
5712 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5713 break;
5714 case '[':
5715 if (s->diff_context > 0) {
5716 s->diff_context--;
5717 s->matched_line = 0;
5718 diff_view_indicate_progress(view);
5719 err = create_diff(s);
5720 if (s->first_displayed_line + view->nlines - 1 >
5721 s->nlines) {
5722 s->first_displayed_line = 1;
5723 s->last_displayed_line = view->nlines;
5725 } else
5726 view->count = 0;
5727 break;
5728 case ']':
5729 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5730 s->diff_context++;
5731 s->matched_line = 0;
5732 diff_view_indicate_progress(view);
5733 err = create_diff(s);
5734 } else
5735 view->count = 0;
5736 break;
5737 case '<':
5738 case ',':
5739 case 'K':
5740 up = 1;
5741 /* FALL THROUGH */
5742 case '>':
5743 case '.':
5744 case 'J':
5745 if (s->parent_view == NULL) {
5746 view->count = 0;
5747 break;
5749 s->parent_view->count = view->count;
5751 if (s->parent_view->type == TOG_VIEW_LOG) {
5752 ls = &s->parent_view->state.log;
5753 old_selected_entry = ls->selected_entry;
5755 err = input_log_view(NULL, s->parent_view,
5756 up ? KEY_UP : KEY_DOWN);
5757 if (err)
5758 break;
5759 view->count = s->parent_view->count;
5761 if (old_selected_entry == ls->selected_entry)
5762 break;
5764 err = set_selected_commit(s, ls->selected_entry);
5765 if (err)
5766 break;
5767 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5768 struct tog_blame_view_state *bs;
5769 struct got_object_id *id, *prev_id;
5771 bs = &s->parent_view->state.blame;
5772 prev_id = get_annotation_for_line(bs->blame.lines,
5773 bs->blame.nlines, bs->last_diffed_line);
5775 err = input_blame_view(&view, s->parent_view,
5776 up ? KEY_UP : KEY_DOWN);
5777 if (err)
5778 break;
5779 view->count = s->parent_view->count;
5781 if (prev_id == NULL)
5782 break;
5783 id = get_selected_commit_id(bs->blame.lines,
5784 bs->blame.nlines, bs->first_displayed_line,
5785 bs->selected_line);
5786 if (id == NULL)
5787 break;
5789 if (!got_object_id_cmp(prev_id, id))
5790 break;
5792 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5793 if (err)
5794 break;
5796 s->first_displayed_line = 1;
5797 s->last_displayed_line = view->nlines;
5798 s->matched_line = 0;
5799 view->x = 0;
5801 diff_view_indicate_progress(view);
5802 err = create_diff(s);
5803 break;
5804 default:
5805 view->count = 0;
5806 break;
5809 return err;
5812 static const struct got_error *
5813 cmd_diff(int argc, char *argv[])
5815 const struct got_error *error;
5816 struct got_repository *repo = NULL;
5817 struct got_worktree *worktree = NULL;
5818 struct got_object_id *id1 = NULL, *id2 = NULL;
5819 char *repo_path = NULL, *cwd = NULL;
5820 char *id_str1 = NULL, *id_str2 = NULL;
5821 char *label1 = NULL, *label2 = NULL;
5822 int diff_context = 3, ignore_whitespace = 0;
5823 int ch, force_text_diff = 0;
5824 const char *errstr;
5825 struct tog_view *view;
5826 int *pack_fds = NULL;
5828 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5829 switch (ch) {
5830 case 'a':
5831 force_text_diff = 1;
5832 break;
5833 case 'C':
5834 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5835 &errstr);
5836 if (errstr != NULL)
5837 errx(1, "number of context lines is %s: %s",
5838 errstr, errstr);
5839 break;
5840 case 'r':
5841 repo_path = realpath(optarg, NULL);
5842 if (repo_path == NULL)
5843 return got_error_from_errno2("realpath",
5844 optarg);
5845 got_path_strip_trailing_slashes(repo_path);
5846 break;
5847 case 'w':
5848 ignore_whitespace = 1;
5849 break;
5850 default:
5851 usage_diff();
5852 /* NOTREACHED */
5856 argc -= optind;
5857 argv += optind;
5859 if (argc == 0) {
5860 usage_diff(); /* TODO show local worktree changes */
5861 } else if (argc == 2) {
5862 id_str1 = argv[0];
5863 id_str2 = argv[1];
5864 } else
5865 usage_diff();
5867 error = got_repo_pack_fds_open(&pack_fds);
5868 if (error)
5869 goto done;
5871 if (repo_path == NULL) {
5872 cwd = getcwd(NULL, 0);
5873 if (cwd == NULL)
5874 return got_error_from_errno("getcwd");
5875 error = got_worktree_open(&worktree, cwd);
5876 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5877 goto done;
5878 if (worktree)
5879 repo_path =
5880 strdup(got_worktree_get_repo_path(worktree));
5881 else
5882 repo_path = strdup(cwd);
5883 if (repo_path == NULL) {
5884 error = got_error_from_errno("strdup");
5885 goto done;
5889 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5890 if (error)
5891 goto done;
5893 init_curses();
5895 error = apply_unveil(got_repo_get_path(repo), NULL);
5896 if (error)
5897 goto done;
5899 error = tog_load_refs(repo, 0);
5900 if (error)
5901 goto done;
5903 error = got_repo_match_object_id(&id1, &label1, id_str1,
5904 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5905 if (error)
5906 goto done;
5908 error = got_repo_match_object_id(&id2, &label2, id_str2,
5909 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5910 if (error)
5911 goto done;
5913 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5914 if (view == NULL) {
5915 error = got_error_from_errno("view_open");
5916 goto done;
5918 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5919 ignore_whitespace, force_text_diff, NULL, repo);
5920 if (error)
5921 goto done;
5922 error = view_loop(view);
5923 done:
5924 free(label1);
5925 free(label2);
5926 free(repo_path);
5927 free(cwd);
5928 if (repo) {
5929 const struct got_error *close_err = got_repo_close(repo);
5930 if (error == NULL)
5931 error = close_err;
5933 if (worktree)
5934 got_worktree_close(worktree);
5935 if (pack_fds) {
5936 const struct got_error *pack_err =
5937 got_repo_pack_fds_close(pack_fds);
5938 if (error == NULL)
5939 error = pack_err;
5941 tog_free_refs();
5942 return error;
5945 __dead static void
5946 usage_blame(void)
5948 endwin();
5949 fprintf(stderr,
5950 "usage: %s blame [-c commit] [-r repository-path] path\n",
5951 getprogname());
5952 exit(1);
5955 struct tog_blame_line {
5956 int annotated;
5957 struct got_object_id *id;
5960 static const struct got_error *
5961 draw_blame(struct tog_view *view)
5963 struct tog_blame_view_state *s = &view->state.blame;
5964 struct tog_blame *blame = &s->blame;
5965 regmatch_t *regmatch = &view->regmatch;
5966 const struct got_error *err;
5967 int lineno = 0, nprinted = 0;
5968 char *line = NULL;
5969 size_t linesize = 0;
5970 ssize_t linelen;
5971 wchar_t *wline;
5972 int width;
5973 struct tog_blame_line *blame_line;
5974 struct got_object_id *prev_id = NULL;
5975 char *id_str;
5976 struct tog_color *tc;
5978 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5979 if (err)
5980 return err;
5982 rewind(blame->f);
5983 werase(view->window);
5985 if (asprintf(&line, "commit %s", id_str) == -1) {
5986 err = got_error_from_errno("asprintf");
5987 free(id_str);
5988 return err;
5991 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5992 free(line);
5993 line = NULL;
5994 if (err)
5995 return err;
5996 if (view_needs_focus_indication(view))
5997 wstandout(view->window);
5998 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5999 if (tc)
6000 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6001 waddwstr(view->window, wline);
6002 while (width++ < view->ncols)
6003 waddch(view->window, ' ');
6004 if (tc)
6005 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6006 if (view_needs_focus_indication(view))
6007 wstandend(view->window);
6008 free(wline);
6009 wline = NULL;
6011 if (view->gline > blame->nlines)
6012 view->gline = blame->nlines;
6014 if (tog_io.wait_for_ui) {
6015 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6016 int rc;
6018 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6019 if (rc)
6020 return got_error_set_errno(rc, "pthread_cond_wait");
6021 tog_io.wait_for_ui = 0;
6024 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6025 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6026 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6027 free(id_str);
6028 return got_error_from_errno("asprintf");
6030 free(id_str);
6031 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6032 free(line);
6033 line = NULL;
6034 if (err)
6035 return err;
6036 waddwstr(view->window, wline);
6037 free(wline);
6038 wline = NULL;
6039 if (width < view->ncols - 1)
6040 waddch(view->window, '\n');
6042 s->eof = 0;
6043 view->maxx = 0;
6044 while (nprinted < view->nlines - 2) {
6045 linelen = getline(&line, &linesize, blame->f);
6046 if (linelen == -1) {
6047 if (feof(blame->f)) {
6048 s->eof = 1;
6049 break;
6051 free(line);
6052 return got_ferror(blame->f, GOT_ERR_IO);
6054 if (++lineno < s->first_displayed_line)
6055 continue;
6056 if (view->gline && !gotoline(view, &lineno, &nprinted))
6057 continue;
6059 /* Set view->maxx based on full line length. */
6060 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6061 if (err) {
6062 free(line);
6063 return err;
6065 free(wline);
6066 wline = NULL;
6067 view->maxx = MAX(view->maxx, width);
6069 if (nprinted == s->selected_line - 1)
6070 wstandout(view->window);
6072 if (blame->nlines > 0) {
6073 blame_line = &blame->lines[lineno - 1];
6074 if (blame_line->annotated && prev_id &&
6075 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6076 !(nprinted == s->selected_line - 1)) {
6077 waddstr(view->window, " ");
6078 } else if (blame_line->annotated) {
6079 char *id_str;
6080 err = got_object_id_str(&id_str,
6081 blame_line->id);
6082 if (err) {
6083 free(line);
6084 return err;
6086 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6087 if (tc)
6088 wattr_on(view->window,
6089 COLOR_PAIR(tc->colorpair), NULL);
6090 wprintw(view->window, "%.8s", id_str);
6091 if (tc)
6092 wattr_off(view->window,
6093 COLOR_PAIR(tc->colorpair), NULL);
6094 free(id_str);
6095 prev_id = blame_line->id;
6096 } else {
6097 waddstr(view->window, "........");
6098 prev_id = NULL;
6100 } else {
6101 waddstr(view->window, "........");
6102 prev_id = NULL;
6105 if (nprinted == s->selected_line - 1)
6106 wstandend(view->window);
6107 waddstr(view->window, " ");
6109 if (view->ncols <= 9) {
6110 width = 9;
6111 } else if (s->first_displayed_line + nprinted ==
6112 s->matched_line &&
6113 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6114 err = add_matched_line(&width, line, view->ncols - 9, 9,
6115 view->window, view->x, regmatch);
6116 if (err) {
6117 free(line);
6118 return err;
6120 width += 9;
6121 } else {
6122 int skip;
6123 err = format_line(&wline, &width, &skip, line,
6124 view->x, view->ncols - 9, 9, 1);
6125 if (err) {
6126 free(line);
6127 return err;
6129 waddwstr(view->window, &wline[skip]);
6130 width += 9;
6131 free(wline);
6132 wline = NULL;
6135 if (width <= view->ncols - 1)
6136 waddch(view->window, '\n');
6137 if (++nprinted == 1)
6138 s->first_displayed_line = lineno;
6140 free(line);
6141 s->last_displayed_line = lineno;
6143 view_border(view);
6145 return NULL;
6148 static const struct got_error *
6149 blame_cb(void *arg, int nlines, int lineno,
6150 struct got_commit_object *commit, struct got_object_id *id)
6152 const struct got_error *err = NULL;
6153 struct tog_blame_cb_args *a = arg;
6154 struct tog_blame_line *line;
6155 int errcode;
6157 if (nlines != a->nlines ||
6158 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6159 return got_error(GOT_ERR_RANGE);
6161 errcode = pthread_mutex_lock(&tog_mutex);
6162 if (errcode)
6163 return got_error_set_errno(errcode, "pthread_mutex_lock");
6165 if (*a->quit) { /* user has quit the blame view */
6166 err = got_error(GOT_ERR_ITER_COMPLETED);
6167 goto done;
6170 if (lineno == -1)
6171 goto done; /* no change in this commit */
6173 line = &a->lines[lineno - 1];
6174 if (line->annotated)
6175 goto done;
6177 line->id = got_object_id_dup(id);
6178 if (line->id == NULL) {
6179 err = got_error_from_errno("got_object_id_dup");
6180 goto done;
6182 line->annotated = 1;
6183 done:
6184 errcode = pthread_mutex_unlock(&tog_mutex);
6185 if (errcode)
6186 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6187 return err;
6190 static void *
6191 blame_thread(void *arg)
6193 const struct got_error *err, *close_err;
6194 struct tog_blame_thread_args *ta = arg;
6195 struct tog_blame_cb_args *a = ta->cb_args;
6196 int errcode, fd1 = -1, fd2 = -1;
6197 FILE *f1 = NULL, *f2 = NULL;
6199 fd1 = got_opentempfd();
6200 if (fd1 == -1)
6201 return (void *)got_error_from_errno("got_opentempfd");
6203 fd2 = got_opentempfd();
6204 if (fd2 == -1) {
6205 err = got_error_from_errno("got_opentempfd");
6206 goto done;
6209 f1 = got_opentemp();
6210 if (f1 == NULL) {
6211 err = (void *)got_error_from_errno("got_opentemp");
6212 goto done;
6214 f2 = got_opentemp();
6215 if (f2 == NULL) {
6216 err = (void *)got_error_from_errno("got_opentemp");
6217 goto done;
6220 err = block_signals_used_by_main_thread();
6221 if (err)
6222 goto done;
6224 err = got_blame(ta->path, a->commit_id, ta->repo,
6225 tog_diff_algo, blame_cb, ta->cb_args,
6226 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6227 if (err && err->code == GOT_ERR_CANCELLED)
6228 err = NULL;
6230 errcode = pthread_mutex_lock(&tog_mutex);
6231 if (errcode) {
6232 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6233 goto done;
6236 close_err = got_repo_close(ta->repo);
6237 if (err == NULL)
6238 err = close_err;
6239 ta->repo = NULL;
6240 *ta->complete = 1;
6242 if (tog_io.wait_for_ui) {
6243 errcode = pthread_cond_signal(&ta->blame_complete);
6244 if (errcode && err == NULL)
6245 err = got_error_set_errno(errcode,
6246 "pthread_cond_signal");
6249 errcode = pthread_mutex_unlock(&tog_mutex);
6250 if (errcode && err == NULL)
6251 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6253 done:
6254 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6255 err = got_error_from_errno("close");
6256 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6257 err = got_error_from_errno("close");
6258 if (f1 && fclose(f1) == EOF && err == NULL)
6259 err = got_error_from_errno("fclose");
6260 if (f2 && fclose(f2) == EOF && err == NULL)
6261 err = got_error_from_errno("fclose");
6263 return (void *)err;
6266 static struct got_object_id *
6267 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6268 int first_displayed_line, int selected_line)
6270 struct tog_blame_line *line;
6272 if (nlines <= 0)
6273 return NULL;
6275 line = &lines[first_displayed_line - 1 + selected_line - 1];
6276 if (!line->annotated)
6277 return NULL;
6279 return line->id;
6282 static struct got_object_id *
6283 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6284 int lineno)
6286 struct tog_blame_line *line;
6288 if (nlines <= 0 || lineno >= nlines)
6289 return NULL;
6291 line = &lines[lineno - 1];
6292 if (!line->annotated)
6293 return NULL;
6295 return line->id;
6298 static const struct got_error *
6299 stop_blame(struct tog_blame *blame)
6301 const struct got_error *err = NULL;
6302 int i;
6304 if (blame->thread) {
6305 int errcode;
6306 errcode = pthread_mutex_unlock(&tog_mutex);
6307 if (errcode)
6308 return got_error_set_errno(errcode,
6309 "pthread_mutex_unlock");
6310 errcode = pthread_join(blame->thread, (void **)&err);
6311 if (errcode)
6312 return got_error_set_errno(errcode, "pthread_join");
6313 errcode = pthread_mutex_lock(&tog_mutex);
6314 if (errcode)
6315 return got_error_set_errno(errcode,
6316 "pthread_mutex_lock");
6317 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6318 err = NULL;
6319 blame->thread = NULL;
6321 if (blame->thread_args.repo) {
6322 const struct got_error *close_err;
6323 close_err = got_repo_close(blame->thread_args.repo);
6324 if (err == NULL)
6325 err = close_err;
6326 blame->thread_args.repo = NULL;
6328 if (blame->f) {
6329 if (fclose(blame->f) == EOF && err == NULL)
6330 err = got_error_from_errno("fclose");
6331 blame->f = NULL;
6333 if (blame->lines) {
6334 for (i = 0; i < blame->nlines; i++)
6335 free(blame->lines[i].id);
6336 free(blame->lines);
6337 blame->lines = NULL;
6339 free(blame->cb_args.commit_id);
6340 blame->cb_args.commit_id = NULL;
6341 if (blame->pack_fds) {
6342 const struct got_error *pack_err =
6343 got_repo_pack_fds_close(blame->pack_fds);
6344 if (err == NULL)
6345 err = pack_err;
6346 blame->pack_fds = NULL;
6348 return err;
6351 static const struct got_error *
6352 cancel_blame_view(void *arg)
6354 const struct got_error *err = NULL;
6355 int *done = arg;
6356 int errcode;
6358 errcode = pthread_mutex_lock(&tog_mutex);
6359 if (errcode)
6360 return got_error_set_errno(errcode,
6361 "pthread_mutex_unlock");
6363 if (*done)
6364 err = got_error(GOT_ERR_CANCELLED);
6366 errcode = pthread_mutex_unlock(&tog_mutex);
6367 if (errcode)
6368 return got_error_set_errno(errcode,
6369 "pthread_mutex_lock");
6371 return err;
6374 static const struct got_error *
6375 run_blame(struct tog_view *view)
6377 struct tog_blame_view_state *s = &view->state.blame;
6378 struct tog_blame *blame = &s->blame;
6379 const struct got_error *err = NULL;
6380 struct got_commit_object *commit = NULL;
6381 struct got_blob_object *blob = NULL;
6382 struct got_repository *thread_repo = NULL;
6383 struct got_object_id *obj_id = NULL;
6384 int obj_type, fd = -1;
6385 int *pack_fds = NULL;
6387 err = got_object_open_as_commit(&commit, s->repo,
6388 &s->blamed_commit->id);
6389 if (err)
6390 return err;
6392 fd = got_opentempfd();
6393 if (fd == -1) {
6394 err = got_error_from_errno("got_opentempfd");
6395 goto done;
6398 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6399 if (err)
6400 goto done;
6402 err = got_object_get_type(&obj_type, s->repo, obj_id);
6403 if (err)
6404 goto done;
6406 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6407 err = got_error(GOT_ERR_OBJ_TYPE);
6408 goto done;
6411 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6412 if (err)
6413 goto done;
6414 blame->f = got_opentemp();
6415 if (blame->f == NULL) {
6416 err = got_error_from_errno("got_opentemp");
6417 goto done;
6419 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6420 &blame->line_offsets, blame->f, blob);
6421 if (err)
6422 goto done;
6423 if (blame->nlines == 0) {
6424 s->blame_complete = 1;
6425 goto done;
6428 /* Don't include \n at EOF in the blame line count. */
6429 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6430 blame->nlines--;
6432 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6433 if (blame->lines == NULL) {
6434 err = got_error_from_errno("calloc");
6435 goto done;
6438 err = got_repo_pack_fds_open(&pack_fds);
6439 if (err)
6440 goto done;
6441 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6442 pack_fds);
6443 if (err)
6444 goto done;
6446 blame->pack_fds = pack_fds;
6447 blame->cb_args.view = view;
6448 blame->cb_args.lines = blame->lines;
6449 blame->cb_args.nlines = blame->nlines;
6450 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6451 if (blame->cb_args.commit_id == NULL) {
6452 err = got_error_from_errno("got_object_id_dup");
6453 goto done;
6455 blame->cb_args.quit = &s->done;
6457 blame->thread_args.path = s->path;
6458 blame->thread_args.repo = thread_repo;
6459 blame->thread_args.cb_args = &blame->cb_args;
6460 blame->thread_args.complete = &s->blame_complete;
6461 blame->thread_args.cancel_cb = cancel_blame_view;
6462 blame->thread_args.cancel_arg = &s->done;
6463 s->blame_complete = 0;
6465 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6466 s->first_displayed_line = 1;
6467 s->last_displayed_line = view->nlines;
6468 s->selected_line = 1;
6470 s->matched_line = 0;
6472 done:
6473 if (commit)
6474 got_object_commit_close(commit);
6475 if (fd != -1 && close(fd) == -1 && err == NULL)
6476 err = got_error_from_errno("close");
6477 if (blob)
6478 got_object_blob_close(blob);
6479 free(obj_id);
6480 if (err)
6481 stop_blame(blame);
6482 return err;
6485 static const struct got_error *
6486 open_blame_view(struct tog_view *view, char *path,
6487 struct got_object_id *commit_id, struct got_repository *repo)
6489 const struct got_error *err = NULL;
6490 struct tog_blame_view_state *s = &view->state.blame;
6492 STAILQ_INIT(&s->blamed_commits);
6494 s->path = strdup(path);
6495 if (s->path == NULL)
6496 return got_error_from_errno("strdup");
6498 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6499 if (err) {
6500 free(s->path);
6501 return err;
6504 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6505 s->first_displayed_line = 1;
6506 s->last_displayed_line = view->nlines;
6507 s->selected_line = 1;
6508 s->blame_complete = 0;
6509 s->repo = repo;
6510 s->commit_id = commit_id;
6511 memset(&s->blame, 0, sizeof(s->blame));
6513 STAILQ_INIT(&s->colors);
6514 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6515 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6516 get_color_value("TOG_COLOR_COMMIT"));
6517 if (err)
6518 return err;
6521 view->show = show_blame_view;
6522 view->input = input_blame_view;
6523 view->reset = reset_blame_view;
6524 view->close = close_blame_view;
6525 view->search_start = search_start_blame_view;
6526 view->search_setup = search_setup_blame_view;
6527 view->search_next = search_next_view_match;
6529 if (using_mock_io) {
6530 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6531 int rc;
6533 rc = pthread_cond_init(&bta->blame_complete, NULL);
6534 if (rc)
6535 return got_error_set_errno(rc, "pthread_cond_init");
6538 return run_blame(view);
6541 static const struct got_error *
6542 close_blame_view(struct tog_view *view)
6544 const struct got_error *err = NULL;
6545 struct tog_blame_view_state *s = &view->state.blame;
6547 if (s->blame.thread)
6548 err = stop_blame(&s->blame);
6550 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6551 struct got_object_qid *blamed_commit;
6552 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6553 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6554 got_object_qid_free(blamed_commit);
6557 if (using_mock_io) {
6558 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6559 int rc;
6561 rc = pthread_cond_destroy(&bta->blame_complete);
6562 if (rc && err == NULL)
6563 err = got_error_set_errno(rc, "pthread_cond_destroy");
6566 free(s->path);
6567 free_colors(&s->colors);
6568 return err;
6571 static const struct got_error *
6572 search_start_blame_view(struct tog_view *view)
6574 struct tog_blame_view_state *s = &view->state.blame;
6576 s->matched_line = 0;
6577 return NULL;
6580 static void
6581 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6582 size_t *nlines, int **first, int **last, int **match, int **selected)
6584 struct tog_blame_view_state *s = &view->state.blame;
6586 *f = s->blame.f;
6587 *nlines = s->blame.nlines;
6588 *line_offsets = s->blame.line_offsets;
6589 *match = &s->matched_line;
6590 *first = &s->first_displayed_line;
6591 *last = &s->last_displayed_line;
6592 *selected = &s->selected_line;
6595 static const struct got_error *
6596 show_blame_view(struct tog_view *view)
6598 const struct got_error *err = NULL;
6599 struct tog_blame_view_state *s = &view->state.blame;
6600 int errcode;
6602 if (s->blame.thread == NULL && !s->blame_complete) {
6603 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6604 &s->blame.thread_args);
6605 if (errcode)
6606 return got_error_set_errno(errcode, "pthread_create");
6608 if (!using_mock_io)
6609 halfdelay(1); /* fast refresh while annotating */
6612 if (s->blame_complete && !using_mock_io)
6613 halfdelay(10); /* disable fast refresh */
6615 err = draw_blame(view);
6617 view_border(view);
6618 return err;
6621 static const struct got_error *
6622 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6623 struct got_repository *repo, struct got_object_id *id)
6625 struct tog_view *log_view;
6626 const struct got_error *err = NULL;
6628 *new_view = NULL;
6630 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6631 if (log_view == NULL)
6632 return got_error_from_errno("view_open");
6634 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6635 if (err)
6636 view_close(log_view);
6637 else
6638 *new_view = log_view;
6640 return err;
6643 static const struct got_error *
6644 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6646 const struct got_error *err = NULL, *thread_err = NULL;
6647 struct tog_view *diff_view;
6648 struct tog_blame_view_state *s = &view->state.blame;
6649 int eos, nscroll, begin_y = 0, begin_x = 0;
6651 eos = nscroll = view->nlines - 2;
6652 if (view_is_hsplit_top(view))
6653 --eos; /* border */
6655 switch (ch) {
6656 case '0':
6657 case '$':
6658 case KEY_RIGHT:
6659 case 'l':
6660 case KEY_LEFT:
6661 case 'h':
6662 horizontal_scroll_input(view, ch);
6663 break;
6664 case 'q':
6665 s->done = 1;
6666 break;
6667 case 'g':
6668 case KEY_HOME:
6669 s->selected_line = 1;
6670 s->first_displayed_line = 1;
6671 view->count = 0;
6672 break;
6673 case 'G':
6674 case KEY_END:
6675 if (s->blame.nlines < eos) {
6676 s->selected_line = s->blame.nlines;
6677 s->first_displayed_line = 1;
6678 } else {
6679 s->selected_line = eos;
6680 s->first_displayed_line = s->blame.nlines - (eos - 1);
6682 view->count = 0;
6683 break;
6684 case 'k':
6685 case KEY_UP:
6686 case CTRL('p'):
6687 if (s->selected_line > 1)
6688 s->selected_line--;
6689 else if (s->selected_line == 1 &&
6690 s->first_displayed_line > 1)
6691 s->first_displayed_line--;
6692 else
6693 view->count = 0;
6694 break;
6695 case CTRL('u'):
6696 case 'u':
6697 nscroll /= 2;
6698 /* FALL THROUGH */
6699 case KEY_PPAGE:
6700 case CTRL('b'):
6701 case 'b':
6702 if (s->first_displayed_line == 1) {
6703 if (view->count > 1)
6704 nscroll += nscroll;
6705 s->selected_line = MAX(1, s->selected_line - nscroll);
6706 view->count = 0;
6707 break;
6709 if (s->first_displayed_line > nscroll)
6710 s->first_displayed_line -= nscroll;
6711 else
6712 s->first_displayed_line = 1;
6713 break;
6714 case 'j':
6715 case KEY_DOWN:
6716 case CTRL('n'):
6717 if (s->selected_line < eos && s->first_displayed_line +
6718 s->selected_line <= s->blame.nlines)
6719 s->selected_line++;
6720 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6721 s->first_displayed_line++;
6722 else
6723 view->count = 0;
6724 break;
6725 case 'c':
6726 case 'p': {
6727 struct got_object_id *id = NULL;
6729 view->count = 0;
6730 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6731 s->first_displayed_line, s->selected_line);
6732 if (id == NULL)
6733 break;
6734 if (ch == 'p') {
6735 struct got_commit_object *commit, *pcommit;
6736 struct got_object_qid *pid;
6737 struct got_object_id *blob_id = NULL;
6738 int obj_type;
6739 err = got_object_open_as_commit(&commit,
6740 s->repo, id);
6741 if (err)
6742 break;
6743 pid = STAILQ_FIRST(
6744 got_object_commit_get_parent_ids(commit));
6745 if (pid == NULL) {
6746 got_object_commit_close(commit);
6747 break;
6749 /* Check if path history ends here. */
6750 err = got_object_open_as_commit(&pcommit,
6751 s->repo, &pid->id);
6752 if (err)
6753 break;
6754 err = got_object_id_by_path(&blob_id, s->repo,
6755 pcommit, s->path);
6756 got_object_commit_close(pcommit);
6757 if (err) {
6758 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6759 err = NULL;
6760 got_object_commit_close(commit);
6761 break;
6763 err = got_object_get_type(&obj_type, s->repo,
6764 blob_id);
6765 free(blob_id);
6766 /* Can't blame non-blob type objects. */
6767 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6768 got_object_commit_close(commit);
6769 break;
6771 err = got_object_qid_alloc(&s->blamed_commit,
6772 &pid->id);
6773 got_object_commit_close(commit);
6774 } else {
6775 if (got_object_id_cmp(id,
6776 &s->blamed_commit->id) == 0)
6777 break;
6778 err = got_object_qid_alloc(&s->blamed_commit,
6779 id);
6781 if (err)
6782 break;
6783 s->done = 1;
6784 thread_err = stop_blame(&s->blame);
6785 s->done = 0;
6786 if (thread_err)
6787 break;
6788 STAILQ_INSERT_HEAD(&s->blamed_commits,
6789 s->blamed_commit, entry);
6790 err = run_blame(view);
6791 if (err)
6792 break;
6793 break;
6795 case 'C': {
6796 struct got_object_qid *first;
6798 view->count = 0;
6799 first = STAILQ_FIRST(&s->blamed_commits);
6800 if (!got_object_id_cmp(&first->id, s->commit_id))
6801 break;
6802 s->done = 1;
6803 thread_err = stop_blame(&s->blame);
6804 s->done = 0;
6805 if (thread_err)
6806 break;
6807 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6808 got_object_qid_free(s->blamed_commit);
6809 s->blamed_commit =
6810 STAILQ_FIRST(&s->blamed_commits);
6811 err = run_blame(view);
6812 if (err)
6813 break;
6814 break;
6816 case 'L':
6817 view->count = 0;
6818 s->id_to_log = get_selected_commit_id(s->blame.lines,
6819 s->blame.nlines, s->first_displayed_line, s->selected_line);
6820 if (s->id_to_log)
6821 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6822 break;
6823 case KEY_ENTER:
6824 case '\r': {
6825 struct got_object_id *id = NULL;
6826 struct got_object_qid *pid;
6827 struct got_commit_object *commit = NULL;
6829 view->count = 0;
6830 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6831 s->first_displayed_line, s->selected_line);
6832 if (id == NULL)
6833 break;
6834 err = got_object_open_as_commit(&commit, s->repo, id);
6835 if (err)
6836 break;
6837 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6838 if (*new_view) {
6839 /* traversed from diff view, release diff resources */
6840 err = close_diff_view(*new_view);
6841 if (err)
6842 break;
6843 diff_view = *new_view;
6844 } else {
6845 if (view_is_parent_view(view))
6846 view_get_split(view, &begin_y, &begin_x);
6848 diff_view = view_open(0, 0, begin_y, begin_x,
6849 TOG_VIEW_DIFF);
6850 if (diff_view == NULL) {
6851 got_object_commit_close(commit);
6852 err = got_error_from_errno("view_open");
6853 break;
6856 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6857 id, NULL, NULL, 3, 0, 0, view, s->repo);
6858 got_object_commit_close(commit);
6859 if (err) {
6860 view_close(diff_view);
6861 break;
6863 s->last_diffed_line = s->first_displayed_line - 1 +
6864 s->selected_line;
6865 if (*new_view)
6866 break; /* still open from active diff view */
6867 if (view_is_parent_view(view) &&
6868 view->mode == TOG_VIEW_SPLIT_HRZN) {
6869 err = view_init_hsplit(view, begin_y);
6870 if (err)
6871 break;
6874 view->focussed = 0;
6875 diff_view->focussed = 1;
6876 diff_view->mode = view->mode;
6877 diff_view->nlines = view->lines - begin_y;
6878 if (view_is_parent_view(view)) {
6879 view_transfer_size(diff_view, view);
6880 err = view_close_child(view);
6881 if (err)
6882 break;
6883 err = view_set_child(view, diff_view);
6884 if (err)
6885 break;
6886 view->focus_child = 1;
6887 } else
6888 *new_view = diff_view;
6889 if (err)
6890 break;
6891 break;
6893 case CTRL('d'):
6894 case 'd':
6895 nscroll /= 2;
6896 /* FALL THROUGH */
6897 case KEY_NPAGE:
6898 case CTRL('f'):
6899 case 'f':
6900 case ' ':
6901 if (s->last_displayed_line >= s->blame.nlines &&
6902 s->selected_line >= MIN(s->blame.nlines,
6903 view->nlines - 2)) {
6904 view->count = 0;
6905 break;
6907 if (s->last_displayed_line >= s->blame.nlines &&
6908 s->selected_line < view->nlines - 2) {
6909 s->selected_line +=
6910 MIN(nscroll, s->last_displayed_line -
6911 s->first_displayed_line - s->selected_line + 1);
6913 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6914 s->first_displayed_line += nscroll;
6915 else
6916 s->first_displayed_line =
6917 s->blame.nlines - (view->nlines - 3);
6918 break;
6919 case KEY_RESIZE:
6920 if (s->selected_line > view->nlines - 2) {
6921 s->selected_line = MIN(s->blame.nlines,
6922 view->nlines - 2);
6924 break;
6925 default:
6926 view->count = 0;
6927 break;
6929 return thread_err ? thread_err : err;
6932 static const struct got_error *
6933 reset_blame_view(struct tog_view *view)
6935 const struct got_error *err;
6936 struct tog_blame_view_state *s = &view->state.blame;
6938 view->count = 0;
6939 s->done = 1;
6940 err = stop_blame(&s->blame);
6941 s->done = 0;
6942 if (err)
6943 return err;
6944 return run_blame(view);
6947 static const struct got_error *
6948 cmd_blame(int argc, char *argv[])
6950 const struct got_error *error;
6951 struct got_repository *repo = NULL;
6952 struct got_worktree *worktree = NULL;
6953 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6954 char *link_target = NULL;
6955 struct got_object_id *commit_id = NULL;
6956 struct got_commit_object *commit = NULL;
6957 char *commit_id_str = NULL;
6958 int ch;
6959 struct tog_view *view = NULL;
6960 int *pack_fds = NULL;
6962 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6963 switch (ch) {
6964 case 'c':
6965 commit_id_str = optarg;
6966 break;
6967 case 'r':
6968 repo_path = realpath(optarg, NULL);
6969 if (repo_path == NULL)
6970 return got_error_from_errno2("realpath",
6971 optarg);
6972 break;
6973 default:
6974 usage_blame();
6975 /* NOTREACHED */
6979 argc -= optind;
6980 argv += optind;
6982 if (argc != 1)
6983 usage_blame();
6985 error = got_repo_pack_fds_open(&pack_fds);
6986 if (error != NULL)
6987 goto done;
6989 if (repo_path == NULL) {
6990 cwd = getcwd(NULL, 0);
6991 if (cwd == NULL)
6992 return got_error_from_errno("getcwd");
6993 error = got_worktree_open(&worktree, cwd);
6994 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6995 goto done;
6996 if (worktree)
6997 repo_path =
6998 strdup(got_worktree_get_repo_path(worktree));
6999 else
7000 repo_path = strdup(cwd);
7001 if (repo_path == NULL) {
7002 error = got_error_from_errno("strdup");
7003 goto done;
7007 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7008 if (error != NULL)
7009 goto done;
7011 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7012 worktree);
7013 if (error)
7014 goto done;
7016 init_curses();
7018 error = apply_unveil(got_repo_get_path(repo), NULL);
7019 if (error)
7020 goto done;
7022 error = tog_load_refs(repo, 0);
7023 if (error)
7024 goto done;
7026 if (commit_id_str == NULL) {
7027 struct got_reference *head_ref;
7028 error = got_ref_open(&head_ref, repo, worktree ?
7029 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7030 if (error != NULL)
7031 goto done;
7032 error = got_ref_resolve(&commit_id, repo, head_ref);
7033 got_ref_close(head_ref);
7034 } else {
7035 error = got_repo_match_object_id(&commit_id, NULL,
7036 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7038 if (error != NULL)
7039 goto done;
7041 error = got_object_open_as_commit(&commit, repo, commit_id);
7042 if (error)
7043 goto done;
7045 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7046 commit, repo);
7047 if (error)
7048 goto done;
7050 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7051 if (view == NULL) {
7052 error = got_error_from_errno("view_open");
7053 goto done;
7055 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7056 commit_id, repo);
7057 if (error != NULL) {
7058 if (view->close == NULL)
7059 close_blame_view(view);
7060 view_close(view);
7061 goto done;
7063 if (worktree) {
7064 /* Release work tree lock. */
7065 got_worktree_close(worktree);
7066 worktree = NULL;
7068 error = view_loop(view);
7069 done:
7070 free(repo_path);
7071 free(in_repo_path);
7072 free(link_target);
7073 free(cwd);
7074 free(commit_id);
7075 if (commit)
7076 got_object_commit_close(commit);
7077 if (worktree)
7078 got_worktree_close(worktree);
7079 if (repo) {
7080 const struct got_error *close_err = got_repo_close(repo);
7081 if (error == NULL)
7082 error = close_err;
7084 if (pack_fds) {
7085 const struct got_error *pack_err =
7086 got_repo_pack_fds_close(pack_fds);
7087 if (error == NULL)
7088 error = pack_err;
7090 tog_free_refs();
7091 return error;
7094 static const struct got_error *
7095 draw_tree_entries(struct tog_view *view, const char *parent_path)
7097 struct tog_tree_view_state *s = &view->state.tree;
7098 const struct got_error *err = NULL;
7099 struct got_tree_entry *te;
7100 wchar_t *wline;
7101 char *index = NULL;
7102 struct tog_color *tc;
7103 int width, n, nentries, scrollx, i = 1;
7104 int limit = view->nlines;
7106 s->ndisplayed = 0;
7107 if (view_is_hsplit_top(view))
7108 --limit; /* border */
7110 werase(view->window);
7112 if (limit == 0)
7113 return NULL;
7115 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7116 0, 0);
7117 if (err)
7118 return err;
7119 if (view_needs_focus_indication(view))
7120 wstandout(view->window);
7121 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7122 if (tc)
7123 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7124 waddwstr(view->window, wline);
7125 free(wline);
7126 wline = NULL;
7127 while (width++ < view->ncols)
7128 waddch(view->window, ' ');
7129 if (tc)
7130 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7131 if (view_needs_focus_indication(view))
7132 wstandend(view->window);
7133 if (--limit <= 0)
7134 return NULL;
7136 i += s->selected;
7137 if (s->first_displayed_entry) {
7138 i += got_tree_entry_get_index(s->first_displayed_entry);
7139 if (s->tree != s->root)
7140 ++i; /* account for ".." entry */
7142 nentries = got_object_tree_get_nentries(s->tree);
7143 if (asprintf(&index, "[%d/%d] %s",
7144 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7145 return got_error_from_errno("asprintf");
7146 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7147 free(index);
7148 if (err)
7149 return err;
7150 waddwstr(view->window, wline);
7151 free(wline);
7152 wline = NULL;
7153 if (width < view->ncols - 1)
7154 waddch(view->window, '\n');
7155 if (--limit <= 0)
7156 return NULL;
7157 waddch(view->window, '\n');
7158 if (--limit <= 0)
7159 return NULL;
7161 if (s->first_displayed_entry == NULL) {
7162 te = got_object_tree_get_first_entry(s->tree);
7163 if (s->selected == 0) {
7164 if (view->focussed)
7165 wstandout(view->window);
7166 s->selected_entry = NULL;
7168 waddstr(view->window, " ..\n"); /* parent directory */
7169 if (s->selected == 0 && view->focussed)
7170 wstandend(view->window);
7171 s->ndisplayed++;
7172 if (--limit <= 0)
7173 return NULL;
7174 n = 1;
7175 } else {
7176 n = 0;
7177 te = s->first_displayed_entry;
7180 view->maxx = 0;
7181 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7182 char *line = NULL, *id_str = NULL, *link_target = NULL;
7183 const char *modestr = "";
7184 mode_t mode;
7186 te = got_object_tree_get_entry(s->tree, i);
7187 mode = got_tree_entry_get_mode(te);
7189 if (s->show_ids) {
7190 err = got_object_id_str(&id_str,
7191 got_tree_entry_get_id(te));
7192 if (err)
7193 return got_error_from_errno(
7194 "got_object_id_str");
7196 if (got_object_tree_entry_is_submodule(te))
7197 modestr = "$";
7198 else if (S_ISLNK(mode)) {
7199 int i;
7201 err = got_tree_entry_get_symlink_target(&link_target,
7202 te, s->repo);
7203 if (err) {
7204 free(id_str);
7205 return err;
7207 for (i = 0; i < strlen(link_target); i++) {
7208 if (!isprint((unsigned char)link_target[i]))
7209 link_target[i] = '?';
7211 modestr = "@";
7213 else if (S_ISDIR(mode))
7214 modestr = "/";
7215 else if (mode & S_IXUSR)
7216 modestr = "*";
7217 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7218 got_tree_entry_get_name(te), modestr,
7219 link_target ? " -> ": "",
7220 link_target ? link_target : "") == -1) {
7221 free(id_str);
7222 free(link_target);
7223 return got_error_from_errno("asprintf");
7225 free(id_str);
7226 free(link_target);
7228 /* use full line width to determine view->maxx */
7229 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7230 if (err) {
7231 free(line);
7232 break;
7234 view->maxx = MAX(view->maxx, width);
7235 free(wline);
7236 wline = NULL;
7238 err = format_line(&wline, &width, &scrollx, line, view->x,
7239 view->ncols, 0, 0);
7240 if (err) {
7241 free(line);
7242 break;
7244 if (n == s->selected) {
7245 if (view->focussed)
7246 wstandout(view->window);
7247 s->selected_entry = te;
7249 tc = match_color(&s->colors, line);
7250 if (tc)
7251 wattr_on(view->window,
7252 COLOR_PAIR(tc->colorpair), NULL);
7253 waddwstr(view->window, &wline[scrollx]);
7254 if (tc)
7255 wattr_off(view->window,
7256 COLOR_PAIR(tc->colorpair), NULL);
7257 if (width < view->ncols)
7258 waddch(view->window, '\n');
7259 if (n == s->selected && view->focussed)
7260 wstandend(view->window);
7261 free(line);
7262 free(wline);
7263 wline = NULL;
7264 n++;
7265 s->ndisplayed++;
7266 s->last_displayed_entry = te;
7267 if (--limit <= 0)
7268 break;
7271 return err;
7274 static void
7275 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7277 struct got_tree_entry *te;
7278 int isroot = s->tree == s->root;
7279 int i = 0;
7281 if (s->first_displayed_entry == NULL)
7282 return;
7284 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7285 while (i++ < maxscroll) {
7286 if (te == NULL) {
7287 if (!isroot)
7288 s->first_displayed_entry = NULL;
7289 break;
7291 s->first_displayed_entry = te;
7292 te = got_tree_entry_get_prev(s->tree, te);
7296 static const struct got_error *
7297 tree_scroll_down(struct tog_view *view, int maxscroll)
7299 struct tog_tree_view_state *s = &view->state.tree;
7300 struct got_tree_entry *next, *last;
7301 int n = 0;
7303 if (s->first_displayed_entry)
7304 next = got_tree_entry_get_next(s->tree,
7305 s->first_displayed_entry);
7306 else
7307 next = got_object_tree_get_first_entry(s->tree);
7309 last = s->last_displayed_entry;
7310 while (next && n++ < maxscroll) {
7311 if (last) {
7312 s->last_displayed_entry = last;
7313 last = got_tree_entry_get_next(s->tree, last);
7315 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7316 s->first_displayed_entry = next;
7317 next = got_tree_entry_get_next(s->tree, next);
7321 return NULL;
7324 static const struct got_error *
7325 tree_entry_path(char **path, struct tog_parent_trees *parents,
7326 struct got_tree_entry *te)
7328 const struct got_error *err = NULL;
7329 struct tog_parent_tree *pt;
7330 size_t len = 2; /* for leading slash and NUL */
7332 TAILQ_FOREACH(pt, parents, entry)
7333 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7334 + 1 /* slash */;
7335 if (te)
7336 len += strlen(got_tree_entry_get_name(te));
7338 *path = calloc(1, len);
7339 if (path == NULL)
7340 return got_error_from_errno("calloc");
7342 (*path)[0] = '/';
7343 pt = TAILQ_LAST(parents, tog_parent_trees);
7344 while (pt) {
7345 const char *name = got_tree_entry_get_name(pt->selected_entry);
7346 if (strlcat(*path, name, len) >= len) {
7347 err = got_error(GOT_ERR_NO_SPACE);
7348 goto done;
7350 if (strlcat(*path, "/", len) >= len) {
7351 err = got_error(GOT_ERR_NO_SPACE);
7352 goto done;
7354 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7356 if (te) {
7357 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7358 err = got_error(GOT_ERR_NO_SPACE);
7359 goto done;
7362 done:
7363 if (err) {
7364 free(*path);
7365 *path = NULL;
7367 return err;
7370 static const struct got_error *
7371 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7372 struct got_tree_entry *te, struct tog_parent_trees *parents,
7373 struct got_object_id *commit_id, struct got_repository *repo)
7375 const struct got_error *err = NULL;
7376 char *path;
7377 struct tog_view *blame_view;
7379 *new_view = NULL;
7381 err = tree_entry_path(&path, parents, te);
7382 if (err)
7383 return err;
7385 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7386 if (blame_view == NULL) {
7387 err = got_error_from_errno("view_open");
7388 goto done;
7391 err = open_blame_view(blame_view, path, commit_id, repo);
7392 if (err) {
7393 if (err->code == GOT_ERR_CANCELLED)
7394 err = NULL;
7395 view_close(blame_view);
7396 } else
7397 *new_view = blame_view;
7398 done:
7399 free(path);
7400 return err;
7403 static const struct got_error *
7404 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7405 struct tog_tree_view_state *s)
7407 struct tog_view *log_view;
7408 const struct got_error *err = NULL;
7409 char *path;
7411 *new_view = NULL;
7413 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7414 if (log_view == NULL)
7415 return got_error_from_errno("view_open");
7417 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7418 if (err)
7419 return err;
7421 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7422 path, 0);
7423 if (err)
7424 view_close(log_view);
7425 else
7426 *new_view = log_view;
7427 free(path);
7428 return err;
7431 static const struct got_error *
7432 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7433 const char *head_ref_name, struct got_repository *repo)
7435 const struct got_error *err = NULL;
7436 char *commit_id_str = NULL;
7437 struct tog_tree_view_state *s = &view->state.tree;
7438 struct got_commit_object *commit = NULL;
7440 TAILQ_INIT(&s->parents);
7441 STAILQ_INIT(&s->colors);
7443 s->commit_id = got_object_id_dup(commit_id);
7444 if (s->commit_id == NULL) {
7445 err = got_error_from_errno("got_object_id_dup");
7446 goto done;
7449 err = got_object_open_as_commit(&commit, repo, commit_id);
7450 if (err)
7451 goto done;
7454 * The root is opened here and will be closed when the view is closed.
7455 * Any visited subtrees and their path-wise parents are opened and
7456 * closed on demand.
7458 err = got_object_open_as_tree(&s->root, repo,
7459 got_object_commit_get_tree_id(commit));
7460 if (err)
7461 goto done;
7462 s->tree = s->root;
7464 err = got_object_id_str(&commit_id_str, commit_id);
7465 if (err != NULL)
7466 goto done;
7468 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7469 err = got_error_from_errno("asprintf");
7470 goto done;
7473 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7474 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7475 if (head_ref_name) {
7476 s->head_ref_name = strdup(head_ref_name);
7477 if (s->head_ref_name == NULL) {
7478 err = got_error_from_errno("strdup");
7479 goto done;
7482 s->repo = repo;
7484 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7485 err = add_color(&s->colors, "\\$$",
7486 TOG_COLOR_TREE_SUBMODULE,
7487 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7488 if (err)
7489 goto done;
7490 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7491 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7492 if (err)
7493 goto done;
7494 err = add_color(&s->colors, "/$",
7495 TOG_COLOR_TREE_DIRECTORY,
7496 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7497 if (err)
7498 goto done;
7500 err = add_color(&s->colors, "\\*$",
7501 TOG_COLOR_TREE_EXECUTABLE,
7502 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7503 if (err)
7504 goto done;
7506 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7507 get_color_value("TOG_COLOR_COMMIT"));
7508 if (err)
7509 goto done;
7512 view->show = show_tree_view;
7513 view->input = input_tree_view;
7514 view->close = close_tree_view;
7515 view->search_start = search_start_tree_view;
7516 view->search_next = search_next_tree_view;
7517 done:
7518 free(commit_id_str);
7519 if (commit)
7520 got_object_commit_close(commit);
7521 if (err) {
7522 if (view->close == NULL)
7523 close_tree_view(view);
7524 view_close(view);
7526 return err;
7529 static const struct got_error *
7530 close_tree_view(struct tog_view *view)
7532 struct tog_tree_view_state *s = &view->state.tree;
7534 free_colors(&s->colors);
7535 free(s->tree_label);
7536 s->tree_label = NULL;
7537 free(s->commit_id);
7538 s->commit_id = NULL;
7539 free(s->head_ref_name);
7540 s->head_ref_name = NULL;
7541 while (!TAILQ_EMPTY(&s->parents)) {
7542 struct tog_parent_tree *parent;
7543 parent = TAILQ_FIRST(&s->parents);
7544 TAILQ_REMOVE(&s->parents, parent, entry);
7545 if (parent->tree != s->root)
7546 got_object_tree_close(parent->tree);
7547 free(parent);
7550 if (s->tree != NULL && s->tree != s->root)
7551 got_object_tree_close(s->tree);
7552 if (s->root)
7553 got_object_tree_close(s->root);
7554 return NULL;
7557 static const struct got_error *
7558 search_start_tree_view(struct tog_view *view)
7560 struct tog_tree_view_state *s = &view->state.tree;
7562 s->matched_entry = NULL;
7563 return NULL;
7566 static int
7567 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7569 regmatch_t regmatch;
7571 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7572 0) == 0;
7575 static const struct got_error *
7576 search_next_tree_view(struct tog_view *view)
7578 struct tog_tree_view_state *s = &view->state.tree;
7579 struct got_tree_entry *te = NULL;
7581 if (!view->searching) {
7582 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7583 return NULL;
7586 if (s->matched_entry) {
7587 if (view->searching == TOG_SEARCH_FORWARD) {
7588 if (s->selected_entry)
7589 te = got_tree_entry_get_next(s->tree,
7590 s->selected_entry);
7591 else
7592 te = got_object_tree_get_first_entry(s->tree);
7593 } else {
7594 if (s->selected_entry == NULL)
7595 te = got_object_tree_get_last_entry(s->tree);
7596 else
7597 te = got_tree_entry_get_prev(s->tree,
7598 s->selected_entry);
7600 } else {
7601 if (s->selected_entry)
7602 te = s->selected_entry;
7603 else if (view->searching == TOG_SEARCH_FORWARD)
7604 te = got_object_tree_get_first_entry(s->tree);
7605 else
7606 te = got_object_tree_get_last_entry(s->tree);
7609 while (1) {
7610 if (te == NULL) {
7611 if (s->matched_entry == NULL) {
7612 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7613 return NULL;
7615 if (view->searching == TOG_SEARCH_FORWARD)
7616 te = got_object_tree_get_first_entry(s->tree);
7617 else
7618 te = got_object_tree_get_last_entry(s->tree);
7621 if (match_tree_entry(te, &view->regex)) {
7622 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7623 s->matched_entry = te;
7624 break;
7627 if (view->searching == TOG_SEARCH_FORWARD)
7628 te = got_tree_entry_get_next(s->tree, te);
7629 else
7630 te = got_tree_entry_get_prev(s->tree, te);
7633 if (s->matched_entry) {
7634 s->first_displayed_entry = s->matched_entry;
7635 s->selected = 0;
7638 return NULL;
7641 static const struct got_error *
7642 show_tree_view(struct tog_view *view)
7644 const struct got_error *err = NULL;
7645 struct tog_tree_view_state *s = &view->state.tree;
7646 char *parent_path;
7648 err = tree_entry_path(&parent_path, &s->parents, NULL);
7649 if (err)
7650 return err;
7652 err = draw_tree_entries(view, parent_path);
7653 free(parent_path);
7655 view_border(view);
7656 return err;
7659 static const struct got_error *
7660 tree_goto_line(struct tog_view *view, int nlines)
7662 const struct got_error *err = NULL;
7663 struct tog_tree_view_state *s = &view->state.tree;
7664 struct got_tree_entry **fte, **lte, **ste;
7665 int g, last, first = 1, i = 1;
7666 int root = s->tree == s->root;
7667 int off = root ? 1 : 2;
7669 g = view->gline;
7670 view->gline = 0;
7672 if (g == 0)
7673 g = 1;
7674 else if (g > got_object_tree_get_nentries(s->tree))
7675 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7677 fte = &s->first_displayed_entry;
7678 lte = &s->last_displayed_entry;
7679 ste = &s->selected_entry;
7681 if (*fte != NULL) {
7682 first = got_tree_entry_get_index(*fte);
7683 first += off; /* account for ".." */
7685 last = got_tree_entry_get_index(*lte);
7686 last += off;
7688 if (g >= first && g <= last && g - first < nlines) {
7689 s->selected = g - first;
7690 return NULL; /* gline is on the current page */
7693 if (*ste != NULL) {
7694 i = got_tree_entry_get_index(*ste);
7695 i += off;
7698 if (i < g) {
7699 err = tree_scroll_down(view, g - i);
7700 if (err)
7701 return err;
7702 if (got_tree_entry_get_index(*lte) >=
7703 got_object_tree_get_nentries(s->tree) - 1 &&
7704 first + s->selected < g &&
7705 s->selected < s->ndisplayed - 1) {
7706 first = got_tree_entry_get_index(*fte);
7707 first += off;
7708 s->selected = g - first;
7710 } else if (i > g)
7711 tree_scroll_up(s, i - g);
7713 if (g < nlines &&
7714 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7715 s->selected = g - 1;
7717 return NULL;
7720 static const struct got_error *
7721 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7723 const struct got_error *err = NULL;
7724 struct tog_tree_view_state *s = &view->state.tree;
7725 struct got_tree_entry *te;
7726 int n, nscroll = view->nlines - 3;
7728 if (view->gline)
7729 return tree_goto_line(view, nscroll);
7731 switch (ch) {
7732 case '0':
7733 case '$':
7734 case KEY_RIGHT:
7735 case 'l':
7736 case KEY_LEFT:
7737 case 'h':
7738 horizontal_scroll_input(view, ch);
7739 break;
7740 case 'i':
7741 s->show_ids = !s->show_ids;
7742 view->count = 0;
7743 break;
7744 case 'L':
7745 view->count = 0;
7746 if (!s->selected_entry)
7747 break;
7748 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7749 break;
7750 case 'R':
7751 view->count = 0;
7752 err = view_request_new(new_view, view, TOG_VIEW_REF);
7753 break;
7754 case 'g':
7755 case '=':
7756 case KEY_HOME:
7757 s->selected = 0;
7758 view->count = 0;
7759 if (s->tree == s->root)
7760 s->first_displayed_entry =
7761 got_object_tree_get_first_entry(s->tree);
7762 else
7763 s->first_displayed_entry = NULL;
7764 break;
7765 case 'G':
7766 case '*':
7767 case KEY_END: {
7768 int eos = view->nlines - 3;
7770 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7771 --eos; /* border */
7772 s->selected = 0;
7773 view->count = 0;
7774 te = got_object_tree_get_last_entry(s->tree);
7775 for (n = 0; n < eos; n++) {
7776 if (te == NULL) {
7777 if (s->tree != s->root) {
7778 s->first_displayed_entry = NULL;
7779 n++;
7781 break;
7783 s->first_displayed_entry = te;
7784 te = got_tree_entry_get_prev(s->tree, te);
7786 if (n > 0)
7787 s->selected = n - 1;
7788 break;
7790 case 'k':
7791 case KEY_UP:
7792 case CTRL('p'):
7793 if (s->selected > 0) {
7794 s->selected--;
7795 break;
7797 tree_scroll_up(s, 1);
7798 if (s->selected_entry == NULL ||
7799 (s->tree == s->root && s->selected_entry ==
7800 got_object_tree_get_first_entry(s->tree)))
7801 view->count = 0;
7802 break;
7803 case CTRL('u'):
7804 case 'u':
7805 nscroll /= 2;
7806 /* FALL THROUGH */
7807 case KEY_PPAGE:
7808 case CTRL('b'):
7809 case 'b':
7810 if (s->tree == s->root) {
7811 if (got_object_tree_get_first_entry(s->tree) ==
7812 s->first_displayed_entry)
7813 s->selected -= MIN(s->selected, nscroll);
7814 } else {
7815 if (s->first_displayed_entry == NULL)
7816 s->selected -= MIN(s->selected, nscroll);
7818 tree_scroll_up(s, MAX(0, nscroll));
7819 if (s->selected_entry == NULL ||
7820 (s->tree == s->root && s->selected_entry ==
7821 got_object_tree_get_first_entry(s->tree)))
7822 view->count = 0;
7823 break;
7824 case 'j':
7825 case KEY_DOWN:
7826 case CTRL('n'):
7827 if (s->selected < s->ndisplayed - 1) {
7828 s->selected++;
7829 break;
7831 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7832 == NULL) {
7833 /* can't scroll any further */
7834 view->count = 0;
7835 break;
7837 tree_scroll_down(view, 1);
7838 break;
7839 case CTRL('d'):
7840 case 'd':
7841 nscroll /= 2;
7842 /* FALL THROUGH */
7843 case KEY_NPAGE:
7844 case CTRL('f'):
7845 case 'f':
7846 case ' ':
7847 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7848 == NULL) {
7849 /* can't scroll any further; move cursor down */
7850 if (s->selected < s->ndisplayed - 1)
7851 s->selected += MIN(nscroll,
7852 s->ndisplayed - s->selected - 1);
7853 else
7854 view->count = 0;
7855 break;
7857 tree_scroll_down(view, nscroll);
7858 break;
7859 case KEY_ENTER:
7860 case '\r':
7861 case KEY_BACKSPACE:
7862 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7863 struct tog_parent_tree *parent;
7864 /* user selected '..' */
7865 if (s->tree == s->root) {
7866 view->count = 0;
7867 break;
7869 parent = TAILQ_FIRST(&s->parents);
7870 TAILQ_REMOVE(&s->parents, parent,
7871 entry);
7872 got_object_tree_close(s->tree);
7873 s->tree = parent->tree;
7874 s->first_displayed_entry =
7875 parent->first_displayed_entry;
7876 s->selected_entry =
7877 parent->selected_entry;
7878 s->selected = parent->selected;
7879 if (s->selected > view->nlines - 3) {
7880 err = offset_selection_down(view);
7881 if (err)
7882 break;
7884 free(parent);
7885 } else if (S_ISDIR(got_tree_entry_get_mode(
7886 s->selected_entry))) {
7887 struct got_tree_object *subtree;
7888 view->count = 0;
7889 err = got_object_open_as_tree(&subtree, s->repo,
7890 got_tree_entry_get_id(s->selected_entry));
7891 if (err)
7892 break;
7893 err = tree_view_visit_subtree(s, subtree);
7894 if (err) {
7895 got_object_tree_close(subtree);
7896 break;
7898 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7899 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7900 break;
7901 case KEY_RESIZE:
7902 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7903 s->selected = view->nlines - 4;
7904 view->count = 0;
7905 break;
7906 default:
7907 view->count = 0;
7908 break;
7911 return err;
7914 __dead static void
7915 usage_tree(void)
7917 endwin();
7918 fprintf(stderr,
7919 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7920 getprogname());
7921 exit(1);
7924 static const struct got_error *
7925 cmd_tree(int argc, char *argv[])
7927 const struct got_error *error;
7928 struct got_repository *repo = NULL;
7929 struct got_worktree *worktree = NULL;
7930 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7931 struct got_object_id *commit_id = NULL;
7932 struct got_commit_object *commit = NULL;
7933 const char *commit_id_arg = NULL;
7934 char *label = NULL;
7935 struct got_reference *ref = NULL;
7936 const char *head_ref_name = NULL;
7937 int ch;
7938 struct tog_view *view;
7939 int *pack_fds = NULL;
7941 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7942 switch (ch) {
7943 case 'c':
7944 commit_id_arg = optarg;
7945 break;
7946 case 'r':
7947 repo_path = realpath(optarg, NULL);
7948 if (repo_path == NULL)
7949 return got_error_from_errno2("realpath",
7950 optarg);
7951 break;
7952 default:
7953 usage_tree();
7954 /* NOTREACHED */
7958 argc -= optind;
7959 argv += optind;
7961 if (argc > 1)
7962 usage_tree();
7964 error = got_repo_pack_fds_open(&pack_fds);
7965 if (error != NULL)
7966 goto done;
7968 if (repo_path == NULL) {
7969 cwd = getcwd(NULL, 0);
7970 if (cwd == NULL)
7971 return got_error_from_errno("getcwd");
7972 error = got_worktree_open(&worktree, cwd);
7973 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7974 goto done;
7975 if (worktree)
7976 repo_path =
7977 strdup(got_worktree_get_repo_path(worktree));
7978 else
7979 repo_path = strdup(cwd);
7980 if (repo_path == NULL) {
7981 error = got_error_from_errno("strdup");
7982 goto done;
7986 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7987 if (error != NULL)
7988 goto done;
7990 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7991 repo, worktree);
7992 if (error)
7993 goto done;
7995 init_curses();
7997 error = apply_unveil(got_repo_get_path(repo), NULL);
7998 if (error)
7999 goto done;
8001 error = tog_load_refs(repo, 0);
8002 if (error)
8003 goto done;
8005 if (commit_id_arg == NULL) {
8006 error = got_repo_match_object_id(&commit_id, &label,
8007 worktree ? got_worktree_get_head_ref_name(worktree) :
8008 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8009 if (error)
8010 goto done;
8011 head_ref_name = label;
8012 } else {
8013 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8014 if (error == NULL)
8015 head_ref_name = got_ref_get_name(ref);
8016 else if (error->code != GOT_ERR_NOT_REF)
8017 goto done;
8018 error = got_repo_match_object_id(&commit_id, NULL,
8019 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8020 if (error)
8021 goto done;
8024 error = got_object_open_as_commit(&commit, repo, commit_id);
8025 if (error)
8026 goto done;
8028 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8029 if (view == NULL) {
8030 error = got_error_from_errno("view_open");
8031 goto done;
8033 error = open_tree_view(view, commit_id, head_ref_name, repo);
8034 if (error)
8035 goto done;
8036 if (!got_path_is_root_dir(in_repo_path)) {
8037 error = tree_view_walk_path(&view->state.tree, commit,
8038 in_repo_path);
8039 if (error)
8040 goto done;
8043 if (worktree) {
8044 /* Release work tree lock. */
8045 got_worktree_close(worktree);
8046 worktree = NULL;
8048 error = view_loop(view);
8049 done:
8050 free(repo_path);
8051 free(cwd);
8052 free(commit_id);
8053 free(label);
8054 if (ref)
8055 got_ref_close(ref);
8056 if (repo) {
8057 const struct got_error *close_err = got_repo_close(repo);
8058 if (error == NULL)
8059 error = close_err;
8061 if (pack_fds) {
8062 const struct got_error *pack_err =
8063 got_repo_pack_fds_close(pack_fds);
8064 if (error == NULL)
8065 error = pack_err;
8067 tog_free_refs();
8068 return error;
8071 static const struct got_error *
8072 ref_view_load_refs(struct tog_ref_view_state *s)
8074 struct got_reflist_entry *sre;
8075 struct tog_reflist_entry *re;
8077 s->nrefs = 0;
8078 TAILQ_FOREACH(sre, &tog_refs, entry) {
8079 if (strncmp(got_ref_get_name(sre->ref),
8080 "refs/got/", 9) == 0 &&
8081 strncmp(got_ref_get_name(sre->ref),
8082 "refs/got/backup/", 16) != 0)
8083 continue;
8085 re = malloc(sizeof(*re));
8086 if (re == NULL)
8087 return got_error_from_errno("malloc");
8089 re->ref = got_ref_dup(sre->ref);
8090 if (re->ref == NULL)
8091 return got_error_from_errno("got_ref_dup");
8092 re->idx = s->nrefs++;
8093 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8096 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8097 return NULL;
8100 static void
8101 ref_view_free_refs(struct tog_ref_view_state *s)
8103 struct tog_reflist_entry *re;
8105 while (!TAILQ_EMPTY(&s->refs)) {
8106 re = TAILQ_FIRST(&s->refs);
8107 TAILQ_REMOVE(&s->refs, re, entry);
8108 got_ref_close(re->ref);
8109 free(re);
8113 static const struct got_error *
8114 open_ref_view(struct tog_view *view, struct got_repository *repo)
8116 const struct got_error *err = NULL;
8117 struct tog_ref_view_state *s = &view->state.ref;
8119 s->selected_entry = 0;
8120 s->repo = repo;
8122 TAILQ_INIT(&s->refs);
8123 STAILQ_INIT(&s->colors);
8125 err = ref_view_load_refs(s);
8126 if (err)
8127 goto done;
8129 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8130 err = add_color(&s->colors, "^refs/heads/",
8131 TOG_COLOR_REFS_HEADS,
8132 get_color_value("TOG_COLOR_REFS_HEADS"));
8133 if (err)
8134 goto done;
8136 err = add_color(&s->colors, "^refs/tags/",
8137 TOG_COLOR_REFS_TAGS,
8138 get_color_value("TOG_COLOR_REFS_TAGS"));
8139 if (err)
8140 goto done;
8142 err = add_color(&s->colors, "^refs/remotes/",
8143 TOG_COLOR_REFS_REMOTES,
8144 get_color_value("TOG_COLOR_REFS_REMOTES"));
8145 if (err)
8146 goto done;
8148 err = add_color(&s->colors, "^refs/got/backup/",
8149 TOG_COLOR_REFS_BACKUP,
8150 get_color_value("TOG_COLOR_REFS_BACKUP"));
8151 if (err)
8152 goto done;
8155 view->show = show_ref_view;
8156 view->input = input_ref_view;
8157 view->close = close_ref_view;
8158 view->search_start = search_start_ref_view;
8159 view->search_next = search_next_ref_view;
8160 done:
8161 if (err) {
8162 if (view->close == NULL)
8163 close_ref_view(view);
8164 view_close(view);
8166 return err;
8169 static const struct got_error *
8170 close_ref_view(struct tog_view *view)
8172 struct tog_ref_view_state *s = &view->state.ref;
8174 ref_view_free_refs(s);
8175 free_colors(&s->colors);
8177 return NULL;
8180 static const struct got_error *
8181 resolve_reflist_entry(struct got_object_id **commit_id,
8182 struct tog_reflist_entry *re, struct got_repository *repo)
8184 const struct got_error *err = NULL;
8185 struct got_object_id *obj_id;
8186 struct got_tag_object *tag = NULL;
8187 int obj_type;
8189 *commit_id = NULL;
8191 err = got_ref_resolve(&obj_id, repo, re->ref);
8192 if (err)
8193 return err;
8195 err = got_object_get_type(&obj_type, repo, obj_id);
8196 if (err)
8197 goto done;
8199 switch (obj_type) {
8200 case GOT_OBJ_TYPE_COMMIT:
8201 *commit_id = obj_id;
8202 break;
8203 case GOT_OBJ_TYPE_TAG:
8204 err = got_object_open_as_tag(&tag, repo, obj_id);
8205 if (err)
8206 goto done;
8207 free(obj_id);
8208 err = got_object_get_type(&obj_type, repo,
8209 got_object_tag_get_object_id(tag));
8210 if (err)
8211 goto done;
8212 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8213 err = got_error(GOT_ERR_OBJ_TYPE);
8214 goto done;
8216 *commit_id = got_object_id_dup(
8217 got_object_tag_get_object_id(tag));
8218 if (*commit_id == NULL) {
8219 err = got_error_from_errno("got_object_id_dup");
8220 goto done;
8222 break;
8223 default:
8224 err = got_error(GOT_ERR_OBJ_TYPE);
8225 break;
8228 done:
8229 if (tag)
8230 got_object_tag_close(tag);
8231 if (err) {
8232 free(*commit_id);
8233 *commit_id = NULL;
8235 return err;
8238 static const struct got_error *
8239 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8240 struct tog_reflist_entry *re, struct got_repository *repo)
8242 struct tog_view *log_view;
8243 const struct got_error *err = NULL;
8244 struct got_object_id *commit_id = NULL;
8246 *new_view = NULL;
8248 err = resolve_reflist_entry(&commit_id, re, repo);
8249 if (err) {
8250 if (err->code != GOT_ERR_OBJ_TYPE)
8251 return err;
8252 else
8253 return NULL;
8256 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8257 if (log_view == NULL) {
8258 err = got_error_from_errno("view_open");
8259 goto done;
8262 err = open_log_view(log_view, commit_id, repo,
8263 got_ref_get_name(re->ref), "", 0);
8264 done:
8265 if (err)
8266 view_close(log_view);
8267 else
8268 *new_view = log_view;
8269 free(commit_id);
8270 return err;
8273 static void
8274 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8276 struct tog_reflist_entry *re;
8277 int i = 0;
8279 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8280 return;
8282 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8283 while (i++ < maxscroll) {
8284 if (re == NULL)
8285 break;
8286 s->first_displayed_entry = re;
8287 re = TAILQ_PREV(re, tog_reflist_head, entry);
8291 static const struct got_error *
8292 ref_scroll_down(struct tog_view *view, int maxscroll)
8294 struct tog_ref_view_state *s = &view->state.ref;
8295 struct tog_reflist_entry *next, *last;
8296 int n = 0;
8298 if (s->first_displayed_entry)
8299 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8300 else
8301 next = TAILQ_FIRST(&s->refs);
8303 last = s->last_displayed_entry;
8304 while (next && n++ < maxscroll) {
8305 if (last) {
8306 s->last_displayed_entry = last;
8307 last = TAILQ_NEXT(last, entry);
8309 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8310 s->first_displayed_entry = next;
8311 next = TAILQ_NEXT(next, entry);
8315 return NULL;
8318 static const struct got_error *
8319 search_start_ref_view(struct tog_view *view)
8321 struct tog_ref_view_state *s = &view->state.ref;
8323 s->matched_entry = NULL;
8324 return NULL;
8327 static int
8328 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8330 regmatch_t regmatch;
8332 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8333 0) == 0;
8336 static const struct got_error *
8337 search_next_ref_view(struct tog_view *view)
8339 struct tog_ref_view_state *s = &view->state.ref;
8340 struct tog_reflist_entry *re = NULL;
8342 if (!view->searching) {
8343 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8344 return NULL;
8347 if (s->matched_entry) {
8348 if (view->searching == TOG_SEARCH_FORWARD) {
8349 if (s->selected_entry)
8350 re = TAILQ_NEXT(s->selected_entry, entry);
8351 else
8352 re = TAILQ_PREV(s->selected_entry,
8353 tog_reflist_head, entry);
8354 } else {
8355 if (s->selected_entry == NULL)
8356 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8357 else
8358 re = TAILQ_PREV(s->selected_entry,
8359 tog_reflist_head, entry);
8361 } else {
8362 if (s->selected_entry)
8363 re = s->selected_entry;
8364 else if (view->searching == TOG_SEARCH_FORWARD)
8365 re = TAILQ_FIRST(&s->refs);
8366 else
8367 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8370 while (1) {
8371 if (re == NULL) {
8372 if (s->matched_entry == NULL) {
8373 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8374 return NULL;
8376 if (view->searching == TOG_SEARCH_FORWARD)
8377 re = TAILQ_FIRST(&s->refs);
8378 else
8379 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8382 if (match_reflist_entry(re, &view->regex)) {
8383 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8384 s->matched_entry = re;
8385 break;
8388 if (view->searching == TOG_SEARCH_FORWARD)
8389 re = TAILQ_NEXT(re, entry);
8390 else
8391 re = TAILQ_PREV(re, tog_reflist_head, entry);
8394 if (s->matched_entry) {
8395 s->first_displayed_entry = s->matched_entry;
8396 s->selected = 0;
8399 return NULL;
8402 static const struct got_error *
8403 show_ref_view(struct tog_view *view)
8405 const struct got_error *err = NULL;
8406 struct tog_ref_view_state *s = &view->state.ref;
8407 struct tog_reflist_entry *re;
8408 char *line = NULL;
8409 wchar_t *wline;
8410 struct tog_color *tc;
8411 int width, n, scrollx;
8412 int limit = view->nlines;
8414 werase(view->window);
8416 s->ndisplayed = 0;
8417 if (view_is_hsplit_top(view))
8418 --limit; /* border */
8420 if (limit == 0)
8421 return NULL;
8423 re = s->first_displayed_entry;
8425 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8426 s->nrefs) == -1)
8427 return got_error_from_errno("asprintf");
8429 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8430 if (err) {
8431 free(line);
8432 return err;
8434 if (view_needs_focus_indication(view))
8435 wstandout(view->window);
8436 waddwstr(view->window, wline);
8437 while (width++ < view->ncols)
8438 waddch(view->window, ' ');
8439 if (view_needs_focus_indication(view))
8440 wstandend(view->window);
8441 free(wline);
8442 wline = NULL;
8443 free(line);
8444 line = NULL;
8445 if (--limit <= 0)
8446 return NULL;
8448 n = 0;
8449 view->maxx = 0;
8450 while (re && limit > 0) {
8451 char *line = NULL;
8452 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8454 if (s->show_date) {
8455 struct got_commit_object *ci;
8456 struct got_tag_object *tag;
8457 struct got_object_id *id;
8458 struct tm tm;
8459 time_t t;
8461 err = got_ref_resolve(&id, s->repo, re->ref);
8462 if (err)
8463 return err;
8464 err = got_object_open_as_tag(&tag, s->repo, id);
8465 if (err) {
8466 if (err->code != GOT_ERR_OBJ_TYPE) {
8467 free(id);
8468 return err;
8470 err = got_object_open_as_commit(&ci, s->repo,
8471 id);
8472 if (err) {
8473 free(id);
8474 return err;
8476 t = got_object_commit_get_committer_time(ci);
8477 got_object_commit_close(ci);
8478 } else {
8479 t = got_object_tag_get_tagger_time(tag);
8480 got_object_tag_close(tag);
8482 free(id);
8483 if (gmtime_r(&t, &tm) == NULL)
8484 return got_error_from_errno("gmtime_r");
8485 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8486 return got_error(GOT_ERR_NO_SPACE);
8488 if (got_ref_is_symbolic(re->ref)) {
8489 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8490 ymd : "", got_ref_get_name(re->ref),
8491 got_ref_get_symref_target(re->ref)) == -1)
8492 return got_error_from_errno("asprintf");
8493 } else if (s->show_ids) {
8494 struct got_object_id *id;
8495 char *id_str;
8496 err = got_ref_resolve(&id, s->repo, re->ref);
8497 if (err)
8498 return err;
8499 err = got_object_id_str(&id_str, id);
8500 if (err) {
8501 free(id);
8502 return err;
8504 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8505 got_ref_get_name(re->ref), id_str) == -1) {
8506 err = got_error_from_errno("asprintf");
8507 free(id);
8508 free(id_str);
8509 return err;
8511 free(id);
8512 free(id_str);
8513 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8514 got_ref_get_name(re->ref)) == -1)
8515 return got_error_from_errno("asprintf");
8517 /* use full line width to determine view->maxx */
8518 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8519 if (err) {
8520 free(line);
8521 return err;
8523 view->maxx = MAX(view->maxx, width);
8524 free(wline);
8525 wline = NULL;
8527 err = format_line(&wline, &width, &scrollx, line, view->x,
8528 view->ncols, 0, 0);
8529 if (err) {
8530 free(line);
8531 return err;
8533 if (n == s->selected) {
8534 if (view->focussed)
8535 wstandout(view->window);
8536 s->selected_entry = re;
8538 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8539 if (tc)
8540 wattr_on(view->window,
8541 COLOR_PAIR(tc->colorpair), NULL);
8542 waddwstr(view->window, &wline[scrollx]);
8543 if (tc)
8544 wattr_off(view->window,
8545 COLOR_PAIR(tc->colorpair), NULL);
8546 if (width < view->ncols)
8547 waddch(view->window, '\n');
8548 if (n == s->selected && view->focussed)
8549 wstandend(view->window);
8550 free(line);
8551 free(wline);
8552 wline = NULL;
8553 n++;
8554 s->ndisplayed++;
8555 s->last_displayed_entry = re;
8557 limit--;
8558 re = TAILQ_NEXT(re, entry);
8561 view_border(view);
8562 return err;
8565 static const struct got_error *
8566 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8567 struct tog_reflist_entry *re, struct got_repository *repo)
8569 const struct got_error *err = NULL;
8570 struct got_object_id *commit_id = NULL;
8571 struct tog_view *tree_view;
8573 *new_view = NULL;
8575 err = resolve_reflist_entry(&commit_id, re, repo);
8576 if (err) {
8577 if (err->code != GOT_ERR_OBJ_TYPE)
8578 return err;
8579 else
8580 return NULL;
8584 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8585 if (tree_view == NULL) {
8586 err = got_error_from_errno("view_open");
8587 goto done;
8590 err = open_tree_view(tree_view, commit_id,
8591 got_ref_get_name(re->ref), repo);
8592 if (err)
8593 goto done;
8595 *new_view = tree_view;
8596 done:
8597 free(commit_id);
8598 return err;
8601 static const struct got_error *
8602 ref_goto_line(struct tog_view *view, int nlines)
8604 const struct got_error *err = NULL;
8605 struct tog_ref_view_state *s = &view->state.ref;
8606 int g, idx = s->selected_entry->idx;
8608 g = view->gline;
8609 view->gline = 0;
8611 if (g == 0)
8612 g = 1;
8613 else if (g > s->nrefs)
8614 g = s->nrefs;
8616 if (g >= s->first_displayed_entry->idx + 1 &&
8617 g <= s->last_displayed_entry->idx + 1 &&
8618 g - s->first_displayed_entry->idx - 1 < nlines) {
8619 s->selected = g - s->first_displayed_entry->idx - 1;
8620 return NULL;
8623 if (idx + 1 < g) {
8624 err = ref_scroll_down(view, g - idx - 1);
8625 if (err)
8626 return err;
8627 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8628 s->first_displayed_entry->idx + s->selected < g &&
8629 s->selected < s->ndisplayed - 1)
8630 s->selected = g - s->first_displayed_entry->idx - 1;
8631 } else if (idx + 1 > g)
8632 ref_scroll_up(s, idx - g + 1);
8634 if (g < nlines && s->first_displayed_entry->idx == 0)
8635 s->selected = g - 1;
8637 return NULL;
8641 static const struct got_error *
8642 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8644 const struct got_error *err = NULL;
8645 struct tog_ref_view_state *s = &view->state.ref;
8646 struct tog_reflist_entry *re;
8647 int n, nscroll = view->nlines - 1;
8649 if (view->gline)
8650 return ref_goto_line(view, nscroll);
8652 switch (ch) {
8653 case '0':
8654 case '$':
8655 case KEY_RIGHT:
8656 case 'l':
8657 case KEY_LEFT:
8658 case 'h':
8659 horizontal_scroll_input(view, ch);
8660 break;
8661 case 'i':
8662 s->show_ids = !s->show_ids;
8663 view->count = 0;
8664 break;
8665 case 'm':
8666 s->show_date = !s->show_date;
8667 view->count = 0;
8668 break;
8669 case 'o':
8670 s->sort_by_date = !s->sort_by_date;
8671 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8672 view->count = 0;
8673 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8674 got_ref_cmp_by_commit_timestamp_descending :
8675 tog_ref_cmp_by_name, s->repo);
8676 if (err)
8677 break;
8678 got_reflist_object_id_map_free(tog_refs_idmap);
8679 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8680 &tog_refs, s->repo);
8681 if (err)
8682 break;
8683 ref_view_free_refs(s);
8684 err = ref_view_load_refs(s);
8685 break;
8686 case KEY_ENTER:
8687 case '\r':
8688 view->count = 0;
8689 if (!s->selected_entry)
8690 break;
8691 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8692 break;
8693 case 'T':
8694 view->count = 0;
8695 if (!s->selected_entry)
8696 break;
8697 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8698 break;
8699 case 'g':
8700 case '=':
8701 case KEY_HOME:
8702 s->selected = 0;
8703 view->count = 0;
8704 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8705 break;
8706 case 'G':
8707 case '*':
8708 case KEY_END: {
8709 int eos = view->nlines - 1;
8711 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8712 --eos; /* border */
8713 s->selected = 0;
8714 view->count = 0;
8715 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8716 for (n = 0; n < eos; n++) {
8717 if (re == NULL)
8718 break;
8719 s->first_displayed_entry = re;
8720 re = TAILQ_PREV(re, tog_reflist_head, entry);
8722 if (n > 0)
8723 s->selected = n - 1;
8724 break;
8726 case 'k':
8727 case KEY_UP:
8728 case CTRL('p'):
8729 if (s->selected > 0) {
8730 s->selected--;
8731 break;
8733 ref_scroll_up(s, 1);
8734 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8735 view->count = 0;
8736 break;
8737 case CTRL('u'):
8738 case 'u':
8739 nscroll /= 2;
8740 /* FALL THROUGH */
8741 case KEY_PPAGE:
8742 case CTRL('b'):
8743 case 'b':
8744 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8745 s->selected -= MIN(nscroll, s->selected);
8746 ref_scroll_up(s, MAX(0, nscroll));
8747 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8748 view->count = 0;
8749 break;
8750 case 'j':
8751 case KEY_DOWN:
8752 case CTRL('n'):
8753 if (s->selected < s->ndisplayed - 1) {
8754 s->selected++;
8755 break;
8757 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8758 /* can't scroll any further */
8759 view->count = 0;
8760 break;
8762 ref_scroll_down(view, 1);
8763 break;
8764 case CTRL('d'):
8765 case 'd':
8766 nscroll /= 2;
8767 /* FALL THROUGH */
8768 case KEY_NPAGE:
8769 case CTRL('f'):
8770 case 'f':
8771 case ' ':
8772 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8773 /* can't scroll any further; move cursor down */
8774 if (s->selected < s->ndisplayed - 1)
8775 s->selected += MIN(nscroll,
8776 s->ndisplayed - s->selected - 1);
8777 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8778 s->selected += s->ndisplayed - s->selected - 1;
8779 view->count = 0;
8780 break;
8782 ref_scroll_down(view, nscroll);
8783 break;
8784 case CTRL('l'):
8785 view->count = 0;
8786 tog_free_refs();
8787 err = tog_load_refs(s->repo, s->sort_by_date);
8788 if (err)
8789 break;
8790 ref_view_free_refs(s);
8791 err = ref_view_load_refs(s);
8792 break;
8793 case KEY_RESIZE:
8794 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8795 s->selected = view->nlines - 2;
8796 break;
8797 default:
8798 view->count = 0;
8799 break;
8802 return err;
8805 __dead static void
8806 usage_ref(void)
8808 endwin();
8809 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8810 getprogname());
8811 exit(1);
8814 static const struct got_error *
8815 cmd_ref(int argc, char *argv[])
8817 const struct got_error *error;
8818 struct got_repository *repo = NULL;
8819 struct got_worktree *worktree = NULL;
8820 char *cwd = NULL, *repo_path = NULL;
8821 int ch;
8822 struct tog_view *view;
8823 int *pack_fds = NULL;
8825 while ((ch = getopt(argc, argv, "r:")) != -1) {
8826 switch (ch) {
8827 case 'r':
8828 repo_path = realpath(optarg, NULL);
8829 if (repo_path == NULL)
8830 return got_error_from_errno2("realpath",
8831 optarg);
8832 break;
8833 default:
8834 usage_ref();
8835 /* NOTREACHED */
8839 argc -= optind;
8840 argv += optind;
8842 if (argc > 1)
8843 usage_ref();
8845 error = got_repo_pack_fds_open(&pack_fds);
8846 if (error != NULL)
8847 goto done;
8849 if (repo_path == NULL) {
8850 cwd = getcwd(NULL, 0);
8851 if (cwd == NULL)
8852 return got_error_from_errno("getcwd");
8853 error = got_worktree_open(&worktree, cwd);
8854 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8855 goto done;
8856 if (worktree)
8857 repo_path =
8858 strdup(got_worktree_get_repo_path(worktree));
8859 else
8860 repo_path = strdup(cwd);
8861 if (repo_path == NULL) {
8862 error = got_error_from_errno("strdup");
8863 goto done;
8867 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8868 if (error != NULL)
8869 goto done;
8871 init_curses();
8873 error = apply_unveil(got_repo_get_path(repo), NULL);
8874 if (error)
8875 goto done;
8877 error = tog_load_refs(repo, 0);
8878 if (error)
8879 goto done;
8881 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8882 if (view == NULL) {
8883 error = got_error_from_errno("view_open");
8884 goto done;
8887 error = open_ref_view(view, repo);
8888 if (error)
8889 goto done;
8891 if (worktree) {
8892 /* Release work tree lock. */
8893 got_worktree_close(worktree);
8894 worktree = NULL;
8896 error = view_loop(view);
8897 done:
8898 free(repo_path);
8899 free(cwd);
8900 if (repo) {
8901 const struct got_error *close_err = got_repo_close(repo);
8902 if (close_err)
8903 error = close_err;
8905 if (pack_fds) {
8906 const struct got_error *pack_err =
8907 got_repo_pack_fds_close(pack_fds);
8908 if (error == NULL)
8909 error = pack_err;
8911 tog_free_refs();
8912 return error;
8915 static const struct got_error*
8916 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8917 const char *str)
8919 size_t len;
8921 if (win == NULL)
8922 win = stdscr;
8924 len = strlen(str);
8925 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8927 if (focus)
8928 wstandout(win);
8929 if (mvwprintw(win, y, x, "%s", str) == ERR)
8930 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8931 if (focus)
8932 wstandend(win);
8934 return NULL;
8937 static const struct got_error *
8938 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8940 off_t *p;
8942 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8943 if (p == NULL) {
8944 free(*line_offsets);
8945 *line_offsets = NULL;
8946 return got_error_from_errno("reallocarray");
8949 *line_offsets = p;
8950 (*line_offsets)[*nlines] = off;
8951 ++(*nlines);
8952 return NULL;
8955 static const struct got_error *
8956 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8958 *ret = 0;
8960 for (;n > 0; --n, ++km) {
8961 char *t0, *t, *k;
8962 size_t len = 1;
8964 if (km->keys == NULL)
8965 continue;
8967 t = t0 = strdup(km->keys);
8968 if (t0 == NULL)
8969 return got_error_from_errno("strdup");
8971 len += strlen(t);
8972 while ((k = strsep(&t, " ")) != NULL)
8973 len += strlen(k) > 1 ? 2 : 0;
8974 free(t0);
8975 *ret = MAX(*ret, len);
8978 return NULL;
8982 * Write keymap section headers, keys, and key info in km to f.
8983 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8984 * wrap control and symbolic keys in guillemets, else use <>.
8986 static const struct got_error *
8987 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8989 int n, len = width;
8991 if (km->keys) {
8992 static const char *u8_glyph[] = {
8993 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8994 "\xe2\x80\xba" /* U+203A (utf8 >) */
8996 char *t0, *t, *k;
8997 int cs, s, first = 1;
8999 cs = got_locale_is_utf8();
9001 t = t0 = strdup(km->keys);
9002 if (t0 == NULL)
9003 return got_error_from_errno("strdup");
9005 len = strlen(km->keys);
9006 while ((k = strsep(&t, " ")) != NULL) {
9007 s = strlen(k) > 1; /* control or symbolic key */
9008 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9009 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9010 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9011 if (n < 0) {
9012 free(t0);
9013 return got_error_from_errno("fprintf");
9015 first = 0;
9016 len += s ? 2 : 0;
9017 *off += n;
9019 free(t0);
9021 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9022 if (n < 0)
9023 return got_error_from_errno("fprintf");
9024 *off += n;
9026 return NULL;
9029 static const struct got_error *
9030 format_help(struct tog_help_view_state *s)
9032 const struct got_error *err = NULL;
9033 off_t off = 0;
9034 int i, max, n, show = s->all;
9035 static const struct tog_key_map km[] = {
9036 #define KEYMAP_(info, type) { NULL, (info), type }
9037 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9038 GENERATE_HELP
9039 #undef KEYMAP_
9040 #undef KEY_
9043 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9044 if (err)
9045 return err;
9047 n = nitems(km);
9048 err = max_key_str(&max, km, n);
9049 if (err)
9050 return err;
9052 for (i = 0; i < n; ++i) {
9053 if (km[i].keys == NULL) {
9054 show = s->all;
9055 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9056 km[i].type == s->type || s->all)
9057 show = 1;
9059 if (show) {
9060 err = format_help_line(&off, s->f, &km[i], max);
9061 if (err)
9062 return err;
9063 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9064 if (err)
9065 return err;
9068 fputc('\n', s->f);
9069 ++off;
9070 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9071 return err;
9074 static const struct got_error *
9075 create_help(struct tog_help_view_state *s)
9077 FILE *f;
9078 const struct got_error *err;
9080 free(s->line_offsets);
9081 s->line_offsets = NULL;
9082 s->nlines = 0;
9084 f = got_opentemp();
9085 if (f == NULL)
9086 return got_error_from_errno("got_opentemp");
9087 s->f = f;
9089 err = format_help(s);
9090 if (err)
9091 return err;
9093 if (s->f && fflush(s->f) != 0)
9094 return got_error_from_errno("fflush");
9096 return NULL;
9099 static const struct got_error *
9100 search_start_help_view(struct tog_view *view)
9102 view->state.help.matched_line = 0;
9103 return NULL;
9106 static void
9107 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9108 size_t *nlines, int **first, int **last, int **match, int **selected)
9110 struct tog_help_view_state *s = &view->state.help;
9112 *f = s->f;
9113 *nlines = s->nlines;
9114 *line_offsets = s->line_offsets;
9115 *match = &s->matched_line;
9116 *first = &s->first_displayed_line;
9117 *last = &s->last_displayed_line;
9118 *selected = &s->selected_line;
9121 static const struct got_error *
9122 show_help_view(struct tog_view *view)
9124 struct tog_help_view_state *s = &view->state.help;
9125 const struct got_error *err;
9126 regmatch_t *regmatch = &view->regmatch;
9127 wchar_t *wline;
9128 char *line;
9129 ssize_t linelen;
9130 size_t linesz = 0;
9131 int width, nprinted = 0, rc = 0;
9132 int eos = view->nlines;
9134 if (view_is_hsplit_top(view))
9135 --eos; /* account for border */
9137 s->lineno = 0;
9138 rewind(s->f);
9139 werase(view->window);
9141 if (view->gline > s->nlines - 1)
9142 view->gline = s->nlines - 1;
9144 err = win_draw_center(view->window, 0, 0, view->ncols,
9145 view_needs_focus_indication(view),
9146 "tog help (press q to return to tog)");
9147 if (err)
9148 return err;
9149 if (eos <= 1)
9150 return NULL;
9151 waddstr(view->window, "\n\n");
9152 eos -= 2;
9154 s->eof = 0;
9155 view->maxx = 0;
9156 line = NULL;
9157 while (eos > 0 && nprinted < eos) {
9158 attr_t attr = 0;
9160 linelen = getline(&line, &linesz, s->f);
9161 if (linelen == -1) {
9162 if (!feof(s->f)) {
9163 free(line);
9164 return got_ferror(s->f, GOT_ERR_IO);
9166 s->eof = 1;
9167 break;
9169 if (++s->lineno < s->first_displayed_line)
9170 continue;
9171 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9172 continue;
9173 if (s->lineno == view->hiline)
9174 attr = A_STANDOUT;
9176 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9177 view->x ? 1 : 0);
9178 if (err) {
9179 free(line);
9180 return err;
9182 view->maxx = MAX(view->maxx, width);
9183 free(wline);
9184 wline = NULL;
9186 if (attr)
9187 wattron(view->window, attr);
9188 if (s->first_displayed_line + nprinted == s->matched_line &&
9189 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9190 err = add_matched_line(&width, line, view->ncols - 1, 0,
9191 view->window, view->x, regmatch);
9192 if (err) {
9193 free(line);
9194 return err;
9196 } else {
9197 int skip;
9199 err = format_line(&wline, &width, &skip, line,
9200 view->x, view->ncols, 0, view->x ? 1 : 0);
9201 if (err) {
9202 free(line);
9203 return err;
9205 waddwstr(view->window, &wline[skip]);
9206 free(wline);
9207 wline = NULL;
9209 if (s->lineno == view->hiline) {
9210 while (width++ < view->ncols)
9211 waddch(view->window, ' ');
9212 } else {
9213 if (width < view->ncols)
9214 waddch(view->window, '\n');
9216 if (attr)
9217 wattroff(view->window, attr);
9218 if (++nprinted == 1)
9219 s->first_displayed_line = s->lineno;
9221 free(line);
9222 if (nprinted > 0)
9223 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9224 else
9225 s->last_displayed_line = s->first_displayed_line;
9227 view_border(view);
9229 if (s->eof) {
9230 rc = waddnstr(view->window,
9231 "See the tog(1) manual page for full documentation",
9232 view->ncols - 1);
9233 if (rc == ERR)
9234 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9235 } else {
9236 wmove(view->window, view->nlines - 1, 0);
9237 wclrtoeol(view->window);
9238 wstandout(view->window);
9239 rc = waddnstr(view->window, "scroll down for more...",
9240 view->ncols - 1);
9241 if (rc == ERR)
9242 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9243 if (getcurx(view->window) < view->ncols - 6) {
9244 rc = wprintw(view->window, "[%.0f%%]",
9245 100.00 * s->last_displayed_line / s->nlines);
9246 if (rc == ERR)
9247 return got_error_msg(GOT_ERR_IO, "wprintw");
9249 wstandend(view->window);
9252 return NULL;
9255 static const struct got_error *
9256 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9258 struct tog_help_view_state *s = &view->state.help;
9259 const struct got_error *err = NULL;
9260 char *line = NULL;
9261 ssize_t linelen;
9262 size_t linesz = 0;
9263 int eos, nscroll;
9265 eos = nscroll = view->nlines;
9266 if (view_is_hsplit_top(view))
9267 --eos; /* border */
9269 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9271 switch (ch) {
9272 case '0':
9273 case '$':
9274 case KEY_RIGHT:
9275 case 'l':
9276 case KEY_LEFT:
9277 case 'h':
9278 horizontal_scroll_input(view, ch);
9279 break;
9280 case 'g':
9281 case KEY_HOME:
9282 s->first_displayed_line = 1;
9283 view->count = 0;
9284 break;
9285 case 'G':
9286 case KEY_END:
9287 view->count = 0;
9288 if (s->eof)
9289 break;
9290 s->first_displayed_line = (s->nlines - eos) + 3;
9291 s->eof = 1;
9292 break;
9293 case 'k':
9294 case KEY_UP:
9295 if (s->first_displayed_line > 1)
9296 --s->first_displayed_line;
9297 else
9298 view->count = 0;
9299 break;
9300 case CTRL('u'):
9301 case 'u':
9302 nscroll /= 2;
9303 /* FALL THROUGH */
9304 case KEY_PPAGE:
9305 case CTRL('b'):
9306 case 'b':
9307 if (s->first_displayed_line == 1) {
9308 view->count = 0;
9309 break;
9311 while (--nscroll > 0 && s->first_displayed_line > 1)
9312 s->first_displayed_line--;
9313 break;
9314 case 'j':
9315 case KEY_DOWN:
9316 case CTRL('n'):
9317 if (!s->eof)
9318 ++s->first_displayed_line;
9319 else
9320 view->count = 0;
9321 break;
9322 case CTRL('d'):
9323 case 'd':
9324 nscroll /= 2;
9325 /* FALL THROUGH */
9326 case KEY_NPAGE:
9327 case CTRL('f'):
9328 case 'f':
9329 case ' ':
9330 if (s->eof) {
9331 view->count = 0;
9332 break;
9334 while (!s->eof && --nscroll > 0) {
9335 linelen = getline(&line, &linesz, s->f);
9336 s->first_displayed_line++;
9337 if (linelen == -1) {
9338 if (feof(s->f))
9339 s->eof = 1;
9340 else
9341 err = got_ferror(s->f, GOT_ERR_IO);
9342 break;
9345 free(line);
9346 break;
9347 default:
9348 view->count = 0;
9349 break;
9352 return err;
9355 static const struct got_error *
9356 close_help_view(struct tog_view *view)
9358 struct tog_help_view_state *s = &view->state.help;
9360 free(s->line_offsets);
9361 s->line_offsets = NULL;
9362 if (fclose(s->f) == EOF)
9363 return got_error_from_errno("fclose");
9365 return NULL;
9368 static const struct got_error *
9369 reset_help_view(struct tog_view *view)
9371 struct tog_help_view_state *s = &view->state.help;
9374 if (s->f && fclose(s->f) == EOF)
9375 return got_error_from_errno("fclose");
9377 wclear(view->window);
9378 view->count = 0;
9379 view->x = 0;
9380 s->all = !s->all;
9381 s->first_displayed_line = 1;
9382 s->last_displayed_line = view->nlines;
9383 s->matched_line = 0;
9385 return create_help(s);
9388 static const struct got_error *
9389 open_help_view(struct tog_view *view, struct tog_view *parent)
9391 const struct got_error *err = NULL;
9392 struct tog_help_view_state *s = &view->state.help;
9394 s->type = (enum tog_keymap_type)parent->type;
9395 s->first_displayed_line = 1;
9396 s->last_displayed_line = view->nlines;
9397 s->selected_line = 1;
9399 view->show = show_help_view;
9400 view->input = input_help_view;
9401 view->reset = reset_help_view;
9402 view->close = close_help_view;
9403 view->search_start = search_start_help_view;
9404 view->search_setup = search_setup_help_view;
9405 view->search_next = search_next_view_match;
9407 err = create_help(s);
9408 return err;
9411 static const struct got_error *
9412 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9413 enum tog_view_type request, int y, int x)
9415 const struct got_error *err = NULL;
9417 *new_view = NULL;
9419 switch (request) {
9420 case TOG_VIEW_DIFF:
9421 if (view->type == TOG_VIEW_LOG) {
9422 struct tog_log_view_state *s = &view->state.log;
9424 err = open_diff_view_for_commit(new_view, y, x,
9425 s->selected_entry->commit, s->selected_entry->id,
9426 view, s->repo);
9427 } else
9428 return got_error_msg(GOT_ERR_NOT_IMPL,
9429 "parent/child view pair not supported");
9430 break;
9431 case TOG_VIEW_BLAME:
9432 if (view->type == TOG_VIEW_TREE) {
9433 struct tog_tree_view_state *s = &view->state.tree;
9435 err = blame_tree_entry(new_view, y, x,
9436 s->selected_entry, &s->parents, s->commit_id,
9437 s->repo);
9438 } else
9439 return got_error_msg(GOT_ERR_NOT_IMPL,
9440 "parent/child view pair not supported");
9441 break;
9442 case TOG_VIEW_LOG:
9443 if (view->type == TOG_VIEW_BLAME)
9444 err = log_annotated_line(new_view, y, x,
9445 view->state.blame.repo, view->state.blame.id_to_log);
9446 else if (view->type == TOG_VIEW_TREE)
9447 err = log_selected_tree_entry(new_view, y, x,
9448 &view->state.tree);
9449 else if (view->type == TOG_VIEW_REF)
9450 err = log_ref_entry(new_view, y, x,
9451 view->state.ref.selected_entry,
9452 view->state.ref.repo);
9453 else
9454 return got_error_msg(GOT_ERR_NOT_IMPL,
9455 "parent/child view pair not supported");
9456 break;
9457 case TOG_VIEW_TREE:
9458 if (view->type == TOG_VIEW_LOG)
9459 err = browse_commit_tree(new_view, y, x,
9460 view->state.log.selected_entry,
9461 view->state.log.in_repo_path,
9462 view->state.log.head_ref_name,
9463 view->state.log.repo);
9464 else if (view->type == TOG_VIEW_REF)
9465 err = browse_ref_tree(new_view, y, x,
9466 view->state.ref.selected_entry,
9467 view->state.ref.repo);
9468 else
9469 return got_error_msg(GOT_ERR_NOT_IMPL,
9470 "parent/child view pair not supported");
9471 break;
9472 case TOG_VIEW_REF:
9473 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9474 if (*new_view == NULL)
9475 return got_error_from_errno("view_open");
9476 if (view->type == TOG_VIEW_LOG)
9477 err = open_ref_view(*new_view, view->state.log.repo);
9478 else if (view->type == TOG_VIEW_TREE)
9479 err = open_ref_view(*new_view, view->state.tree.repo);
9480 else
9481 err = got_error_msg(GOT_ERR_NOT_IMPL,
9482 "parent/child view pair not supported");
9483 if (err)
9484 view_close(*new_view);
9485 break;
9486 case TOG_VIEW_HELP:
9487 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9488 if (*new_view == NULL)
9489 return got_error_from_errno("view_open");
9490 err = open_help_view(*new_view, view);
9491 if (err)
9492 view_close(*new_view);
9493 break;
9494 default:
9495 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9498 return err;
9502 * If view was scrolled down to move the selected line into view when opening a
9503 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9505 static void
9506 offset_selection_up(struct tog_view *view)
9508 switch (view->type) {
9509 case TOG_VIEW_BLAME: {
9510 struct tog_blame_view_state *s = &view->state.blame;
9511 if (s->first_displayed_line == 1) {
9512 s->selected_line = MAX(s->selected_line - view->offset,
9513 1);
9514 break;
9516 if (s->first_displayed_line > view->offset)
9517 s->first_displayed_line -= view->offset;
9518 else
9519 s->first_displayed_line = 1;
9520 s->selected_line += view->offset;
9521 break;
9523 case TOG_VIEW_LOG:
9524 log_scroll_up(&view->state.log, view->offset);
9525 view->state.log.selected += view->offset;
9526 break;
9527 case TOG_VIEW_REF:
9528 ref_scroll_up(&view->state.ref, view->offset);
9529 view->state.ref.selected += view->offset;
9530 break;
9531 case TOG_VIEW_TREE:
9532 tree_scroll_up(&view->state.tree, view->offset);
9533 view->state.tree.selected += view->offset;
9534 break;
9535 default:
9536 break;
9539 view->offset = 0;
9543 * If the selected line is in the section of screen covered by the bottom split,
9544 * scroll down offset lines to move it into view and index its new position.
9546 static const struct got_error *
9547 offset_selection_down(struct tog_view *view)
9549 const struct got_error *err = NULL;
9550 const struct got_error *(*scrolld)(struct tog_view *, int);
9551 int *selected = NULL;
9552 int header, offset;
9554 switch (view->type) {
9555 case TOG_VIEW_BLAME: {
9556 struct tog_blame_view_state *s = &view->state.blame;
9557 header = 3;
9558 scrolld = NULL;
9559 if (s->selected_line > view->nlines - header) {
9560 offset = abs(view->nlines - s->selected_line - header);
9561 s->first_displayed_line += offset;
9562 s->selected_line -= offset;
9563 view->offset = offset;
9565 break;
9567 case TOG_VIEW_LOG: {
9568 struct tog_log_view_state *s = &view->state.log;
9569 scrolld = &log_scroll_down;
9570 header = view_is_parent_view(view) ? 3 : 2;
9571 selected = &s->selected;
9572 break;
9574 case TOG_VIEW_REF: {
9575 struct tog_ref_view_state *s = &view->state.ref;
9576 scrolld = &ref_scroll_down;
9577 header = 3;
9578 selected = &s->selected;
9579 break;
9581 case TOG_VIEW_TREE: {
9582 struct tog_tree_view_state *s = &view->state.tree;
9583 scrolld = &tree_scroll_down;
9584 header = 5;
9585 selected = &s->selected;
9586 break;
9588 default:
9589 selected = NULL;
9590 scrolld = NULL;
9591 header = 0;
9592 break;
9595 if (selected && *selected > view->nlines - header) {
9596 offset = abs(view->nlines - *selected - header);
9597 view->offset = offset;
9598 if (scrolld && offset) {
9599 err = scrolld(view, offset);
9600 *selected -= offset;
9604 return err;
9607 static void
9608 list_commands(FILE *fp)
9610 size_t i;
9612 fprintf(fp, "commands:");
9613 for (i = 0; i < nitems(tog_commands); i++) {
9614 const struct tog_cmd *cmd = &tog_commands[i];
9615 fprintf(fp, " %s", cmd->name);
9617 fputc('\n', fp);
9620 __dead static void
9621 usage(int hflag, int status)
9623 FILE *fp = (status == 0) ? stdout : stderr;
9625 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9626 getprogname());
9627 if (hflag) {
9628 fprintf(fp, "lazy usage: %s path\n", getprogname());
9629 list_commands(fp);
9631 exit(status);
9634 static char **
9635 make_argv(int argc, ...)
9637 va_list ap;
9638 char **argv;
9639 int i;
9641 va_start(ap, argc);
9643 argv = calloc(argc, sizeof(char *));
9644 if (argv == NULL)
9645 err(1, "calloc");
9646 for (i = 0; i < argc; i++) {
9647 argv[i] = strdup(va_arg(ap, char *));
9648 if (argv[i] == NULL)
9649 err(1, "strdup");
9652 va_end(ap);
9653 return argv;
9657 * Try to convert 'tog path' into a 'tog log path' command.
9658 * The user could simply have mistyped the command rather than knowingly
9659 * provided a path. So check whether argv[0] can in fact be resolved
9660 * to a path in the HEAD commit and print a special error if not.
9661 * This hack is for mpi@ <3
9663 static const struct got_error *
9664 tog_log_with_path(int argc, char *argv[])
9666 const struct got_error *error = NULL, *close_err;
9667 const struct tog_cmd *cmd = NULL;
9668 struct got_repository *repo = NULL;
9669 struct got_worktree *worktree = NULL;
9670 struct got_object_id *commit_id = NULL, *id = NULL;
9671 struct got_commit_object *commit = NULL;
9672 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9673 char *commit_id_str = NULL, **cmd_argv = NULL;
9674 int *pack_fds = NULL;
9676 cwd = getcwd(NULL, 0);
9677 if (cwd == NULL)
9678 return got_error_from_errno("getcwd");
9680 error = got_repo_pack_fds_open(&pack_fds);
9681 if (error != NULL)
9682 goto done;
9684 error = got_worktree_open(&worktree, cwd);
9685 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9686 goto done;
9688 if (worktree)
9689 repo_path = strdup(got_worktree_get_repo_path(worktree));
9690 else
9691 repo_path = strdup(cwd);
9692 if (repo_path == NULL) {
9693 error = got_error_from_errno("strdup");
9694 goto done;
9697 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9698 if (error != NULL)
9699 goto done;
9701 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9702 repo, worktree);
9703 if (error)
9704 goto done;
9706 error = tog_load_refs(repo, 0);
9707 if (error)
9708 goto done;
9709 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9710 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9711 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9712 if (error)
9713 goto done;
9715 if (worktree) {
9716 got_worktree_close(worktree);
9717 worktree = NULL;
9720 error = got_object_open_as_commit(&commit, repo, commit_id);
9721 if (error)
9722 goto done;
9724 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9725 if (error) {
9726 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9727 goto done;
9728 fprintf(stderr, "%s: '%s' is no known command or path\n",
9729 getprogname(), argv[0]);
9730 usage(1, 1);
9731 /* not reached */
9734 error = got_object_id_str(&commit_id_str, commit_id);
9735 if (error)
9736 goto done;
9738 cmd = &tog_commands[0]; /* log */
9739 argc = 4;
9740 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9741 error = cmd->cmd_main(argc, cmd_argv);
9742 done:
9743 if (repo) {
9744 close_err = got_repo_close(repo);
9745 if (error == NULL)
9746 error = close_err;
9748 if (commit)
9749 got_object_commit_close(commit);
9750 if (worktree)
9751 got_worktree_close(worktree);
9752 if (pack_fds) {
9753 const struct got_error *pack_err =
9754 got_repo_pack_fds_close(pack_fds);
9755 if (error == NULL)
9756 error = pack_err;
9758 free(id);
9759 free(commit_id_str);
9760 free(commit_id);
9761 free(cwd);
9762 free(repo_path);
9763 free(in_repo_path);
9764 if (cmd_argv) {
9765 int i;
9766 for (i = 0; i < argc; i++)
9767 free(cmd_argv[i]);
9768 free(cmd_argv);
9770 tog_free_refs();
9771 return error;
9774 int
9775 main(int argc, char *argv[])
9777 const struct got_error *io_err, *error = NULL;
9778 const struct tog_cmd *cmd = NULL;
9779 int ch, hflag = 0, Vflag = 0;
9780 char **cmd_argv = NULL;
9781 static const struct option longopts[] = {
9782 { "version", no_argument, NULL, 'V' },
9783 { NULL, 0, NULL, 0}
9785 char *diff_algo_str = NULL;
9786 const char *test_script_path;
9788 setlocale(LC_CTYPE, "");
9791 * Test mode init must happen before pledge() because "tty" will
9792 * not allow TTY-related ioctls to occur via regular files.
9794 test_script_path = getenv("TOG_TEST_SCRIPT");
9795 if (test_script_path != NULL) {
9796 error = init_mock_term(test_script_path);
9797 if (error) {
9798 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9799 return 1;
9803 #if !defined(PROFILE)
9804 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9805 NULL) == -1)
9806 err(1, "pledge");
9807 #endif
9809 if (!isatty(STDIN_FILENO))
9810 errx(1, "standard input is not a tty");
9812 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9813 switch (ch) {
9814 case 'h':
9815 hflag = 1;
9816 break;
9817 case 'V':
9818 Vflag = 1;
9819 break;
9820 default:
9821 usage(hflag, 1);
9822 /* NOTREACHED */
9826 argc -= optind;
9827 argv += optind;
9828 optind = 1;
9829 optreset = 1;
9831 if (Vflag) {
9832 got_version_print_str();
9833 return 0;
9836 if (argc == 0) {
9837 if (hflag)
9838 usage(hflag, 0);
9839 /* Build an argument vector which runs a default command. */
9840 cmd = &tog_commands[0];
9841 argc = 1;
9842 cmd_argv = make_argv(argc, cmd->name);
9843 } else {
9844 size_t i;
9846 /* Did the user specify a command? */
9847 for (i = 0; i < nitems(tog_commands); i++) {
9848 if (strncmp(tog_commands[i].name, argv[0],
9849 strlen(argv[0])) == 0) {
9850 cmd = &tog_commands[i];
9851 break;
9856 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9857 if (diff_algo_str) {
9858 if (strcasecmp(diff_algo_str, "patience") == 0)
9859 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9860 if (strcasecmp(diff_algo_str, "myers") == 0)
9861 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9864 if (cmd == NULL) {
9865 if (argc != 1)
9866 usage(0, 1);
9867 /* No command specified; try log with a path */
9868 error = tog_log_with_path(argc, argv);
9869 } else {
9870 if (hflag)
9871 cmd->cmd_usage();
9872 else
9873 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9876 if (using_mock_io) {
9877 io_err = tog_io_close();
9878 if (error == NULL)
9879 error = io_err;
9881 endwin();
9882 if (cmd_argv) {
9883 int i;
9884 for (i = 0; i < argc; i++)
9885 free(cmd_argv[i]);
9886 free(cmd_argv);
9889 if (error && error->code != GOT_ERR_CANCELLED &&
9890 error->code != GOT_ERR_EOF &&
9891 error->code != GOT_ERR_PRIVSEP_EXIT &&
9892 error->code != GOT_ERR_PRIVSEP_PIPE &&
9893 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9894 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9895 return 0;