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 };
437 struct tog_blame {
438 FILE *f;
439 off_t filesize;
440 struct tog_blame_line *lines;
441 int nlines;
442 off_t *line_offsets;
443 pthread_t thread;
444 struct tog_blame_thread_args thread_args;
445 struct tog_blame_cb_args cb_args;
446 const char *path;
447 int *pack_fds;
448 };
450 struct tog_blame_view_state {
451 int first_displayed_line;
452 int last_displayed_line;
453 int selected_line;
454 int last_diffed_line;
455 int blame_complete;
456 int eof;
457 int done;
458 struct got_object_id_queue blamed_commits;
459 struct got_object_qid *blamed_commit;
460 char *path;
461 struct got_repository *repo;
462 struct got_object_id *commit_id;
463 struct got_object_id *id_to_log;
464 struct tog_blame blame;
465 int matched_line;
466 struct tog_colors colors;
467 };
469 struct tog_parent_tree {
470 TAILQ_ENTRY(tog_parent_tree) entry;
471 struct got_tree_object *tree;
472 struct got_tree_entry *first_displayed_entry;
473 struct got_tree_entry *selected_entry;
474 int selected;
475 };
477 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
479 struct tog_tree_view_state {
480 char *tree_label;
481 struct got_object_id *commit_id;/* commit which this tree belongs to */
482 struct got_tree_object *root; /* the commit's root tree entry */
483 struct got_tree_object *tree; /* currently displayed (sub-)tree */
484 struct got_tree_entry *first_displayed_entry;
485 struct got_tree_entry *last_displayed_entry;
486 struct got_tree_entry *selected_entry;
487 int ndisplayed, selected, show_ids;
488 struct tog_parent_trees parents; /* parent trees of current sub-tree */
489 char *head_ref_name;
490 struct got_repository *repo;
491 struct got_tree_entry *matched_entry;
492 struct tog_colors colors;
493 };
495 struct tog_reflist_entry {
496 TAILQ_ENTRY(tog_reflist_entry) entry;
497 struct got_reference *ref;
498 int idx;
499 };
501 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
503 struct tog_ref_view_state {
504 struct tog_reflist_head refs;
505 struct tog_reflist_entry *first_displayed_entry;
506 struct tog_reflist_entry *last_displayed_entry;
507 struct tog_reflist_entry *selected_entry;
508 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
509 struct got_repository *repo;
510 struct tog_reflist_entry *matched_entry;
511 struct tog_colors colors;
512 };
514 struct tog_help_view_state {
515 FILE *f;
516 off_t *line_offsets;
517 size_t nlines;
518 int lineno;
519 int first_displayed_line;
520 int last_displayed_line;
521 int eof;
522 int matched_line;
523 int selected_line;
524 int all;
525 enum tog_keymap_type type;
526 };
528 #define GENERATE_HELP \
529 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
530 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
531 KEY_("k C-p Up", "Move cursor or page up one line"), \
532 KEY_("j C-n Down", "Move cursor or page down one line"), \
533 KEY_("C-b b PgUp", "Scroll the view up one page"), \
534 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
535 KEY_("C-u u", "Scroll the view up one half page"), \
536 KEY_("C-d d", "Scroll the view down one half page"), \
537 KEY_("g", "Go to line N (default: first line)"), \
538 KEY_("Home =", "Go to the first line"), \
539 KEY_("G", "Go to line N (default: last line)"), \
540 KEY_("End *", "Go to the last line"), \
541 KEY_("l Right", "Scroll the view right"), \
542 KEY_("h Left", "Scroll the view left"), \
543 KEY_("$", "Scroll view to the rightmost position"), \
544 KEY_("0", "Scroll view to the leftmost position"), \
545 KEY_("-", "Decrease size of the focussed split"), \
546 KEY_("+", "Increase size of the focussed split"), \
547 KEY_("Tab", "Switch focus between views"), \
548 KEY_("F", "Toggle fullscreen mode"), \
549 KEY_("/", "Open prompt to enter search term"), \
550 KEY_("n", "Find next line/token matching the current search term"), \
551 KEY_("N", "Find previous line/token matching the current search term"),\
552 KEY_("q", "Quit the focussed view; Quit help screen"), \
553 KEY_("Q", "Quit tog"), \
555 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
556 KEY_("< ,", "Move cursor up one commit"), \
557 KEY_("> .", "Move cursor down one commit"), \
558 KEY_("Enter", "Open diff view of the selected commit"), \
559 KEY_("B", "Reload the log view and toggle display of merged commits"), \
560 KEY_("R", "Open ref view of all repository references"), \
561 KEY_("T", "Display tree view of the repository from the selected" \
562 " commit"), \
563 KEY_("@", "Toggle between displaying author and committer name"), \
564 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
565 KEY_("C-g Backspace", "Cancel current search or log operation"), \
566 KEY_("C-l", "Reload the log view with new commits in the repository"), \
568 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
569 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
570 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
571 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
572 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
573 " data"), \
574 KEY_("(", "Go to the previous file in the diff"), \
575 KEY_(")", "Go to the next file in the diff"), \
576 KEY_("{", "Go to the previous hunk in the diff"), \
577 KEY_("}", "Go to the next hunk in the diff"), \
578 KEY_("[", "Decrease the number of context lines"), \
579 KEY_("]", "Increase the number of context lines"), \
580 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
582 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
583 KEY_("Enter", "Display diff view of the selected line's commit"), \
584 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
585 KEY_("L", "Open log view for the currently selected annotated line"), \
586 KEY_("C", "Reload view with the previously blamed commit"), \
587 KEY_("c", "Reload view with the version of the file found in the" \
588 " selected line's commit"), \
589 KEY_("p", "Reload view with the version of the file found in the" \
590 " selected line's parent commit"), \
592 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
593 KEY_("Enter", "Enter selected directory or open blame view of the" \
594 " selected file"), \
595 KEY_("L", "Open log view for the selected entry"), \
596 KEY_("R", "Open ref view of all repository references"), \
597 KEY_("i", "Show object IDs for all tree entries"), \
598 KEY_("Backspace", "Return to the parent directory"), \
600 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
601 KEY_("Enter", "Display log view of the selected reference"), \
602 KEY_("T", "Display tree view of the selected reference"), \
603 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
604 KEY_("m", "Toggle display of last modified date for each reference"), \
605 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
606 KEY_("C-l", "Reload view with all repository references")
608 struct tog_key_map {
609 const char *keys;
610 const char *info;
611 enum tog_keymap_type type;
612 };
614 /* curses io for tog regress */
615 struct tog_io {
616 FILE *cin;
617 FILE *cout;
618 FILE *f;
619 } tog_io;
620 static int using_mock_io;
622 #define TOG_SCREEN_DUMP "SCREENDUMP"
623 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
624 #define TOG_KEY_SCRDUMP SHRT_MIN
626 /*
627 * We implement two types of views: parent views and child views.
629 * The 'Tab' key switches focus between a parent view and its child view.
630 * Child views are shown side-by-side to their parent view, provided
631 * there is enough screen estate.
633 * When a new view is opened from within a parent view, this new view
634 * becomes a child view of the parent view, replacing any existing child.
636 * When a new view is opened from within a child view, this new view
637 * becomes a parent view which will obscure the views below until the
638 * user quits the new parent view by typing 'q'.
640 * This list of views contains parent views only.
641 * Child views are only pointed to by their parent view.
642 */
643 TAILQ_HEAD(tog_view_list_head, tog_view);
645 struct tog_view {
646 TAILQ_ENTRY(tog_view) entry;
647 WINDOW *window;
648 PANEL *panel;
649 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
650 int resized_y, resized_x; /* begin_y/x based on user resizing */
651 int maxx, x; /* max column and current start column */
652 int lines, cols; /* copies of LINES and COLS */
653 int nscrolled, offset; /* lines scrolled and hsplit line offset */
654 int gline, hiline; /* navigate to and highlight this nG line */
655 int ch, count; /* current keymap and count prefix */
656 int resized; /* set when in a resize event */
657 int focussed; /* Only set on one parent or child view at a time. */
658 int dying;
659 struct tog_view *parent;
660 struct tog_view *child;
662 /*
663 * This flag is initially set on parent views when a new child view
664 * is created. It gets toggled when the 'Tab' key switches focus
665 * between parent and child.
666 * The flag indicates whether focus should be passed on to our child
667 * view if this parent view gets picked for focus after another parent
668 * view was closed. This prevents child views from losing focus in such
669 * situations.
670 */
671 int focus_child;
673 enum tog_view_mode mode;
674 /* type-specific state */
675 enum tog_view_type type;
676 union {
677 struct tog_diff_view_state diff;
678 struct tog_log_view_state log;
679 struct tog_blame_view_state blame;
680 struct tog_tree_view_state tree;
681 struct tog_ref_view_state ref;
682 struct tog_help_view_state help;
683 } state;
685 const struct got_error *(*show)(struct tog_view *);
686 const struct got_error *(*input)(struct tog_view **,
687 struct tog_view *, int);
688 const struct got_error *(*reset)(struct tog_view *);
689 const struct got_error *(*resize)(struct tog_view *, int);
690 const struct got_error *(*close)(struct tog_view *);
692 const struct got_error *(*search_start)(struct tog_view *);
693 const struct got_error *(*search_next)(struct tog_view *);
694 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
695 int **, int **, int **, int **);
696 int search_started;
697 int searching;
698 #define TOG_SEARCH_FORWARD 1
699 #define TOG_SEARCH_BACKWARD 2
700 int search_next_done;
701 #define TOG_SEARCH_HAVE_MORE 1
702 #define TOG_SEARCH_NO_MORE 2
703 #define TOG_SEARCH_HAVE_NONE 3
704 regex_t regex;
705 regmatch_t regmatch;
706 const char *action;
707 };
709 static const struct got_error *open_diff_view(struct tog_view *,
710 struct got_object_id *, struct got_object_id *,
711 const char *, const char *, int, int, int, struct tog_view *,
712 struct got_repository *);
713 static const struct got_error *show_diff_view(struct tog_view *);
714 static const struct got_error *input_diff_view(struct tog_view **,
715 struct tog_view *, int);
716 static const struct got_error *reset_diff_view(struct tog_view *);
717 static const struct got_error* close_diff_view(struct tog_view *);
718 static const struct got_error *search_start_diff_view(struct tog_view *);
719 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
720 size_t *, int **, int **, int **, int **);
721 static const struct got_error *search_next_view_match(struct tog_view *);
723 static const struct got_error *open_log_view(struct tog_view *,
724 struct got_object_id *, struct got_repository *,
725 const char *, const char *, int);
726 static const struct got_error * show_log_view(struct tog_view *);
727 static const struct got_error *input_log_view(struct tog_view **,
728 struct tog_view *, int);
729 static const struct got_error *resize_log_view(struct tog_view *, int);
730 static const struct got_error *close_log_view(struct tog_view *);
731 static const struct got_error *search_start_log_view(struct tog_view *);
732 static const struct got_error *search_next_log_view(struct tog_view *);
734 static const struct got_error *open_blame_view(struct tog_view *, char *,
735 struct got_object_id *, struct got_repository *);
736 static const struct got_error *show_blame_view(struct tog_view *);
737 static const struct got_error *input_blame_view(struct tog_view **,
738 struct tog_view *, int);
739 static const struct got_error *reset_blame_view(struct tog_view *);
740 static const struct got_error *close_blame_view(struct tog_view *);
741 static const struct got_error *search_start_blame_view(struct tog_view *);
742 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
743 size_t *, int **, int **, int **, int **);
745 static const struct got_error *open_tree_view(struct tog_view *,
746 struct got_object_id *, const char *, struct got_repository *);
747 static const struct got_error *show_tree_view(struct tog_view *);
748 static const struct got_error *input_tree_view(struct tog_view **,
749 struct tog_view *, int);
750 static const struct got_error *close_tree_view(struct tog_view *);
751 static const struct got_error *search_start_tree_view(struct tog_view *);
752 static const struct got_error *search_next_tree_view(struct tog_view *);
754 static const struct got_error *open_ref_view(struct tog_view *,
755 struct got_repository *);
756 static const struct got_error *show_ref_view(struct tog_view *);
757 static const struct got_error *input_ref_view(struct tog_view **,
758 struct tog_view *, int);
759 static const struct got_error *close_ref_view(struct tog_view *);
760 static const struct got_error *search_start_ref_view(struct tog_view *);
761 static const struct got_error *search_next_ref_view(struct tog_view *);
763 static const struct got_error *open_help_view(struct tog_view *,
764 struct tog_view *);
765 static const struct got_error *show_help_view(struct tog_view *);
766 static const struct got_error *input_help_view(struct tog_view **,
767 struct tog_view *, int);
768 static const struct got_error *reset_help_view(struct tog_view *);
769 static const struct got_error* close_help_view(struct tog_view *);
770 static const struct got_error *search_start_help_view(struct tog_view *);
771 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
772 size_t *, int **, int **, int **, int **);
774 static volatile sig_atomic_t tog_sigwinch_received;
775 static volatile sig_atomic_t tog_sigpipe_received;
776 static volatile sig_atomic_t tog_sigcont_received;
777 static volatile sig_atomic_t tog_sigint_received;
778 static volatile sig_atomic_t tog_sigterm_received;
780 static void
781 tog_sigwinch(int signo)
783 tog_sigwinch_received = 1;
786 static void
787 tog_sigpipe(int signo)
789 tog_sigpipe_received = 1;
792 static void
793 tog_sigcont(int signo)
795 tog_sigcont_received = 1;
798 static void
799 tog_sigint(int signo)
801 tog_sigint_received = 1;
804 static void
805 tog_sigterm(int signo)
807 tog_sigterm_received = 1;
810 static int
811 tog_fatal_signal_received(void)
813 return (tog_sigpipe_received ||
814 tog_sigint_received || tog_sigterm_received);
817 static const struct got_error *
818 view_close(struct tog_view *view)
820 const struct got_error *err = NULL, *child_err = NULL;
822 if (view->child) {
823 child_err = view_close(view->child);
824 view->child = NULL;
826 if (view->close)
827 err = view->close(view);
828 if (view->panel)
829 del_panel(view->panel);
830 if (view->window)
831 delwin(view->window);
832 free(view);
833 return err ? err : child_err;
836 static struct tog_view *
837 view_open(int nlines, int ncols, int begin_y, int begin_x,
838 enum tog_view_type type)
840 struct tog_view *view = calloc(1, sizeof(*view));
842 if (view == NULL)
843 return NULL;
845 view->type = type;
846 view->lines = LINES;
847 view->cols = COLS;
848 view->nlines = nlines ? nlines : LINES - begin_y;
849 view->ncols = ncols ? ncols : COLS - begin_x;
850 view->begin_y = begin_y;
851 view->begin_x = begin_x;
852 view->window = newwin(nlines, ncols, begin_y, begin_x);
853 if (view->window == NULL) {
854 view_close(view);
855 return NULL;
857 view->panel = new_panel(view->window);
858 if (view->panel == NULL ||
859 set_panel_userptr(view->panel, view) != OK) {
860 view_close(view);
861 return NULL;
864 keypad(view->window, TRUE);
865 return view;
868 static int
869 view_split_begin_x(int begin_x)
871 if (begin_x > 0 || COLS < 120)
872 return 0;
873 return (COLS - MAX(COLS / 2, 80));
876 /* XXX Stub till we decide what to do. */
877 static int
878 view_split_begin_y(int lines)
880 return lines * HSPLIT_SCALE;
883 static const struct got_error *view_resize(struct tog_view *);
885 static const struct got_error *
886 view_splitscreen(struct tog_view *view)
888 const struct got_error *err = NULL;
890 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
891 if (view->resized_y && view->resized_y < view->lines)
892 view->begin_y = view->resized_y;
893 else
894 view->begin_y = view_split_begin_y(view->nlines);
895 view->begin_x = 0;
896 } else if (!view->resized) {
897 if (view->resized_x && view->resized_x < view->cols - 1 &&
898 view->cols > 119)
899 view->begin_x = view->resized_x;
900 else
901 view->begin_x = view_split_begin_x(0);
902 view->begin_y = 0;
904 view->nlines = LINES - view->begin_y;
905 view->ncols = COLS - view->begin_x;
906 view->lines = LINES;
907 view->cols = COLS;
908 err = view_resize(view);
909 if (err)
910 return err;
912 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
913 view->parent->nlines = view->begin_y;
915 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
916 return got_error_from_errno("mvwin");
918 return NULL;
921 static const struct got_error *
922 view_fullscreen(struct tog_view *view)
924 const struct got_error *err = NULL;
926 view->begin_x = 0;
927 view->begin_y = view->resized ? view->begin_y : 0;
928 view->nlines = view->resized ? view->nlines : LINES;
929 view->ncols = COLS;
930 view->lines = LINES;
931 view->cols = COLS;
932 err = view_resize(view);
933 if (err)
934 return err;
936 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
937 return got_error_from_errno("mvwin");
939 return NULL;
942 static int
943 view_is_parent_view(struct tog_view *view)
945 return view->parent == NULL;
948 static int
949 view_is_splitscreen(struct tog_view *view)
951 return view->begin_x > 0 || view->begin_y > 0;
954 static int
955 view_is_fullscreen(struct tog_view *view)
957 return view->nlines == LINES && view->ncols == COLS;
960 static int
961 view_is_hsplit_top(struct tog_view *view)
963 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
964 view_is_splitscreen(view->child);
967 static void
968 view_border(struct tog_view *view)
970 PANEL *panel;
971 const struct tog_view *view_above;
973 if (view->parent)
974 return view_border(view->parent);
976 panel = panel_above(view->panel);
977 if (panel == NULL)
978 return;
980 view_above = panel_userptr(panel);
981 if (view->mode == TOG_VIEW_SPLIT_HRZN)
982 mvwhline(view->window, view_above->begin_y - 1,
983 view->begin_x, got_locale_is_utf8() ?
984 ACS_HLINE : '-', view->ncols);
985 else
986 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
987 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
990 static const struct got_error *view_init_hsplit(struct tog_view *, int);
991 static const struct got_error *request_log_commits(struct tog_view *);
992 static const struct got_error *offset_selection_down(struct tog_view *);
993 static void offset_selection_up(struct tog_view *);
994 static void view_get_split(struct tog_view *, int *, int *);
996 static const struct got_error *
997 view_resize(struct tog_view *view)
999 const struct got_error *err = NULL;
1000 int dif, nlines, ncols;
1002 dif = LINES - view->lines; /* line difference */
1004 if (view->lines > LINES)
1005 nlines = view->nlines - (view->lines - LINES);
1006 else
1007 nlines = view->nlines + (LINES - view->lines);
1008 if (view->cols > COLS)
1009 ncols = view->ncols - (view->cols - COLS);
1010 else
1011 ncols = view->ncols + (COLS - view->cols);
1013 if (view->child) {
1014 int hs = view->child->begin_y;
1016 if (!view_is_fullscreen(view))
1017 view->child->begin_x = view_split_begin_x(view->begin_x);
1018 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1019 view->child->begin_x == 0) {
1020 ncols = COLS;
1022 view_fullscreen(view->child);
1023 if (view->child->focussed)
1024 show_panel(view->child->panel);
1025 else
1026 show_panel(view->panel);
1027 } else {
1028 ncols = view->child->begin_x;
1030 view_splitscreen(view->child);
1031 show_panel(view->child->panel);
1034 * XXX This is ugly and needs to be moved into the above
1035 * logic but "works" for now and my attempts at moving it
1036 * break either 'tab' or 'F' key maps in horizontal splits.
1038 if (hs) {
1039 err = view_splitscreen(view->child);
1040 if (err)
1041 return err;
1042 if (dif < 0) { /* top split decreased */
1043 err = offset_selection_down(view);
1044 if (err)
1045 return err;
1047 view_border(view);
1048 update_panels();
1049 doupdate();
1050 show_panel(view->child->panel);
1051 nlines = view->nlines;
1053 } else if (view->parent == NULL)
1054 ncols = COLS;
1056 if (view->resize && dif > 0) {
1057 err = view->resize(view, dif);
1058 if (err)
1059 return err;
1062 if (wresize(view->window, nlines, ncols) == ERR)
1063 return got_error_from_errno("wresize");
1064 if (replace_panel(view->panel, view->window) == ERR)
1065 return got_error_from_errno("replace_panel");
1066 wclear(view->window);
1068 view->nlines = nlines;
1069 view->ncols = ncols;
1070 view->lines = LINES;
1071 view->cols = COLS;
1073 return NULL;
1076 static const struct got_error *
1077 resize_log_view(struct tog_view *view, int increase)
1079 struct tog_log_view_state *s = &view->state.log;
1080 const struct got_error *err = NULL;
1081 int n = 0;
1083 if (s->selected_entry)
1084 n = s->selected_entry->idx + view->lines - s->selected;
1087 * Request commits to account for the increased
1088 * height so we have enough to populate the view.
1090 if (s->commits->ncommits < n) {
1091 view->nscrolled = n - s->commits->ncommits + increase + 1;
1092 err = request_log_commits(view);
1095 return err;
1098 static void
1099 view_adjust_offset(struct tog_view *view, int n)
1101 if (n == 0)
1102 return;
1104 if (view->parent && view->parent->offset) {
1105 if (view->parent->offset + n >= 0)
1106 view->parent->offset += n;
1107 else
1108 view->parent->offset = 0;
1109 } else if (view->offset) {
1110 if (view->offset - n >= 0)
1111 view->offset -= n;
1112 else
1113 view->offset = 0;
1117 static const struct got_error *
1118 view_resize_split(struct tog_view *view, int resize)
1120 const struct got_error *err = NULL;
1121 struct tog_view *v = NULL;
1123 if (view->parent)
1124 v = view->parent;
1125 else
1126 v = view;
1128 if (!v->child || !view_is_splitscreen(v->child))
1129 return NULL;
1131 v->resized = v->child->resized = resize; /* lock for resize event */
1133 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1134 if (v->child->resized_y)
1135 v->child->begin_y = v->child->resized_y;
1136 if (view->parent)
1137 v->child->begin_y -= resize;
1138 else
1139 v->child->begin_y += resize;
1140 if (v->child->begin_y < 3) {
1141 view->count = 0;
1142 v->child->begin_y = 3;
1143 } else if (v->child->begin_y > LINES - 1) {
1144 view->count = 0;
1145 v->child->begin_y = LINES - 1;
1147 v->ncols = COLS;
1148 v->child->ncols = COLS;
1149 view_adjust_offset(view, resize);
1150 err = view_init_hsplit(v, v->child->begin_y);
1151 if (err)
1152 return err;
1153 v->child->resized_y = v->child->begin_y;
1154 } else {
1155 if (v->child->resized_x)
1156 v->child->begin_x = v->child->resized_x;
1157 if (view->parent)
1158 v->child->begin_x -= resize;
1159 else
1160 v->child->begin_x += resize;
1161 if (v->child->begin_x < 11) {
1162 view->count = 0;
1163 v->child->begin_x = 11;
1164 } else if (v->child->begin_x > COLS - 1) {
1165 view->count = 0;
1166 v->child->begin_x = COLS - 1;
1168 v->child->resized_x = v->child->begin_x;
1171 v->child->mode = v->mode;
1172 v->child->nlines = v->lines - v->child->begin_y;
1173 v->child->ncols = v->cols - v->child->begin_x;
1174 v->focus_child = 1;
1176 err = view_fullscreen(v);
1177 if (err)
1178 return err;
1179 err = view_splitscreen(v->child);
1180 if (err)
1181 return err;
1183 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1184 err = offset_selection_down(v->child);
1185 if (err)
1186 return err;
1189 if (v->resize)
1190 err = v->resize(v, 0);
1191 else if (v->child->resize)
1192 err = v->child->resize(v->child, 0);
1194 v->resized = v->child->resized = 0;
1196 return err;
1199 static void
1200 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1202 struct tog_view *v = src->child ? src->child : src;
1204 dst->resized_x = v->resized_x;
1205 dst->resized_y = v->resized_y;
1208 static const struct got_error *
1209 view_close_child(struct tog_view *view)
1211 const struct got_error *err = NULL;
1213 if (view->child == NULL)
1214 return NULL;
1216 err = view_close(view->child);
1217 view->child = NULL;
1218 return err;
1221 static const struct got_error *
1222 view_set_child(struct tog_view *view, struct tog_view *child)
1224 const struct got_error *err = NULL;
1226 view->child = child;
1227 child->parent = view;
1229 err = view_resize(view);
1230 if (err)
1231 return err;
1233 if (view->child->resized_x || view->child->resized_y)
1234 err = view_resize_split(view, 0);
1236 return err;
1239 static const struct got_error *view_dispatch_request(struct tog_view **,
1240 struct tog_view *, enum tog_view_type, int, int);
1242 static const struct got_error *
1243 view_request_new(struct tog_view **requested, struct tog_view *view,
1244 enum tog_view_type request)
1246 struct tog_view *new_view = NULL;
1247 const struct got_error *err;
1248 int y = 0, x = 0;
1250 *requested = NULL;
1252 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1253 view_get_split(view, &y, &x);
1255 err = view_dispatch_request(&new_view, view, request, y, x);
1256 if (err)
1257 return err;
1259 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1260 request != TOG_VIEW_HELP) {
1261 err = view_init_hsplit(view, y);
1262 if (err)
1263 return err;
1266 view->focussed = 0;
1267 new_view->focussed = 1;
1268 new_view->mode = view->mode;
1269 new_view->nlines = request == TOG_VIEW_HELP ?
1270 view->lines : view->lines - y;
1272 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1273 view_transfer_size(new_view, view);
1274 err = view_close_child(view);
1275 if (err)
1276 return err;
1277 err = view_set_child(view, new_view);
1278 if (err)
1279 return err;
1280 view->focus_child = 1;
1281 } else
1282 *requested = new_view;
1284 return NULL;
1287 static void
1288 tog_resizeterm(void)
1290 int cols, lines;
1291 struct winsize size;
1293 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1294 cols = 80; /* Default */
1295 lines = 24;
1296 } else {
1297 cols = size.ws_col;
1298 lines = size.ws_row;
1300 resize_term(lines, cols);
1303 static const struct got_error *
1304 view_search_start(struct tog_view *view, int fast_refresh)
1306 const struct got_error *err = NULL;
1307 struct tog_view *v = view;
1308 char pattern[1024];
1309 int ret;
1311 if (view->search_started) {
1312 regfree(&view->regex);
1313 view->searching = 0;
1314 memset(&view->regmatch, 0, sizeof(view->regmatch));
1316 view->search_started = 0;
1318 if (view->nlines < 1)
1319 return NULL;
1321 if (view_is_hsplit_top(view))
1322 v = view->child;
1323 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1324 v = view->parent;
1326 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1327 wclrtoeol(v->window);
1329 nodelay(v->window, FALSE); /* block for search term input */
1330 nocbreak();
1331 echo();
1332 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1333 wrefresh(v->window);
1334 cbreak();
1335 noecho();
1336 nodelay(v->window, TRUE);
1337 if (!fast_refresh && !using_mock_io)
1338 halfdelay(10);
1339 if (ret == ERR)
1340 return NULL;
1342 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1343 err = view->search_start(view);
1344 if (err) {
1345 regfree(&view->regex);
1346 return err;
1348 view->search_started = 1;
1349 view->searching = TOG_SEARCH_FORWARD;
1350 view->search_next_done = 0;
1351 view->search_next(view);
1354 return NULL;
1357 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1358 static const struct got_error *
1359 switch_split(struct tog_view *view)
1361 const struct got_error *err = NULL;
1362 struct tog_view *v = NULL;
1364 if (view->parent)
1365 v = view->parent;
1366 else
1367 v = view;
1369 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1370 v->mode = TOG_VIEW_SPLIT_VERT;
1371 else
1372 v->mode = TOG_VIEW_SPLIT_HRZN;
1374 if (!v->child)
1375 return NULL;
1376 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1377 v->mode = TOG_VIEW_SPLIT_NONE;
1379 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1380 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1381 v->child->begin_y = v->child->resized_y;
1382 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1383 v->child->begin_x = v->child->resized_x;
1386 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1387 v->ncols = COLS;
1388 v->child->ncols = COLS;
1389 v->child->nscrolled = LINES - v->child->nlines;
1391 err = view_init_hsplit(v, v->child->begin_y);
1392 if (err)
1393 return err;
1395 v->child->mode = v->mode;
1396 v->child->nlines = v->lines - v->child->begin_y;
1397 v->focus_child = 1;
1399 err = view_fullscreen(v);
1400 if (err)
1401 return err;
1402 err = view_splitscreen(v->child);
1403 if (err)
1404 return err;
1406 if (v->mode == TOG_VIEW_SPLIT_NONE)
1407 v->mode = TOG_VIEW_SPLIT_VERT;
1408 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1409 err = offset_selection_down(v);
1410 if (err)
1411 return err;
1412 err = offset_selection_down(v->child);
1413 if (err)
1414 return err;
1415 } else {
1416 offset_selection_up(v);
1417 offset_selection_up(v->child);
1419 if (v->resize)
1420 err = v->resize(v, 0);
1421 else if (v->child->resize)
1422 err = v->child->resize(v->child, 0);
1424 return err;
1428 * Strip trailing whitespace from str starting at byte *n;
1429 * if *n < 0, use strlen(str). Return new str length in *n.
1431 static void
1432 strip_trailing_ws(char *str, int *n)
1434 size_t x = *n;
1436 if (str == NULL || *str == '\0')
1437 return;
1439 if (x < 0)
1440 x = strlen(str);
1442 while (x-- > 0 && isspace((unsigned char)str[x]))
1443 str[x] = '\0';
1445 *n = x + 1;
1449 * Extract visible substring of line y from the curses screen
1450 * and strip trailing whitespace. If vline is set and locale is
1451 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1452 * character is written out as 'x'. Write the line to file f.
1454 static const struct got_error *
1455 view_write_line(FILE *f, int y, int vline)
1457 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1458 int r, w;
1460 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1461 if (r == ERR)
1462 return got_error_fmt(GOT_ERR_RANGE,
1463 "failed to extract line %d", y);
1466 * In some views, lines are padded with blanks to COLS width.
1467 * Strip them so we can diff without the -b flag when testing.
1469 strip_trailing_ws(line, &r);
1471 if (vline > 0 && got_locale_is_utf8())
1472 line[vline] = '|';
1474 w = fprintf(f, "%s\n", line);
1475 if (w != r + 1) /* \n */
1476 return got_ferror(f, GOT_ERR_IO);
1478 return NULL;
1482 * Capture the visible curses screen by writing each line to the
1483 * file at the path set via the TOG_SCR_DUMP environment variable.
1485 static const struct got_error *
1486 screendump(struct tog_view *view)
1488 const struct got_error *err;
1489 FILE *f = NULL;
1490 const char *path;
1491 int i;
1493 path = getenv("TOG_SCR_DUMP");
1494 if (path == NULL || *path == '\0')
1495 return got_error_msg(GOT_ERR_BAD_PATH,
1496 "TOG_SCR_DUMP path not set to capture screen dump");
1497 f = fopen(path, "wex");
1498 if (f == NULL)
1499 return got_error_from_errno_fmt("fopen: %s", path);
1501 if ((view->child && view->child->begin_x) ||
1502 (view->parent && view->begin_x)) {
1503 int ncols = view->child ? view->ncols : view->parent->ncols;
1505 /* vertical splitscreen */
1506 for (i = 0; i < view->nlines; ++i) {
1507 err = view_write_line(f, i, ncols - 1);
1508 if (err)
1509 goto done;
1511 } else {
1512 int hline = 0;
1514 /* fullscreen or horizontal splitscreen */
1515 if ((view->child && view->child->begin_y) ||
1516 (view->parent && view->begin_y)) /* hsplit */
1517 hline = view->child ?
1518 view->child->begin_y : view->begin_y;
1520 for (i = 0; i < view->lines; i++) {
1521 if (hline && got_locale_is_utf8() && i == hline - 1) {
1522 int c;
1524 /* ACS_HLINE writes out as 'q', overwrite it */
1525 for (c = 0; c < view->cols; ++c)
1526 fputc('-', f);
1527 fputc('\n', f);
1528 continue;
1531 err = view_write_line(f, i, 0);
1532 if (err)
1533 goto done;
1537 done:
1538 if (f && fclose(f) == EOF && err == NULL)
1539 err = got_ferror(f, GOT_ERR_IO);
1540 return err;
1544 * Compute view->count from numeric input. Assign total to view->count and
1545 * return first non-numeric key entered.
1547 static int
1548 get_compound_key(struct tog_view *view, int c)
1550 struct tog_view *v = view;
1551 int x, n = 0;
1553 if (view_is_hsplit_top(view))
1554 v = view->child;
1555 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1556 v = view->parent;
1558 view->count = 0;
1559 cbreak(); /* block for input */
1560 nodelay(view->window, FALSE);
1561 wmove(v->window, v->nlines - 1, 0);
1562 wclrtoeol(v->window);
1563 waddch(v->window, ':');
1565 do {
1566 x = getcurx(v->window);
1567 if (x != ERR && x < view->ncols) {
1568 waddch(v->window, c);
1569 wrefresh(v->window);
1573 * Don't overflow. Max valid request should be the greatest
1574 * between the longest and total lines; cap at 10 million.
1576 if (n >= 9999999)
1577 n = 9999999;
1578 else
1579 n = n * 10 + (c - '0');
1580 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1582 if (c == 'G' || c == 'g') { /* nG key map */
1583 view->gline = view->hiline = n;
1584 n = 0;
1585 c = 0;
1588 /* Massage excessive or inapplicable values at the input handler. */
1589 view->count = n;
1591 return c;
1594 static void
1595 action_report(struct tog_view *view)
1597 struct tog_view *v = view;
1599 if (view_is_hsplit_top(view))
1600 v = view->child;
1601 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1602 v = view->parent;
1604 wmove(v->window, v->nlines - 1, 0);
1605 wclrtoeol(v->window);
1606 wprintw(v->window, ":%s", view->action);
1607 wrefresh(v->window);
1610 * Clear action status report. Only clear in blame view
1611 * once annotating is complete, otherwise it's too fast.
1613 if (view->type == TOG_VIEW_BLAME) {
1614 if (view->state.blame.blame_complete)
1615 view->action = NULL;
1616 } else
1617 view->action = NULL;
1621 * Read the next line from the test script and assign
1622 * key instruction to *ch. If at EOF, set the *done flag.
1624 static const struct got_error *
1625 tog_read_script_key(FILE *script, int *ch, int *done)
1627 const struct got_error *err = NULL;
1628 char *line = NULL;
1629 size_t linesz = 0;
1631 if (getline(&line, &linesz, script) == -1) {
1632 if (feof(script)) {
1633 *done = 1;
1634 goto done;
1635 } else {
1636 err = got_ferror(script, GOT_ERR_IO);
1637 goto done;
1639 } else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1640 *ch = KEY_ENTER;
1641 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1642 *ch = KEY_RIGHT;
1643 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1644 *ch = KEY_LEFT;
1645 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1646 *ch = KEY_DOWN;
1647 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1648 *ch = KEY_UP;
1649 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1650 *ch = TOG_KEY_SCRDUMP;
1651 else
1652 *ch = *line;
1654 done:
1655 free(line);
1656 return err;
1659 static const struct got_error *
1660 view_input(struct tog_view **new, int *done, struct tog_view *view,
1661 struct tog_view_list_head *views, int fast_refresh)
1663 const struct got_error *err = NULL;
1664 struct tog_view *v;
1665 int ch, errcode;
1667 *new = NULL;
1669 if (view->action)
1670 action_report(view);
1672 /* Clear "no matches" indicator. */
1673 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1674 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1675 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1676 view->count = 0;
1679 if (view->searching && !view->search_next_done) {
1680 errcode = pthread_mutex_unlock(&tog_mutex);
1681 if (errcode)
1682 return got_error_set_errno(errcode,
1683 "pthread_mutex_unlock");
1684 sched_yield();
1685 errcode = pthread_mutex_lock(&tog_mutex);
1686 if (errcode)
1687 return got_error_set_errno(errcode,
1688 "pthread_mutex_lock");
1689 view->search_next(view);
1690 return NULL;
1693 /* Allow threads to make progress while we are waiting for input. */
1694 errcode = pthread_mutex_unlock(&tog_mutex);
1695 if (errcode)
1696 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1698 if (using_mock_io) {
1699 err = tog_read_script_key(tog_io.f, &ch, done);
1700 if (err)
1701 return err;
1702 } else if (view->count && --view->count) {
1703 cbreak();
1704 nodelay(view->window, TRUE);
1705 ch = wgetch(view->window);
1706 /* let C-g or backspace abort unfinished count */
1707 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1708 view->count = 0;
1709 else
1710 ch = view->ch;
1711 } else {
1712 ch = wgetch(view->window);
1713 if (ch >= '1' && ch <= '9')
1714 view->ch = ch = get_compound_key(view, ch);
1716 if (view->hiline && ch != ERR && ch != 0)
1717 view->hiline = 0; /* key pressed, clear line highlight */
1718 nodelay(view->window, TRUE);
1719 errcode = pthread_mutex_lock(&tog_mutex);
1720 if (errcode)
1721 return got_error_set_errno(errcode, "pthread_mutex_lock");
1723 if (tog_sigwinch_received || tog_sigcont_received) {
1724 tog_resizeterm();
1725 tog_sigwinch_received = 0;
1726 tog_sigcont_received = 0;
1727 TAILQ_FOREACH(v, views, entry) {
1728 err = view_resize(v);
1729 if (err)
1730 return err;
1731 err = v->input(new, v, KEY_RESIZE);
1732 if (err)
1733 return err;
1734 if (v->child) {
1735 err = view_resize(v->child);
1736 if (err)
1737 return err;
1738 err = v->child->input(new, v->child,
1739 KEY_RESIZE);
1740 if (err)
1741 return err;
1742 if (v->child->resized_x || v->child->resized_y) {
1743 err = view_resize_split(v, 0);
1744 if (err)
1745 return err;
1751 switch (ch) {
1752 case '?':
1753 case 'H':
1754 case KEY_F(1):
1755 if (view->type == TOG_VIEW_HELP)
1756 err = view->reset(view);
1757 else
1758 err = view_request_new(new, view, TOG_VIEW_HELP);
1759 break;
1760 case '\t':
1761 view->count = 0;
1762 if (view->child) {
1763 view->focussed = 0;
1764 view->child->focussed = 1;
1765 view->focus_child = 1;
1766 } else if (view->parent) {
1767 view->focussed = 0;
1768 view->parent->focussed = 1;
1769 view->parent->focus_child = 0;
1770 if (!view_is_splitscreen(view)) {
1771 if (view->parent->resize) {
1772 err = view->parent->resize(view->parent,
1773 0);
1774 if (err)
1775 return err;
1777 offset_selection_up(view->parent);
1778 err = view_fullscreen(view->parent);
1779 if (err)
1780 return err;
1783 break;
1784 case 'q':
1785 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1786 if (view->parent->resize) {
1787 /* might need more commits to fill fullscreen */
1788 err = view->parent->resize(view->parent, 0);
1789 if (err)
1790 break;
1792 offset_selection_up(view->parent);
1794 err = view->input(new, view, ch);
1795 view->dying = 1;
1796 break;
1797 case 'Q':
1798 *done = 1;
1799 break;
1800 case 'F':
1801 view->count = 0;
1802 if (view_is_parent_view(view)) {
1803 if (view->child == NULL)
1804 break;
1805 if (view_is_splitscreen(view->child)) {
1806 view->focussed = 0;
1807 view->child->focussed = 1;
1808 err = view_fullscreen(view->child);
1809 } else {
1810 err = view_splitscreen(view->child);
1811 if (!err)
1812 err = view_resize_split(view, 0);
1814 if (err)
1815 break;
1816 err = view->child->input(new, view->child,
1817 KEY_RESIZE);
1818 } else {
1819 if (view_is_splitscreen(view)) {
1820 view->parent->focussed = 0;
1821 view->focussed = 1;
1822 err = view_fullscreen(view);
1823 } else {
1824 err = view_splitscreen(view);
1825 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1826 err = view_resize(view->parent);
1827 if (!err)
1828 err = view_resize_split(view, 0);
1830 if (err)
1831 break;
1832 err = view->input(new, view, KEY_RESIZE);
1834 if (err)
1835 break;
1836 if (view->resize) {
1837 err = view->resize(view, 0);
1838 if (err)
1839 break;
1841 if (view->parent)
1842 err = offset_selection_down(view->parent);
1843 if (!err)
1844 err = offset_selection_down(view);
1845 break;
1846 case 'S':
1847 view->count = 0;
1848 err = switch_split(view);
1849 break;
1850 case '-':
1851 err = view_resize_split(view, -1);
1852 break;
1853 case '+':
1854 err = view_resize_split(view, 1);
1855 break;
1856 case KEY_RESIZE:
1857 break;
1858 case '/':
1859 view->count = 0;
1860 if (view->search_start)
1861 view_search_start(view, fast_refresh);
1862 else
1863 err = view->input(new, view, ch);
1864 break;
1865 case 'N':
1866 case 'n':
1867 if (view->search_started && view->search_next) {
1868 view->searching = (ch == 'n' ?
1869 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1870 view->search_next_done = 0;
1871 view->search_next(view);
1872 } else
1873 err = view->input(new, view, ch);
1874 break;
1875 case 'A':
1876 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1877 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1878 view->action = "Patience diff algorithm";
1879 } else {
1880 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1881 view->action = "Myers diff algorithm";
1883 TAILQ_FOREACH(v, views, entry) {
1884 if (v->reset) {
1885 err = v->reset(v);
1886 if (err)
1887 return err;
1889 if (v->child && v->child->reset) {
1890 err = v->child->reset(v->child);
1891 if (err)
1892 return err;
1895 break;
1896 case TOG_KEY_SCRDUMP:
1897 err = screendump(view);
1898 break;
1899 default:
1900 err = view->input(new, view, ch);
1901 break;
1904 return err;
1907 static int
1908 view_needs_focus_indication(struct tog_view *view)
1910 if (view_is_parent_view(view)) {
1911 if (view->child == NULL || view->child->focussed)
1912 return 0;
1913 if (!view_is_splitscreen(view->child))
1914 return 0;
1915 } else if (!view_is_splitscreen(view))
1916 return 0;
1918 return view->focussed;
1921 static const struct got_error *
1922 tog_io_close(void)
1924 const struct got_error *err = NULL;
1926 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1927 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1928 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1929 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1930 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1931 err = got_ferror(tog_io.f, GOT_ERR_IO);
1933 return err;
1936 static const struct got_error *
1937 view_loop(struct tog_view *view)
1939 const struct got_error *err = NULL;
1940 struct tog_view_list_head views;
1941 struct tog_view *new_view;
1942 char *mode;
1943 int fast_refresh = 10;
1944 int done = 0, errcode;
1946 mode = getenv("TOG_VIEW_SPLIT_MODE");
1947 if (!mode || !(*mode == 'h' || *mode == 'H'))
1948 view->mode = TOG_VIEW_SPLIT_VERT;
1949 else
1950 view->mode = TOG_VIEW_SPLIT_HRZN;
1952 errcode = pthread_mutex_lock(&tog_mutex);
1953 if (errcode)
1954 return got_error_set_errno(errcode, "pthread_mutex_lock");
1956 TAILQ_INIT(&views);
1957 TAILQ_INSERT_HEAD(&views, view, entry);
1959 view->focussed = 1;
1960 err = view->show(view);
1961 if (err)
1962 return err;
1963 update_panels();
1964 doupdate();
1965 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1966 !tog_fatal_signal_received()) {
1967 /* Refresh fast during initialization, then become slower. */
1968 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1969 halfdelay(10); /* switch to once per second */
1971 err = view_input(&new_view, &done, view, &views, fast_refresh);
1972 if (err)
1973 break;
1975 if (view->dying && view == TAILQ_FIRST(&views) &&
1976 TAILQ_NEXT(view, entry) == NULL)
1977 done = 1;
1978 if (done) {
1979 struct tog_view *v;
1982 * When we quit, scroll the screen up a single line
1983 * so we don't lose any information.
1985 TAILQ_FOREACH(v, &views, entry) {
1986 wmove(v->window, 0, 0);
1987 wdeleteln(v->window);
1988 wnoutrefresh(v->window);
1989 if (v->child && !view_is_fullscreen(v)) {
1990 wmove(v->child->window, 0, 0);
1991 wdeleteln(v->child->window);
1992 wnoutrefresh(v->child->window);
1995 doupdate();
1998 if (view->dying) {
1999 struct tog_view *v, *prev = NULL;
2001 if (view_is_parent_view(view))
2002 prev = TAILQ_PREV(view, tog_view_list_head,
2003 entry);
2004 else if (view->parent)
2005 prev = view->parent;
2007 if (view->parent) {
2008 view->parent->child = NULL;
2009 view->parent->focus_child = 0;
2010 /* Restore fullscreen line height. */
2011 view->parent->nlines = view->parent->lines;
2012 err = view_resize(view->parent);
2013 if (err)
2014 break;
2015 /* Make resized splits persist. */
2016 view_transfer_size(view->parent, view);
2017 } else
2018 TAILQ_REMOVE(&views, view, entry);
2020 err = view_close(view);
2021 if (err)
2022 goto done;
2024 view = NULL;
2025 TAILQ_FOREACH(v, &views, entry) {
2026 if (v->focussed)
2027 break;
2029 if (view == NULL && new_view == NULL) {
2030 /* No view has focus. Try to pick one. */
2031 if (prev)
2032 view = prev;
2033 else if (!TAILQ_EMPTY(&views)) {
2034 view = TAILQ_LAST(&views,
2035 tog_view_list_head);
2037 if (view) {
2038 if (view->focus_child) {
2039 view->child->focussed = 1;
2040 view = view->child;
2041 } else
2042 view->focussed = 1;
2046 if (new_view) {
2047 struct tog_view *v, *t;
2048 /* Only allow one parent view per type. */
2049 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2050 if (v->type != new_view->type)
2051 continue;
2052 TAILQ_REMOVE(&views, v, entry);
2053 err = view_close(v);
2054 if (err)
2055 goto done;
2056 break;
2058 TAILQ_INSERT_TAIL(&views, new_view, entry);
2059 view = new_view;
2061 if (view && !done) {
2062 if (view_is_parent_view(view)) {
2063 if (view->child && view->child->focussed)
2064 view = view->child;
2065 } else {
2066 if (view->parent && view->parent->focussed)
2067 view = view->parent;
2069 show_panel(view->panel);
2070 if (view->child && view_is_splitscreen(view->child))
2071 show_panel(view->child->panel);
2072 if (view->parent && view_is_splitscreen(view)) {
2073 err = view->parent->show(view->parent);
2074 if (err)
2075 goto done;
2077 err = view->show(view);
2078 if (err)
2079 goto done;
2080 if (view->child) {
2081 err = view->child->show(view->child);
2082 if (err)
2083 goto done;
2085 update_panels();
2086 doupdate();
2089 done:
2090 while (!TAILQ_EMPTY(&views)) {
2091 const struct got_error *close_err;
2092 view = TAILQ_FIRST(&views);
2093 TAILQ_REMOVE(&views, view, entry);
2094 close_err = view_close(view);
2095 if (close_err && err == NULL)
2096 err = close_err;
2099 errcode = pthread_mutex_unlock(&tog_mutex);
2100 if (errcode && err == NULL)
2101 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2103 return err;
2106 __dead static void
2107 usage_log(void)
2109 endwin();
2110 fprintf(stderr,
2111 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2112 getprogname());
2113 exit(1);
2116 /* Create newly allocated wide-character string equivalent to a byte string. */
2117 static const struct got_error *
2118 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2120 char *vis = NULL;
2121 const struct got_error *err = NULL;
2123 *ws = NULL;
2124 *wlen = mbstowcs(NULL, s, 0);
2125 if (*wlen == (size_t)-1) {
2126 int vislen;
2127 if (errno != EILSEQ)
2128 return got_error_from_errno("mbstowcs");
2130 /* byte string invalid in current encoding; try to "fix" it */
2131 err = got_mbsavis(&vis, &vislen, s);
2132 if (err)
2133 return err;
2134 *wlen = mbstowcs(NULL, vis, 0);
2135 if (*wlen == (size_t)-1) {
2136 err = got_error_from_errno("mbstowcs"); /* give up */
2137 goto done;
2141 *ws = calloc(*wlen + 1, sizeof(**ws));
2142 if (*ws == NULL) {
2143 err = got_error_from_errno("calloc");
2144 goto done;
2147 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2148 err = got_error_from_errno("mbstowcs");
2149 done:
2150 free(vis);
2151 if (err) {
2152 free(*ws);
2153 *ws = NULL;
2154 *wlen = 0;
2156 return err;
2159 static const struct got_error *
2160 expand_tab(char **ptr, const char *src)
2162 char *dst;
2163 size_t len, n, idx = 0, sz = 0;
2165 *ptr = NULL;
2166 n = len = strlen(src);
2167 dst = malloc(n + 1);
2168 if (dst == NULL)
2169 return got_error_from_errno("malloc");
2171 while (idx < len && src[idx]) {
2172 const char c = src[idx];
2174 if (c == '\t') {
2175 size_t nb = TABSIZE - sz % TABSIZE;
2176 char *p;
2178 p = realloc(dst, n + nb);
2179 if (p == NULL) {
2180 free(dst);
2181 return got_error_from_errno("realloc");
2184 dst = p;
2185 n += nb;
2186 memset(dst + sz, ' ', nb);
2187 sz += nb;
2188 } else
2189 dst[sz++] = src[idx];
2190 ++idx;
2193 dst[sz] = '\0';
2194 *ptr = dst;
2195 return NULL;
2199 * Advance at most n columns from wline starting at offset off.
2200 * Return the index to the first character after the span operation.
2201 * Return the combined column width of all spanned wide character in
2202 * *rcol.
2204 static int
2205 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2207 int width, i, cols = 0;
2209 if (n == 0) {
2210 *rcol = cols;
2211 return off;
2214 for (i = off; wline[i] != L'\0'; ++i) {
2215 if (wline[i] == L'\t')
2216 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2217 else
2218 width = wcwidth(wline[i]);
2220 if (width == -1) {
2221 width = 1;
2222 wline[i] = L'.';
2225 if (cols + width > n)
2226 break;
2227 cols += width;
2230 *rcol = cols;
2231 return i;
2235 * Format a line for display, ensuring that it won't overflow a width limit.
2236 * With scrolling, the width returned refers to the scrolled version of the
2237 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2239 static const struct got_error *
2240 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2241 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2243 const struct got_error *err = NULL;
2244 int cols;
2245 wchar_t *wline = NULL;
2246 char *exstr = NULL;
2247 size_t wlen;
2248 int i, scrollx;
2250 *wlinep = NULL;
2251 *widthp = 0;
2253 if (expand) {
2254 err = expand_tab(&exstr, line);
2255 if (err)
2256 return err;
2259 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2260 free(exstr);
2261 if (err)
2262 return err;
2264 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2266 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2267 wline[wlen - 1] = L'\0';
2268 wlen--;
2270 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2271 wline[wlen - 1] = L'\0';
2272 wlen--;
2275 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2276 wline[i] = L'\0';
2278 if (widthp)
2279 *widthp = cols;
2280 if (scrollxp)
2281 *scrollxp = scrollx;
2282 if (err)
2283 free(wline);
2284 else
2285 *wlinep = wline;
2286 return err;
2289 static const struct got_error*
2290 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2291 struct got_object_id *id, struct got_repository *repo)
2293 static const struct got_error *err = NULL;
2294 struct got_reflist_entry *re;
2295 char *s;
2296 const char *name;
2298 *refs_str = NULL;
2300 TAILQ_FOREACH(re, refs, entry) {
2301 struct got_tag_object *tag = NULL;
2302 struct got_object_id *ref_id;
2303 int cmp;
2305 name = got_ref_get_name(re->ref);
2306 if (strcmp(name, GOT_REF_HEAD) == 0)
2307 continue;
2308 if (strncmp(name, "refs/", 5) == 0)
2309 name += 5;
2310 if (strncmp(name, "got/", 4) == 0 &&
2311 strncmp(name, "got/backup/", 11) != 0)
2312 continue;
2313 if (strncmp(name, "heads/", 6) == 0)
2314 name += 6;
2315 if (strncmp(name, "remotes/", 8) == 0) {
2316 name += 8;
2317 s = strstr(name, "/" GOT_REF_HEAD);
2318 if (s != NULL && s[strlen(s)] == '\0')
2319 continue;
2321 err = got_ref_resolve(&ref_id, repo, re->ref);
2322 if (err)
2323 break;
2324 if (strncmp(name, "tags/", 5) == 0) {
2325 err = got_object_open_as_tag(&tag, repo, ref_id);
2326 if (err) {
2327 if (err->code != GOT_ERR_OBJ_TYPE) {
2328 free(ref_id);
2329 break;
2331 /* Ref points at something other than a tag. */
2332 err = NULL;
2333 tag = NULL;
2336 cmp = got_object_id_cmp(tag ?
2337 got_object_tag_get_object_id(tag) : ref_id, id);
2338 free(ref_id);
2339 if (tag)
2340 got_object_tag_close(tag);
2341 if (cmp != 0)
2342 continue;
2343 s = *refs_str;
2344 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2345 s ? ", " : "", name) == -1) {
2346 err = got_error_from_errno("asprintf");
2347 free(s);
2348 *refs_str = NULL;
2349 break;
2351 free(s);
2354 return err;
2357 static const struct got_error *
2358 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2359 int col_tab_align)
2361 char *smallerthan;
2363 smallerthan = strchr(author, '<');
2364 if (smallerthan && smallerthan[1] != '\0')
2365 author = smallerthan + 1;
2366 author[strcspn(author, "@>")] = '\0';
2367 return format_line(wauthor, author_width, NULL, author, 0, limit,
2368 col_tab_align, 0);
2371 static const struct got_error *
2372 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2373 struct got_object_id *id, const size_t date_display_cols,
2374 int author_display_cols)
2376 struct tog_log_view_state *s = &view->state.log;
2377 const struct got_error *err = NULL;
2378 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2379 char *logmsg0 = NULL, *logmsg = NULL;
2380 char *author = NULL;
2381 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2382 int author_width, logmsg_width;
2383 char *newline, *line = NULL;
2384 int col, limit, scrollx;
2385 const int avail = view->ncols;
2386 struct tm tm;
2387 time_t committer_time;
2388 struct tog_color *tc;
2390 committer_time = got_object_commit_get_committer_time(commit);
2391 if (gmtime_r(&committer_time, &tm) == NULL)
2392 return got_error_from_errno("gmtime_r");
2393 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2394 return got_error(GOT_ERR_NO_SPACE);
2396 if (avail <= date_display_cols)
2397 limit = MIN(sizeof(datebuf) - 1, avail);
2398 else
2399 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2400 tc = get_color(&s->colors, TOG_COLOR_DATE);
2401 if (tc)
2402 wattr_on(view->window,
2403 COLOR_PAIR(tc->colorpair), NULL);
2404 waddnstr(view->window, datebuf, limit);
2405 if (tc)
2406 wattr_off(view->window,
2407 COLOR_PAIR(tc->colorpair), NULL);
2408 col = limit;
2409 if (col > avail)
2410 goto done;
2412 if (avail >= 120) {
2413 char *id_str;
2414 err = got_object_id_str(&id_str, id);
2415 if (err)
2416 goto done;
2417 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2418 if (tc)
2419 wattr_on(view->window,
2420 COLOR_PAIR(tc->colorpair), NULL);
2421 wprintw(view->window, "%.8s ", id_str);
2422 if (tc)
2423 wattr_off(view->window,
2424 COLOR_PAIR(tc->colorpair), NULL);
2425 free(id_str);
2426 col += 9;
2427 if (col > avail)
2428 goto done;
2431 if (s->use_committer)
2432 author = strdup(got_object_commit_get_committer(commit));
2433 else
2434 author = strdup(got_object_commit_get_author(commit));
2435 if (author == NULL) {
2436 err = got_error_from_errno("strdup");
2437 goto done;
2439 err = format_author(&wauthor, &author_width, author, avail - col, col);
2440 if (err)
2441 goto done;
2442 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2443 if (tc)
2444 wattr_on(view->window,
2445 COLOR_PAIR(tc->colorpair), NULL);
2446 waddwstr(view->window, wauthor);
2447 col += author_width;
2448 while (col < avail && author_width < author_display_cols + 2) {
2449 waddch(view->window, ' ');
2450 col++;
2451 author_width++;
2453 if (tc)
2454 wattr_off(view->window,
2455 COLOR_PAIR(tc->colorpair), NULL);
2456 if (col > avail)
2457 goto done;
2459 err = got_object_commit_get_logmsg(&logmsg0, commit);
2460 if (err)
2461 goto done;
2462 logmsg = logmsg0;
2463 while (*logmsg == '\n')
2464 logmsg++;
2465 newline = strchr(logmsg, '\n');
2466 if (newline)
2467 *newline = '\0';
2468 limit = avail - col;
2469 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2470 limit--; /* for the border */
2471 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2472 limit, col, 1);
2473 if (err)
2474 goto done;
2475 waddwstr(view->window, &wlogmsg[scrollx]);
2476 col += MAX(logmsg_width, 0);
2477 while (col < avail) {
2478 waddch(view->window, ' ');
2479 col++;
2481 done:
2482 free(logmsg0);
2483 free(wlogmsg);
2484 free(author);
2485 free(wauthor);
2486 free(line);
2487 return err;
2490 static struct commit_queue_entry *
2491 alloc_commit_queue_entry(struct got_commit_object *commit,
2492 struct got_object_id *id)
2494 struct commit_queue_entry *entry;
2495 struct got_object_id *dup;
2497 entry = calloc(1, sizeof(*entry));
2498 if (entry == NULL)
2499 return NULL;
2501 dup = got_object_id_dup(id);
2502 if (dup == NULL) {
2503 free(entry);
2504 return NULL;
2507 entry->id = dup;
2508 entry->commit = commit;
2509 return entry;
2512 static void
2513 pop_commit(struct commit_queue *commits)
2515 struct commit_queue_entry *entry;
2517 entry = TAILQ_FIRST(&commits->head);
2518 TAILQ_REMOVE(&commits->head, entry, entry);
2519 got_object_commit_close(entry->commit);
2520 commits->ncommits--;
2521 free(entry->id);
2522 free(entry);
2525 static void
2526 free_commits(struct commit_queue *commits)
2528 while (!TAILQ_EMPTY(&commits->head))
2529 pop_commit(commits);
2532 static const struct got_error *
2533 match_commit(int *have_match, struct got_object_id *id,
2534 struct got_commit_object *commit, regex_t *regex)
2536 const struct got_error *err = NULL;
2537 regmatch_t regmatch;
2538 char *id_str = NULL, *logmsg = NULL;
2540 *have_match = 0;
2542 err = got_object_id_str(&id_str, id);
2543 if (err)
2544 return err;
2546 err = got_object_commit_get_logmsg(&logmsg, commit);
2547 if (err)
2548 goto done;
2550 if (regexec(regex, got_object_commit_get_author(commit), 1,
2551 &regmatch, 0) == 0 ||
2552 regexec(regex, got_object_commit_get_committer(commit), 1,
2553 &regmatch, 0) == 0 ||
2554 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2555 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2556 *have_match = 1;
2557 done:
2558 free(id_str);
2559 free(logmsg);
2560 return err;
2563 static const struct got_error *
2564 queue_commits(struct tog_log_thread_args *a)
2566 const struct got_error *err = NULL;
2569 * We keep all commits open throughout the lifetime of the log
2570 * view in order to avoid having to re-fetch commits from disk
2571 * while updating the display.
2573 do {
2574 struct got_object_id id;
2575 struct got_commit_object *commit;
2576 struct commit_queue_entry *entry;
2577 int limit_match = 0;
2578 int errcode;
2580 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2581 NULL, NULL);
2582 if (err)
2583 break;
2585 err = got_object_open_as_commit(&commit, a->repo, &id);
2586 if (err)
2587 break;
2588 entry = alloc_commit_queue_entry(commit, &id);
2589 if (entry == NULL) {
2590 err = got_error_from_errno("alloc_commit_queue_entry");
2591 break;
2594 errcode = pthread_mutex_lock(&tog_mutex);
2595 if (errcode) {
2596 err = got_error_set_errno(errcode,
2597 "pthread_mutex_lock");
2598 break;
2601 entry->idx = a->real_commits->ncommits;
2602 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2603 a->real_commits->ncommits++;
2605 if (*a->limiting) {
2606 err = match_commit(&limit_match, &id, commit,
2607 a->limit_regex);
2608 if (err)
2609 break;
2611 if (limit_match) {
2612 struct commit_queue_entry *matched;
2614 matched = alloc_commit_queue_entry(
2615 entry->commit, entry->id);
2616 if (matched == NULL) {
2617 err = got_error_from_errno(
2618 "alloc_commit_queue_entry");
2619 break;
2621 matched->commit = entry->commit;
2622 got_object_commit_retain(entry->commit);
2624 matched->idx = a->limit_commits->ncommits;
2625 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2626 matched, entry);
2627 a->limit_commits->ncommits++;
2631 * This is how we signal log_thread() that we
2632 * have found a match, and that it should be
2633 * counted as a new entry for the view.
2635 a->limit_match = limit_match;
2638 if (*a->searching == TOG_SEARCH_FORWARD &&
2639 !*a->search_next_done) {
2640 int have_match;
2641 err = match_commit(&have_match, &id, commit, a->regex);
2642 if (err)
2643 break;
2645 if (*a->limiting) {
2646 if (limit_match && have_match)
2647 *a->search_next_done =
2648 TOG_SEARCH_HAVE_MORE;
2649 } else if (have_match)
2650 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2653 errcode = pthread_mutex_unlock(&tog_mutex);
2654 if (errcode && err == NULL)
2655 err = got_error_set_errno(errcode,
2656 "pthread_mutex_unlock");
2657 if (err)
2658 break;
2659 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2661 return err;
2664 static void
2665 select_commit(struct tog_log_view_state *s)
2667 struct commit_queue_entry *entry;
2668 int ncommits = 0;
2670 entry = s->first_displayed_entry;
2671 while (entry) {
2672 if (ncommits == s->selected) {
2673 s->selected_entry = entry;
2674 break;
2676 entry = TAILQ_NEXT(entry, entry);
2677 ncommits++;
2681 static const struct got_error *
2682 draw_commits(struct tog_view *view)
2684 const struct got_error *err = NULL;
2685 struct tog_log_view_state *s = &view->state.log;
2686 struct commit_queue_entry *entry = s->selected_entry;
2687 int limit = view->nlines;
2688 int width;
2689 int ncommits, author_cols = 4;
2690 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2691 char *refs_str = NULL;
2692 wchar_t *wline;
2693 struct tog_color *tc;
2694 static const size_t date_display_cols = 12;
2696 if (view_is_hsplit_top(view))
2697 --limit; /* account for border */
2699 if (s->selected_entry &&
2700 !(view->searching && view->search_next_done == 0)) {
2701 struct got_reflist_head *refs;
2702 err = got_object_id_str(&id_str, s->selected_entry->id);
2703 if (err)
2704 return err;
2705 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2706 s->selected_entry->id);
2707 if (refs) {
2708 err = build_refs_str(&refs_str, refs,
2709 s->selected_entry->id, s->repo);
2710 if (err)
2711 goto done;
2715 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2716 halfdelay(10); /* disable fast refresh */
2718 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2719 if (asprintf(&ncommits_str, " [%d/%d] %s",
2720 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2721 (view->searching && !view->search_next_done) ?
2722 "searching..." : "loading...") == -1) {
2723 err = got_error_from_errno("asprintf");
2724 goto done;
2726 } else {
2727 const char *search_str = NULL;
2728 const char *limit_str = NULL;
2730 if (view->searching) {
2731 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2732 search_str = "no more matches";
2733 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2734 search_str = "no matches found";
2735 else if (!view->search_next_done)
2736 search_str = "searching...";
2739 if (s->limit_view && s->commits->ncommits == 0)
2740 limit_str = "no matches found";
2742 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2743 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2744 search_str ? search_str : (refs_str ? refs_str : ""),
2745 limit_str ? limit_str : "") == -1) {
2746 err = got_error_from_errno("asprintf");
2747 goto done;
2751 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2752 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2753 "........................................",
2754 s->in_repo_path, ncommits_str) == -1) {
2755 err = got_error_from_errno("asprintf");
2756 header = NULL;
2757 goto done;
2759 } else if (asprintf(&header, "commit %s%s",
2760 id_str ? id_str : "........................................",
2761 ncommits_str) == -1) {
2762 err = got_error_from_errno("asprintf");
2763 header = NULL;
2764 goto done;
2766 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2767 if (err)
2768 goto done;
2770 werase(view->window);
2772 if (view_needs_focus_indication(view))
2773 wstandout(view->window);
2774 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2775 if (tc)
2776 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2777 waddwstr(view->window, wline);
2778 while (width < view->ncols) {
2779 waddch(view->window, ' ');
2780 width++;
2782 if (tc)
2783 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2784 if (view_needs_focus_indication(view))
2785 wstandend(view->window);
2786 free(wline);
2787 if (limit <= 1)
2788 goto done;
2790 /* Grow author column size if necessary, and set view->maxx. */
2791 entry = s->first_displayed_entry;
2792 ncommits = 0;
2793 view->maxx = 0;
2794 while (entry) {
2795 struct got_commit_object *c = entry->commit;
2796 char *author, *eol, *msg, *msg0;
2797 wchar_t *wauthor, *wmsg;
2798 int width;
2799 if (ncommits >= limit - 1)
2800 break;
2801 if (s->use_committer)
2802 author = strdup(got_object_commit_get_committer(c));
2803 else
2804 author = strdup(got_object_commit_get_author(c));
2805 if (author == NULL) {
2806 err = got_error_from_errno("strdup");
2807 goto done;
2809 err = format_author(&wauthor, &width, author, COLS,
2810 date_display_cols);
2811 if (author_cols < width)
2812 author_cols = width;
2813 free(wauthor);
2814 free(author);
2815 if (err)
2816 goto done;
2817 err = got_object_commit_get_logmsg(&msg0, c);
2818 if (err)
2819 goto done;
2820 msg = msg0;
2821 while (*msg == '\n')
2822 ++msg;
2823 if ((eol = strchr(msg, '\n')))
2824 *eol = '\0';
2825 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2826 date_display_cols + author_cols, 0);
2827 if (err)
2828 goto done;
2829 view->maxx = MAX(view->maxx, width);
2830 free(msg0);
2831 free(wmsg);
2832 ncommits++;
2833 entry = TAILQ_NEXT(entry, entry);
2836 entry = s->first_displayed_entry;
2837 s->last_displayed_entry = s->first_displayed_entry;
2838 ncommits = 0;
2839 while (entry) {
2840 if (ncommits >= limit - 1)
2841 break;
2842 if (ncommits == s->selected)
2843 wstandout(view->window);
2844 err = draw_commit(view, entry->commit, entry->id,
2845 date_display_cols, author_cols);
2846 if (ncommits == s->selected)
2847 wstandend(view->window);
2848 if (err)
2849 goto done;
2850 ncommits++;
2851 s->last_displayed_entry = entry;
2852 entry = TAILQ_NEXT(entry, entry);
2855 view_border(view);
2856 done:
2857 free(id_str);
2858 free(refs_str);
2859 free(ncommits_str);
2860 free(header);
2861 return err;
2864 static void
2865 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2867 struct commit_queue_entry *entry;
2868 int nscrolled = 0;
2870 entry = TAILQ_FIRST(&s->commits->head);
2871 if (s->first_displayed_entry == entry)
2872 return;
2874 entry = s->first_displayed_entry;
2875 while (entry && nscrolled < maxscroll) {
2876 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2877 if (entry) {
2878 s->first_displayed_entry = entry;
2879 nscrolled++;
2884 static const struct got_error *
2885 trigger_log_thread(struct tog_view *view, int wait)
2887 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2888 int errcode;
2890 if (!using_mock_io)
2891 halfdelay(1); /* fast refresh while loading commits */
2893 while (!ta->log_complete && !tog_thread_error &&
2894 (ta->commits_needed > 0 || ta->load_all)) {
2895 /* Wake the log thread. */
2896 errcode = pthread_cond_signal(&ta->need_commits);
2897 if (errcode)
2898 return got_error_set_errno(errcode,
2899 "pthread_cond_signal");
2902 * The mutex will be released while the view loop waits
2903 * in wgetch(), at which time the log thread will run.
2905 if (!wait)
2906 break;
2908 /* Display progress update in log view. */
2909 show_log_view(view);
2910 update_panels();
2911 doupdate();
2913 /* Wait right here while next commit is being loaded. */
2914 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2915 if (errcode)
2916 return got_error_set_errno(errcode,
2917 "pthread_cond_wait");
2919 /* Display progress update in log view. */
2920 show_log_view(view);
2921 update_panels();
2922 doupdate();
2925 return NULL;
2928 static const struct got_error *
2929 request_log_commits(struct tog_view *view)
2931 struct tog_log_view_state *state = &view->state.log;
2932 const struct got_error *err = NULL;
2934 if (state->thread_args.log_complete)
2935 return NULL;
2937 state->thread_args.commits_needed += view->nscrolled;
2938 err = trigger_log_thread(view, 1);
2939 view->nscrolled = 0;
2941 return err;
2944 static const struct got_error *
2945 log_scroll_down(struct tog_view *view, int maxscroll)
2947 struct tog_log_view_state *s = &view->state.log;
2948 const struct got_error *err = NULL;
2949 struct commit_queue_entry *pentry;
2950 int nscrolled = 0, ncommits_needed;
2952 if (s->last_displayed_entry == NULL)
2953 return NULL;
2955 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2956 if (s->commits->ncommits < ncommits_needed &&
2957 !s->thread_args.log_complete) {
2959 * Ask the log thread for required amount of commits.
2961 s->thread_args.commits_needed +=
2962 ncommits_needed - s->commits->ncommits;
2963 err = trigger_log_thread(view, 1);
2964 if (err)
2965 return err;
2968 do {
2969 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2970 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2971 break;
2973 s->last_displayed_entry = pentry ?
2974 pentry : s->last_displayed_entry;
2976 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2977 if (pentry == NULL)
2978 break;
2979 s->first_displayed_entry = pentry;
2980 } while (++nscrolled < maxscroll);
2982 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2983 view->nscrolled += nscrolled;
2984 else
2985 view->nscrolled = 0;
2987 return err;
2990 static const struct got_error *
2991 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2992 struct got_commit_object *commit, struct got_object_id *commit_id,
2993 struct tog_view *log_view, struct got_repository *repo)
2995 const struct got_error *err;
2996 struct got_object_qid *parent_id;
2997 struct tog_view *diff_view;
2999 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3000 if (diff_view == NULL)
3001 return got_error_from_errno("view_open");
3003 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3004 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3005 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3006 if (err == NULL)
3007 *new_view = diff_view;
3008 return err;
3011 static const struct got_error *
3012 tree_view_visit_subtree(struct tog_tree_view_state *s,
3013 struct got_tree_object *subtree)
3015 struct tog_parent_tree *parent;
3017 parent = calloc(1, sizeof(*parent));
3018 if (parent == NULL)
3019 return got_error_from_errno("calloc");
3021 parent->tree = s->tree;
3022 parent->first_displayed_entry = s->first_displayed_entry;
3023 parent->selected_entry = s->selected_entry;
3024 parent->selected = s->selected;
3025 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3026 s->tree = subtree;
3027 s->selected = 0;
3028 s->first_displayed_entry = NULL;
3029 return NULL;
3032 static const struct got_error *
3033 tree_view_walk_path(struct tog_tree_view_state *s,
3034 struct got_commit_object *commit, const char *path)
3036 const struct got_error *err = NULL;
3037 struct got_tree_object *tree = NULL;
3038 const char *p;
3039 char *slash, *subpath = NULL;
3041 /* Walk the path and open corresponding tree objects. */
3042 p = path;
3043 while (*p) {
3044 struct got_tree_entry *te;
3045 struct got_object_id *tree_id;
3046 char *te_name;
3048 while (p[0] == '/')
3049 p++;
3051 /* Ensure the correct subtree entry is selected. */
3052 slash = strchr(p, '/');
3053 if (slash == NULL)
3054 te_name = strdup(p);
3055 else
3056 te_name = strndup(p, slash - p);
3057 if (te_name == NULL) {
3058 err = got_error_from_errno("strndup");
3059 break;
3061 te = got_object_tree_find_entry(s->tree, te_name);
3062 if (te == NULL) {
3063 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3064 free(te_name);
3065 break;
3067 free(te_name);
3068 s->first_displayed_entry = s->selected_entry = te;
3070 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3071 break; /* jump to this file's entry */
3073 slash = strchr(p, '/');
3074 if (slash)
3075 subpath = strndup(path, slash - path);
3076 else
3077 subpath = strdup(path);
3078 if (subpath == NULL) {
3079 err = got_error_from_errno("strdup");
3080 break;
3083 err = got_object_id_by_path(&tree_id, s->repo, commit,
3084 subpath);
3085 if (err)
3086 break;
3088 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3089 free(tree_id);
3090 if (err)
3091 break;
3093 err = tree_view_visit_subtree(s, tree);
3094 if (err) {
3095 got_object_tree_close(tree);
3096 break;
3098 if (slash == NULL)
3099 break;
3100 free(subpath);
3101 subpath = NULL;
3102 p = slash;
3105 free(subpath);
3106 return err;
3109 static const struct got_error *
3110 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3111 struct commit_queue_entry *entry, const char *path,
3112 const char *head_ref_name, struct got_repository *repo)
3114 const struct got_error *err = NULL;
3115 struct tog_tree_view_state *s;
3116 struct tog_view *tree_view;
3118 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3119 if (tree_view == NULL)
3120 return got_error_from_errno("view_open");
3122 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3123 if (err)
3124 return err;
3125 s = &tree_view->state.tree;
3127 *new_view = tree_view;
3129 if (got_path_is_root_dir(path))
3130 return NULL;
3132 return tree_view_walk_path(s, entry->commit, path);
3135 static const struct got_error *
3136 block_signals_used_by_main_thread(void)
3138 sigset_t sigset;
3139 int errcode;
3141 if (sigemptyset(&sigset) == -1)
3142 return got_error_from_errno("sigemptyset");
3144 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3145 if (sigaddset(&sigset, SIGWINCH) == -1)
3146 return got_error_from_errno("sigaddset");
3147 if (sigaddset(&sigset, SIGCONT) == -1)
3148 return got_error_from_errno("sigaddset");
3149 if (sigaddset(&sigset, SIGINT) == -1)
3150 return got_error_from_errno("sigaddset");
3151 if (sigaddset(&sigset, SIGTERM) == -1)
3152 return got_error_from_errno("sigaddset");
3154 /* ncurses handles SIGTSTP */
3155 if (sigaddset(&sigset, SIGTSTP) == -1)
3156 return got_error_from_errno("sigaddset");
3158 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3159 if (errcode)
3160 return got_error_set_errno(errcode, "pthread_sigmask");
3162 return NULL;
3165 static void *
3166 log_thread(void *arg)
3168 const struct got_error *err = NULL;
3169 int errcode = 0;
3170 struct tog_log_thread_args *a = arg;
3171 int done = 0;
3174 * Sync startup with main thread such that we begin our
3175 * work once view_input() has released the mutex.
3177 errcode = pthread_mutex_lock(&tog_mutex);
3178 if (errcode) {
3179 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3180 return (void *)err;
3183 err = block_signals_used_by_main_thread();
3184 if (err) {
3185 pthread_mutex_unlock(&tog_mutex);
3186 goto done;
3189 while (!done && !err && !tog_fatal_signal_received()) {
3190 errcode = pthread_mutex_unlock(&tog_mutex);
3191 if (errcode) {
3192 err = got_error_set_errno(errcode,
3193 "pthread_mutex_unlock");
3194 goto done;
3196 err = queue_commits(a);
3197 if (err) {
3198 if (err->code != GOT_ERR_ITER_COMPLETED)
3199 goto done;
3200 err = NULL;
3201 done = 1;
3202 } else if (a->commits_needed > 0 && !a->load_all) {
3203 if (*a->limiting) {
3204 if (a->limit_match)
3205 a->commits_needed--;
3206 } else
3207 a->commits_needed--;
3210 errcode = pthread_mutex_lock(&tog_mutex);
3211 if (errcode) {
3212 err = got_error_set_errno(errcode,
3213 "pthread_mutex_lock");
3214 goto done;
3215 } else if (*a->quit)
3216 done = 1;
3217 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3218 *a->first_displayed_entry =
3219 TAILQ_FIRST(&a->limit_commits->head);
3220 *a->selected_entry = *a->first_displayed_entry;
3221 } else if (*a->first_displayed_entry == NULL) {
3222 *a->first_displayed_entry =
3223 TAILQ_FIRST(&a->real_commits->head);
3224 *a->selected_entry = *a->first_displayed_entry;
3227 errcode = pthread_cond_signal(&a->commit_loaded);
3228 if (errcode) {
3229 err = got_error_set_errno(errcode,
3230 "pthread_cond_signal");
3231 pthread_mutex_unlock(&tog_mutex);
3232 goto done;
3235 if (done)
3236 a->commits_needed = 0;
3237 else {
3238 if (a->commits_needed == 0 && !a->load_all) {
3239 errcode = pthread_cond_wait(&a->need_commits,
3240 &tog_mutex);
3241 if (errcode) {
3242 err = got_error_set_errno(errcode,
3243 "pthread_cond_wait");
3244 pthread_mutex_unlock(&tog_mutex);
3245 goto done;
3247 if (*a->quit)
3248 done = 1;
3252 a->log_complete = 1;
3253 errcode = pthread_mutex_unlock(&tog_mutex);
3254 if (errcode)
3255 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3256 done:
3257 if (err) {
3258 tog_thread_error = 1;
3259 pthread_cond_signal(&a->commit_loaded);
3261 return (void *)err;
3264 static const struct got_error *
3265 stop_log_thread(struct tog_log_view_state *s)
3267 const struct got_error *err = NULL, *thread_err = NULL;
3268 int errcode;
3270 if (s->thread) {
3271 s->quit = 1;
3272 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3273 if (errcode)
3274 return got_error_set_errno(errcode,
3275 "pthread_cond_signal");
3276 errcode = pthread_mutex_unlock(&tog_mutex);
3277 if (errcode)
3278 return got_error_set_errno(errcode,
3279 "pthread_mutex_unlock");
3280 errcode = pthread_join(s->thread, (void **)&thread_err);
3281 if (errcode)
3282 return got_error_set_errno(errcode, "pthread_join");
3283 errcode = pthread_mutex_lock(&tog_mutex);
3284 if (errcode)
3285 return got_error_set_errno(errcode,
3286 "pthread_mutex_lock");
3287 s->thread = NULL;
3290 if (s->thread_args.repo) {
3291 err = got_repo_close(s->thread_args.repo);
3292 s->thread_args.repo = NULL;
3295 if (s->thread_args.pack_fds) {
3296 const struct got_error *pack_err =
3297 got_repo_pack_fds_close(s->thread_args.pack_fds);
3298 if (err == NULL)
3299 err = pack_err;
3300 s->thread_args.pack_fds = NULL;
3303 if (s->thread_args.graph) {
3304 got_commit_graph_close(s->thread_args.graph);
3305 s->thread_args.graph = NULL;
3308 return err ? err : thread_err;
3311 static const struct got_error *
3312 close_log_view(struct tog_view *view)
3314 const struct got_error *err = NULL;
3315 struct tog_log_view_state *s = &view->state.log;
3316 int errcode;
3318 err = stop_log_thread(s);
3320 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3321 if (errcode && err == NULL)
3322 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3324 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3325 if (errcode && err == NULL)
3326 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3328 free_commits(&s->limit_commits);
3329 free_commits(&s->real_commits);
3330 free(s->in_repo_path);
3331 s->in_repo_path = NULL;
3332 free(s->start_id);
3333 s->start_id = NULL;
3334 free(s->head_ref_name);
3335 s->head_ref_name = NULL;
3336 return err;
3340 * We use two queues to implement the limit feature: first consists of
3341 * commits matching the current limit_regex; second is the real queue
3342 * of all known commits (real_commits). When the user starts limiting,
3343 * we swap queues such that all movement and displaying functionality
3344 * works with very slight change.
3346 static const struct got_error *
3347 limit_log_view(struct tog_view *view)
3349 struct tog_log_view_state *s = &view->state.log;
3350 struct commit_queue_entry *entry;
3351 struct tog_view *v = view;
3352 const struct got_error *err = NULL;
3353 char pattern[1024];
3354 int ret;
3356 if (view_is_hsplit_top(view))
3357 v = view->child;
3358 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3359 v = view->parent;
3361 /* Get the pattern */
3362 wmove(v->window, v->nlines - 1, 0);
3363 wclrtoeol(v->window);
3364 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3365 nodelay(v->window, FALSE);
3366 nocbreak();
3367 echo();
3368 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3369 cbreak();
3370 noecho();
3371 nodelay(v->window, TRUE);
3372 if (ret == ERR)
3373 return NULL;
3375 if (*pattern == '\0') {
3377 * Safety measure for the situation where the user
3378 * resets limit without previously limiting anything.
3380 if (!s->limit_view)
3381 return NULL;
3384 * User could have pressed Ctrl+L, which refreshed the
3385 * commit queues, it means we can't save previously
3386 * (before limit took place) displayed entries,
3387 * because they would point to already free'ed memory,
3388 * so we are forced to always select first entry of
3389 * the queue.
3391 s->commits = &s->real_commits;
3392 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3393 s->selected_entry = s->first_displayed_entry;
3394 s->selected = 0;
3395 s->limit_view = 0;
3397 return NULL;
3400 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3401 return NULL;
3403 s->limit_view = 1;
3405 /* Clear the screen while loading limit view */
3406 s->first_displayed_entry = NULL;
3407 s->last_displayed_entry = NULL;
3408 s->selected_entry = NULL;
3409 s->commits = &s->limit_commits;
3411 /* Prepare limit queue for new search */
3412 free_commits(&s->limit_commits);
3413 s->limit_commits.ncommits = 0;
3415 /* First process commits, which are in queue already */
3416 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3417 int have_match = 0;
3419 err = match_commit(&have_match, entry->id,
3420 entry->commit, &s->limit_regex);
3421 if (err)
3422 return err;
3424 if (have_match) {
3425 struct commit_queue_entry *matched;
3427 matched = alloc_commit_queue_entry(entry->commit,
3428 entry->id);
3429 if (matched == NULL) {
3430 err = got_error_from_errno(
3431 "alloc_commit_queue_entry");
3432 break;
3434 matched->commit = entry->commit;
3435 got_object_commit_retain(entry->commit);
3437 matched->idx = s->limit_commits.ncommits;
3438 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3439 matched, entry);
3440 s->limit_commits.ncommits++;
3444 /* Second process all the commits, until we fill the screen */
3445 if (s->limit_commits.ncommits < view->nlines - 1 &&
3446 !s->thread_args.log_complete) {
3447 s->thread_args.commits_needed +=
3448 view->nlines - s->limit_commits.ncommits - 1;
3449 err = trigger_log_thread(view, 1);
3450 if (err)
3451 return err;
3454 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3455 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3456 s->selected = 0;
3458 return NULL;
3461 static const struct got_error *
3462 search_start_log_view(struct tog_view *view)
3464 struct tog_log_view_state *s = &view->state.log;
3466 s->matched_entry = NULL;
3467 s->search_entry = NULL;
3468 return NULL;
3471 static const struct got_error *
3472 search_next_log_view(struct tog_view *view)
3474 const struct got_error *err = NULL;
3475 struct tog_log_view_state *s = &view->state.log;
3476 struct commit_queue_entry *entry;
3478 /* Display progress update in log view. */
3479 show_log_view(view);
3480 update_panels();
3481 doupdate();
3483 if (s->search_entry) {
3484 int errcode, ch;
3485 errcode = pthread_mutex_unlock(&tog_mutex);
3486 if (errcode)
3487 return got_error_set_errno(errcode,
3488 "pthread_mutex_unlock");
3489 ch = wgetch(view->window);
3490 errcode = pthread_mutex_lock(&tog_mutex);
3491 if (errcode)
3492 return got_error_set_errno(errcode,
3493 "pthread_mutex_lock");
3494 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3495 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3496 return NULL;
3498 if (view->searching == TOG_SEARCH_FORWARD)
3499 entry = TAILQ_NEXT(s->search_entry, entry);
3500 else
3501 entry = TAILQ_PREV(s->search_entry,
3502 commit_queue_head, entry);
3503 } else if (s->matched_entry) {
3505 * If the user has moved the cursor after we hit a match,
3506 * the position from where we should continue searching
3507 * might have changed.
3509 if (view->searching == TOG_SEARCH_FORWARD)
3510 entry = TAILQ_NEXT(s->selected_entry, entry);
3511 else
3512 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3513 entry);
3514 } else {
3515 entry = s->selected_entry;
3518 while (1) {
3519 int have_match = 0;
3521 if (entry == NULL) {
3522 if (s->thread_args.log_complete ||
3523 view->searching == TOG_SEARCH_BACKWARD) {
3524 view->search_next_done =
3525 (s->matched_entry == NULL ?
3526 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3527 s->search_entry = NULL;
3528 return NULL;
3531 * Poke the log thread for more commits and return,
3532 * allowing the main loop to make progress. Search
3533 * will resume at s->search_entry once we come back.
3535 s->thread_args.commits_needed++;
3536 return trigger_log_thread(view, 0);
3539 err = match_commit(&have_match, entry->id, entry->commit,
3540 &view->regex);
3541 if (err)
3542 break;
3543 if (have_match) {
3544 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3545 s->matched_entry = entry;
3546 break;
3549 s->search_entry = entry;
3550 if (view->searching == TOG_SEARCH_FORWARD)
3551 entry = TAILQ_NEXT(entry, entry);
3552 else
3553 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3556 if (s->matched_entry) {
3557 int cur = s->selected_entry->idx;
3558 while (cur < s->matched_entry->idx) {
3559 err = input_log_view(NULL, view, KEY_DOWN);
3560 if (err)
3561 return err;
3562 cur++;
3564 while (cur > s->matched_entry->idx) {
3565 err = input_log_view(NULL, view, KEY_UP);
3566 if (err)
3567 return err;
3568 cur--;
3572 s->search_entry = NULL;
3574 return NULL;
3577 static const struct got_error *
3578 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3579 struct got_repository *repo, const char *head_ref_name,
3580 const char *in_repo_path, int log_branches)
3582 const struct got_error *err = NULL;
3583 struct tog_log_view_state *s = &view->state.log;
3584 struct got_repository *thread_repo = NULL;
3585 struct got_commit_graph *thread_graph = NULL;
3586 int errcode;
3588 if (in_repo_path != s->in_repo_path) {
3589 free(s->in_repo_path);
3590 s->in_repo_path = strdup(in_repo_path);
3591 if (s->in_repo_path == NULL)
3592 return got_error_from_errno("strdup");
3595 /* The commit queue only contains commits being displayed. */
3596 TAILQ_INIT(&s->real_commits.head);
3597 s->real_commits.ncommits = 0;
3598 s->commits = &s->real_commits;
3600 TAILQ_INIT(&s->limit_commits.head);
3601 s->limit_view = 0;
3602 s->limit_commits.ncommits = 0;
3604 s->repo = repo;
3605 if (head_ref_name) {
3606 s->head_ref_name = strdup(head_ref_name);
3607 if (s->head_ref_name == NULL) {
3608 err = got_error_from_errno("strdup");
3609 goto done;
3612 s->start_id = got_object_id_dup(start_id);
3613 if (s->start_id == NULL) {
3614 err = got_error_from_errno("got_object_id_dup");
3615 goto done;
3617 s->log_branches = log_branches;
3618 s->use_committer = 1;
3620 STAILQ_INIT(&s->colors);
3621 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3622 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3623 get_color_value("TOG_COLOR_COMMIT"));
3624 if (err)
3625 goto done;
3626 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3627 get_color_value("TOG_COLOR_AUTHOR"));
3628 if (err) {
3629 free_colors(&s->colors);
3630 goto done;
3632 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3633 get_color_value("TOG_COLOR_DATE"));
3634 if (err) {
3635 free_colors(&s->colors);
3636 goto done;
3640 view->show = show_log_view;
3641 view->input = input_log_view;
3642 view->resize = resize_log_view;
3643 view->close = close_log_view;
3644 view->search_start = search_start_log_view;
3645 view->search_next = search_next_log_view;
3647 if (s->thread_args.pack_fds == NULL) {
3648 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3649 if (err)
3650 goto done;
3652 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3653 s->thread_args.pack_fds);
3654 if (err)
3655 goto done;
3656 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3657 !s->log_branches);
3658 if (err)
3659 goto done;
3660 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3661 s->repo, NULL, NULL);
3662 if (err)
3663 goto done;
3665 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3666 if (errcode) {
3667 err = got_error_set_errno(errcode, "pthread_cond_init");
3668 goto done;
3670 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3671 if (errcode) {
3672 err = got_error_set_errno(errcode, "pthread_cond_init");
3673 goto done;
3676 s->thread_args.commits_needed = view->nlines;
3677 s->thread_args.graph = thread_graph;
3678 s->thread_args.real_commits = &s->real_commits;
3679 s->thread_args.limit_commits = &s->limit_commits;
3680 s->thread_args.in_repo_path = s->in_repo_path;
3681 s->thread_args.start_id = s->start_id;
3682 s->thread_args.repo = thread_repo;
3683 s->thread_args.log_complete = 0;
3684 s->thread_args.quit = &s->quit;
3685 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3686 s->thread_args.selected_entry = &s->selected_entry;
3687 s->thread_args.searching = &view->searching;
3688 s->thread_args.search_next_done = &view->search_next_done;
3689 s->thread_args.regex = &view->regex;
3690 s->thread_args.limiting = &s->limit_view;
3691 s->thread_args.limit_regex = &s->limit_regex;
3692 s->thread_args.limit_commits = &s->limit_commits;
3693 done:
3694 if (err)
3695 close_log_view(view);
3696 return err;
3699 static const struct got_error *
3700 show_log_view(struct tog_view *view)
3702 const struct got_error *err;
3703 struct tog_log_view_state *s = &view->state.log;
3705 if (s->thread == NULL) {
3706 int errcode = pthread_create(&s->thread, NULL, log_thread,
3707 &s->thread_args);
3708 if (errcode)
3709 return got_error_set_errno(errcode, "pthread_create");
3710 if (s->thread_args.commits_needed > 0) {
3711 err = trigger_log_thread(view, 1);
3712 if (err)
3713 return err;
3717 return draw_commits(view);
3720 static void
3721 log_move_cursor_up(struct tog_view *view, int page, int home)
3723 struct tog_log_view_state *s = &view->state.log;
3725 if (s->first_displayed_entry == NULL)
3726 return;
3727 if (s->selected_entry->idx == 0)
3728 view->count = 0;
3730 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3731 || home)
3732 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3734 if (!page && !home && s->selected > 0)
3735 --s->selected;
3736 else
3737 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3739 select_commit(s);
3740 return;
3743 static const struct got_error *
3744 log_move_cursor_down(struct tog_view *view, int page)
3746 struct tog_log_view_state *s = &view->state.log;
3747 const struct got_error *err = NULL;
3748 int eos = view->nlines - 2;
3750 if (s->first_displayed_entry == NULL)
3751 return NULL;
3753 if (s->thread_args.log_complete &&
3754 s->selected_entry->idx >= s->commits->ncommits - 1)
3755 return NULL;
3757 if (view_is_hsplit_top(view))
3758 --eos; /* border consumes the last line */
3760 if (!page) {
3761 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3762 ++s->selected;
3763 else
3764 err = log_scroll_down(view, 1);
3765 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3766 struct commit_queue_entry *entry;
3767 int n;
3769 s->selected = 0;
3770 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3771 s->last_displayed_entry = entry;
3772 for (n = 0; n <= eos; n++) {
3773 if (entry == NULL)
3774 break;
3775 s->first_displayed_entry = entry;
3776 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3778 if (n > 0)
3779 s->selected = n - 1;
3780 } else {
3781 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3782 s->thread_args.log_complete)
3783 s->selected += MIN(page,
3784 s->commits->ncommits - s->selected_entry->idx - 1);
3785 else
3786 err = log_scroll_down(view, page);
3788 if (err)
3789 return err;
3792 * We might necessarily overshoot in horizontal
3793 * splits; if so, select the last displayed commit.
3795 if (s->first_displayed_entry && s->last_displayed_entry) {
3796 s->selected = MIN(s->selected,
3797 s->last_displayed_entry->idx -
3798 s->first_displayed_entry->idx);
3801 select_commit(s);
3803 if (s->thread_args.log_complete &&
3804 s->selected_entry->idx == s->commits->ncommits - 1)
3805 view->count = 0;
3807 return NULL;
3810 static void
3811 view_get_split(struct tog_view *view, int *y, int *x)
3813 *x = 0;
3814 *y = 0;
3816 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3817 if (view->child && view->child->resized_y)
3818 *y = view->child->resized_y;
3819 else if (view->resized_y)
3820 *y = view->resized_y;
3821 else
3822 *y = view_split_begin_y(view->lines);
3823 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3824 if (view->child && view->child->resized_x)
3825 *x = view->child->resized_x;
3826 else if (view->resized_x)
3827 *x = view->resized_x;
3828 else
3829 *x = view_split_begin_x(view->begin_x);
3833 /* Split view horizontally at y and offset view->state->selected line. */
3834 static const struct got_error *
3835 view_init_hsplit(struct tog_view *view, int y)
3837 const struct got_error *err = NULL;
3839 view->nlines = y;
3840 view->ncols = COLS;
3841 err = view_resize(view);
3842 if (err)
3843 return err;
3845 err = offset_selection_down(view);
3847 return err;
3850 static const struct got_error *
3851 log_goto_line(struct tog_view *view, int nlines)
3853 const struct got_error *err = NULL;
3854 struct tog_log_view_state *s = &view->state.log;
3855 int g, idx = s->selected_entry->idx;
3857 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3858 return NULL;
3860 g = view->gline;
3861 view->gline = 0;
3863 if (g >= s->first_displayed_entry->idx + 1 &&
3864 g <= s->last_displayed_entry->idx + 1 &&
3865 g - s->first_displayed_entry->idx - 1 < nlines) {
3866 s->selected = g - s->first_displayed_entry->idx - 1;
3867 select_commit(s);
3868 return NULL;
3871 if (idx + 1 < g) {
3872 err = log_move_cursor_down(view, g - idx - 1);
3873 if (!err && g > s->selected_entry->idx + 1)
3874 err = log_move_cursor_down(view,
3875 g - s->first_displayed_entry->idx - 1);
3876 if (err)
3877 return err;
3878 } else if (idx + 1 > g)
3879 log_move_cursor_up(view, idx - g + 1, 0);
3881 if (g < nlines && s->first_displayed_entry->idx == 0)
3882 s->selected = g - 1;
3884 select_commit(s);
3885 return NULL;
3889 static void
3890 horizontal_scroll_input(struct tog_view *view, int ch)
3893 switch (ch) {
3894 case KEY_LEFT:
3895 case 'h':
3896 view->x -= MIN(view->x, 2);
3897 if (view->x <= 0)
3898 view->count = 0;
3899 break;
3900 case KEY_RIGHT:
3901 case 'l':
3902 if (view->x + view->ncols / 2 < view->maxx)
3903 view->x += 2;
3904 else
3905 view->count = 0;
3906 break;
3907 case '0':
3908 view->x = 0;
3909 break;
3910 case '$':
3911 view->x = MAX(view->maxx - view->ncols / 2, 0);
3912 view->count = 0;
3913 break;
3914 default:
3915 break;
3919 static const struct got_error *
3920 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3922 const struct got_error *err = NULL;
3923 struct tog_log_view_state *s = &view->state.log;
3924 int eos, nscroll;
3926 if (s->thread_args.load_all) {
3927 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3928 s->thread_args.load_all = 0;
3929 else if (s->thread_args.log_complete) {
3930 err = log_move_cursor_down(view, s->commits->ncommits);
3931 s->thread_args.load_all = 0;
3933 if (err)
3934 return err;
3937 eos = nscroll = view->nlines - 1;
3938 if (view_is_hsplit_top(view))
3939 --eos; /* border */
3941 if (view->gline)
3942 return log_goto_line(view, eos);
3944 switch (ch) {
3945 case '&':
3946 err = limit_log_view(view);
3947 break;
3948 case 'q':
3949 s->quit = 1;
3950 break;
3951 case '0':
3952 case '$':
3953 case KEY_RIGHT:
3954 case 'l':
3955 case KEY_LEFT:
3956 case 'h':
3957 horizontal_scroll_input(view, ch);
3958 break;
3959 case 'k':
3960 case KEY_UP:
3961 case '<':
3962 case ',':
3963 case CTRL('p'):
3964 log_move_cursor_up(view, 0, 0);
3965 break;
3966 case 'g':
3967 case '=':
3968 case KEY_HOME:
3969 log_move_cursor_up(view, 0, 1);
3970 view->count = 0;
3971 break;
3972 case CTRL('u'):
3973 case 'u':
3974 nscroll /= 2;
3975 /* FALL THROUGH */
3976 case KEY_PPAGE:
3977 case CTRL('b'):
3978 case 'b':
3979 log_move_cursor_up(view, nscroll, 0);
3980 break;
3981 case 'j':
3982 case KEY_DOWN:
3983 case '>':
3984 case '.':
3985 case CTRL('n'):
3986 err = log_move_cursor_down(view, 0);
3987 break;
3988 case '@':
3989 s->use_committer = !s->use_committer;
3990 view->action = s->use_committer ?
3991 "show committer" : "show commit author";
3992 break;
3993 case 'G':
3994 case '*':
3995 case KEY_END: {
3996 /* We don't know yet how many commits, so we're forced to
3997 * traverse them all. */
3998 view->count = 0;
3999 s->thread_args.load_all = 1;
4000 if (!s->thread_args.log_complete)
4001 return trigger_log_thread(view, 0);
4002 err = log_move_cursor_down(view, s->commits->ncommits);
4003 s->thread_args.load_all = 0;
4004 break;
4006 case CTRL('d'):
4007 case 'd':
4008 nscroll /= 2;
4009 /* FALL THROUGH */
4010 case KEY_NPAGE:
4011 case CTRL('f'):
4012 case 'f':
4013 case ' ':
4014 err = log_move_cursor_down(view, nscroll);
4015 break;
4016 case KEY_RESIZE:
4017 if (s->selected > view->nlines - 2)
4018 s->selected = view->nlines - 2;
4019 if (s->selected > s->commits->ncommits - 1)
4020 s->selected = s->commits->ncommits - 1;
4021 select_commit(s);
4022 if (s->commits->ncommits < view->nlines - 1 &&
4023 !s->thread_args.log_complete) {
4024 s->thread_args.commits_needed += (view->nlines - 1) -
4025 s->commits->ncommits;
4026 err = trigger_log_thread(view, 1);
4028 break;
4029 case KEY_ENTER:
4030 case '\r':
4031 view->count = 0;
4032 if (s->selected_entry == NULL)
4033 break;
4034 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4035 break;
4036 case 'T':
4037 view->count = 0;
4038 if (s->selected_entry == NULL)
4039 break;
4040 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4041 break;
4042 case KEY_BACKSPACE:
4043 case CTRL('l'):
4044 case 'B':
4045 view->count = 0;
4046 if (ch == KEY_BACKSPACE &&
4047 got_path_is_root_dir(s->in_repo_path))
4048 break;
4049 err = stop_log_thread(s);
4050 if (err)
4051 return err;
4052 if (ch == KEY_BACKSPACE) {
4053 char *parent_path;
4054 err = got_path_dirname(&parent_path, s->in_repo_path);
4055 if (err)
4056 return err;
4057 free(s->in_repo_path);
4058 s->in_repo_path = parent_path;
4059 s->thread_args.in_repo_path = s->in_repo_path;
4060 } else if (ch == CTRL('l')) {
4061 struct got_object_id *start_id;
4062 err = got_repo_match_object_id(&start_id, NULL,
4063 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4064 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4065 if (err) {
4066 if (s->head_ref_name == NULL ||
4067 err->code != GOT_ERR_NOT_REF)
4068 return err;
4069 /* Try to cope with deleted references. */
4070 free(s->head_ref_name);
4071 s->head_ref_name = NULL;
4072 err = got_repo_match_object_id(&start_id,
4073 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4074 &tog_refs, s->repo);
4075 if (err)
4076 return err;
4078 free(s->start_id);
4079 s->start_id = start_id;
4080 s->thread_args.start_id = s->start_id;
4081 } else /* 'B' */
4082 s->log_branches = !s->log_branches;
4084 if (s->thread_args.pack_fds == NULL) {
4085 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4086 if (err)
4087 return err;
4089 err = got_repo_open(&s->thread_args.repo,
4090 got_repo_get_path(s->repo), NULL,
4091 s->thread_args.pack_fds);
4092 if (err)
4093 return err;
4094 tog_free_refs();
4095 err = tog_load_refs(s->repo, 0);
4096 if (err)
4097 return err;
4098 err = got_commit_graph_open(&s->thread_args.graph,
4099 s->in_repo_path, !s->log_branches);
4100 if (err)
4101 return err;
4102 err = got_commit_graph_iter_start(s->thread_args.graph,
4103 s->start_id, s->repo, NULL, NULL);
4104 if (err)
4105 return err;
4106 free_commits(&s->real_commits);
4107 free_commits(&s->limit_commits);
4108 s->first_displayed_entry = NULL;
4109 s->last_displayed_entry = NULL;
4110 s->selected_entry = NULL;
4111 s->selected = 0;
4112 s->thread_args.log_complete = 0;
4113 s->quit = 0;
4114 s->thread_args.commits_needed = view->lines;
4115 s->matched_entry = NULL;
4116 s->search_entry = NULL;
4117 view->offset = 0;
4118 break;
4119 case 'R':
4120 view->count = 0;
4121 err = view_request_new(new_view, view, TOG_VIEW_REF);
4122 break;
4123 default:
4124 view->count = 0;
4125 break;
4128 return err;
4131 static const struct got_error *
4132 apply_unveil(const char *repo_path, const char *worktree_path)
4134 const struct got_error *error;
4136 #ifdef PROFILE
4137 if (unveil("gmon.out", "rwc") != 0)
4138 return got_error_from_errno2("unveil", "gmon.out");
4139 #endif
4140 if (repo_path && unveil(repo_path, "r") != 0)
4141 return got_error_from_errno2("unveil", repo_path);
4143 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4144 return got_error_from_errno2("unveil", worktree_path);
4146 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4147 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4149 error = got_privsep_unveil_exec_helpers();
4150 if (error != NULL)
4151 return error;
4153 if (unveil(NULL, NULL) != 0)
4154 return got_error_from_errno("unveil");
4156 return NULL;
4159 static const struct got_error *
4160 init_mock_term(const char *test_script_path)
4162 const struct got_error *err = NULL;
4164 if (test_script_path == NULL || *test_script_path == '\0')
4165 return got_error_msg(GOT_ERR_IO, "GOT_TOG_TEST not defined");
4167 tog_io.f = fopen(test_script_path, "re");
4168 if (tog_io.f == NULL) {
4169 err = got_error_from_errno_fmt("fopen: %s",
4170 test_script_path);
4171 goto done;
4174 /* test mode, we don't want any output */
4175 tog_io.cout = fopen("/dev/null", "w+");
4176 if (tog_io.cout == NULL) {
4177 err = got_error_from_errno("fopen: /dev/null");
4178 goto done;
4181 tog_io.cin = fopen("/dev/tty", "r+");
4182 if (tog_io.cin == NULL) {
4183 err = got_error_from_errno("fopen: /dev/tty");
4184 goto done;
4187 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4188 err = got_error_from_errno("fseeko");
4189 goto done;
4192 /* use local TERM so we test in different environments */
4193 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4194 err = got_error_msg(GOT_ERR_IO,
4195 "newterm: failed to initialise curses");
4197 using_mock_io = 1;
4198 done:
4199 if (err)
4200 tog_io_close();
4201 return err;
4204 static void
4205 init_curses(void)
4208 * Override default signal handlers before starting ncurses.
4209 * This should prevent ncurses from installing its own
4210 * broken cleanup() signal handler.
4212 signal(SIGWINCH, tog_sigwinch);
4213 signal(SIGPIPE, tog_sigpipe);
4214 signal(SIGCONT, tog_sigcont);
4215 signal(SIGINT, tog_sigint);
4216 signal(SIGTERM, tog_sigterm);
4218 if (using_mock_io) /* In test mode we use a fake terminal */
4219 return;
4221 initscr();
4223 cbreak();
4224 halfdelay(1); /* Fast refresh while initial view is loading. */
4225 noecho();
4226 nonl();
4227 intrflush(stdscr, FALSE);
4228 keypad(stdscr, TRUE);
4229 curs_set(0);
4230 if (getenv("TOG_COLORS") != NULL) {
4231 start_color();
4232 use_default_colors();
4235 return;
4238 static const struct got_error *
4239 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4240 struct got_repository *repo, struct got_worktree *worktree)
4242 const struct got_error *err = NULL;
4244 if (argc == 0) {
4245 *in_repo_path = strdup("/");
4246 if (*in_repo_path == NULL)
4247 return got_error_from_errno("strdup");
4248 return NULL;
4251 if (worktree) {
4252 const char *prefix = got_worktree_get_path_prefix(worktree);
4253 char *p;
4255 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4256 if (err)
4257 return err;
4258 if (asprintf(in_repo_path, "%s%s%s", prefix,
4259 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4260 p) == -1) {
4261 err = got_error_from_errno("asprintf");
4262 *in_repo_path = NULL;
4264 free(p);
4265 } else
4266 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4268 return err;
4271 static const struct got_error *
4272 cmd_log(int argc, char *argv[])
4274 const struct got_error *error;
4275 struct got_repository *repo = NULL;
4276 struct got_worktree *worktree = NULL;
4277 struct got_object_id *start_id = NULL;
4278 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4279 char *start_commit = NULL, *label = NULL;
4280 struct got_reference *ref = NULL;
4281 const char *head_ref_name = NULL;
4282 int ch, log_branches = 0;
4283 struct tog_view *view;
4284 int *pack_fds = NULL;
4286 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4287 switch (ch) {
4288 case 'b':
4289 log_branches = 1;
4290 break;
4291 case 'c':
4292 start_commit = optarg;
4293 break;
4294 case 'r':
4295 repo_path = realpath(optarg, NULL);
4296 if (repo_path == NULL)
4297 return got_error_from_errno2("realpath",
4298 optarg);
4299 break;
4300 default:
4301 usage_log();
4302 /* NOTREACHED */
4306 argc -= optind;
4307 argv += optind;
4309 if (argc > 1)
4310 usage_log();
4312 error = got_repo_pack_fds_open(&pack_fds);
4313 if (error != NULL)
4314 goto done;
4316 if (repo_path == NULL) {
4317 cwd = getcwd(NULL, 0);
4318 if (cwd == NULL)
4319 return got_error_from_errno("getcwd");
4320 error = got_worktree_open(&worktree, cwd);
4321 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4322 goto done;
4323 if (worktree)
4324 repo_path =
4325 strdup(got_worktree_get_repo_path(worktree));
4326 else
4327 repo_path = strdup(cwd);
4328 if (repo_path == NULL) {
4329 error = got_error_from_errno("strdup");
4330 goto done;
4334 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4335 if (error != NULL)
4336 goto done;
4338 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4339 repo, worktree);
4340 if (error)
4341 goto done;
4343 init_curses();
4345 error = apply_unveil(got_repo_get_path(repo),
4346 worktree ? got_worktree_get_root_path(worktree) : NULL);
4347 if (error)
4348 goto done;
4350 /* already loaded by tog_log_with_path()? */
4351 if (TAILQ_EMPTY(&tog_refs)) {
4352 error = tog_load_refs(repo, 0);
4353 if (error)
4354 goto done;
4357 if (start_commit == NULL) {
4358 error = got_repo_match_object_id(&start_id, &label,
4359 worktree ? got_worktree_get_head_ref_name(worktree) :
4360 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4361 if (error)
4362 goto done;
4363 head_ref_name = label;
4364 } else {
4365 error = got_ref_open(&ref, repo, start_commit, 0);
4366 if (error == NULL)
4367 head_ref_name = got_ref_get_name(ref);
4368 else if (error->code != GOT_ERR_NOT_REF)
4369 goto done;
4370 error = got_repo_match_object_id(&start_id, NULL,
4371 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4372 if (error)
4373 goto done;
4376 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4377 if (view == NULL) {
4378 error = got_error_from_errno("view_open");
4379 goto done;
4381 error = open_log_view(view, start_id, repo, head_ref_name,
4382 in_repo_path, log_branches);
4383 if (error)
4384 goto done;
4385 if (worktree) {
4386 /* Release work tree lock. */
4387 got_worktree_close(worktree);
4388 worktree = NULL;
4390 error = view_loop(view);
4391 done:
4392 free(in_repo_path);
4393 free(repo_path);
4394 free(cwd);
4395 free(start_id);
4396 free(label);
4397 if (ref)
4398 got_ref_close(ref);
4399 if (repo) {
4400 const struct got_error *close_err = got_repo_close(repo);
4401 if (error == NULL)
4402 error = close_err;
4404 if (worktree)
4405 got_worktree_close(worktree);
4406 if (pack_fds) {
4407 const struct got_error *pack_err =
4408 got_repo_pack_fds_close(pack_fds);
4409 if (error == NULL)
4410 error = pack_err;
4412 tog_free_refs();
4413 return error;
4416 __dead static void
4417 usage_diff(void)
4419 endwin();
4420 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4421 "object1 object2\n", getprogname());
4422 exit(1);
4425 static int
4426 match_line(const char *line, regex_t *regex, size_t nmatch,
4427 regmatch_t *regmatch)
4429 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4432 static struct tog_color *
4433 match_color(struct tog_colors *colors, const char *line)
4435 struct tog_color *tc = NULL;
4437 STAILQ_FOREACH(tc, colors, entry) {
4438 if (match_line(line, &tc->regex, 0, NULL))
4439 return tc;
4442 return NULL;
4445 static const struct got_error *
4446 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4447 WINDOW *window, int skipcol, regmatch_t *regmatch)
4449 const struct got_error *err = NULL;
4450 char *exstr = NULL;
4451 wchar_t *wline = NULL;
4452 int rme, rms, n, width, scrollx;
4453 int width0 = 0, width1 = 0, width2 = 0;
4454 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4456 *wtotal = 0;
4458 rms = regmatch->rm_so;
4459 rme = regmatch->rm_eo;
4461 err = expand_tab(&exstr, line);
4462 if (err)
4463 return err;
4465 /* Split the line into 3 segments, according to match offsets. */
4466 seg0 = strndup(exstr, rms);
4467 if (seg0 == NULL) {
4468 err = got_error_from_errno("strndup");
4469 goto done;
4471 seg1 = strndup(exstr + rms, rme - rms);
4472 if (seg1 == NULL) {
4473 err = got_error_from_errno("strndup");
4474 goto done;
4476 seg2 = strdup(exstr + rme);
4477 if (seg2 == NULL) {
4478 err = got_error_from_errno("strndup");
4479 goto done;
4482 /* draw up to matched token if we haven't scrolled past it */
4483 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4484 col_tab_align, 1);
4485 if (err)
4486 goto done;
4487 n = MAX(width0 - skipcol, 0);
4488 if (n) {
4489 free(wline);
4490 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4491 wlimit, col_tab_align, 1);
4492 if (err)
4493 goto done;
4494 waddwstr(window, &wline[scrollx]);
4495 wlimit -= width;
4496 *wtotal += width;
4499 if (wlimit > 0) {
4500 int i = 0, w = 0;
4501 size_t wlen;
4503 free(wline);
4504 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4505 col_tab_align, 1);
4506 if (err)
4507 goto done;
4508 wlen = wcslen(wline);
4509 while (i < wlen) {
4510 width = wcwidth(wline[i]);
4511 if (width == -1) {
4512 /* should not happen, tabs are expanded */
4513 err = got_error(GOT_ERR_RANGE);
4514 goto done;
4516 if (width0 + w + width > skipcol)
4517 break;
4518 w += width;
4519 i++;
4521 /* draw (visible part of) matched token (if scrolled into it) */
4522 if (width1 - w > 0) {
4523 wattron(window, A_STANDOUT);
4524 waddwstr(window, &wline[i]);
4525 wattroff(window, A_STANDOUT);
4526 wlimit -= (width1 - w);
4527 *wtotal += (width1 - w);
4531 if (wlimit > 0) { /* draw rest of line */
4532 free(wline);
4533 if (skipcol > width0 + width1) {
4534 err = format_line(&wline, &width2, &scrollx, seg2,
4535 skipcol - (width0 + width1), wlimit,
4536 col_tab_align, 1);
4537 if (err)
4538 goto done;
4539 waddwstr(window, &wline[scrollx]);
4540 } else {
4541 err = format_line(&wline, &width2, NULL, seg2, 0,
4542 wlimit, col_tab_align, 1);
4543 if (err)
4544 goto done;
4545 waddwstr(window, wline);
4547 *wtotal += width2;
4549 done:
4550 free(wline);
4551 free(exstr);
4552 free(seg0);
4553 free(seg1);
4554 free(seg2);
4555 return err;
4558 static int
4559 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4561 FILE *f = NULL;
4562 int *eof, *first, *selected;
4564 if (view->type == TOG_VIEW_DIFF) {
4565 struct tog_diff_view_state *s = &view->state.diff;
4567 first = &s->first_displayed_line;
4568 selected = first;
4569 eof = &s->eof;
4570 f = s->f;
4571 } else if (view->type == TOG_VIEW_HELP) {
4572 struct tog_help_view_state *s = &view->state.help;
4574 first = &s->first_displayed_line;
4575 selected = first;
4576 eof = &s->eof;
4577 f = s->f;
4578 } else if (view->type == TOG_VIEW_BLAME) {
4579 struct tog_blame_view_state *s = &view->state.blame;
4581 first = &s->first_displayed_line;
4582 selected = &s->selected_line;
4583 eof = &s->eof;
4584 f = s->blame.f;
4585 } else
4586 return 0;
4588 /* Center gline in the middle of the page like vi(1). */
4589 if (*lineno < view->gline - (view->nlines - 3) / 2)
4590 return 0;
4591 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4592 rewind(f);
4593 *eof = 0;
4594 *first = 1;
4595 *lineno = 0;
4596 *nprinted = 0;
4597 return 0;
4600 *selected = view->gline <= (view->nlines - 3) / 2 ?
4601 view->gline : (view->nlines - 3) / 2 + 1;
4602 view->gline = 0;
4604 return 1;
4607 static const struct got_error *
4608 draw_file(struct tog_view *view, const char *header)
4610 struct tog_diff_view_state *s = &view->state.diff;
4611 regmatch_t *regmatch = &view->regmatch;
4612 const struct got_error *err;
4613 int nprinted = 0;
4614 char *line;
4615 size_t linesize = 0;
4616 ssize_t linelen;
4617 wchar_t *wline;
4618 int width;
4619 int max_lines = view->nlines;
4620 int nlines = s->nlines;
4621 off_t line_offset;
4623 s->lineno = s->first_displayed_line - 1;
4624 line_offset = s->lines[s->first_displayed_line - 1].offset;
4625 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4626 return got_error_from_errno("fseek");
4628 werase(view->window);
4630 if (view->gline > s->nlines - 1)
4631 view->gline = s->nlines - 1;
4633 if (header) {
4634 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4635 1 : view->gline - (view->nlines - 3) / 2 :
4636 s->lineno + s->selected_line;
4638 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4639 return got_error_from_errno("asprintf");
4640 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4641 0, 0);
4642 free(line);
4643 if (err)
4644 return err;
4646 if (view_needs_focus_indication(view))
4647 wstandout(view->window);
4648 waddwstr(view->window, wline);
4649 free(wline);
4650 wline = NULL;
4651 while (width++ < view->ncols)
4652 waddch(view->window, ' ');
4653 if (view_needs_focus_indication(view))
4654 wstandend(view->window);
4656 if (max_lines <= 1)
4657 return NULL;
4658 max_lines--;
4661 s->eof = 0;
4662 view->maxx = 0;
4663 line = NULL;
4664 while (max_lines > 0 && nprinted < max_lines) {
4665 enum got_diff_line_type linetype;
4666 attr_t attr = 0;
4668 linelen = getline(&line, &linesize, s->f);
4669 if (linelen == -1) {
4670 if (feof(s->f)) {
4671 s->eof = 1;
4672 break;
4674 free(line);
4675 return got_ferror(s->f, GOT_ERR_IO);
4678 if (++s->lineno < s->first_displayed_line)
4679 continue;
4680 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4681 continue;
4682 if (s->lineno == view->hiline)
4683 attr = A_STANDOUT;
4685 /* Set view->maxx based on full line length. */
4686 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4687 view->x ? 1 : 0);
4688 if (err) {
4689 free(line);
4690 return err;
4692 view->maxx = MAX(view->maxx, width);
4693 free(wline);
4694 wline = NULL;
4696 linetype = s->lines[s->lineno].type;
4697 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4698 linetype < GOT_DIFF_LINE_CONTEXT)
4699 attr |= COLOR_PAIR(linetype);
4700 if (attr)
4701 wattron(view->window, attr);
4702 if (s->first_displayed_line + nprinted == s->matched_line &&
4703 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4704 err = add_matched_line(&width, line, view->ncols, 0,
4705 view->window, view->x, regmatch);
4706 if (err) {
4707 free(line);
4708 return err;
4710 } else {
4711 int skip;
4712 err = format_line(&wline, &width, &skip, line,
4713 view->x, view->ncols, 0, view->x ? 1 : 0);
4714 if (err) {
4715 free(line);
4716 return err;
4718 waddwstr(view->window, &wline[skip]);
4719 free(wline);
4720 wline = NULL;
4722 if (s->lineno == view->hiline) {
4723 /* highlight full gline length */
4724 while (width++ < view->ncols)
4725 waddch(view->window, ' ');
4726 } else {
4727 if (width <= view->ncols - 1)
4728 waddch(view->window, '\n');
4730 if (attr)
4731 wattroff(view->window, attr);
4732 if (++nprinted == 1)
4733 s->first_displayed_line = s->lineno;
4735 free(line);
4736 if (nprinted >= 1)
4737 s->last_displayed_line = s->first_displayed_line +
4738 (nprinted - 1);
4739 else
4740 s->last_displayed_line = s->first_displayed_line;
4742 view_border(view);
4744 if (s->eof) {
4745 while (nprinted < view->nlines) {
4746 waddch(view->window, '\n');
4747 nprinted++;
4750 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4751 view->ncols, 0, 0);
4752 if (err) {
4753 return err;
4756 wstandout(view->window);
4757 waddwstr(view->window, wline);
4758 free(wline);
4759 wline = NULL;
4760 wstandend(view->window);
4763 return NULL;
4766 static char *
4767 get_datestr(time_t *time, char *datebuf)
4769 struct tm mytm, *tm;
4770 char *p, *s;
4772 tm = gmtime_r(time, &mytm);
4773 if (tm == NULL)
4774 return NULL;
4775 s = asctime_r(tm, datebuf);
4776 if (s == NULL)
4777 return NULL;
4778 p = strchr(s, '\n');
4779 if (p)
4780 *p = '\0';
4781 return s;
4784 static const struct got_error *
4785 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4786 off_t off, uint8_t type)
4788 struct got_diff_line *p;
4790 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4791 if (p == NULL)
4792 return got_error_from_errno("reallocarray");
4793 *lines = p;
4794 (*lines)[*nlines].offset = off;
4795 (*lines)[*nlines].type = type;
4796 (*nlines)++;
4798 return NULL;
4801 static const struct got_error *
4802 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4803 struct got_diff_line *s_lines, size_t s_nlines)
4805 struct got_diff_line *p;
4806 char buf[BUFSIZ];
4807 size_t i, r;
4809 if (fseeko(src, 0L, SEEK_SET) == -1)
4810 return got_error_from_errno("fseeko");
4812 for (;;) {
4813 r = fread(buf, 1, sizeof(buf), src);
4814 if (r == 0) {
4815 if (ferror(src))
4816 return got_error_from_errno("fread");
4817 if (feof(src))
4818 break;
4820 if (fwrite(buf, 1, r, dst) != r)
4821 return got_ferror(dst, GOT_ERR_IO);
4824 if (s_nlines == 0 && *d_nlines == 0)
4825 return NULL;
4828 * If commit info was in dst, increment line offsets
4829 * of the appended diff content, but skip s_lines[0]
4830 * because offset zero is already in *d_lines.
4832 if (*d_nlines > 0) {
4833 for (i = 1; i < s_nlines; ++i)
4834 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4836 if (s_nlines > 0) {
4837 --s_nlines;
4838 ++s_lines;
4842 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4843 if (p == NULL) {
4844 /* d_lines is freed in close_diff_view() */
4845 return got_error_from_errno("reallocarray");
4848 *d_lines = p;
4850 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4851 *d_nlines += s_nlines;
4853 return NULL;
4856 static const struct got_error *
4857 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4858 struct got_object_id *commit_id, struct got_reflist_head *refs,
4859 struct got_repository *repo, int ignore_ws, int force_text_diff,
4860 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4862 const struct got_error *err = NULL;
4863 char datebuf[26], *datestr;
4864 struct got_commit_object *commit;
4865 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4866 time_t committer_time;
4867 const char *author, *committer;
4868 char *refs_str = NULL;
4869 struct got_pathlist_entry *pe;
4870 off_t outoff = 0;
4871 int n;
4873 if (refs) {
4874 err = build_refs_str(&refs_str, refs, commit_id, repo);
4875 if (err)
4876 return err;
4879 err = got_object_open_as_commit(&commit, repo, commit_id);
4880 if (err)
4881 return err;
4883 err = got_object_id_str(&id_str, commit_id);
4884 if (err) {
4885 err = got_error_from_errno("got_object_id_str");
4886 goto done;
4889 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4890 if (err)
4891 goto done;
4893 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4894 refs_str ? refs_str : "", refs_str ? ")" : "");
4895 if (n < 0) {
4896 err = got_error_from_errno("fprintf");
4897 goto done;
4899 outoff += n;
4900 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4901 if (err)
4902 goto done;
4904 n = fprintf(outfile, "from: %s\n",
4905 got_object_commit_get_author(commit));
4906 if (n < 0) {
4907 err = got_error_from_errno("fprintf");
4908 goto done;
4910 outoff += n;
4911 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4912 if (err)
4913 goto done;
4915 author = got_object_commit_get_author(commit);
4916 committer = got_object_commit_get_committer(commit);
4917 if (strcmp(author, committer) != 0) {
4918 n = fprintf(outfile, "via: %s\n", committer);
4919 if (n < 0) {
4920 err = got_error_from_errno("fprintf");
4921 goto done;
4923 outoff += n;
4924 err = add_line_metadata(lines, nlines, outoff,
4925 GOT_DIFF_LINE_AUTHOR);
4926 if (err)
4927 goto done;
4929 committer_time = got_object_commit_get_committer_time(commit);
4930 datestr = get_datestr(&committer_time, datebuf);
4931 if (datestr) {
4932 n = fprintf(outfile, "date: %s UTC\n", datestr);
4933 if (n < 0) {
4934 err = got_error_from_errno("fprintf");
4935 goto done;
4937 outoff += n;
4938 err = add_line_metadata(lines, nlines, outoff,
4939 GOT_DIFF_LINE_DATE);
4940 if (err)
4941 goto done;
4943 if (got_object_commit_get_nparents(commit) > 1) {
4944 const struct got_object_id_queue *parent_ids;
4945 struct got_object_qid *qid;
4946 int pn = 1;
4947 parent_ids = got_object_commit_get_parent_ids(commit);
4948 STAILQ_FOREACH(qid, parent_ids, entry) {
4949 err = got_object_id_str(&id_str, &qid->id);
4950 if (err)
4951 goto done;
4952 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4953 if (n < 0) {
4954 err = got_error_from_errno("fprintf");
4955 goto done;
4957 outoff += n;
4958 err = add_line_metadata(lines, nlines, outoff,
4959 GOT_DIFF_LINE_META);
4960 if (err)
4961 goto done;
4962 free(id_str);
4963 id_str = NULL;
4967 err = got_object_commit_get_logmsg(&logmsg, commit);
4968 if (err)
4969 goto done;
4970 s = logmsg;
4971 while ((line = strsep(&s, "\n")) != NULL) {
4972 n = fprintf(outfile, "%s\n", line);
4973 if (n < 0) {
4974 err = got_error_from_errno("fprintf");
4975 goto done;
4977 outoff += n;
4978 err = add_line_metadata(lines, nlines, outoff,
4979 GOT_DIFF_LINE_LOGMSG);
4980 if (err)
4981 goto done;
4984 TAILQ_FOREACH(pe, dsa->paths, entry) {
4985 struct got_diff_changed_path *cp = pe->data;
4986 int pad = dsa->max_path_len - pe->path_len + 1;
4988 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4989 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4990 dsa->rm_cols + 1, cp->rm);
4991 if (n < 0) {
4992 err = got_error_from_errno("fprintf");
4993 goto done;
4995 outoff += n;
4996 err = add_line_metadata(lines, nlines, outoff,
4997 GOT_DIFF_LINE_CHANGES);
4998 if (err)
4999 goto done;
5002 fputc('\n', outfile);
5003 outoff++;
5004 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5005 if (err)
5006 goto done;
5008 n = fprintf(outfile,
5009 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5010 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5011 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5012 if (n < 0) {
5013 err = got_error_from_errno("fprintf");
5014 goto done;
5016 outoff += n;
5017 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5018 if (err)
5019 goto done;
5021 fputc('\n', outfile);
5022 outoff++;
5023 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5024 done:
5025 free(id_str);
5026 free(logmsg);
5027 free(refs_str);
5028 got_object_commit_close(commit);
5029 if (err) {
5030 free(*lines);
5031 *lines = NULL;
5032 *nlines = 0;
5034 return err;
5037 static const struct got_error *
5038 create_diff(struct tog_diff_view_state *s)
5040 const struct got_error *err = NULL;
5041 FILE *f = NULL, *tmp_diff_file = NULL;
5042 int obj_type;
5043 struct got_diff_line *lines = NULL;
5044 struct got_pathlist_head changed_paths;
5046 TAILQ_INIT(&changed_paths);
5048 free(s->lines);
5049 s->lines = malloc(sizeof(*s->lines));
5050 if (s->lines == NULL)
5051 return got_error_from_errno("malloc");
5052 s->nlines = 0;
5054 f = got_opentemp();
5055 if (f == NULL) {
5056 err = got_error_from_errno("got_opentemp");
5057 goto done;
5059 tmp_diff_file = got_opentemp();
5060 if (tmp_diff_file == NULL) {
5061 err = got_error_from_errno("got_opentemp");
5062 goto done;
5064 if (s->f && fclose(s->f) == EOF) {
5065 err = got_error_from_errno("fclose");
5066 goto done;
5068 s->f = f;
5070 if (s->id1)
5071 err = got_object_get_type(&obj_type, s->repo, s->id1);
5072 else
5073 err = got_object_get_type(&obj_type, s->repo, s->id2);
5074 if (err)
5075 goto done;
5077 switch (obj_type) {
5078 case GOT_OBJ_TYPE_BLOB:
5079 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5080 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5081 s->label1, s->label2, tog_diff_algo, s->diff_context,
5082 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5083 s->f);
5084 break;
5085 case GOT_OBJ_TYPE_TREE:
5086 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5087 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5088 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5089 s->force_text_diff, NULL, s->repo, s->f);
5090 break;
5091 case GOT_OBJ_TYPE_COMMIT: {
5092 const struct got_object_id_queue *parent_ids;
5093 struct got_object_qid *pid;
5094 struct got_commit_object *commit2;
5095 struct got_reflist_head *refs;
5096 size_t nlines = 0;
5097 struct got_diffstat_cb_arg dsa = {
5098 0, 0, 0, 0, 0, 0,
5099 &changed_paths,
5100 s->ignore_whitespace,
5101 s->force_text_diff,
5102 tog_diff_algo
5105 lines = malloc(sizeof(*lines));
5106 if (lines == NULL) {
5107 err = got_error_from_errno("malloc");
5108 goto done;
5111 /* build diff first in tmp file then append to commit info */
5112 err = got_diff_objects_as_commits(&lines, &nlines,
5113 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5114 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5115 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5116 if (err)
5117 break;
5119 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5120 if (err)
5121 goto done;
5122 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5123 /* Show commit info if we're diffing to a parent/root commit. */
5124 if (s->id1 == NULL) {
5125 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5126 refs, s->repo, s->ignore_whitespace,
5127 s->force_text_diff, &dsa, s->f);
5128 if (err)
5129 goto done;
5130 } else {
5131 parent_ids = got_object_commit_get_parent_ids(commit2);
5132 STAILQ_FOREACH(pid, parent_ids, entry) {
5133 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5134 err = write_commit_info(&s->lines,
5135 &s->nlines, s->id2, refs, s->repo,
5136 s->ignore_whitespace,
5137 s->force_text_diff, &dsa, s->f);
5138 if (err)
5139 goto done;
5140 break;
5144 got_object_commit_close(commit2);
5146 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5147 lines, nlines);
5148 break;
5150 default:
5151 err = got_error(GOT_ERR_OBJ_TYPE);
5152 break;
5154 done:
5155 free(lines);
5156 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5157 if (s->f && fflush(s->f) != 0 && err == NULL)
5158 err = got_error_from_errno("fflush");
5159 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5160 err = got_error_from_errno("fclose");
5161 return err;
5164 static void
5165 diff_view_indicate_progress(struct tog_view *view)
5167 mvwaddstr(view->window, 0, 0, "diffing...");
5168 update_panels();
5169 doupdate();
5172 static const struct got_error *
5173 search_start_diff_view(struct tog_view *view)
5175 struct tog_diff_view_state *s = &view->state.diff;
5177 s->matched_line = 0;
5178 return NULL;
5181 static void
5182 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5183 size_t *nlines, int **first, int **last, int **match, int **selected)
5185 struct tog_diff_view_state *s = &view->state.diff;
5187 *f = s->f;
5188 *nlines = s->nlines;
5189 *line_offsets = NULL;
5190 *match = &s->matched_line;
5191 *first = &s->first_displayed_line;
5192 *last = &s->last_displayed_line;
5193 *selected = &s->selected_line;
5196 static const struct got_error *
5197 search_next_view_match(struct tog_view *view)
5199 const struct got_error *err = NULL;
5200 FILE *f;
5201 int lineno;
5202 char *line = NULL;
5203 size_t linesize = 0;
5204 ssize_t linelen;
5205 off_t *line_offsets;
5206 size_t nlines = 0;
5207 int *first, *last, *match, *selected;
5209 if (!view->search_setup)
5210 return got_error_msg(GOT_ERR_NOT_IMPL,
5211 "view search not supported");
5212 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5213 &match, &selected);
5215 if (!view->searching) {
5216 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5217 return NULL;
5220 if (*match) {
5221 if (view->searching == TOG_SEARCH_FORWARD)
5222 lineno = *first + 1;
5223 else
5224 lineno = *first - 1;
5225 } else
5226 lineno = *first - 1 + *selected;
5228 while (1) {
5229 off_t offset;
5231 if (lineno <= 0 || lineno > nlines) {
5232 if (*match == 0) {
5233 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5234 break;
5237 if (view->searching == TOG_SEARCH_FORWARD)
5238 lineno = 1;
5239 else
5240 lineno = nlines;
5243 offset = view->type == TOG_VIEW_DIFF ?
5244 view->state.diff.lines[lineno - 1].offset :
5245 line_offsets[lineno - 1];
5246 if (fseeko(f, offset, SEEK_SET) != 0) {
5247 free(line);
5248 return got_error_from_errno("fseeko");
5250 linelen = getline(&line, &linesize, f);
5251 if (linelen != -1) {
5252 char *exstr;
5253 err = expand_tab(&exstr, line);
5254 if (err)
5255 break;
5256 if (match_line(exstr, &view->regex, 1,
5257 &view->regmatch)) {
5258 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5259 *match = lineno;
5260 free(exstr);
5261 break;
5263 free(exstr);
5265 if (view->searching == TOG_SEARCH_FORWARD)
5266 lineno++;
5267 else
5268 lineno--;
5270 free(line);
5272 if (*match) {
5273 *first = *match;
5274 *selected = 1;
5277 return err;
5280 static const struct got_error *
5281 close_diff_view(struct tog_view *view)
5283 const struct got_error *err = NULL;
5284 struct tog_diff_view_state *s = &view->state.diff;
5286 free(s->id1);
5287 s->id1 = NULL;
5288 free(s->id2);
5289 s->id2 = NULL;
5290 if (s->f && fclose(s->f) == EOF)
5291 err = got_error_from_errno("fclose");
5292 s->f = NULL;
5293 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5294 err = got_error_from_errno("fclose");
5295 s->f1 = NULL;
5296 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5297 err = got_error_from_errno("fclose");
5298 s->f2 = NULL;
5299 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5300 err = got_error_from_errno("close");
5301 s->fd1 = -1;
5302 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5303 err = got_error_from_errno("close");
5304 s->fd2 = -1;
5305 free(s->lines);
5306 s->lines = NULL;
5307 s->nlines = 0;
5308 return err;
5311 static const struct got_error *
5312 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5313 struct got_object_id *id2, const char *label1, const char *label2,
5314 int diff_context, int ignore_whitespace, int force_text_diff,
5315 struct tog_view *parent_view, struct got_repository *repo)
5317 const struct got_error *err;
5318 struct tog_diff_view_state *s = &view->state.diff;
5320 memset(s, 0, sizeof(*s));
5321 s->fd1 = -1;
5322 s->fd2 = -1;
5324 if (id1 != NULL && id2 != NULL) {
5325 int type1, type2;
5326 err = got_object_get_type(&type1, repo, id1);
5327 if (err)
5328 return err;
5329 err = got_object_get_type(&type2, repo, id2);
5330 if (err)
5331 return err;
5333 if (type1 != type2)
5334 return got_error(GOT_ERR_OBJ_TYPE);
5336 s->first_displayed_line = 1;
5337 s->last_displayed_line = view->nlines;
5338 s->selected_line = 1;
5339 s->repo = repo;
5340 s->id1 = id1;
5341 s->id2 = id2;
5342 s->label1 = label1;
5343 s->label2 = label2;
5345 if (id1) {
5346 s->id1 = got_object_id_dup(id1);
5347 if (s->id1 == NULL)
5348 return got_error_from_errno("got_object_id_dup");
5349 } else
5350 s->id1 = NULL;
5352 s->id2 = got_object_id_dup(id2);
5353 if (s->id2 == NULL) {
5354 err = got_error_from_errno("got_object_id_dup");
5355 goto done;
5358 s->f1 = got_opentemp();
5359 if (s->f1 == NULL) {
5360 err = got_error_from_errno("got_opentemp");
5361 goto done;
5364 s->f2 = got_opentemp();
5365 if (s->f2 == NULL) {
5366 err = got_error_from_errno("got_opentemp");
5367 goto done;
5370 s->fd1 = got_opentempfd();
5371 if (s->fd1 == -1) {
5372 err = got_error_from_errno("got_opentempfd");
5373 goto done;
5376 s->fd2 = got_opentempfd();
5377 if (s->fd2 == -1) {
5378 err = got_error_from_errno("got_opentempfd");
5379 goto done;
5382 s->diff_context = diff_context;
5383 s->ignore_whitespace = ignore_whitespace;
5384 s->force_text_diff = force_text_diff;
5385 s->parent_view = parent_view;
5386 s->repo = repo;
5388 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5389 int rc;
5391 rc = init_pair(GOT_DIFF_LINE_MINUS,
5392 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5393 if (rc != ERR)
5394 rc = init_pair(GOT_DIFF_LINE_PLUS,
5395 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5396 if (rc != ERR)
5397 rc = init_pair(GOT_DIFF_LINE_HUNK,
5398 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5399 if (rc != ERR)
5400 rc = init_pair(GOT_DIFF_LINE_META,
5401 get_color_value("TOG_COLOR_DIFF_META"), -1);
5402 if (rc != ERR)
5403 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5404 get_color_value("TOG_COLOR_DIFF_META"), -1);
5405 if (rc != ERR)
5406 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5407 get_color_value("TOG_COLOR_DIFF_META"), -1);
5408 if (rc != ERR)
5409 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5410 get_color_value("TOG_COLOR_DIFF_META"), -1);
5411 if (rc != ERR)
5412 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5413 get_color_value("TOG_COLOR_AUTHOR"), -1);
5414 if (rc != ERR)
5415 rc = init_pair(GOT_DIFF_LINE_DATE,
5416 get_color_value("TOG_COLOR_DATE"), -1);
5417 if (rc == ERR) {
5418 err = got_error(GOT_ERR_RANGE);
5419 goto done;
5423 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5424 view_is_splitscreen(view))
5425 show_log_view(parent_view); /* draw border */
5426 diff_view_indicate_progress(view);
5428 err = create_diff(s);
5430 view->show = show_diff_view;
5431 view->input = input_diff_view;
5432 view->reset = reset_diff_view;
5433 view->close = close_diff_view;
5434 view->search_start = search_start_diff_view;
5435 view->search_setup = search_setup_diff_view;
5436 view->search_next = search_next_view_match;
5437 done:
5438 if (err)
5439 close_diff_view(view);
5440 return err;
5443 static const struct got_error *
5444 show_diff_view(struct tog_view *view)
5446 const struct got_error *err;
5447 struct tog_diff_view_state *s = &view->state.diff;
5448 char *id_str1 = NULL, *id_str2, *header;
5449 const char *label1, *label2;
5451 if (s->id1) {
5452 err = got_object_id_str(&id_str1, s->id1);
5453 if (err)
5454 return err;
5455 label1 = s->label1 ? s->label1 : id_str1;
5456 } else
5457 label1 = "/dev/null";
5459 err = got_object_id_str(&id_str2, s->id2);
5460 if (err)
5461 return err;
5462 label2 = s->label2 ? s->label2 : id_str2;
5464 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5465 err = got_error_from_errno("asprintf");
5466 free(id_str1);
5467 free(id_str2);
5468 return err;
5470 free(id_str1);
5471 free(id_str2);
5473 err = draw_file(view, header);
5474 free(header);
5475 return err;
5478 static const struct got_error *
5479 set_selected_commit(struct tog_diff_view_state *s,
5480 struct commit_queue_entry *entry)
5482 const struct got_error *err;
5483 const struct got_object_id_queue *parent_ids;
5484 struct got_commit_object *selected_commit;
5485 struct got_object_qid *pid;
5487 free(s->id2);
5488 s->id2 = got_object_id_dup(entry->id);
5489 if (s->id2 == NULL)
5490 return got_error_from_errno("got_object_id_dup");
5492 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5493 if (err)
5494 return err;
5495 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5496 free(s->id1);
5497 pid = STAILQ_FIRST(parent_ids);
5498 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5499 got_object_commit_close(selected_commit);
5500 return NULL;
5503 static const struct got_error *
5504 reset_diff_view(struct tog_view *view)
5506 struct tog_diff_view_state *s = &view->state.diff;
5508 view->count = 0;
5509 wclear(view->window);
5510 s->first_displayed_line = 1;
5511 s->last_displayed_line = view->nlines;
5512 s->matched_line = 0;
5513 diff_view_indicate_progress(view);
5514 return create_diff(s);
5517 static void
5518 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5520 int start, i;
5522 i = start = s->first_displayed_line - 1;
5524 while (s->lines[i].type != type) {
5525 if (i == 0)
5526 i = s->nlines - 1;
5527 if (--i == start)
5528 return; /* do nothing, requested type not in file */
5531 s->selected_line = 1;
5532 s->first_displayed_line = i;
5535 static void
5536 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5538 int start, i;
5540 i = start = s->first_displayed_line + 1;
5542 while (s->lines[i].type != type) {
5543 if (i == s->nlines - 1)
5544 i = 0;
5545 if (++i == start)
5546 return; /* do nothing, requested type not in file */
5549 s->selected_line = 1;
5550 s->first_displayed_line = i;
5553 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5554 int, int, int);
5555 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5556 int, int);
5558 static const struct got_error *
5559 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5561 const struct got_error *err = NULL;
5562 struct tog_diff_view_state *s = &view->state.diff;
5563 struct tog_log_view_state *ls;
5564 struct commit_queue_entry *old_selected_entry;
5565 char *line = NULL;
5566 size_t linesize = 0;
5567 ssize_t linelen;
5568 int i, nscroll = view->nlines - 1, up = 0;
5570 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5572 switch (ch) {
5573 case '0':
5574 case '$':
5575 case KEY_RIGHT:
5576 case 'l':
5577 case KEY_LEFT:
5578 case 'h':
5579 horizontal_scroll_input(view, ch);
5580 break;
5581 case 'a':
5582 case 'w':
5583 if (ch == 'a') {
5584 s->force_text_diff = !s->force_text_diff;
5585 view->action = s->force_text_diff ?
5586 "force ASCII text enabled" :
5587 "force ASCII text disabled";
5589 else if (ch == 'w') {
5590 s->ignore_whitespace = !s->ignore_whitespace;
5591 view->action = s->ignore_whitespace ?
5592 "ignore whitespace enabled" :
5593 "ignore whitespace disabled";
5595 err = reset_diff_view(view);
5596 break;
5597 case 'g':
5598 case KEY_HOME:
5599 s->first_displayed_line = 1;
5600 view->count = 0;
5601 break;
5602 case 'G':
5603 case KEY_END:
5604 view->count = 0;
5605 if (s->eof)
5606 break;
5608 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5609 s->eof = 1;
5610 break;
5611 case 'k':
5612 case KEY_UP:
5613 case CTRL('p'):
5614 if (s->first_displayed_line > 1)
5615 s->first_displayed_line--;
5616 else
5617 view->count = 0;
5618 break;
5619 case CTRL('u'):
5620 case 'u':
5621 nscroll /= 2;
5622 /* FALL THROUGH */
5623 case KEY_PPAGE:
5624 case CTRL('b'):
5625 case 'b':
5626 if (s->first_displayed_line == 1) {
5627 view->count = 0;
5628 break;
5630 i = 0;
5631 while (i++ < nscroll && s->first_displayed_line > 1)
5632 s->first_displayed_line--;
5633 break;
5634 case 'j':
5635 case KEY_DOWN:
5636 case CTRL('n'):
5637 if (!s->eof)
5638 s->first_displayed_line++;
5639 else
5640 view->count = 0;
5641 break;
5642 case CTRL('d'):
5643 case 'd':
5644 nscroll /= 2;
5645 /* FALL THROUGH */
5646 case KEY_NPAGE:
5647 case CTRL('f'):
5648 case 'f':
5649 case ' ':
5650 if (s->eof) {
5651 view->count = 0;
5652 break;
5654 i = 0;
5655 while (!s->eof && i++ < nscroll) {
5656 linelen = getline(&line, &linesize, s->f);
5657 s->first_displayed_line++;
5658 if (linelen == -1) {
5659 if (feof(s->f)) {
5660 s->eof = 1;
5661 } else
5662 err = got_ferror(s->f, GOT_ERR_IO);
5663 break;
5666 free(line);
5667 break;
5668 case '(':
5669 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5670 break;
5671 case ')':
5672 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5673 break;
5674 case '{':
5675 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5676 break;
5677 case '}':
5678 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5679 break;
5680 case '[':
5681 if (s->diff_context > 0) {
5682 s->diff_context--;
5683 s->matched_line = 0;
5684 diff_view_indicate_progress(view);
5685 err = create_diff(s);
5686 if (s->first_displayed_line + view->nlines - 1 >
5687 s->nlines) {
5688 s->first_displayed_line = 1;
5689 s->last_displayed_line = view->nlines;
5691 } else
5692 view->count = 0;
5693 break;
5694 case ']':
5695 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5696 s->diff_context++;
5697 s->matched_line = 0;
5698 diff_view_indicate_progress(view);
5699 err = create_diff(s);
5700 } else
5701 view->count = 0;
5702 break;
5703 case '<':
5704 case ',':
5705 case 'K':
5706 up = 1;
5707 /* FALL THROUGH */
5708 case '>':
5709 case '.':
5710 case 'J':
5711 if (s->parent_view == NULL) {
5712 view->count = 0;
5713 break;
5715 s->parent_view->count = view->count;
5717 if (s->parent_view->type == TOG_VIEW_LOG) {
5718 ls = &s->parent_view->state.log;
5719 old_selected_entry = ls->selected_entry;
5721 err = input_log_view(NULL, s->parent_view,
5722 up ? KEY_UP : KEY_DOWN);
5723 if (err)
5724 break;
5725 view->count = s->parent_view->count;
5727 if (old_selected_entry == ls->selected_entry)
5728 break;
5730 err = set_selected_commit(s, ls->selected_entry);
5731 if (err)
5732 break;
5733 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5734 struct tog_blame_view_state *bs;
5735 struct got_object_id *id, *prev_id;
5737 bs = &s->parent_view->state.blame;
5738 prev_id = get_annotation_for_line(bs->blame.lines,
5739 bs->blame.nlines, bs->last_diffed_line);
5741 err = input_blame_view(&view, s->parent_view,
5742 up ? KEY_UP : KEY_DOWN);
5743 if (err)
5744 break;
5745 view->count = s->parent_view->count;
5747 if (prev_id == NULL)
5748 break;
5749 id = get_selected_commit_id(bs->blame.lines,
5750 bs->blame.nlines, bs->first_displayed_line,
5751 bs->selected_line);
5752 if (id == NULL)
5753 break;
5755 if (!got_object_id_cmp(prev_id, id))
5756 break;
5758 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5759 if (err)
5760 break;
5762 s->first_displayed_line = 1;
5763 s->last_displayed_line = view->nlines;
5764 s->matched_line = 0;
5765 view->x = 0;
5767 diff_view_indicate_progress(view);
5768 err = create_diff(s);
5769 break;
5770 default:
5771 view->count = 0;
5772 break;
5775 return err;
5778 static const struct got_error *
5779 cmd_diff(int argc, char *argv[])
5781 const struct got_error *error;
5782 struct got_repository *repo = NULL;
5783 struct got_worktree *worktree = NULL;
5784 struct got_object_id *id1 = NULL, *id2 = NULL;
5785 char *repo_path = NULL, *cwd = NULL;
5786 char *id_str1 = NULL, *id_str2 = NULL;
5787 char *label1 = NULL, *label2 = NULL;
5788 int diff_context = 3, ignore_whitespace = 0;
5789 int ch, force_text_diff = 0;
5790 const char *errstr;
5791 struct tog_view *view;
5792 int *pack_fds = NULL;
5794 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5795 switch (ch) {
5796 case 'a':
5797 force_text_diff = 1;
5798 break;
5799 case 'C':
5800 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5801 &errstr);
5802 if (errstr != NULL)
5803 errx(1, "number of context lines is %s: %s",
5804 errstr, errstr);
5805 break;
5806 case 'r':
5807 repo_path = realpath(optarg, NULL);
5808 if (repo_path == NULL)
5809 return got_error_from_errno2("realpath",
5810 optarg);
5811 got_path_strip_trailing_slashes(repo_path);
5812 break;
5813 case 'w':
5814 ignore_whitespace = 1;
5815 break;
5816 default:
5817 usage_diff();
5818 /* NOTREACHED */
5822 argc -= optind;
5823 argv += optind;
5825 if (argc == 0) {
5826 usage_diff(); /* TODO show local worktree changes */
5827 } else if (argc == 2) {
5828 id_str1 = argv[0];
5829 id_str2 = argv[1];
5830 } else
5831 usage_diff();
5833 error = got_repo_pack_fds_open(&pack_fds);
5834 if (error)
5835 goto done;
5837 if (repo_path == NULL) {
5838 cwd = getcwd(NULL, 0);
5839 if (cwd == NULL)
5840 return got_error_from_errno("getcwd");
5841 error = got_worktree_open(&worktree, cwd);
5842 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5843 goto done;
5844 if (worktree)
5845 repo_path =
5846 strdup(got_worktree_get_repo_path(worktree));
5847 else
5848 repo_path = strdup(cwd);
5849 if (repo_path == NULL) {
5850 error = got_error_from_errno("strdup");
5851 goto done;
5855 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5856 if (error)
5857 goto done;
5859 init_curses();
5861 error = apply_unveil(got_repo_get_path(repo), NULL);
5862 if (error)
5863 goto done;
5865 error = tog_load_refs(repo, 0);
5866 if (error)
5867 goto done;
5869 error = got_repo_match_object_id(&id1, &label1, id_str1,
5870 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5871 if (error)
5872 goto done;
5874 error = got_repo_match_object_id(&id2, &label2, id_str2,
5875 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5876 if (error)
5877 goto done;
5879 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5880 if (view == NULL) {
5881 error = got_error_from_errno("view_open");
5882 goto done;
5884 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5885 ignore_whitespace, force_text_diff, NULL, repo);
5886 if (error)
5887 goto done;
5888 error = view_loop(view);
5889 done:
5890 free(label1);
5891 free(label2);
5892 free(repo_path);
5893 free(cwd);
5894 if (repo) {
5895 const struct got_error *close_err = got_repo_close(repo);
5896 if (error == NULL)
5897 error = close_err;
5899 if (worktree)
5900 got_worktree_close(worktree);
5901 if (pack_fds) {
5902 const struct got_error *pack_err =
5903 got_repo_pack_fds_close(pack_fds);
5904 if (error == NULL)
5905 error = pack_err;
5907 tog_free_refs();
5908 return error;
5911 __dead static void
5912 usage_blame(void)
5914 endwin();
5915 fprintf(stderr,
5916 "usage: %s blame [-c commit] [-r repository-path] path\n",
5917 getprogname());
5918 exit(1);
5921 struct tog_blame_line {
5922 int annotated;
5923 struct got_object_id *id;
5926 static const struct got_error *
5927 draw_blame(struct tog_view *view)
5929 struct tog_blame_view_state *s = &view->state.blame;
5930 struct tog_blame *blame = &s->blame;
5931 regmatch_t *regmatch = &view->regmatch;
5932 const struct got_error *err;
5933 int lineno = 0, nprinted = 0;
5934 char *line = NULL;
5935 size_t linesize = 0;
5936 ssize_t linelen;
5937 wchar_t *wline;
5938 int width;
5939 struct tog_blame_line *blame_line;
5940 struct got_object_id *prev_id = NULL;
5941 char *id_str;
5942 struct tog_color *tc;
5944 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5945 if (err)
5946 return err;
5948 rewind(blame->f);
5949 werase(view->window);
5951 if (asprintf(&line, "commit %s", id_str) == -1) {
5952 err = got_error_from_errno("asprintf");
5953 free(id_str);
5954 return err;
5957 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5958 free(line);
5959 line = NULL;
5960 if (err)
5961 return err;
5962 if (view_needs_focus_indication(view))
5963 wstandout(view->window);
5964 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5965 if (tc)
5966 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5967 waddwstr(view->window, wline);
5968 while (width++ < view->ncols)
5969 waddch(view->window, ' ');
5970 if (tc)
5971 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5972 if (view_needs_focus_indication(view))
5973 wstandend(view->window);
5974 free(wline);
5975 wline = NULL;
5977 if (view->gline > blame->nlines)
5978 view->gline = blame->nlines;
5980 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5981 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5982 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5983 free(id_str);
5984 return got_error_from_errno("asprintf");
5986 free(id_str);
5987 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5988 free(line);
5989 line = NULL;
5990 if (err)
5991 return err;
5992 waddwstr(view->window, wline);
5993 free(wline);
5994 wline = NULL;
5995 if (width < view->ncols - 1)
5996 waddch(view->window, '\n');
5998 s->eof = 0;
5999 view->maxx = 0;
6000 while (nprinted < view->nlines - 2) {
6001 linelen = getline(&line, &linesize, blame->f);
6002 if (linelen == -1) {
6003 if (feof(blame->f)) {
6004 s->eof = 1;
6005 break;
6007 free(line);
6008 return got_ferror(blame->f, GOT_ERR_IO);
6010 if (++lineno < s->first_displayed_line)
6011 continue;
6012 if (view->gline && !gotoline(view, &lineno, &nprinted))
6013 continue;
6015 /* Set view->maxx based on full line length. */
6016 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6017 if (err) {
6018 free(line);
6019 return err;
6021 free(wline);
6022 wline = NULL;
6023 view->maxx = MAX(view->maxx, width);
6025 if (nprinted == s->selected_line - 1)
6026 wstandout(view->window);
6028 if (blame->nlines > 0) {
6029 blame_line = &blame->lines[lineno - 1];
6030 if (blame_line->annotated && prev_id &&
6031 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6032 !(nprinted == s->selected_line - 1)) {
6033 waddstr(view->window, " ");
6034 } else if (blame_line->annotated) {
6035 char *id_str;
6036 err = got_object_id_str(&id_str,
6037 blame_line->id);
6038 if (err) {
6039 free(line);
6040 return err;
6042 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6043 if (tc)
6044 wattr_on(view->window,
6045 COLOR_PAIR(tc->colorpair), NULL);
6046 wprintw(view->window, "%.8s", id_str);
6047 if (tc)
6048 wattr_off(view->window,
6049 COLOR_PAIR(tc->colorpair), NULL);
6050 free(id_str);
6051 prev_id = blame_line->id;
6052 } else {
6053 waddstr(view->window, "........");
6054 prev_id = NULL;
6056 } else {
6057 waddstr(view->window, "........");
6058 prev_id = NULL;
6061 if (nprinted == s->selected_line - 1)
6062 wstandend(view->window);
6063 waddstr(view->window, " ");
6065 if (view->ncols <= 9) {
6066 width = 9;
6067 } else if (s->first_displayed_line + nprinted ==
6068 s->matched_line &&
6069 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6070 err = add_matched_line(&width, line, view->ncols - 9, 9,
6071 view->window, view->x, regmatch);
6072 if (err) {
6073 free(line);
6074 return err;
6076 width += 9;
6077 } else {
6078 int skip;
6079 err = format_line(&wline, &width, &skip, line,
6080 view->x, view->ncols - 9, 9, 1);
6081 if (err) {
6082 free(line);
6083 return err;
6085 waddwstr(view->window, &wline[skip]);
6086 width += 9;
6087 free(wline);
6088 wline = NULL;
6091 if (width <= view->ncols - 1)
6092 waddch(view->window, '\n');
6093 if (++nprinted == 1)
6094 s->first_displayed_line = lineno;
6096 free(line);
6097 s->last_displayed_line = lineno;
6099 view_border(view);
6101 return NULL;
6104 static const struct got_error *
6105 blame_cb(void *arg, int nlines, int lineno,
6106 struct got_commit_object *commit, struct got_object_id *id)
6108 const struct got_error *err = NULL;
6109 struct tog_blame_cb_args *a = arg;
6110 struct tog_blame_line *line;
6111 int errcode;
6113 if (nlines != a->nlines ||
6114 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6115 return got_error(GOT_ERR_RANGE);
6117 errcode = pthread_mutex_lock(&tog_mutex);
6118 if (errcode)
6119 return got_error_set_errno(errcode, "pthread_mutex_lock");
6121 if (*a->quit) { /* user has quit the blame view */
6122 err = got_error(GOT_ERR_ITER_COMPLETED);
6123 goto done;
6126 if (lineno == -1)
6127 goto done; /* no change in this commit */
6129 line = &a->lines[lineno - 1];
6130 if (line->annotated)
6131 goto done;
6133 line->id = got_object_id_dup(id);
6134 if (line->id == NULL) {
6135 err = got_error_from_errno("got_object_id_dup");
6136 goto done;
6138 line->annotated = 1;
6139 done:
6140 errcode = pthread_mutex_unlock(&tog_mutex);
6141 if (errcode)
6142 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6143 return err;
6146 static void *
6147 blame_thread(void *arg)
6149 const struct got_error *err, *close_err;
6150 struct tog_blame_thread_args *ta = arg;
6151 struct tog_blame_cb_args *a = ta->cb_args;
6152 int errcode, fd1 = -1, fd2 = -1;
6153 FILE *f1 = NULL, *f2 = NULL;
6155 fd1 = got_opentempfd();
6156 if (fd1 == -1)
6157 return (void *)got_error_from_errno("got_opentempfd");
6159 fd2 = got_opentempfd();
6160 if (fd2 == -1) {
6161 err = got_error_from_errno("got_opentempfd");
6162 goto done;
6165 f1 = got_opentemp();
6166 if (f1 == NULL) {
6167 err = (void *)got_error_from_errno("got_opentemp");
6168 goto done;
6170 f2 = got_opentemp();
6171 if (f2 == NULL) {
6172 err = (void *)got_error_from_errno("got_opentemp");
6173 goto done;
6176 err = block_signals_used_by_main_thread();
6177 if (err)
6178 goto done;
6180 err = got_blame(ta->path, a->commit_id, ta->repo,
6181 tog_diff_algo, blame_cb, ta->cb_args,
6182 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6183 if (err && err->code == GOT_ERR_CANCELLED)
6184 err = NULL;
6186 errcode = pthread_mutex_lock(&tog_mutex);
6187 if (errcode) {
6188 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6189 goto done;
6192 close_err = got_repo_close(ta->repo);
6193 if (err == NULL)
6194 err = close_err;
6195 ta->repo = NULL;
6196 *ta->complete = 1;
6198 errcode = pthread_mutex_unlock(&tog_mutex);
6199 if (errcode && err == NULL)
6200 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6202 done:
6203 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6204 err = got_error_from_errno("close");
6205 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6206 err = got_error_from_errno("close");
6207 if (f1 && fclose(f1) == EOF && err == NULL)
6208 err = got_error_from_errno("fclose");
6209 if (f2 && fclose(f2) == EOF && err == NULL)
6210 err = got_error_from_errno("fclose");
6212 return (void *)err;
6215 static struct got_object_id *
6216 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6217 int first_displayed_line, int selected_line)
6219 struct tog_blame_line *line;
6221 if (nlines <= 0)
6222 return NULL;
6224 line = &lines[first_displayed_line - 1 + selected_line - 1];
6225 if (!line->annotated)
6226 return NULL;
6228 return line->id;
6231 static struct got_object_id *
6232 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6233 int lineno)
6235 struct tog_blame_line *line;
6237 if (nlines <= 0 || lineno >= nlines)
6238 return NULL;
6240 line = &lines[lineno - 1];
6241 if (!line->annotated)
6242 return NULL;
6244 return line->id;
6247 static const struct got_error *
6248 stop_blame(struct tog_blame *blame)
6250 const struct got_error *err = NULL;
6251 int i;
6253 if (blame->thread) {
6254 int errcode;
6255 errcode = pthread_mutex_unlock(&tog_mutex);
6256 if (errcode)
6257 return got_error_set_errno(errcode,
6258 "pthread_mutex_unlock");
6259 errcode = pthread_join(blame->thread, (void **)&err);
6260 if (errcode)
6261 return got_error_set_errno(errcode, "pthread_join");
6262 errcode = pthread_mutex_lock(&tog_mutex);
6263 if (errcode)
6264 return got_error_set_errno(errcode,
6265 "pthread_mutex_lock");
6266 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6267 err = NULL;
6268 blame->thread = NULL;
6270 if (blame->thread_args.repo) {
6271 const struct got_error *close_err;
6272 close_err = got_repo_close(blame->thread_args.repo);
6273 if (err == NULL)
6274 err = close_err;
6275 blame->thread_args.repo = NULL;
6277 if (blame->f) {
6278 if (fclose(blame->f) == EOF && err == NULL)
6279 err = got_error_from_errno("fclose");
6280 blame->f = NULL;
6282 if (blame->lines) {
6283 for (i = 0; i < blame->nlines; i++)
6284 free(blame->lines[i].id);
6285 free(blame->lines);
6286 blame->lines = NULL;
6288 free(blame->cb_args.commit_id);
6289 blame->cb_args.commit_id = NULL;
6290 if (blame->pack_fds) {
6291 const struct got_error *pack_err =
6292 got_repo_pack_fds_close(blame->pack_fds);
6293 if (err == NULL)
6294 err = pack_err;
6295 blame->pack_fds = NULL;
6297 return err;
6300 static const struct got_error *
6301 cancel_blame_view(void *arg)
6303 const struct got_error *err = NULL;
6304 int *done = arg;
6305 int errcode;
6307 errcode = pthread_mutex_lock(&tog_mutex);
6308 if (errcode)
6309 return got_error_set_errno(errcode,
6310 "pthread_mutex_unlock");
6312 if (*done)
6313 err = got_error(GOT_ERR_CANCELLED);
6315 errcode = pthread_mutex_unlock(&tog_mutex);
6316 if (errcode)
6317 return got_error_set_errno(errcode,
6318 "pthread_mutex_lock");
6320 return err;
6323 static const struct got_error *
6324 run_blame(struct tog_view *view)
6326 struct tog_blame_view_state *s = &view->state.blame;
6327 struct tog_blame *blame = &s->blame;
6328 const struct got_error *err = NULL;
6329 struct got_commit_object *commit = NULL;
6330 struct got_blob_object *blob = NULL;
6331 struct got_repository *thread_repo = NULL;
6332 struct got_object_id *obj_id = NULL;
6333 int obj_type, fd = -1;
6334 int *pack_fds = NULL;
6336 err = got_object_open_as_commit(&commit, s->repo,
6337 &s->blamed_commit->id);
6338 if (err)
6339 return err;
6341 fd = got_opentempfd();
6342 if (fd == -1) {
6343 err = got_error_from_errno("got_opentempfd");
6344 goto done;
6347 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6348 if (err)
6349 goto done;
6351 err = got_object_get_type(&obj_type, s->repo, obj_id);
6352 if (err)
6353 goto done;
6355 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6356 err = got_error(GOT_ERR_OBJ_TYPE);
6357 goto done;
6360 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6361 if (err)
6362 goto done;
6363 blame->f = got_opentemp();
6364 if (blame->f == NULL) {
6365 err = got_error_from_errno("got_opentemp");
6366 goto done;
6368 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6369 &blame->line_offsets, blame->f, blob);
6370 if (err)
6371 goto done;
6372 if (blame->nlines == 0) {
6373 s->blame_complete = 1;
6374 goto done;
6377 /* Don't include \n at EOF in the blame line count. */
6378 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6379 blame->nlines--;
6381 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6382 if (blame->lines == NULL) {
6383 err = got_error_from_errno("calloc");
6384 goto done;
6387 err = got_repo_pack_fds_open(&pack_fds);
6388 if (err)
6389 goto done;
6390 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6391 pack_fds);
6392 if (err)
6393 goto done;
6395 blame->pack_fds = pack_fds;
6396 blame->cb_args.view = view;
6397 blame->cb_args.lines = blame->lines;
6398 blame->cb_args.nlines = blame->nlines;
6399 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6400 if (blame->cb_args.commit_id == NULL) {
6401 err = got_error_from_errno("got_object_id_dup");
6402 goto done;
6404 blame->cb_args.quit = &s->done;
6406 blame->thread_args.path = s->path;
6407 blame->thread_args.repo = thread_repo;
6408 blame->thread_args.cb_args = &blame->cb_args;
6409 blame->thread_args.complete = &s->blame_complete;
6410 blame->thread_args.cancel_cb = cancel_blame_view;
6411 blame->thread_args.cancel_arg = &s->done;
6412 s->blame_complete = 0;
6414 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6415 s->first_displayed_line = 1;
6416 s->last_displayed_line = view->nlines;
6417 s->selected_line = 1;
6419 s->matched_line = 0;
6421 done:
6422 if (commit)
6423 got_object_commit_close(commit);
6424 if (fd != -1 && close(fd) == -1 && err == NULL)
6425 err = got_error_from_errno("close");
6426 if (blob)
6427 got_object_blob_close(blob);
6428 free(obj_id);
6429 if (err)
6430 stop_blame(blame);
6431 return err;
6434 static const struct got_error *
6435 open_blame_view(struct tog_view *view, char *path,
6436 struct got_object_id *commit_id, struct got_repository *repo)
6438 const struct got_error *err = NULL;
6439 struct tog_blame_view_state *s = &view->state.blame;
6441 STAILQ_INIT(&s->blamed_commits);
6443 s->path = strdup(path);
6444 if (s->path == NULL)
6445 return got_error_from_errno("strdup");
6447 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6448 if (err) {
6449 free(s->path);
6450 return err;
6453 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6454 s->first_displayed_line = 1;
6455 s->last_displayed_line = view->nlines;
6456 s->selected_line = 1;
6457 s->blame_complete = 0;
6458 s->repo = repo;
6459 s->commit_id = commit_id;
6460 memset(&s->blame, 0, sizeof(s->blame));
6462 STAILQ_INIT(&s->colors);
6463 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6464 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6465 get_color_value("TOG_COLOR_COMMIT"));
6466 if (err)
6467 return err;
6470 view->show = show_blame_view;
6471 view->input = input_blame_view;
6472 view->reset = reset_blame_view;
6473 view->close = close_blame_view;
6474 view->search_start = search_start_blame_view;
6475 view->search_setup = search_setup_blame_view;
6476 view->search_next = search_next_view_match;
6478 return run_blame(view);
6481 static const struct got_error *
6482 close_blame_view(struct tog_view *view)
6484 const struct got_error *err = NULL;
6485 struct tog_blame_view_state *s = &view->state.blame;
6487 if (s->blame.thread)
6488 err = stop_blame(&s->blame);
6490 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6491 struct got_object_qid *blamed_commit;
6492 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6493 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6494 got_object_qid_free(blamed_commit);
6497 free(s->path);
6498 free_colors(&s->colors);
6499 return err;
6502 static const struct got_error *
6503 search_start_blame_view(struct tog_view *view)
6505 struct tog_blame_view_state *s = &view->state.blame;
6507 s->matched_line = 0;
6508 return NULL;
6511 static void
6512 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6513 size_t *nlines, int **first, int **last, int **match, int **selected)
6515 struct tog_blame_view_state *s = &view->state.blame;
6517 *f = s->blame.f;
6518 *nlines = s->blame.nlines;
6519 *line_offsets = s->blame.line_offsets;
6520 *match = &s->matched_line;
6521 *first = &s->first_displayed_line;
6522 *last = &s->last_displayed_line;
6523 *selected = &s->selected_line;
6526 static const struct got_error *
6527 show_blame_view(struct tog_view *view)
6529 const struct got_error *err = NULL;
6530 struct tog_blame_view_state *s = &view->state.blame;
6531 int errcode;
6533 if (s->blame.thread == NULL && !s->blame_complete) {
6534 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6535 &s->blame.thread_args);
6536 if (errcode)
6537 return got_error_set_errno(errcode, "pthread_create");
6539 if (!using_mock_io)
6540 halfdelay(1); /* fast refresh while annotating */
6543 if (s->blame_complete && !using_mock_io)
6544 halfdelay(10); /* disable fast refresh */
6546 err = draw_blame(view);
6548 view_border(view);
6549 return err;
6552 static const struct got_error *
6553 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6554 struct got_repository *repo, struct got_object_id *id)
6556 struct tog_view *log_view;
6557 const struct got_error *err = NULL;
6559 *new_view = NULL;
6561 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6562 if (log_view == NULL)
6563 return got_error_from_errno("view_open");
6565 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6566 if (err)
6567 view_close(log_view);
6568 else
6569 *new_view = log_view;
6571 return err;
6574 static const struct got_error *
6575 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6577 const struct got_error *err = NULL, *thread_err = NULL;
6578 struct tog_view *diff_view;
6579 struct tog_blame_view_state *s = &view->state.blame;
6580 int eos, nscroll, begin_y = 0, begin_x = 0;
6582 eos = nscroll = view->nlines - 2;
6583 if (view_is_hsplit_top(view))
6584 --eos; /* border */
6586 switch (ch) {
6587 case '0':
6588 case '$':
6589 case KEY_RIGHT:
6590 case 'l':
6591 case KEY_LEFT:
6592 case 'h':
6593 horizontal_scroll_input(view, ch);
6594 break;
6595 case 'q':
6596 s->done = 1;
6597 break;
6598 case 'g':
6599 case KEY_HOME:
6600 s->selected_line = 1;
6601 s->first_displayed_line = 1;
6602 view->count = 0;
6603 break;
6604 case 'G':
6605 case KEY_END:
6606 if (s->blame.nlines < eos) {
6607 s->selected_line = s->blame.nlines;
6608 s->first_displayed_line = 1;
6609 } else {
6610 s->selected_line = eos;
6611 s->first_displayed_line = s->blame.nlines - (eos - 1);
6613 view->count = 0;
6614 break;
6615 case 'k':
6616 case KEY_UP:
6617 case CTRL('p'):
6618 if (s->selected_line > 1)
6619 s->selected_line--;
6620 else if (s->selected_line == 1 &&
6621 s->first_displayed_line > 1)
6622 s->first_displayed_line--;
6623 else
6624 view->count = 0;
6625 break;
6626 case CTRL('u'):
6627 case 'u':
6628 nscroll /= 2;
6629 /* FALL THROUGH */
6630 case KEY_PPAGE:
6631 case CTRL('b'):
6632 case 'b':
6633 if (s->first_displayed_line == 1) {
6634 if (view->count > 1)
6635 nscroll += nscroll;
6636 s->selected_line = MAX(1, s->selected_line - nscroll);
6637 view->count = 0;
6638 break;
6640 if (s->first_displayed_line > nscroll)
6641 s->first_displayed_line -= nscroll;
6642 else
6643 s->first_displayed_line = 1;
6644 break;
6645 case 'j':
6646 case KEY_DOWN:
6647 case CTRL('n'):
6648 if (s->selected_line < eos && s->first_displayed_line +
6649 s->selected_line <= s->blame.nlines)
6650 s->selected_line++;
6651 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6652 s->first_displayed_line++;
6653 else
6654 view->count = 0;
6655 break;
6656 case 'c':
6657 case 'p': {
6658 struct got_object_id *id = NULL;
6660 view->count = 0;
6661 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6662 s->first_displayed_line, s->selected_line);
6663 if (id == NULL)
6664 break;
6665 if (ch == 'p') {
6666 struct got_commit_object *commit, *pcommit;
6667 struct got_object_qid *pid;
6668 struct got_object_id *blob_id = NULL;
6669 int obj_type;
6670 err = got_object_open_as_commit(&commit,
6671 s->repo, id);
6672 if (err)
6673 break;
6674 pid = STAILQ_FIRST(
6675 got_object_commit_get_parent_ids(commit));
6676 if (pid == NULL) {
6677 got_object_commit_close(commit);
6678 break;
6680 /* Check if path history ends here. */
6681 err = got_object_open_as_commit(&pcommit,
6682 s->repo, &pid->id);
6683 if (err)
6684 break;
6685 err = got_object_id_by_path(&blob_id, s->repo,
6686 pcommit, s->path);
6687 got_object_commit_close(pcommit);
6688 if (err) {
6689 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6690 err = NULL;
6691 got_object_commit_close(commit);
6692 break;
6694 err = got_object_get_type(&obj_type, s->repo,
6695 blob_id);
6696 free(blob_id);
6697 /* Can't blame non-blob type objects. */
6698 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6699 got_object_commit_close(commit);
6700 break;
6702 err = got_object_qid_alloc(&s->blamed_commit,
6703 &pid->id);
6704 got_object_commit_close(commit);
6705 } else {
6706 if (got_object_id_cmp(id,
6707 &s->blamed_commit->id) == 0)
6708 break;
6709 err = got_object_qid_alloc(&s->blamed_commit,
6710 id);
6712 if (err)
6713 break;
6714 s->done = 1;
6715 thread_err = stop_blame(&s->blame);
6716 s->done = 0;
6717 if (thread_err)
6718 break;
6719 STAILQ_INSERT_HEAD(&s->blamed_commits,
6720 s->blamed_commit, entry);
6721 err = run_blame(view);
6722 if (err)
6723 break;
6724 break;
6726 case 'C': {
6727 struct got_object_qid *first;
6729 view->count = 0;
6730 first = STAILQ_FIRST(&s->blamed_commits);
6731 if (!got_object_id_cmp(&first->id, s->commit_id))
6732 break;
6733 s->done = 1;
6734 thread_err = stop_blame(&s->blame);
6735 s->done = 0;
6736 if (thread_err)
6737 break;
6738 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6739 got_object_qid_free(s->blamed_commit);
6740 s->blamed_commit =
6741 STAILQ_FIRST(&s->blamed_commits);
6742 err = run_blame(view);
6743 if (err)
6744 break;
6745 break;
6747 case 'L':
6748 view->count = 0;
6749 s->id_to_log = get_selected_commit_id(s->blame.lines,
6750 s->blame.nlines, s->first_displayed_line, s->selected_line);
6751 if (s->id_to_log)
6752 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6753 break;
6754 case KEY_ENTER:
6755 case '\r': {
6756 struct got_object_id *id = NULL;
6757 struct got_object_qid *pid;
6758 struct got_commit_object *commit = NULL;
6760 view->count = 0;
6761 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6762 s->first_displayed_line, s->selected_line);
6763 if (id == NULL)
6764 break;
6765 err = got_object_open_as_commit(&commit, s->repo, id);
6766 if (err)
6767 break;
6768 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6769 if (*new_view) {
6770 /* traversed from diff view, release diff resources */
6771 err = close_diff_view(*new_view);
6772 if (err)
6773 break;
6774 diff_view = *new_view;
6775 } else {
6776 if (view_is_parent_view(view))
6777 view_get_split(view, &begin_y, &begin_x);
6779 diff_view = view_open(0, 0, begin_y, begin_x,
6780 TOG_VIEW_DIFF);
6781 if (diff_view == NULL) {
6782 got_object_commit_close(commit);
6783 err = got_error_from_errno("view_open");
6784 break;
6787 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6788 id, NULL, NULL, 3, 0, 0, view, s->repo);
6789 got_object_commit_close(commit);
6790 if (err) {
6791 view_close(diff_view);
6792 break;
6794 s->last_diffed_line = s->first_displayed_line - 1 +
6795 s->selected_line;
6796 if (*new_view)
6797 break; /* still open from active diff view */
6798 if (view_is_parent_view(view) &&
6799 view->mode == TOG_VIEW_SPLIT_HRZN) {
6800 err = view_init_hsplit(view, begin_y);
6801 if (err)
6802 break;
6805 view->focussed = 0;
6806 diff_view->focussed = 1;
6807 diff_view->mode = view->mode;
6808 diff_view->nlines = view->lines - begin_y;
6809 if (view_is_parent_view(view)) {
6810 view_transfer_size(diff_view, view);
6811 err = view_close_child(view);
6812 if (err)
6813 break;
6814 err = view_set_child(view, diff_view);
6815 if (err)
6816 break;
6817 view->focus_child = 1;
6818 } else
6819 *new_view = diff_view;
6820 if (err)
6821 break;
6822 break;
6824 case CTRL('d'):
6825 case 'd':
6826 nscroll /= 2;
6827 /* FALL THROUGH */
6828 case KEY_NPAGE:
6829 case CTRL('f'):
6830 case 'f':
6831 case ' ':
6832 if (s->last_displayed_line >= s->blame.nlines &&
6833 s->selected_line >= MIN(s->blame.nlines,
6834 view->nlines - 2)) {
6835 view->count = 0;
6836 break;
6838 if (s->last_displayed_line >= s->blame.nlines &&
6839 s->selected_line < view->nlines - 2) {
6840 s->selected_line +=
6841 MIN(nscroll, s->last_displayed_line -
6842 s->first_displayed_line - s->selected_line + 1);
6844 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6845 s->first_displayed_line += nscroll;
6846 else
6847 s->first_displayed_line =
6848 s->blame.nlines - (view->nlines - 3);
6849 break;
6850 case KEY_RESIZE:
6851 if (s->selected_line > view->nlines - 2) {
6852 s->selected_line = MIN(s->blame.nlines,
6853 view->nlines - 2);
6855 break;
6856 default:
6857 view->count = 0;
6858 break;
6860 return thread_err ? thread_err : err;
6863 static const struct got_error *
6864 reset_blame_view(struct tog_view *view)
6866 const struct got_error *err;
6867 struct tog_blame_view_state *s = &view->state.blame;
6869 view->count = 0;
6870 s->done = 1;
6871 err = stop_blame(&s->blame);
6872 s->done = 0;
6873 if (err)
6874 return err;
6875 return run_blame(view);
6878 static const struct got_error *
6879 cmd_blame(int argc, char *argv[])
6881 const struct got_error *error;
6882 struct got_repository *repo = NULL;
6883 struct got_worktree *worktree = NULL;
6884 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6885 char *link_target = NULL;
6886 struct got_object_id *commit_id = NULL;
6887 struct got_commit_object *commit = NULL;
6888 char *commit_id_str = NULL;
6889 int ch;
6890 struct tog_view *view;
6891 int *pack_fds = NULL;
6893 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6894 switch (ch) {
6895 case 'c':
6896 commit_id_str = optarg;
6897 break;
6898 case 'r':
6899 repo_path = realpath(optarg, NULL);
6900 if (repo_path == NULL)
6901 return got_error_from_errno2("realpath",
6902 optarg);
6903 break;
6904 default:
6905 usage_blame();
6906 /* NOTREACHED */
6910 argc -= optind;
6911 argv += optind;
6913 if (argc != 1)
6914 usage_blame();
6916 error = got_repo_pack_fds_open(&pack_fds);
6917 if (error != NULL)
6918 goto done;
6920 if (repo_path == NULL) {
6921 cwd = getcwd(NULL, 0);
6922 if (cwd == NULL)
6923 return got_error_from_errno("getcwd");
6924 error = got_worktree_open(&worktree, cwd);
6925 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6926 goto done;
6927 if (worktree)
6928 repo_path =
6929 strdup(got_worktree_get_repo_path(worktree));
6930 else
6931 repo_path = strdup(cwd);
6932 if (repo_path == NULL) {
6933 error = got_error_from_errno("strdup");
6934 goto done;
6938 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6939 if (error != NULL)
6940 goto done;
6942 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6943 worktree);
6944 if (error)
6945 goto done;
6947 init_curses();
6949 error = apply_unveil(got_repo_get_path(repo), NULL);
6950 if (error)
6951 goto done;
6953 error = tog_load_refs(repo, 0);
6954 if (error)
6955 goto done;
6957 if (commit_id_str == NULL) {
6958 struct got_reference *head_ref;
6959 error = got_ref_open(&head_ref, repo, worktree ?
6960 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6961 if (error != NULL)
6962 goto done;
6963 error = got_ref_resolve(&commit_id, repo, head_ref);
6964 got_ref_close(head_ref);
6965 } else {
6966 error = got_repo_match_object_id(&commit_id, NULL,
6967 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6969 if (error != NULL)
6970 goto done;
6972 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6973 if (view == NULL) {
6974 error = got_error_from_errno("view_open");
6975 goto done;
6978 error = got_object_open_as_commit(&commit, repo, commit_id);
6979 if (error)
6980 goto done;
6982 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6983 commit, repo);
6984 if (error)
6985 goto done;
6987 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6988 commit_id, repo);
6989 if (error)
6990 goto done;
6991 if (worktree) {
6992 /* Release work tree lock. */
6993 got_worktree_close(worktree);
6994 worktree = NULL;
6996 error = view_loop(view);
6997 done:
6998 free(repo_path);
6999 free(in_repo_path);
7000 free(link_target);
7001 free(cwd);
7002 free(commit_id);
7003 if (commit)
7004 got_object_commit_close(commit);
7005 if (worktree)
7006 got_worktree_close(worktree);
7007 if (repo) {
7008 const struct got_error *close_err = got_repo_close(repo);
7009 if (error == NULL)
7010 error = close_err;
7012 if (pack_fds) {
7013 const struct got_error *pack_err =
7014 got_repo_pack_fds_close(pack_fds);
7015 if (error == NULL)
7016 error = pack_err;
7018 tog_free_refs();
7019 return error;
7022 static const struct got_error *
7023 draw_tree_entries(struct tog_view *view, const char *parent_path)
7025 struct tog_tree_view_state *s = &view->state.tree;
7026 const struct got_error *err = NULL;
7027 struct got_tree_entry *te;
7028 wchar_t *wline;
7029 char *index = NULL;
7030 struct tog_color *tc;
7031 int width, n, nentries, scrollx, i = 1;
7032 int limit = view->nlines;
7034 s->ndisplayed = 0;
7035 if (view_is_hsplit_top(view))
7036 --limit; /* border */
7038 werase(view->window);
7040 if (limit == 0)
7041 return NULL;
7043 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7044 0, 0);
7045 if (err)
7046 return err;
7047 if (view_needs_focus_indication(view))
7048 wstandout(view->window);
7049 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7050 if (tc)
7051 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7052 waddwstr(view->window, wline);
7053 free(wline);
7054 wline = NULL;
7055 while (width++ < view->ncols)
7056 waddch(view->window, ' ');
7057 if (tc)
7058 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7059 if (view_needs_focus_indication(view))
7060 wstandend(view->window);
7061 if (--limit <= 0)
7062 return NULL;
7064 i += s->selected;
7065 if (s->first_displayed_entry) {
7066 i += got_tree_entry_get_index(s->first_displayed_entry);
7067 if (s->tree != s->root)
7068 ++i; /* account for ".." entry */
7070 nentries = got_object_tree_get_nentries(s->tree);
7071 if (asprintf(&index, "[%d/%d] %s",
7072 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7073 return got_error_from_errno("asprintf");
7074 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7075 free(index);
7076 if (err)
7077 return err;
7078 waddwstr(view->window, wline);
7079 free(wline);
7080 wline = NULL;
7081 if (width < view->ncols - 1)
7082 waddch(view->window, '\n');
7083 if (--limit <= 0)
7084 return NULL;
7085 waddch(view->window, '\n');
7086 if (--limit <= 0)
7087 return NULL;
7089 if (s->first_displayed_entry == NULL) {
7090 te = got_object_tree_get_first_entry(s->tree);
7091 if (s->selected == 0) {
7092 if (view->focussed)
7093 wstandout(view->window);
7094 s->selected_entry = NULL;
7096 waddstr(view->window, " ..\n"); /* parent directory */
7097 if (s->selected == 0 && view->focussed)
7098 wstandend(view->window);
7099 s->ndisplayed++;
7100 if (--limit <= 0)
7101 return NULL;
7102 n = 1;
7103 } else {
7104 n = 0;
7105 te = s->first_displayed_entry;
7108 view->maxx = 0;
7109 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7110 char *line = NULL, *id_str = NULL, *link_target = NULL;
7111 const char *modestr = "";
7112 mode_t mode;
7114 te = got_object_tree_get_entry(s->tree, i);
7115 mode = got_tree_entry_get_mode(te);
7117 if (s->show_ids) {
7118 err = got_object_id_str(&id_str,
7119 got_tree_entry_get_id(te));
7120 if (err)
7121 return got_error_from_errno(
7122 "got_object_id_str");
7124 if (got_object_tree_entry_is_submodule(te))
7125 modestr = "$";
7126 else if (S_ISLNK(mode)) {
7127 int i;
7129 err = got_tree_entry_get_symlink_target(&link_target,
7130 te, s->repo);
7131 if (err) {
7132 free(id_str);
7133 return err;
7135 for (i = 0; i < strlen(link_target); i++) {
7136 if (!isprint((unsigned char)link_target[i]))
7137 link_target[i] = '?';
7139 modestr = "@";
7141 else if (S_ISDIR(mode))
7142 modestr = "/";
7143 else if (mode & S_IXUSR)
7144 modestr = "*";
7145 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7146 got_tree_entry_get_name(te), modestr,
7147 link_target ? " -> ": "",
7148 link_target ? link_target : "") == -1) {
7149 free(id_str);
7150 free(link_target);
7151 return got_error_from_errno("asprintf");
7153 free(id_str);
7154 free(link_target);
7156 /* use full line width to determine view->maxx */
7157 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7158 if (err) {
7159 free(line);
7160 break;
7162 view->maxx = MAX(view->maxx, width);
7163 free(wline);
7164 wline = NULL;
7166 err = format_line(&wline, &width, &scrollx, line, view->x,
7167 view->ncols, 0, 0);
7168 if (err) {
7169 free(line);
7170 break;
7172 if (n == s->selected) {
7173 if (view->focussed)
7174 wstandout(view->window);
7175 s->selected_entry = te;
7177 tc = match_color(&s->colors, line);
7178 if (tc)
7179 wattr_on(view->window,
7180 COLOR_PAIR(tc->colorpair), NULL);
7181 waddwstr(view->window, &wline[scrollx]);
7182 if (tc)
7183 wattr_off(view->window,
7184 COLOR_PAIR(tc->colorpair), NULL);
7185 if (width < view->ncols)
7186 waddch(view->window, '\n');
7187 if (n == s->selected && view->focussed)
7188 wstandend(view->window);
7189 free(line);
7190 free(wline);
7191 wline = NULL;
7192 n++;
7193 s->ndisplayed++;
7194 s->last_displayed_entry = te;
7195 if (--limit <= 0)
7196 break;
7199 return err;
7202 static void
7203 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7205 struct got_tree_entry *te;
7206 int isroot = s->tree == s->root;
7207 int i = 0;
7209 if (s->first_displayed_entry == NULL)
7210 return;
7212 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7213 while (i++ < maxscroll) {
7214 if (te == NULL) {
7215 if (!isroot)
7216 s->first_displayed_entry = NULL;
7217 break;
7219 s->first_displayed_entry = te;
7220 te = got_tree_entry_get_prev(s->tree, te);
7224 static const struct got_error *
7225 tree_scroll_down(struct tog_view *view, int maxscroll)
7227 struct tog_tree_view_state *s = &view->state.tree;
7228 struct got_tree_entry *next, *last;
7229 int n = 0;
7231 if (s->first_displayed_entry)
7232 next = got_tree_entry_get_next(s->tree,
7233 s->first_displayed_entry);
7234 else
7235 next = got_object_tree_get_first_entry(s->tree);
7237 last = s->last_displayed_entry;
7238 while (next && n++ < maxscroll) {
7239 if (last) {
7240 s->last_displayed_entry = last;
7241 last = got_tree_entry_get_next(s->tree, last);
7243 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7244 s->first_displayed_entry = next;
7245 next = got_tree_entry_get_next(s->tree, next);
7249 return NULL;
7252 static const struct got_error *
7253 tree_entry_path(char **path, struct tog_parent_trees *parents,
7254 struct got_tree_entry *te)
7256 const struct got_error *err = NULL;
7257 struct tog_parent_tree *pt;
7258 size_t len = 2; /* for leading slash and NUL */
7260 TAILQ_FOREACH(pt, parents, entry)
7261 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7262 + 1 /* slash */;
7263 if (te)
7264 len += strlen(got_tree_entry_get_name(te));
7266 *path = calloc(1, len);
7267 if (path == NULL)
7268 return got_error_from_errno("calloc");
7270 (*path)[0] = '/';
7271 pt = TAILQ_LAST(parents, tog_parent_trees);
7272 while (pt) {
7273 const char *name = got_tree_entry_get_name(pt->selected_entry);
7274 if (strlcat(*path, name, len) >= len) {
7275 err = got_error(GOT_ERR_NO_SPACE);
7276 goto done;
7278 if (strlcat(*path, "/", len) >= len) {
7279 err = got_error(GOT_ERR_NO_SPACE);
7280 goto done;
7282 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7284 if (te) {
7285 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7286 err = got_error(GOT_ERR_NO_SPACE);
7287 goto done;
7290 done:
7291 if (err) {
7292 free(*path);
7293 *path = NULL;
7295 return err;
7298 static const struct got_error *
7299 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7300 struct got_tree_entry *te, struct tog_parent_trees *parents,
7301 struct got_object_id *commit_id, struct got_repository *repo)
7303 const struct got_error *err = NULL;
7304 char *path;
7305 struct tog_view *blame_view;
7307 *new_view = NULL;
7309 err = tree_entry_path(&path, parents, te);
7310 if (err)
7311 return err;
7313 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7314 if (blame_view == NULL) {
7315 err = got_error_from_errno("view_open");
7316 goto done;
7319 err = open_blame_view(blame_view, path, commit_id, repo);
7320 if (err) {
7321 if (err->code == GOT_ERR_CANCELLED)
7322 err = NULL;
7323 view_close(blame_view);
7324 } else
7325 *new_view = blame_view;
7326 done:
7327 free(path);
7328 return err;
7331 static const struct got_error *
7332 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7333 struct tog_tree_view_state *s)
7335 struct tog_view *log_view;
7336 const struct got_error *err = NULL;
7337 char *path;
7339 *new_view = NULL;
7341 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7342 if (log_view == NULL)
7343 return got_error_from_errno("view_open");
7345 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7346 if (err)
7347 return err;
7349 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7350 path, 0);
7351 if (err)
7352 view_close(log_view);
7353 else
7354 *new_view = log_view;
7355 free(path);
7356 return err;
7359 static const struct got_error *
7360 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7361 const char *head_ref_name, struct got_repository *repo)
7363 const struct got_error *err = NULL;
7364 char *commit_id_str = NULL;
7365 struct tog_tree_view_state *s = &view->state.tree;
7366 struct got_commit_object *commit = NULL;
7368 TAILQ_INIT(&s->parents);
7369 STAILQ_INIT(&s->colors);
7371 s->commit_id = got_object_id_dup(commit_id);
7372 if (s->commit_id == NULL)
7373 return got_error_from_errno("got_object_id_dup");
7375 err = got_object_open_as_commit(&commit, repo, commit_id);
7376 if (err)
7377 goto done;
7380 * The root is opened here and will be closed when the view is closed.
7381 * Any visited subtrees and their path-wise parents are opened and
7382 * closed on demand.
7384 err = got_object_open_as_tree(&s->root, repo,
7385 got_object_commit_get_tree_id(commit));
7386 if (err)
7387 goto done;
7388 s->tree = s->root;
7390 err = got_object_id_str(&commit_id_str, commit_id);
7391 if (err != NULL)
7392 goto done;
7394 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7395 err = got_error_from_errno("asprintf");
7396 goto done;
7399 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7400 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7401 if (head_ref_name) {
7402 s->head_ref_name = strdup(head_ref_name);
7403 if (s->head_ref_name == NULL) {
7404 err = got_error_from_errno("strdup");
7405 goto done;
7408 s->repo = repo;
7410 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7411 err = add_color(&s->colors, "\\$$",
7412 TOG_COLOR_TREE_SUBMODULE,
7413 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7414 if (err)
7415 goto done;
7416 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7417 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7418 if (err)
7419 goto done;
7420 err = add_color(&s->colors, "/$",
7421 TOG_COLOR_TREE_DIRECTORY,
7422 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7423 if (err)
7424 goto done;
7426 err = add_color(&s->colors, "\\*$",
7427 TOG_COLOR_TREE_EXECUTABLE,
7428 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7429 if (err)
7430 goto done;
7432 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7433 get_color_value("TOG_COLOR_COMMIT"));
7434 if (err)
7435 goto done;
7438 view->show = show_tree_view;
7439 view->input = input_tree_view;
7440 view->close = close_tree_view;
7441 view->search_start = search_start_tree_view;
7442 view->search_next = search_next_tree_view;
7443 done:
7444 free(commit_id_str);
7445 if (commit)
7446 got_object_commit_close(commit);
7447 if (err)
7448 close_tree_view(view);
7449 return err;
7452 static const struct got_error *
7453 close_tree_view(struct tog_view *view)
7455 struct tog_tree_view_state *s = &view->state.tree;
7457 free_colors(&s->colors);
7458 free(s->tree_label);
7459 s->tree_label = NULL;
7460 free(s->commit_id);
7461 s->commit_id = NULL;
7462 free(s->head_ref_name);
7463 s->head_ref_name = NULL;
7464 while (!TAILQ_EMPTY(&s->parents)) {
7465 struct tog_parent_tree *parent;
7466 parent = TAILQ_FIRST(&s->parents);
7467 TAILQ_REMOVE(&s->parents, parent, entry);
7468 if (parent->tree != s->root)
7469 got_object_tree_close(parent->tree);
7470 free(parent);
7473 if (s->tree != NULL && s->tree != s->root)
7474 got_object_tree_close(s->tree);
7475 if (s->root)
7476 got_object_tree_close(s->root);
7477 return NULL;
7480 static const struct got_error *
7481 search_start_tree_view(struct tog_view *view)
7483 struct tog_tree_view_state *s = &view->state.tree;
7485 s->matched_entry = NULL;
7486 return NULL;
7489 static int
7490 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7492 regmatch_t regmatch;
7494 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7495 0) == 0;
7498 static const struct got_error *
7499 search_next_tree_view(struct tog_view *view)
7501 struct tog_tree_view_state *s = &view->state.tree;
7502 struct got_tree_entry *te = NULL;
7504 if (!view->searching) {
7505 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7506 return NULL;
7509 if (s->matched_entry) {
7510 if (view->searching == TOG_SEARCH_FORWARD) {
7511 if (s->selected_entry)
7512 te = got_tree_entry_get_next(s->tree,
7513 s->selected_entry);
7514 else
7515 te = got_object_tree_get_first_entry(s->tree);
7516 } else {
7517 if (s->selected_entry == NULL)
7518 te = got_object_tree_get_last_entry(s->tree);
7519 else
7520 te = got_tree_entry_get_prev(s->tree,
7521 s->selected_entry);
7523 } else {
7524 if (s->selected_entry)
7525 te = s->selected_entry;
7526 else if (view->searching == TOG_SEARCH_FORWARD)
7527 te = got_object_tree_get_first_entry(s->tree);
7528 else
7529 te = got_object_tree_get_last_entry(s->tree);
7532 while (1) {
7533 if (te == NULL) {
7534 if (s->matched_entry == NULL) {
7535 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7536 return NULL;
7538 if (view->searching == TOG_SEARCH_FORWARD)
7539 te = got_object_tree_get_first_entry(s->tree);
7540 else
7541 te = got_object_tree_get_last_entry(s->tree);
7544 if (match_tree_entry(te, &view->regex)) {
7545 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7546 s->matched_entry = te;
7547 break;
7550 if (view->searching == TOG_SEARCH_FORWARD)
7551 te = got_tree_entry_get_next(s->tree, te);
7552 else
7553 te = got_tree_entry_get_prev(s->tree, te);
7556 if (s->matched_entry) {
7557 s->first_displayed_entry = s->matched_entry;
7558 s->selected = 0;
7561 return NULL;
7564 static const struct got_error *
7565 show_tree_view(struct tog_view *view)
7567 const struct got_error *err = NULL;
7568 struct tog_tree_view_state *s = &view->state.tree;
7569 char *parent_path;
7571 err = tree_entry_path(&parent_path, &s->parents, NULL);
7572 if (err)
7573 return err;
7575 err = draw_tree_entries(view, parent_path);
7576 free(parent_path);
7578 view_border(view);
7579 return err;
7582 static const struct got_error *
7583 tree_goto_line(struct tog_view *view, int nlines)
7585 const struct got_error *err = NULL;
7586 struct tog_tree_view_state *s = &view->state.tree;
7587 struct got_tree_entry **fte, **lte, **ste;
7588 int g, last, first = 1, i = 1;
7589 int root = s->tree == s->root;
7590 int off = root ? 1 : 2;
7592 g = view->gline;
7593 view->gline = 0;
7595 if (g == 0)
7596 g = 1;
7597 else if (g > got_object_tree_get_nentries(s->tree))
7598 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7600 fte = &s->first_displayed_entry;
7601 lte = &s->last_displayed_entry;
7602 ste = &s->selected_entry;
7604 if (*fte != NULL) {
7605 first = got_tree_entry_get_index(*fte);
7606 first += off; /* account for ".." */
7608 last = got_tree_entry_get_index(*lte);
7609 last += off;
7611 if (g >= first && g <= last && g - first < nlines) {
7612 s->selected = g - first;
7613 return NULL; /* gline is on the current page */
7616 if (*ste != NULL) {
7617 i = got_tree_entry_get_index(*ste);
7618 i += off;
7621 if (i < g) {
7622 err = tree_scroll_down(view, g - i);
7623 if (err)
7624 return err;
7625 if (got_tree_entry_get_index(*lte) >=
7626 got_object_tree_get_nentries(s->tree) - 1 &&
7627 first + s->selected < g &&
7628 s->selected < s->ndisplayed - 1) {
7629 first = got_tree_entry_get_index(*fte);
7630 first += off;
7631 s->selected = g - first;
7633 } else if (i > g)
7634 tree_scroll_up(s, i - g);
7636 if (g < nlines &&
7637 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7638 s->selected = g - 1;
7640 return NULL;
7643 static const struct got_error *
7644 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7646 const struct got_error *err = NULL;
7647 struct tog_tree_view_state *s = &view->state.tree;
7648 struct got_tree_entry *te;
7649 int n, nscroll = view->nlines - 3;
7651 if (view->gline)
7652 return tree_goto_line(view, nscroll);
7654 switch (ch) {
7655 case '0':
7656 case '$':
7657 case KEY_RIGHT:
7658 case 'l':
7659 case KEY_LEFT:
7660 case 'h':
7661 horizontal_scroll_input(view, ch);
7662 break;
7663 case 'i':
7664 s->show_ids = !s->show_ids;
7665 view->count = 0;
7666 break;
7667 case 'L':
7668 view->count = 0;
7669 if (!s->selected_entry)
7670 break;
7671 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7672 break;
7673 case 'R':
7674 view->count = 0;
7675 err = view_request_new(new_view, view, TOG_VIEW_REF);
7676 break;
7677 case 'g':
7678 case '=':
7679 case KEY_HOME:
7680 s->selected = 0;
7681 view->count = 0;
7682 if (s->tree == s->root)
7683 s->first_displayed_entry =
7684 got_object_tree_get_first_entry(s->tree);
7685 else
7686 s->first_displayed_entry = NULL;
7687 break;
7688 case 'G':
7689 case '*':
7690 case KEY_END: {
7691 int eos = view->nlines - 3;
7693 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7694 --eos; /* border */
7695 s->selected = 0;
7696 view->count = 0;
7697 te = got_object_tree_get_last_entry(s->tree);
7698 for (n = 0; n < eos; n++) {
7699 if (te == NULL) {
7700 if (s->tree != s->root) {
7701 s->first_displayed_entry = NULL;
7702 n++;
7704 break;
7706 s->first_displayed_entry = te;
7707 te = got_tree_entry_get_prev(s->tree, te);
7709 if (n > 0)
7710 s->selected = n - 1;
7711 break;
7713 case 'k':
7714 case KEY_UP:
7715 case CTRL('p'):
7716 if (s->selected > 0) {
7717 s->selected--;
7718 break;
7720 tree_scroll_up(s, 1);
7721 if (s->selected_entry == NULL ||
7722 (s->tree == s->root && s->selected_entry ==
7723 got_object_tree_get_first_entry(s->tree)))
7724 view->count = 0;
7725 break;
7726 case CTRL('u'):
7727 case 'u':
7728 nscroll /= 2;
7729 /* FALL THROUGH */
7730 case KEY_PPAGE:
7731 case CTRL('b'):
7732 case 'b':
7733 if (s->tree == s->root) {
7734 if (got_object_tree_get_first_entry(s->tree) ==
7735 s->first_displayed_entry)
7736 s->selected -= MIN(s->selected, nscroll);
7737 } else {
7738 if (s->first_displayed_entry == NULL)
7739 s->selected -= MIN(s->selected, nscroll);
7741 tree_scroll_up(s, MAX(0, nscroll));
7742 if (s->selected_entry == NULL ||
7743 (s->tree == s->root && s->selected_entry ==
7744 got_object_tree_get_first_entry(s->tree)))
7745 view->count = 0;
7746 break;
7747 case 'j':
7748 case KEY_DOWN:
7749 case CTRL('n'):
7750 if (s->selected < s->ndisplayed - 1) {
7751 s->selected++;
7752 break;
7754 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7755 == NULL) {
7756 /* can't scroll any further */
7757 view->count = 0;
7758 break;
7760 tree_scroll_down(view, 1);
7761 break;
7762 case CTRL('d'):
7763 case 'd':
7764 nscroll /= 2;
7765 /* FALL THROUGH */
7766 case KEY_NPAGE:
7767 case CTRL('f'):
7768 case 'f':
7769 case ' ':
7770 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7771 == NULL) {
7772 /* can't scroll any further; move cursor down */
7773 if (s->selected < s->ndisplayed - 1)
7774 s->selected += MIN(nscroll,
7775 s->ndisplayed - s->selected - 1);
7776 else
7777 view->count = 0;
7778 break;
7780 tree_scroll_down(view, nscroll);
7781 break;
7782 case KEY_ENTER:
7783 case '\r':
7784 case KEY_BACKSPACE:
7785 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7786 struct tog_parent_tree *parent;
7787 /* user selected '..' */
7788 if (s->tree == s->root) {
7789 view->count = 0;
7790 break;
7792 parent = TAILQ_FIRST(&s->parents);
7793 TAILQ_REMOVE(&s->parents, parent,
7794 entry);
7795 got_object_tree_close(s->tree);
7796 s->tree = parent->tree;
7797 s->first_displayed_entry =
7798 parent->first_displayed_entry;
7799 s->selected_entry =
7800 parent->selected_entry;
7801 s->selected = parent->selected;
7802 if (s->selected > view->nlines - 3) {
7803 err = offset_selection_down(view);
7804 if (err)
7805 break;
7807 free(parent);
7808 } else if (S_ISDIR(got_tree_entry_get_mode(
7809 s->selected_entry))) {
7810 struct got_tree_object *subtree;
7811 view->count = 0;
7812 err = got_object_open_as_tree(&subtree, s->repo,
7813 got_tree_entry_get_id(s->selected_entry));
7814 if (err)
7815 break;
7816 err = tree_view_visit_subtree(s, subtree);
7817 if (err) {
7818 got_object_tree_close(subtree);
7819 break;
7821 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7822 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7823 break;
7824 case KEY_RESIZE:
7825 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7826 s->selected = view->nlines - 4;
7827 view->count = 0;
7828 break;
7829 default:
7830 view->count = 0;
7831 break;
7834 return err;
7837 __dead static void
7838 usage_tree(void)
7840 endwin();
7841 fprintf(stderr,
7842 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7843 getprogname());
7844 exit(1);
7847 static const struct got_error *
7848 cmd_tree(int argc, char *argv[])
7850 const struct got_error *error;
7851 struct got_repository *repo = NULL;
7852 struct got_worktree *worktree = NULL;
7853 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7854 struct got_object_id *commit_id = NULL;
7855 struct got_commit_object *commit = NULL;
7856 const char *commit_id_arg = NULL;
7857 char *label = NULL;
7858 struct got_reference *ref = NULL;
7859 const char *head_ref_name = NULL;
7860 int ch;
7861 struct tog_view *view;
7862 int *pack_fds = NULL;
7864 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7865 switch (ch) {
7866 case 'c':
7867 commit_id_arg = optarg;
7868 break;
7869 case 'r':
7870 repo_path = realpath(optarg, NULL);
7871 if (repo_path == NULL)
7872 return got_error_from_errno2("realpath",
7873 optarg);
7874 break;
7875 default:
7876 usage_tree();
7877 /* NOTREACHED */
7881 argc -= optind;
7882 argv += optind;
7884 if (argc > 1)
7885 usage_tree();
7887 error = got_repo_pack_fds_open(&pack_fds);
7888 if (error != NULL)
7889 goto done;
7891 if (repo_path == NULL) {
7892 cwd = getcwd(NULL, 0);
7893 if (cwd == NULL)
7894 return got_error_from_errno("getcwd");
7895 error = got_worktree_open(&worktree, cwd);
7896 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7897 goto done;
7898 if (worktree)
7899 repo_path =
7900 strdup(got_worktree_get_repo_path(worktree));
7901 else
7902 repo_path = strdup(cwd);
7903 if (repo_path == NULL) {
7904 error = got_error_from_errno("strdup");
7905 goto done;
7909 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7910 if (error != NULL)
7911 goto done;
7913 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7914 repo, worktree);
7915 if (error)
7916 goto done;
7918 init_curses();
7920 error = apply_unveil(got_repo_get_path(repo), NULL);
7921 if (error)
7922 goto done;
7924 error = tog_load_refs(repo, 0);
7925 if (error)
7926 goto done;
7928 if (commit_id_arg == NULL) {
7929 error = got_repo_match_object_id(&commit_id, &label,
7930 worktree ? got_worktree_get_head_ref_name(worktree) :
7931 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7932 if (error)
7933 goto done;
7934 head_ref_name = label;
7935 } else {
7936 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7937 if (error == NULL)
7938 head_ref_name = got_ref_get_name(ref);
7939 else if (error->code != GOT_ERR_NOT_REF)
7940 goto done;
7941 error = got_repo_match_object_id(&commit_id, NULL,
7942 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7943 if (error)
7944 goto done;
7947 error = got_object_open_as_commit(&commit, repo, commit_id);
7948 if (error)
7949 goto done;
7951 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7952 if (view == NULL) {
7953 error = got_error_from_errno("view_open");
7954 goto done;
7956 error = open_tree_view(view, commit_id, head_ref_name, repo);
7957 if (error)
7958 goto done;
7959 if (!got_path_is_root_dir(in_repo_path)) {
7960 error = tree_view_walk_path(&view->state.tree, commit,
7961 in_repo_path);
7962 if (error)
7963 goto done;
7966 if (worktree) {
7967 /* Release work tree lock. */
7968 got_worktree_close(worktree);
7969 worktree = NULL;
7971 error = view_loop(view);
7972 done:
7973 free(repo_path);
7974 free(cwd);
7975 free(commit_id);
7976 free(label);
7977 if (ref)
7978 got_ref_close(ref);
7979 if (repo) {
7980 const struct got_error *close_err = got_repo_close(repo);
7981 if (error == NULL)
7982 error = close_err;
7984 if (pack_fds) {
7985 const struct got_error *pack_err =
7986 got_repo_pack_fds_close(pack_fds);
7987 if (error == NULL)
7988 error = pack_err;
7990 tog_free_refs();
7991 return error;
7994 static const struct got_error *
7995 ref_view_load_refs(struct tog_ref_view_state *s)
7997 struct got_reflist_entry *sre;
7998 struct tog_reflist_entry *re;
8000 s->nrefs = 0;
8001 TAILQ_FOREACH(sre, &tog_refs, entry) {
8002 if (strncmp(got_ref_get_name(sre->ref),
8003 "refs/got/", 9) == 0 &&
8004 strncmp(got_ref_get_name(sre->ref),
8005 "refs/got/backup/", 16) != 0)
8006 continue;
8008 re = malloc(sizeof(*re));
8009 if (re == NULL)
8010 return got_error_from_errno("malloc");
8012 re->ref = got_ref_dup(sre->ref);
8013 if (re->ref == NULL)
8014 return got_error_from_errno("got_ref_dup");
8015 re->idx = s->nrefs++;
8016 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8019 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8020 return NULL;
8023 static void
8024 ref_view_free_refs(struct tog_ref_view_state *s)
8026 struct tog_reflist_entry *re;
8028 while (!TAILQ_EMPTY(&s->refs)) {
8029 re = TAILQ_FIRST(&s->refs);
8030 TAILQ_REMOVE(&s->refs, re, entry);
8031 got_ref_close(re->ref);
8032 free(re);
8036 static const struct got_error *
8037 open_ref_view(struct tog_view *view, struct got_repository *repo)
8039 const struct got_error *err = NULL;
8040 struct tog_ref_view_state *s = &view->state.ref;
8042 s->selected_entry = 0;
8043 s->repo = repo;
8045 TAILQ_INIT(&s->refs);
8046 STAILQ_INIT(&s->colors);
8048 err = ref_view_load_refs(s);
8049 if (err)
8050 return err;
8052 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8053 err = add_color(&s->colors, "^refs/heads/",
8054 TOG_COLOR_REFS_HEADS,
8055 get_color_value("TOG_COLOR_REFS_HEADS"));
8056 if (err)
8057 goto done;
8059 err = add_color(&s->colors, "^refs/tags/",
8060 TOG_COLOR_REFS_TAGS,
8061 get_color_value("TOG_COLOR_REFS_TAGS"));
8062 if (err)
8063 goto done;
8065 err = add_color(&s->colors, "^refs/remotes/",
8066 TOG_COLOR_REFS_REMOTES,
8067 get_color_value("TOG_COLOR_REFS_REMOTES"));
8068 if (err)
8069 goto done;
8071 err = add_color(&s->colors, "^refs/got/backup/",
8072 TOG_COLOR_REFS_BACKUP,
8073 get_color_value("TOG_COLOR_REFS_BACKUP"));
8074 if (err)
8075 goto done;
8078 view->show = show_ref_view;
8079 view->input = input_ref_view;
8080 view->close = close_ref_view;
8081 view->search_start = search_start_ref_view;
8082 view->search_next = search_next_ref_view;
8083 done:
8084 if (err)
8085 free_colors(&s->colors);
8086 return err;
8089 static const struct got_error *
8090 close_ref_view(struct tog_view *view)
8092 struct tog_ref_view_state *s = &view->state.ref;
8094 ref_view_free_refs(s);
8095 free_colors(&s->colors);
8097 return NULL;
8100 static const struct got_error *
8101 resolve_reflist_entry(struct got_object_id **commit_id,
8102 struct tog_reflist_entry *re, struct got_repository *repo)
8104 const struct got_error *err = NULL;
8105 struct got_object_id *obj_id;
8106 struct got_tag_object *tag = NULL;
8107 int obj_type;
8109 *commit_id = NULL;
8111 err = got_ref_resolve(&obj_id, repo, re->ref);
8112 if (err)
8113 return err;
8115 err = got_object_get_type(&obj_type, repo, obj_id);
8116 if (err)
8117 goto done;
8119 switch (obj_type) {
8120 case GOT_OBJ_TYPE_COMMIT:
8121 *commit_id = obj_id;
8122 break;
8123 case GOT_OBJ_TYPE_TAG:
8124 err = got_object_open_as_tag(&tag, repo, obj_id);
8125 if (err)
8126 goto done;
8127 free(obj_id);
8128 err = got_object_get_type(&obj_type, repo,
8129 got_object_tag_get_object_id(tag));
8130 if (err)
8131 goto done;
8132 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8133 err = got_error(GOT_ERR_OBJ_TYPE);
8134 goto done;
8136 *commit_id = got_object_id_dup(
8137 got_object_tag_get_object_id(tag));
8138 if (*commit_id == NULL) {
8139 err = got_error_from_errno("got_object_id_dup");
8140 goto done;
8142 break;
8143 default:
8144 err = got_error(GOT_ERR_OBJ_TYPE);
8145 break;
8148 done:
8149 if (tag)
8150 got_object_tag_close(tag);
8151 if (err) {
8152 free(*commit_id);
8153 *commit_id = NULL;
8155 return err;
8158 static const struct got_error *
8159 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8160 struct tog_reflist_entry *re, struct got_repository *repo)
8162 struct tog_view *log_view;
8163 const struct got_error *err = NULL;
8164 struct got_object_id *commit_id = NULL;
8166 *new_view = NULL;
8168 err = resolve_reflist_entry(&commit_id, re, repo);
8169 if (err) {
8170 if (err->code != GOT_ERR_OBJ_TYPE)
8171 return err;
8172 else
8173 return NULL;
8176 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8177 if (log_view == NULL) {
8178 err = got_error_from_errno("view_open");
8179 goto done;
8182 err = open_log_view(log_view, commit_id, repo,
8183 got_ref_get_name(re->ref), "", 0);
8184 done:
8185 if (err)
8186 view_close(log_view);
8187 else
8188 *new_view = log_view;
8189 free(commit_id);
8190 return err;
8193 static void
8194 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8196 struct tog_reflist_entry *re;
8197 int i = 0;
8199 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8200 return;
8202 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8203 while (i++ < maxscroll) {
8204 if (re == NULL)
8205 break;
8206 s->first_displayed_entry = re;
8207 re = TAILQ_PREV(re, tog_reflist_head, entry);
8211 static const struct got_error *
8212 ref_scroll_down(struct tog_view *view, int maxscroll)
8214 struct tog_ref_view_state *s = &view->state.ref;
8215 struct tog_reflist_entry *next, *last;
8216 int n = 0;
8218 if (s->first_displayed_entry)
8219 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8220 else
8221 next = TAILQ_FIRST(&s->refs);
8223 last = s->last_displayed_entry;
8224 while (next && n++ < maxscroll) {
8225 if (last) {
8226 s->last_displayed_entry = last;
8227 last = TAILQ_NEXT(last, entry);
8229 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8230 s->first_displayed_entry = next;
8231 next = TAILQ_NEXT(next, entry);
8235 return NULL;
8238 static const struct got_error *
8239 search_start_ref_view(struct tog_view *view)
8241 struct tog_ref_view_state *s = &view->state.ref;
8243 s->matched_entry = NULL;
8244 return NULL;
8247 static int
8248 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8250 regmatch_t regmatch;
8252 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8253 0) == 0;
8256 static const struct got_error *
8257 search_next_ref_view(struct tog_view *view)
8259 struct tog_ref_view_state *s = &view->state.ref;
8260 struct tog_reflist_entry *re = NULL;
8262 if (!view->searching) {
8263 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8264 return NULL;
8267 if (s->matched_entry) {
8268 if (view->searching == TOG_SEARCH_FORWARD) {
8269 if (s->selected_entry)
8270 re = TAILQ_NEXT(s->selected_entry, entry);
8271 else
8272 re = TAILQ_PREV(s->selected_entry,
8273 tog_reflist_head, entry);
8274 } else {
8275 if (s->selected_entry == NULL)
8276 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8277 else
8278 re = TAILQ_PREV(s->selected_entry,
8279 tog_reflist_head, entry);
8281 } else {
8282 if (s->selected_entry)
8283 re = s->selected_entry;
8284 else if (view->searching == TOG_SEARCH_FORWARD)
8285 re = TAILQ_FIRST(&s->refs);
8286 else
8287 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8290 while (1) {
8291 if (re == NULL) {
8292 if (s->matched_entry == NULL) {
8293 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8294 return NULL;
8296 if (view->searching == TOG_SEARCH_FORWARD)
8297 re = TAILQ_FIRST(&s->refs);
8298 else
8299 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8302 if (match_reflist_entry(re, &view->regex)) {
8303 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8304 s->matched_entry = re;
8305 break;
8308 if (view->searching == TOG_SEARCH_FORWARD)
8309 re = TAILQ_NEXT(re, entry);
8310 else
8311 re = TAILQ_PREV(re, tog_reflist_head, entry);
8314 if (s->matched_entry) {
8315 s->first_displayed_entry = s->matched_entry;
8316 s->selected = 0;
8319 return NULL;
8322 static const struct got_error *
8323 show_ref_view(struct tog_view *view)
8325 const struct got_error *err = NULL;
8326 struct tog_ref_view_state *s = &view->state.ref;
8327 struct tog_reflist_entry *re;
8328 char *line = NULL;
8329 wchar_t *wline;
8330 struct tog_color *tc;
8331 int width, n, scrollx;
8332 int limit = view->nlines;
8334 werase(view->window);
8336 s->ndisplayed = 0;
8337 if (view_is_hsplit_top(view))
8338 --limit; /* border */
8340 if (limit == 0)
8341 return NULL;
8343 re = s->first_displayed_entry;
8345 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8346 s->nrefs) == -1)
8347 return got_error_from_errno("asprintf");
8349 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8350 if (err) {
8351 free(line);
8352 return err;
8354 if (view_needs_focus_indication(view))
8355 wstandout(view->window);
8356 waddwstr(view->window, wline);
8357 while (width++ < view->ncols)
8358 waddch(view->window, ' ');
8359 if (view_needs_focus_indication(view))
8360 wstandend(view->window);
8361 free(wline);
8362 wline = NULL;
8363 free(line);
8364 line = NULL;
8365 if (--limit <= 0)
8366 return NULL;
8368 n = 0;
8369 view->maxx = 0;
8370 while (re && limit > 0) {
8371 char *line = NULL;
8372 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8374 if (s->show_date) {
8375 struct got_commit_object *ci;
8376 struct got_tag_object *tag;
8377 struct got_object_id *id;
8378 struct tm tm;
8379 time_t t;
8381 err = got_ref_resolve(&id, s->repo, re->ref);
8382 if (err)
8383 return err;
8384 err = got_object_open_as_tag(&tag, s->repo, id);
8385 if (err) {
8386 if (err->code != GOT_ERR_OBJ_TYPE) {
8387 free(id);
8388 return err;
8390 err = got_object_open_as_commit(&ci, s->repo,
8391 id);
8392 if (err) {
8393 free(id);
8394 return err;
8396 t = got_object_commit_get_committer_time(ci);
8397 got_object_commit_close(ci);
8398 } else {
8399 t = got_object_tag_get_tagger_time(tag);
8400 got_object_tag_close(tag);
8402 free(id);
8403 if (gmtime_r(&t, &tm) == NULL)
8404 return got_error_from_errno("gmtime_r");
8405 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8406 return got_error(GOT_ERR_NO_SPACE);
8408 if (got_ref_is_symbolic(re->ref)) {
8409 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8410 ymd : "", got_ref_get_name(re->ref),
8411 got_ref_get_symref_target(re->ref)) == -1)
8412 return got_error_from_errno("asprintf");
8413 } else if (s->show_ids) {
8414 struct got_object_id *id;
8415 char *id_str;
8416 err = got_ref_resolve(&id, s->repo, re->ref);
8417 if (err)
8418 return err;
8419 err = got_object_id_str(&id_str, id);
8420 if (err) {
8421 free(id);
8422 return err;
8424 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8425 got_ref_get_name(re->ref), id_str) == -1) {
8426 err = got_error_from_errno("asprintf");
8427 free(id);
8428 free(id_str);
8429 return err;
8431 free(id);
8432 free(id_str);
8433 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8434 got_ref_get_name(re->ref)) == -1)
8435 return got_error_from_errno("asprintf");
8437 /* use full line width to determine view->maxx */
8438 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8439 if (err) {
8440 free(line);
8441 return err;
8443 view->maxx = MAX(view->maxx, width);
8444 free(wline);
8445 wline = NULL;
8447 err = format_line(&wline, &width, &scrollx, line, view->x,
8448 view->ncols, 0, 0);
8449 if (err) {
8450 free(line);
8451 return err;
8453 if (n == s->selected) {
8454 if (view->focussed)
8455 wstandout(view->window);
8456 s->selected_entry = re;
8458 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8459 if (tc)
8460 wattr_on(view->window,
8461 COLOR_PAIR(tc->colorpair), NULL);
8462 waddwstr(view->window, &wline[scrollx]);
8463 if (tc)
8464 wattr_off(view->window,
8465 COLOR_PAIR(tc->colorpair), NULL);
8466 if (width < view->ncols)
8467 waddch(view->window, '\n');
8468 if (n == s->selected && view->focussed)
8469 wstandend(view->window);
8470 free(line);
8471 free(wline);
8472 wline = NULL;
8473 n++;
8474 s->ndisplayed++;
8475 s->last_displayed_entry = re;
8477 limit--;
8478 re = TAILQ_NEXT(re, entry);
8481 view_border(view);
8482 return err;
8485 static const struct got_error *
8486 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8487 struct tog_reflist_entry *re, struct got_repository *repo)
8489 const struct got_error *err = NULL;
8490 struct got_object_id *commit_id = NULL;
8491 struct tog_view *tree_view;
8493 *new_view = NULL;
8495 err = resolve_reflist_entry(&commit_id, re, repo);
8496 if (err) {
8497 if (err->code != GOT_ERR_OBJ_TYPE)
8498 return err;
8499 else
8500 return NULL;
8504 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8505 if (tree_view == NULL) {
8506 err = got_error_from_errno("view_open");
8507 goto done;
8510 err = open_tree_view(tree_view, commit_id,
8511 got_ref_get_name(re->ref), repo);
8512 if (err)
8513 goto done;
8515 *new_view = tree_view;
8516 done:
8517 free(commit_id);
8518 return err;
8521 static const struct got_error *
8522 ref_goto_line(struct tog_view *view, int nlines)
8524 const struct got_error *err = NULL;
8525 struct tog_ref_view_state *s = &view->state.ref;
8526 int g, idx = s->selected_entry->idx;
8528 g = view->gline;
8529 view->gline = 0;
8531 if (g == 0)
8532 g = 1;
8533 else if (g > s->nrefs)
8534 g = s->nrefs;
8536 if (g >= s->first_displayed_entry->idx + 1 &&
8537 g <= s->last_displayed_entry->idx + 1 &&
8538 g - s->first_displayed_entry->idx - 1 < nlines) {
8539 s->selected = g - s->first_displayed_entry->idx - 1;
8540 return NULL;
8543 if (idx + 1 < g) {
8544 err = ref_scroll_down(view, g - idx - 1);
8545 if (err)
8546 return err;
8547 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8548 s->first_displayed_entry->idx + s->selected < g &&
8549 s->selected < s->ndisplayed - 1)
8550 s->selected = g - s->first_displayed_entry->idx - 1;
8551 } else if (idx + 1 > g)
8552 ref_scroll_up(s, idx - g + 1);
8554 if (g < nlines && s->first_displayed_entry->idx == 0)
8555 s->selected = g - 1;
8557 return NULL;
8561 static const struct got_error *
8562 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8564 const struct got_error *err = NULL;
8565 struct tog_ref_view_state *s = &view->state.ref;
8566 struct tog_reflist_entry *re;
8567 int n, nscroll = view->nlines - 1;
8569 if (view->gline)
8570 return ref_goto_line(view, nscroll);
8572 switch (ch) {
8573 case '0':
8574 case '$':
8575 case KEY_RIGHT:
8576 case 'l':
8577 case KEY_LEFT:
8578 case 'h':
8579 horizontal_scroll_input(view, ch);
8580 break;
8581 case 'i':
8582 s->show_ids = !s->show_ids;
8583 view->count = 0;
8584 break;
8585 case 'm':
8586 s->show_date = !s->show_date;
8587 view->count = 0;
8588 break;
8589 case 'o':
8590 s->sort_by_date = !s->sort_by_date;
8591 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8592 view->count = 0;
8593 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8594 got_ref_cmp_by_commit_timestamp_descending :
8595 tog_ref_cmp_by_name, s->repo);
8596 if (err)
8597 break;
8598 got_reflist_object_id_map_free(tog_refs_idmap);
8599 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8600 &tog_refs, s->repo);
8601 if (err)
8602 break;
8603 ref_view_free_refs(s);
8604 err = ref_view_load_refs(s);
8605 break;
8606 case KEY_ENTER:
8607 case '\r':
8608 view->count = 0;
8609 if (!s->selected_entry)
8610 break;
8611 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8612 break;
8613 case 'T':
8614 view->count = 0;
8615 if (!s->selected_entry)
8616 break;
8617 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8618 break;
8619 case 'g':
8620 case '=':
8621 case KEY_HOME:
8622 s->selected = 0;
8623 view->count = 0;
8624 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8625 break;
8626 case 'G':
8627 case '*':
8628 case KEY_END: {
8629 int eos = view->nlines - 1;
8631 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8632 --eos; /* border */
8633 s->selected = 0;
8634 view->count = 0;
8635 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8636 for (n = 0; n < eos; n++) {
8637 if (re == NULL)
8638 break;
8639 s->first_displayed_entry = re;
8640 re = TAILQ_PREV(re, tog_reflist_head, entry);
8642 if (n > 0)
8643 s->selected = n - 1;
8644 break;
8646 case 'k':
8647 case KEY_UP:
8648 case CTRL('p'):
8649 if (s->selected > 0) {
8650 s->selected--;
8651 break;
8653 ref_scroll_up(s, 1);
8654 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8655 view->count = 0;
8656 break;
8657 case CTRL('u'):
8658 case 'u':
8659 nscroll /= 2;
8660 /* FALL THROUGH */
8661 case KEY_PPAGE:
8662 case CTRL('b'):
8663 case 'b':
8664 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8665 s->selected -= MIN(nscroll, s->selected);
8666 ref_scroll_up(s, MAX(0, nscroll));
8667 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8668 view->count = 0;
8669 break;
8670 case 'j':
8671 case KEY_DOWN:
8672 case CTRL('n'):
8673 if (s->selected < s->ndisplayed - 1) {
8674 s->selected++;
8675 break;
8677 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8678 /* can't scroll any further */
8679 view->count = 0;
8680 break;
8682 ref_scroll_down(view, 1);
8683 break;
8684 case CTRL('d'):
8685 case 'd':
8686 nscroll /= 2;
8687 /* FALL THROUGH */
8688 case KEY_NPAGE:
8689 case CTRL('f'):
8690 case 'f':
8691 case ' ':
8692 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8693 /* can't scroll any further; move cursor down */
8694 if (s->selected < s->ndisplayed - 1)
8695 s->selected += MIN(nscroll,
8696 s->ndisplayed - s->selected - 1);
8697 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8698 s->selected += s->ndisplayed - s->selected - 1;
8699 view->count = 0;
8700 break;
8702 ref_scroll_down(view, nscroll);
8703 break;
8704 case CTRL('l'):
8705 view->count = 0;
8706 tog_free_refs();
8707 err = tog_load_refs(s->repo, s->sort_by_date);
8708 if (err)
8709 break;
8710 ref_view_free_refs(s);
8711 err = ref_view_load_refs(s);
8712 break;
8713 case KEY_RESIZE:
8714 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8715 s->selected = view->nlines - 2;
8716 break;
8717 default:
8718 view->count = 0;
8719 break;
8722 return err;
8725 __dead static void
8726 usage_ref(void)
8728 endwin();
8729 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8730 getprogname());
8731 exit(1);
8734 static const struct got_error *
8735 cmd_ref(int argc, char *argv[])
8737 const struct got_error *error;
8738 struct got_repository *repo = NULL;
8739 struct got_worktree *worktree = NULL;
8740 char *cwd = NULL, *repo_path = NULL;
8741 int ch;
8742 struct tog_view *view;
8743 int *pack_fds = NULL;
8745 while ((ch = getopt(argc, argv, "r:")) != -1) {
8746 switch (ch) {
8747 case 'r':
8748 repo_path = realpath(optarg, NULL);
8749 if (repo_path == NULL)
8750 return got_error_from_errno2("realpath",
8751 optarg);
8752 break;
8753 default:
8754 usage_ref();
8755 /* NOTREACHED */
8759 argc -= optind;
8760 argv += optind;
8762 if (argc > 1)
8763 usage_ref();
8765 error = got_repo_pack_fds_open(&pack_fds);
8766 if (error != NULL)
8767 goto done;
8769 if (repo_path == NULL) {
8770 cwd = getcwd(NULL, 0);
8771 if (cwd == NULL)
8772 return got_error_from_errno("getcwd");
8773 error = got_worktree_open(&worktree, cwd);
8774 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8775 goto done;
8776 if (worktree)
8777 repo_path =
8778 strdup(got_worktree_get_repo_path(worktree));
8779 else
8780 repo_path = strdup(cwd);
8781 if (repo_path == NULL) {
8782 error = got_error_from_errno("strdup");
8783 goto done;
8787 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8788 if (error != NULL)
8789 goto done;
8791 init_curses();
8793 error = apply_unveil(got_repo_get_path(repo), NULL);
8794 if (error)
8795 goto done;
8797 error = tog_load_refs(repo, 0);
8798 if (error)
8799 goto done;
8801 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8802 if (view == NULL) {
8803 error = got_error_from_errno("view_open");
8804 goto done;
8807 error = open_ref_view(view, repo);
8808 if (error)
8809 goto done;
8811 if (worktree) {
8812 /* Release work tree lock. */
8813 got_worktree_close(worktree);
8814 worktree = NULL;
8816 error = view_loop(view);
8817 done:
8818 free(repo_path);
8819 free(cwd);
8820 if (repo) {
8821 const struct got_error *close_err = got_repo_close(repo);
8822 if (close_err)
8823 error = close_err;
8825 if (pack_fds) {
8826 const struct got_error *pack_err =
8827 got_repo_pack_fds_close(pack_fds);
8828 if (error == NULL)
8829 error = pack_err;
8831 tog_free_refs();
8832 return error;
8835 static const struct got_error*
8836 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8837 const char *str)
8839 size_t len;
8841 if (win == NULL)
8842 win = stdscr;
8844 len = strlen(str);
8845 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8847 if (focus)
8848 wstandout(win);
8849 if (mvwprintw(win, y, x, "%s", str) == ERR)
8850 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8851 if (focus)
8852 wstandend(win);
8854 return NULL;
8857 static const struct got_error *
8858 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8860 off_t *p;
8862 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8863 if (p == NULL) {
8864 free(*line_offsets);
8865 *line_offsets = NULL;
8866 return got_error_from_errno("reallocarray");
8869 *line_offsets = p;
8870 (*line_offsets)[*nlines] = off;
8871 ++(*nlines);
8872 return NULL;
8875 static const struct got_error *
8876 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8878 *ret = 0;
8880 for (;n > 0; --n, ++km) {
8881 char *t0, *t, *k;
8882 size_t len = 1;
8884 if (km->keys == NULL)
8885 continue;
8887 t = t0 = strdup(km->keys);
8888 if (t0 == NULL)
8889 return got_error_from_errno("strdup");
8891 len += strlen(t);
8892 while ((k = strsep(&t, " ")) != NULL)
8893 len += strlen(k) > 1 ? 2 : 0;
8894 free(t0);
8895 *ret = MAX(*ret, len);
8898 return NULL;
8902 * Write keymap section headers, keys, and key info in km to f.
8903 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8904 * wrap control and symbolic keys in guillemets, else use <>.
8906 static const struct got_error *
8907 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8909 int n, len = width;
8911 if (km->keys) {
8912 static const char *u8_glyph[] = {
8913 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8914 "\xe2\x80\xba" /* U+203A (utf8 >) */
8916 char *t0, *t, *k;
8917 int cs, s, first = 1;
8919 cs = got_locale_is_utf8();
8921 t = t0 = strdup(km->keys);
8922 if (t0 == NULL)
8923 return got_error_from_errno("strdup");
8925 len = strlen(km->keys);
8926 while ((k = strsep(&t, " ")) != NULL) {
8927 s = strlen(k) > 1; /* control or symbolic key */
8928 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8929 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8930 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8931 if (n < 0) {
8932 free(t0);
8933 return got_error_from_errno("fprintf");
8935 first = 0;
8936 len += s ? 2 : 0;
8937 *off += n;
8939 free(t0);
8941 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8942 if (n < 0)
8943 return got_error_from_errno("fprintf");
8944 *off += n;
8946 return NULL;
8949 static const struct got_error *
8950 format_help(struct tog_help_view_state *s)
8952 const struct got_error *err = NULL;
8953 off_t off = 0;
8954 int i, max, n, show = s->all;
8955 static const struct tog_key_map km[] = {
8956 #define KEYMAP_(info, type) { NULL, (info), type }
8957 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8958 GENERATE_HELP
8959 #undef KEYMAP_
8960 #undef KEY_
8963 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8964 if (err)
8965 return err;
8967 n = nitems(km);
8968 err = max_key_str(&max, km, n);
8969 if (err)
8970 return err;
8972 for (i = 0; i < n; ++i) {
8973 if (km[i].keys == NULL) {
8974 show = s->all;
8975 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8976 km[i].type == s->type || s->all)
8977 show = 1;
8979 if (show) {
8980 err = format_help_line(&off, s->f, &km[i], max);
8981 if (err)
8982 return err;
8983 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8984 if (err)
8985 return err;
8988 fputc('\n', s->f);
8989 ++off;
8990 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8991 return err;
8994 static const struct got_error *
8995 create_help(struct tog_help_view_state *s)
8997 FILE *f;
8998 const struct got_error *err;
9000 free(s->line_offsets);
9001 s->line_offsets = NULL;
9002 s->nlines = 0;
9004 f = got_opentemp();
9005 if (f == NULL)
9006 return got_error_from_errno("got_opentemp");
9007 s->f = f;
9009 err = format_help(s);
9010 if (err)
9011 return err;
9013 if (s->f && fflush(s->f) != 0)
9014 return got_error_from_errno("fflush");
9016 return NULL;
9019 static const struct got_error *
9020 search_start_help_view(struct tog_view *view)
9022 view->state.help.matched_line = 0;
9023 return NULL;
9026 static void
9027 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9028 size_t *nlines, int **first, int **last, int **match, int **selected)
9030 struct tog_help_view_state *s = &view->state.help;
9032 *f = s->f;
9033 *nlines = s->nlines;
9034 *line_offsets = s->line_offsets;
9035 *match = &s->matched_line;
9036 *first = &s->first_displayed_line;
9037 *last = &s->last_displayed_line;
9038 *selected = &s->selected_line;
9041 static const struct got_error *
9042 show_help_view(struct tog_view *view)
9044 struct tog_help_view_state *s = &view->state.help;
9045 const struct got_error *err;
9046 regmatch_t *regmatch = &view->regmatch;
9047 wchar_t *wline;
9048 char *line;
9049 ssize_t linelen;
9050 size_t linesz = 0;
9051 int width, nprinted = 0, rc = 0;
9052 int eos = view->nlines;
9054 if (view_is_hsplit_top(view))
9055 --eos; /* account for border */
9057 s->lineno = 0;
9058 rewind(s->f);
9059 werase(view->window);
9061 if (view->gline > s->nlines - 1)
9062 view->gline = s->nlines - 1;
9064 err = win_draw_center(view->window, 0, 0, view->ncols,
9065 view_needs_focus_indication(view),
9066 "tog help (press q to return to tog)");
9067 if (err)
9068 return err;
9069 if (eos <= 1)
9070 return NULL;
9071 waddstr(view->window, "\n\n");
9072 eos -= 2;
9074 s->eof = 0;
9075 view->maxx = 0;
9076 line = NULL;
9077 while (eos > 0 && nprinted < eos) {
9078 attr_t attr = 0;
9080 linelen = getline(&line, &linesz, s->f);
9081 if (linelen == -1) {
9082 if (!feof(s->f)) {
9083 free(line);
9084 return got_ferror(s->f, GOT_ERR_IO);
9086 s->eof = 1;
9087 break;
9089 if (++s->lineno < s->first_displayed_line)
9090 continue;
9091 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9092 continue;
9093 if (s->lineno == view->hiline)
9094 attr = A_STANDOUT;
9096 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9097 view->x ? 1 : 0);
9098 if (err) {
9099 free(line);
9100 return err;
9102 view->maxx = MAX(view->maxx, width);
9103 free(wline);
9104 wline = NULL;
9106 if (attr)
9107 wattron(view->window, attr);
9108 if (s->first_displayed_line + nprinted == s->matched_line &&
9109 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9110 err = add_matched_line(&width, line, view->ncols - 1, 0,
9111 view->window, view->x, regmatch);
9112 if (err) {
9113 free(line);
9114 return err;
9116 } else {
9117 int skip;
9119 err = format_line(&wline, &width, &skip, line,
9120 view->x, view->ncols, 0, view->x ? 1 : 0);
9121 if (err) {
9122 free(line);
9123 return err;
9125 waddwstr(view->window, &wline[skip]);
9126 free(wline);
9127 wline = NULL;
9129 if (s->lineno == view->hiline) {
9130 while (width++ < view->ncols)
9131 waddch(view->window, ' ');
9132 } else {
9133 if (width < view->ncols)
9134 waddch(view->window, '\n');
9136 if (attr)
9137 wattroff(view->window, attr);
9138 if (++nprinted == 1)
9139 s->first_displayed_line = s->lineno;
9141 free(line);
9142 if (nprinted > 0)
9143 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9144 else
9145 s->last_displayed_line = s->first_displayed_line;
9147 view_border(view);
9149 if (s->eof) {
9150 rc = waddnstr(view->window,
9151 "See the tog(1) manual page for full documentation",
9152 view->ncols - 1);
9153 if (rc == ERR)
9154 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9155 } else {
9156 wmove(view->window, view->nlines - 1, 0);
9157 wclrtoeol(view->window);
9158 wstandout(view->window);
9159 rc = waddnstr(view->window, "scroll down for more...",
9160 view->ncols - 1);
9161 if (rc == ERR)
9162 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9163 if (getcurx(view->window) < view->ncols - 6) {
9164 rc = wprintw(view->window, "[%.0f%%]",
9165 100.00 * s->last_displayed_line / s->nlines);
9166 if (rc == ERR)
9167 return got_error_msg(GOT_ERR_IO, "wprintw");
9169 wstandend(view->window);
9172 return NULL;
9175 static const struct got_error *
9176 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9178 struct tog_help_view_state *s = &view->state.help;
9179 const struct got_error *err = NULL;
9180 char *line = NULL;
9181 ssize_t linelen;
9182 size_t linesz = 0;
9183 int eos, nscroll;
9185 eos = nscroll = view->nlines;
9186 if (view_is_hsplit_top(view))
9187 --eos; /* border */
9189 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9191 switch (ch) {
9192 case '0':
9193 case '$':
9194 case KEY_RIGHT:
9195 case 'l':
9196 case KEY_LEFT:
9197 case 'h':
9198 horizontal_scroll_input(view, ch);
9199 break;
9200 case 'g':
9201 case KEY_HOME:
9202 s->first_displayed_line = 1;
9203 view->count = 0;
9204 break;
9205 case 'G':
9206 case KEY_END:
9207 view->count = 0;
9208 if (s->eof)
9209 break;
9210 s->first_displayed_line = (s->nlines - eos) + 3;
9211 s->eof = 1;
9212 break;
9213 case 'k':
9214 case KEY_UP:
9215 if (s->first_displayed_line > 1)
9216 --s->first_displayed_line;
9217 else
9218 view->count = 0;
9219 break;
9220 case CTRL('u'):
9221 case 'u':
9222 nscroll /= 2;
9223 /* FALL THROUGH */
9224 case KEY_PPAGE:
9225 case CTRL('b'):
9226 case 'b':
9227 if (s->first_displayed_line == 1) {
9228 view->count = 0;
9229 break;
9231 while (--nscroll > 0 && s->first_displayed_line > 1)
9232 s->first_displayed_line--;
9233 break;
9234 case 'j':
9235 case KEY_DOWN:
9236 case CTRL('n'):
9237 if (!s->eof)
9238 ++s->first_displayed_line;
9239 else
9240 view->count = 0;
9241 break;
9242 case CTRL('d'):
9243 case 'd':
9244 nscroll /= 2;
9245 /* FALL THROUGH */
9246 case KEY_NPAGE:
9247 case CTRL('f'):
9248 case 'f':
9249 case ' ':
9250 if (s->eof) {
9251 view->count = 0;
9252 break;
9254 while (!s->eof && --nscroll > 0) {
9255 linelen = getline(&line, &linesz, s->f);
9256 s->first_displayed_line++;
9257 if (linelen == -1) {
9258 if (feof(s->f))
9259 s->eof = 1;
9260 else
9261 err = got_ferror(s->f, GOT_ERR_IO);
9262 break;
9265 free(line);
9266 break;
9267 default:
9268 view->count = 0;
9269 break;
9272 return err;
9275 static const struct got_error *
9276 close_help_view(struct tog_view *view)
9278 struct tog_help_view_state *s = &view->state.help;
9280 free(s->line_offsets);
9281 s->line_offsets = NULL;
9282 if (fclose(s->f) == EOF)
9283 return got_error_from_errno("fclose");
9285 return NULL;
9288 static const struct got_error *
9289 reset_help_view(struct tog_view *view)
9291 struct tog_help_view_state *s = &view->state.help;
9294 if (s->f && fclose(s->f) == EOF)
9295 return got_error_from_errno("fclose");
9297 wclear(view->window);
9298 view->count = 0;
9299 view->x = 0;
9300 s->all = !s->all;
9301 s->first_displayed_line = 1;
9302 s->last_displayed_line = view->nlines;
9303 s->matched_line = 0;
9305 return create_help(s);
9308 static const struct got_error *
9309 open_help_view(struct tog_view *view, struct tog_view *parent)
9311 const struct got_error *err = NULL;
9312 struct tog_help_view_state *s = &view->state.help;
9314 s->type = (enum tog_keymap_type)parent->type;
9315 s->first_displayed_line = 1;
9316 s->last_displayed_line = view->nlines;
9317 s->selected_line = 1;
9319 view->show = show_help_view;
9320 view->input = input_help_view;
9321 view->reset = reset_help_view;
9322 view->close = close_help_view;
9323 view->search_start = search_start_help_view;
9324 view->search_setup = search_setup_help_view;
9325 view->search_next = search_next_view_match;
9327 err = create_help(s);
9328 return err;
9331 static const struct got_error *
9332 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9333 enum tog_view_type request, int y, int x)
9335 const struct got_error *err = NULL;
9337 *new_view = NULL;
9339 switch (request) {
9340 case TOG_VIEW_DIFF:
9341 if (view->type == TOG_VIEW_LOG) {
9342 struct tog_log_view_state *s = &view->state.log;
9344 err = open_diff_view_for_commit(new_view, y, x,
9345 s->selected_entry->commit, s->selected_entry->id,
9346 view, s->repo);
9347 } else
9348 return got_error_msg(GOT_ERR_NOT_IMPL,
9349 "parent/child view pair not supported");
9350 break;
9351 case TOG_VIEW_BLAME:
9352 if (view->type == TOG_VIEW_TREE) {
9353 struct tog_tree_view_state *s = &view->state.tree;
9355 err = blame_tree_entry(new_view, y, x,
9356 s->selected_entry, &s->parents, s->commit_id,
9357 s->repo);
9358 } else
9359 return got_error_msg(GOT_ERR_NOT_IMPL,
9360 "parent/child view pair not supported");
9361 break;
9362 case TOG_VIEW_LOG:
9363 if (view->type == TOG_VIEW_BLAME)
9364 err = log_annotated_line(new_view, y, x,
9365 view->state.blame.repo, view->state.blame.id_to_log);
9366 else if (view->type == TOG_VIEW_TREE)
9367 err = log_selected_tree_entry(new_view, y, x,
9368 &view->state.tree);
9369 else if (view->type == TOG_VIEW_REF)
9370 err = log_ref_entry(new_view, y, x,
9371 view->state.ref.selected_entry,
9372 view->state.ref.repo);
9373 else
9374 return got_error_msg(GOT_ERR_NOT_IMPL,
9375 "parent/child view pair not supported");
9376 break;
9377 case TOG_VIEW_TREE:
9378 if (view->type == TOG_VIEW_LOG)
9379 err = browse_commit_tree(new_view, y, x,
9380 view->state.log.selected_entry,
9381 view->state.log.in_repo_path,
9382 view->state.log.head_ref_name,
9383 view->state.log.repo);
9384 else if (view->type == TOG_VIEW_REF)
9385 err = browse_ref_tree(new_view, y, x,
9386 view->state.ref.selected_entry,
9387 view->state.ref.repo);
9388 else
9389 return got_error_msg(GOT_ERR_NOT_IMPL,
9390 "parent/child view pair not supported");
9391 break;
9392 case TOG_VIEW_REF:
9393 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9394 if (*new_view == NULL)
9395 return got_error_from_errno("view_open");
9396 if (view->type == TOG_VIEW_LOG)
9397 err = open_ref_view(*new_view, view->state.log.repo);
9398 else if (view->type == TOG_VIEW_TREE)
9399 err = open_ref_view(*new_view, view->state.tree.repo);
9400 else
9401 err = got_error_msg(GOT_ERR_NOT_IMPL,
9402 "parent/child view pair not supported");
9403 if (err)
9404 view_close(*new_view);
9405 break;
9406 case TOG_VIEW_HELP:
9407 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9408 if (*new_view == NULL)
9409 return got_error_from_errno("view_open");
9410 err = open_help_view(*new_view, view);
9411 if (err)
9412 view_close(*new_view);
9413 break;
9414 default:
9415 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9418 return err;
9422 * If view was scrolled down to move the selected line into view when opening a
9423 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9425 static void
9426 offset_selection_up(struct tog_view *view)
9428 switch (view->type) {
9429 case TOG_VIEW_BLAME: {
9430 struct tog_blame_view_state *s = &view->state.blame;
9431 if (s->first_displayed_line == 1) {
9432 s->selected_line = MAX(s->selected_line - view->offset,
9433 1);
9434 break;
9436 if (s->first_displayed_line > view->offset)
9437 s->first_displayed_line -= view->offset;
9438 else
9439 s->first_displayed_line = 1;
9440 s->selected_line += view->offset;
9441 break;
9443 case TOG_VIEW_LOG:
9444 log_scroll_up(&view->state.log, view->offset);
9445 view->state.log.selected += view->offset;
9446 break;
9447 case TOG_VIEW_REF:
9448 ref_scroll_up(&view->state.ref, view->offset);
9449 view->state.ref.selected += view->offset;
9450 break;
9451 case TOG_VIEW_TREE:
9452 tree_scroll_up(&view->state.tree, view->offset);
9453 view->state.tree.selected += view->offset;
9454 break;
9455 default:
9456 break;
9459 view->offset = 0;
9463 * If the selected line is in the section of screen covered by the bottom split,
9464 * scroll down offset lines to move it into view and index its new position.
9466 static const struct got_error *
9467 offset_selection_down(struct tog_view *view)
9469 const struct got_error *err = NULL;
9470 const struct got_error *(*scrolld)(struct tog_view *, int);
9471 int *selected = NULL;
9472 int header, offset;
9474 switch (view->type) {
9475 case TOG_VIEW_BLAME: {
9476 struct tog_blame_view_state *s = &view->state.blame;
9477 header = 3;
9478 scrolld = NULL;
9479 if (s->selected_line > view->nlines - header) {
9480 offset = abs(view->nlines - s->selected_line - header);
9481 s->first_displayed_line += offset;
9482 s->selected_line -= offset;
9483 view->offset = offset;
9485 break;
9487 case TOG_VIEW_LOG: {
9488 struct tog_log_view_state *s = &view->state.log;
9489 scrolld = &log_scroll_down;
9490 header = view_is_parent_view(view) ? 3 : 2;
9491 selected = &s->selected;
9492 break;
9494 case TOG_VIEW_REF: {
9495 struct tog_ref_view_state *s = &view->state.ref;
9496 scrolld = &ref_scroll_down;
9497 header = 3;
9498 selected = &s->selected;
9499 break;
9501 case TOG_VIEW_TREE: {
9502 struct tog_tree_view_state *s = &view->state.tree;
9503 scrolld = &tree_scroll_down;
9504 header = 5;
9505 selected = &s->selected;
9506 break;
9508 default:
9509 selected = NULL;
9510 scrolld = NULL;
9511 header = 0;
9512 break;
9515 if (selected && *selected > view->nlines - header) {
9516 offset = abs(view->nlines - *selected - header);
9517 view->offset = offset;
9518 if (scrolld && offset) {
9519 err = scrolld(view, offset);
9520 *selected -= offset;
9524 return err;
9527 static void
9528 list_commands(FILE *fp)
9530 size_t i;
9532 fprintf(fp, "commands:");
9533 for (i = 0; i < nitems(tog_commands); i++) {
9534 const struct tog_cmd *cmd = &tog_commands[i];
9535 fprintf(fp, " %s", cmd->name);
9537 fputc('\n', fp);
9540 __dead static void
9541 usage(int hflag, int status)
9543 FILE *fp = (status == 0) ? stdout : stderr;
9545 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9546 getprogname());
9547 if (hflag) {
9548 fprintf(fp, "lazy usage: %s path\n", getprogname());
9549 list_commands(fp);
9551 exit(status);
9554 static char **
9555 make_argv(int argc, ...)
9557 va_list ap;
9558 char **argv;
9559 int i;
9561 va_start(ap, argc);
9563 argv = calloc(argc, sizeof(char *));
9564 if (argv == NULL)
9565 err(1, "calloc");
9566 for (i = 0; i < argc; i++) {
9567 argv[i] = strdup(va_arg(ap, char *));
9568 if (argv[i] == NULL)
9569 err(1, "strdup");
9572 va_end(ap);
9573 return argv;
9577 * Try to convert 'tog path' into a 'tog log path' command.
9578 * The user could simply have mistyped the command rather than knowingly
9579 * provided a path. So check whether argv[0] can in fact be resolved
9580 * to a path in the HEAD commit and print a special error if not.
9581 * This hack is for mpi@ <3
9583 static const struct got_error *
9584 tog_log_with_path(int argc, char *argv[])
9586 const struct got_error *error = NULL, *close_err;
9587 const struct tog_cmd *cmd = NULL;
9588 struct got_repository *repo = NULL;
9589 struct got_worktree *worktree = NULL;
9590 struct got_object_id *commit_id = NULL, *id = NULL;
9591 struct got_commit_object *commit = NULL;
9592 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9593 char *commit_id_str = NULL, **cmd_argv = NULL;
9594 int *pack_fds = NULL;
9596 cwd = getcwd(NULL, 0);
9597 if (cwd == NULL)
9598 return got_error_from_errno("getcwd");
9600 error = got_repo_pack_fds_open(&pack_fds);
9601 if (error != NULL)
9602 goto done;
9604 error = got_worktree_open(&worktree, cwd);
9605 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9606 goto done;
9608 if (worktree)
9609 repo_path = strdup(got_worktree_get_repo_path(worktree));
9610 else
9611 repo_path = strdup(cwd);
9612 if (repo_path == NULL) {
9613 error = got_error_from_errno("strdup");
9614 goto done;
9617 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9618 if (error != NULL)
9619 goto done;
9621 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9622 repo, worktree);
9623 if (error)
9624 goto done;
9626 error = tog_load_refs(repo, 0);
9627 if (error)
9628 goto done;
9629 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9630 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9631 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9632 if (error)
9633 goto done;
9635 if (worktree) {
9636 got_worktree_close(worktree);
9637 worktree = NULL;
9640 error = got_object_open_as_commit(&commit, repo, commit_id);
9641 if (error)
9642 goto done;
9644 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9645 if (error) {
9646 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9647 goto done;
9648 fprintf(stderr, "%s: '%s' is no known command or path\n",
9649 getprogname(), argv[0]);
9650 usage(1, 1);
9651 /* not reached */
9654 error = got_object_id_str(&commit_id_str, commit_id);
9655 if (error)
9656 goto done;
9658 cmd = &tog_commands[0]; /* log */
9659 argc = 4;
9660 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9661 error = cmd->cmd_main(argc, cmd_argv);
9662 done:
9663 if (repo) {
9664 close_err = got_repo_close(repo);
9665 if (error == NULL)
9666 error = close_err;
9668 if (commit)
9669 got_object_commit_close(commit);
9670 if (worktree)
9671 got_worktree_close(worktree);
9672 if (pack_fds) {
9673 const struct got_error *pack_err =
9674 got_repo_pack_fds_close(pack_fds);
9675 if (error == NULL)
9676 error = pack_err;
9678 free(id);
9679 free(commit_id_str);
9680 free(commit_id);
9681 free(cwd);
9682 free(repo_path);
9683 free(in_repo_path);
9684 if (cmd_argv) {
9685 int i;
9686 for (i = 0; i < argc; i++)
9687 free(cmd_argv[i]);
9688 free(cmd_argv);
9690 tog_free_refs();
9691 return error;
9694 int
9695 main(int argc, char *argv[])
9697 const struct got_error *io_err, *error = NULL;
9698 const struct tog_cmd *cmd = NULL;
9699 int ch, hflag = 0, Vflag = 0;
9700 char **cmd_argv = NULL;
9701 static const struct option longopts[] = {
9702 { "version", no_argument, NULL, 'V' },
9703 { NULL, 0, NULL, 0}
9705 char *diff_algo_str = NULL;
9706 const char *test_script_path;
9708 setlocale(LC_CTYPE, "");
9711 * Test mode init must happen before pledge() because "tty" will
9712 * not allow TTY-related ioctls to occur via regular files.
9714 test_script_path = getenv("GOT_TOG_TEST");
9715 if (test_script_path != NULL) {
9716 error = init_mock_term(test_script_path);
9717 if (error) {
9718 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9719 return 1;
9723 #if !defined(PROFILE)
9724 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9725 NULL) == -1)
9726 err(1, "pledge");
9727 #endif
9729 if (!isatty(STDIN_FILENO))
9730 errx(1, "standard input is not a tty");
9732 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9733 switch (ch) {
9734 case 'h':
9735 hflag = 1;
9736 break;
9737 case 'V':
9738 Vflag = 1;
9739 break;
9740 default:
9741 usage(hflag, 1);
9742 /* NOTREACHED */
9746 argc -= optind;
9747 argv += optind;
9748 optind = 1;
9749 optreset = 1;
9751 if (Vflag) {
9752 got_version_print_str();
9753 return 0;
9756 if (argc == 0) {
9757 if (hflag)
9758 usage(hflag, 0);
9759 /* Build an argument vector which runs a default command. */
9760 cmd = &tog_commands[0];
9761 argc = 1;
9762 cmd_argv = make_argv(argc, cmd->name);
9763 } else {
9764 size_t i;
9766 /* Did the user specify a command? */
9767 for (i = 0; i < nitems(tog_commands); i++) {
9768 if (strncmp(tog_commands[i].name, argv[0],
9769 strlen(argv[0])) == 0) {
9770 cmd = &tog_commands[i];
9771 break;
9776 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9777 if (diff_algo_str) {
9778 if (strcasecmp(diff_algo_str, "patience") == 0)
9779 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9780 if (strcasecmp(diff_algo_str, "myers") == 0)
9781 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9784 if (cmd == NULL) {
9785 if (argc != 1)
9786 usage(0, 1);
9787 /* No command specified; try log with a path */
9788 error = tog_log_with_path(argc, argv);
9789 } else {
9790 if (hflag)
9791 cmd->cmd_usage();
9792 else
9793 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9796 if (using_mock_io) {
9797 io_err = tog_io_close();
9798 if (error == NULL)
9799 error = io_err;
9801 endwin();
9802 if (cmd_argv) {
9803 int i;
9804 for (i = 0; i < argc; i++)
9805 free(cmd_argv[i]);
9806 free(cmd_argv);
9809 if (error && error->code != GOT_ERR_CANCELLED &&
9810 error->code != GOT_ERR_EOF &&
9811 error->code != GOT_ERR_PRIVSEP_EXIT &&
9812 error->code != GOT_ERR_PRIVSEP_PIPE &&
9813 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9814 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9815 return 0;