Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
60 #ifndef MIN
61 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
62 #endif
64 #ifndef MAX
65 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
66 #endif
68 #define CTRL(x) ((x) & 0x1f)
70 #ifndef nitems
71 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
72 #endif
74 struct tog_cmd {
75 const char *name;
76 const struct got_error *(*cmd_main)(int, char *[]);
77 void (*cmd_usage)(void);
78 };
80 __dead static void usage(int, int);
81 __dead static void usage_log(void);
82 __dead static void usage_diff(void);
83 __dead static void usage_blame(void);
84 __dead static void usage_tree(void);
85 __dead static void usage_ref(void);
87 static const struct got_error* cmd_log(int, char *[]);
88 static const struct got_error* cmd_diff(int, char *[]);
89 static const struct got_error* cmd_blame(int, char *[]);
90 static const struct got_error* cmd_tree(int, char *[]);
91 static const struct got_error* cmd_ref(int, char *[]);
93 static const struct tog_cmd tog_commands[] = {
94 { "log", cmd_log, usage_log },
95 { "diff", cmd_diff, usage_diff },
96 { "blame", cmd_blame, usage_blame },
97 { "tree", cmd_tree, usage_tree },
98 { "ref", cmd_ref, usage_ref },
99 };
101 enum tog_view_type {
102 TOG_VIEW_DIFF,
103 TOG_VIEW_LOG,
104 TOG_VIEW_BLAME,
105 TOG_VIEW_TREE,
106 TOG_VIEW_REF,
107 TOG_VIEW_HELP
108 };
110 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
111 enum tog_keymap_type {
112 TOG_KEYMAP_KEYS = -2,
113 TOG_KEYMAP_GLOBAL,
114 TOG_KEYMAP_DIFF,
115 TOG_KEYMAP_LOG,
116 TOG_KEYMAP_BLAME,
117 TOG_KEYMAP_TREE,
118 TOG_KEYMAP_REF,
119 TOG_KEYMAP_HELP
120 };
122 enum tog_view_mode {
123 TOG_VIEW_SPLIT_NONE,
124 TOG_VIEW_SPLIT_VERT,
125 TOG_VIEW_SPLIT_HRZN
126 };
128 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
130 #define TOG_EOF_STRING "(END)"
132 struct commit_queue_entry {
133 TAILQ_ENTRY(commit_queue_entry) entry;
134 struct got_object_id *id;
135 struct got_commit_object *commit;
136 int idx;
137 };
138 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
139 struct commit_queue {
140 int ncommits;
141 struct commit_queue_head head;
142 };
144 struct tog_color {
145 STAILQ_ENTRY(tog_color) entry;
146 regex_t regex;
147 short colorpair;
148 };
149 STAILQ_HEAD(tog_colors, tog_color);
151 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
152 static struct got_reflist_object_id_map *tog_refs_idmap;
153 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
155 static const struct got_error *
156 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
157 struct got_reference* re2)
159 const char *name1 = got_ref_get_name(re1);
160 const char *name2 = got_ref_get_name(re2);
161 int isbackup1, isbackup2;
163 /* Sort backup refs towards the bottom of the list. */
164 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
165 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
166 if (!isbackup1 && isbackup2) {
167 *cmp = -1;
168 return NULL;
169 } else if (isbackup1 && !isbackup2) {
170 *cmp = 1;
171 return NULL;
174 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
175 return NULL;
178 static const struct got_error *
179 tog_load_refs(struct got_repository *repo, int sort_by_date)
181 const struct got_error *err;
183 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
184 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
185 repo);
186 if (err)
187 return err;
189 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
190 repo);
193 static void
194 tog_free_refs(void)
196 if (tog_refs_idmap) {
197 got_reflist_object_id_map_free(tog_refs_idmap);
198 tog_refs_idmap = NULL;
200 got_ref_list_free(&tog_refs);
203 static const struct got_error *
204 add_color(struct tog_colors *colors, const char *pattern,
205 int idx, short color)
207 const struct got_error *err = NULL;
208 struct tog_color *tc;
209 int regerr = 0;
211 if (idx < 1 || idx > COLOR_PAIRS - 1)
212 return NULL;
214 init_pair(idx, color, -1);
216 tc = calloc(1, sizeof(*tc));
217 if (tc == NULL)
218 return got_error_from_errno("calloc");
219 regerr = regcomp(&tc->regex, pattern,
220 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
221 if (regerr) {
222 static char regerr_msg[512];
223 static char err_msg[512];
224 regerror(regerr, &tc->regex, regerr_msg,
225 sizeof(regerr_msg));
226 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
227 regerr_msg);
228 err = got_error_msg(GOT_ERR_REGEX, err_msg);
229 free(tc);
230 return err;
232 tc->colorpair = idx;
233 STAILQ_INSERT_HEAD(colors, tc, entry);
234 return NULL;
237 static void
238 free_colors(struct tog_colors *colors)
240 struct tog_color *tc;
242 while (!STAILQ_EMPTY(colors)) {
243 tc = STAILQ_FIRST(colors);
244 STAILQ_REMOVE_HEAD(colors, entry);
245 regfree(&tc->regex);
246 free(tc);
250 static struct tog_color *
251 get_color(struct tog_colors *colors, int colorpair)
253 struct tog_color *tc = NULL;
255 STAILQ_FOREACH(tc, colors, entry) {
256 if (tc->colorpair == colorpair)
257 return tc;
260 return NULL;
263 static int
264 default_color_value(const char *envvar)
266 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
281 return COLOR_GREEN;
282 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
287 return COLOR_YELLOW;
288 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
291 return COLOR_MAGENTA;
292 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
295 return COLOR_CYAN;
297 return -1;
300 static int
301 get_color_value(const char *envvar)
303 const char *val = getenv(envvar);
305 if (val == NULL)
306 return default_color_value(envvar);
308 if (strcasecmp(val, "black") == 0)
309 return COLOR_BLACK;
310 if (strcasecmp(val, "red") == 0)
311 return COLOR_RED;
312 if (strcasecmp(val, "green") == 0)
313 return COLOR_GREEN;
314 if (strcasecmp(val, "yellow") == 0)
315 return COLOR_YELLOW;
316 if (strcasecmp(val, "blue") == 0)
317 return COLOR_BLUE;
318 if (strcasecmp(val, "magenta") == 0)
319 return COLOR_MAGENTA;
320 if (strcasecmp(val, "cyan") == 0)
321 return COLOR_CYAN;
322 if (strcasecmp(val, "white") == 0)
323 return COLOR_WHITE;
324 if (strcasecmp(val, "default") == 0)
325 return -1;
327 return default_color_value(envvar);
330 struct tog_diff_view_state {
331 struct got_object_id *id1, *id2;
332 const char *label1, *label2;
333 FILE *f, *f1, *f2;
334 int fd1, fd2;
335 int lineno;
336 int first_displayed_line;
337 int last_displayed_line;
338 int eof;
339 int diff_context;
340 int ignore_whitespace;
341 int force_text_diff;
342 struct got_repository *repo;
343 struct got_diff_line *lines;
344 size_t nlines;
345 int matched_line;
346 int selected_line;
348 /* passed from log or blame view; may be NULL */
349 struct tog_view *parent_view;
350 };
352 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
353 static volatile sig_atomic_t tog_thread_error;
355 struct tog_log_thread_args {
356 pthread_cond_t need_commits;
357 pthread_cond_t commit_loaded;
358 int commits_needed;
359 int load_all;
360 struct got_commit_graph *graph;
361 struct commit_queue *real_commits;
362 const char *in_repo_path;
363 struct got_object_id *start_id;
364 struct got_repository *repo;
365 int *pack_fds;
366 int log_complete;
367 sig_atomic_t *quit;
368 struct commit_queue_entry **first_displayed_entry;
369 struct commit_queue_entry **selected_entry;
370 int *searching;
371 int *search_next_done;
372 regex_t *regex;
373 int *limiting;
374 int limit_match;
375 regex_t *limit_regex;
376 struct commit_queue *limit_commits;
377 };
379 struct tog_log_view_state {
380 struct commit_queue *commits;
381 struct commit_queue_entry *first_displayed_entry;
382 struct commit_queue_entry *last_displayed_entry;
383 struct commit_queue_entry *selected_entry;
384 struct commit_queue real_commits;
385 int selected;
386 char *in_repo_path;
387 char *head_ref_name;
388 int log_branches;
389 struct got_repository *repo;
390 struct got_object_id *start_id;
391 sig_atomic_t quit;
392 pthread_t thread;
393 struct tog_log_thread_args thread_args;
394 struct commit_queue_entry *matched_entry;
395 struct commit_queue_entry *search_entry;
396 struct tog_colors colors;
397 int use_committer;
398 int limit_view;
399 regex_t limit_regex;
400 struct commit_queue limit_commits;
401 };
403 #define TOG_COLOR_DIFF_MINUS 1
404 #define TOG_COLOR_DIFF_PLUS 2
405 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
406 #define TOG_COLOR_DIFF_META 4
407 #define TOG_COLOR_TREE_SUBMODULE 5
408 #define TOG_COLOR_TREE_SYMLINK 6
409 #define TOG_COLOR_TREE_DIRECTORY 7
410 #define TOG_COLOR_TREE_EXECUTABLE 8
411 #define TOG_COLOR_COMMIT 9
412 #define TOG_COLOR_AUTHOR 10
413 #define TOG_COLOR_DATE 11
414 #define TOG_COLOR_REFS_HEADS 12
415 #define TOG_COLOR_REFS_TAGS 13
416 #define TOG_COLOR_REFS_REMOTES 14
417 #define TOG_COLOR_REFS_BACKUP 15
419 struct tog_blame_cb_args {
420 struct tog_blame_line *lines; /* one per line */
421 int nlines;
423 struct tog_view *view;
424 struct got_object_id *commit_id;
425 int *quit;
426 };
428 struct tog_blame_thread_args {
429 const char *path;
430 struct got_repository *repo;
431 struct tog_blame_cb_args *cb_args;
432 int *complete;
433 got_cancel_cb cancel_cb;
434 void *cancel_arg;
435 pthread_cond_t blame_complete;
436 };
438 struct tog_blame {
439 FILE *f;
440 off_t filesize;
441 struct tog_blame_line *lines;
442 int nlines;
443 off_t *line_offsets;
444 pthread_t thread;
445 struct tog_blame_thread_args thread_args;
446 struct tog_blame_cb_args cb_args;
447 const char *path;
448 int *pack_fds;
449 };
451 struct tog_blame_view_state {
452 int first_displayed_line;
453 int last_displayed_line;
454 int selected_line;
455 int last_diffed_line;
456 int blame_complete;
457 int eof;
458 int done;
459 struct got_object_id_queue blamed_commits;
460 struct got_object_qid *blamed_commit;
461 char *path;
462 struct got_repository *repo;
463 struct got_object_id *commit_id;
464 struct got_object_id *id_to_log;
465 struct tog_blame blame;
466 int matched_line;
467 struct tog_colors colors;
468 };
470 struct tog_parent_tree {
471 TAILQ_ENTRY(tog_parent_tree) entry;
472 struct got_tree_object *tree;
473 struct got_tree_entry *first_displayed_entry;
474 struct got_tree_entry *selected_entry;
475 int selected;
476 };
478 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
480 struct tog_tree_view_state {
481 char *tree_label;
482 struct got_object_id *commit_id;/* commit which this tree belongs to */
483 struct got_tree_object *root; /* the commit's root tree entry */
484 struct got_tree_object *tree; /* currently displayed (sub-)tree */
485 struct got_tree_entry *first_displayed_entry;
486 struct got_tree_entry *last_displayed_entry;
487 struct got_tree_entry *selected_entry;
488 int ndisplayed, selected, show_ids;
489 struct tog_parent_trees parents; /* parent trees of current sub-tree */
490 char *head_ref_name;
491 struct got_repository *repo;
492 struct got_tree_entry *matched_entry;
493 struct tog_colors colors;
494 };
496 struct tog_reflist_entry {
497 TAILQ_ENTRY(tog_reflist_entry) entry;
498 struct got_reference *ref;
499 int idx;
500 };
502 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
504 struct tog_ref_view_state {
505 struct tog_reflist_head refs;
506 struct tog_reflist_entry *first_displayed_entry;
507 struct tog_reflist_entry *last_displayed_entry;
508 struct tog_reflist_entry *selected_entry;
509 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
510 struct got_repository *repo;
511 struct tog_reflist_entry *matched_entry;
512 struct tog_colors colors;
513 };
515 struct tog_help_view_state {
516 FILE *f;
517 off_t *line_offsets;
518 size_t nlines;
519 int lineno;
520 int first_displayed_line;
521 int last_displayed_line;
522 int eof;
523 int matched_line;
524 int selected_line;
525 int all;
526 enum tog_keymap_type type;
527 };
529 #define GENERATE_HELP \
530 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
531 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
532 KEY_("k C-p Up", "Move cursor or page up one line"), \
533 KEY_("j C-n Down", "Move cursor or page down one line"), \
534 KEY_("C-b b PgUp", "Scroll the view up one page"), \
535 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
536 KEY_("C-u u", "Scroll the view up one half page"), \
537 KEY_("C-d d", "Scroll the view down one half page"), \
538 KEY_("g", "Go to line N (default: first line)"), \
539 KEY_("Home =", "Go to the first line"), \
540 KEY_("G", "Go to line N (default: last line)"), \
541 KEY_("End *", "Go to the last line"), \
542 KEY_("l Right", "Scroll the view right"), \
543 KEY_("h Left", "Scroll the view left"), \
544 KEY_("$", "Scroll view to the rightmost position"), \
545 KEY_("0", "Scroll view to the leftmost position"), \
546 KEY_("-", "Decrease size of the focussed split"), \
547 KEY_("+", "Increase size of the focussed split"), \
548 KEY_("Tab", "Switch focus between views"), \
549 KEY_("F", "Toggle fullscreen mode"), \
550 KEY_("S", "Switch split-screen layout"), \
551 KEY_("/", "Open prompt to enter search term"), \
552 KEY_("n", "Find next line/token matching the current search term"), \
553 KEY_("N", "Find previous line/token matching the current search term"),\
554 KEY_("q", "Quit the focussed view; Quit help screen"), \
555 KEY_("Q", "Quit tog"), \
557 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
558 KEY_("< ,", "Move cursor up one commit"), \
559 KEY_("> .", "Move cursor down one commit"), \
560 KEY_("Enter", "Open diff view of the selected commit"), \
561 KEY_("B", "Reload the log view and toggle display of merged commits"), \
562 KEY_("R", "Open ref view of all repository references"), \
563 KEY_("T", "Display tree view of the repository from the selected" \
564 " commit"), \
565 KEY_("@", "Toggle between displaying author and committer name"), \
566 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
567 KEY_("C-g Backspace", "Cancel current search or log operation"), \
568 KEY_("C-l", "Reload the log view with new commits in the repository"), \
570 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
571 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
572 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
573 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
574 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
575 " data"), \
576 KEY_("(", "Go to the previous file in the diff"), \
577 KEY_(")", "Go to the next file in the diff"), \
578 KEY_("{", "Go to the previous hunk in the diff"), \
579 KEY_("}", "Go to the next hunk in the diff"), \
580 KEY_("[", "Decrease the number of context lines"), \
581 KEY_("]", "Increase the number of context lines"), \
582 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
584 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
585 KEY_("Enter", "Display diff view of the selected line's commit"), \
586 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
587 KEY_("L", "Open log view for the currently selected annotated line"), \
588 KEY_("C", "Reload view with the previously blamed commit"), \
589 KEY_("c", "Reload view with the version of the file found in the" \
590 " selected line's commit"), \
591 KEY_("p", "Reload view with the version of the file found in the" \
592 " selected line's parent commit"), \
594 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
595 KEY_("Enter", "Enter selected directory or open blame view of the" \
596 " selected file"), \
597 KEY_("L", "Open log view for the selected entry"), \
598 KEY_("R", "Open ref view of all repository references"), \
599 KEY_("i", "Show object IDs for all tree entries"), \
600 KEY_("Backspace", "Return to the parent directory"), \
602 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
603 KEY_("Enter", "Display log view of the selected reference"), \
604 KEY_("T", "Display tree view of the selected reference"), \
605 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
606 KEY_("m", "Toggle display of last modified date for each reference"), \
607 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
608 KEY_("C-l", "Reload view with all repository references")
610 struct tog_key_map {
611 const char *keys;
612 const char *info;
613 enum tog_keymap_type type;
614 };
616 /* curses io for tog regress */
617 struct tog_io {
618 FILE *cin;
619 FILE *cout;
620 FILE *f;
621 int wait_for_ui;
622 } tog_io;
623 static int using_mock_io;
625 #define TOG_KEY_SCRDUMP SHRT_MIN
627 /*
628 * We implement two types of views: parent views and child views.
630 * The 'Tab' key switches focus between a parent view and its child view.
631 * Child views are shown side-by-side to their parent view, provided
632 * there is enough screen estate.
634 * When a new view is opened from within a parent view, this new view
635 * becomes a child view of the parent view, replacing any existing child.
637 * When a new view is opened from within a child view, this new view
638 * becomes a parent view which will obscure the views below until the
639 * user quits the new parent view by typing 'q'.
641 * This list of views contains parent views only.
642 * Child views are only pointed to by their parent view.
643 */
644 TAILQ_HEAD(tog_view_list_head, tog_view);
646 struct tog_view {
647 TAILQ_ENTRY(tog_view) entry;
648 WINDOW *window;
649 PANEL *panel;
650 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
651 int resized_y, resized_x; /* begin_y/x based on user resizing */
652 int maxx, x; /* max column and current start column */
653 int lines, cols; /* copies of LINES and COLS */
654 int nscrolled, offset; /* lines scrolled and hsplit line offset */
655 int gline, hiline; /* navigate to and highlight this nG line */
656 int ch, count; /* current keymap and count prefix */
657 int resized; /* set when in a resize event */
658 int focussed; /* Only set on one parent or child view at a time. */
659 int dying;
660 struct tog_view *parent;
661 struct tog_view *child;
663 /*
664 * This flag is initially set on parent views when a new child view
665 * is created. It gets toggled when the 'Tab' key switches focus
666 * between parent and child.
667 * The flag indicates whether focus should be passed on to our child
668 * view if this parent view gets picked for focus after another parent
669 * view was closed. This prevents child views from losing focus in such
670 * situations.
671 */
672 int focus_child;
674 enum tog_view_mode mode;
675 /* type-specific state */
676 enum tog_view_type type;
677 union {
678 struct tog_diff_view_state diff;
679 struct tog_log_view_state log;
680 struct tog_blame_view_state blame;
681 struct tog_tree_view_state tree;
682 struct tog_ref_view_state ref;
683 struct tog_help_view_state help;
684 } state;
686 const struct got_error *(*show)(struct tog_view *);
687 const struct got_error *(*input)(struct tog_view **,
688 struct tog_view *, int);
689 const struct got_error *(*reset)(struct tog_view *);
690 const struct got_error *(*resize)(struct tog_view *, int);
691 const struct got_error *(*close)(struct tog_view *);
693 const struct got_error *(*search_start)(struct tog_view *);
694 const struct got_error *(*search_next)(struct tog_view *);
695 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
696 int **, int **, int **, int **);
697 int search_started;
698 int searching;
699 #define TOG_SEARCH_FORWARD 1
700 #define TOG_SEARCH_BACKWARD 2
701 int search_next_done;
702 #define TOG_SEARCH_HAVE_MORE 1
703 #define TOG_SEARCH_NO_MORE 2
704 #define TOG_SEARCH_HAVE_NONE 3
705 regex_t regex;
706 regmatch_t regmatch;
707 const char *action;
708 };
710 static const struct got_error *open_diff_view(struct tog_view *,
711 struct got_object_id *, struct got_object_id *,
712 const char *, const char *, int, int, int, struct tog_view *,
713 struct got_repository *);
714 static const struct got_error *show_diff_view(struct tog_view *);
715 static const struct got_error *input_diff_view(struct tog_view **,
716 struct tog_view *, int);
717 static const struct got_error *reset_diff_view(struct tog_view *);
718 static const struct got_error* close_diff_view(struct tog_view *);
719 static const struct got_error *search_start_diff_view(struct tog_view *);
720 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
721 size_t *, int **, int **, int **, int **);
722 static const struct got_error *search_next_view_match(struct tog_view *);
724 static const struct got_error *open_log_view(struct tog_view *,
725 struct got_object_id *, struct got_repository *,
726 const char *, const char *, int);
727 static const struct got_error * show_log_view(struct tog_view *);
728 static const struct got_error *input_log_view(struct tog_view **,
729 struct tog_view *, int);
730 static const struct got_error *resize_log_view(struct tog_view *, int);
731 static const struct got_error *close_log_view(struct tog_view *);
732 static const struct got_error *search_start_log_view(struct tog_view *);
733 static const struct got_error *search_next_log_view(struct tog_view *);
735 static const struct got_error *open_blame_view(struct tog_view *, char *,
736 struct got_object_id *, struct got_repository *);
737 static const struct got_error *show_blame_view(struct tog_view *);
738 static const struct got_error *input_blame_view(struct tog_view **,
739 struct tog_view *, int);
740 static const struct got_error *reset_blame_view(struct tog_view *);
741 static const struct got_error *close_blame_view(struct tog_view *);
742 static const struct got_error *search_start_blame_view(struct tog_view *);
743 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
744 size_t *, int **, int **, int **, int **);
746 static const struct got_error *open_tree_view(struct tog_view *,
747 struct got_object_id *, const char *, struct got_repository *);
748 static const struct got_error *show_tree_view(struct tog_view *);
749 static const struct got_error *input_tree_view(struct tog_view **,
750 struct tog_view *, int);
751 static const struct got_error *close_tree_view(struct tog_view *);
752 static const struct got_error *search_start_tree_view(struct tog_view *);
753 static const struct got_error *search_next_tree_view(struct tog_view *);
755 static const struct got_error *open_ref_view(struct tog_view *,
756 struct got_repository *);
757 static const struct got_error *show_ref_view(struct tog_view *);
758 static const struct got_error *input_ref_view(struct tog_view **,
759 struct tog_view *, int);
760 static const struct got_error *close_ref_view(struct tog_view *);
761 static const struct got_error *search_start_ref_view(struct tog_view *);
762 static const struct got_error *search_next_ref_view(struct tog_view *);
764 static const struct got_error *open_help_view(struct tog_view *,
765 struct tog_view *);
766 static const struct got_error *show_help_view(struct tog_view *);
767 static const struct got_error *input_help_view(struct tog_view **,
768 struct tog_view *, int);
769 static const struct got_error *reset_help_view(struct tog_view *);
770 static const struct got_error* close_help_view(struct tog_view *);
771 static const struct got_error *search_start_help_view(struct tog_view *);
772 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
773 size_t *, int **, int **, int **, int **);
775 static volatile sig_atomic_t tog_sigwinch_received;
776 static volatile sig_atomic_t tog_sigpipe_received;
777 static volatile sig_atomic_t tog_sigcont_received;
778 static volatile sig_atomic_t tog_sigint_received;
779 static volatile sig_atomic_t tog_sigterm_received;
781 static void
782 tog_sigwinch(int signo)
784 tog_sigwinch_received = 1;
787 static void
788 tog_sigpipe(int signo)
790 tog_sigpipe_received = 1;
793 static void
794 tog_sigcont(int signo)
796 tog_sigcont_received = 1;
799 static void
800 tog_sigint(int signo)
802 tog_sigint_received = 1;
805 static void
806 tog_sigterm(int signo)
808 tog_sigterm_received = 1;
811 static int
812 tog_fatal_signal_received(void)
814 return (tog_sigpipe_received ||
815 tog_sigint_received || tog_sigterm_received);
818 static const struct got_error *
819 view_close(struct tog_view *view)
821 const struct got_error *err = NULL, *child_err = NULL;
823 if (view->child) {
824 child_err = view_close(view->child);
825 view->child = NULL;
827 if (view->close)
828 err = view->close(view);
829 if (view->panel)
830 del_panel(view->panel);
831 if (view->window)
832 delwin(view->window);
833 free(view);
834 return err ? err : child_err;
837 static struct tog_view *
838 view_open(int nlines, int ncols, int begin_y, int begin_x,
839 enum tog_view_type type)
841 struct tog_view *view = calloc(1, sizeof(*view));
843 if (view == NULL)
844 return NULL;
846 view->type = type;
847 view->lines = LINES;
848 view->cols = COLS;
849 view->nlines = nlines ? nlines : LINES - begin_y;
850 view->ncols = ncols ? ncols : COLS - begin_x;
851 view->begin_y = begin_y;
852 view->begin_x = begin_x;
853 view->window = newwin(nlines, ncols, begin_y, begin_x);
854 if (view->window == NULL) {
855 view_close(view);
856 return NULL;
858 view->panel = new_panel(view->window);
859 if (view->panel == NULL ||
860 set_panel_userptr(view->panel, view) != OK) {
861 view_close(view);
862 return NULL;
865 keypad(view->window, TRUE);
866 return view;
869 static int
870 view_split_begin_x(int begin_x)
872 if (begin_x > 0 || COLS < 120)
873 return 0;
874 return (COLS - MAX(COLS / 2, 80));
877 /* XXX Stub till we decide what to do. */
878 static int
879 view_split_begin_y(int lines)
881 return lines * HSPLIT_SCALE;
884 static const struct got_error *view_resize(struct tog_view *);
886 static const struct got_error *
887 view_splitscreen(struct tog_view *view)
889 const struct got_error *err = NULL;
891 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
892 if (view->resized_y && view->resized_y < view->lines)
893 view->begin_y = view->resized_y;
894 else
895 view->begin_y = view_split_begin_y(view->nlines);
896 view->begin_x = 0;
897 } else if (!view->resized) {
898 if (view->resized_x && view->resized_x < view->cols - 1 &&
899 view->cols > 119)
900 view->begin_x = view->resized_x;
901 else
902 view->begin_x = view_split_begin_x(0);
903 view->begin_y = 0;
905 view->nlines = LINES - view->begin_y;
906 view->ncols = COLS - view->begin_x;
907 view->lines = LINES;
908 view->cols = COLS;
909 err = view_resize(view);
910 if (err)
911 return err;
913 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
914 view->parent->nlines = view->begin_y;
916 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
917 return got_error_from_errno("mvwin");
919 return NULL;
922 static const struct got_error *
923 view_fullscreen(struct tog_view *view)
925 const struct got_error *err = NULL;
927 view->begin_x = 0;
928 view->begin_y = view->resized ? view->begin_y : 0;
929 view->nlines = view->resized ? view->nlines : LINES;
930 view->ncols = COLS;
931 view->lines = LINES;
932 view->cols = COLS;
933 err = view_resize(view);
934 if (err)
935 return err;
937 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
938 return got_error_from_errno("mvwin");
940 return NULL;
943 static int
944 view_is_parent_view(struct tog_view *view)
946 return view->parent == NULL;
949 static int
950 view_is_splitscreen(struct tog_view *view)
952 return view->begin_x > 0 || view->begin_y > 0;
955 static int
956 view_is_fullscreen(struct tog_view *view)
958 return view->nlines == LINES && view->ncols == COLS;
961 static int
962 view_is_hsplit_top(struct tog_view *view)
964 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
965 view_is_splitscreen(view->child);
968 static void
969 view_border(struct tog_view *view)
971 PANEL *panel;
972 const struct tog_view *view_above;
974 if (view->parent)
975 return view_border(view->parent);
977 panel = panel_above(view->panel);
978 if (panel == NULL)
979 return;
981 view_above = panel_userptr(panel);
982 if (view->mode == TOG_VIEW_SPLIT_HRZN)
983 mvwhline(view->window, view_above->begin_y - 1,
984 view->begin_x, got_locale_is_utf8() ?
985 ACS_HLINE : '-', view->ncols);
986 else
987 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
988 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
991 static const struct got_error *view_init_hsplit(struct tog_view *, int);
992 static const struct got_error *request_log_commits(struct tog_view *);
993 static const struct got_error *offset_selection_down(struct tog_view *);
994 static void offset_selection_up(struct tog_view *);
995 static void view_get_split(struct tog_view *, int *, int *);
997 static const struct got_error *
998 view_resize(struct tog_view *view)
1000 const struct got_error *err = NULL;
1001 int dif, nlines, ncols;
1003 dif = LINES - view->lines; /* line difference */
1005 if (view->lines > LINES)
1006 nlines = view->nlines - (view->lines - LINES);
1007 else
1008 nlines = view->nlines + (LINES - view->lines);
1009 if (view->cols > COLS)
1010 ncols = view->ncols - (view->cols - COLS);
1011 else
1012 ncols = view->ncols + (COLS - view->cols);
1014 if (view->child) {
1015 int hs = view->child->begin_y;
1017 if (!view_is_fullscreen(view))
1018 view->child->begin_x = view_split_begin_x(view->begin_x);
1019 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1020 view->child->begin_x == 0) {
1021 ncols = COLS;
1023 view_fullscreen(view->child);
1024 if (view->child->focussed)
1025 show_panel(view->child->panel);
1026 else
1027 show_panel(view->panel);
1028 } else {
1029 ncols = view->child->begin_x;
1031 view_splitscreen(view->child);
1032 show_panel(view->child->panel);
1035 * XXX This is ugly and needs to be moved into the above
1036 * logic but "works" for now and my attempts at moving it
1037 * break either 'tab' or 'F' key maps in horizontal splits.
1039 if (hs) {
1040 err = view_splitscreen(view->child);
1041 if (err)
1042 return err;
1043 if (dif < 0) { /* top split decreased */
1044 err = offset_selection_down(view);
1045 if (err)
1046 return err;
1048 view_border(view);
1049 update_panels();
1050 doupdate();
1051 show_panel(view->child->panel);
1052 nlines = view->nlines;
1054 } else if (view->parent == NULL)
1055 ncols = COLS;
1057 if (view->resize && dif > 0) {
1058 err = view->resize(view, dif);
1059 if (err)
1060 return err;
1063 if (wresize(view->window, nlines, ncols) == ERR)
1064 return got_error_from_errno("wresize");
1065 if (replace_panel(view->panel, view->window) == ERR)
1066 return got_error_from_errno("replace_panel");
1067 wclear(view->window);
1069 view->nlines = nlines;
1070 view->ncols = ncols;
1071 view->lines = LINES;
1072 view->cols = COLS;
1074 return NULL;
1077 static const struct got_error *
1078 resize_log_view(struct tog_view *view, int increase)
1080 struct tog_log_view_state *s = &view->state.log;
1081 const struct got_error *err = NULL;
1082 int n = 0;
1084 if (s->selected_entry)
1085 n = s->selected_entry->idx + view->lines - s->selected;
1088 * Request commits to account for the increased
1089 * height so we have enough to populate the view.
1091 if (s->commits->ncommits < n) {
1092 view->nscrolled = n - s->commits->ncommits + increase + 1;
1093 err = request_log_commits(view);
1096 return err;
1099 static void
1100 view_adjust_offset(struct tog_view *view, int n)
1102 if (n == 0)
1103 return;
1105 if (view->parent && view->parent->offset) {
1106 if (view->parent->offset + n >= 0)
1107 view->parent->offset += n;
1108 else
1109 view->parent->offset = 0;
1110 } else if (view->offset) {
1111 if (view->offset - n >= 0)
1112 view->offset -= n;
1113 else
1114 view->offset = 0;
1118 static const struct got_error *
1119 view_resize_split(struct tog_view *view, int resize)
1121 const struct got_error *err = NULL;
1122 struct tog_view *v = NULL;
1124 if (view->parent)
1125 v = view->parent;
1126 else
1127 v = view;
1129 if (!v->child || !view_is_splitscreen(v->child))
1130 return NULL;
1132 v->resized = v->child->resized = resize; /* lock for resize event */
1134 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1135 if (v->child->resized_y)
1136 v->child->begin_y = v->child->resized_y;
1137 if (view->parent)
1138 v->child->begin_y -= resize;
1139 else
1140 v->child->begin_y += resize;
1141 if (v->child->begin_y < 3) {
1142 view->count = 0;
1143 v->child->begin_y = 3;
1144 } else if (v->child->begin_y > LINES - 1) {
1145 view->count = 0;
1146 v->child->begin_y = LINES - 1;
1148 v->ncols = COLS;
1149 v->child->ncols = COLS;
1150 view_adjust_offset(view, resize);
1151 err = view_init_hsplit(v, v->child->begin_y);
1152 if (err)
1153 return err;
1154 v->child->resized_y = v->child->begin_y;
1155 } else {
1156 if (v->child->resized_x)
1157 v->child->begin_x = v->child->resized_x;
1158 if (view->parent)
1159 v->child->begin_x -= resize;
1160 else
1161 v->child->begin_x += resize;
1162 if (v->child->begin_x < 11) {
1163 view->count = 0;
1164 v->child->begin_x = 11;
1165 } else if (v->child->begin_x > COLS - 1) {
1166 view->count = 0;
1167 v->child->begin_x = COLS - 1;
1169 v->child->resized_x = v->child->begin_x;
1172 v->child->mode = v->mode;
1173 v->child->nlines = v->lines - v->child->begin_y;
1174 v->child->ncols = v->cols - v->child->begin_x;
1175 v->focus_child = 1;
1177 err = view_fullscreen(v);
1178 if (err)
1179 return err;
1180 err = view_splitscreen(v->child);
1181 if (err)
1182 return err;
1184 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1185 err = offset_selection_down(v->child);
1186 if (err)
1187 return err;
1190 if (v->resize)
1191 err = v->resize(v, 0);
1192 else if (v->child->resize)
1193 err = v->child->resize(v->child, 0);
1195 v->resized = v->child->resized = 0;
1197 return err;
1200 static void
1201 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1203 struct tog_view *v = src->child ? src->child : src;
1205 dst->resized_x = v->resized_x;
1206 dst->resized_y = v->resized_y;
1209 static const struct got_error *
1210 view_close_child(struct tog_view *view)
1212 const struct got_error *err = NULL;
1214 if (view->child == NULL)
1215 return NULL;
1217 err = view_close(view->child);
1218 view->child = NULL;
1219 return err;
1222 static const struct got_error *
1223 view_set_child(struct tog_view *view, struct tog_view *child)
1225 const struct got_error *err = NULL;
1227 view->child = child;
1228 child->parent = view;
1230 err = view_resize(view);
1231 if (err)
1232 return err;
1234 if (view->child->resized_x || view->child->resized_y)
1235 err = view_resize_split(view, 0);
1237 return err;
1240 static const struct got_error *view_dispatch_request(struct tog_view **,
1241 struct tog_view *, enum tog_view_type, int, int);
1243 static const struct got_error *
1244 view_request_new(struct tog_view **requested, struct tog_view *view,
1245 enum tog_view_type request)
1247 struct tog_view *new_view = NULL;
1248 const struct got_error *err;
1249 int y = 0, x = 0;
1251 *requested = NULL;
1253 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1254 view_get_split(view, &y, &x);
1256 err = view_dispatch_request(&new_view, view, request, y, x);
1257 if (err)
1258 return err;
1260 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1261 request != TOG_VIEW_HELP) {
1262 err = view_init_hsplit(view, y);
1263 if (err)
1264 return err;
1267 view->focussed = 0;
1268 new_view->focussed = 1;
1269 new_view->mode = view->mode;
1270 new_view->nlines = request == TOG_VIEW_HELP ?
1271 view->lines : view->lines - y;
1273 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1274 view_transfer_size(new_view, view);
1275 err = view_close_child(view);
1276 if (err)
1277 return err;
1278 err = view_set_child(view, new_view);
1279 if (err)
1280 return err;
1281 view->focus_child = 1;
1282 } else
1283 *requested = new_view;
1285 return NULL;
1288 static void
1289 tog_resizeterm(void)
1291 int cols, lines;
1292 struct winsize size;
1294 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1295 cols = 80; /* Default */
1296 lines = 24;
1297 } else {
1298 cols = size.ws_col;
1299 lines = size.ws_row;
1301 resize_term(lines, cols);
1304 static const struct got_error *
1305 view_search_start(struct tog_view *view, int fast_refresh)
1307 const struct got_error *err = NULL;
1308 struct tog_view *v = view;
1309 char pattern[1024];
1310 int ret;
1312 if (view->search_started) {
1313 regfree(&view->regex);
1314 view->searching = 0;
1315 memset(&view->regmatch, 0, sizeof(view->regmatch));
1317 view->search_started = 0;
1319 if (view->nlines < 1)
1320 return NULL;
1322 if (view_is_hsplit_top(view))
1323 v = view->child;
1324 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1325 v = view->parent;
1327 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1328 wclrtoeol(v->window);
1330 nodelay(v->window, FALSE); /* block for search term input */
1331 nocbreak();
1332 echo();
1333 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1334 wrefresh(v->window);
1335 cbreak();
1336 noecho();
1337 nodelay(v->window, TRUE);
1338 if (!fast_refresh && !using_mock_io)
1339 halfdelay(10);
1340 if (ret == ERR)
1341 return NULL;
1343 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1344 err = view->search_start(view);
1345 if (err) {
1346 regfree(&view->regex);
1347 return err;
1349 view->search_started = 1;
1350 view->searching = TOG_SEARCH_FORWARD;
1351 view->search_next_done = 0;
1352 view->search_next(view);
1355 return NULL;
1358 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1359 static const struct got_error *
1360 switch_split(struct tog_view *view)
1362 const struct got_error *err = NULL;
1363 struct tog_view *v = NULL;
1365 if (view->parent)
1366 v = view->parent;
1367 else
1368 v = view;
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1371 v->mode = TOG_VIEW_SPLIT_VERT;
1372 else
1373 v->mode = TOG_VIEW_SPLIT_HRZN;
1375 if (!v->child)
1376 return NULL;
1377 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1378 v->mode = TOG_VIEW_SPLIT_NONE;
1380 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1381 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1382 v->child->begin_y = v->child->resized_y;
1383 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1384 v->child->begin_x = v->child->resized_x;
1387 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1388 v->ncols = COLS;
1389 v->child->ncols = COLS;
1390 v->child->nscrolled = LINES - v->child->nlines;
1392 err = view_init_hsplit(v, v->child->begin_y);
1393 if (err)
1394 return err;
1396 v->child->mode = v->mode;
1397 v->child->nlines = v->lines - v->child->begin_y;
1398 v->focus_child = 1;
1400 err = view_fullscreen(v);
1401 if (err)
1402 return err;
1403 err = view_splitscreen(v->child);
1404 if (err)
1405 return err;
1407 if (v->mode == TOG_VIEW_SPLIT_NONE)
1408 v->mode = TOG_VIEW_SPLIT_VERT;
1409 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1410 err = offset_selection_down(v);
1411 if (err)
1412 return err;
1413 err = offset_selection_down(v->child);
1414 if (err)
1415 return err;
1416 } else {
1417 offset_selection_up(v);
1418 offset_selection_up(v->child);
1420 if (v->resize)
1421 err = v->resize(v, 0);
1422 else if (v->child->resize)
1423 err = v->child->resize(v->child, 0);
1425 return err;
1429 * Strip trailing whitespace from str starting at byte *n;
1430 * if *n < 0, use strlen(str). Return new str length in *n.
1432 static void
1433 strip_trailing_ws(char *str, int *n)
1435 size_t x = *n;
1437 if (str == NULL || *str == '\0')
1438 return;
1440 if (x < 0)
1441 x = strlen(str);
1443 while (x-- > 0 && isspace((unsigned char)str[x]))
1444 str[x] = '\0';
1446 *n = x + 1;
1450 * Extract visible substring of line y from the curses screen
1451 * and strip trailing whitespace. If vline is set, overwrite
1452 * line[vline] with '|' because the ACS_VLINE character is
1453 * written out as 'x'. Write the line to file f.
1455 static const struct got_error *
1456 view_write_line(FILE *f, int y, int vline)
1458 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1459 int r, w;
1461 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1462 if (r == ERR)
1463 return got_error_fmt(GOT_ERR_RANGE,
1464 "failed to extract line %d", y);
1467 * In some views, lines are padded with blanks to COLS width.
1468 * Strip them so we can diff without the -b flag when testing.
1470 strip_trailing_ws(line, &r);
1472 if (vline > 0)
1473 line[vline] = '|';
1475 w = fprintf(f, "%s\n", line);
1476 if (w != r + 1) /* \n */
1477 return got_ferror(f, GOT_ERR_IO);
1479 return NULL;
1483 * Capture the visible curses screen by writing each line to the
1484 * file at the path set via the TOG_SCR_DUMP environment variable.
1486 static const struct got_error *
1487 screendump(struct tog_view *view)
1489 const struct got_error *err;
1490 FILE *f = NULL;
1491 const char *path;
1492 int i;
1494 path = getenv("TOG_SCR_DUMP");
1495 if (path == NULL || *path == '\0')
1496 return got_error_msg(GOT_ERR_BAD_PATH,
1497 "TOG_SCR_DUMP path not set to capture screen dump");
1498 f = fopen(path, "wex");
1499 if (f == NULL)
1500 return got_error_from_errno_fmt("fopen: %s", path);
1502 if ((view->child && view->child->begin_x) ||
1503 (view->parent && view->begin_x)) {
1504 int ncols = view->child ? view->ncols : view->parent->ncols;
1506 /* vertical splitscreen */
1507 for (i = 0; i < view->nlines; ++i) {
1508 err = view_write_line(f, i, ncols - 1);
1509 if (err)
1510 goto done;
1512 } else {
1513 int hline = 0;
1515 /* fullscreen or horizontal splitscreen */
1516 if ((view->child && view->child->begin_y) ||
1517 (view->parent && view->begin_y)) /* hsplit */
1518 hline = view->child ?
1519 view->child->begin_y : view->begin_y;
1521 for (i = 0; i < view->lines; i++) {
1522 if (hline && i == hline - 1) {
1523 int c;
1525 /* ACS_HLINE writes out as 'q', overwrite it */
1526 for (c = 0; c < view->cols; ++c)
1527 fputc('-', f);
1528 fputc('\n', f);
1529 continue;
1532 err = view_write_line(f, i, 0);
1533 if (err)
1534 goto done;
1538 done:
1539 if (f && fclose(f) == EOF && err == NULL)
1540 err = got_ferror(f, GOT_ERR_IO);
1541 return err;
1545 * Compute view->count from numeric input. Assign total to view->count and
1546 * return first non-numeric key entered.
1548 static int
1549 get_compound_key(struct tog_view *view, int c)
1551 struct tog_view *v = view;
1552 int x, n = 0;
1554 if (view_is_hsplit_top(view))
1555 v = view->child;
1556 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1557 v = view->parent;
1559 view->count = 0;
1560 cbreak(); /* block for input */
1561 nodelay(view->window, FALSE);
1562 wmove(v->window, v->nlines - 1, 0);
1563 wclrtoeol(v->window);
1564 waddch(v->window, ':');
1566 do {
1567 x = getcurx(v->window);
1568 if (x != ERR && x < view->ncols) {
1569 waddch(v->window, c);
1570 wrefresh(v->window);
1574 * Don't overflow. Max valid request should be the greatest
1575 * between the longest and total lines; cap at 10 million.
1577 if (n >= 9999999)
1578 n = 9999999;
1579 else
1580 n = n * 10 + (c - '0');
1581 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1583 if (c == 'G' || c == 'g') { /* nG key map */
1584 view->gline = view->hiline = n;
1585 n = 0;
1586 c = 0;
1589 /* Massage excessive or inapplicable values at the input handler. */
1590 view->count = n;
1592 return c;
1595 static void
1596 action_report(struct tog_view *view)
1598 struct tog_view *v = view;
1600 if (view_is_hsplit_top(view))
1601 v = view->child;
1602 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1603 v = view->parent;
1605 wmove(v->window, v->nlines - 1, 0);
1606 wclrtoeol(v->window);
1607 wprintw(v->window, ":%s", view->action);
1608 wrefresh(v->window);
1611 * Clear action status report. Only clear in blame view
1612 * once annotating is complete, otherwise it's too fast.
1614 if (view->type == TOG_VIEW_BLAME) {
1615 if (view->state.blame.blame_complete)
1616 view->action = NULL;
1617 } else
1618 view->action = NULL;
1622 * Read the next line from the test script and assign
1623 * key instruction to *ch. If at EOF, set the *done flag.
1625 static const struct got_error *
1626 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1628 const struct got_error *err = NULL;
1629 char *line = NULL;
1630 size_t linesz = 0;
1632 if (view->count && --view->count) {
1633 *ch = view->ch;
1634 return NULL;
1635 } else
1636 *ch = -1;
1638 if (getline(&line, &linesz, script) == -1) {
1639 if (feof(script)) {
1640 *done = 1;
1641 goto done;
1642 } else {
1643 err = got_ferror(script, GOT_ERR_IO);
1644 goto done;
1648 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1649 tog_io.wait_for_ui = 1;
1650 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1651 *ch = KEY_ENTER;
1652 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1653 *ch = KEY_RIGHT;
1654 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1655 *ch = KEY_LEFT;
1656 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1657 *ch = KEY_DOWN;
1658 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1659 *ch = KEY_UP;
1660 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1661 *ch = TOG_KEY_SCRDUMP;
1662 else if (isdigit((unsigned char)*line)) {
1663 char *t = line;
1665 while (isdigit((unsigned char)*t))
1666 ++t;
1667 view->ch = *ch = *t;
1668 *t = '\0';
1669 /* ignore error, view->count is 0 if instruction is invalid */
1670 view->count = strtonum(line, 0, INT_MAX, NULL);
1671 } else
1672 *ch = *line;
1674 done:
1675 free(line);
1676 return err;
1679 static const struct got_error *
1680 view_input(struct tog_view **new, int *done, struct tog_view *view,
1681 struct tog_view_list_head *views, int fast_refresh)
1683 const struct got_error *err = NULL;
1684 struct tog_view *v;
1685 int ch, errcode;
1687 *new = NULL;
1689 if (view->action)
1690 action_report(view);
1692 /* Clear "no matches" indicator. */
1693 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1694 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1695 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1696 view->count = 0;
1699 if (view->searching && !view->search_next_done) {
1700 errcode = pthread_mutex_unlock(&tog_mutex);
1701 if (errcode)
1702 return got_error_set_errno(errcode,
1703 "pthread_mutex_unlock");
1704 sched_yield();
1705 errcode = pthread_mutex_lock(&tog_mutex);
1706 if (errcode)
1707 return got_error_set_errno(errcode,
1708 "pthread_mutex_lock");
1709 view->search_next(view);
1710 return NULL;
1713 /* Allow threads to make progress while we are waiting for input. */
1714 errcode = pthread_mutex_unlock(&tog_mutex);
1715 if (errcode)
1716 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1718 if (using_mock_io) {
1719 err = tog_read_script_key(tog_io.f, view, &ch, done);
1720 if (err) {
1721 errcode = pthread_mutex_lock(&tog_mutex);
1722 return err;
1724 } else if (view->count && --view->count) {
1725 cbreak();
1726 nodelay(view->window, TRUE);
1727 ch = wgetch(view->window);
1728 /* let C-g or backspace abort unfinished count */
1729 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1730 view->count = 0;
1731 else
1732 ch = view->ch;
1733 } else {
1734 ch = wgetch(view->window);
1735 if (ch >= '1' && ch <= '9')
1736 view->ch = ch = get_compound_key(view, ch);
1738 if (view->hiline && ch != ERR && ch != 0)
1739 view->hiline = 0; /* key pressed, clear line highlight */
1740 nodelay(view->window, TRUE);
1741 errcode = pthread_mutex_lock(&tog_mutex);
1742 if (errcode)
1743 return got_error_set_errno(errcode, "pthread_mutex_lock");
1745 if (tog_sigwinch_received || tog_sigcont_received) {
1746 tog_resizeterm();
1747 tog_sigwinch_received = 0;
1748 tog_sigcont_received = 0;
1749 TAILQ_FOREACH(v, views, entry) {
1750 err = view_resize(v);
1751 if (err)
1752 return err;
1753 err = v->input(new, v, KEY_RESIZE);
1754 if (err)
1755 return err;
1756 if (v->child) {
1757 err = view_resize(v->child);
1758 if (err)
1759 return err;
1760 err = v->child->input(new, v->child,
1761 KEY_RESIZE);
1762 if (err)
1763 return err;
1764 if (v->child->resized_x || v->child->resized_y) {
1765 err = view_resize_split(v, 0);
1766 if (err)
1767 return err;
1773 switch (ch) {
1774 case '?':
1775 case 'H':
1776 case KEY_F(1):
1777 if (view->type == TOG_VIEW_HELP)
1778 err = view->reset(view);
1779 else
1780 err = view_request_new(new, view, TOG_VIEW_HELP);
1781 break;
1782 case '\t':
1783 view->count = 0;
1784 if (view->child) {
1785 view->focussed = 0;
1786 view->child->focussed = 1;
1787 view->focus_child = 1;
1788 } else if (view->parent) {
1789 view->focussed = 0;
1790 view->parent->focussed = 1;
1791 view->parent->focus_child = 0;
1792 if (!view_is_splitscreen(view)) {
1793 if (view->parent->resize) {
1794 err = view->parent->resize(view->parent,
1795 0);
1796 if (err)
1797 return err;
1799 offset_selection_up(view->parent);
1800 err = view_fullscreen(view->parent);
1801 if (err)
1802 return err;
1805 break;
1806 case 'q':
1807 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1808 if (view->parent->resize) {
1809 /* might need more commits to fill fullscreen */
1810 err = view->parent->resize(view->parent, 0);
1811 if (err)
1812 break;
1814 offset_selection_up(view->parent);
1816 err = view->input(new, view, ch);
1817 view->dying = 1;
1818 break;
1819 case 'Q':
1820 *done = 1;
1821 break;
1822 case 'F':
1823 view->count = 0;
1824 if (view_is_parent_view(view)) {
1825 if (view->child == NULL)
1826 break;
1827 if (view_is_splitscreen(view->child)) {
1828 view->focussed = 0;
1829 view->child->focussed = 1;
1830 err = view_fullscreen(view->child);
1831 } else {
1832 err = view_splitscreen(view->child);
1833 if (!err)
1834 err = view_resize_split(view, 0);
1836 if (err)
1837 break;
1838 err = view->child->input(new, view->child,
1839 KEY_RESIZE);
1840 } else {
1841 if (view_is_splitscreen(view)) {
1842 view->parent->focussed = 0;
1843 view->focussed = 1;
1844 err = view_fullscreen(view);
1845 } else {
1846 err = view_splitscreen(view);
1847 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1848 err = view_resize(view->parent);
1849 if (!err)
1850 err = view_resize_split(view, 0);
1852 if (err)
1853 break;
1854 err = view->input(new, view, KEY_RESIZE);
1856 if (err)
1857 break;
1858 if (view->resize) {
1859 err = view->resize(view, 0);
1860 if (err)
1861 break;
1863 if (view->parent)
1864 err = offset_selection_down(view->parent);
1865 if (!err)
1866 err = offset_selection_down(view);
1867 break;
1868 case 'S':
1869 view->count = 0;
1870 err = switch_split(view);
1871 break;
1872 case '-':
1873 err = view_resize_split(view, -1);
1874 break;
1875 case '+':
1876 err = view_resize_split(view, 1);
1877 break;
1878 case KEY_RESIZE:
1879 break;
1880 case '/':
1881 view->count = 0;
1882 if (view->search_start)
1883 view_search_start(view, fast_refresh);
1884 else
1885 err = view->input(new, view, ch);
1886 break;
1887 case 'N':
1888 case 'n':
1889 if (view->search_started && view->search_next) {
1890 view->searching = (ch == 'n' ?
1891 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1892 view->search_next_done = 0;
1893 view->search_next(view);
1894 } else
1895 err = view->input(new, view, ch);
1896 break;
1897 case 'A':
1898 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1899 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1900 view->action = "Patience diff algorithm";
1901 } else {
1902 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1903 view->action = "Myers diff algorithm";
1905 TAILQ_FOREACH(v, views, entry) {
1906 if (v->reset) {
1907 err = v->reset(v);
1908 if (err)
1909 return err;
1911 if (v->child && v->child->reset) {
1912 err = v->child->reset(v->child);
1913 if (err)
1914 return err;
1917 break;
1918 case TOG_KEY_SCRDUMP:
1919 err = screendump(view);
1920 break;
1921 default:
1922 err = view->input(new, view, ch);
1923 break;
1926 return err;
1929 static int
1930 view_needs_focus_indication(struct tog_view *view)
1932 if (view_is_parent_view(view)) {
1933 if (view->child == NULL || view->child->focussed)
1934 return 0;
1935 if (!view_is_splitscreen(view->child))
1936 return 0;
1937 } else if (!view_is_splitscreen(view))
1938 return 0;
1940 return view->focussed;
1943 static const struct got_error *
1944 tog_io_close(void)
1946 const struct got_error *err = NULL;
1948 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1949 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1950 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1951 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1952 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1953 err = got_ferror(tog_io.f, GOT_ERR_IO);
1955 return err;
1958 static const struct got_error *
1959 view_loop(struct tog_view *view)
1961 const struct got_error *err = NULL;
1962 struct tog_view_list_head views;
1963 struct tog_view *new_view;
1964 char *mode;
1965 int fast_refresh = 10;
1966 int done = 0, errcode;
1968 mode = getenv("TOG_VIEW_SPLIT_MODE");
1969 if (!mode || !(*mode == 'h' || *mode == 'H'))
1970 view->mode = TOG_VIEW_SPLIT_VERT;
1971 else
1972 view->mode = TOG_VIEW_SPLIT_HRZN;
1974 errcode = pthread_mutex_lock(&tog_mutex);
1975 if (errcode)
1976 return got_error_set_errno(errcode, "pthread_mutex_lock");
1978 TAILQ_INIT(&views);
1979 TAILQ_INSERT_HEAD(&views, view, entry);
1981 view->focussed = 1;
1982 err = view->show(view);
1983 if (err)
1984 return err;
1985 update_panels();
1986 doupdate();
1987 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1988 !tog_fatal_signal_received()) {
1989 /* Refresh fast during initialization, then become slower. */
1990 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1991 halfdelay(10); /* switch to once per second */
1993 err = view_input(&new_view, &done, view, &views, fast_refresh);
1994 if (err)
1995 break;
1997 if (view->dying && view == TAILQ_FIRST(&views) &&
1998 TAILQ_NEXT(view, entry) == NULL)
1999 done = 1;
2000 if (done) {
2001 struct tog_view *v;
2004 * When we quit, scroll the screen up a single line
2005 * so we don't lose any information.
2007 TAILQ_FOREACH(v, &views, entry) {
2008 wmove(v->window, 0, 0);
2009 wdeleteln(v->window);
2010 wnoutrefresh(v->window);
2011 if (v->child && !view_is_fullscreen(v)) {
2012 wmove(v->child->window, 0, 0);
2013 wdeleteln(v->child->window);
2014 wnoutrefresh(v->child->window);
2017 doupdate();
2020 if (view->dying) {
2021 struct tog_view *v, *prev = NULL;
2023 if (view_is_parent_view(view))
2024 prev = TAILQ_PREV(view, tog_view_list_head,
2025 entry);
2026 else if (view->parent)
2027 prev = view->parent;
2029 if (view->parent) {
2030 view->parent->child = NULL;
2031 view->parent->focus_child = 0;
2032 /* Restore fullscreen line height. */
2033 view->parent->nlines = view->parent->lines;
2034 err = view_resize(view->parent);
2035 if (err)
2036 break;
2037 /* Make resized splits persist. */
2038 view_transfer_size(view->parent, view);
2039 } else
2040 TAILQ_REMOVE(&views, view, entry);
2042 err = view_close(view);
2043 if (err)
2044 goto done;
2046 view = NULL;
2047 TAILQ_FOREACH(v, &views, entry) {
2048 if (v->focussed)
2049 break;
2051 if (view == NULL && new_view == NULL) {
2052 /* No view has focus. Try to pick one. */
2053 if (prev)
2054 view = prev;
2055 else if (!TAILQ_EMPTY(&views)) {
2056 view = TAILQ_LAST(&views,
2057 tog_view_list_head);
2059 if (view) {
2060 if (view->focus_child) {
2061 view->child->focussed = 1;
2062 view = view->child;
2063 } else
2064 view->focussed = 1;
2068 if (new_view) {
2069 struct tog_view *v, *t;
2070 /* Only allow one parent view per type. */
2071 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2072 if (v->type != new_view->type)
2073 continue;
2074 TAILQ_REMOVE(&views, v, entry);
2075 err = view_close(v);
2076 if (err)
2077 goto done;
2078 break;
2080 TAILQ_INSERT_TAIL(&views, new_view, entry);
2081 view = new_view;
2083 if (view && !done) {
2084 if (view_is_parent_view(view)) {
2085 if (view->child && view->child->focussed)
2086 view = view->child;
2087 } else {
2088 if (view->parent && view->parent->focussed)
2089 view = view->parent;
2091 show_panel(view->panel);
2092 if (view->child && view_is_splitscreen(view->child))
2093 show_panel(view->child->panel);
2094 if (view->parent && view_is_splitscreen(view)) {
2095 err = view->parent->show(view->parent);
2096 if (err)
2097 goto done;
2099 err = view->show(view);
2100 if (err)
2101 goto done;
2102 if (view->child) {
2103 err = view->child->show(view->child);
2104 if (err)
2105 goto done;
2107 update_panels();
2108 doupdate();
2111 done:
2112 while (!TAILQ_EMPTY(&views)) {
2113 const struct got_error *close_err;
2114 view = TAILQ_FIRST(&views);
2115 TAILQ_REMOVE(&views, view, entry);
2116 close_err = view_close(view);
2117 if (close_err && err == NULL)
2118 err = close_err;
2121 errcode = pthread_mutex_unlock(&tog_mutex);
2122 if (errcode && err == NULL)
2123 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2125 return err;
2128 __dead static void
2129 usage_log(void)
2131 endwin();
2132 fprintf(stderr,
2133 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2134 getprogname());
2135 exit(1);
2138 /* Create newly allocated wide-character string equivalent to a byte string. */
2139 static const struct got_error *
2140 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2142 char *vis = NULL;
2143 const struct got_error *err = NULL;
2145 *ws = NULL;
2146 *wlen = mbstowcs(NULL, s, 0);
2147 if (*wlen == (size_t)-1) {
2148 int vislen;
2149 if (errno != EILSEQ)
2150 return got_error_from_errno("mbstowcs");
2152 /* byte string invalid in current encoding; try to "fix" it */
2153 err = got_mbsavis(&vis, &vislen, s);
2154 if (err)
2155 return err;
2156 *wlen = mbstowcs(NULL, vis, 0);
2157 if (*wlen == (size_t)-1) {
2158 err = got_error_from_errno("mbstowcs"); /* give up */
2159 goto done;
2163 *ws = calloc(*wlen + 1, sizeof(**ws));
2164 if (*ws == NULL) {
2165 err = got_error_from_errno("calloc");
2166 goto done;
2169 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2170 err = got_error_from_errno("mbstowcs");
2171 done:
2172 free(vis);
2173 if (err) {
2174 free(*ws);
2175 *ws = NULL;
2176 *wlen = 0;
2178 return err;
2181 static const struct got_error *
2182 expand_tab(char **ptr, const char *src)
2184 char *dst;
2185 size_t len, n, idx = 0, sz = 0;
2187 *ptr = NULL;
2188 n = len = strlen(src);
2189 dst = malloc(n + 1);
2190 if (dst == NULL)
2191 return got_error_from_errno("malloc");
2193 while (idx < len && src[idx]) {
2194 const char c = src[idx];
2196 if (c == '\t') {
2197 size_t nb = TABSIZE - sz % TABSIZE;
2198 char *p;
2200 p = realloc(dst, n + nb);
2201 if (p == NULL) {
2202 free(dst);
2203 return got_error_from_errno("realloc");
2206 dst = p;
2207 n += nb;
2208 memset(dst + sz, ' ', nb);
2209 sz += nb;
2210 } else
2211 dst[sz++] = src[idx];
2212 ++idx;
2215 dst[sz] = '\0';
2216 *ptr = dst;
2217 return NULL;
2221 * Advance at most n columns from wline starting at offset off.
2222 * Return the index to the first character after the span operation.
2223 * Return the combined column width of all spanned wide character in
2224 * *rcol.
2226 static int
2227 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2229 int width, i, cols = 0;
2231 if (n == 0) {
2232 *rcol = cols;
2233 return off;
2236 for (i = off; wline[i] != L'\0'; ++i) {
2237 if (wline[i] == L'\t')
2238 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2239 else
2240 width = wcwidth(wline[i]);
2242 if (width == -1) {
2243 width = 1;
2244 wline[i] = L'.';
2247 if (cols + width > n)
2248 break;
2249 cols += width;
2252 *rcol = cols;
2253 return i;
2257 * Format a line for display, ensuring that it won't overflow a width limit.
2258 * With scrolling, the width returned refers to the scrolled version of the
2259 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2261 static const struct got_error *
2262 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2263 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2265 const struct got_error *err = NULL;
2266 int cols;
2267 wchar_t *wline = NULL;
2268 char *exstr = NULL;
2269 size_t wlen;
2270 int i, scrollx;
2272 *wlinep = NULL;
2273 *widthp = 0;
2275 if (expand) {
2276 err = expand_tab(&exstr, line);
2277 if (err)
2278 return err;
2281 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2282 free(exstr);
2283 if (err)
2284 return err;
2286 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2288 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2289 wline[wlen - 1] = L'\0';
2290 wlen--;
2292 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2293 wline[wlen - 1] = L'\0';
2294 wlen--;
2297 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2298 wline[i] = L'\0';
2300 if (widthp)
2301 *widthp = cols;
2302 if (scrollxp)
2303 *scrollxp = scrollx;
2304 if (err)
2305 free(wline);
2306 else
2307 *wlinep = wline;
2308 return err;
2311 static const struct got_error*
2312 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2313 struct got_object_id *id, struct got_repository *repo)
2315 static const struct got_error *err = NULL;
2316 struct got_reflist_entry *re;
2317 char *s;
2318 const char *name;
2320 *refs_str = NULL;
2322 TAILQ_FOREACH(re, refs, entry) {
2323 struct got_tag_object *tag = NULL;
2324 struct got_object_id *ref_id;
2325 int cmp;
2327 name = got_ref_get_name(re->ref);
2328 if (strcmp(name, GOT_REF_HEAD) == 0)
2329 continue;
2330 if (strncmp(name, "refs/", 5) == 0)
2331 name += 5;
2332 if (strncmp(name, "got/", 4) == 0 &&
2333 strncmp(name, "got/backup/", 11) != 0)
2334 continue;
2335 if (strncmp(name, "heads/", 6) == 0)
2336 name += 6;
2337 if (strncmp(name, "remotes/", 8) == 0) {
2338 name += 8;
2339 s = strstr(name, "/" GOT_REF_HEAD);
2340 if (s != NULL && s[strlen(s)] == '\0')
2341 continue;
2343 err = got_ref_resolve(&ref_id, repo, re->ref);
2344 if (err)
2345 break;
2346 if (strncmp(name, "tags/", 5) == 0) {
2347 err = got_object_open_as_tag(&tag, repo, ref_id);
2348 if (err) {
2349 if (err->code != GOT_ERR_OBJ_TYPE) {
2350 free(ref_id);
2351 break;
2353 /* Ref points at something other than a tag. */
2354 err = NULL;
2355 tag = NULL;
2358 cmp = got_object_id_cmp(tag ?
2359 got_object_tag_get_object_id(tag) : ref_id, id);
2360 free(ref_id);
2361 if (tag)
2362 got_object_tag_close(tag);
2363 if (cmp != 0)
2364 continue;
2365 s = *refs_str;
2366 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2367 s ? ", " : "", name) == -1) {
2368 err = got_error_from_errno("asprintf");
2369 free(s);
2370 *refs_str = NULL;
2371 break;
2373 free(s);
2376 return err;
2379 static const struct got_error *
2380 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2381 int col_tab_align)
2383 char *smallerthan;
2385 smallerthan = strchr(author, '<');
2386 if (smallerthan && smallerthan[1] != '\0')
2387 author = smallerthan + 1;
2388 author[strcspn(author, "@>")] = '\0';
2389 return format_line(wauthor, author_width, NULL, author, 0, limit,
2390 col_tab_align, 0);
2393 static const struct got_error *
2394 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2395 struct got_object_id *id, const size_t date_display_cols,
2396 int author_display_cols)
2398 struct tog_log_view_state *s = &view->state.log;
2399 const struct got_error *err = NULL;
2400 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2401 char *logmsg0 = NULL, *logmsg = NULL;
2402 char *author = NULL;
2403 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2404 int author_width, logmsg_width;
2405 char *newline, *line = NULL;
2406 int col, limit, scrollx;
2407 const int avail = view->ncols;
2408 struct tm tm;
2409 time_t committer_time;
2410 struct tog_color *tc;
2412 committer_time = got_object_commit_get_committer_time(commit);
2413 if (gmtime_r(&committer_time, &tm) == NULL)
2414 return got_error_from_errno("gmtime_r");
2415 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2416 return got_error(GOT_ERR_NO_SPACE);
2418 if (avail <= date_display_cols)
2419 limit = MIN(sizeof(datebuf) - 1, avail);
2420 else
2421 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2422 tc = get_color(&s->colors, TOG_COLOR_DATE);
2423 if (tc)
2424 wattr_on(view->window,
2425 COLOR_PAIR(tc->colorpair), NULL);
2426 waddnstr(view->window, datebuf, limit);
2427 if (tc)
2428 wattr_off(view->window,
2429 COLOR_PAIR(tc->colorpair), NULL);
2430 col = limit;
2431 if (col > avail)
2432 goto done;
2434 if (avail >= 120) {
2435 char *id_str;
2436 err = got_object_id_str(&id_str, id);
2437 if (err)
2438 goto done;
2439 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2440 if (tc)
2441 wattr_on(view->window,
2442 COLOR_PAIR(tc->colorpair), NULL);
2443 wprintw(view->window, "%.8s ", id_str);
2444 if (tc)
2445 wattr_off(view->window,
2446 COLOR_PAIR(tc->colorpair), NULL);
2447 free(id_str);
2448 col += 9;
2449 if (col > avail)
2450 goto done;
2453 if (s->use_committer)
2454 author = strdup(got_object_commit_get_committer(commit));
2455 else
2456 author = strdup(got_object_commit_get_author(commit));
2457 if (author == NULL) {
2458 err = got_error_from_errno("strdup");
2459 goto done;
2461 err = format_author(&wauthor, &author_width, author, avail - col, col);
2462 if (err)
2463 goto done;
2464 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2465 if (tc)
2466 wattr_on(view->window,
2467 COLOR_PAIR(tc->colorpair), NULL);
2468 waddwstr(view->window, wauthor);
2469 col += author_width;
2470 while (col < avail && author_width < author_display_cols + 2) {
2471 waddch(view->window, ' ');
2472 col++;
2473 author_width++;
2475 if (tc)
2476 wattr_off(view->window,
2477 COLOR_PAIR(tc->colorpair), NULL);
2478 if (col > avail)
2479 goto done;
2481 err = got_object_commit_get_logmsg(&logmsg0, commit);
2482 if (err)
2483 goto done;
2484 logmsg = logmsg0;
2485 while (*logmsg == '\n')
2486 logmsg++;
2487 newline = strchr(logmsg, '\n');
2488 if (newline)
2489 *newline = '\0';
2490 limit = avail - col;
2491 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2492 limit--; /* for the border */
2493 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2494 limit, col, 1);
2495 if (err)
2496 goto done;
2497 waddwstr(view->window, &wlogmsg[scrollx]);
2498 col += MAX(logmsg_width, 0);
2499 while (col < avail) {
2500 waddch(view->window, ' ');
2501 col++;
2503 done:
2504 free(logmsg0);
2505 free(wlogmsg);
2506 free(author);
2507 free(wauthor);
2508 free(line);
2509 return err;
2512 static struct commit_queue_entry *
2513 alloc_commit_queue_entry(struct got_commit_object *commit,
2514 struct got_object_id *id)
2516 struct commit_queue_entry *entry;
2517 struct got_object_id *dup;
2519 entry = calloc(1, sizeof(*entry));
2520 if (entry == NULL)
2521 return NULL;
2523 dup = got_object_id_dup(id);
2524 if (dup == NULL) {
2525 free(entry);
2526 return NULL;
2529 entry->id = dup;
2530 entry->commit = commit;
2531 return entry;
2534 static void
2535 pop_commit(struct commit_queue *commits)
2537 struct commit_queue_entry *entry;
2539 entry = TAILQ_FIRST(&commits->head);
2540 TAILQ_REMOVE(&commits->head, entry, entry);
2541 got_object_commit_close(entry->commit);
2542 commits->ncommits--;
2543 free(entry->id);
2544 free(entry);
2547 static void
2548 free_commits(struct commit_queue *commits)
2550 while (!TAILQ_EMPTY(&commits->head))
2551 pop_commit(commits);
2554 static const struct got_error *
2555 match_commit(int *have_match, struct got_object_id *id,
2556 struct got_commit_object *commit, regex_t *regex)
2558 const struct got_error *err = NULL;
2559 regmatch_t regmatch;
2560 char *id_str = NULL, *logmsg = NULL;
2562 *have_match = 0;
2564 err = got_object_id_str(&id_str, id);
2565 if (err)
2566 return err;
2568 err = got_object_commit_get_logmsg(&logmsg, commit);
2569 if (err)
2570 goto done;
2572 if (regexec(regex, got_object_commit_get_author(commit), 1,
2573 &regmatch, 0) == 0 ||
2574 regexec(regex, got_object_commit_get_committer(commit), 1,
2575 &regmatch, 0) == 0 ||
2576 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2577 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2578 *have_match = 1;
2579 done:
2580 free(id_str);
2581 free(logmsg);
2582 return err;
2585 static const struct got_error *
2586 queue_commits(struct tog_log_thread_args *a)
2588 const struct got_error *err = NULL;
2591 * We keep all commits open throughout the lifetime of the log
2592 * view in order to avoid having to re-fetch commits from disk
2593 * while updating the display.
2595 do {
2596 struct got_object_id id;
2597 struct got_commit_object *commit;
2598 struct commit_queue_entry *entry;
2599 int limit_match = 0;
2600 int errcode;
2602 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2603 NULL, NULL);
2604 if (err)
2605 break;
2607 err = got_object_open_as_commit(&commit, a->repo, &id);
2608 if (err)
2609 break;
2610 entry = alloc_commit_queue_entry(commit, &id);
2611 if (entry == NULL) {
2612 err = got_error_from_errno("alloc_commit_queue_entry");
2613 break;
2616 errcode = pthread_mutex_lock(&tog_mutex);
2617 if (errcode) {
2618 err = got_error_set_errno(errcode,
2619 "pthread_mutex_lock");
2620 break;
2623 entry->idx = a->real_commits->ncommits;
2624 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2625 a->real_commits->ncommits++;
2627 if (*a->limiting) {
2628 err = match_commit(&limit_match, &id, commit,
2629 a->limit_regex);
2630 if (err)
2631 break;
2633 if (limit_match) {
2634 struct commit_queue_entry *matched;
2636 matched = alloc_commit_queue_entry(
2637 entry->commit, entry->id);
2638 if (matched == NULL) {
2639 err = got_error_from_errno(
2640 "alloc_commit_queue_entry");
2641 break;
2643 matched->commit = entry->commit;
2644 got_object_commit_retain(entry->commit);
2646 matched->idx = a->limit_commits->ncommits;
2647 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2648 matched, entry);
2649 a->limit_commits->ncommits++;
2653 * This is how we signal log_thread() that we
2654 * have found a match, and that it should be
2655 * counted as a new entry for the view.
2657 a->limit_match = limit_match;
2660 if (*a->searching == TOG_SEARCH_FORWARD &&
2661 !*a->search_next_done) {
2662 int have_match;
2663 err = match_commit(&have_match, &id, commit, a->regex);
2664 if (err)
2665 break;
2667 if (*a->limiting) {
2668 if (limit_match && have_match)
2669 *a->search_next_done =
2670 TOG_SEARCH_HAVE_MORE;
2671 } else if (have_match)
2672 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2675 errcode = pthread_mutex_unlock(&tog_mutex);
2676 if (errcode && err == NULL)
2677 err = got_error_set_errno(errcode,
2678 "pthread_mutex_unlock");
2679 if (err)
2680 break;
2681 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2683 return err;
2686 static void
2687 select_commit(struct tog_log_view_state *s)
2689 struct commit_queue_entry *entry;
2690 int ncommits = 0;
2692 entry = s->first_displayed_entry;
2693 while (entry) {
2694 if (ncommits == s->selected) {
2695 s->selected_entry = entry;
2696 break;
2698 entry = TAILQ_NEXT(entry, entry);
2699 ncommits++;
2703 static const struct got_error *
2704 draw_commits(struct tog_view *view)
2706 const struct got_error *err = NULL;
2707 struct tog_log_view_state *s = &view->state.log;
2708 struct commit_queue_entry *entry = s->selected_entry;
2709 int limit = view->nlines;
2710 int width;
2711 int ncommits, author_cols = 4;
2712 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2713 char *refs_str = NULL;
2714 wchar_t *wline;
2715 struct tog_color *tc;
2716 static const size_t date_display_cols = 12;
2718 if (view_is_hsplit_top(view))
2719 --limit; /* account for border */
2721 if (s->selected_entry &&
2722 !(view->searching && view->search_next_done == 0)) {
2723 struct got_reflist_head *refs;
2724 err = got_object_id_str(&id_str, s->selected_entry->id);
2725 if (err)
2726 return err;
2727 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2728 s->selected_entry->id);
2729 if (refs) {
2730 err = build_refs_str(&refs_str, refs,
2731 s->selected_entry->id, s->repo);
2732 if (err)
2733 goto done;
2737 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2738 halfdelay(10); /* disable fast refresh */
2740 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2741 if (asprintf(&ncommits_str, " [%d/%d] %s",
2742 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2743 (view->searching && !view->search_next_done) ?
2744 "searching..." : "loading...") == -1) {
2745 err = got_error_from_errno("asprintf");
2746 goto done;
2748 } else {
2749 const char *search_str = NULL;
2750 const char *limit_str = NULL;
2752 if (view->searching) {
2753 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2754 search_str = "no more matches";
2755 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2756 search_str = "no matches found";
2757 else if (!view->search_next_done)
2758 search_str = "searching...";
2761 if (s->limit_view && s->commits->ncommits == 0)
2762 limit_str = "no matches found";
2764 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2765 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2766 search_str ? search_str : (refs_str ? refs_str : ""),
2767 limit_str ? limit_str : "") == -1) {
2768 err = got_error_from_errno("asprintf");
2769 goto done;
2773 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2774 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2775 "........................................",
2776 s->in_repo_path, ncommits_str) == -1) {
2777 err = got_error_from_errno("asprintf");
2778 header = NULL;
2779 goto done;
2781 } else if (asprintf(&header, "commit %s%s",
2782 id_str ? id_str : "........................................",
2783 ncommits_str) == -1) {
2784 err = got_error_from_errno("asprintf");
2785 header = NULL;
2786 goto done;
2788 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2789 if (err)
2790 goto done;
2792 werase(view->window);
2794 if (view_needs_focus_indication(view))
2795 wstandout(view->window);
2796 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2797 if (tc)
2798 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2799 waddwstr(view->window, wline);
2800 while (width < view->ncols) {
2801 waddch(view->window, ' ');
2802 width++;
2804 if (tc)
2805 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2806 if (view_needs_focus_indication(view))
2807 wstandend(view->window);
2808 free(wline);
2809 if (limit <= 1)
2810 goto done;
2812 /* Grow author column size if necessary, and set view->maxx. */
2813 entry = s->first_displayed_entry;
2814 ncommits = 0;
2815 view->maxx = 0;
2816 while (entry) {
2817 struct got_commit_object *c = entry->commit;
2818 char *author, *eol, *msg, *msg0;
2819 wchar_t *wauthor, *wmsg;
2820 int width;
2821 if (ncommits >= limit - 1)
2822 break;
2823 if (s->use_committer)
2824 author = strdup(got_object_commit_get_committer(c));
2825 else
2826 author = strdup(got_object_commit_get_author(c));
2827 if (author == NULL) {
2828 err = got_error_from_errno("strdup");
2829 goto done;
2831 err = format_author(&wauthor, &width, author, COLS,
2832 date_display_cols);
2833 if (author_cols < width)
2834 author_cols = width;
2835 free(wauthor);
2836 free(author);
2837 if (err)
2838 goto done;
2839 err = got_object_commit_get_logmsg(&msg0, c);
2840 if (err)
2841 goto done;
2842 msg = msg0;
2843 while (*msg == '\n')
2844 ++msg;
2845 if ((eol = strchr(msg, '\n')))
2846 *eol = '\0';
2847 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2848 date_display_cols + author_cols, 0);
2849 if (err)
2850 goto done;
2851 view->maxx = MAX(view->maxx, width);
2852 free(msg0);
2853 free(wmsg);
2854 ncommits++;
2855 entry = TAILQ_NEXT(entry, entry);
2858 entry = s->first_displayed_entry;
2859 s->last_displayed_entry = s->first_displayed_entry;
2860 ncommits = 0;
2861 while (entry) {
2862 if (ncommits >= limit - 1)
2863 break;
2864 if (ncommits == s->selected)
2865 wstandout(view->window);
2866 err = draw_commit(view, entry->commit, entry->id,
2867 date_display_cols, author_cols);
2868 if (ncommits == s->selected)
2869 wstandend(view->window);
2870 if (err)
2871 goto done;
2872 ncommits++;
2873 s->last_displayed_entry = entry;
2874 entry = TAILQ_NEXT(entry, entry);
2877 view_border(view);
2878 done:
2879 free(id_str);
2880 free(refs_str);
2881 free(ncommits_str);
2882 free(header);
2883 return err;
2886 static void
2887 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2889 struct commit_queue_entry *entry;
2890 int nscrolled = 0;
2892 entry = TAILQ_FIRST(&s->commits->head);
2893 if (s->first_displayed_entry == entry)
2894 return;
2896 entry = s->first_displayed_entry;
2897 while (entry && nscrolled < maxscroll) {
2898 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2899 if (entry) {
2900 s->first_displayed_entry = entry;
2901 nscrolled++;
2906 static const struct got_error *
2907 trigger_log_thread(struct tog_view *view, int wait)
2909 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2910 int errcode;
2912 if (!using_mock_io)
2913 halfdelay(1); /* fast refresh while loading commits */
2915 while (!ta->log_complete && !tog_thread_error &&
2916 (ta->commits_needed > 0 || ta->load_all)) {
2917 /* Wake the log thread. */
2918 errcode = pthread_cond_signal(&ta->need_commits);
2919 if (errcode)
2920 return got_error_set_errno(errcode,
2921 "pthread_cond_signal");
2924 * The mutex will be released while the view loop waits
2925 * in wgetch(), at which time the log thread will run.
2927 if (!wait)
2928 break;
2930 /* Display progress update in log view. */
2931 show_log_view(view);
2932 update_panels();
2933 doupdate();
2935 /* Wait right here while next commit is being loaded. */
2936 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2937 if (errcode)
2938 return got_error_set_errno(errcode,
2939 "pthread_cond_wait");
2941 /* Display progress update in log view. */
2942 show_log_view(view);
2943 update_panels();
2944 doupdate();
2947 return NULL;
2950 static const struct got_error *
2951 request_log_commits(struct tog_view *view)
2953 struct tog_log_view_state *state = &view->state.log;
2954 const struct got_error *err = NULL;
2956 if (state->thread_args.log_complete)
2957 return NULL;
2959 state->thread_args.commits_needed += view->nscrolled;
2960 err = trigger_log_thread(view, 1);
2961 view->nscrolled = 0;
2963 return err;
2966 static const struct got_error *
2967 log_scroll_down(struct tog_view *view, int maxscroll)
2969 struct tog_log_view_state *s = &view->state.log;
2970 const struct got_error *err = NULL;
2971 struct commit_queue_entry *pentry;
2972 int nscrolled = 0, ncommits_needed;
2974 if (s->last_displayed_entry == NULL)
2975 return NULL;
2977 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2978 if (s->commits->ncommits < ncommits_needed &&
2979 !s->thread_args.log_complete) {
2981 * Ask the log thread for required amount of commits.
2983 s->thread_args.commits_needed +=
2984 ncommits_needed - s->commits->ncommits;
2985 err = trigger_log_thread(view, 1);
2986 if (err)
2987 return err;
2990 do {
2991 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2992 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2993 break;
2995 s->last_displayed_entry = pentry ?
2996 pentry : s->last_displayed_entry;
2998 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2999 if (pentry == NULL)
3000 break;
3001 s->first_displayed_entry = pentry;
3002 } while (++nscrolled < maxscroll);
3004 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3005 view->nscrolled += nscrolled;
3006 else
3007 view->nscrolled = 0;
3009 return err;
3012 static const struct got_error *
3013 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3014 struct got_commit_object *commit, struct got_object_id *commit_id,
3015 struct tog_view *log_view, struct got_repository *repo)
3017 const struct got_error *err;
3018 struct got_object_qid *parent_id;
3019 struct tog_view *diff_view;
3021 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3022 if (diff_view == NULL)
3023 return got_error_from_errno("view_open");
3025 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3026 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3027 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3028 if (err == NULL)
3029 *new_view = diff_view;
3030 return err;
3033 static const struct got_error *
3034 tree_view_visit_subtree(struct tog_tree_view_state *s,
3035 struct got_tree_object *subtree)
3037 struct tog_parent_tree *parent;
3039 parent = calloc(1, sizeof(*parent));
3040 if (parent == NULL)
3041 return got_error_from_errno("calloc");
3043 parent->tree = s->tree;
3044 parent->first_displayed_entry = s->first_displayed_entry;
3045 parent->selected_entry = s->selected_entry;
3046 parent->selected = s->selected;
3047 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3048 s->tree = subtree;
3049 s->selected = 0;
3050 s->first_displayed_entry = NULL;
3051 return NULL;
3054 static const struct got_error *
3055 tree_view_walk_path(struct tog_tree_view_state *s,
3056 struct got_commit_object *commit, const char *path)
3058 const struct got_error *err = NULL;
3059 struct got_tree_object *tree = NULL;
3060 const char *p;
3061 char *slash, *subpath = NULL;
3063 /* Walk the path and open corresponding tree objects. */
3064 p = path;
3065 while (*p) {
3066 struct got_tree_entry *te;
3067 struct got_object_id *tree_id;
3068 char *te_name;
3070 while (p[0] == '/')
3071 p++;
3073 /* Ensure the correct subtree entry is selected. */
3074 slash = strchr(p, '/');
3075 if (slash == NULL)
3076 te_name = strdup(p);
3077 else
3078 te_name = strndup(p, slash - p);
3079 if (te_name == NULL) {
3080 err = got_error_from_errno("strndup");
3081 break;
3083 te = got_object_tree_find_entry(s->tree, te_name);
3084 if (te == NULL) {
3085 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3086 free(te_name);
3087 break;
3089 free(te_name);
3090 s->first_displayed_entry = s->selected_entry = te;
3092 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3093 break; /* jump to this file's entry */
3095 slash = strchr(p, '/');
3096 if (slash)
3097 subpath = strndup(path, slash - path);
3098 else
3099 subpath = strdup(path);
3100 if (subpath == NULL) {
3101 err = got_error_from_errno("strdup");
3102 break;
3105 err = got_object_id_by_path(&tree_id, s->repo, commit,
3106 subpath);
3107 if (err)
3108 break;
3110 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3111 free(tree_id);
3112 if (err)
3113 break;
3115 err = tree_view_visit_subtree(s, tree);
3116 if (err) {
3117 got_object_tree_close(tree);
3118 break;
3120 if (slash == NULL)
3121 break;
3122 free(subpath);
3123 subpath = NULL;
3124 p = slash;
3127 free(subpath);
3128 return err;
3131 static const struct got_error *
3132 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3133 struct commit_queue_entry *entry, const char *path,
3134 const char *head_ref_name, struct got_repository *repo)
3136 const struct got_error *err = NULL;
3137 struct tog_tree_view_state *s;
3138 struct tog_view *tree_view;
3140 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3141 if (tree_view == NULL)
3142 return got_error_from_errno("view_open");
3144 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3145 if (err)
3146 return err;
3147 s = &tree_view->state.tree;
3149 *new_view = tree_view;
3151 if (got_path_is_root_dir(path))
3152 return NULL;
3154 return tree_view_walk_path(s, entry->commit, path);
3157 static const struct got_error *
3158 block_signals_used_by_main_thread(void)
3160 sigset_t sigset;
3161 int errcode;
3163 if (sigemptyset(&sigset) == -1)
3164 return got_error_from_errno("sigemptyset");
3166 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3167 if (sigaddset(&sigset, SIGWINCH) == -1)
3168 return got_error_from_errno("sigaddset");
3169 if (sigaddset(&sigset, SIGCONT) == -1)
3170 return got_error_from_errno("sigaddset");
3171 if (sigaddset(&sigset, SIGINT) == -1)
3172 return got_error_from_errno("sigaddset");
3173 if (sigaddset(&sigset, SIGTERM) == -1)
3174 return got_error_from_errno("sigaddset");
3176 /* ncurses handles SIGTSTP */
3177 if (sigaddset(&sigset, SIGTSTP) == -1)
3178 return got_error_from_errno("sigaddset");
3180 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3181 if (errcode)
3182 return got_error_set_errno(errcode, "pthread_sigmask");
3184 return NULL;
3187 static void *
3188 log_thread(void *arg)
3190 const struct got_error *err = NULL;
3191 int errcode = 0;
3192 struct tog_log_thread_args *a = arg;
3193 int done = 0;
3196 * Sync startup with main thread such that we begin our
3197 * work once view_input() has released the mutex.
3199 errcode = pthread_mutex_lock(&tog_mutex);
3200 if (errcode) {
3201 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3202 return (void *)err;
3205 err = block_signals_used_by_main_thread();
3206 if (err) {
3207 pthread_mutex_unlock(&tog_mutex);
3208 goto done;
3211 while (!done && !err && !tog_fatal_signal_received()) {
3212 errcode = pthread_mutex_unlock(&tog_mutex);
3213 if (errcode) {
3214 err = got_error_set_errno(errcode,
3215 "pthread_mutex_unlock");
3216 goto done;
3218 err = queue_commits(a);
3219 if (err) {
3220 if (err->code != GOT_ERR_ITER_COMPLETED)
3221 goto done;
3222 err = NULL;
3223 done = 1;
3224 } else if (a->commits_needed > 0 && !a->load_all) {
3225 if (*a->limiting) {
3226 if (a->limit_match)
3227 a->commits_needed--;
3228 } else
3229 a->commits_needed--;
3232 errcode = pthread_mutex_lock(&tog_mutex);
3233 if (errcode) {
3234 err = got_error_set_errno(errcode,
3235 "pthread_mutex_lock");
3236 goto done;
3237 } else if (*a->quit)
3238 done = 1;
3239 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3240 *a->first_displayed_entry =
3241 TAILQ_FIRST(&a->limit_commits->head);
3242 *a->selected_entry = *a->first_displayed_entry;
3243 } else if (*a->first_displayed_entry == NULL) {
3244 *a->first_displayed_entry =
3245 TAILQ_FIRST(&a->real_commits->head);
3246 *a->selected_entry = *a->first_displayed_entry;
3249 errcode = pthread_cond_signal(&a->commit_loaded);
3250 if (errcode) {
3251 err = got_error_set_errno(errcode,
3252 "pthread_cond_signal");
3253 pthread_mutex_unlock(&tog_mutex);
3254 goto done;
3257 if (done)
3258 a->commits_needed = 0;
3259 else {
3260 if (a->commits_needed == 0 && !a->load_all) {
3261 errcode = pthread_cond_wait(&a->need_commits,
3262 &tog_mutex);
3263 if (errcode) {
3264 err = got_error_set_errno(errcode,
3265 "pthread_cond_wait");
3266 pthread_mutex_unlock(&tog_mutex);
3267 goto done;
3269 if (*a->quit)
3270 done = 1;
3274 a->log_complete = 1;
3275 errcode = pthread_mutex_unlock(&tog_mutex);
3276 if (errcode)
3277 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3278 done:
3279 if (err) {
3280 tog_thread_error = 1;
3281 pthread_cond_signal(&a->commit_loaded);
3283 return (void *)err;
3286 static const struct got_error *
3287 stop_log_thread(struct tog_log_view_state *s)
3289 const struct got_error *err = NULL, *thread_err = NULL;
3290 int errcode;
3292 if (s->thread) {
3293 s->quit = 1;
3294 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3295 if (errcode)
3296 return got_error_set_errno(errcode,
3297 "pthread_cond_signal");
3298 errcode = pthread_mutex_unlock(&tog_mutex);
3299 if (errcode)
3300 return got_error_set_errno(errcode,
3301 "pthread_mutex_unlock");
3302 errcode = pthread_join(s->thread, (void **)&thread_err);
3303 if (errcode)
3304 return got_error_set_errno(errcode, "pthread_join");
3305 errcode = pthread_mutex_lock(&tog_mutex);
3306 if (errcode)
3307 return got_error_set_errno(errcode,
3308 "pthread_mutex_lock");
3309 s->thread = NULL;
3312 if (s->thread_args.repo) {
3313 err = got_repo_close(s->thread_args.repo);
3314 s->thread_args.repo = NULL;
3317 if (s->thread_args.pack_fds) {
3318 const struct got_error *pack_err =
3319 got_repo_pack_fds_close(s->thread_args.pack_fds);
3320 if (err == NULL)
3321 err = pack_err;
3322 s->thread_args.pack_fds = NULL;
3325 if (s->thread_args.graph) {
3326 got_commit_graph_close(s->thread_args.graph);
3327 s->thread_args.graph = NULL;
3330 return err ? err : thread_err;
3333 static const struct got_error *
3334 close_log_view(struct tog_view *view)
3336 const struct got_error *err = NULL;
3337 struct tog_log_view_state *s = &view->state.log;
3338 int errcode;
3340 err = stop_log_thread(s);
3342 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3343 if (errcode && err == NULL)
3344 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3346 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3347 if (errcode && err == NULL)
3348 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3350 free_commits(&s->limit_commits);
3351 free_commits(&s->real_commits);
3352 free(s->in_repo_path);
3353 s->in_repo_path = NULL;
3354 free(s->start_id);
3355 s->start_id = NULL;
3356 free(s->head_ref_name);
3357 s->head_ref_name = NULL;
3358 return err;
3362 * We use two queues to implement the limit feature: first consists of
3363 * commits matching the current limit_regex; second is the real queue
3364 * of all known commits (real_commits). When the user starts limiting,
3365 * we swap queues such that all movement and displaying functionality
3366 * works with very slight change.
3368 static const struct got_error *
3369 limit_log_view(struct tog_view *view)
3371 struct tog_log_view_state *s = &view->state.log;
3372 struct commit_queue_entry *entry;
3373 struct tog_view *v = view;
3374 const struct got_error *err = NULL;
3375 char pattern[1024];
3376 int ret;
3378 if (view_is_hsplit_top(view))
3379 v = view->child;
3380 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3381 v = view->parent;
3383 /* Get the pattern */
3384 wmove(v->window, v->nlines - 1, 0);
3385 wclrtoeol(v->window);
3386 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3387 nodelay(v->window, FALSE);
3388 nocbreak();
3389 echo();
3390 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3391 cbreak();
3392 noecho();
3393 nodelay(v->window, TRUE);
3394 if (ret == ERR)
3395 return NULL;
3397 if (*pattern == '\0') {
3399 * Safety measure for the situation where the user
3400 * resets limit without previously limiting anything.
3402 if (!s->limit_view)
3403 return NULL;
3406 * User could have pressed Ctrl+L, which refreshed the
3407 * commit queues, it means we can't save previously
3408 * (before limit took place) displayed entries,
3409 * because they would point to already free'ed memory,
3410 * so we are forced to always select first entry of
3411 * the queue.
3413 s->commits = &s->real_commits;
3414 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3415 s->selected_entry = s->first_displayed_entry;
3416 s->selected = 0;
3417 s->limit_view = 0;
3419 return NULL;
3422 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3423 return NULL;
3425 s->limit_view = 1;
3427 /* Clear the screen while loading limit view */
3428 s->first_displayed_entry = NULL;
3429 s->last_displayed_entry = NULL;
3430 s->selected_entry = NULL;
3431 s->commits = &s->limit_commits;
3433 /* Prepare limit queue for new search */
3434 free_commits(&s->limit_commits);
3435 s->limit_commits.ncommits = 0;
3437 /* First process commits, which are in queue already */
3438 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3439 int have_match = 0;
3441 err = match_commit(&have_match, entry->id,
3442 entry->commit, &s->limit_regex);
3443 if (err)
3444 return err;
3446 if (have_match) {
3447 struct commit_queue_entry *matched;
3449 matched = alloc_commit_queue_entry(entry->commit,
3450 entry->id);
3451 if (matched == NULL) {
3452 err = got_error_from_errno(
3453 "alloc_commit_queue_entry");
3454 break;
3456 matched->commit = entry->commit;
3457 got_object_commit_retain(entry->commit);
3459 matched->idx = s->limit_commits.ncommits;
3460 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3461 matched, entry);
3462 s->limit_commits.ncommits++;
3466 /* Second process all the commits, until we fill the screen */
3467 if (s->limit_commits.ncommits < view->nlines - 1 &&
3468 !s->thread_args.log_complete) {
3469 s->thread_args.commits_needed +=
3470 view->nlines - s->limit_commits.ncommits - 1;
3471 err = trigger_log_thread(view, 1);
3472 if (err)
3473 return err;
3476 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3477 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3478 s->selected = 0;
3480 return NULL;
3483 static const struct got_error *
3484 search_start_log_view(struct tog_view *view)
3486 struct tog_log_view_state *s = &view->state.log;
3488 s->matched_entry = NULL;
3489 s->search_entry = NULL;
3490 return NULL;
3493 static const struct got_error *
3494 search_next_log_view(struct tog_view *view)
3496 const struct got_error *err = NULL;
3497 struct tog_log_view_state *s = &view->state.log;
3498 struct commit_queue_entry *entry;
3500 /* Display progress update in log view. */
3501 show_log_view(view);
3502 update_panels();
3503 doupdate();
3505 if (s->search_entry) {
3506 int errcode, ch;
3507 errcode = pthread_mutex_unlock(&tog_mutex);
3508 if (errcode)
3509 return got_error_set_errno(errcode,
3510 "pthread_mutex_unlock");
3511 ch = wgetch(view->window);
3512 errcode = pthread_mutex_lock(&tog_mutex);
3513 if (errcode)
3514 return got_error_set_errno(errcode,
3515 "pthread_mutex_lock");
3516 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3517 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3518 return NULL;
3520 if (view->searching == TOG_SEARCH_FORWARD)
3521 entry = TAILQ_NEXT(s->search_entry, entry);
3522 else
3523 entry = TAILQ_PREV(s->search_entry,
3524 commit_queue_head, entry);
3525 } else if (s->matched_entry) {
3527 * If the user has moved the cursor after we hit a match,
3528 * the position from where we should continue searching
3529 * might have changed.
3531 if (view->searching == TOG_SEARCH_FORWARD)
3532 entry = TAILQ_NEXT(s->selected_entry, entry);
3533 else
3534 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3535 entry);
3536 } else {
3537 entry = s->selected_entry;
3540 while (1) {
3541 int have_match = 0;
3543 if (entry == NULL) {
3544 if (s->thread_args.log_complete ||
3545 view->searching == TOG_SEARCH_BACKWARD) {
3546 view->search_next_done =
3547 (s->matched_entry == NULL ?
3548 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3549 s->search_entry = NULL;
3550 return NULL;
3553 * Poke the log thread for more commits and return,
3554 * allowing the main loop to make progress. Search
3555 * will resume at s->search_entry once we come back.
3557 s->thread_args.commits_needed++;
3558 return trigger_log_thread(view, 0);
3561 err = match_commit(&have_match, entry->id, entry->commit,
3562 &view->regex);
3563 if (err)
3564 break;
3565 if (have_match) {
3566 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3567 s->matched_entry = entry;
3568 break;
3571 s->search_entry = entry;
3572 if (view->searching == TOG_SEARCH_FORWARD)
3573 entry = TAILQ_NEXT(entry, entry);
3574 else
3575 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3578 if (s->matched_entry) {
3579 int cur = s->selected_entry->idx;
3580 while (cur < s->matched_entry->idx) {
3581 err = input_log_view(NULL, view, KEY_DOWN);
3582 if (err)
3583 return err;
3584 cur++;
3586 while (cur > s->matched_entry->idx) {
3587 err = input_log_view(NULL, view, KEY_UP);
3588 if (err)
3589 return err;
3590 cur--;
3594 s->search_entry = NULL;
3596 return NULL;
3599 static const struct got_error *
3600 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3601 struct got_repository *repo, const char *head_ref_name,
3602 const char *in_repo_path, int log_branches)
3604 const struct got_error *err = NULL;
3605 struct tog_log_view_state *s = &view->state.log;
3606 struct got_repository *thread_repo = NULL;
3607 struct got_commit_graph *thread_graph = NULL;
3608 int errcode;
3610 if (in_repo_path != s->in_repo_path) {
3611 free(s->in_repo_path);
3612 s->in_repo_path = strdup(in_repo_path);
3613 if (s->in_repo_path == NULL) {
3614 err = got_error_from_errno("strdup");
3615 goto done;
3619 /* The commit queue only contains commits being displayed. */
3620 TAILQ_INIT(&s->real_commits.head);
3621 s->real_commits.ncommits = 0;
3622 s->commits = &s->real_commits;
3624 TAILQ_INIT(&s->limit_commits.head);
3625 s->limit_view = 0;
3626 s->limit_commits.ncommits = 0;
3628 s->repo = repo;
3629 if (head_ref_name) {
3630 s->head_ref_name = strdup(head_ref_name);
3631 if (s->head_ref_name == NULL) {
3632 err = got_error_from_errno("strdup");
3633 goto done;
3636 s->start_id = got_object_id_dup(start_id);
3637 if (s->start_id == NULL) {
3638 err = got_error_from_errno("got_object_id_dup");
3639 goto done;
3641 s->log_branches = log_branches;
3642 s->use_committer = 1;
3644 STAILQ_INIT(&s->colors);
3645 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3646 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3647 get_color_value("TOG_COLOR_COMMIT"));
3648 if (err)
3649 goto done;
3650 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3651 get_color_value("TOG_COLOR_AUTHOR"));
3652 if (err) {
3653 free_colors(&s->colors);
3654 goto done;
3656 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3657 get_color_value("TOG_COLOR_DATE"));
3658 if (err) {
3659 free_colors(&s->colors);
3660 goto done;
3664 view->show = show_log_view;
3665 view->input = input_log_view;
3666 view->resize = resize_log_view;
3667 view->close = close_log_view;
3668 view->search_start = search_start_log_view;
3669 view->search_next = search_next_log_view;
3671 if (s->thread_args.pack_fds == NULL) {
3672 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3673 if (err)
3674 goto done;
3676 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3677 s->thread_args.pack_fds);
3678 if (err)
3679 goto done;
3680 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3681 !s->log_branches);
3682 if (err)
3683 goto done;
3684 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3685 s->repo, NULL, NULL);
3686 if (err)
3687 goto done;
3689 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3690 if (errcode) {
3691 err = got_error_set_errno(errcode, "pthread_cond_init");
3692 goto done;
3694 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3695 if (errcode) {
3696 err = got_error_set_errno(errcode, "pthread_cond_init");
3697 goto done;
3700 s->thread_args.commits_needed = view->nlines;
3701 s->thread_args.graph = thread_graph;
3702 s->thread_args.real_commits = &s->real_commits;
3703 s->thread_args.limit_commits = &s->limit_commits;
3704 s->thread_args.in_repo_path = s->in_repo_path;
3705 s->thread_args.start_id = s->start_id;
3706 s->thread_args.repo = thread_repo;
3707 s->thread_args.log_complete = 0;
3708 s->thread_args.quit = &s->quit;
3709 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3710 s->thread_args.selected_entry = &s->selected_entry;
3711 s->thread_args.searching = &view->searching;
3712 s->thread_args.search_next_done = &view->search_next_done;
3713 s->thread_args.regex = &view->regex;
3714 s->thread_args.limiting = &s->limit_view;
3715 s->thread_args.limit_regex = &s->limit_regex;
3716 s->thread_args.limit_commits = &s->limit_commits;
3717 done:
3718 if (err) {
3719 if (view->close == NULL)
3720 close_log_view(view);
3721 view_close(view);
3723 return err;
3726 static const struct got_error *
3727 show_log_view(struct tog_view *view)
3729 const struct got_error *err;
3730 struct tog_log_view_state *s = &view->state.log;
3732 if (s->thread == NULL) {
3733 int errcode = pthread_create(&s->thread, NULL, log_thread,
3734 &s->thread_args);
3735 if (errcode)
3736 return got_error_set_errno(errcode, "pthread_create");
3737 if (s->thread_args.commits_needed > 0) {
3738 err = trigger_log_thread(view, 1);
3739 if (err)
3740 return err;
3744 return draw_commits(view);
3747 static void
3748 log_move_cursor_up(struct tog_view *view, int page, int home)
3750 struct tog_log_view_state *s = &view->state.log;
3752 if (s->first_displayed_entry == NULL)
3753 return;
3754 if (s->selected_entry->idx == 0)
3755 view->count = 0;
3757 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3758 || home)
3759 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3761 if (!page && !home && s->selected > 0)
3762 --s->selected;
3763 else
3764 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3766 select_commit(s);
3767 return;
3770 static const struct got_error *
3771 log_move_cursor_down(struct tog_view *view, int page)
3773 struct tog_log_view_state *s = &view->state.log;
3774 const struct got_error *err = NULL;
3775 int eos = view->nlines - 2;
3777 if (s->first_displayed_entry == NULL)
3778 return NULL;
3780 if (s->thread_args.log_complete &&
3781 s->selected_entry->idx >= s->commits->ncommits - 1)
3782 return NULL;
3784 if (view_is_hsplit_top(view))
3785 --eos; /* border consumes the last line */
3787 if (!page) {
3788 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3789 ++s->selected;
3790 else
3791 err = log_scroll_down(view, 1);
3792 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3793 struct commit_queue_entry *entry;
3794 int n;
3796 s->selected = 0;
3797 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3798 s->last_displayed_entry = entry;
3799 for (n = 0; n <= eos; n++) {
3800 if (entry == NULL)
3801 break;
3802 s->first_displayed_entry = entry;
3803 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3805 if (n > 0)
3806 s->selected = n - 1;
3807 } else {
3808 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3809 s->thread_args.log_complete)
3810 s->selected += MIN(page,
3811 s->commits->ncommits - s->selected_entry->idx - 1);
3812 else
3813 err = log_scroll_down(view, page);
3815 if (err)
3816 return err;
3819 * We might necessarily overshoot in horizontal
3820 * splits; if so, select the last displayed commit.
3822 if (s->first_displayed_entry && s->last_displayed_entry) {
3823 s->selected = MIN(s->selected,
3824 s->last_displayed_entry->idx -
3825 s->first_displayed_entry->idx);
3828 select_commit(s);
3830 if (s->thread_args.log_complete &&
3831 s->selected_entry->idx == s->commits->ncommits - 1)
3832 view->count = 0;
3834 return NULL;
3837 static void
3838 view_get_split(struct tog_view *view, int *y, int *x)
3840 *x = 0;
3841 *y = 0;
3843 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3844 if (view->child && view->child->resized_y)
3845 *y = view->child->resized_y;
3846 else if (view->resized_y)
3847 *y = view->resized_y;
3848 else
3849 *y = view_split_begin_y(view->lines);
3850 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3851 if (view->child && view->child->resized_x)
3852 *x = view->child->resized_x;
3853 else if (view->resized_x)
3854 *x = view->resized_x;
3855 else
3856 *x = view_split_begin_x(view->begin_x);
3860 /* Split view horizontally at y and offset view->state->selected line. */
3861 static const struct got_error *
3862 view_init_hsplit(struct tog_view *view, int y)
3864 const struct got_error *err = NULL;
3866 view->nlines = y;
3867 view->ncols = COLS;
3868 err = view_resize(view);
3869 if (err)
3870 return err;
3872 err = offset_selection_down(view);
3874 return err;
3877 static const struct got_error *
3878 log_goto_line(struct tog_view *view, int nlines)
3880 const struct got_error *err = NULL;
3881 struct tog_log_view_state *s = &view->state.log;
3882 int g, idx = s->selected_entry->idx;
3884 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3885 return NULL;
3887 g = view->gline;
3888 view->gline = 0;
3890 if (g >= s->first_displayed_entry->idx + 1 &&
3891 g <= s->last_displayed_entry->idx + 1 &&
3892 g - s->first_displayed_entry->idx - 1 < nlines) {
3893 s->selected = g - s->first_displayed_entry->idx - 1;
3894 select_commit(s);
3895 return NULL;
3898 if (idx + 1 < g) {
3899 err = log_move_cursor_down(view, g - idx - 1);
3900 if (!err && g > s->selected_entry->idx + 1)
3901 err = log_move_cursor_down(view,
3902 g - s->first_displayed_entry->idx - 1);
3903 if (err)
3904 return err;
3905 } else if (idx + 1 > g)
3906 log_move_cursor_up(view, idx - g + 1, 0);
3908 if (g < nlines && s->first_displayed_entry->idx == 0)
3909 s->selected = g - 1;
3911 select_commit(s);
3912 return NULL;
3916 static void
3917 horizontal_scroll_input(struct tog_view *view, int ch)
3920 switch (ch) {
3921 case KEY_LEFT:
3922 case 'h':
3923 view->x -= MIN(view->x, 2);
3924 if (view->x <= 0)
3925 view->count = 0;
3926 break;
3927 case KEY_RIGHT:
3928 case 'l':
3929 if (view->x + view->ncols / 2 < view->maxx)
3930 view->x += 2;
3931 else
3932 view->count = 0;
3933 break;
3934 case '0':
3935 view->x = 0;
3936 break;
3937 case '$':
3938 view->x = MAX(view->maxx - view->ncols / 2, 0);
3939 view->count = 0;
3940 break;
3941 default:
3942 break;
3946 static const struct got_error *
3947 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3949 const struct got_error *err = NULL;
3950 struct tog_log_view_state *s = &view->state.log;
3951 int eos, nscroll;
3953 if (s->thread_args.load_all) {
3954 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3955 s->thread_args.load_all = 0;
3956 else if (s->thread_args.log_complete) {
3957 err = log_move_cursor_down(view, s->commits->ncommits);
3958 s->thread_args.load_all = 0;
3960 if (err)
3961 return err;
3964 eos = nscroll = view->nlines - 1;
3965 if (view_is_hsplit_top(view))
3966 --eos; /* border */
3968 if (view->gline)
3969 return log_goto_line(view, eos);
3971 switch (ch) {
3972 case '&':
3973 err = limit_log_view(view);
3974 break;
3975 case 'q':
3976 s->quit = 1;
3977 break;
3978 case '0':
3979 case '$':
3980 case KEY_RIGHT:
3981 case 'l':
3982 case KEY_LEFT:
3983 case 'h':
3984 horizontal_scroll_input(view, ch);
3985 break;
3986 case 'k':
3987 case KEY_UP:
3988 case '<':
3989 case ',':
3990 case CTRL('p'):
3991 log_move_cursor_up(view, 0, 0);
3992 break;
3993 case 'g':
3994 case '=':
3995 case KEY_HOME:
3996 log_move_cursor_up(view, 0, 1);
3997 view->count = 0;
3998 break;
3999 case CTRL('u'):
4000 case 'u':
4001 nscroll /= 2;
4002 /* FALL THROUGH */
4003 case KEY_PPAGE:
4004 case CTRL('b'):
4005 case 'b':
4006 log_move_cursor_up(view, nscroll, 0);
4007 break;
4008 case 'j':
4009 case KEY_DOWN:
4010 case '>':
4011 case '.':
4012 case CTRL('n'):
4013 err = log_move_cursor_down(view, 0);
4014 break;
4015 case '@':
4016 s->use_committer = !s->use_committer;
4017 view->action = s->use_committer ?
4018 "show committer" : "show commit author";
4019 break;
4020 case 'G':
4021 case '*':
4022 case KEY_END: {
4023 /* We don't know yet how many commits, so we're forced to
4024 * traverse them all. */
4025 view->count = 0;
4026 s->thread_args.load_all = 1;
4027 if (!s->thread_args.log_complete)
4028 return trigger_log_thread(view, 0);
4029 err = log_move_cursor_down(view, s->commits->ncommits);
4030 s->thread_args.load_all = 0;
4031 break;
4033 case CTRL('d'):
4034 case 'd':
4035 nscroll /= 2;
4036 /* FALL THROUGH */
4037 case KEY_NPAGE:
4038 case CTRL('f'):
4039 case 'f':
4040 case ' ':
4041 err = log_move_cursor_down(view, nscroll);
4042 break;
4043 case KEY_RESIZE:
4044 if (s->selected > view->nlines - 2)
4045 s->selected = view->nlines - 2;
4046 if (s->selected > s->commits->ncommits - 1)
4047 s->selected = s->commits->ncommits - 1;
4048 select_commit(s);
4049 if (s->commits->ncommits < view->nlines - 1 &&
4050 !s->thread_args.log_complete) {
4051 s->thread_args.commits_needed += (view->nlines - 1) -
4052 s->commits->ncommits;
4053 err = trigger_log_thread(view, 1);
4055 break;
4056 case KEY_ENTER:
4057 case '\r':
4058 view->count = 0;
4059 if (s->selected_entry == NULL)
4060 break;
4061 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4062 break;
4063 case 'T':
4064 view->count = 0;
4065 if (s->selected_entry == NULL)
4066 break;
4067 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4068 break;
4069 case KEY_BACKSPACE:
4070 case CTRL('l'):
4071 case 'B':
4072 view->count = 0;
4073 if (ch == KEY_BACKSPACE &&
4074 got_path_is_root_dir(s->in_repo_path))
4075 break;
4076 err = stop_log_thread(s);
4077 if (err)
4078 return err;
4079 if (ch == KEY_BACKSPACE) {
4080 char *parent_path;
4081 err = got_path_dirname(&parent_path, s->in_repo_path);
4082 if (err)
4083 return err;
4084 free(s->in_repo_path);
4085 s->in_repo_path = parent_path;
4086 s->thread_args.in_repo_path = s->in_repo_path;
4087 } else if (ch == CTRL('l')) {
4088 struct got_object_id *start_id;
4089 err = got_repo_match_object_id(&start_id, NULL,
4090 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4091 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4092 if (err) {
4093 if (s->head_ref_name == NULL ||
4094 err->code != GOT_ERR_NOT_REF)
4095 return err;
4096 /* Try to cope with deleted references. */
4097 free(s->head_ref_name);
4098 s->head_ref_name = NULL;
4099 err = got_repo_match_object_id(&start_id,
4100 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4101 &tog_refs, s->repo);
4102 if (err)
4103 return err;
4105 free(s->start_id);
4106 s->start_id = start_id;
4107 s->thread_args.start_id = s->start_id;
4108 } else /* 'B' */
4109 s->log_branches = !s->log_branches;
4111 if (s->thread_args.pack_fds == NULL) {
4112 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4113 if (err)
4114 return err;
4116 err = got_repo_open(&s->thread_args.repo,
4117 got_repo_get_path(s->repo), NULL,
4118 s->thread_args.pack_fds);
4119 if (err)
4120 return err;
4121 tog_free_refs();
4122 err = tog_load_refs(s->repo, 0);
4123 if (err)
4124 return err;
4125 err = got_commit_graph_open(&s->thread_args.graph,
4126 s->in_repo_path, !s->log_branches);
4127 if (err)
4128 return err;
4129 err = got_commit_graph_iter_start(s->thread_args.graph,
4130 s->start_id, s->repo, NULL, NULL);
4131 if (err)
4132 return err;
4133 free_commits(&s->real_commits);
4134 free_commits(&s->limit_commits);
4135 s->first_displayed_entry = NULL;
4136 s->last_displayed_entry = NULL;
4137 s->selected_entry = NULL;
4138 s->selected = 0;
4139 s->thread_args.log_complete = 0;
4140 s->quit = 0;
4141 s->thread_args.commits_needed = view->lines;
4142 s->matched_entry = NULL;
4143 s->search_entry = NULL;
4144 view->offset = 0;
4145 break;
4146 case 'R':
4147 view->count = 0;
4148 err = view_request_new(new_view, view, TOG_VIEW_REF);
4149 break;
4150 default:
4151 view->count = 0;
4152 break;
4155 return err;
4158 static const struct got_error *
4159 apply_unveil(const char *repo_path, const char *worktree_path)
4161 const struct got_error *error;
4163 #ifdef PROFILE
4164 if (unveil("gmon.out", "rwc") != 0)
4165 return got_error_from_errno2("unveil", "gmon.out");
4166 #endif
4167 if (repo_path && unveil(repo_path, "r") != 0)
4168 return got_error_from_errno2("unveil", repo_path);
4170 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4171 return got_error_from_errno2("unveil", worktree_path);
4173 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4174 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4176 error = got_privsep_unveil_exec_helpers();
4177 if (error != NULL)
4178 return error;
4180 if (unveil(NULL, NULL) != 0)
4181 return got_error_from_errno("unveil");
4183 return NULL;
4186 static const struct got_error *
4187 init_mock_term(const char *test_script_path)
4189 const struct got_error *err = NULL;
4191 if (test_script_path == NULL || *test_script_path == '\0')
4192 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4194 tog_io.f = fopen(test_script_path, "re");
4195 if (tog_io.f == NULL) {
4196 err = got_error_from_errno_fmt("fopen: %s",
4197 test_script_path);
4198 goto done;
4201 /* test mode, we don't want any output */
4202 tog_io.cout = fopen("/dev/null", "w+");
4203 if (tog_io.cout == NULL) {
4204 err = got_error_from_errno("fopen: /dev/null");
4205 goto done;
4208 tog_io.cin = fopen("/dev/tty", "r+");
4209 if (tog_io.cin == NULL) {
4210 err = got_error_from_errno("fopen: /dev/tty");
4211 goto done;
4214 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4215 err = got_error_from_errno("fseeko");
4216 goto done;
4219 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4220 err = got_error_msg(GOT_ERR_IO,
4221 "newterm: failed to initialise curses");
4223 using_mock_io = 1;
4225 done:
4226 if (err)
4227 tog_io_close();
4228 return err;
4231 static void
4232 init_curses(void)
4235 * Override default signal handlers before starting ncurses.
4236 * This should prevent ncurses from installing its own
4237 * broken cleanup() signal handler.
4239 signal(SIGWINCH, tog_sigwinch);
4240 signal(SIGPIPE, tog_sigpipe);
4241 signal(SIGCONT, tog_sigcont);
4242 signal(SIGINT, tog_sigint);
4243 signal(SIGTERM, tog_sigterm);
4245 if (using_mock_io) /* In test mode we use a fake terminal */
4246 return;
4248 initscr();
4250 cbreak();
4251 halfdelay(1); /* Fast refresh while initial view is loading. */
4252 noecho();
4253 nonl();
4254 intrflush(stdscr, FALSE);
4255 keypad(stdscr, TRUE);
4256 curs_set(0);
4257 if (getenv("TOG_COLORS") != NULL) {
4258 start_color();
4259 use_default_colors();
4262 return;
4265 static const struct got_error *
4266 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4267 struct got_repository *repo, struct got_worktree *worktree)
4269 const struct got_error *err = NULL;
4271 if (argc == 0) {
4272 *in_repo_path = strdup("/");
4273 if (*in_repo_path == NULL)
4274 return got_error_from_errno("strdup");
4275 return NULL;
4278 if (worktree) {
4279 const char *prefix = got_worktree_get_path_prefix(worktree);
4280 char *p;
4282 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4283 if (err)
4284 return err;
4285 if (asprintf(in_repo_path, "%s%s%s", prefix,
4286 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4287 p) == -1) {
4288 err = got_error_from_errno("asprintf");
4289 *in_repo_path = NULL;
4291 free(p);
4292 } else
4293 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4295 return err;
4298 static const struct got_error *
4299 cmd_log(int argc, char *argv[])
4301 const struct got_error *error;
4302 struct got_repository *repo = NULL;
4303 struct got_worktree *worktree = NULL;
4304 struct got_object_id *start_id = NULL;
4305 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4306 char *start_commit = NULL, *label = NULL;
4307 struct got_reference *ref = NULL;
4308 const char *head_ref_name = NULL;
4309 int ch, log_branches = 0;
4310 struct tog_view *view;
4311 int *pack_fds = NULL;
4313 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4314 switch (ch) {
4315 case 'b':
4316 log_branches = 1;
4317 break;
4318 case 'c':
4319 start_commit = optarg;
4320 break;
4321 case 'r':
4322 repo_path = realpath(optarg, NULL);
4323 if (repo_path == NULL)
4324 return got_error_from_errno2("realpath",
4325 optarg);
4326 break;
4327 default:
4328 usage_log();
4329 /* NOTREACHED */
4333 argc -= optind;
4334 argv += optind;
4336 if (argc > 1)
4337 usage_log();
4339 error = got_repo_pack_fds_open(&pack_fds);
4340 if (error != NULL)
4341 goto done;
4343 if (repo_path == NULL) {
4344 cwd = getcwd(NULL, 0);
4345 if (cwd == NULL)
4346 return got_error_from_errno("getcwd");
4347 error = got_worktree_open(&worktree, cwd);
4348 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4349 goto done;
4350 if (worktree)
4351 repo_path =
4352 strdup(got_worktree_get_repo_path(worktree));
4353 else
4354 repo_path = strdup(cwd);
4355 if (repo_path == NULL) {
4356 error = got_error_from_errno("strdup");
4357 goto done;
4361 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4362 if (error != NULL)
4363 goto done;
4365 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4366 repo, worktree);
4367 if (error)
4368 goto done;
4370 init_curses();
4372 error = apply_unveil(got_repo_get_path(repo),
4373 worktree ? got_worktree_get_root_path(worktree) : NULL);
4374 if (error)
4375 goto done;
4377 /* already loaded by tog_log_with_path()? */
4378 if (TAILQ_EMPTY(&tog_refs)) {
4379 error = tog_load_refs(repo, 0);
4380 if (error)
4381 goto done;
4384 if (start_commit == NULL) {
4385 error = got_repo_match_object_id(&start_id, &label,
4386 worktree ? got_worktree_get_head_ref_name(worktree) :
4387 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4388 if (error)
4389 goto done;
4390 head_ref_name = label;
4391 } else {
4392 error = got_ref_open(&ref, repo, start_commit, 0);
4393 if (error == NULL)
4394 head_ref_name = got_ref_get_name(ref);
4395 else if (error->code != GOT_ERR_NOT_REF)
4396 goto done;
4397 error = got_repo_match_object_id(&start_id, NULL,
4398 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4399 if (error)
4400 goto done;
4403 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4404 if (view == NULL) {
4405 error = got_error_from_errno("view_open");
4406 goto done;
4408 error = open_log_view(view, start_id, repo, head_ref_name,
4409 in_repo_path, log_branches);
4410 if (error)
4411 goto done;
4412 if (worktree) {
4413 /* Release work tree lock. */
4414 got_worktree_close(worktree);
4415 worktree = NULL;
4417 error = view_loop(view);
4418 done:
4419 free(in_repo_path);
4420 free(repo_path);
4421 free(cwd);
4422 free(start_id);
4423 free(label);
4424 if (ref)
4425 got_ref_close(ref);
4426 if (repo) {
4427 const struct got_error *close_err = got_repo_close(repo);
4428 if (error == NULL)
4429 error = close_err;
4431 if (worktree)
4432 got_worktree_close(worktree);
4433 if (pack_fds) {
4434 const struct got_error *pack_err =
4435 got_repo_pack_fds_close(pack_fds);
4436 if (error == NULL)
4437 error = pack_err;
4439 tog_free_refs();
4440 return error;
4443 __dead static void
4444 usage_diff(void)
4446 endwin();
4447 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4448 "object1 object2\n", getprogname());
4449 exit(1);
4452 static int
4453 match_line(const char *line, regex_t *regex, size_t nmatch,
4454 regmatch_t *regmatch)
4456 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4459 static struct tog_color *
4460 match_color(struct tog_colors *colors, const char *line)
4462 struct tog_color *tc = NULL;
4464 STAILQ_FOREACH(tc, colors, entry) {
4465 if (match_line(line, &tc->regex, 0, NULL))
4466 return tc;
4469 return NULL;
4472 static const struct got_error *
4473 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4474 WINDOW *window, int skipcol, regmatch_t *regmatch)
4476 const struct got_error *err = NULL;
4477 char *exstr = NULL;
4478 wchar_t *wline = NULL;
4479 int rme, rms, n, width, scrollx;
4480 int width0 = 0, width1 = 0, width2 = 0;
4481 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4483 *wtotal = 0;
4485 rms = regmatch->rm_so;
4486 rme = regmatch->rm_eo;
4488 err = expand_tab(&exstr, line);
4489 if (err)
4490 return err;
4492 /* Split the line into 3 segments, according to match offsets. */
4493 seg0 = strndup(exstr, rms);
4494 if (seg0 == NULL) {
4495 err = got_error_from_errno("strndup");
4496 goto done;
4498 seg1 = strndup(exstr + rms, rme - rms);
4499 if (seg1 == NULL) {
4500 err = got_error_from_errno("strndup");
4501 goto done;
4503 seg2 = strdup(exstr + rme);
4504 if (seg2 == NULL) {
4505 err = got_error_from_errno("strndup");
4506 goto done;
4509 /* draw up to matched token if we haven't scrolled past it */
4510 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4511 col_tab_align, 1);
4512 if (err)
4513 goto done;
4514 n = MAX(width0 - skipcol, 0);
4515 if (n) {
4516 free(wline);
4517 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4518 wlimit, col_tab_align, 1);
4519 if (err)
4520 goto done;
4521 waddwstr(window, &wline[scrollx]);
4522 wlimit -= width;
4523 *wtotal += width;
4526 if (wlimit > 0) {
4527 int i = 0, w = 0;
4528 size_t wlen;
4530 free(wline);
4531 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4532 col_tab_align, 1);
4533 if (err)
4534 goto done;
4535 wlen = wcslen(wline);
4536 while (i < wlen) {
4537 width = wcwidth(wline[i]);
4538 if (width == -1) {
4539 /* should not happen, tabs are expanded */
4540 err = got_error(GOT_ERR_RANGE);
4541 goto done;
4543 if (width0 + w + width > skipcol)
4544 break;
4545 w += width;
4546 i++;
4548 /* draw (visible part of) matched token (if scrolled into it) */
4549 if (width1 - w > 0) {
4550 wattron(window, A_STANDOUT);
4551 waddwstr(window, &wline[i]);
4552 wattroff(window, A_STANDOUT);
4553 wlimit -= (width1 - w);
4554 *wtotal += (width1 - w);
4558 if (wlimit > 0) { /* draw rest of line */
4559 free(wline);
4560 if (skipcol > width0 + width1) {
4561 err = format_line(&wline, &width2, &scrollx, seg2,
4562 skipcol - (width0 + width1), wlimit,
4563 col_tab_align, 1);
4564 if (err)
4565 goto done;
4566 waddwstr(window, &wline[scrollx]);
4567 } else {
4568 err = format_line(&wline, &width2, NULL, seg2, 0,
4569 wlimit, col_tab_align, 1);
4570 if (err)
4571 goto done;
4572 waddwstr(window, wline);
4574 *wtotal += width2;
4576 done:
4577 free(wline);
4578 free(exstr);
4579 free(seg0);
4580 free(seg1);
4581 free(seg2);
4582 return err;
4585 static int
4586 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4588 FILE *f = NULL;
4589 int *eof, *first, *selected;
4591 if (view->type == TOG_VIEW_DIFF) {
4592 struct tog_diff_view_state *s = &view->state.diff;
4594 first = &s->first_displayed_line;
4595 selected = first;
4596 eof = &s->eof;
4597 f = s->f;
4598 } else if (view->type == TOG_VIEW_HELP) {
4599 struct tog_help_view_state *s = &view->state.help;
4601 first = &s->first_displayed_line;
4602 selected = first;
4603 eof = &s->eof;
4604 f = s->f;
4605 } else if (view->type == TOG_VIEW_BLAME) {
4606 struct tog_blame_view_state *s = &view->state.blame;
4608 first = &s->first_displayed_line;
4609 selected = &s->selected_line;
4610 eof = &s->eof;
4611 f = s->blame.f;
4612 } else
4613 return 0;
4615 /* Center gline in the middle of the page like vi(1). */
4616 if (*lineno < view->gline - (view->nlines - 3) / 2)
4617 return 0;
4618 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4619 rewind(f);
4620 *eof = 0;
4621 *first = 1;
4622 *lineno = 0;
4623 *nprinted = 0;
4624 return 0;
4627 *selected = view->gline <= (view->nlines - 3) / 2 ?
4628 view->gline : (view->nlines - 3) / 2 + 1;
4629 view->gline = 0;
4631 return 1;
4634 static const struct got_error *
4635 draw_file(struct tog_view *view, const char *header)
4637 struct tog_diff_view_state *s = &view->state.diff;
4638 regmatch_t *regmatch = &view->regmatch;
4639 const struct got_error *err;
4640 int nprinted = 0;
4641 char *line;
4642 size_t linesize = 0;
4643 ssize_t linelen;
4644 wchar_t *wline;
4645 int width;
4646 int max_lines = view->nlines;
4647 int nlines = s->nlines;
4648 off_t line_offset;
4650 s->lineno = s->first_displayed_line - 1;
4651 line_offset = s->lines[s->first_displayed_line - 1].offset;
4652 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4653 return got_error_from_errno("fseek");
4655 werase(view->window);
4657 if (view->gline > s->nlines - 1)
4658 view->gline = s->nlines - 1;
4660 if (header) {
4661 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4662 1 : view->gline - (view->nlines - 3) / 2 :
4663 s->lineno + s->selected_line;
4665 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4666 return got_error_from_errno("asprintf");
4667 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4668 0, 0);
4669 free(line);
4670 if (err)
4671 return err;
4673 if (view_needs_focus_indication(view))
4674 wstandout(view->window);
4675 waddwstr(view->window, wline);
4676 free(wline);
4677 wline = NULL;
4678 while (width++ < view->ncols)
4679 waddch(view->window, ' ');
4680 if (view_needs_focus_indication(view))
4681 wstandend(view->window);
4683 if (max_lines <= 1)
4684 return NULL;
4685 max_lines--;
4688 s->eof = 0;
4689 view->maxx = 0;
4690 line = NULL;
4691 while (max_lines > 0 && nprinted < max_lines) {
4692 enum got_diff_line_type linetype;
4693 attr_t attr = 0;
4695 linelen = getline(&line, &linesize, s->f);
4696 if (linelen == -1) {
4697 if (feof(s->f)) {
4698 s->eof = 1;
4699 break;
4701 free(line);
4702 return got_ferror(s->f, GOT_ERR_IO);
4705 if (++s->lineno < s->first_displayed_line)
4706 continue;
4707 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4708 continue;
4709 if (s->lineno == view->hiline)
4710 attr = A_STANDOUT;
4712 /* Set view->maxx based on full line length. */
4713 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4714 view->x ? 1 : 0);
4715 if (err) {
4716 free(line);
4717 return err;
4719 view->maxx = MAX(view->maxx, width);
4720 free(wline);
4721 wline = NULL;
4723 linetype = s->lines[s->lineno].type;
4724 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4725 linetype < GOT_DIFF_LINE_CONTEXT)
4726 attr |= COLOR_PAIR(linetype);
4727 if (attr)
4728 wattron(view->window, attr);
4729 if (s->first_displayed_line + nprinted == s->matched_line &&
4730 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4731 err = add_matched_line(&width, line, view->ncols, 0,
4732 view->window, view->x, regmatch);
4733 if (err) {
4734 free(line);
4735 return err;
4737 } else {
4738 int skip;
4739 err = format_line(&wline, &width, &skip, line,
4740 view->x, view->ncols, 0, view->x ? 1 : 0);
4741 if (err) {
4742 free(line);
4743 return err;
4745 waddwstr(view->window, &wline[skip]);
4746 free(wline);
4747 wline = NULL;
4749 if (s->lineno == view->hiline) {
4750 /* highlight full gline length */
4751 while (width++ < view->ncols)
4752 waddch(view->window, ' ');
4753 } else {
4754 if (width <= view->ncols - 1)
4755 waddch(view->window, '\n');
4757 if (attr)
4758 wattroff(view->window, attr);
4759 if (++nprinted == 1)
4760 s->first_displayed_line = s->lineno;
4762 free(line);
4763 if (nprinted >= 1)
4764 s->last_displayed_line = s->first_displayed_line +
4765 (nprinted - 1);
4766 else
4767 s->last_displayed_line = s->first_displayed_line;
4769 view_border(view);
4771 if (s->eof) {
4772 while (nprinted < view->nlines) {
4773 waddch(view->window, '\n');
4774 nprinted++;
4777 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4778 view->ncols, 0, 0);
4779 if (err) {
4780 return err;
4783 wstandout(view->window);
4784 waddwstr(view->window, wline);
4785 free(wline);
4786 wline = NULL;
4787 wstandend(view->window);
4790 return NULL;
4793 static char *
4794 get_datestr(time_t *time, char *datebuf)
4796 struct tm mytm, *tm;
4797 char *p, *s;
4799 tm = gmtime_r(time, &mytm);
4800 if (tm == NULL)
4801 return NULL;
4802 s = asctime_r(tm, datebuf);
4803 if (s == NULL)
4804 return NULL;
4805 p = strchr(s, '\n');
4806 if (p)
4807 *p = '\0';
4808 return s;
4811 static const struct got_error *
4812 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4813 off_t off, uint8_t type)
4815 struct got_diff_line *p;
4817 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4818 if (p == NULL)
4819 return got_error_from_errno("reallocarray");
4820 *lines = p;
4821 (*lines)[*nlines].offset = off;
4822 (*lines)[*nlines].type = type;
4823 (*nlines)++;
4825 return NULL;
4828 static const struct got_error *
4829 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4830 struct got_diff_line *s_lines, size_t s_nlines)
4832 struct got_diff_line *p;
4833 char buf[BUFSIZ];
4834 size_t i, r;
4836 if (fseeko(src, 0L, SEEK_SET) == -1)
4837 return got_error_from_errno("fseeko");
4839 for (;;) {
4840 r = fread(buf, 1, sizeof(buf), src);
4841 if (r == 0) {
4842 if (ferror(src))
4843 return got_error_from_errno("fread");
4844 if (feof(src))
4845 break;
4847 if (fwrite(buf, 1, r, dst) != r)
4848 return got_ferror(dst, GOT_ERR_IO);
4851 if (s_nlines == 0 && *d_nlines == 0)
4852 return NULL;
4855 * If commit info was in dst, increment line offsets
4856 * of the appended diff content, but skip s_lines[0]
4857 * because offset zero is already in *d_lines.
4859 if (*d_nlines > 0) {
4860 for (i = 1; i < s_nlines; ++i)
4861 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4863 if (s_nlines > 0) {
4864 --s_nlines;
4865 ++s_lines;
4869 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4870 if (p == NULL) {
4871 /* d_lines is freed in close_diff_view() */
4872 return got_error_from_errno("reallocarray");
4875 *d_lines = p;
4877 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4878 *d_nlines += s_nlines;
4880 return NULL;
4883 static const struct got_error *
4884 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4885 struct got_object_id *commit_id, struct got_reflist_head *refs,
4886 struct got_repository *repo, int ignore_ws, int force_text_diff,
4887 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4889 const struct got_error *err = NULL;
4890 char datebuf[26], *datestr;
4891 struct got_commit_object *commit;
4892 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4893 time_t committer_time;
4894 const char *author, *committer;
4895 char *refs_str = NULL;
4896 struct got_pathlist_entry *pe;
4897 off_t outoff = 0;
4898 int n;
4900 if (refs) {
4901 err = build_refs_str(&refs_str, refs, commit_id, repo);
4902 if (err)
4903 return err;
4906 err = got_object_open_as_commit(&commit, repo, commit_id);
4907 if (err)
4908 return err;
4910 err = got_object_id_str(&id_str, commit_id);
4911 if (err) {
4912 err = got_error_from_errno("got_object_id_str");
4913 goto done;
4916 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4917 if (err)
4918 goto done;
4920 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4921 refs_str ? refs_str : "", refs_str ? ")" : "");
4922 if (n < 0) {
4923 err = got_error_from_errno("fprintf");
4924 goto done;
4926 outoff += n;
4927 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4928 if (err)
4929 goto done;
4931 n = fprintf(outfile, "from: %s\n",
4932 got_object_commit_get_author(commit));
4933 if (n < 0) {
4934 err = got_error_from_errno("fprintf");
4935 goto done;
4937 outoff += n;
4938 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4939 if (err)
4940 goto done;
4942 author = got_object_commit_get_author(commit);
4943 committer = got_object_commit_get_committer(commit);
4944 if (strcmp(author, committer) != 0) {
4945 n = fprintf(outfile, "via: %s\n", committer);
4946 if (n < 0) {
4947 err = got_error_from_errno("fprintf");
4948 goto done;
4950 outoff += n;
4951 err = add_line_metadata(lines, nlines, outoff,
4952 GOT_DIFF_LINE_AUTHOR);
4953 if (err)
4954 goto done;
4956 committer_time = got_object_commit_get_committer_time(commit);
4957 datestr = get_datestr(&committer_time, datebuf);
4958 if (datestr) {
4959 n = fprintf(outfile, "date: %s UTC\n", datestr);
4960 if (n < 0) {
4961 err = got_error_from_errno("fprintf");
4962 goto done;
4964 outoff += n;
4965 err = add_line_metadata(lines, nlines, outoff,
4966 GOT_DIFF_LINE_DATE);
4967 if (err)
4968 goto done;
4970 if (got_object_commit_get_nparents(commit) > 1) {
4971 const struct got_object_id_queue *parent_ids;
4972 struct got_object_qid *qid;
4973 int pn = 1;
4974 parent_ids = got_object_commit_get_parent_ids(commit);
4975 STAILQ_FOREACH(qid, parent_ids, entry) {
4976 err = got_object_id_str(&id_str, &qid->id);
4977 if (err)
4978 goto done;
4979 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4980 if (n < 0) {
4981 err = got_error_from_errno("fprintf");
4982 goto done;
4984 outoff += n;
4985 err = add_line_metadata(lines, nlines, outoff,
4986 GOT_DIFF_LINE_META);
4987 if (err)
4988 goto done;
4989 free(id_str);
4990 id_str = NULL;
4994 err = got_object_commit_get_logmsg(&logmsg, commit);
4995 if (err)
4996 goto done;
4997 s = logmsg;
4998 while ((line = strsep(&s, "\n")) != NULL) {
4999 n = fprintf(outfile, "%s\n", line);
5000 if (n < 0) {
5001 err = got_error_from_errno("fprintf");
5002 goto done;
5004 outoff += n;
5005 err = add_line_metadata(lines, nlines, outoff,
5006 GOT_DIFF_LINE_LOGMSG);
5007 if (err)
5008 goto done;
5011 TAILQ_FOREACH(pe, dsa->paths, entry) {
5012 struct got_diff_changed_path *cp = pe->data;
5013 int pad = dsa->max_path_len - pe->path_len + 1;
5015 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5016 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5017 dsa->rm_cols + 1, cp->rm);
5018 if (n < 0) {
5019 err = got_error_from_errno("fprintf");
5020 goto done;
5022 outoff += n;
5023 err = add_line_metadata(lines, nlines, outoff,
5024 GOT_DIFF_LINE_CHANGES);
5025 if (err)
5026 goto done;
5029 fputc('\n', outfile);
5030 outoff++;
5031 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5032 if (err)
5033 goto done;
5035 n = fprintf(outfile,
5036 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5037 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5038 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5039 if (n < 0) {
5040 err = got_error_from_errno("fprintf");
5041 goto done;
5043 outoff += n;
5044 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5045 if (err)
5046 goto done;
5048 fputc('\n', outfile);
5049 outoff++;
5050 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5051 done:
5052 free(id_str);
5053 free(logmsg);
5054 free(refs_str);
5055 got_object_commit_close(commit);
5056 if (err) {
5057 free(*lines);
5058 *lines = NULL;
5059 *nlines = 0;
5061 return err;
5064 static const struct got_error *
5065 create_diff(struct tog_diff_view_state *s)
5067 const struct got_error *err = NULL;
5068 FILE *f = NULL, *tmp_diff_file = NULL;
5069 int obj_type;
5070 struct got_diff_line *lines = NULL;
5071 struct got_pathlist_head changed_paths;
5073 TAILQ_INIT(&changed_paths);
5075 free(s->lines);
5076 s->lines = malloc(sizeof(*s->lines));
5077 if (s->lines == NULL)
5078 return got_error_from_errno("malloc");
5079 s->nlines = 0;
5081 f = got_opentemp();
5082 if (f == NULL) {
5083 err = got_error_from_errno("got_opentemp");
5084 goto done;
5086 tmp_diff_file = got_opentemp();
5087 if (tmp_diff_file == NULL) {
5088 err = got_error_from_errno("got_opentemp");
5089 goto done;
5091 if (s->f && fclose(s->f) == EOF) {
5092 err = got_error_from_errno("fclose");
5093 goto done;
5095 s->f = f;
5097 if (s->id1)
5098 err = got_object_get_type(&obj_type, s->repo, s->id1);
5099 else
5100 err = got_object_get_type(&obj_type, s->repo, s->id2);
5101 if (err)
5102 goto done;
5104 switch (obj_type) {
5105 case GOT_OBJ_TYPE_BLOB:
5106 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5107 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5108 s->label1, s->label2, tog_diff_algo, s->diff_context,
5109 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5110 s->f);
5111 break;
5112 case GOT_OBJ_TYPE_TREE:
5113 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5114 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5115 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5116 s->force_text_diff, NULL, s->repo, s->f);
5117 break;
5118 case GOT_OBJ_TYPE_COMMIT: {
5119 const struct got_object_id_queue *parent_ids;
5120 struct got_object_qid *pid;
5121 struct got_commit_object *commit2;
5122 struct got_reflist_head *refs;
5123 size_t nlines = 0;
5124 struct got_diffstat_cb_arg dsa = {
5125 0, 0, 0, 0, 0, 0,
5126 &changed_paths,
5127 s->ignore_whitespace,
5128 s->force_text_diff,
5129 tog_diff_algo
5132 lines = malloc(sizeof(*lines));
5133 if (lines == NULL) {
5134 err = got_error_from_errno("malloc");
5135 goto done;
5138 /* build diff first in tmp file then append to commit info */
5139 err = got_diff_objects_as_commits(&lines, &nlines,
5140 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5141 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5142 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5143 if (err)
5144 break;
5146 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5147 if (err)
5148 goto done;
5149 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5150 /* Show commit info if we're diffing to a parent/root commit. */
5151 if (s->id1 == NULL) {
5152 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5153 refs, s->repo, s->ignore_whitespace,
5154 s->force_text_diff, &dsa, s->f);
5155 if (err)
5156 goto done;
5157 } else {
5158 parent_ids = got_object_commit_get_parent_ids(commit2);
5159 STAILQ_FOREACH(pid, parent_ids, entry) {
5160 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5161 err = write_commit_info(&s->lines,
5162 &s->nlines, s->id2, refs, s->repo,
5163 s->ignore_whitespace,
5164 s->force_text_diff, &dsa, s->f);
5165 if (err)
5166 goto done;
5167 break;
5171 got_object_commit_close(commit2);
5173 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5174 lines, nlines);
5175 break;
5177 default:
5178 err = got_error(GOT_ERR_OBJ_TYPE);
5179 break;
5181 done:
5182 free(lines);
5183 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5184 if (s->f && fflush(s->f) != 0 && err == NULL)
5185 err = got_error_from_errno("fflush");
5186 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5187 err = got_error_from_errno("fclose");
5188 return err;
5191 static void
5192 diff_view_indicate_progress(struct tog_view *view)
5194 mvwaddstr(view->window, 0, 0, "diffing...");
5195 update_panels();
5196 doupdate();
5199 static const struct got_error *
5200 search_start_diff_view(struct tog_view *view)
5202 struct tog_diff_view_state *s = &view->state.diff;
5204 s->matched_line = 0;
5205 return NULL;
5208 static void
5209 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5210 size_t *nlines, int **first, int **last, int **match, int **selected)
5212 struct tog_diff_view_state *s = &view->state.diff;
5214 *f = s->f;
5215 *nlines = s->nlines;
5216 *line_offsets = NULL;
5217 *match = &s->matched_line;
5218 *first = &s->first_displayed_line;
5219 *last = &s->last_displayed_line;
5220 *selected = &s->selected_line;
5223 static const struct got_error *
5224 search_next_view_match(struct tog_view *view)
5226 const struct got_error *err = NULL;
5227 FILE *f;
5228 int lineno;
5229 char *line = NULL;
5230 size_t linesize = 0;
5231 ssize_t linelen;
5232 off_t *line_offsets;
5233 size_t nlines = 0;
5234 int *first, *last, *match, *selected;
5236 if (!view->search_setup)
5237 return got_error_msg(GOT_ERR_NOT_IMPL,
5238 "view search not supported");
5239 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5240 &match, &selected);
5242 if (!view->searching) {
5243 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5244 return NULL;
5247 if (*match) {
5248 if (view->searching == TOG_SEARCH_FORWARD)
5249 lineno = *first + 1;
5250 else
5251 lineno = *first - 1;
5252 } else
5253 lineno = *first - 1 + *selected;
5255 while (1) {
5256 off_t offset;
5258 if (lineno <= 0 || lineno > nlines) {
5259 if (*match == 0) {
5260 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5261 break;
5264 if (view->searching == TOG_SEARCH_FORWARD)
5265 lineno = 1;
5266 else
5267 lineno = nlines;
5270 offset = view->type == TOG_VIEW_DIFF ?
5271 view->state.diff.lines[lineno - 1].offset :
5272 line_offsets[lineno - 1];
5273 if (fseeko(f, offset, SEEK_SET) != 0) {
5274 free(line);
5275 return got_error_from_errno("fseeko");
5277 linelen = getline(&line, &linesize, f);
5278 if (linelen != -1) {
5279 char *exstr;
5280 err = expand_tab(&exstr, line);
5281 if (err)
5282 break;
5283 if (match_line(exstr, &view->regex, 1,
5284 &view->regmatch)) {
5285 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5286 *match = lineno;
5287 free(exstr);
5288 break;
5290 free(exstr);
5292 if (view->searching == TOG_SEARCH_FORWARD)
5293 lineno++;
5294 else
5295 lineno--;
5297 free(line);
5299 if (*match) {
5300 *first = *match;
5301 *selected = 1;
5304 return err;
5307 static const struct got_error *
5308 close_diff_view(struct tog_view *view)
5310 const struct got_error *err = NULL;
5311 struct tog_diff_view_state *s = &view->state.diff;
5313 free(s->id1);
5314 s->id1 = NULL;
5315 free(s->id2);
5316 s->id2 = NULL;
5317 if (s->f && fclose(s->f) == EOF)
5318 err = got_error_from_errno("fclose");
5319 s->f = NULL;
5320 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5321 err = got_error_from_errno("fclose");
5322 s->f1 = NULL;
5323 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5324 err = got_error_from_errno("fclose");
5325 s->f2 = NULL;
5326 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5327 err = got_error_from_errno("close");
5328 s->fd1 = -1;
5329 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5330 err = got_error_from_errno("close");
5331 s->fd2 = -1;
5332 free(s->lines);
5333 s->lines = NULL;
5334 s->nlines = 0;
5335 return err;
5338 static const struct got_error *
5339 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5340 struct got_object_id *id2, const char *label1, const char *label2,
5341 int diff_context, int ignore_whitespace, int force_text_diff,
5342 struct tog_view *parent_view, struct got_repository *repo)
5344 const struct got_error *err;
5345 struct tog_diff_view_state *s = &view->state.diff;
5347 memset(s, 0, sizeof(*s));
5348 s->fd1 = -1;
5349 s->fd2 = -1;
5351 if (id1 != NULL && id2 != NULL) {
5352 int type1, type2;
5354 err = got_object_get_type(&type1, repo, id1);
5355 if (err)
5356 goto done;
5357 err = got_object_get_type(&type2, repo, id2);
5358 if (err)
5359 goto done;
5361 if (type1 != type2) {
5362 err = got_error(GOT_ERR_OBJ_TYPE);
5363 goto done;
5366 s->first_displayed_line = 1;
5367 s->last_displayed_line = view->nlines;
5368 s->selected_line = 1;
5369 s->repo = repo;
5370 s->id1 = id1;
5371 s->id2 = id2;
5372 s->label1 = label1;
5373 s->label2 = label2;
5375 if (id1) {
5376 s->id1 = got_object_id_dup(id1);
5377 if (s->id1 == NULL) {
5378 err = got_error_from_errno("got_object_id_dup");
5379 goto done;
5381 } else
5382 s->id1 = NULL;
5384 s->id2 = got_object_id_dup(id2);
5385 if (s->id2 == NULL) {
5386 err = got_error_from_errno("got_object_id_dup");
5387 goto done;
5390 s->f1 = got_opentemp();
5391 if (s->f1 == NULL) {
5392 err = got_error_from_errno("got_opentemp");
5393 goto done;
5396 s->f2 = got_opentemp();
5397 if (s->f2 == NULL) {
5398 err = got_error_from_errno("got_opentemp");
5399 goto done;
5402 s->fd1 = got_opentempfd();
5403 if (s->fd1 == -1) {
5404 err = got_error_from_errno("got_opentempfd");
5405 goto done;
5408 s->fd2 = got_opentempfd();
5409 if (s->fd2 == -1) {
5410 err = got_error_from_errno("got_opentempfd");
5411 goto done;
5414 s->diff_context = diff_context;
5415 s->ignore_whitespace = ignore_whitespace;
5416 s->force_text_diff = force_text_diff;
5417 s->parent_view = parent_view;
5418 s->repo = repo;
5420 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5421 int rc;
5423 rc = init_pair(GOT_DIFF_LINE_MINUS,
5424 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5425 if (rc != ERR)
5426 rc = init_pair(GOT_DIFF_LINE_PLUS,
5427 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5428 if (rc != ERR)
5429 rc = init_pair(GOT_DIFF_LINE_HUNK,
5430 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5431 if (rc != ERR)
5432 rc = init_pair(GOT_DIFF_LINE_META,
5433 get_color_value("TOG_COLOR_DIFF_META"), -1);
5434 if (rc != ERR)
5435 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5436 get_color_value("TOG_COLOR_DIFF_META"), -1);
5437 if (rc != ERR)
5438 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5439 get_color_value("TOG_COLOR_DIFF_META"), -1);
5440 if (rc != ERR)
5441 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5442 get_color_value("TOG_COLOR_DIFF_META"), -1);
5443 if (rc != ERR)
5444 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5445 get_color_value("TOG_COLOR_AUTHOR"), -1);
5446 if (rc != ERR)
5447 rc = init_pair(GOT_DIFF_LINE_DATE,
5448 get_color_value("TOG_COLOR_DATE"), -1);
5449 if (rc == ERR) {
5450 err = got_error(GOT_ERR_RANGE);
5451 goto done;
5455 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5456 view_is_splitscreen(view))
5457 show_log_view(parent_view); /* draw border */
5458 diff_view_indicate_progress(view);
5460 err = create_diff(s);
5462 view->show = show_diff_view;
5463 view->input = input_diff_view;
5464 view->reset = reset_diff_view;
5465 view->close = close_diff_view;
5466 view->search_start = search_start_diff_view;
5467 view->search_setup = search_setup_diff_view;
5468 view->search_next = search_next_view_match;
5469 done:
5470 if (err) {
5471 if (view->close == NULL)
5472 close_diff_view(view);
5473 view_close(view);
5475 return err;
5478 static const struct got_error *
5479 show_diff_view(struct tog_view *view)
5481 const struct got_error *err;
5482 struct tog_diff_view_state *s = &view->state.diff;
5483 char *id_str1 = NULL, *id_str2, *header;
5484 const char *label1, *label2;
5486 if (s->id1) {
5487 err = got_object_id_str(&id_str1, s->id1);
5488 if (err)
5489 return err;
5490 label1 = s->label1 ? s->label1 : id_str1;
5491 } else
5492 label1 = "/dev/null";
5494 err = got_object_id_str(&id_str2, s->id2);
5495 if (err)
5496 return err;
5497 label2 = s->label2 ? s->label2 : id_str2;
5499 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5500 err = got_error_from_errno("asprintf");
5501 free(id_str1);
5502 free(id_str2);
5503 return err;
5505 free(id_str1);
5506 free(id_str2);
5508 err = draw_file(view, header);
5509 free(header);
5510 return err;
5513 static const struct got_error *
5514 set_selected_commit(struct tog_diff_view_state *s,
5515 struct commit_queue_entry *entry)
5517 const struct got_error *err;
5518 const struct got_object_id_queue *parent_ids;
5519 struct got_commit_object *selected_commit;
5520 struct got_object_qid *pid;
5522 free(s->id2);
5523 s->id2 = got_object_id_dup(entry->id);
5524 if (s->id2 == NULL)
5525 return got_error_from_errno("got_object_id_dup");
5527 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5528 if (err)
5529 return err;
5530 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5531 free(s->id1);
5532 pid = STAILQ_FIRST(parent_ids);
5533 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5534 got_object_commit_close(selected_commit);
5535 return NULL;
5538 static const struct got_error *
5539 reset_diff_view(struct tog_view *view)
5541 struct tog_diff_view_state *s = &view->state.diff;
5543 view->count = 0;
5544 wclear(view->window);
5545 s->first_displayed_line = 1;
5546 s->last_displayed_line = view->nlines;
5547 s->matched_line = 0;
5548 diff_view_indicate_progress(view);
5549 return create_diff(s);
5552 static void
5553 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5555 int start, i;
5557 i = start = s->first_displayed_line - 1;
5559 while (s->lines[i].type != type) {
5560 if (i == 0)
5561 i = s->nlines - 1;
5562 if (--i == start)
5563 return; /* do nothing, requested type not in file */
5566 s->selected_line = 1;
5567 s->first_displayed_line = i;
5570 static void
5571 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5573 int start, i;
5575 i = start = s->first_displayed_line + 1;
5577 while (s->lines[i].type != type) {
5578 if (i == s->nlines - 1)
5579 i = 0;
5580 if (++i == start)
5581 return; /* do nothing, requested type not in file */
5584 s->selected_line = 1;
5585 s->first_displayed_line = i;
5588 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5589 int, int, int);
5590 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5591 int, int);
5593 static const struct got_error *
5594 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5596 const struct got_error *err = NULL;
5597 struct tog_diff_view_state *s = &view->state.diff;
5598 struct tog_log_view_state *ls;
5599 struct commit_queue_entry *old_selected_entry;
5600 char *line = NULL;
5601 size_t linesize = 0;
5602 ssize_t linelen;
5603 int i, nscroll = view->nlines - 1, up = 0;
5605 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5607 switch (ch) {
5608 case '0':
5609 case '$':
5610 case KEY_RIGHT:
5611 case 'l':
5612 case KEY_LEFT:
5613 case 'h':
5614 horizontal_scroll_input(view, ch);
5615 break;
5616 case 'a':
5617 case 'w':
5618 if (ch == 'a') {
5619 s->force_text_diff = !s->force_text_diff;
5620 view->action = s->force_text_diff ?
5621 "force ASCII text enabled" :
5622 "force ASCII text disabled";
5624 else if (ch == 'w') {
5625 s->ignore_whitespace = !s->ignore_whitespace;
5626 view->action = s->ignore_whitespace ?
5627 "ignore whitespace enabled" :
5628 "ignore whitespace disabled";
5630 err = reset_diff_view(view);
5631 break;
5632 case 'g':
5633 case KEY_HOME:
5634 s->first_displayed_line = 1;
5635 view->count = 0;
5636 break;
5637 case 'G':
5638 case KEY_END:
5639 view->count = 0;
5640 if (s->eof)
5641 break;
5643 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5644 s->eof = 1;
5645 break;
5646 case 'k':
5647 case KEY_UP:
5648 case CTRL('p'):
5649 if (s->first_displayed_line > 1)
5650 s->first_displayed_line--;
5651 else
5652 view->count = 0;
5653 break;
5654 case CTRL('u'):
5655 case 'u':
5656 nscroll /= 2;
5657 /* FALL THROUGH */
5658 case KEY_PPAGE:
5659 case CTRL('b'):
5660 case 'b':
5661 if (s->first_displayed_line == 1) {
5662 view->count = 0;
5663 break;
5665 i = 0;
5666 while (i++ < nscroll && s->first_displayed_line > 1)
5667 s->first_displayed_line--;
5668 break;
5669 case 'j':
5670 case KEY_DOWN:
5671 case CTRL('n'):
5672 if (!s->eof)
5673 s->first_displayed_line++;
5674 else
5675 view->count = 0;
5676 break;
5677 case CTRL('d'):
5678 case 'd':
5679 nscroll /= 2;
5680 /* FALL THROUGH */
5681 case KEY_NPAGE:
5682 case CTRL('f'):
5683 case 'f':
5684 case ' ':
5685 if (s->eof) {
5686 view->count = 0;
5687 break;
5689 i = 0;
5690 while (!s->eof && i++ < nscroll) {
5691 linelen = getline(&line, &linesize, s->f);
5692 s->first_displayed_line++;
5693 if (linelen == -1) {
5694 if (feof(s->f)) {
5695 s->eof = 1;
5696 } else
5697 err = got_ferror(s->f, GOT_ERR_IO);
5698 break;
5701 free(line);
5702 break;
5703 case '(':
5704 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5705 break;
5706 case ')':
5707 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5708 break;
5709 case '{':
5710 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5711 break;
5712 case '}':
5713 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5714 break;
5715 case '[':
5716 if (s->diff_context > 0) {
5717 s->diff_context--;
5718 s->matched_line = 0;
5719 diff_view_indicate_progress(view);
5720 err = create_diff(s);
5721 if (s->first_displayed_line + view->nlines - 1 >
5722 s->nlines) {
5723 s->first_displayed_line = 1;
5724 s->last_displayed_line = view->nlines;
5726 } else
5727 view->count = 0;
5728 break;
5729 case ']':
5730 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5731 s->diff_context++;
5732 s->matched_line = 0;
5733 diff_view_indicate_progress(view);
5734 err = create_diff(s);
5735 } else
5736 view->count = 0;
5737 break;
5738 case '<':
5739 case ',':
5740 case 'K':
5741 up = 1;
5742 /* FALL THROUGH */
5743 case '>':
5744 case '.':
5745 case 'J':
5746 if (s->parent_view == NULL) {
5747 view->count = 0;
5748 break;
5750 s->parent_view->count = view->count;
5752 if (s->parent_view->type == TOG_VIEW_LOG) {
5753 ls = &s->parent_view->state.log;
5754 old_selected_entry = ls->selected_entry;
5756 err = input_log_view(NULL, s->parent_view,
5757 up ? KEY_UP : KEY_DOWN);
5758 if (err)
5759 break;
5760 view->count = s->parent_view->count;
5762 if (old_selected_entry == ls->selected_entry)
5763 break;
5765 err = set_selected_commit(s, ls->selected_entry);
5766 if (err)
5767 break;
5768 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5769 struct tog_blame_view_state *bs;
5770 struct got_object_id *id, *prev_id;
5772 bs = &s->parent_view->state.blame;
5773 prev_id = get_annotation_for_line(bs->blame.lines,
5774 bs->blame.nlines, bs->last_diffed_line);
5776 err = input_blame_view(&view, s->parent_view,
5777 up ? KEY_UP : KEY_DOWN);
5778 if (err)
5779 break;
5780 view->count = s->parent_view->count;
5782 if (prev_id == NULL)
5783 break;
5784 id = get_selected_commit_id(bs->blame.lines,
5785 bs->blame.nlines, bs->first_displayed_line,
5786 bs->selected_line);
5787 if (id == NULL)
5788 break;
5790 if (!got_object_id_cmp(prev_id, id))
5791 break;
5793 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5794 if (err)
5795 break;
5797 s->first_displayed_line = 1;
5798 s->last_displayed_line = view->nlines;
5799 s->matched_line = 0;
5800 view->x = 0;
5802 diff_view_indicate_progress(view);
5803 err = create_diff(s);
5804 break;
5805 default:
5806 view->count = 0;
5807 break;
5810 return err;
5813 static const struct got_error *
5814 cmd_diff(int argc, char *argv[])
5816 const struct got_error *error;
5817 struct got_repository *repo = NULL;
5818 struct got_worktree *worktree = NULL;
5819 struct got_object_id *id1 = NULL, *id2 = NULL;
5820 char *repo_path = NULL, *cwd = NULL;
5821 char *id_str1 = NULL, *id_str2 = NULL;
5822 char *label1 = NULL, *label2 = NULL;
5823 int diff_context = 3, ignore_whitespace = 0;
5824 int ch, force_text_diff = 0;
5825 const char *errstr;
5826 struct tog_view *view;
5827 int *pack_fds = NULL;
5829 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5830 switch (ch) {
5831 case 'a':
5832 force_text_diff = 1;
5833 break;
5834 case 'C':
5835 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5836 &errstr);
5837 if (errstr != NULL)
5838 errx(1, "number of context lines is %s: %s",
5839 errstr, errstr);
5840 break;
5841 case 'r':
5842 repo_path = realpath(optarg, NULL);
5843 if (repo_path == NULL)
5844 return got_error_from_errno2("realpath",
5845 optarg);
5846 got_path_strip_trailing_slashes(repo_path);
5847 break;
5848 case 'w':
5849 ignore_whitespace = 1;
5850 break;
5851 default:
5852 usage_diff();
5853 /* NOTREACHED */
5857 argc -= optind;
5858 argv += optind;
5860 if (argc == 0) {
5861 usage_diff(); /* TODO show local worktree changes */
5862 } else if (argc == 2) {
5863 id_str1 = argv[0];
5864 id_str2 = argv[1];
5865 } else
5866 usage_diff();
5868 error = got_repo_pack_fds_open(&pack_fds);
5869 if (error)
5870 goto done;
5872 if (repo_path == NULL) {
5873 cwd = getcwd(NULL, 0);
5874 if (cwd == NULL)
5875 return got_error_from_errno("getcwd");
5876 error = got_worktree_open(&worktree, cwd);
5877 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5878 goto done;
5879 if (worktree)
5880 repo_path =
5881 strdup(got_worktree_get_repo_path(worktree));
5882 else
5883 repo_path = strdup(cwd);
5884 if (repo_path == NULL) {
5885 error = got_error_from_errno("strdup");
5886 goto done;
5890 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5891 if (error)
5892 goto done;
5894 init_curses();
5896 error = apply_unveil(got_repo_get_path(repo), NULL);
5897 if (error)
5898 goto done;
5900 error = tog_load_refs(repo, 0);
5901 if (error)
5902 goto done;
5904 error = got_repo_match_object_id(&id1, &label1, id_str1,
5905 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5906 if (error)
5907 goto done;
5909 error = got_repo_match_object_id(&id2, &label2, id_str2,
5910 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5911 if (error)
5912 goto done;
5914 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5915 if (view == NULL) {
5916 error = got_error_from_errno("view_open");
5917 goto done;
5919 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5920 ignore_whitespace, force_text_diff, NULL, repo);
5921 if (error)
5922 goto done;
5923 error = view_loop(view);
5924 done:
5925 free(label1);
5926 free(label2);
5927 free(repo_path);
5928 free(cwd);
5929 if (repo) {
5930 const struct got_error *close_err = got_repo_close(repo);
5931 if (error == NULL)
5932 error = close_err;
5934 if (worktree)
5935 got_worktree_close(worktree);
5936 if (pack_fds) {
5937 const struct got_error *pack_err =
5938 got_repo_pack_fds_close(pack_fds);
5939 if (error == NULL)
5940 error = pack_err;
5942 tog_free_refs();
5943 return error;
5946 __dead static void
5947 usage_blame(void)
5949 endwin();
5950 fprintf(stderr,
5951 "usage: %s blame [-c commit] [-r repository-path] path\n",
5952 getprogname());
5953 exit(1);
5956 struct tog_blame_line {
5957 int annotated;
5958 struct got_object_id *id;
5961 static const struct got_error *
5962 draw_blame(struct tog_view *view)
5964 struct tog_blame_view_state *s = &view->state.blame;
5965 struct tog_blame *blame = &s->blame;
5966 regmatch_t *regmatch = &view->regmatch;
5967 const struct got_error *err;
5968 int lineno = 0, nprinted = 0;
5969 char *line = NULL;
5970 size_t linesize = 0;
5971 ssize_t linelen;
5972 wchar_t *wline;
5973 int width;
5974 struct tog_blame_line *blame_line;
5975 struct got_object_id *prev_id = NULL;
5976 char *id_str;
5977 struct tog_color *tc;
5979 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5980 if (err)
5981 return err;
5983 rewind(blame->f);
5984 werase(view->window);
5986 if (asprintf(&line, "commit %s", id_str) == -1) {
5987 err = got_error_from_errno("asprintf");
5988 free(id_str);
5989 return err;
5992 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5993 free(line);
5994 line = NULL;
5995 if (err)
5996 return err;
5997 if (view_needs_focus_indication(view))
5998 wstandout(view->window);
5999 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6000 if (tc)
6001 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6002 waddwstr(view->window, wline);
6003 while (width++ < view->ncols)
6004 waddch(view->window, ' ');
6005 if (tc)
6006 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6007 if (view_needs_focus_indication(view))
6008 wstandend(view->window);
6009 free(wline);
6010 wline = NULL;
6012 if (view->gline > blame->nlines)
6013 view->gline = blame->nlines;
6015 if (tog_io.wait_for_ui) {
6016 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6017 int rc;
6019 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6020 if (rc)
6021 return got_error_set_errno(rc, "pthread_cond_wait");
6022 tog_io.wait_for_ui = 0;
6025 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6026 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6027 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6028 free(id_str);
6029 return got_error_from_errno("asprintf");
6031 free(id_str);
6032 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6033 free(line);
6034 line = NULL;
6035 if (err)
6036 return err;
6037 waddwstr(view->window, wline);
6038 free(wline);
6039 wline = NULL;
6040 if (width < view->ncols - 1)
6041 waddch(view->window, '\n');
6043 s->eof = 0;
6044 view->maxx = 0;
6045 while (nprinted < view->nlines - 2) {
6046 linelen = getline(&line, &linesize, blame->f);
6047 if (linelen == -1) {
6048 if (feof(blame->f)) {
6049 s->eof = 1;
6050 break;
6052 free(line);
6053 return got_ferror(blame->f, GOT_ERR_IO);
6055 if (++lineno < s->first_displayed_line)
6056 continue;
6057 if (view->gline && !gotoline(view, &lineno, &nprinted))
6058 continue;
6060 /* Set view->maxx based on full line length. */
6061 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6062 if (err) {
6063 free(line);
6064 return err;
6066 free(wline);
6067 wline = NULL;
6068 view->maxx = MAX(view->maxx, width);
6070 if (nprinted == s->selected_line - 1)
6071 wstandout(view->window);
6073 if (blame->nlines > 0) {
6074 blame_line = &blame->lines[lineno - 1];
6075 if (blame_line->annotated && prev_id &&
6076 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6077 !(nprinted == s->selected_line - 1)) {
6078 waddstr(view->window, " ");
6079 } else if (blame_line->annotated) {
6080 char *id_str;
6081 err = got_object_id_str(&id_str,
6082 blame_line->id);
6083 if (err) {
6084 free(line);
6085 return err;
6087 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6088 if (tc)
6089 wattr_on(view->window,
6090 COLOR_PAIR(tc->colorpair), NULL);
6091 wprintw(view->window, "%.8s", id_str);
6092 if (tc)
6093 wattr_off(view->window,
6094 COLOR_PAIR(tc->colorpair), NULL);
6095 free(id_str);
6096 prev_id = blame_line->id;
6097 } else {
6098 waddstr(view->window, "........");
6099 prev_id = NULL;
6101 } else {
6102 waddstr(view->window, "........");
6103 prev_id = NULL;
6106 if (nprinted == s->selected_line - 1)
6107 wstandend(view->window);
6108 waddstr(view->window, " ");
6110 if (view->ncols <= 9) {
6111 width = 9;
6112 } else if (s->first_displayed_line + nprinted ==
6113 s->matched_line &&
6114 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6115 err = add_matched_line(&width, line, view->ncols - 9, 9,
6116 view->window, view->x, regmatch);
6117 if (err) {
6118 free(line);
6119 return err;
6121 width += 9;
6122 } else {
6123 int skip;
6124 err = format_line(&wline, &width, &skip, line,
6125 view->x, view->ncols - 9, 9, 1);
6126 if (err) {
6127 free(line);
6128 return err;
6130 waddwstr(view->window, &wline[skip]);
6131 width += 9;
6132 free(wline);
6133 wline = NULL;
6136 if (width <= view->ncols - 1)
6137 waddch(view->window, '\n');
6138 if (++nprinted == 1)
6139 s->first_displayed_line = lineno;
6141 free(line);
6142 s->last_displayed_line = lineno;
6144 view_border(view);
6146 return NULL;
6149 static const struct got_error *
6150 blame_cb(void *arg, int nlines, int lineno,
6151 struct got_commit_object *commit, struct got_object_id *id)
6153 const struct got_error *err = NULL;
6154 struct tog_blame_cb_args *a = arg;
6155 struct tog_blame_line *line;
6156 int errcode;
6158 if (nlines != a->nlines ||
6159 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6160 return got_error(GOT_ERR_RANGE);
6162 errcode = pthread_mutex_lock(&tog_mutex);
6163 if (errcode)
6164 return got_error_set_errno(errcode, "pthread_mutex_lock");
6166 if (*a->quit) { /* user has quit the blame view */
6167 err = got_error(GOT_ERR_ITER_COMPLETED);
6168 goto done;
6171 if (lineno == -1)
6172 goto done; /* no change in this commit */
6174 line = &a->lines[lineno - 1];
6175 if (line->annotated)
6176 goto done;
6178 line->id = got_object_id_dup(id);
6179 if (line->id == NULL) {
6180 err = got_error_from_errno("got_object_id_dup");
6181 goto done;
6183 line->annotated = 1;
6184 done:
6185 errcode = pthread_mutex_unlock(&tog_mutex);
6186 if (errcode)
6187 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6188 return err;
6191 static void *
6192 blame_thread(void *arg)
6194 const struct got_error *err, *close_err;
6195 struct tog_blame_thread_args *ta = arg;
6196 struct tog_blame_cb_args *a = ta->cb_args;
6197 int errcode, fd1 = -1, fd2 = -1;
6198 FILE *f1 = NULL, *f2 = NULL;
6200 fd1 = got_opentempfd();
6201 if (fd1 == -1)
6202 return (void *)got_error_from_errno("got_opentempfd");
6204 fd2 = got_opentempfd();
6205 if (fd2 == -1) {
6206 err = got_error_from_errno("got_opentempfd");
6207 goto done;
6210 f1 = got_opentemp();
6211 if (f1 == NULL) {
6212 err = (void *)got_error_from_errno("got_opentemp");
6213 goto done;
6215 f2 = got_opentemp();
6216 if (f2 == NULL) {
6217 err = (void *)got_error_from_errno("got_opentemp");
6218 goto done;
6221 err = block_signals_used_by_main_thread();
6222 if (err)
6223 goto done;
6225 err = got_blame(ta->path, a->commit_id, ta->repo,
6226 tog_diff_algo, blame_cb, ta->cb_args,
6227 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6228 if (err && err->code == GOT_ERR_CANCELLED)
6229 err = NULL;
6231 errcode = pthread_mutex_lock(&tog_mutex);
6232 if (errcode) {
6233 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6234 goto done;
6237 close_err = got_repo_close(ta->repo);
6238 if (err == NULL)
6239 err = close_err;
6240 ta->repo = NULL;
6241 *ta->complete = 1;
6243 if (tog_io.wait_for_ui) {
6244 errcode = pthread_cond_signal(&ta->blame_complete);
6245 if (errcode && err == NULL)
6246 err = got_error_set_errno(errcode,
6247 "pthread_cond_signal");
6250 errcode = pthread_mutex_unlock(&tog_mutex);
6251 if (errcode && err == NULL)
6252 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6254 done:
6255 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6256 err = got_error_from_errno("close");
6257 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6258 err = got_error_from_errno("close");
6259 if (f1 && fclose(f1) == EOF && err == NULL)
6260 err = got_error_from_errno("fclose");
6261 if (f2 && fclose(f2) == EOF && err == NULL)
6262 err = got_error_from_errno("fclose");
6264 return (void *)err;
6267 static struct got_object_id *
6268 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6269 int first_displayed_line, int selected_line)
6271 struct tog_blame_line *line;
6273 if (nlines <= 0)
6274 return NULL;
6276 line = &lines[first_displayed_line - 1 + selected_line - 1];
6277 if (!line->annotated)
6278 return NULL;
6280 return line->id;
6283 static struct got_object_id *
6284 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6285 int lineno)
6287 struct tog_blame_line *line;
6289 if (nlines <= 0 || lineno >= nlines)
6290 return NULL;
6292 line = &lines[lineno - 1];
6293 if (!line->annotated)
6294 return NULL;
6296 return line->id;
6299 static const struct got_error *
6300 stop_blame(struct tog_blame *blame)
6302 const struct got_error *err = NULL;
6303 int i;
6305 if (blame->thread) {
6306 int errcode;
6307 errcode = pthread_mutex_unlock(&tog_mutex);
6308 if (errcode)
6309 return got_error_set_errno(errcode,
6310 "pthread_mutex_unlock");
6311 errcode = pthread_join(blame->thread, (void **)&err);
6312 if (errcode)
6313 return got_error_set_errno(errcode, "pthread_join");
6314 errcode = pthread_mutex_lock(&tog_mutex);
6315 if (errcode)
6316 return got_error_set_errno(errcode,
6317 "pthread_mutex_lock");
6318 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6319 err = NULL;
6320 blame->thread = NULL;
6322 if (blame->thread_args.repo) {
6323 const struct got_error *close_err;
6324 close_err = got_repo_close(blame->thread_args.repo);
6325 if (err == NULL)
6326 err = close_err;
6327 blame->thread_args.repo = NULL;
6329 if (blame->f) {
6330 if (fclose(blame->f) == EOF && err == NULL)
6331 err = got_error_from_errno("fclose");
6332 blame->f = NULL;
6334 if (blame->lines) {
6335 for (i = 0; i < blame->nlines; i++)
6336 free(blame->lines[i].id);
6337 free(blame->lines);
6338 blame->lines = NULL;
6340 free(blame->cb_args.commit_id);
6341 blame->cb_args.commit_id = NULL;
6342 if (blame->pack_fds) {
6343 const struct got_error *pack_err =
6344 got_repo_pack_fds_close(blame->pack_fds);
6345 if (err == NULL)
6346 err = pack_err;
6347 blame->pack_fds = NULL;
6349 return err;
6352 static const struct got_error *
6353 cancel_blame_view(void *arg)
6355 const struct got_error *err = NULL;
6356 int *done = arg;
6357 int errcode;
6359 errcode = pthread_mutex_lock(&tog_mutex);
6360 if (errcode)
6361 return got_error_set_errno(errcode,
6362 "pthread_mutex_unlock");
6364 if (*done)
6365 err = got_error(GOT_ERR_CANCELLED);
6367 errcode = pthread_mutex_unlock(&tog_mutex);
6368 if (errcode)
6369 return got_error_set_errno(errcode,
6370 "pthread_mutex_lock");
6372 return err;
6375 static const struct got_error *
6376 run_blame(struct tog_view *view)
6378 struct tog_blame_view_state *s = &view->state.blame;
6379 struct tog_blame *blame = &s->blame;
6380 const struct got_error *err = NULL;
6381 struct got_commit_object *commit = NULL;
6382 struct got_blob_object *blob = NULL;
6383 struct got_repository *thread_repo = NULL;
6384 struct got_object_id *obj_id = NULL;
6385 int obj_type, fd = -1;
6386 int *pack_fds = NULL;
6388 err = got_object_open_as_commit(&commit, s->repo,
6389 &s->blamed_commit->id);
6390 if (err)
6391 return err;
6393 fd = got_opentempfd();
6394 if (fd == -1) {
6395 err = got_error_from_errno("got_opentempfd");
6396 goto done;
6399 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6400 if (err)
6401 goto done;
6403 err = got_object_get_type(&obj_type, s->repo, obj_id);
6404 if (err)
6405 goto done;
6407 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6408 err = got_error(GOT_ERR_OBJ_TYPE);
6409 goto done;
6412 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6413 if (err)
6414 goto done;
6415 blame->f = got_opentemp();
6416 if (blame->f == NULL) {
6417 err = got_error_from_errno("got_opentemp");
6418 goto done;
6420 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6421 &blame->line_offsets, blame->f, blob);
6422 if (err)
6423 goto done;
6424 if (blame->nlines == 0) {
6425 s->blame_complete = 1;
6426 goto done;
6429 /* Don't include \n at EOF in the blame line count. */
6430 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6431 blame->nlines--;
6433 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6434 if (blame->lines == NULL) {
6435 err = got_error_from_errno("calloc");
6436 goto done;
6439 err = got_repo_pack_fds_open(&pack_fds);
6440 if (err)
6441 goto done;
6442 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6443 pack_fds);
6444 if (err)
6445 goto done;
6447 blame->pack_fds = pack_fds;
6448 blame->cb_args.view = view;
6449 blame->cb_args.lines = blame->lines;
6450 blame->cb_args.nlines = blame->nlines;
6451 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6452 if (blame->cb_args.commit_id == NULL) {
6453 err = got_error_from_errno("got_object_id_dup");
6454 goto done;
6456 blame->cb_args.quit = &s->done;
6458 blame->thread_args.path = s->path;
6459 blame->thread_args.repo = thread_repo;
6460 blame->thread_args.cb_args = &blame->cb_args;
6461 blame->thread_args.complete = &s->blame_complete;
6462 blame->thread_args.cancel_cb = cancel_blame_view;
6463 blame->thread_args.cancel_arg = &s->done;
6464 s->blame_complete = 0;
6466 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6467 s->first_displayed_line = 1;
6468 s->last_displayed_line = view->nlines;
6469 s->selected_line = 1;
6471 s->matched_line = 0;
6473 done:
6474 if (commit)
6475 got_object_commit_close(commit);
6476 if (fd != -1 && close(fd) == -1 && err == NULL)
6477 err = got_error_from_errno("close");
6478 if (blob)
6479 got_object_blob_close(blob);
6480 free(obj_id);
6481 if (err)
6482 stop_blame(blame);
6483 return err;
6486 static const struct got_error *
6487 open_blame_view(struct tog_view *view, char *path,
6488 struct got_object_id *commit_id, struct got_repository *repo)
6490 const struct got_error *err = NULL;
6491 struct tog_blame_view_state *s = &view->state.blame;
6493 STAILQ_INIT(&s->blamed_commits);
6495 s->path = strdup(path);
6496 if (s->path == NULL)
6497 return got_error_from_errno("strdup");
6499 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6500 if (err) {
6501 free(s->path);
6502 return err;
6505 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6506 s->first_displayed_line = 1;
6507 s->last_displayed_line = view->nlines;
6508 s->selected_line = 1;
6509 s->blame_complete = 0;
6510 s->repo = repo;
6511 s->commit_id = commit_id;
6512 memset(&s->blame, 0, sizeof(s->blame));
6514 STAILQ_INIT(&s->colors);
6515 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6516 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6517 get_color_value("TOG_COLOR_COMMIT"));
6518 if (err)
6519 return err;
6522 view->show = show_blame_view;
6523 view->input = input_blame_view;
6524 view->reset = reset_blame_view;
6525 view->close = close_blame_view;
6526 view->search_start = search_start_blame_view;
6527 view->search_setup = search_setup_blame_view;
6528 view->search_next = search_next_view_match;
6530 if (using_mock_io) {
6531 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6532 int rc;
6534 rc = pthread_cond_init(&bta->blame_complete, NULL);
6535 if (rc)
6536 return got_error_set_errno(rc, "pthread_cond_init");
6539 return run_blame(view);
6542 static const struct got_error *
6543 close_blame_view(struct tog_view *view)
6545 const struct got_error *err = NULL;
6546 struct tog_blame_view_state *s = &view->state.blame;
6548 if (s->blame.thread)
6549 err = stop_blame(&s->blame);
6551 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6552 struct got_object_qid *blamed_commit;
6553 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6554 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6555 got_object_qid_free(blamed_commit);
6558 if (using_mock_io) {
6559 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6560 int rc;
6562 rc = pthread_cond_destroy(&bta->blame_complete);
6563 if (rc && err == NULL)
6564 err = got_error_set_errno(rc, "pthread_cond_destroy");
6567 free(s->path);
6568 free_colors(&s->colors);
6569 return err;
6572 static const struct got_error *
6573 search_start_blame_view(struct tog_view *view)
6575 struct tog_blame_view_state *s = &view->state.blame;
6577 s->matched_line = 0;
6578 return NULL;
6581 static void
6582 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6583 size_t *nlines, int **first, int **last, int **match, int **selected)
6585 struct tog_blame_view_state *s = &view->state.blame;
6587 *f = s->blame.f;
6588 *nlines = s->blame.nlines;
6589 *line_offsets = s->blame.line_offsets;
6590 *match = &s->matched_line;
6591 *first = &s->first_displayed_line;
6592 *last = &s->last_displayed_line;
6593 *selected = &s->selected_line;
6596 static const struct got_error *
6597 show_blame_view(struct tog_view *view)
6599 const struct got_error *err = NULL;
6600 struct tog_blame_view_state *s = &view->state.blame;
6601 int errcode;
6603 if (s->blame.thread == NULL && !s->blame_complete) {
6604 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6605 &s->blame.thread_args);
6606 if (errcode)
6607 return got_error_set_errno(errcode, "pthread_create");
6609 if (!using_mock_io)
6610 halfdelay(1); /* fast refresh while annotating */
6613 if (s->blame_complete && !using_mock_io)
6614 halfdelay(10); /* disable fast refresh */
6616 err = draw_blame(view);
6618 view_border(view);
6619 return err;
6622 static const struct got_error *
6623 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6624 struct got_repository *repo, struct got_object_id *id)
6626 struct tog_view *log_view;
6627 const struct got_error *err = NULL;
6629 *new_view = NULL;
6631 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6632 if (log_view == NULL)
6633 return got_error_from_errno("view_open");
6635 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6636 if (err)
6637 view_close(log_view);
6638 else
6639 *new_view = log_view;
6641 return err;
6644 static const struct got_error *
6645 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6647 const struct got_error *err = NULL, *thread_err = NULL;
6648 struct tog_view *diff_view;
6649 struct tog_blame_view_state *s = &view->state.blame;
6650 int eos, nscroll, begin_y = 0, begin_x = 0;
6652 eos = nscroll = view->nlines - 2;
6653 if (view_is_hsplit_top(view))
6654 --eos; /* border */
6656 switch (ch) {
6657 case '0':
6658 case '$':
6659 case KEY_RIGHT:
6660 case 'l':
6661 case KEY_LEFT:
6662 case 'h':
6663 horizontal_scroll_input(view, ch);
6664 break;
6665 case 'q':
6666 s->done = 1;
6667 break;
6668 case 'g':
6669 case KEY_HOME:
6670 s->selected_line = 1;
6671 s->first_displayed_line = 1;
6672 view->count = 0;
6673 break;
6674 case 'G':
6675 case KEY_END:
6676 if (s->blame.nlines < eos) {
6677 s->selected_line = s->blame.nlines;
6678 s->first_displayed_line = 1;
6679 } else {
6680 s->selected_line = eos;
6681 s->first_displayed_line = s->blame.nlines - (eos - 1);
6683 view->count = 0;
6684 break;
6685 case 'k':
6686 case KEY_UP:
6687 case CTRL('p'):
6688 if (s->selected_line > 1)
6689 s->selected_line--;
6690 else if (s->selected_line == 1 &&
6691 s->first_displayed_line > 1)
6692 s->first_displayed_line--;
6693 else
6694 view->count = 0;
6695 break;
6696 case CTRL('u'):
6697 case 'u':
6698 nscroll /= 2;
6699 /* FALL THROUGH */
6700 case KEY_PPAGE:
6701 case CTRL('b'):
6702 case 'b':
6703 if (s->first_displayed_line == 1) {
6704 if (view->count > 1)
6705 nscroll += nscroll;
6706 s->selected_line = MAX(1, s->selected_line - nscroll);
6707 view->count = 0;
6708 break;
6710 if (s->first_displayed_line > nscroll)
6711 s->first_displayed_line -= nscroll;
6712 else
6713 s->first_displayed_line = 1;
6714 break;
6715 case 'j':
6716 case KEY_DOWN:
6717 case CTRL('n'):
6718 if (s->selected_line < eos && s->first_displayed_line +
6719 s->selected_line <= s->blame.nlines)
6720 s->selected_line++;
6721 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6722 s->first_displayed_line++;
6723 else
6724 view->count = 0;
6725 break;
6726 case 'c':
6727 case 'p': {
6728 struct got_object_id *id = NULL;
6730 view->count = 0;
6731 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6732 s->first_displayed_line, s->selected_line);
6733 if (id == NULL)
6734 break;
6735 if (ch == 'p') {
6736 struct got_commit_object *commit, *pcommit;
6737 struct got_object_qid *pid;
6738 struct got_object_id *blob_id = NULL;
6739 int obj_type;
6740 err = got_object_open_as_commit(&commit,
6741 s->repo, id);
6742 if (err)
6743 break;
6744 pid = STAILQ_FIRST(
6745 got_object_commit_get_parent_ids(commit));
6746 if (pid == NULL) {
6747 got_object_commit_close(commit);
6748 break;
6750 /* Check if path history ends here. */
6751 err = got_object_open_as_commit(&pcommit,
6752 s->repo, &pid->id);
6753 if (err)
6754 break;
6755 err = got_object_id_by_path(&blob_id, s->repo,
6756 pcommit, s->path);
6757 got_object_commit_close(pcommit);
6758 if (err) {
6759 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6760 err = NULL;
6761 got_object_commit_close(commit);
6762 break;
6764 err = got_object_get_type(&obj_type, s->repo,
6765 blob_id);
6766 free(blob_id);
6767 /* Can't blame non-blob type objects. */
6768 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6769 got_object_commit_close(commit);
6770 break;
6772 err = got_object_qid_alloc(&s->blamed_commit,
6773 &pid->id);
6774 got_object_commit_close(commit);
6775 } else {
6776 if (got_object_id_cmp(id,
6777 &s->blamed_commit->id) == 0)
6778 break;
6779 err = got_object_qid_alloc(&s->blamed_commit,
6780 id);
6782 if (err)
6783 break;
6784 s->done = 1;
6785 thread_err = stop_blame(&s->blame);
6786 s->done = 0;
6787 if (thread_err)
6788 break;
6789 STAILQ_INSERT_HEAD(&s->blamed_commits,
6790 s->blamed_commit, entry);
6791 err = run_blame(view);
6792 if (err)
6793 break;
6794 break;
6796 case 'C': {
6797 struct got_object_qid *first;
6799 view->count = 0;
6800 first = STAILQ_FIRST(&s->blamed_commits);
6801 if (!got_object_id_cmp(&first->id, s->commit_id))
6802 break;
6803 s->done = 1;
6804 thread_err = stop_blame(&s->blame);
6805 s->done = 0;
6806 if (thread_err)
6807 break;
6808 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6809 got_object_qid_free(s->blamed_commit);
6810 s->blamed_commit =
6811 STAILQ_FIRST(&s->blamed_commits);
6812 err = run_blame(view);
6813 if (err)
6814 break;
6815 break;
6817 case 'L':
6818 view->count = 0;
6819 s->id_to_log = get_selected_commit_id(s->blame.lines,
6820 s->blame.nlines, s->first_displayed_line, s->selected_line);
6821 if (s->id_to_log)
6822 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6823 break;
6824 case KEY_ENTER:
6825 case '\r': {
6826 struct got_object_id *id = NULL;
6827 struct got_object_qid *pid;
6828 struct got_commit_object *commit = NULL;
6830 view->count = 0;
6831 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6832 s->first_displayed_line, s->selected_line);
6833 if (id == NULL)
6834 break;
6835 err = got_object_open_as_commit(&commit, s->repo, id);
6836 if (err)
6837 break;
6838 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6839 if (*new_view) {
6840 /* traversed from diff view, release diff resources */
6841 err = close_diff_view(*new_view);
6842 if (err)
6843 break;
6844 diff_view = *new_view;
6845 } else {
6846 if (view_is_parent_view(view))
6847 view_get_split(view, &begin_y, &begin_x);
6849 diff_view = view_open(0, 0, begin_y, begin_x,
6850 TOG_VIEW_DIFF);
6851 if (diff_view == NULL) {
6852 got_object_commit_close(commit);
6853 err = got_error_from_errno("view_open");
6854 break;
6857 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6858 id, NULL, NULL, 3, 0, 0, view, s->repo);
6859 got_object_commit_close(commit);
6860 if (err) {
6861 view_close(diff_view);
6862 break;
6864 s->last_diffed_line = s->first_displayed_line - 1 +
6865 s->selected_line;
6866 if (*new_view)
6867 break; /* still open from active diff view */
6868 if (view_is_parent_view(view) &&
6869 view->mode == TOG_VIEW_SPLIT_HRZN) {
6870 err = view_init_hsplit(view, begin_y);
6871 if (err)
6872 break;
6875 view->focussed = 0;
6876 diff_view->focussed = 1;
6877 diff_view->mode = view->mode;
6878 diff_view->nlines = view->lines - begin_y;
6879 if (view_is_parent_view(view)) {
6880 view_transfer_size(diff_view, view);
6881 err = view_close_child(view);
6882 if (err)
6883 break;
6884 err = view_set_child(view, diff_view);
6885 if (err)
6886 break;
6887 view->focus_child = 1;
6888 } else
6889 *new_view = diff_view;
6890 if (err)
6891 break;
6892 break;
6894 case CTRL('d'):
6895 case 'd':
6896 nscroll /= 2;
6897 /* FALL THROUGH */
6898 case KEY_NPAGE:
6899 case CTRL('f'):
6900 case 'f':
6901 case ' ':
6902 if (s->last_displayed_line >= s->blame.nlines &&
6903 s->selected_line >= MIN(s->blame.nlines,
6904 view->nlines - 2)) {
6905 view->count = 0;
6906 break;
6908 if (s->last_displayed_line >= s->blame.nlines &&
6909 s->selected_line < view->nlines - 2) {
6910 s->selected_line +=
6911 MIN(nscroll, s->last_displayed_line -
6912 s->first_displayed_line - s->selected_line + 1);
6914 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6915 s->first_displayed_line += nscroll;
6916 else
6917 s->first_displayed_line =
6918 s->blame.nlines - (view->nlines - 3);
6919 break;
6920 case KEY_RESIZE:
6921 if (s->selected_line > view->nlines - 2) {
6922 s->selected_line = MIN(s->blame.nlines,
6923 view->nlines - 2);
6925 break;
6926 default:
6927 view->count = 0;
6928 break;
6930 return thread_err ? thread_err : err;
6933 static const struct got_error *
6934 reset_blame_view(struct tog_view *view)
6936 const struct got_error *err;
6937 struct tog_blame_view_state *s = &view->state.blame;
6939 view->count = 0;
6940 s->done = 1;
6941 err = stop_blame(&s->blame);
6942 s->done = 0;
6943 if (err)
6944 return err;
6945 return run_blame(view);
6948 static const struct got_error *
6949 cmd_blame(int argc, char *argv[])
6951 const struct got_error *error;
6952 struct got_repository *repo = NULL;
6953 struct got_worktree *worktree = NULL;
6954 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6955 char *link_target = NULL;
6956 struct got_object_id *commit_id = NULL;
6957 struct got_commit_object *commit = NULL;
6958 char *commit_id_str = NULL;
6959 int ch;
6960 struct tog_view *view = NULL;
6961 int *pack_fds = NULL;
6963 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6964 switch (ch) {
6965 case 'c':
6966 commit_id_str = optarg;
6967 break;
6968 case 'r':
6969 repo_path = realpath(optarg, NULL);
6970 if (repo_path == NULL)
6971 return got_error_from_errno2("realpath",
6972 optarg);
6973 break;
6974 default:
6975 usage_blame();
6976 /* NOTREACHED */
6980 argc -= optind;
6981 argv += optind;
6983 if (argc != 1)
6984 usage_blame();
6986 error = got_repo_pack_fds_open(&pack_fds);
6987 if (error != NULL)
6988 goto done;
6990 if (repo_path == NULL) {
6991 cwd = getcwd(NULL, 0);
6992 if (cwd == NULL)
6993 return got_error_from_errno("getcwd");
6994 error = got_worktree_open(&worktree, cwd);
6995 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6996 goto done;
6997 if (worktree)
6998 repo_path =
6999 strdup(got_worktree_get_repo_path(worktree));
7000 else
7001 repo_path = strdup(cwd);
7002 if (repo_path == NULL) {
7003 error = got_error_from_errno("strdup");
7004 goto done;
7008 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7009 if (error != NULL)
7010 goto done;
7012 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7013 worktree);
7014 if (error)
7015 goto done;
7017 init_curses();
7019 error = apply_unveil(got_repo_get_path(repo), NULL);
7020 if (error)
7021 goto done;
7023 error = tog_load_refs(repo, 0);
7024 if (error)
7025 goto done;
7027 if (commit_id_str == NULL) {
7028 struct got_reference *head_ref;
7029 error = got_ref_open(&head_ref, repo, worktree ?
7030 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7031 if (error != NULL)
7032 goto done;
7033 error = got_ref_resolve(&commit_id, repo, head_ref);
7034 got_ref_close(head_ref);
7035 } else {
7036 error = got_repo_match_object_id(&commit_id, NULL,
7037 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7039 if (error != NULL)
7040 goto done;
7042 error = got_object_open_as_commit(&commit, repo, commit_id);
7043 if (error)
7044 goto done;
7046 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7047 commit, repo);
7048 if (error)
7049 goto done;
7051 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7052 if (view == NULL) {
7053 error = got_error_from_errno("view_open");
7054 goto done;
7056 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7057 commit_id, repo);
7058 if (error != NULL) {
7059 if (view->close == NULL)
7060 close_blame_view(view);
7061 view_close(view);
7062 goto done;
7064 if (worktree) {
7065 /* Release work tree lock. */
7066 got_worktree_close(worktree);
7067 worktree = NULL;
7069 error = view_loop(view);
7070 done:
7071 free(repo_path);
7072 free(in_repo_path);
7073 free(link_target);
7074 free(cwd);
7075 free(commit_id);
7076 if (commit)
7077 got_object_commit_close(commit);
7078 if (worktree)
7079 got_worktree_close(worktree);
7080 if (repo) {
7081 const struct got_error *close_err = got_repo_close(repo);
7082 if (error == NULL)
7083 error = close_err;
7085 if (pack_fds) {
7086 const struct got_error *pack_err =
7087 got_repo_pack_fds_close(pack_fds);
7088 if (error == NULL)
7089 error = pack_err;
7091 tog_free_refs();
7092 return error;
7095 static const struct got_error *
7096 draw_tree_entries(struct tog_view *view, const char *parent_path)
7098 struct tog_tree_view_state *s = &view->state.tree;
7099 const struct got_error *err = NULL;
7100 struct got_tree_entry *te;
7101 wchar_t *wline;
7102 char *index = NULL;
7103 struct tog_color *tc;
7104 int width, n, nentries, scrollx, i = 1;
7105 int limit = view->nlines;
7107 s->ndisplayed = 0;
7108 if (view_is_hsplit_top(view))
7109 --limit; /* border */
7111 werase(view->window);
7113 if (limit == 0)
7114 return NULL;
7116 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7117 0, 0);
7118 if (err)
7119 return err;
7120 if (view_needs_focus_indication(view))
7121 wstandout(view->window);
7122 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7123 if (tc)
7124 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7125 waddwstr(view->window, wline);
7126 free(wline);
7127 wline = NULL;
7128 while (width++ < view->ncols)
7129 waddch(view->window, ' ');
7130 if (tc)
7131 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7132 if (view_needs_focus_indication(view))
7133 wstandend(view->window);
7134 if (--limit <= 0)
7135 return NULL;
7137 i += s->selected;
7138 if (s->first_displayed_entry) {
7139 i += got_tree_entry_get_index(s->first_displayed_entry);
7140 if (s->tree != s->root)
7141 ++i; /* account for ".." entry */
7143 nentries = got_object_tree_get_nentries(s->tree);
7144 if (asprintf(&index, "[%d/%d] %s",
7145 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7146 return got_error_from_errno("asprintf");
7147 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7148 free(index);
7149 if (err)
7150 return err;
7151 waddwstr(view->window, wline);
7152 free(wline);
7153 wline = NULL;
7154 if (width < view->ncols - 1)
7155 waddch(view->window, '\n');
7156 if (--limit <= 0)
7157 return NULL;
7158 waddch(view->window, '\n');
7159 if (--limit <= 0)
7160 return NULL;
7162 if (s->first_displayed_entry == NULL) {
7163 te = got_object_tree_get_first_entry(s->tree);
7164 if (s->selected == 0) {
7165 if (view->focussed)
7166 wstandout(view->window);
7167 s->selected_entry = NULL;
7169 waddstr(view->window, " ..\n"); /* parent directory */
7170 if (s->selected == 0 && view->focussed)
7171 wstandend(view->window);
7172 s->ndisplayed++;
7173 if (--limit <= 0)
7174 return NULL;
7175 n = 1;
7176 } else {
7177 n = 0;
7178 te = s->first_displayed_entry;
7181 view->maxx = 0;
7182 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7183 char *line = NULL, *id_str = NULL, *link_target = NULL;
7184 const char *modestr = "";
7185 mode_t mode;
7187 te = got_object_tree_get_entry(s->tree, i);
7188 mode = got_tree_entry_get_mode(te);
7190 if (s->show_ids) {
7191 err = got_object_id_str(&id_str,
7192 got_tree_entry_get_id(te));
7193 if (err)
7194 return got_error_from_errno(
7195 "got_object_id_str");
7197 if (got_object_tree_entry_is_submodule(te))
7198 modestr = "$";
7199 else if (S_ISLNK(mode)) {
7200 int i;
7202 err = got_tree_entry_get_symlink_target(&link_target,
7203 te, s->repo);
7204 if (err) {
7205 free(id_str);
7206 return err;
7208 for (i = 0; i < strlen(link_target); i++) {
7209 if (!isprint((unsigned char)link_target[i]))
7210 link_target[i] = '?';
7212 modestr = "@";
7214 else if (S_ISDIR(mode))
7215 modestr = "/";
7216 else if (mode & S_IXUSR)
7217 modestr = "*";
7218 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7219 got_tree_entry_get_name(te), modestr,
7220 link_target ? " -> ": "",
7221 link_target ? link_target : "") == -1) {
7222 free(id_str);
7223 free(link_target);
7224 return got_error_from_errno("asprintf");
7226 free(id_str);
7227 free(link_target);
7229 /* use full line width to determine view->maxx */
7230 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7231 if (err) {
7232 free(line);
7233 break;
7235 view->maxx = MAX(view->maxx, width);
7236 free(wline);
7237 wline = NULL;
7239 err = format_line(&wline, &width, &scrollx, line, view->x,
7240 view->ncols, 0, 0);
7241 if (err) {
7242 free(line);
7243 break;
7245 if (n == s->selected) {
7246 if (view->focussed)
7247 wstandout(view->window);
7248 s->selected_entry = te;
7250 tc = match_color(&s->colors, line);
7251 if (tc)
7252 wattr_on(view->window,
7253 COLOR_PAIR(tc->colorpair), NULL);
7254 waddwstr(view->window, &wline[scrollx]);
7255 if (tc)
7256 wattr_off(view->window,
7257 COLOR_PAIR(tc->colorpair), NULL);
7258 if (width < view->ncols)
7259 waddch(view->window, '\n');
7260 if (n == s->selected && view->focussed)
7261 wstandend(view->window);
7262 free(line);
7263 free(wline);
7264 wline = NULL;
7265 n++;
7266 s->ndisplayed++;
7267 s->last_displayed_entry = te;
7268 if (--limit <= 0)
7269 break;
7272 return err;
7275 static void
7276 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7278 struct got_tree_entry *te;
7279 int isroot = s->tree == s->root;
7280 int i = 0;
7282 if (s->first_displayed_entry == NULL)
7283 return;
7285 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7286 while (i++ < maxscroll) {
7287 if (te == NULL) {
7288 if (!isroot)
7289 s->first_displayed_entry = NULL;
7290 break;
7292 s->first_displayed_entry = te;
7293 te = got_tree_entry_get_prev(s->tree, te);
7297 static const struct got_error *
7298 tree_scroll_down(struct tog_view *view, int maxscroll)
7300 struct tog_tree_view_state *s = &view->state.tree;
7301 struct got_tree_entry *next, *last;
7302 int n = 0;
7304 if (s->first_displayed_entry)
7305 next = got_tree_entry_get_next(s->tree,
7306 s->first_displayed_entry);
7307 else
7308 next = got_object_tree_get_first_entry(s->tree);
7310 last = s->last_displayed_entry;
7311 while (next && n++ < maxscroll) {
7312 if (last) {
7313 s->last_displayed_entry = last;
7314 last = got_tree_entry_get_next(s->tree, last);
7316 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7317 s->first_displayed_entry = next;
7318 next = got_tree_entry_get_next(s->tree, next);
7322 return NULL;
7325 static const struct got_error *
7326 tree_entry_path(char **path, struct tog_parent_trees *parents,
7327 struct got_tree_entry *te)
7329 const struct got_error *err = NULL;
7330 struct tog_parent_tree *pt;
7331 size_t len = 2; /* for leading slash and NUL */
7333 TAILQ_FOREACH(pt, parents, entry)
7334 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7335 + 1 /* slash */;
7336 if (te)
7337 len += strlen(got_tree_entry_get_name(te));
7339 *path = calloc(1, len);
7340 if (path == NULL)
7341 return got_error_from_errno("calloc");
7343 (*path)[0] = '/';
7344 pt = TAILQ_LAST(parents, tog_parent_trees);
7345 while (pt) {
7346 const char *name = got_tree_entry_get_name(pt->selected_entry);
7347 if (strlcat(*path, name, len) >= len) {
7348 err = got_error(GOT_ERR_NO_SPACE);
7349 goto done;
7351 if (strlcat(*path, "/", len) >= len) {
7352 err = got_error(GOT_ERR_NO_SPACE);
7353 goto done;
7355 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7357 if (te) {
7358 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7359 err = got_error(GOT_ERR_NO_SPACE);
7360 goto done;
7363 done:
7364 if (err) {
7365 free(*path);
7366 *path = NULL;
7368 return err;
7371 static const struct got_error *
7372 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7373 struct got_tree_entry *te, struct tog_parent_trees *parents,
7374 struct got_object_id *commit_id, struct got_repository *repo)
7376 const struct got_error *err = NULL;
7377 char *path;
7378 struct tog_view *blame_view;
7380 *new_view = NULL;
7382 err = tree_entry_path(&path, parents, te);
7383 if (err)
7384 return err;
7386 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7387 if (blame_view == NULL) {
7388 err = got_error_from_errno("view_open");
7389 goto done;
7392 err = open_blame_view(blame_view, path, commit_id, repo);
7393 if (err) {
7394 if (err->code == GOT_ERR_CANCELLED)
7395 err = NULL;
7396 view_close(blame_view);
7397 } else
7398 *new_view = blame_view;
7399 done:
7400 free(path);
7401 return err;
7404 static const struct got_error *
7405 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7406 struct tog_tree_view_state *s)
7408 struct tog_view *log_view;
7409 const struct got_error *err = NULL;
7410 char *path;
7412 *new_view = NULL;
7414 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7415 if (log_view == NULL)
7416 return got_error_from_errno("view_open");
7418 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7419 if (err)
7420 return err;
7422 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7423 path, 0);
7424 if (err)
7425 view_close(log_view);
7426 else
7427 *new_view = log_view;
7428 free(path);
7429 return err;
7432 static const struct got_error *
7433 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7434 const char *head_ref_name, struct got_repository *repo)
7436 const struct got_error *err = NULL;
7437 char *commit_id_str = NULL;
7438 struct tog_tree_view_state *s = &view->state.tree;
7439 struct got_commit_object *commit = NULL;
7441 TAILQ_INIT(&s->parents);
7442 STAILQ_INIT(&s->colors);
7444 s->commit_id = got_object_id_dup(commit_id);
7445 if (s->commit_id == NULL) {
7446 err = got_error_from_errno("got_object_id_dup");
7447 goto done;
7450 err = got_object_open_as_commit(&commit, repo, commit_id);
7451 if (err)
7452 goto done;
7455 * The root is opened here and will be closed when the view is closed.
7456 * Any visited subtrees and their path-wise parents are opened and
7457 * closed on demand.
7459 err = got_object_open_as_tree(&s->root, repo,
7460 got_object_commit_get_tree_id(commit));
7461 if (err)
7462 goto done;
7463 s->tree = s->root;
7465 err = got_object_id_str(&commit_id_str, commit_id);
7466 if (err != NULL)
7467 goto done;
7469 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7470 err = got_error_from_errno("asprintf");
7471 goto done;
7474 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7475 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7476 if (head_ref_name) {
7477 s->head_ref_name = strdup(head_ref_name);
7478 if (s->head_ref_name == NULL) {
7479 err = got_error_from_errno("strdup");
7480 goto done;
7483 s->repo = repo;
7485 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7486 err = add_color(&s->colors, "\\$$",
7487 TOG_COLOR_TREE_SUBMODULE,
7488 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7489 if (err)
7490 goto done;
7491 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7492 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7493 if (err)
7494 goto done;
7495 err = add_color(&s->colors, "/$",
7496 TOG_COLOR_TREE_DIRECTORY,
7497 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7498 if (err)
7499 goto done;
7501 err = add_color(&s->colors, "\\*$",
7502 TOG_COLOR_TREE_EXECUTABLE,
7503 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7504 if (err)
7505 goto done;
7507 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7508 get_color_value("TOG_COLOR_COMMIT"));
7509 if (err)
7510 goto done;
7513 view->show = show_tree_view;
7514 view->input = input_tree_view;
7515 view->close = close_tree_view;
7516 view->search_start = search_start_tree_view;
7517 view->search_next = search_next_tree_view;
7518 done:
7519 free(commit_id_str);
7520 if (commit)
7521 got_object_commit_close(commit);
7522 if (err) {
7523 if (view->close == NULL)
7524 close_tree_view(view);
7525 view_close(view);
7527 return err;
7530 static const struct got_error *
7531 close_tree_view(struct tog_view *view)
7533 struct tog_tree_view_state *s = &view->state.tree;
7535 free_colors(&s->colors);
7536 free(s->tree_label);
7537 s->tree_label = NULL;
7538 free(s->commit_id);
7539 s->commit_id = NULL;
7540 free(s->head_ref_name);
7541 s->head_ref_name = NULL;
7542 while (!TAILQ_EMPTY(&s->parents)) {
7543 struct tog_parent_tree *parent;
7544 parent = TAILQ_FIRST(&s->parents);
7545 TAILQ_REMOVE(&s->parents, parent, entry);
7546 if (parent->tree != s->root)
7547 got_object_tree_close(parent->tree);
7548 free(parent);
7551 if (s->tree != NULL && s->tree != s->root)
7552 got_object_tree_close(s->tree);
7553 if (s->root)
7554 got_object_tree_close(s->root);
7555 return NULL;
7558 static const struct got_error *
7559 search_start_tree_view(struct tog_view *view)
7561 struct tog_tree_view_state *s = &view->state.tree;
7563 s->matched_entry = NULL;
7564 return NULL;
7567 static int
7568 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7570 regmatch_t regmatch;
7572 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7573 0) == 0;
7576 static const struct got_error *
7577 search_next_tree_view(struct tog_view *view)
7579 struct tog_tree_view_state *s = &view->state.tree;
7580 struct got_tree_entry *te = NULL;
7582 if (!view->searching) {
7583 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7584 return NULL;
7587 if (s->matched_entry) {
7588 if (view->searching == TOG_SEARCH_FORWARD) {
7589 if (s->selected_entry)
7590 te = got_tree_entry_get_next(s->tree,
7591 s->selected_entry);
7592 else
7593 te = got_object_tree_get_first_entry(s->tree);
7594 } else {
7595 if (s->selected_entry == NULL)
7596 te = got_object_tree_get_last_entry(s->tree);
7597 else
7598 te = got_tree_entry_get_prev(s->tree,
7599 s->selected_entry);
7601 } else {
7602 if (s->selected_entry)
7603 te = s->selected_entry;
7604 else if (view->searching == TOG_SEARCH_FORWARD)
7605 te = got_object_tree_get_first_entry(s->tree);
7606 else
7607 te = got_object_tree_get_last_entry(s->tree);
7610 while (1) {
7611 if (te == NULL) {
7612 if (s->matched_entry == NULL) {
7613 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7614 return NULL;
7616 if (view->searching == TOG_SEARCH_FORWARD)
7617 te = got_object_tree_get_first_entry(s->tree);
7618 else
7619 te = got_object_tree_get_last_entry(s->tree);
7622 if (match_tree_entry(te, &view->regex)) {
7623 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7624 s->matched_entry = te;
7625 break;
7628 if (view->searching == TOG_SEARCH_FORWARD)
7629 te = got_tree_entry_get_next(s->tree, te);
7630 else
7631 te = got_tree_entry_get_prev(s->tree, te);
7634 if (s->matched_entry) {
7635 s->first_displayed_entry = s->matched_entry;
7636 s->selected = 0;
7639 return NULL;
7642 static const struct got_error *
7643 show_tree_view(struct tog_view *view)
7645 const struct got_error *err = NULL;
7646 struct tog_tree_view_state *s = &view->state.tree;
7647 char *parent_path;
7649 err = tree_entry_path(&parent_path, &s->parents, NULL);
7650 if (err)
7651 return err;
7653 err = draw_tree_entries(view, parent_path);
7654 free(parent_path);
7656 view_border(view);
7657 return err;
7660 static const struct got_error *
7661 tree_goto_line(struct tog_view *view, int nlines)
7663 const struct got_error *err = NULL;
7664 struct tog_tree_view_state *s = &view->state.tree;
7665 struct got_tree_entry **fte, **lte, **ste;
7666 int g, last, first = 1, i = 1;
7667 int root = s->tree == s->root;
7668 int off = root ? 1 : 2;
7670 g = view->gline;
7671 view->gline = 0;
7673 if (g == 0)
7674 g = 1;
7675 else if (g > got_object_tree_get_nentries(s->tree))
7676 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7678 fte = &s->first_displayed_entry;
7679 lte = &s->last_displayed_entry;
7680 ste = &s->selected_entry;
7682 if (*fte != NULL) {
7683 first = got_tree_entry_get_index(*fte);
7684 first += off; /* account for ".." */
7686 last = got_tree_entry_get_index(*lte);
7687 last += off;
7689 if (g >= first && g <= last && g - first < nlines) {
7690 s->selected = g - first;
7691 return NULL; /* gline is on the current page */
7694 if (*ste != NULL) {
7695 i = got_tree_entry_get_index(*ste);
7696 i += off;
7699 if (i < g) {
7700 err = tree_scroll_down(view, g - i);
7701 if (err)
7702 return err;
7703 if (got_tree_entry_get_index(*lte) >=
7704 got_object_tree_get_nentries(s->tree) - 1 &&
7705 first + s->selected < g &&
7706 s->selected < s->ndisplayed - 1) {
7707 first = got_tree_entry_get_index(*fte);
7708 first += off;
7709 s->selected = g - first;
7711 } else if (i > g)
7712 tree_scroll_up(s, i - g);
7714 if (g < nlines &&
7715 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7716 s->selected = g - 1;
7718 return NULL;
7721 static const struct got_error *
7722 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7724 const struct got_error *err = NULL;
7725 struct tog_tree_view_state *s = &view->state.tree;
7726 struct got_tree_entry *te;
7727 int n, nscroll = view->nlines - 3;
7729 if (view->gline)
7730 return tree_goto_line(view, nscroll);
7732 switch (ch) {
7733 case '0':
7734 case '$':
7735 case KEY_RIGHT:
7736 case 'l':
7737 case KEY_LEFT:
7738 case 'h':
7739 horizontal_scroll_input(view, ch);
7740 break;
7741 case 'i':
7742 s->show_ids = !s->show_ids;
7743 view->count = 0;
7744 break;
7745 case 'L':
7746 view->count = 0;
7747 if (!s->selected_entry)
7748 break;
7749 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7750 break;
7751 case 'R':
7752 view->count = 0;
7753 err = view_request_new(new_view, view, TOG_VIEW_REF);
7754 break;
7755 case 'g':
7756 case '=':
7757 case KEY_HOME:
7758 s->selected = 0;
7759 view->count = 0;
7760 if (s->tree == s->root)
7761 s->first_displayed_entry =
7762 got_object_tree_get_first_entry(s->tree);
7763 else
7764 s->first_displayed_entry = NULL;
7765 break;
7766 case 'G':
7767 case '*':
7768 case KEY_END: {
7769 int eos = view->nlines - 3;
7771 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7772 --eos; /* border */
7773 s->selected = 0;
7774 view->count = 0;
7775 te = got_object_tree_get_last_entry(s->tree);
7776 for (n = 0; n < eos; n++) {
7777 if (te == NULL) {
7778 if (s->tree != s->root) {
7779 s->first_displayed_entry = NULL;
7780 n++;
7782 break;
7784 s->first_displayed_entry = te;
7785 te = got_tree_entry_get_prev(s->tree, te);
7787 if (n > 0)
7788 s->selected = n - 1;
7789 break;
7791 case 'k':
7792 case KEY_UP:
7793 case CTRL('p'):
7794 if (s->selected > 0) {
7795 s->selected--;
7796 break;
7798 tree_scroll_up(s, 1);
7799 if (s->selected_entry == NULL ||
7800 (s->tree == s->root && s->selected_entry ==
7801 got_object_tree_get_first_entry(s->tree)))
7802 view->count = 0;
7803 break;
7804 case CTRL('u'):
7805 case 'u':
7806 nscroll /= 2;
7807 /* FALL THROUGH */
7808 case KEY_PPAGE:
7809 case CTRL('b'):
7810 case 'b':
7811 if (s->tree == s->root) {
7812 if (got_object_tree_get_first_entry(s->tree) ==
7813 s->first_displayed_entry)
7814 s->selected -= MIN(s->selected, nscroll);
7815 } else {
7816 if (s->first_displayed_entry == NULL)
7817 s->selected -= MIN(s->selected, nscroll);
7819 tree_scroll_up(s, MAX(0, nscroll));
7820 if (s->selected_entry == NULL ||
7821 (s->tree == s->root && s->selected_entry ==
7822 got_object_tree_get_first_entry(s->tree)))
7823 view->count = 0;
7824 break;
7825 case 'j':
7826 case KEY_DOWN:
7827 case CTRL('n'):
7828 if (s->selected < s->ndisplayed - 1) {
7829 s->selected++;
7830 break;
7832 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7833 == NULL) {
7834 /* can't scroll any further */
7835 view->count = 0;
7836 break;
7838 tree_scroll_down(view, 1);
7839 break;
7840 case CTRL('d'):
7841 case 'd':
7842 nscroll /= 2;
7843 /* FALL THROUGH */
7844 case KEY_NPAGE:
7845 case CTRL('f'):
7846 case 'f':
7847 case ' ':
7848 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7849 == NULL) {
7850 /* can't scroll any further; move cursor down */
7851 if (s->selected < s->ndisplayed - 1)
7852 s->selected += MIN(nscroll,
7853 s->ndisplayed - s->selected - 1);
7854 else
7855 view->count = 0;
7856 break;
7858 tree_scroll_down(view, nscroll);
7859 break;
7860 case KEY_ENTER:
7861 case '\r':
7862 case KEY_BACKSPACE:
7863 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7864 struct tog_parent_tree *parent;
7865 /* user selected '..' */
7866 if (s->tree == s->root) {
7867 view->count = 0;
7868 break;
7870 parent = TAILQ_FIRST(&s->parents);
7871 TAILQ_REMOVE(&s->parents, parent,
7872 entry);
7873 got_object_tree_close(s->tree);
7874 s->tree = parent->tree;
7875 s->first_displayed_entry =
7876 parent->first_displayed_entry;
7877 s->selected_entry =
7878 parent->selected_entry;
7879 s->selected = parent->selected;
7880 if (s->selected > view->nlines - 3) {
7881 err = offset_selection_down(view);
7882 if (err)
7883 break;
7885 free(parent);
7886 } else if (S_ISDIR(got_tree_entry_get_mode(
7887 s->selected_entry))) {
7888 struct got_tree_object *subtree;
7889 view->count = 0;
7890 err = got_object_open_as_tree(&subtree, s->repo,
7891 got_tree_entry_get_id(s->selected_entry));
7892 if (err)
7893 break;
7894 err = tree_view_visit_subtree(s, subtree);
7895 if (err) {
7896 got_object_tree_close(subtree);
7897 break;
7899 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7900 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7901 break;
7902 case KEY_RESIZE:
7903 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7904 s->selected = view->nlines - 4;
7905 view->count = 0;
7906 break;
7907 default:
7908 view->count = 0;
7909 break;
7912 return err;
7915 __dead static void
7916 usage_tree(void)
7918 endwin();
7919 fprintf(stderr,
7920 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7921 getprogname());
7922 exit(1);
7925 static const struct got_error *
7926 cmd_tree(int argc, char *argv[])
7928 const struct got_error *error;
7929 struct got_repository *repo = NULL;
7930 struct got_worktree *worktree = NULL;
7931 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7932 struct got_object_id *commit_id = NULL;
7933 struct got_commit_object *commit = NULL;
7934 const char *commit_id_arg = NULL;
7935 char *label = NULL;
7936 struct got_reference *ref = NULL;
7937 const char *head_ref_name = NULL;
7938 int ch;
7939 struct tog_view *view;
7940 int *pack_fds = NULL;
7942 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7943 switch (ch) {
7944 case 'c':
7945 commit_id_arg = optarg;
7946 break;
7947 case 'r':
7948 repo_path = realpath(optarg, NULL);
7949 if (repo_path == NULL)
7950 return got_error_from_errno2("realpath",
7951 optarg);
7952 break;
7953 default:
7954 usage_tree();
7955 /* NOTREACHED */
7959 argc -= optind;
7960 argv += optind;
7962 if (argc > 1)
7963 usage_tree();
7965 error = got_repo_pack_fds_open(&pack_fds);
7966 if (error != NULL)
7967 goto done;
7969 if (repo_path == NULL) {
7970 cwd = getcwd(NULL, 0);
7971 if (cwd == NULL)
7972 return got_error_from_errno("getcwd");
7973 error = got_worktree_open(&worktree, cwd);
7974 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7975 goto done;
7976 if (worktree)
7977 repo_path =
7978 strdup(got_worktree_get_repo_path(worktree));
7979 else
7980 repo_path = strdup(cwd);
7981 if (repo_path == NULL) {
7982 error = got_error_from_errno("strdup");
7983 goto done;
7987 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7988 if (error != NULL)
7989 goto done;
7991 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7992 repo, worktree);
7993 if (error)
7994 goto done;
7996 init_curses();
7998 error = apply_unveil(got_repo_get_path(repo), NULL);
7999 if (error)
8000 goto done;
8002 error = tog_load_refs(repo, 0);
8003 if (error)
8004 goto done;
8006 if (commit_id_arg == NULL) {
8007 error = got_repo_match_object_id(&commit_id, &label,
8008 worktree ? got_worktree_get_head_ref_name(worktree) :
8009 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8010 if (error)
8011 goto done;
8012 head_ref_name = label;
8013 } else {
8014 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8015 if (error == NULL)
8016 head_ref_name = got_ref_get_name(ref);
8017 else if (error->code != GOT_ERR_NOT_REF)
8018 goto done;
8019 error = got_repo_match_object_id(&commit_id, NULL,
8020 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8021 if (error)
8022 goto done;
8025 error = got_object_open_as_commit(&commit, repo, commit_id);
8026 if (error)
8027 goto done;
8029 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8030 if (view == NULL) {
8031 error = got_error_from_errno("view_open");
8032 goto done;
8034 error = open_tree_view(view, commit_id, head_ref_name, repo);
8035 if (error)
8036 goto done;
8037 if (!got_path_is_root_dir(in_repo_path)) {
8038 error = tree_view_walk_path(&view->state.tree, commit,
8039 in_repo_path);
8040 if (error)
8041 goto done;
8044 if (worktree) {
8045 /* Release work tree lock. */
8046 got_worktree_close(worktree);
8047 worktree = NULL;
8049 error = view_loop(view);
8050 done:
8051 free(repo_path);
8052 free(cwd);
8053 free(commit_id);
8054 free(label);
8055 if (ref)
8056 got_ref_close(ref);
8057 if (repo) {
8058 const struct got_error *close_err = got_repo_close(repo);
8059 if (error == NULL)
8060 error = close_err;
8062 if (pack_fds) {
8063 const struct got_error *pack_err =
8064 got_repo_pack_fds_close(pack_fds);
8065 if (error == NULL)
8066 error = pack_err;
8068 tog_free_refs();
8069 return error;
8072 static const struct got_error *
8073 ref_view_load_refs(struct tog_ref_view_state *s)
8075 struct got_reflist_entry *sre;
8076 struct tog_reflist_entry *re;
8078 s->nrefs = 0;
8079 TAILQ_FOREACH(sre, &tog_refs, entry) {
8080 if (strncmp(got_ref_get_name(sre->ref),
8081 "refs/got/", 9) == 0 &&
8082 strncmp(got_ref_get_name(sre->ref),
8083 "refs/got/backup/", 16) != 0)
8084 continue;
8086 re = malloc(sizeof(*re));
8087 if (re == NULL)
8088 return got_error_from_errno("malloc");
8090 re->ref = got_ref_dup(sre->ref);
8091 if (re->ref == NULL)
8092 return got_error_from_errno("got_ref_dup");
8093 re->idx = s->nrefs++;
8094 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8097 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8098 return NULL;
8101 static void
8102 ref_view_free_refs(struct tog_ref_view_state *s)
8104 struct tog_reflist_entry *re;
8106 while (!TAILQ_EMPTY(&s->refs)) {
8107 re = TAILQ_FIRST(&s->refs);
8108 TAILQ_REMOVE(&s->refs, re, entry);
8109 got_ref_close(re->ref);
8110 free(re);
8114 static const struct got_error *
8115 open_ref_view(struct tog_view *view, struct got_repository *repo)
8117 const struct got_error *err = NULL;
8118 struct tog_ref_view_state *s = &view->state.ref;
8120 s->selected_entry = 0;
8121 s->repo = repo;
8123 TAILQ_INIT(&s->refs);
8124 STAILQ_INIT(&s->colors);
8126 err = ref_view_load_refs(s);
8127 if (err)
8128 goto done;
8130 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8131 err = add_color(&s->colors, "^refs/heads/",
8132 TOG_COLOR_REFS_HEADS,
8133 get_color_value("TOG_COLOR_REFS_HEADS"));
8134 if (err)
8135 goto done;
8137 err = add_color(&s->colors, "^refs/tags/",
8138 TOG_COLOR_REFS_TAGS,
8139 get_color_value("TOG_COLOR_REFS_TAGS"));
8140 if (err)
8141 goto done;
8143 err = add_color(&s->colors, "^refs/remotes/",
8144 TOG_COLOR_REFS_REMOTES,
8145 get_color_value("TOG_COLOR_REFS_REMOTES"));
8146 if (err)
8147 goto done;
8149 err = add_color(&s->colors, "^refs/got/backup/",
8150 TOG_COLOR_REFS_BACKUP,
8151 get_color_value("TOG_COLOR_REFS_BACKUP"));
8152 if (err)
8153 goto done;
8156 view->show = show_ref_view;
8157 view->input = input_ref_view;
8158 view->close = close_ref_view;
8159 view->search_start = search_start_ref_view;
8160 view->search_next = search_next_ref_view;
8161 done:
8162 if (err) {
8163 if (view->close == NULL)
8164 close_ref_view(view);
8165 view_close(view);
8167 return err;
8170 static const struct got_error *
8171 close_ref_view(struct tog_view *view)
8173 struct tog_ref_view_state *s = &view->state.ref;
8175 ref_view_free_refs(s);
8176 free_colors(&s->colors);
8178 return NULL;
8181 static const struct got_error *
8182 resolve_reflist_entry(struct got_object_id **commit_id,
8183 struct tog_reflist_entry *re, struct got_repository *repo)
8185 const struct got_error *err = NULL;
8186 struct got_object_id *obj_id;
8187 struct got_tag_object *tag = NULL;
8188 int obj_type;
8190 *commit_id = NULL;
8192 err = got_ref_resolve(&obj_id, repo, re->ref);
8193 if (err)
8194 return err;
8196 err = got_object_get_type(&obj_type, repo, obj_id);
8197 if (err)
8198 goto done;
8200 switch (obj_type) {
8201 case GOT_OBJ_TYPE_COMMIT:
8202 *commit_id = obj_id;
8203 break;
8204 case GOT_OBJ_TYPE_TAG:
8205 err = got_object_open_as_tag(&tag, repo, obj_id);
8206 if (err)
8207 goto done;
8208 free(obj_id);
8209 err = got_object_get_type(&obj_type, repo,
8210 got_object_tag_get_object_id(tag));
8211 if (err)
8212 goto done;
8213 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8214 err = got_error(GOT_ERR_OBJ_TYPE);
8215 goto done;
8217 *commit_id = got_object_id_dup(
8218 got_object_tag_get_object_id(tag));
8219 if (*commit_id == NULL) {
8220 err = got_error_from_errno("got_object_id_dup");
8221 goto done;
8223 break;
8224 default:
8225 err = got_error(GOT_ERR_OBJ_TYPE);
8226 break;
8229 done:
8230 if (tag)
8231 got_object_tag_close(tag);
8232 if (err) {
8233 free(*commit_id);
8234 *commit_id = NULL;
8236 return err;
8239 static const struct got_error *
8240 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8241 struct tog_reflist_entry *re, struct got_repository *repo)
8243 struct tog_view *log_view;
8244 const struct got_error *err = NULL;
8245 struct got_object_id *commit_id = NULL;
8247 *new_view = NULL;
8249 err = resolve_reflist_entry(&commit_id, re, repo);
8250 if (err) {
8251 if (err->code != GOT_ERR_OBJ_TYPE)
8252 return err;
8253 else
8254 return NULL;
8257 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8258 if (log_view == NULL) {
8259 err = got_error_from_errno("view_open");
8260 goto done;
8263 err = open_log_view(log_view, commit_id, repo,
8264 got_ref_get_name(re->ref), "", 0);
8265 done:
8266 if (err)
8267 view_close(log_view);
8268 else
8269 *new_view = log_view;
8270 free(commit_id);
8271 return err;
8274 static void
8275 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8277 struct tog_reflist_entry *re;
8278 int i = 0;
8280 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8281 return;
8283 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8284 while (i++ < maxscroll) {
8285 if (re == NULL)
8286 break;
8287 s->first_displayed_entry = re;
8288 re = TAILQ_PREV(re, tog_reflist_head, entry);
8292 static const struct got_error *
8293 ref_scroll_down(struct tog_view *view, int maxscroll)
8295 struct tog_ref_view_state *s = &view->state.ref;
8296 struct tog_reflist_entry *next, *last;
8297 int n = 0;
8299 if (s->first_displayed_entry)
8300 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8301 else
8302 next = TAILQ_FIRST(&s->refs);
8304 last = s->last_displayed_entry;
8305 while (next && n++ < maxscroll) {
8306 if (last) {
8307 s->last_displayed_entry = last;
8308 last = TAILQ_NEXT(last, entry);
8310 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8311 s->first_displayed_entry = next;
8312 next = TAILQ_NEXT(next, entry);
8316 return NULL;
8319 static const struct got_error *
8320 search_start_ref_view(struct tog_view *view)
8322 struct tog_ref_view_state *s = &view->state.ref;
8324 s->matched_entry = NULL;
8325 return NULL;
8328 static int
8329 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8331 regmatch_t regmatch;
8333 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8334 0) == 0;
8337 static const struct got_error *
8338 search_next_ref_view(struct tog_view *view)
8340 struct tog_ref_view_state *s = &view->state.ref;
8341 struct tog_reflist_entry *re = NULL;
8343 if (!view->searching) {
8344 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8345 return NULL;
8348 if (s->matched_entry) {
8349 if (view->searching == TOG_SEARCH_FORWARD) {
8350 if (s->selected_entry)
8351 re = TAILQ_NEXT(s->selected_entry, entry);
8352 else
8353 re = TAILQ_PREV(s->selected_entry,
8354 tog_reflist_head, entry);
8355 } else {
8356 if (s->selected_entry == NULL)
8357 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8358 else
8359 re = TAILQ_PREV(s->selected_entry,
8360 tog_reflist_head, entry);
8362 } else {
8363 if (s->selected_entry)
8364 re = s->selected_entry;
8365 else if (view->searching == TOG_SEARCH_FORWARD)
8366 re = TAILQ_FIRST(&s->refs);
8367 else
8368 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8371 while (1) {
8372 if (re == NULL) {
8373 if (s->matched_entry == NULL) {
8374 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8375 return NULL;
8377 if (view->searching == TOG_SEARCH_FORWARD)
8378 re = TAILQ_FIRST(&s->refs);
8379 else
8380 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8383 if (match_reflist_entry(re, &view->regex)) {
8384 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8385 s->matched_entry = re;
8386 break;
8389 if (view->searching == TOG_SEARCH_FORWARD)
8390 re = TAILQ_NEXT(re, entry);
8391 else
8392 re = TAILQ_PREV(re, tog_reflist_head, entry);
8395 if (s->matched_entry) {
8396 s->first_displayed_entry = s->matched_entry;
8397 s->selected = 0;
8400 return NULL;
8403 static const struct got_error *
8404 show_ref_view(struct tog_view *view)
8406 const struct got_error *err = NULL;
8407 struct tog_ref_view_state *s = &view->state.ref;
8408 struct tog_reflist_entry *re;
8409 char *line = NULL;
8410 wchar_t *wline;
8411 struct tog_color *tc;
8412 int width, n, scrollx;
8413 int limit = view->nlines;
8415 werase(view->window);
8417 s->ndisplayed = 0;
8418 if (view_is_hsplit_top(view))
8419 --limit; /* border */
8421 if (limit == 0)
8422 return NULL;
8424 re = s->first_displayed_entry;
8426 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8427 s->nrefs) == -1)
8428 return got_error_from_errno("asprintf");
8430 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8431 if (err) {
8432 free(line);
8433 return err;
8435 if (view_needs_focus_indication(view))
8436 wstandout(view->window);
8437 waddwstr(view->window, wline);
8438 while (width++ < view->ncols)
8439 waddch(view->window, ' ');
8440 if (view_needs_focus_indication(view))
8441 wstandend(view->window);
8442 free(wline);
8443 wline = NULL;
8444 free(line);
8445 line = NULL;
8446 if (--limit <= 0)
8447 return NULL;
8449 n = 0;
8450 view->maxx = 0;
8451 while (re && limit > 0) {
8452 char *line = NULL;
8453 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8455 if (s->show_date) {
8456 struct got_commit_object *ci;
8457 struct got_tag_object *tag;
8458 struct got_object_id *id;
8459 struct tm tm;
8460 time_t t;
8462 err = got_ref_resolve(&id, s->repo, re->ref);
8463 if (err)
8464 return err;
8465 err = got_object_open_as_tag(&tag, s->repo, id);
8466 if (err) {
8467 if (err->code != GOT_ERR_OBJ_TYPE) {
8468 free(id);
8469 return err;
8471 err = got_object_open_as_commit(&ci, s->repo,
8472 id);
8473 if (err) {
8474 free(id);
8475 return err;
8477 t = got_object_commit_get_committer_time(ci);
8478 got_object_commit_close(ci);
8479 } else {
8480 t = got_object_tag_get_tagger_time(tag);
8481 got_object_tag_close(tag);
8483 free(id);
8484 if (gmtime_r(&t, &tm) == NULL)
8485 return got_error_from_errno("gmtime_r");
8486 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8487 return got_error(GOT_ERR_NO_SPACE);
8489 if (got_ref_is_symbolic(re->ref)) {
8490 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8491 ymd : "", got_ref_get_name(re->ref),
8492 got_ref_get_symref_target(re->ref)) == -1)
8493 return got_error_from_errno("asprintf");
8494 } else if (s->show_ids) {
8495 struct got_object_id *id;
8496 char *id_str;
8497 err = got_ref_resolve(&id, s->repo, re->ref);
8498 if (err)
8499 return err;
8500 err = got_object_id_str(&id_str, id);
8501 if (err) {
8502 free(id);
8503 return err;
8505 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8506 got_ref_get_name(re->ref), id_str) == -1) {
8507 err = got_error_from_errno("asprintf");
8508 free(id);
8509 free(id_str);
8510 return err;
8512 free(id);
8513 free(id_str);
8514 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8515 got_ref_get_name(re->ref)) == -1)
8516 return got_error_from_errno("asprintf");
8518 /* use full line width to determine view->maxx */
8519 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8520 if (err) {
8521 free(line);
8522 return err;
8524 view->maxx = MAX(view->maxx, width);
8525 free(wline);
8526 wline = NULL;
8528 err = format_line(&wline, &width, &scrollx, line, view->x,
8529 view->ncols, 0, 0);
8530 if (err) {
8531 free(line);
8532 return err;
8534 if (n == s->selected) {
8535 if (view->focussed)
8536 wstandout(view->window);
8537 s->selected_entry = re;
8539 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8540 if (tc)
8541 wattr_on(view->window,
8542 COLOR_PAIR(tc->colorpair), NULL);
8543 waddwstr(view->window, &wline[scrollx]);
8544 if (tc)
8545 wattr_off(view->window,
8546 COLOR_PAIR(tc->colorpair), NULL);
8547 if (width < view->ncols)
8548 waddch(view->window, '\n');
8549 if (n == s->selected && view->focussed)
8550 wstandend(view->window);
8551 free(line);
8552 free(wline);
8553 wline = NULL;
8554 n++;
8555 s->ndisplayed++;
8556 s->last_displayed_entry = re;
8558 limit--;
8559 re = TAILQ_NEXT(re, entry);
8562 view_border(view);
8563 return err;
8566 static const struct got_error *
8567 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8568 struct tog_reflist_entry *re, struct got_repository *repo)
8570 const struct got_error *err = NULL;
8571 struct got_object_id *commit_id = NULL;
8572 struct tog_view *tree_view;
8574 *new_view = NULL;
8576 err = resolve_reflist_entry(&commit_id, re, repo);
8577 if (err) {
8578 if (err->code != GOT_ERR_OBJ_TYPE)
8579 return err;
8580 else
8581 return NULL;
8585 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8586 if (tree_view == NULL) {
8587 err = got_error_from_errno("view_open");
8588 goto done;
8591 err = open_tree_view(tree_view, commit_id,
8592 got_ref_get_name(re->ref), repo);
8593 if (err)
8594 goto done;
8596 *new_view = tree_view;
8597 done:
8598 free(commit_id);
8599 return err;
8602 static const struct got_error *
8603 ref_goto_line(struct tog_view *view, int nlines)
8605 const struct got_error *err = NULL;
8606 struct tog_ref_view_state *s = &view->state.ref;
8607 int g, idx = s->selected_entry->idx;
8609 g = view->gline;
8610 view->gline = 0;
8612 if (g == 0)
8613 g = 1;
8614 else if (g > s->nrefs)
8615 g = s->nrefs;
8617 if (g >= s->first_displayed_entry->idx + 1 &&
8618 g <= s->last_displayed_entry->idx + 1 &&
8619 g - s->first_displayed_entry->idx - 1 < nlines) {
8620 s->selected = g - s->first_displayed_entry->idx - 1;
8621 return NULL;
8624 if (idx + 1 < g) {
8625 err = ref_scroll_down(view, g - idx - 1);
8626 if (err)
8627 return err;
8628 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8629 s->first_displayed_entry->idx + s->selected < g &&
8630 s->selected < s->ndisplayed - 1)
8631 s->selected = g - s->first_displayed_entry->idx - 1;
8632 } else if (idx + 1 > g)
8633 ref_scroll_up(s, idx - g + 1);
8635 if (g < nlines && s->first_displayed_entry->idx == 0)
8636 s->selected = g - 1;
8638 return NULL;
8642 static const struct got_error *
8643 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8645 const struct got_error *err = NULL;
8646 struct tog_ref_view_state *s = &view->state.ref;
8647 struct tog_reflist_entry *re;
8648 int n, nscroll = view->nlines - 1;
8650 if (view->gline)
8651 return ref_goto_line(view, nscroll);
8653 switch (ch) {
8654 case '0':
8655 case '$':
8656 case KEY_RIGHT:
8657 case 'l':
8658 case KEY_LEFT:
8659 case 'h':
8660 horizontal_scroll_input(view, ch);
8661 break;
8662 case 'i':
8663 s->show_ids = !s->show_ids;
8664 view->count = 0;
8665 break;
8666 case 'm':
8667 s->show_date = !s->show_date;
8668 view->count = 0;
8669 break;
8670 case 'o':
8671 s->sort_by_date = !s->sort_by_date;
8672 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8673 view->count = 0;
8674 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8675 got_ref_cmp_by_commit_timestamp_descending :
8676 tog_ref_cmp_by_name, s->repo);
8677 if (err)
8678 break;
8679 got_reflist_object_id_map_free(tog_refs_idmap);
8680 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8681 &tog_refs, s->repo);
8682 if (err)
8683 break;
8684 ref_view_free_refs(s);
8685 err = ref_view_load_refs(s);
8686 break;
8687 case KEY_ENTER:
8688 case '\r':
8689 view->count = 0;
8690 if (!s->selected_entry)
8691 break;
8692 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8693 break;
8694 case 'T':
8695 view->count = 0;
8696 if (!s->selected_entry)
8697 break;
8698 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8699 break;
8700 case 'g':
8701 case '=':
8702 case KEY_HOME:
8703 s->selected = 0;
8704 view->count = 0;
8705 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8706 break;
8707 case 'G':
8708 case '*':
8709 case KEY_END: {
8710 int eos = view->nlines - 1;
8712 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8713 --eos; /* border */
8714 s->selected = 0;
8715 view->count = 0;
8716 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8717 for (n = 0; n < eos; n++) {
8718 if (re == NULL)
8719 break;
8720 s->first_displayed_entry = re;
8721 re = TAILQ_PREV(re, tog_reflist_head, entry);
8723 if (n > 0)
8724 s->selected = n - 1;
8725 break;
8727 case 'k':
8728 case KEY_UP:
8729 case CTRL('p'):
8730 if (s->selected > 0) {
8731 s->selected--;
8732 break;
8734 ref_scroll_up(s, 1);
8735 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8736 view->count = 0;
8737 break;
8738 case CTRL('u'):
8739 case 'u':
8740 nscroll /= 2;
8741 /* FALL THROUGH */
8742 case KEY_PPAGE:
8743 case CTRL('b'):
8744 case 'b':
8745 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8746 s->selected -= MIN(nscroll, s->selected);
8747 ref_scroll_up(s, MAX(0, nscroll));
8748 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8749 view->count = 0;
8750 break;
8751 case 'j':
8752 case KEY_DOWN:
8753 case CTRL('n'):
8754 if (s->selected < s->ndisplayed - 1) {
8755 s->selected++;
8756 break;
8758 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8759 /* can't scroll any further */
8760 view->count = 0;
8761 break;
8763 ref_scroll_down(view, 1);
8764 break;
8765 case CTRL('d'):
8766 case 'd':
8767 nscroll /= 2;
8768 /* FALL THROUGH */
8769 case KEY_NPAGE:
8770 case CTRL('f'):
8771 case 'f':
8772 case ' ':
8773 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8774 /* can't scroll any further; move cursor down */
8775 if (s->selected < s->ndisplayed - 1)
8776 s->selected += MIN(nscroll,
8777 s->ndisplayed - s->selected - 1);
8778 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8779 s->selected += s->ndisplayed - s->selected - 1;
8780 view->count = 0;
8781 break;
8783 ref_scroll_down(view, nscroll);
8784 break;
8785 case CTRL('l'):
8786 view->count = 0;
8787 tog_free_refs();
8788 err = tog_load_refs(s->repo, s->sort_by_date);
8789 if (err)
8790 break;
8791 ref_view_free_refs(s);
8792 err = ref_view_load_refs(s);
8793 break;
8794 case KEY_RESIZE:
8795 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8796 s->selected = view->nlines - 2;
8797 break;
8798 default:
8799 view->count = 0;
8800 break;
8803 return err;
8806 __dead static void
8807 usage_ref(void)
8809 endwin();
8810 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8811 getprogname());
8812 exit(1);
8815 static const struct got_error *
8816 cmd_ref(int argc, char *argv[])
8818 const struct got_error *error;
8819 struct got_repository *repo = NULL;
8820 struct got_worktree *worktree = NULL;
8821 char *cwd = NULL, *repo_path = NULL;
8822 int ch;
8823 struct tog_view *view;
8824 int *pack_fds = NULL;
8826 while ((ch = getopt(argc, argv, "r:")) != -1) {
8827 switch (ch) {
8828 case 'r':
8829 repo_path = realpath(optarg, NULL);
8830 if (repo_path == NULL)
8831 return got_error_from_errno2("realpath",
8832 optarg);
8833 break;
8834 default:
8835 usage_ref();
8836 /* NOTREACHED */
8840 argc -= optind;
8841 argv += optind;
8843 if (argc > 1)
8844 usage_ref();
8846 error = got_repo_pack_fds_open(&pack_fds);
8847 if (error != NULL)
8848 goto done;
8850 if (repo_path == NULL) {
8851 cwd = getcwd(NULL, 0);
8852 if (cwd == NULL)
8853 return got_error_from_errno("getcwd");
8854 error = got_worktree_open(&worktree, cwd);
8855 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8856 goto done;
8857 if (worktree)
8858 repo_path =
8859 strdup(got_worktree_get_repo_path(worktree));
8860 else
8861 repo_path = strdup(cwd);
8862 if (repo_path == NULL) {
8863 error = got_error_from_errno("strdup");
8864 goto done;
8868 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8869 if (error != NULL)
8870 goto done;
8872 init_curses();
8874 error = apply_unveil(got_repo_get_path(repo), NULL);
8875 if (error)
8876 goto done;
8878 error = tog_load_refs(repo, 0);
8879 if (error)
8880 goto done;
8882 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8883 if (view == NULL) {
8884 error = got_error_from_errno("view_open");
8885 goto done;
8888 error = open_ref_view(view, repo);
8889 if (error)
8890 goto done;
8892 if (worktree) {
8893 /* Release work tree lock. */
8894 got_worktree_close(worktree);
8895 worktree = NULL;
8897 error = view_loop(view);
8898 done:
8899 free(repo_path);
8900 free(cwd);
8901 if (repo) {
8902 const struct got_error *close_err = got_repo_close(repo);
8903 if (close_err)
8904 error = close_err;
8906 if (pack_fds) {
8907 const struct got_error *pack_err =
8908 got_repo_pack_fds_close(pack_fds);
8909 if (error == NULL)
8910 error = pack_err;
8912 tog_free_refs();
8913 return error;
8916 static const struct got_error*
8917 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8918 const char *str)
8920 size_t len;
8922 if (win == NULL)
8923 win = stdscr;
8925 len = strlen(str);
8926 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8928 if (focus)
8929 wstandout(win);
8930 if (mvwprintw(win, y, x, "%s", str) == ERR)
8931 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8932 if (focus)
8933 wstandend(win);
8935 return NULL;
8938 static const struct got_error *
8939 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8941 off_t *p;
8943 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8944 if (p == NULL) {
8945 free(*line_offsets);
8946 *line_offsets = NULL;
8947 return got_error_from_errno("reallocarray");
8950 *line_offsets = p;
8951 (*line_offsets)[*nlines] = off;
8952 ++(*nlines);
8953 return NULL;
8956 static const struct got_error *
8957 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8959 *ret = 0;
8961 for (;n > 0; --n, ++km) {
8962 char *t0, *t, *k;
8963 size_t len = 1;
8965 if (km->keys == NULL)
8966 continue;
8968 t = t0 = strdup(km->keys);
8969 if (t0 == NULL)
8970 return got_error_from_errno("strdup");
8972 len += strlen(t);
8973 while ((k = strsep(&t, " ")) != NULL)
8974 len += strlen(k) > 1 ? 2 : 0;
8975 free(t0);
8976 *ret = MAX(*ret, len);
8979 return NULL;
8983 * Write keymap section headers, keys, and key info in km to f.
8984 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8985 * wrap control and symbolic keys in guillemets, else use <>.
8987 static const struct got_error *
8988 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8990 int n, len = width;
8992 if (km->keys) {
8993 static const char *u8_glyph[] = {
8994 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8995 "\xe2\x80\xba" /* U+203A (utf8 >) */
8997 char *t0, *t, *k;
8998 int cs, s, first = 1;
9000 cs = got_locale_is_utf8();
9002 t = t0 = strdup(km->keys);
9003 if (t0 == NULL)
9004 return got_error_from_errno("strdup");
9006 len = strlen(km->keys);
9007 while ((k = strsep(&t, " ")) != NULL) {
9008 s = strlen(k) > 1; /* control or symbolic key */
9009 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9010 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9011 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9012 if (n < 0) {
9013 free(t0);
9014 return got_error_from_errno("fprintf");
9016 first = 0;
9017 len += s ? 2 : 0;
9018 *off += n;
9020 free(t0);
9022 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9023 if (n < 0)
9024 return got_error_from_errno("fprintf");
9025 *off += n;
9027 return NULL;
9030 static const struct got_error *
9031 format_help(struct tog_help_view_state *s)
9033 const struct got_error *err = NULL;
9034 off_t off = 0;
9035 int i, max, n, show = s->all;
9036 static const struct tog_key_map km[] = {
9037 #define KEYMAP_(info, type) { NULL, (info), type }
9038 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9039 GENERATE_HELP
9040 #undef KEYMAP_
9041 #undef KEY_
9044 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9045 if (err)
9046 return err;
9048 n = nitems(km);
9049 err = max_key_str(&max, km, n);
9050 if (err)
9051 return err;
9053 for (i = 0; i < n; ++i) {
9054 if (km[i].keys == NULL) {
9055 show = s->all;
9056 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9057 km[i].type == s->type || s->all)
9058 show = 1;
9060 if (show) {
9061 err = format_help_line(&off, s->f, &km[i], max);
9062 if (err)
9063 return err;
9064 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9065 if (err)
9066 return err;
9069 fputc('\n', s->f);
9070 ++off;
9071 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9072 return err;
9075 static const struct got_error *
9076 create_help(struct tog_help_view_state *s)
9078 FILE *f;
9079 const struct got_error *err;
9081 free(s->line_offsets);
9082 s->line_offsets = NULL;
9083 s->nlines = 0;
9085 f = got_opentemp();
9086 if (f == NULL)
9087 return got_error_from_errno("got_opentemp");
9088 s->f = f;
9090 err = format_help(s);
9091 if (err)
9092 return err;
9094 if (s->f && fflush(s->f) != 0)
9095 return got_error_from_errno("fflush");
9097 return NULL;
9100 static const struct got_error *
9101 search_start_help_view(struct tog_view *view)
9103 view->state.help.matched_line = 0;
9104 return NULL;
9107 static void
9108 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9109 size_t *nlines, int **first, int **last, int **match, int **selected)
9111 struct tog_help_view_state *s = &view->state.help;
9113 *f = s->f;
9114 *nlines = s->nlines;
9115 *line_offsets = s->line_offsets;
9116 *match = &s->matched_line;
9117 *first = &s->first_displayed_line;
9118 *last = &s->last_displayed_line;
9119 *selected = &s->selected_line;
9122 static const struct got_error *
9123 show_help_view(struct tog_view *view)
9125 struct tog_help_view_state *s = &view->state.help;
9126 const struct got_error *err;
9127 regmatch_t *regmatch = &view->regmatch;
9128 wchar_t *wline;
9129 char *line;
9130 ssize_t linelen;
9131 size_t linesz = 0;
9132 int width, nprinted = 0, rc = 0;
9133 int eos = view->nlines;
9135 if (view_is_hsplit_top(view))
9136 --eos; /* account for border */
9138 s->lineno = 0;
9139 rewind(s->f);
9140 werase(view->window);
9142 if (view->gline > s->nlines - 1)
9143 view->gline = s->nlines - 1;
9145 err = win_draw_center(view->window, 0, 0, view->ncols,
9146 view_needs_focus_indication(view),
9147 "tog help (press q to return to tog)");
9148 if (err)
9149 return err;
9150 if (eos <= 1)
9151 return NULL;
9152 waddstr(view->window, "\n\n");
9153 eos -= 2;
9155 s->eof = 0;
9156 view->maxx = 0;
9157 line = NULL;
9158 while (eos > 0 && nprinted < eos) {
9159 attr_t attr = 0;
9161 linelen = getline(&line, &linesz, s->f);
9162 if (linelen == -1) {
9163 if (!feof(s->f)) {
9164 free(line);
9165 return got_ferror(s->f, GOT_ERR_IO);
9167 s->eof = 1;
9168 break;
9170 if (++s->lineno < s->first_displayed_line)
9171 continue;
9172 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9173 continue;
9174 if (s->lineno == view->hiline)
9175 attr = A_STANDOUT;
9177 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9178 view->x ? 1 : 0);
9179 if (err) {
9180 free(line);
9181 return err;
9183 view->maxx = MAX(view->maxx, width);
9184 free(wline);
9185 wline = NULL;
9187 if (attr)
9188 wattron(view->window, attr);
9189 if (s->first_displayed_line + nprinted == s->matched_line &&
9190 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9191 err = add_matched_line(&width, line, view->ncols - 1, 0,
9192 view->window, view->x, regmatch);
9193 if (err) {
9194 free(line);
9195 return err;
9197 } else {
9198 int skip;
9200 err = format_line(&wline, &width, &skip, line,
9201 view->x, view->ncols, 0, view->x ? 1 : 0);
9202 if (err) {
9203 free(line);
9204 return err;
9206 waddwstr(view->window, &wline[skip]);
9207 free(wline);
9208 wline = NULL;
9210 if (s->lineno == view->hiline) {
9211 while (width++ < view->ncols)
9212 waddch(view->window, ' ');
9213 } else {
9214 if (width < view->ncols)
9215 waddch(view->window, '\n');
9217 if (attr)
9218 wattroff(view->window, attr);
9219 if (++nprinted == 1)
9220 s->first_displayed_line = s->lineno;
9222 free(line);
9223 if (nprinted > 0)
9224 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9225 else
9226 s->last_displayed_line = s->first_displayed_line;
9228 view_border(view);
9230 if (s->eof) {
9231 rc = waddnstr(view->window,
9232 "See the tog(1) manual page for full documentation",
9233 view->ncols - 1);
9234 if (rc == ERR)
9235 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9236 } else {
9237 wmove(view->window, view->nlines - 1, 0);
9238 wclrtoeol(view->window);
9239 wstandout(view->window);
9240 rc = waddnstr(view->window, "scroll down for more...",
9241 view->ncols - 1);
9242 if (rc == ERR)
9243 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9244 if (getcurx(view->window) < view->ncols - 6) {
9245 rc = wprintw(view->window, "[%.0f%%]",
9246 100.00 * s->last_displayed_line / s->nlines);
9247 if (rc == ERR)
9248 return got_error_msg(GOT_ERR_IO, "wprintw");
9250 wstandend(view->window);
9253 return NULL;
9256 static const struct got_error *
9257 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9259 struct tog_help_view_state *s = &view->state.help;
9260 const struct got_error *err = NULL;
9261 char *line = NULL;
9262 ssize_t linelen;
9263 size_t linesz = 0;
9264 int eos, nscroll;
9266 eos = nscroll = view->nlines;
9267 if (view_is_hsplit_top(view))
9268 --eos; /* border */
9270 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9272 switch (ch) {
9273 case '0':
9274 case '$':
9275 case KEY_RIGHT:
9276 case 'l':
9277 case KEY_LEFT:
9278 case 'h':
9279 horizontal_scroll_input(view, ch);
9280 break;
9281 case 'g':
9282 case KEY_HOME:
9283 s->first_displayed_line = 1;
9284 view->count = 0;
9285 break;
9286 case 'G':
9287 case KEY_END:
9288 view->count = 0;
9289 if (s->eof)
9290 break;
9291 s->first_displayed_line = (s->nlines - eos) + 3;
9292 s->eof = 1;
9293 break;
9294 case 'k':
9295 case KEY_UP:
9296 if (s->first_displayed_line > 1)
9297 --s->first_displayed_line;
9298 else
9299 view->count = 0;
9300 break;
9301 case CTRL('u'):
9302 case 'u':
9303 nscroll /= 2;
9304 /* FALL THROUGH */
9305 case KEY_PPAGE:
9306 case CTRL('b'):
9307 case 'b':
9308 if (s->first_displayed_line == 1) {
9309 view->count = 0;
9310 break;
9312 while (--nscroll > 0 && s->first_displayed_line > 1)
9313 s->first_displayed_line--;
9314 break;
9315 case 'j':
9316 case KEY_DOWN:
9317 case CTRL('n'):
9318 if (!s->eof)
9319 ++s->first_displayed_line;
9320 else
9321 view->count = 0;
9322 break;
9323 case CTRL('d'):
9324 case 'd':
9325 nscroll /= 2;
9326 /* FALL THROUGH */
9327 case KEY_NPAGE:
9328 case CTRL('f'):
9329 case 'f':
9330 case ' ':
9331 if (s->eof) {
9332 view->count = 0;
9333 break;
9335 while (!s->eof && --nscroll > 0) {
9336 linelen = getline(&line, &linesz, s->f);
9337 s->first_displayed_line++;
9338 if (linelen == -1) {
9339 if (feof(s->f))
9340 s->eof = 1;
9341 else
9342 err = got_ferror(s->f, GOT_ERR_IO);
9343 break;
9346 free(line);
9347 break;
9348 default:
9349 view->count = 0;
9350 break;
9353 return err;
9356 static const struct got_error *
9357 close_help_view(struct tog_view *view)
9359 struct tog_help_view_state *s = &view->state.help;
9361 free(s->line_offsets);
9362 s->line_offsets = NULL;
9363 if (fclose(s->f) == EOF)
9364 return got_error_from_errno("fclose");
9366 return NULL;
9369 static const struct got_error *
9370 reset_help_view(struct tog_view *view)
9372 struct tog_help_view_state *s = &view->state.help;
9375 if (s->f && fclose(s->f) == EOF)
9376 return got_error_from_errno("fclose");
9378 wclear(view->window);
9379 view->count = 0;
9380 view->x = 0;
9381 s->all = !s->all;
9382 s->first_displayed_line = 1;
9383 s->last_displayed_line = view->nlines;
9384 s->matched_line = 0;
9386 return create_help(s);
9389 static const struct got_error *
9390 open_help_view(struct tog_view *view, struct tog_view *parent)
9392 const struct got_error *err = NULL;
9393 struct tog_help_view_state *s = &view->state.help;
9395 s->type = (enum tog_keymap_type)parent->type;
9396 s->first_displayed_line = 1;
9397 s->last_displayed_line = view->nlines;
9398 s->selected_line = 1;
9400 view->show = show_help_view;
9401 view->input = input_help_view;
9402 view->reset = reset_help_view;
9403 view->close = close_help_view;
9404 view->search_start = search_start_help_view;
9405 view->search_setup = search_setup_help_view;
9406 view->search_next = search_next_view_match;
9408 err = create_help(s);
9409 return err;
9412 static const struct got_error *
9413 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9414 enum tog_view_type request, int y, int x)
9416 const struct got_error *err = NULL;
9418 *new_view = NULL;
9420 switch (request) {
9421 case TOG_VIEW_DIFF:
9422 if (view->type == TOG_VIEW_LOG) {
9423 struct tog_log_view_state *s = &view->state.log;
9425 err = open_diff_view_for_commit(new_view, y, x,
9426 s->selected_entry->commit, s->selected_entry->id,
9427 view, s->repo);
9428 } else
9429 return got_error_msg(GOT_ERR_NOT_IMPL,
9430 "parent/child view pair not supported");
9431 break;
9432 case TOG_VIEW_BLAME:
9433 if (view->type == TOG_VIEW_TREE) {
9434 struct tog_tree_view_state *s = &view->state.tree;
9436 err = blame_tree_entry(new_view, y, x,
9437 s->selected_entry, &s->parents, s->commit_id,
9438 s->repo);
9439 } else
9440 return got_error_msg(GOT_ERR_NOT_IMPL,
9441 "parent/child view pair not supported");
9442 break;
9443 case TOG_VIEW_LOG:
9444 if (view->type == TOG_VIEW_BLAME)
9445 err = log_annotated_line(new_view, y, x,
9446 view->state.blame.repo, view->state.blame.id_to_log);
9447 else if (view->type == TOG_VIEW_TREE)
9448 err = log_selected_tree_entry(new_view, y, x,
9449 &view->state.tree);
9450 else if (view->type == TOG_VIEW_REF)
9451 err = log_ref_entry(new_view, y, x,
9452 view->state.ref.selected_entry,
9453 view->state.ref.repo);
9454 else
9455 return got_error_msg(GOT_ERR_NOT_IMPL,
9456 "parent/child view pair not supported");
9457 break;
9458 case TOG_VIEW_TREE:
9459 if (view->type == TOG_VIEW_LOG)
9460 err = browse_commit_tree(new_view, y, x,
9461 view->state.log.selected_entry,
9462 view->state.log.in_repo_path,
9463 view->state.log.head_ref_name,
9464 view->state.log.repo);
9465 else if (view->type == TOG_VIEW_REF)
9466 err = browse_ref_tree(new_view, y, x,
9467 view->state.ref.selected_entry,
9468 view->state.ref.repo);
9469 else
9470 return got_error_msg(GOT_ERR_NOT_IMPL,
9471 "parent/child view pair not supported");
9472 break;
9473 case TOG_VIEW_REF:
9474 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9475 if (*new_view == NULL)
9476 return got_error_from_errno("view_open");
9477 if (view->type == TOG_VIEW_LOG)
9478 err = open_ref_view(*new_view, view->state.log.repo);
9479 else if (view->type == TOG_VIEW_TREE)
9480 err = open_ref_view(*new_view, view->state.tree.repo);
9481 else
9482 err = got_error_msg(GOT_ERR_NOT_IMPL,
9483 "parent/child view pair not supported");
9484 if (err)
9485 view_close(*new_view);
9486 break;
9487 case TOG_VIEW_HELP:
9488 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9489 if (*new_view == NULL)
9490 return got_error_from_errno("view_open");
9491 err = open_help_view(*new_view, view);
9492 if (err)
9493 view_close(*new_view);
9494 break;
9495 default:
9496 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9499 return err;
9503 * If view was scrolled down to move the selected line into view when opening a
9504 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9506 static void
9507 offset_selection_up(struct tog_view *view)
9509 switch (view->type) {
9510 case TOG_VIEW_BLAME: {
9511 struct tog_blame_view_state *s = &view->state.blame;
9512 if (s->first_displayed_line == 1) {
9513 s->selected_line = MAX(s->selected_line - view->offset,
9514 1);
9515 break;
9517 if (s->first_displayed_line > view->offset)
9518 s->first_displayed_line -= view->offset;
9519 else
9520 s->first_displayed_line = 1;
9521 s->selected_line += view->offset;
9522 break;
9524 case TOG_VIEW_LOG:
9525 log_scroll_up(&view->state.log, view->offset);
9526 view->state.log.selected += view->offset;
9527 break;
9528 case TOG_VIEW_REF:
9529 ref_scroll_up(&view->state.ref, view->offset);
9530 view->state.ref.selected += view->offset;
9531 break;
9532 case TOG_VIEW_TREE:
9533 tree_scroll_up(&view->state.tree, view->offset);
9534 view->state.tree.selected += view->offset;
9535 break;
9536 default:
9537 break;
9540 view->offset = 0;
9544 * If the selected line is in the section of screen covered by the bottom split,
9545 * scroll down offset lines to move it into view and index its new position.
9547 static const struct got_error *
9548 offset_selection_down(struct tog_view *view)
9550 const struct got_error *err = NULL;
9551 const struct got_error *(*scrolld)(struct tog_view *, int);
9552 int *selected = NULL;
9553 int header, offset;
9555 switch (view->type) {
9556 case TOG_VIEW_BLAME: {
9557 struct tog_blame_view_state *s = &view->state.blame;
9558 header = 3;
9559 scrolld = NULL;
9560 if (s->selected_line > view->nlines - header) {
9561 offset = abs(view->nlines - s->selected_line - header);
9562 s->first_displayed_line += offset;
9563 s->selected_line -= offset;
9564 view->offset = offset;
9566 break;
9568 case TOG_VIEW_LOG: {
9569 struct tog_log_view_state *s = &view->state.log;
9570 scrolld = &log_scroll_down;
9571 header = view_is_parent_view(view) ? 3 : 2;
9572 selected = &s->selected;
9573 break;
9575 case TOG_VIEW_REF: {
9576 struct tog_ref_view_state *s = &view->state.ref;
9577 scrolld = &ref_scroll_down;
9578 header = 3;
9579 selected = &s->selected;
9580 break;
9582 case TOG_VIEW_TREE: {
9583 struct tog_tree_view_state *s = &view->state.tree;
9584 scrolld = &tree_scroll_down;
9585 header = 5;
9586 selected = &s->selected;
9587 break;
9589 default:
9590 selected = NULL;
9591 scrolld = NULL;
9592 header = 0;
9593 break;
9596 if (selected && *selected > view->nlines - header) {
9597 offset = abs(view->nlines - *selected - header);
9598 view->offset = offset;
9599 if (scrolld && offset) {
9600 err = scrolld(view, offset);
9601 *selected -= offset;
9605 return err;
9608 static void
9609 list_commands(FILE *fp)
9611 size_t i;
9613 fprintf(fp, "commands:");
9614 for (i = 0; i < nitems(tog_commands); i++) {
9615 const struct tog_cmd *cmd = &tog_commands[i];
9616 fprintf(fp, " %s", cmd->name);
9618 fputc('\n', fp);
9621 __dead static void
9622 usage(int hflag, int status)
9624 FILE *fp = (status == 0) ? stdout : stderr;
9626 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9627 getprogname());
9628 if (hflag) {
9629 fprintf(fp, "lazy usage: %s path\n", getprogname());
9630 list_commands(fp);
9632 exit(status);
9635 static char **
9636 make_argv(int argc, ...)
9638 va_list ap;
9639 char **argv;
9640 int i;
9642 va_start(ap, argc);
9644 argv = calloc(argc, sizeof(char *));
9645 if (argv == NULL)
9646 err(1, "calloc");
9647 for (i = 0; i < argc; i++) {
9648 argv[i] = strdup(va_arg(ap, char *));
9649 if (argv[i] == NULL)
9650 err(1, "strdup");
9653 va_end(ap);
9654 return argv;
9658 * Try to convert 'tog path' into a 'tog log path' command.
9659 * The user could simply have mistyped the command rather than knowingly
9660 * provided a path. So check whether argv[0] can in fact be resolved
9661 * to a path in the HEAD commit and print a special error if not.
9662 * This hack is for mpi@ <3
9664 static const struct got_error *
9665 tog_log_with_path(int argc, char *argv[])
9667 const struct got_error *error = NULL, *close_err;
9668 const struct tog_cmd *cmd = NULL;
9669 struct got_repository *repo = NULL;
9670 struct got_worktree *worktree = NULL;
9671 struct got_object_id *commit_id = NULL, *id = NULL;
9672 struct got_commit_object *commit = NULL;
9673 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9674 char *commit_id_str = NULL, **cmd_argv = NULL;
9675 int *pack_fds = NULL;
9677 cwd = getcwd(NULL, 0);
9678 if (cwd == NULL)
9679 return got_error_from_errno("getcwd");
9681 error = got_repo_pack_fds_open(&pack_fds);
9682 if (error != NULL)
9683 goto done;
9685 error = got_worktree_open(&worktree, cwd);
9686 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9687 goto done;
9689 if (worktree)
9690 repo_path = strdup(got_worktree_get_repo_path(worktree));
9691 else
9692 repo_path = strdup(cwd);
9693 if (repo_path == NULL) {
9694 error = got_error_from_errno("strdup");
9695 goto done;
9698 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9699 if (error != NULL)
9700 goto done;
9702 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9703 repo, worktree);
9704 if (error)
9705 goto done;
9707 error = tog_load_refs(repo, 0);
9708 if (error)
9709 goto done;
9710 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9711 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9712 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9713 if (error)
9714 goto done;
9716 if (worktree) {
9717 got_worktree_close(worktree);
9718 worktree = NULL;
9721 error = got_object_open_as_commit(&commit, repo, commit_id);
9722 if (error)
9723 goto done;
9725 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9726 if (error) {
9727 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9728 goto done;
9729 fprintf(stderr, "%s: '%s' is no known command or path\n",
9730 getprogname(), argv[0]);
9731 usage(1, 1);
9732 /* not reached */
9735 error = got_object_id_str(&commit_id_str, commit_id);
9736 if (error)
9737 goto done;
9739 cmd = &tog_commands[0]; /* log */
9740 argc = 4;
9741 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9742 error = cmd->cmd_main(argc, cmd_argv);
9743 done:
9744 if (repo) {
9745 close_err = got_repo_close(repo);
9746 if (error == NULL)
9747 error = close_err;
9749 if (commit)
9750 got_object_commit_close(commit);
9751 if (worktree)
9752 got_worktree_close(worktree);
9753 if (pack_fds) {
9754 const struct got_error *pack_err =
9755 got_repo_pack_fds_close(pack_fds);
9756 if (error == NULL)
9757 error = pack_err;
9759 free(id);
9760 free(commit_id_str);
9761 free(commit_id);
9762 free(cwd);
9763 free(repo_path);
9764 free(in_repo_path);
9765 if (cmd_argv) {
9766 int i;
9767 for (i = 0; i < argc; i++)
9768 free(cmd_argv[i]);
9769 free(cmd_argv);
9771 tog_free_refs();
9772 return error;
9775 int
9776 main(int argc, char *argv[])
9778 const struct got_error *io_err, *error = NULL;
9779 const struct tog_cmd *cmd = NULL;
9780 int ch, hflag = 0, Vflag = 0;
9781 char **cmd_argv = NULL;
9782 static const struct option longopts[] = {
9783 { "version", no_argument, NULL, 'V' },
9784 { NULL, 0, NULL, 0}
9786 char *diff_algo_str = NULL;
9787 const char *test_script_path;
9789 setlocale(LC_CTYPE, "");
9792 * Test mode init must happen before pledge() because "tty" will
9793 * not allow TTY-related ioctls to occur via regular files.
9795 test_script_path = getenv("TOG_TEST_SCRIPT");
9796 if (test_script_path != NULL) {
9797 error = init_mock_term(test_script_path);
9798 if (error) {
9799 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9800 return 1;
9804 #if !defined(PROFILE)
9805 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9806 NULL) == -1)
9807 err(1, "pledge");
9808 #endif
9810 if (!isatty(STDIN_FILENO))
9811 errx(1, "standard input is not a tty");
9813 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9814 switch (ch) {
9815 case 'h':
9816 hflag = 1;
9817 break;
9818 case 'V':
9819 Vflag = 1;
9820 break;
9821 default:
9822 usage(hflag, 1);
9823 /* NOTREACHED */
9827 argc -= optind;
9828 argv += optind;
9829 optind = 1;
9830 optreset = 1;
9832 if (Vflag) {
9833 got_version_print_str();
9834 return 0;
9837 if (argc == 0) {
9838 if (hflag)
9839 usage(hflag, 0);
9840 /* Build an argument vector which runs a default command. */
9841 cmd = &tog_commands[0];
9842 argc = 1;
9843 cmd_argv = make_argv(argc, cmd->name);
9844 } else {
9845 size_t i;
9847 /* Did the user specify a command? */
9848 for (i = 0; i < nitems(tog_commands); i++) {
9849 if (strncmp(tog_commands[i].name, argv[0],
9850 strlen(argv[0])) == 0) {
9851 cmd = &tog_commands[i];
9852 break;
9857 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9858 if (diff_algo_str) {
9859 if (strcasecmp(diff_algo_str, "patience") == 0)
9860 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9861 if (strcasecmp(diff_algo_str, "myers") == 0)
9862 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9865 if (cmd == NULL) {
9866 if (argc != 1)
9867 usage(0, 1);
9868 /* No command specified; try log with a path */
9869 error = tog_log_with_path(argc, argv);
9870 } else {
9871 if (hflag)
9872 cmd->cmd_usage();
9873 else
9874 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9877 if (using_mock_io) {
9878 io_err = tog_io_close();
9879 if (error == NULL)
9880 error = io_err;
9882 endwin();
9883 if (cmd_argv) {
9884 int i;
9885 for (i = 0; i < argc; i++)
9886 free(cmd_argv[i]);
9887 free(cmd_argv);
9890 if (error && error->code != GOT_ERR_CANCELLED &&
9891 error->code != GOT_ERR_EOF &&
9892 error->code != GOT_ERR_PRIVSEP_EXIT &&
9893 error->code != GOT_ERR_PRIVSEP_PIPE &&
9894 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9895 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9896 return 0;