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 err = got_error_from_errno("strdup");
3593 goto done;
3597 /* The commit queue only contains commits being displayed. */
3598 TAILQ_INIT(&s->real_commits.head);
3599 s->real_commits.ncommits = 0;
3600 s->commits = &s->real_commits;
3602 TAILQ_INIT(&s->limit_commits.head);
3603 s->limit_view = 0;
3604 s->limit_commits.ncommits = 0;
3606 s->repo = repo;
3607 if (head_ref_name) {
3608 s->head_ref_name = strdup(head_ref_name);
3609 if (s->head_ref_name == NULL) {
3610 err = got_error_from_errno("strdup");
3611 goto done;
3614 s->start_id = got_object_id_dup(start_id);
3615 if (s->start_id == NULL) {
3616 err = got_error_from_errno("got_object_id_dup");
3617 goto done;
3619 s->log_branches = log_branches;
3620 s->use_committer = 1;
3622 STAILQ_INIT(&s->colors);
3623 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3624 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3625 get_color_value("TOG_COLOR_COMMIT"));
3626 if (err)
3627 goto done;
3628 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3629 get_color_value("TOG_COLOR_AUTHOR"));
3630 if (err) {
3631 free_colors(&s->colors);
3632 goto done;
3634 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3635 get_color_value("TOG_COLOR_DATE"));
3636 if (err) {
3637 free_colors(&s->colors);
3638 goto done;
3642 view->show = show_log_view;
3643 view->input = input_log_view;
3644 view->resize = resize_log_view;
3645 view->close = close_log_view;
3646 view->search_start = search_start_log_view;
3647 view->search_next = search_next_log_view;
3649 if (s->thread_args.pack_fds == NULL) {
3650 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3651 if (err)
3652 goto done;
3654 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3655 s->thread_args.pack_fds);
3656 if (err)
3657 goto done;
3658 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3659 !s->log_branches);
3660 if (err)
3661 goto done;
3662 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3663 s->repo, NULL, NULL);
3664 if (err)
3665 goto done;
3667 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3668 if (errcode) {
3669 err = got_error_set_errno(errcode, "pthread_cond_init");
3670 goto done;
3672 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3673 if (errcode) {
3674 err = got_error_set_errno(errcode, "pthread_cond_init");
3675 goto done;
3678 s->thread_args.commits_needed = view->nlines;
3679 s->thread_args.graph = thread_graph;
3680 s->thread_args.real_commits = &s->real_commits;
3681 s->thread_args.limit_commits = &s->limit_commits;
3682 s->thread_args.in_repo_path = s->in_repo_path;
3683 s->thread_args.start_id = s->start_id;
3684 s->thread_args.repo = thread_repo;
3685 s->thread_args.log_complete = 0;
3686 s->thread_args.quit = &s->quit;
3687 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3688 s->thread_args.selected_entry = &s->selected_entry;
3689 s->thread_args.searching = &view->searching;
3690 s->thread_args.search_next_done = &view->search_next_done;
3691 s->thread_args.regex = &view->regex;
3692 s->thread_args.limiting = &s->limit_view;
3693 s->thread_args.limit_regex = &s->limit_regex;
3694 s->thread_args.limit_commits = &s->limit_commits;
3695 done:
3696 if (err) {
3697 if (view->close == NULL)
3698 close_log_view(view);
3699 view_close(view);
3701 return err;
3704 static const struct got_error *
3705 show_log_view(struct tog_view *view)
3707 const struct got_error *err;
3708 struct tog_log_view_state *s = &view->state.log;
3710 if (s->thread == NULL) {
3711 int errcode = pthread_create(&s->thread, NULL, log_thread,
3712 &s->thread_args);
3713 if (errcode)
3714 return got_error_set_errno(errcode, "pthread_create");
3715 if (s->thread_args.commits_needed > 0) {
3716 err = trigger_log_thread(view, 1);
3717 if (err)
3718 return err;
3722 return draw_commits(view);
3725 static void
3726 log_move_cursor_up(struct tog_view *view, int page, int home)
3728 struct tog_log_view_state *s = &view->state.log;
3730 if (s->first_displayed_entry == NULL)
3731 return;
3732 if (s->selected_entry->idx == 0)
3733 view->count = 0;
3735 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3736 || home)
3737 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3739 if (!page && !home && s->selected > 0)
3740 --s->selected;
3741 else
3742 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3744 select_commit(s);
3745 return;
3748 static const struct got_error *
3749 log_move_cursor_down(struct tog_view *view, int page)
3751 struct tog_log_view_state *s = &view->state.log;
3752 const struct got_error *err = NULL;
3753 int eos = view->nlines - 2;
3755 if (s->first_displayed_entry == NULL)
3756 return NULL;
3758 if (s->thread_args.log_complete &&
3759 s->selected_entry->idx >= s->commits->ncommits - 1)
3760 return NULL;
3762 if (view_is_hsplit_top(view))
3763 --eos; /* border consumes the last line */
3765 if (!page) {
3766 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3767 ++s->selected;
3768 else
3769 err = log_scroll_down(view, 1);
3770 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3771 struct commit_queue_entry *entry;
3772 int n;
3774 s->selected = 0;
3775 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3776 s->last_displayed_entry = entry;
3777 for (n = 0; n <= eos; n++) {
3778 if (entry == NULL)
3779 break;
3780 s->first_displayed_entry = entry;
3781 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3783 if (n > 0)
3784 s->selected = n - 1;
3785 } else {
3786 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3787 s->thread_args.log_complete)
3788 s->selected += MIN(page,
3789 s->commits->ncommits - s->selected_entry->idx - 1);
3790 else
3791 err = log_scroll_down(view, page);
3793 if (err)
3794 return err;
3797 * We might necessarily overshoot in horizontal
3798 * splits; if so, select the last displayed commit.
3800 if (s->first_displayed_entry && s->last_displayed_entry) {
3801 s->selected = MIN(s->selected,
3802 s->last_displayed_entry->idx -
3803 s->first_displayed_entry->idx);
3806 select_commit(s);
3808 if (s->thread_args.log_complete &&
3809 s->selected_entry->idx == s->commits->ncommits - 1)
3810 view->count = 0;
3812 return NULL;
3815 static void
3816 view_get_split(struct tog_view *view, int *y, int *x)
3818 *x = 0;
3819 *y = 0;
3821 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3822 if (view->child && view->child->resized_y)
3823 *y = view->child->resized_y;
3824 else if (view->resized_y)
3825 *y = view->resized_y;
3826 else
3827 *y = view_split_begin_y(view->lines);
3828 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3829 if (view->child && view->child->resized_x)
3830 *x = view->child->resized_x;
3831 else if (view->resized_x)
3832 *x = view->resized_x;
3833 else
3834 *x = view_split_begin_x(view->begin_x);
3838 /* Split view horizontally at y and offset view->state->selected line. */
3839 static const struct got_error *
3840 view_init_hsplit(struct tog_view *view, int y)
3842 const struct got_error *err = NULL;
3844 view->nlines = y;
3845 view->ncols = COLS;
3846 err = view_resize(view);
3847 if (err)
3848 return err;
3850 err = offset_selection_down(view);
3852 return err;
3855 static const struct got_error *
3856 log_goto_line(struct tog_view *view, int nlines)
3858 const struct got_error *err = NULL;
3859 struct tog_log_view_state *s = &view->state.log;
3860 int g, idx = s->selected_entry->idx;
3862 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3863 return NULL;
3865 g = view->gline;
3866 view->gline = 0;
3868 if (g >= s->first_displayed_entry->idx + 1 &&
3869 g <= s->last_displayed_entry->idx + 1 &&
3870 g - s->first_displayed_entry->idx - 1 < nlines) {
3871 s->selected = g - s->first_displayed_entry->idx - 1;
3872 select_commit(s);
3873 return NULL;
3876 if (idx + 1 < g) {
3877 err = log_move_cursor_down(view, g - idx - 1);
3878 if (!err && g > s->selected_entry->idx + 1)
3879 err = log_move_cursor_down(view,
3880 g - s->first_displayed_entry->idx - 1);
3881 if (err)
3882 return err;
3883 } else if (idx + 1 > g)
3884 log_move_cursor_up(view, idx - g + 1, 0);
3886 if (g < nlines && s->first_displayed_entry->idx == 0)
3887 s->selected = g - 1;
3889 select_commit(s);
3890 return NULL;
3894 static void
3895 horizontal_scroll_input(struct tog_view *view, int ch)
3898 switch (ch) {
3899 case KEY_LEFT:
3900 case 'h':
3901 view->x -= MIN(view->x, 2);
3902 if (view->x <= 0)
3903 view->count = 0;
3904 break;
3905 case KEY_RIGHT:
3906 case 'l':
3907 if (view->x + view->ncols / 2 < view->maxx)
3908 view->x += 2;
3909 else
3910 view->count = 0;
3911 break;
3912 case '0':
3913 view->x = 0;
3914 break;
3915 case '$':
3916 view->x = MAX(view->maxx - view->ncols / 2, 0);
3917 view->count = 0;
3918 break;
3919 default:
3920 break;
3924 static const struct got_error *
3925 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3927 const struct got_error *err = NULL;
3928 struct tog_log_view_state *s = &view->state.log;
3929 int eos, nscroll;
3931 if (s->thread_args.load_all) {
3932 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3933 s->thread_args.load_all = 0;
3934 else if (s->thread_args.log_complete) {
3935 err = log_move_cursor_down(view, s->commits->ncommits);
3936 s->thread_args.load_all = 0;
3938 if (err)
3939 return err;
3942 eos = nscroll = view->nlines - 1;
3943 if (view_is_hsplit_top(view))
3944 --eos; /* border */
3946 if (view->gline)
3947 return log_goto_line(view, eos);
3949 switch (ch) {
3950 case '&':
3951 err = limit_log_view(view);
3952 break;
3953 case 'q':
3954 s->quit = 1;
3955 break;
3956 case '0':
3957 case '$':
3958 case KEY_RIGHT:
3959 case 'l':
3960 case KEY_LEFT:
3961 case 'h':
3962 horizontal_scroll_input(view, ch);
3963 break;
3964 case 'k':
3965 case KEY_UP:
3966 case '<':
3967 case ',':
3968 case CTRL('p'):
3969 log_move_cursor_up(view, 0, 0);
3970 break;
3971 case 'g':
3972 case '=':
3973 case KEY_HOME:
3974 log_move_cursor_up(view, 0, 1);
3975 view->count = 0;
3976 break;
3977 case CTRL('u'):
3978 case 'u':
3979 nscroll /= 2;
3980 /* FALL THROUGH */
3981 case KEY_PPAGE:
3982 case CTRL('b'):
3983 case 'b':
3984 log_move_cursor_up(view, nscroll, 0);
3985 break;
3986 case 'j':
3987 case KEY_DOWN:
3988 case '>':
3989 case '.':
3990 case CTRL('n'):
3991 err = log_move_cursor_down(view, 0);
3992 break;
3993 case '@':
3994 s->use_committer = !s->use_committer;
3995 view->action = s->use_committer ?
3996 "show committer" : "show commit author";
3997 break;
3998 case 'G':
3999 case '*':
4000 case KEY_END: {
4001 /* We don't know yet how many commits, so we're forced to
4002 * traverse them all. */
4003 view->count = 0;
4004 s->thread_args.load_all = 1;
4005 if (!s->thread_args.log_complete)
4006 return trigger_log_thread(view, 0);
4007 err = log_move_cursor_down(view, s->commits->ncommits);
4008 s->thread_args.load_all = 0;
4009 break;
4011 case CTRL('d'):
4012 case 'd':
4013 nscroll /= 2;
4014 /* FALL THROUGH */
4015 case KEY_NPAGE:
4016 case CTRL('f'):
4017 case 'f':
4018 case ' ':
4019 err = log_move_cursor_down(view, nscroll);
4020 break;
4021 case KEY_RESIZE:
4022 if (s->selected > view->nlines - 2)
4023 s->selected = view->nlines - 2;
4024 if (s->selected > s->commits->ncommits - 1)
4025 s->selected = s->commits->ncommits - 1;
4026 select_commit(s);
4027 if (s->commits->ncommits < view->nlines - 1 &&
4028 !s->thread_args.log_complete) {
4029 s->thread_args.commits_needed += (view->nlines - 1) -
4030 s->commits->ncommits;
4031 err = trigger_log_thread(view, 1);
4033 break;
4034 case KEY_ENTER:
4035 case '\r':
4036 view->count = 0;
4037 if (s->selected_entry == NULL)
4038 break;
4039 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4040 break;
4041 case 'T':
4042 view->count = 0;
4043 if (s->selected_entry == NULL)
4044 break;
4045 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4046 break;
4047 case KEY_BACKSPACE:
4048 case CTRL('l'):
4049 case 'B':
4050 view->count = 0;
4051 if (ch == KEY_BACKSPACE &&
4052 got_path_is_root_dir(s->in_repo_path))
4053 break;
4054 err = stop_log_thread(s);
4055 if (err)
4056 return err;
4057 if (ch == KEY_BACKSPACE) {
4058 char *parent_path;
4059 err = got_path_dirname(&parent_path, s->in_repo_path);
4060 if (err)
4061 return err;
4062 free(s->in_repo_path);
4063 s->in_repo_path = parent_path;
4064 s->thread_args.in_repo_path = s->in_repo_path;
4065 } else if (ch == CTRL('l')) {
4066 struct got_object_id *start_id;
4067 err = got_repo_match_object_id(&start_id, NULL,
4068 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4069 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4070 if (err) {
4071 if (s->head_ref_name == NULL ||
4072 err->code != GOT_ERR_NOT_REF)
4073 return err;
4074 /* Try to cope with deleted references. */
4075 free(s->head_ref_name);
4076 s->head_ref_name = NULL;
4077 err = got_repo_match_object_id(&start_id,
4078 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4079 &tog_refs, s->repo);
4080 if (err)
4081 return err;
4083 free(s->start_id);
4084 s->start_id = start_id;
4085 s->thread_args.start_id = s->start_id;
4086 } else /* 'B' */
4087 s->log_branches = !s->log_branches;
4089 if (s->thread_args.pack_fds == NULL) {
4090 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4091 if (err)
4092 return err;
4094 err = got_repo_open(&s->thread_args.repo,
4095 got_repo_get_path(s->repo), NULL,
4096 s->thread_args.pack_fds);
4097 if (err)
4098 return err;
4099 tog_free_refs();
4100 err = tog_load_refs(s->repo, 0);
4101 if (err)
4102 return err;
4103 err = got_commit_graph_open(&s->thread_args.graph,
4104 s->in_repo_path, !s->log_branches);
4105 if (err)
4106 return err;
4107 err = got_commit_graph_iter_start(s->thread_args.graph,
4108 s->start_id, s->repo, NULL, NULL);
4109 if (err)
4110 return err;
4111 free_commits(&s->real_commits);
4112 free_commits(&s->limit_commits);
4113 s->first_displayed_entry = NULL;
4114 s->last_displayed_entry = NULL;
4115 s->selected_entry = NULL;
4116 s->selected = 0;
4117 s->thread_args.log_complete = 0;
4118 s->quit = 0;
4119 s->thread_args.commits_needed = view->lines;
4120 s->matched_entry = NULL;
4121 s->search_entry = NULL;
4122 view->offset = 0;
4123 break;
4124 case 'R':
4125 view->count = 0;
4126 err = view_request_new(new_view, view, TOG_VIEW_REF);
4127 break;
4128 default:
4129 view->count = 0;
4130 break;
4133 return err;
4136 static const struct got_error *
4137 apply_unveil(const char *repo_path, const char *worktree_path)
4139 const struct got_error *error;
4141 #ifdef PROFILE
4142 if (unveil("gmon.out", "rwc") != 0)
4143 return got_error_from_errno2("unveil", "gmon.out");
4144 #endif
4145 if (repo_path && unveil(repo_path, "r") != 0)
4146 return got_error_from_errno2("unveil", repo_path);
4148 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4149 return got_error_from_errno2("unveil", worktree_path);
4151 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4152 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4154 error = got_privsep_unveil_exec_helpers();
4155 if (error != NULL)
4156 return error;
4158 if (unveil(NULL, NULL) != 0)
4159 return got_error_from_errno("unveil");
4161 return NULL;
4164 static const struct got_error *
4165 init_mock_term(const char *test_script_path)
4167 const struct got_error *err = NULL;
4169 if (test_script_path == NULL || *test_script_path == '\0')
4170 return got_error_msg(GOT_ERR_IO, "GOT_TOG_TEST not defined");
4172 tog_io.f = fopen(test_script_path, "re");
4173 if (tog_io.f == NULL) {
4174 err = got_error_from_errno_fmt("fopen: %s",
4175 test_script_path);
4176 goto done;
4179 /* test mode, we don't want any output */
4180 tog_io.cout = fopen("/dev/null", "w+");
4181 if (tog_io.cout == NULL) {
4182 err = got_error_from_errno("fopen: /dev/null");
4183 goto done;
4186 tog_io.cin = fopen("/dev/tty", "r+");
4187 if (tog_io.cin == NULL) {
4188 err = got_error_from_errno("fopen: /dev/tty");
4189 goto done;
4192 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4193 err = got_error_from_errno("fseeko");
4194 goto done;
4197 /* use local TERM so we test in different environments */
4198 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4199 err = got_error_msg(GOT_ERR_IO,
4200 "newterm: failed to initialise curses");
4202 using_mock_io = 1;
4203 done:
4204 if (err)
4205 tog_io_close();
4206 return err;
4209 static void
4210 init_curses(void)
4213 * Override default signal handlers before starting ncurses.
4214 * This should prevent ncurses from installing its own
4215 * broken cleanup() signal handler.
4217 signal(SIGWINCH, tog_sigwinch);
4218 signal(SIGPIPE, tog_sigpipe);
4219 signal(SIGCONT, tog_sigcont);
4220 signal(SIGINT, tog_sigint);
4221 signal(SIGTERM, tog_sigterm);
4223 if (using_mock_io) /* In test mode we use a fake terminal */
4224 return;
4226 initscr();
4228 cbreak();
4229 halfdelay(1); /* Fast refresh while initial view is loading. */
4230 noecho();
4231 nonl();
4232 intrflush(stdscr, FALSE);
4233 keypad(stdscr, TRUE);
4234 curs_set(0);
4235 if (getenv("TOG_COLORS") != NULL) {
4236 start_color();
4237 use_default_colors();
4240 return;
4243 static const struct got_error *
4244 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4245 struct got_repository *repo, struct got_worktree *worktree)
4247 const struct got_error *err = NULL;
4249 if (argc == 0) {
4250 *in_repo_path = strdup("/");
4251 if (*in_repo_path == NULL)
4252 return got_error_from_errno("strdup");
4253 return NULL;
4256 if (worktree) {
4257 const char *prefix = got_worktree_get_path_prefix(worktree);
4258 char *p;
4260 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4261 if (err)
4262 return err;
4263 if (asprintf(in_repo_path, "%s%s%s", prefix,
4264 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4265 p) == -1) {
4266 err = got_error_from_errno("asprintf");
4267 *in_repo_path = NULL;
4269 free(p);
4270 } else
4271 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4273 return err;
4276 static const struct got_error *
4277 cmd_log(int argc, char *argv[])
4279 const struct got_error *error;
4280 struct got_repository *repo = NULL;
4281 struct got_worktree *worktree = NULL;
4282 struct got_object_id *start_id = NULL;
4283 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4284 char *start_commit = NULL, *label = NULL;
4285 struct got_reference *ref = NULL;
4286 const char *head_ref_name = NULL;
4287 int ch, log_branches = 0;
4288 struct tog_view *view;
4289 int *pack_fds = NULL;
4291 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4292 switch (ch) {
4293 case 'b':
4294 log_branches = 1;
4295 break;
4296 case 'c':
4297 start_commit = optarg;
4298 break;
4299 case 'r':
4300 repo_path = realpath(optarg, NULL);
4301 if (repo_path == NULL)
4302 return got_error_from_errno2("realpath",
4303 optarg);
4304 break;
4305 default:
4306 usage_log();
4307 /* NOTREACHED */
4311 argc -= optind;
4312 argv += optind;
4314 if (argc > 1)
4315 usage_log();
4317 error = got_repo_pack_fds_open(&pack_fds);
4318 if (error != NULL)
4319 goto done;
4321 if (repo_path == NULL) {
4322 cwd = getcwd(NULL, 0);
4323 if (cwd == NULL)
4324 return got_error_from_errno("getcwd");
4325 error = got_worktree_open(&worktree, cwd);
4326 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4327 goto done;
4328 if (worktree)
4329 repo_path =
4330 strdup(got_worktree_get_repo_path(worktree));
4331 else
4332 repo_path = strdup(cwd);
4333 if (repo_path == NULL) {
4334 error = got_error_from_errno("strdup");
4335 goto done;
4339 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4340 if (error != NULL)
4341 goto done;
4343 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4344 repo, worktree);
4345 if (error)
4346 goto done;
4348 init_curses();
4350 error = apply_unveil(got_repo_get_path(repo),
4351 worktree ? got_worktree_get_root_path(worktree) : NULL);
4352 if (error)
4353 goto done;
4355 /* already loaded by tog_log_with_path()? */
4356 if (TAILQ_EMPTY(&tog_refs)) {
4357 error = tog_load_refs(repo, 0);
4358 if (error)
4359 goto done;
4362 if (start_commit == NULL) {
4363 error = got_repo_match_object_id(&start_id, &label,
4364 worktree ? got_worktree_get_head_ref_name(worktree) :
4365 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4366 if (error)
4367 goto done;
4368 head_ref_name = label;
4369 } else {
4370 error = got_ref_open(&ref, repo, start_commit, 0);
4371 if (error == NULL)
4372 head_ref_name = got_ref_get_name(ref);
4373 else if (error->code != GOT_ERR_NOT_REF)
4374 goto done;
4375 error = got_repo_match_object_id(&start_id, NULL,
4376 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4377 if (error)
4378 goto done;
4381 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4382 if (view == NULL) {
4383 error = got_error_from_errno("view_open");
4384 goto done;
4386 error = open_log_view(view, start_id, repo, head_ref_name,
4387 in_repo_path, log_branches);
4388 if (error)
4389 goto done;
4390 if (worktree) {
4391 /* Release work tree lock. */
4392 got_worktree_close(worktree);
4393 worktree = NULL;
4395 error = view_loop(view);
4396 done:
4397 free(in_repo_path);
4398 free(repo_path);
4399 free(cwd);
4400 free(start_id);
4401 free(label);
4402 if (ref)
4403 got_ref_close(ref);
4404 if (repo) {
4405 const struct got_error *close_err = got_repo_close(repo);
4406 if (error == NULL)
4407 error = close_err;
4409 if (worktree)
4410 got_worktree_close(worktree);
4411 if (pack_fds) {
4412 const struct got_error *pack_err =
4413 got_repo_pack_fds_close(pack_fds);
4414 if (error == NULL)
4415 error = pack_err;
4417 tog_free_refs();
4418 return error;
4421 __dead static void
4422 usage_diff(void)
4424 endwin();
4425 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4426 "object1 object2\n", getprogname());
4427 exit(1);
4430 static int
4431 match_line(const char *line, regex_t *regex, size_t nmatch,
4432 regmatch_t *regmatch)
4434 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4437 static struct tog_color *
4438 match_color(struct tog_colors *colors, const char *line)
4440 struct tog_color *tc = NULL;
4442 STAILQ_FOREACH(tc, colors, entry) {
4443 if (match_line(line, &tc->regex, 0, NULL))
4444 return tc;
4447 return NULL;
4450 static const struct got_error *
4451 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4452 WINDOW *window, int skipcol, regmatch_t *regmatch)
4454 const struct got_error *err = NULL;
4455 char *exstr = NULL;
4456 wchar_t *wline = NULL;
4457 int rme, rms, n, width, scrollx;
4458 int width0 = 0, width1 = 0, width2 = 0;
4459 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4461 *wtotal = 0;
4463 rms = regmatch->rm_so;
4464 rme = regmatch->rm_eo;
4466 err = expand_tab(&exstr, line);
4467 if (err)
4468 return err;
4470 /* Split the line into 3 segments, according to match offsets. */
4471 seg0 = strndup(exstr, rms);
4472 if (seg0 == NULL) {
4473 err = got_error_from_errno("strndup");
4474 goto done;
4476 seg1 = strndup(exstr + rms, rme - rms);
4477 if (seg1 == NULL) {
4478 err = got_error_from_errno("strndup");
4479 goto done;
4481 seg2 = strdup(exstr + rme);
4482 if (seg2 == NULL) {
4483 err = got_error_from_errno("strndup");
4484 goto done;
4487 /* draw up to matched token if we haven't scrolled past it */
4488 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4489 col_tab_align, 1);
4490 if (err)
4491 goto done;
4492 n = MAX(width0 - skipcol, 0);
4493 if (n) {
4494 free(wline);
4495 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4496 wlimit, col_tab_align, 1);
4497 if (err)
4498 goto done;
4499 waddwstr(window, &wline[scrollx]);
4500 wlimit -= width;
4501 *wtotal += width;
4504 if (wlimit > 0) {
4505 int i = 0, w = 0;
4506 size_t wlen;
4508 free(wline);
4509 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4510 col_tab_align, 1);
4511 if (err)
4512 goto done;
4513 wlen = wcslen(wline);
4514 while (i < wlen) {
4515 width = wcwidth(wline[i]);
4516 if (width == -1) {
4517 /* should not happen, tabs are expanded */
4518 err = got_error(GOT_ERR_RANGE);
4519 goto done;
4521 if (width0 + w + width > skipcol)
4522 break;
4523 w += width;
4524 i++;
4526 /* draw (visible part of) matched token (if scrolled into it) */
4527 if (width1 - w > 0) {
4528 wattron(window, A_STANDOUT);
4529 waddwstr(window, &wline[i]);
4530 wattroff(window, A_STANDOUT);
4531 wlimit -= (width1 - w);
4532 *wtotal += (width1 - w);
4536 if (wlimit > 0) { /* draw rest of line */
4537 free(wline);
4538 if (skipcol > width0 + width1) {
4539 err = format_line(&wline, &width2, &scrollx, seg2,
4540 skipcol - (width0 + width1), wlimit,
4541 col_tab_align, 1);
4542 if (err)
4543 goto done;
4544 waddwstr(window, &wline[scrollx]);
4545 } else {
4546 err = format_line(&wline, &width2, NULL, seg2, 0,
4547 wlimit, col_tab_align, 1);
4548 if (err)
4549 goto done;
4550 waddwstr(window, wline);
4552 *wtotal += width2;
4554 done:
4555 free(wline);
4556 free(exstr);
4557 free(seg0);
4558 free(seg1);
4559 free(seg2);
4560 return err;
4563 static int
4564 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4566 FILE *f = NULL;
4567 int *eof, *first, *selected;
4569 if (view->type == TOG_VIEW_DIFF) {
4570 struct tog_diff_view_state *s = &view->state.diff;
4572 first = &s->first_displayed_line;
4573 selected = first;
4574 eof = &s->eof;
4575 f = s->f;
4576 } else if (view->type == TOG_VIEW_HELP) {
4577 struct tog_help_view_state *s = &view->state.help;
4579 first = &s->first_displayed_line;
4580 selected = first;
4581 eof = &s->eof;
4582 f = s->f;
4583 } else if (view->type == TOG_VIEW_BLAME) {
4584 struct tog_blame_view_state *s = &view->state.blame;
4586 first = &s->first_displayed_line;
4587 selected = &s->selected_line;
4588 eof = &s->eof;
4589 f = s->blame.f;
4590 } else
4591 return 0;
4593 /* Center gline in the middle of the page like vi(1). */
4594 if (*lineno < view->gline - (view->nlines - 3) / 2)
4595 return 0;
4596 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4597 rewind(f);
4598 *eof = 0;
4599 *first = 1;
4600 *lineno = 0;
4601 *nprinted = 0;
4602 return 0;
4605 *selected = view->gline <= (view->nlines - 3) / 2 ?
4606 view->gline : (view->nlines - 3) / 2 + 1;
4607 view->gline = 0;
4609 return 1;
4612 static const struct got_error *
4613 draw_file(struct tog_view *view, const char *header)
4615 struct tog_diff_view_state *s = &view->state.diff;
4616 regmatch_t *regmatch = &view->regmatch;
4617 const struct got_error *err;
4618 int nprinted = 0;
4619 char *line;
4620 size_t linesize = 0;
4621 ssize_t linelen;
4622 wchar_t *wline;
4623 int width;
4624 int max_lines = view->nlines;
4625 int nlines = s->nlines;
4626 off_t line_offset;
4628 s->lineno = s->first_displayed_line - 1;
4629 line_offset = s->lines[s->first_displayed_line - 1].offset;
4630 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4631 return got_error_from_errno("fseek");
4633 werase(view->window);
4635 if (view->gline > s->nlines - 1)
4636 view->gline = s->nlines - 1;
4638 if (header) {
4639 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4640 1 : view->gline - (view->nlines - 3) / 2 :
4641 s->lineno + s->selected_line;
4643 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4644 return got_error_from_errno("asprintf");
4645 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4646 0, 0);
4647 free(line);
4648 if (err)
4649 return err;
4651 if (view_needs_focus_indication(view))
4652 wstandout(view->window);
4653 waddwstr(view->window, wline);
4654 free(wline);
4655 wline = NULL;
4656 while (width++ < view->ncols)
4657 waddch(view->window, ' ');
4658 if (view_needs_focus_indication(view))
4659 wstandend(view->window);
4661 if (max_lines <= 1)
4662 return NULL;
4663 max_lines--;
4666 s->eof = 0;
4667 view->maxx = 0;
4668 line = NULL;
4669 while (max_lines > 0 && nprinted < max_lines) {
4670 enum got_diff_line_type linetype;
4671 attr_t attr = 0;
4673 linelen = getline(&line, &linesize, s->f);
4674 if (linelen == -1) {
4675 if (feof(s->f)) {
4676 s->eof = 1;
4677 break;
4679 free(line);
4680 return got_ferror(s->f, GOT_ERR_IO);
4683 if (++s->lineno < s->first_displayed_line)
4684 continue;
4685 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4686 continue;
4687 if (s->lineno == view->hiline)
4688 attr = A_STANDOUT;
4690 /* Set view->maxx based on full line length. */
4691 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4692 view->x ? 1 : 0);
4693 if (err) {
4694 free(line);
4695 return err;
4697 view->maxx = MAX(view->maxx, width);
4698 free(wline);
4699 wline = NULL;
4701 linetype = s->lines[s->lineno].type;
4702 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4703 linetype < GOT_DIFF_LINE_CONTEXT)
4704 attr |= COLOR_PAIR(linetype);
4705 if (attr)
4706 wattron(view->window, attr);
4707 if (s->first_displayed_line + nprinted == s->matched_line &&
4708 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4709 err = add_matched_line(&width, line, view->ncols, 0,
4710 view->window, view->x, regmatch);
4711 if (err) {
4712 free(line);
4713 return err;
4715 } else {
4716 int skip;
4717 err = format_line(&wline, &width, &skip, line,
4718 view->x, view->ncols, 0, view->x ? 1 : 0);
4719 if (err) {
4720 free(line);
4721 return err;
4723 waddwstr(view->window, &wline[skip]);
4724 free(wline);
4725 wline = NULL;
4727 if (s->lineno == view->hiline) {
4728 /* highlight full gline length */
4729 while (width++ < view->ncols)
4730 waddch(view->window, ' ');
4731 } else {
4732 if (width <= view->ncols - 1)
4733 waddch(view->window, '\n');
4735 if (attr)
4736 wattroff(view->window, attr);
4737 if (++nprinted == 1)
4738 s->first_displayed_line = s->lineno;
4740 free(line);
4741 if (nprinted >= 1)
4742 s->last_displayed_line = s->first_displayed_line +
4743 (nprinted - 1);
4744 else
4745 s->last_displayed_line = s->first_displayed_line;
4747 view_border(view);
4749 if (s->eof) {
4750 while (nprinted < view->nlines) {
4751 waddch(view->window, '\n');
4752 nprinted++;
4755 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4756 view->ncols, 0, 0);
4757 if (err) {
4758 return err;
4761 wstandout(view->window);
4762 waddwstr(view->window, wline);
4763 free(wline);
4764 wline = NULL;
4765 wstandend(view->window);
4768 return NULL;
4771 static char *
4772 get_datestr(time_t *time, char *datebuf)
4774 struct tm mytm, *tm;
4775 char *p, *s;
4777 tm = gmtime_r(time, &mytm);
4778 if (tm == NULL)
4779 return NULL;
4780 s = asctime_r(tm, datebuf);
4781 if (s == NULL)
4782 return NULL;
4783 p = strchr(s, '\n');
4784 if (p)
4785 *p = '\0';
4786 return s;
4789 static const struct got_error *
4790 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4791 off_t off, uint8_t type)
4793 struct got_diff_line *p;
4795 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4796 if (p == NULL)
4797 return got_error_from_errno("reallocarray");
4798 *lines = p;
4799 (*lines)[*nlines].offset = off;
4800 (*lines)[*nlines].type = type;
4801 (*nlines)++;
4803 return NULL;
4806 static const struct got_error *
4807 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4808 struct got_diff_line *s_lines, size_t s_nlines)
4810 struct got_diff_line *p;
4811 char buf[BUFSIZ];
4812 size_t i, r;
4814 if (fseeko(src, 0L, SEEK_SET) == -1)
4815 return got_error_from_errno("fseeko");
4817 for (;;) {
4818 r = fread(buf, 1, sizeof(buf), src);
4819 if (r == 0) {
4820 if (ferror(src))
4821 return got_error_from_errno("fread");
4822 if (feof(src))
4823 break;
4825 if (fwrite(buf, 1, r, dst) != r)
4826 return got_ferror(dst, GOT_ERR_IO);
4829 if (s_nlines == 0 && *d_nlines == 0)
4830 return NULL;
4833 * If commit info was in dst, increment line offsets
4834 * of the appended diff content, but skip s_lines[0]
4835 * because offset zero is already in *d_lines.
4837 if (*d_nlines > 0) {
4838 for (i = 1; i < s_nlines; ++i)
4839 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4841 if (s_nlines > 0) {
4842 --s_nlines;
4843 ++s_lines;
4847 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4848 if (p == NULL) {
4849 /* d_lines is freed in close_diff_view() */
4850 return got_error_from_errno("reallocarray");
4853 *d_lines = p;
4855 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4856 *d_nlines += s_nlines;
4858 return NULL;
4861 static const struct got_error *
4862 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4863 struct got_object_id *commit_id, struct got_reflist_head *refs,
4864 struct got_repository *repo, int ignore_ws, int force_text_diff,
4865 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4867 const struct got_error *err = NULL;
4868 char datebuf[26], *datestr;
4869 struct got_commit_object *commit;
4870 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4871 time_t committer_time;
4872 const char *author, *committer;
4873 char *refs_str = NULL;
4874 struct got_pathlist_entry *pe;
4875 off_t outoff = 0;
4876 int n;
4878 if (refs) {
4879 err = build_refs_str(&refs_str, refs, commit_id, repo);
4880 if (err)
4881 return err;
4884 err = got_object_open_as_commit(&commit, repo, commit_id);
4885 if (err)
4886 return err;
4888 err = got_object_id_str(&id_str, commit_id);
4889 if (err) {
4890 err = got_error_from_errno("got_object_id_str");
4891 goto done;
4894 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4895 if (err)
4896 goto done;
4898 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4899 refs_str ? refs_str : "", refs_str ? ")" : "");
4900 if (n < 0) {
4901 err = got_error_from_errno("fprintf");
4902 goto done;
4904 outoff += n;
4905 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4906 if (err)
4907 goto done;
4909 n = fprintf(outfile, "from: %s\n",
4910 got_object_commit_get_author(commit));
4911 if (n < 0) {
4912 err = got_error_from_errno("fprintf");
4913 goto done;
4915 outoff += n;
4916 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4917 if (err)
4918 goto done;
4920 author = got_object_commit_get_author(commit);
4921 committer = got_object_commit_get_committer(commit);
4922 if (strcmp(author, committer) != 0) {
4923 n = fprintf(outfile, "via: %s\n", committer);
4924 if (n < 0) {
4925 err = got_error_from_errno("fprintf");
4926 goto done;
4928 outoff += n;
4929 err = add_line_metadata(lines, nlines, outoff,
4930 GOT_DIFF_LINE_AUTHOR);
4931 if (err)
4932 goto done;
4934 committer_time = got_object_commit_get_committer_time(commit);
4935 datestr = get_datestr(&committer_time, datebuf);
4936 if (datestr) {
4937 n = fprintf(outfile, "date: %s UTC\n", datestr);
4938 if (n < 0) {
4939 err = got_error_from_errno("fprintf");
4940 goto done;
4942 outoff += n;
4943 err = add_line_metadata(lines, nlines, outoff,
4944 GOT_DIFF_LINE_DATE);
4945 if (err)
4946 goto done;
4948 if (got_object_commit_get_nparents(commit) > 1) {
4949 const struct got_object_id_queue *parent_ids;
4950 struct got_object_qid *qid;
4951 int pn = 1;
4952 parent_ids = got_object_commit_get_parent_ids(commit);
4953 STAILQ_FOREACH(qid, parent_ids, entry) {
4954 err = got_object_id_str(&id_str, &qid->id);
4955 if (err)
4956 goto done;
4957 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4958 if (n < 0) {
4959 err = got_error_from_errno("fprintf");
4960 goto done;
4962 outoff += n;
4963 err = add_line_metadata(lines, nlines, outoff,
4964 GOT_DIFF_LINE_META);
4965 if (err)
4966 goto done;
4967 free(id_str);
4968 id_str = NULL;
4972 err = got_object_commit_get_logmsg(&logmsg, commit);
4973 if (err)
4974 goto done;
4975 s = logmsg;
4976 while ((line = strsep(&s, "\n")) != NULL) {
4977 n = fprintf(outfile, "%s\n", line);
4978 if (n < 0) {
4979 err = got_error_from_errno("fprintf");
4980 goto done;
4982 outoff += n;
4983 err = add_line_metadata(lines, nlines, outoff,
4984 GOT_DIFF_LINE_LOGMSG);
4985 if (err)
4986 goto done;
4989 TAILQ_FOREACH(pe, dsa->paths, entry) {
4990 struct got_diff_changed_path *cp = pe->data;
4991 int pad = dsa->max_path_len - pe->path_len + 1;
4993 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4994 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4995 dsa->rm_cols + 1, cp->rm);
4996 if (n < 0) {
4997 err = got_error_from_errno("fprintf");
4998 goto done;
5000 outoff += n;
5001 err = add_line_metadata(lines, nlines, outoff,
5002 GOT_DIFF_LINE_CHANGES);
5003 if (err)
5004 goto done;
5007 fputc('\n', outfile);
5008 outoff++;
5009 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5010 if (err)
5011 goto done;
5013 n = fprintf(outfile,
5014 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5015 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5016 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5017 if (n < 0) {
5018 err = got_error_from_errno("fprintf");
5019 goto done;
5021 outoff += n;
5022 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5023 if (err)
5024 goto done;
5026 fputc('\n', outfile);
5027 outoff++;
5028 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5029 done:
5030 free(id_str);
5031 free(logmsg);
5032 free(refs_str);
5033 got_object_commit_close(commit);
5034 if (err) {
5035 free(*lines);
5036 *lines = NULL;
5037 *nlines = 0;
5039 return err;
5042 static const struct got_error *
5043 create_diff(struct tog_diff_view_state *s)
5045 const struct got_error *err = NULL;
5046 FILE *f = NULL, *tmp_diff_file = NULL;
5047 int obj_type;
5048 struct got_diff_line *lines = NULL;
5049 struct got_pathlist_head changed_paths;
5051 TAILQ_INIT(&changed_paths);
5053 free(s->lines);
5054 s->lines = malloc(sizeof(*s->lines));
5055 if (s->lines == NULL)
5056 return got_error_from_errno("malloc");
5057 s->nlines = 0;
5059 f = got_opentemp();
5060 if (f == NULL) {
5061 err = got_error_from_errno("got_opentemp");
5062 goto done;
5064 tmp_diff_file = got_opentemp();
5065 if (tmp_diff_file == NULL) {
5066 err = got_error_from_errno("got_opentemp");
5067 goto done;
5069 if (s->f && fclose(s->f) == EOF) {
5070 err = got_error_from_errno("fclose");
5071 goto done;
5073 s->f = f;
5075 if (s->id1)
5076 err = got_object_get_type(&obj_type, s->repo, s->id1);
5077 else
5078 err = got_object_get_type(&obj_type, s->repo, s->id2);
5079 if (err)
5080 goto done;
5082 switch (obj_type) {
5083 case GOT_OBJ_TYPE_BLOB:
5084 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5085 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5086 s->label1, s->label2, tog_diff_algo, s->diff_context,
5087 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5088 s->f);
5089 break;
5090 case GOT_OBJ_TYPE_TREE:
5091 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5092 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5093 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5094 s->force_text_diff, NULL, s->repo, s->f);
5095 break;
5096 case GOT_OBJ_TYPE_COMMIT: {
5097 const struct got_object_id_queue *parent_ids;
5098 struct got_object_qid *pid;
5099 struct got_commit_object *commit2;
5100 struct got_reflist_head *refs;
5101 size_t nlines = 0;
5102 struct got_diffstat_cb_arg dsa = {
5103 0, 0, 0, 0, 0, 0,
5104 &changed_paths,
5105 s->ignore_whitespace,
5106 s->force_text_diff,
5107 tog_diff_algo
5110 lines = malloc(sizeof(*lines));
5111 if (lines == NULL) {
5112 err = got_error_from_errno("malloc");
5113 goto done;
5116 /* build diff first in tmp file then append to commit info */
5117 err = got_diff_objects_as_commits(&lines, &nlines,
5118 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5119 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5120 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5121 if (err)
5122 break;
5124 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5125 if (err)
5126 goto done;
5127 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5128 /* Show commit info if we're diffing to a parent/root commit. */
5129 if (s->id1 == NULL) {
5130 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5131 refs, s->repo, s->ignore_whitespace,
5132 s->force_text_diff, &dsa, s->f);
5133 if (err)
5134 goto done;
5135 } else {
5136 parent_ids = got_object_commit_get_parent_ids(commit2);
5137 STAILQ_FOREACH(pid, parent_ids, entry) {
5138 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5139 err = write_commit_info(&s->lines,
5140 &s->nlines, s->id2, refs, s->repo,
5141 s->ignore_whitespace,
5142 s->force_text_diff, &dsa, s->f);
5143 if (err)
5144 goto done;
5145 break;
5149 got_object_commit_close(commit2);
5151 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5152 lines, nlines);
5153 break;
5155 default:
5156 err = got_error(GOT_ERR_OBJ_TYPE);
5157 break;
5159 done:
5160 free(lines);
5161 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5162 if (s->f && fflush(s->f) != 0 && err == NULL)
5163 err = got_error_from_errno("fflush");
5164 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5165 err = got_error_from_errno("fclose");
5166 return err;
5169 static void
5170 diff_view_indicate_progress(struct tog_view *view)
5172 mvwaddstr(view->window, 0, 0, "diffing...");
5173 update_panels();
5174 doupdate();
5177 static const struct got_error *
5178 search_start_diff_view(struct tog_view *view)
5180 struct tog_diff_view_state *s = &view->state.diff;
5182 s->matched_line = 0;
5183 return NULL;
5186 static void
5187 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5188 size_t *nlines, int **first, int **last, int **match, int **selected)
5190 struct tog_diff_view_state *s = &view->state.diff;
5192 *f = s->f;
5193 *nlines = s->nlines;
5194 *line_offsets = NULL;
5195 *match = &s->matched_line;
5196 *first = &s->first_displayed_line;
5197 *last = &s->last_displayed_line;
5198 *selected = &s->selected_line;
5201 static const struct got_error *
5202 search_next_view_match(struct tog_view *view)
5204 const struct got_error *err = NULL;
5205 FILE *f;
5206 int lineno;
5207 char *line = NULL;
5208 size_t linesize = 0;
5209 ssize_t linelen;
5210 off_t *line_offsets;
5211 size_t nlines = 0;
5212 int *first, *last, *match, *selected;
5214 if (!view->search_setup)
5215 return got_error_msg(GOT_ERR_NOT_IMPL,
5216 "view search not supported");
5217 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5218 &match, &selected);
5220 if (!view->searching) {
5221 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5222 return NULL;
5225 if (*match) {
5226 if (view->searching == TOG_SEARCH_FORWARD)
5227 lineno = *first + 1;
5228 else
5229 lineno = *first - 1;
5230 } else
5231 lineno = *first - 1 + *selected;
5233 while (1) {
5234 off_t offset;
5236 if (lineno <= 0 || lineno > nlines) {
5237 if (*match == 0) {
5238 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5239 break;
5242 if (view->searching == TOG_SEARCH_FORWARD)
5243 lineno = 1;
5244 else
5245 lineno = nlines;
5248 offset = view->type == TOG_VIEW_DIFF ?
5249 view->state.diff.lines[lineno - 1].offset :
5250 line_offsets[lineno - 1];
5251 if (fseeko(f, offset, SEEK_SET) != 0) {
5252 free(line);
5253 return got_error_from_errno("fseeko");
5255 linelen = getline(&line, &linesize, f);
5256 if (linelen != -1) {
5257 char *exstr;
5258 err = expand_tab(&exstr, line);
5259 if (err)
5260 break;
5261 if (match_line(exstr, &view->regex, 1,
5262 &view->regmatch)) {
5263 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5264 *match = lineno;
5265 free(exstr);
5266 break;
5268 free(exstr);
5270 if (view->searching == TOG_SEARCH_FORWARD)
5271 lineno++;
5272 else
5273 lineno--;
5275 free(line);
5277 if (*match) {
5278 *first = *match;
5279 *selected = 1;
5282 return err;
5285 static const struct got_error *
5286 close_diff_view(struct tog_view *view)
5288 const struct got_error *err = NULL;
5289 struct tog_diff_view_state *s = &view->state.diff;
5291 free(s->id1);
5292 s->id1 = NULL;
5293 free(s->id2);
5294 s->id2 = NULL;
5295 if (s->f && fclose(s->f) == EOF)
5296 err = got_error_from_errno("fclose");
5297 s->f = NULL;
5298 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5299 err = got_error_from_errno("fclose");
5300 s->f1 = NULL;
5301 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5302 err = got_error_from_errno("fclose");
5303 s->f2 = NULL;
5304 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5305 err = got_error_from_errno("close");
5306 s->fd1 = -1;
5307 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5308 err = got_error_from_errno("close");
5309 s->fd2 = -1;
5310 free(s->lines);
5311 s->lines = NULL;
5312 s->nlines = 0;
5313 return err;
5316 static const struct got_error *
5317 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5318 struct got_object_id *id2, const char *label1, const char *label2,
5319 int diff_context, int ignore_whitespace, int force_text_diff,
5320 struct tog_view *parent_view, struct got_repository *repo)
5322 const struct got_error *err;
5323 struct tog_diff_view_state *s = &view->state.diff;
5325 memset(s, 0, sizeof(*s));
5326 s->fd1 = -1;
5327 s->fd2 = -1;
5329 if (id1 != NULL && id2 != NULL) {
5330 int type1, type2;
5332 err = got_object_get_type(&type1, repo, id1);
5333 if (err)
5334 goto done;
5335 err = got_object_get_type(&type2, repo, id2);
5336 if (err)
5337 goto done;
5339 if (type1 != type2) {
5340 err = got_error(GOT_ERR_OBJ_TYPE);
5341 goto done;
5344 s->first_displayed_line = 1;
5345 s->last_displayed_line = view->nlines;
5346 s->selected_line = 1;
5347 s->repo = repo;
5348 s->id1 = id1;
5349 s->id2 = id2;
5350 s->label1 = label1;
5351 s->label2 = label2;
5353 if (id1) {
5354 s->id1 = got_object_id_dup(id1);
5355 if (s->id1 == NULL) {
5356 err = got_error_from_errno("got_object_id_dup");
5357 goto done;
5359 } else
5360 s->id1 = NULL;
5362 s->id2 = got_object_id_dup(id2);
5363 if (s->id2 == NULL) {
5364 err = got_error_from_errno("got_object_id_dup");
5365 goto done;
5368 s->f1 = got_opentemp();
5369 if (s->f1 == NULL) {
5370 err = got_error_from_errno("got_opentemp");
5371 goto done;
5374 s->f2 = got_opentemp();
5375 if (s->f2 == NULL) {
5376 err = got_error_from_errno("got_opentemp");
5377 goto done;
5380 s->fd1 = got_opentempfd();
5381 if (s->fd1 == -1) {
5382 err = got_error_from_errno("got_opentempfd");
5383 goto done;
5386 s->fd2 = got_opentempfd();
5387 if (s->fd2 == -1) {
5388 err = got_error_from_errno("got_opentempfd");
5389 goto done;
5392 s->diff_context = diff_context;
5393 s->ignore_whitespace = ignore_whitespace;
5394 s->force_text_diff = force_text_diff;
5395 s->parent_view = parent_view;
5396 s->repo = repo;
5398 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5399 int rc;
5401 rc = init_pair(GOT_DIFF_LINE_MINUS,
5402 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5403 if (rc != ERR)
5404 rc = init_pair(GOT_DIFF_LINE_PLUS,
5405 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5406 if (rc != ERR)
5407 rc = init_pair(GOT_DIFF_LINE_HUNK,
5408 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5409 if (rc != ERR)
5410 rc = init_pair(GOT_DIFF_LINE_META,
5411 get_color_value("TOG_COLOR_DIFF_META"), -1);
5412 if (rc != ERR)
5413 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5414 get_color_value("TOG_COLOR_DIFF_META"), -1);
5415 if (rc != ERR)
5416 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5417 get_color_value("TOG_COLOR_DIFF_META"), -1);
5418 if (rc != ERR)
5419 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5420 get_color_value("TOG_COLOR_DIFF_META"), -1);
5421 if (rc != ERR)
5422 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5423 get_color_value("TOG_COLOR_AUTHOR"), -1);
5424 if (rc != ERR)
5425 rc = init_pair(GOT_DIFF_LINE_DATE,
5426 get_color_value("TOG_COLOR_DATE"), -1);
5427 if (rc == ERR) {
5428 err = got_error(GOT_ERR_RANGE);
5429 goto done;
5433 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5434 view_is_splitscreen(view))
5435 show_log_view(parent_view); /* draw border */
5436 diff_view_indicate_progress(view);
5438 err = create_diff(s);
5440 view->show = show_diff_view;
5441 view->input = input_diff_view;
5442 view->reset = reset_diff_view;
5443 view->close = close_diff_view;
5444 view->search_start = search_start_diff_view;
5445 view->search_setup = search_setup_diff_view;
5446 view->search_next = search_next_view_match;
5447 done:
5448 if (err) {
5449 if (view->close == NULL)
5450 close_diff_view(view);
5451 view_close(view);
5453 return err;
5456 static const struct got_error *
5457 show_diff_view(struct tog_view *view)
5459 const struct got_error *err;
5460 struct tog_diff_view_state *s = &view->state.diff;
5461 char *id_str1 = NULL, *id_str2, *header;
5462 const char *label1, *label2;
5464 if (s->id1) {
5465 err = got_object_id_str(&id_str1, s->id1);
5466 if (err)
5467 return err;
5468 label1 = s->label1 ? s->label1 : id_str1;
5469 } else
5470 label1 = "/dev/null";
5472 err = got_object_id_str(&id_str2, s->id2);
5473 if (err)
5474 return err;
5475 label2 = s->label2 ? s->label2 : id_str2;
5477 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5478 err = got_error_from_errno("asprintf");
5479 free(id_str1);
5480 free(id_str2);
5481 return err;
5483 free(id_str1);
5484 free(id_str2);
5486 err = draw_file(view, header);
5487 free(header);
5488 return err;
5491 static const struct got_error *
5492 set_selected_commit(struct tog_diff_view_state *s,
5493 struct commit_queue_entry *entry)
5495 const struct got_error *err;
5496 const struct got_object_id_queue *parent_ids;
5497 struct got_commit_object *selected_commit;
5498 struct got_object_qid *pid;
5500 free(s->id2);
5501 s->id2 = got_object_id_dup(entry->id);
5502 if (s->id2 == NULL)
5503 return got_error_from_errno("got_object_id_dup");
5505 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5506 if (err)
5507 return err;
5508 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5509 free(s->id1);
5510 pid = STAILQ_FIRST(parent_ids);
5511 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5512 got_object_commit_close(selected_commit);
5513 return NULL;
5516 static const struct got_error *
5517 reset_diff_view(struct tog_view *view)
5519 struct tog_diff_view_state *s = &view->state.diff;
5521 view->count = 0;
5522 wclear(view->window);
5523 s->first_displayed_line = 1;
5524 s->last_displayed_line = view->nlines;
5525 s->matched_line = 0;
5526 diff_view_indicate_progress(view);
5527 return create_diff(s);
5530 static void
5531 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5533 int start, i;
5535 i = start = s->first_displayed_line - 1;
5537 while (s->lines[i].type != type) {
5538 if (i == 0)
5539 i = s->nlines - 1;
5540 if (--i == start)
5541 return; /* do nothing, requested type not in file */
5544 s->selected_line = 1;
5545 s->first_displayed_line = i;
5548 static void
5549 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5551 int start, i;
5553 i = start = s->first_displayed_line + 1;
5555 while (s->lines[i].type != type) {
5556 if (i == s->nlines - 1)
5557 i = 0;
5558 if (++i == start)
5559 return; /* do nothing, requested type not in file */
5562 s->selected_line = 1;
5563 s->first_displayed_line = i;
5566 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5567 int, int, int);
5568 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5569 int, int);
5571 static const struct got_error *
5572 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5574 const struct got_error *err = NULL;
5575 struct tog_diff_view_state *s = &view->state.diff;
5576 struct tog_log_view_state *ls;
5577 struct commit_queue_entry *old_selected_entry;
5578 char *line = NULL;
5579 size_t linesize = 0;
5580 ssize_t linelen;
5581 int i, nscroll = view->nlines - 1, up = 0;
5583 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5585 switch (ch) {
5586 case '0':
5587 case '$':
5588 case KEY_RIGHT:
5589 case 'l':
5590 case KEY_LEFT:
5591 case 'h':
5592 horizontal_scroll_input(view, ch);
5593 break;
5594 case 'a':
5595 case 'w':
5596 if (ch == 'a') {
5597 s->force_text_diff = !s->force_text_diff;
5598 view->action = s->force_text_diff ?
5599 "force ASCII text enabled" :
5600 "force ASCII text disabled";
5602 else if (ch == 'w') {
5603 s->ignore_whitespace = !s->ignore_whitespace;
5604 view->action = s->ignore_whitespace ?
5605 "ignore whitespace enabled" :
5606 "ignore whitespace disabled";
5608 err = reset_diff_view(view);
5609 break;
5610 case 'g':
5611 case KEY_HOME:
5612 s->first_displayed_line = 1;
5613 view->count = 0;
5614 break;
5615 case 'G':
5616 case KEY_END:
5617 view->count = 0;
5618 if (s->eof)
5619 break;
5621 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5622 s->eof = 1;
5623 break;
5624 case 'k':
5625 case KEY_UP:
5626 case CTRL('p'):
5627 if (s->first_displayed_line > 1)
5628 s->first_displayed_line--;
5629 else
5630 view->count = 0;
5631 break;
5632 case CTRL('u'):
5633 case 'u':
5634 nscroll /= 2;
5635 /* FALL THROUGH */
5636 case KEY_PPAGE:
5637 case CTRL('b'):
5638 case 'b':
5639 if (s->first_displayed_line == 1) {
5640 view->count = 0;
5641 break;
5643 i = 0;
5644 while (i++ < nscroll && s->first_displayed_line > 1)
5645 s->first_displayed_line--;
5646 break;
5647 case 'j':
5648 case KEY_DOWN:
5649 case CTRL('n'):
5650 if (!s->eof)
5651 s->first_displayed_line++;
5652 else
5653 view->count = 0;
5654 break;
5655 case CTRL('d'):
5656 case 'd':
5657 nscroll /= 2;
5658 /* FALL THROUGH */
5659 case KEY_NPAGE:
5660 case CTRL('f'):
5661 case 'f':
5662 case ' ':
5663 if (s->eof) {
5664 view->count = 0;
5665 break;
5667 i = 0;
5668 while (!s->eof && i++ < nscroll) {
5669 linelen = getline(&line, &linesize, s->f);
5670 s->first_displayed_line++;
5671 if (linelen == -1) {
5672 if (feof(s->f)) {
5673 s->eof = 1;
5674 } else
5675 err = got_ferror(s->f, GOT_ERR_IO);
5676 break;
5679 free(line);
5680 break;
5681 case '(':
5682 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5683 break;
5684 case ')':
5685 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5686 break;
5687 case '{':
5688 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5689 break;
5690 case '}':
5691 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5692 break;
5693 case '[':
5694 if (s->diff_context > 0) {
5695 s->diff_context--;
5696 s->matched_line = 0;
5697 diff_view_indicate_progress(view);
5698 err = create_diff(s);
5699 if (s->first_displayed_line + view->nlines - 1 >
5700 s->nlines) {
5701 s->first_displayed_line = 1;
5702 s->last_displayed_line = view->nlines;
5704 } else
5705 view->count = 0;
5706 break;
5707 case ']':
5708 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5709 s->diff_context++;
5710 s->matched_line = 0;
5711 diff_view_indicate_progress(view);
5712 err = create_diff(s);
5713 } else
5714 view->count = 0;
5715 break;
5716 case '<':
5717 case ',':
5718 case 'K':
5719 up = 1;
5720 /* FALL THROUGH */
5721 case '>':
5722 case '.':
5723 case 'J':
5724 if (s->parent_view == NULL) {
5725 view->count = 0;
5726 break;
5728 s->parent_view->count = view->count;
5730 if (s->parent_view->type == TOG_VIEW_LOG) {
5731 ls = &s->parent_view->state.log;
5732 old_selected_entry = ls->selected_entry;
5734 err = input_log_view(NULL, s->parent_view,
5735 up ? KEY_UP : KEY_DOWN);
5736 if (err)
5737 break;
5738 view->count = s->parent_view->count;
5740 if (old_selected_entry == ls->selected_entry)
5741 break;
5743 err = set_selected_commit(s, ls->selected_entry);
5744 if (err)
5745 break;
5746 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5747 struct tog_blame_view_state *bs;
5748 struct got_object_id *id, *prev_id;
5750 bs = &s->parent_view->state.blame;
5751 prev_id = get_annotation_for_line(bs->blame.lines,
5752 bs->blame.nlines, bs->last_diffed_line);
5754 err = input_blame_view(&view, s->parent_view,
5755 up ? KEY_UP : KEY_DOWN);
5756 if (err)
5757 break;
5758 view->count = s->parent_view->count;
5760 if (prev_id == NULL)
5761 break;
5762 id = get_selected_commit_id(bs->blame.lines,
5763 bs->blame.nlines, bs->first_displayed_line,
5764 bs->selected_line);
5765 if (id == NULL)
5766 break;
5768 if (!got_object_id_cmp(prev_id, id))
5769 break;
5771 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5772 if (err)
5773 break;
5775 s->first_displayed_line = 1;
5776 s->last_displayed_line = view->nlines;
5777 s->matched_line = 0;
5778 view->x = 0;
5780 diff_view_indicate_progress(view);
5781 err = create_diff(s);
5782 break;
5783 default:
5784 view->count = 0;
5785 break;
5788 return err;
5791 static const struct got_error *
5792 cmd_diff(int argc, char *argv[])
5794 const struct got_error *error;
5795 struct got_repository *repo = NULL;
5796 struct got_worktree *worktree = NULL;
5797 struct got_object_id *id1 = NULL, *id2 = NULL;
5798 char *repo_path = NULL, *cwd = NULL;
5799 char *id_str1 = NULL, *id_str2 = NULL;
5800 char *label1 = NULL, *label2 = NULL;
5801 int diff_context = 3, ignore_whitespace = 0;
5802 int ch, force_text_diff = 0;
5803 const char *errstr;
5804 struct tog_view *view;
5805 int *pack_fds = NULL;
5807 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5808 switch (ch) {
5809 case 'a':
5810 force_text_diff = 1;
5811 break;
5812 case 'C':
5813 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5814 &errstr);
5815 if (errstr != NULL)
5816 errx(1, "number of context lines is %s: %s",
5817 errstr, errstr);
5818 break;
5819 case 'r':
5820 repo_path = realpath(optarg, NULL);
5821 if (repo_path == NULL)
5822 return got_error_from_errno2("realpath",
5823 optarg);
5824 got_path_strip_trailing_slashes(repo_path);
5825 break;
5826 case 'w':
5827 ignore_whitespace = 1;
5828 break;
5829 default:
5830 usage_diff();
5831 /* NOTREACHED */
5835 argc -= optind;
5836 argv += optind;
5838 if (argc == 0) {
5839 usage_diff(); /* TODO show local worktree changes */
5840 } else if (argc == 2) {
5841 id_str1 = argv[0];
5842 id_str2 = argv[1];
5843 } else
5844 usage_diff();
5846 error = got_repo_pack_fds_open(&pack_fds);
5847 if (error)
5848 goto done;
5850 if (repo_path == NULL) {
5851 cwd = getcwd(NULL, 0);
5852 if (cwd == NULL)
5853 return got_error_from_errno("getcwd");
5854 error = got_worktree_open(&worktree, cwd);
5855 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5856 goto done;
5857 if (worktree)
5858 repo_path =
5859 strdup(got_worktree_get_repo_path(worktree));
5860 else
5861 repo_path = strdup(cwd);
5862 if (repo_path == NULL) {
5863 error = got_error_from_errno("strdup");
5864 goto done;
5868 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5869 if (error)
5870 goto done;
5872 init_curses();
5874 error = apply_unveil(got_repo_get_path(repo), NULL);
5875 if (error)
5876 goto done;
5878 error = tog_load_refs(repo, 0);
5879 if (error)
5880 goto done;
5882 error = got_repo_match_object_id(&id1, &label1, id_str1,
5883 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5884 if (error)
5885 goto done;
5887 error = got_repo_match_object_id(&id2, &label2, id_str2,
5888 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5889 if (error)
5890 goto done;
5892 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5893 if (view == NULL) {
5894 error = got_error_from_errno("view_open");
5895 goto done;
5897 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5898 ignore_whitespace, force_text_diff, NULL, repo);
5899 if (error)
5900 goto done;
5901 error = view_loop(view);
5902 done:
5903 free(label1);
5904 free(label2);
5905 free(repo_path);
5906 free(cwd);
5907 if (repo) {
5908 const struct got_error *close_err = got_repo_close(repo);
5909 if (error == NULL)
5910 error = close_err;
5912 if (worktree)
5913 got_worktree_close(worktree);
5914 if (pack_fds) {
5915 const struct got_error *pack_err =
5916 got_repo_pack_fds_close(pack_fds);
5917 if (error == NULL)
5918 error = pack_err;
5920 tog_free_refs();
5921 return error;
5924 __dead static void
5925 usage_blame(void)
5927 endwin();
5928 fprintf(stderr,
5929 "usage: %s blame [-c commit] [-r repository-path] path\n",
5930 getprogname());
5931 exit(1);
5934 struct tog_blame_line {
5935 int annotated;
5936 struct got_object_id *id;
5939 static const struct got_error *
5940 draw_blame(struct tog_view *view)
5942 struct tog_blame_view_state *s = &view->state.blame;
5943 struct tog_blame *blame = &s->blame;
5944 regmatch_t *regmatch = &view->regmatch;
5945 const struct got_error *err;
5946 int lineno = 0, nprinted = 0;
5947 char *line = NULL;
5948 size_t linesize = 0;
5949 ssize_t linelen;
5950 wchar_t *wline;
5951 int width;
5952 struct tog_blame_line *blame_line;
5953 struct got_object_id *prev_id = NULL;
5954 char *id_str;
5955 struct tog_color *tc;
5957 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5958 if (err)
5959 return err;
5961 rewind(blame->f);
5962 werase(view->window);
5964 if (asprintf(&line, "commit %s", id_str) == -1) {
5965 err = got_error_from_errno("asprintf");
5966 free(id_str);
5967 return err;
5970 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5971 free(line);
5972 line = NULL;
5973 if (err)
5974 return err;
5975 if (view_needs_focus_indication(view))
5976 wstandout(view->window);
5977 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5978 if (tc)
5979 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5980 waddwstr(view->window, wline);
5981 while (width++ < view->ncols)
5982 waddch(view->window, ' ');
5983 if (tc)
5984 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5985 if (view_needs_focus_indication(view))
5986 wstandend(view->window);
5987 free(wline);
5988 wline = NULL;
5990 if (view->gline > blame->nlines)
5991 view->gline = blame->nlines;
5993 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5994 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5995 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5996 free(id_str);
5997 return got_error_from_errno("asprintf");
5999 free(id_str);
6000 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6001 free(line);
6002 line = NULL;
6003 if (err)
6004 return err;
6005 waddwstr(view->window, wline);
6006 free(wline);
6007 wline = NULL;
6008 if (width < view->ncols - 1)
6009 waddch(view->window, '\n');
6011 s->eof = 0;
6012 view->maxx = 0;
6013 while (nprinted < view->nlines - 2) {
6014 linelen = getline(&line, &linesize, blame->f);
6015 if (linelen == -1) {
6016 if (feof(blame->f)) {
6017 s->eof = 1;
6018 break;
6020 free(line);
6021 return got_ferror(blame->f, GOT_ERR_IO);
6023 if (++lineno < s->first_displayed_line)
6024 continue;
6025 if (view->gline && !gotoline(view, &lineno, &nprinted))
6026 continue;
6028 /* Set view->maxx based on full line length. */
6029 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6030 if (err) {
6031 free(line);
6032 return err;
6034 free(wline);
6035 wline = NULL;
6036 view->maxx = MAX(view->maxx, width);
6038 if (nprinted == s->selected_line - 1)
6039 wstandout(view->window);
6041 if (blame->nlines > 0) {
6042 blame_line = &blame->lines[lineno - 1];
6043 if (blame_line->annotated && prev_id &&
6044 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6045 !(nprinted == s->selected_line - 1)) {
6046 waddstr(view->window, " ");
6047 } else if (blame_line->annotated) {
6048 char *id_str;
6049 err = got_object_id_str(&id_str,
6050 blame_line->id);
6051 if (err) {
6052 free(line);
6053 return err;
6055 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6056 if (tc)
6057 wattr_on(view->window,
6058 COLOR_PAIR(tc->colorpair), NULL);
6059 wprintw(view->window, "%.8s", id_str);
6060 if (tc)
6061 wattr_off(view->window,
6062 COLOR_PAIR(tc->colorpair), NULL);
6063 free(id_str);
6064 prev_id = blame_line->id;
6065 } else {
6066 waddstr(view->window, "........");
6067 prev_id = NULL;
6069 } else {
6070 waddstr(view->window, "........");
6071 prev_id = NULL;
6074 if (nprinted == s->selected_line - 1)
6075 wstandend(view->window);
6076 waddstr(view->window, " ");
6078 if (view->ncols <= 9) {
6079 width = 9;
6080 } else if (s->first_displayed_line + nprinted ==
6081 s->matched_line &&
6082 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6083 err = add_matched_line(&width, line, view->ncols - 9, 9,
6084 view->window, view->x, regmatch);
6085 if (err) {
6086 free(line);
6087 return err;
6089 width += 9;
6090 } else {
6091 int skip;
6092 err = format_line(&wline, &width, &skip, line,
6093 view->x, view->ncols - 9, 9, 1);
6094 if (err) {
6095 free(line);
6096 return err;
6098 waddwstr(view->window, &wline[skip]);
6099 width += 9;
6100 free(wline);
6101 wline = NULL;
6104 if (width <= view->ncols - 1)
6105 waddch(view->window, '\n');
6106 if (++nprinted == 1)
6107 s->first_displayed_line = lineno;
6109 free(line);
6110 s->last_displayed_line = lineno;
6112 view_border(view);
6114 return NULL;
6117 static const struct got_error *
6118 blame_cb(void *arg, int nlines, int lineno,
6119 struct got_commit_object *commit, struct got_object_id *id)
6121 const struct got_error *err = NULL;
6122 struct tog_blame_cb_args *a = arg;
6123 struct tog_blame_line *line;
6124 int errcode;
6126 if (nlines != a->nlines ||
6127 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6128 return got_error(GOT_ERR_RANGE);
6130 errcode = pthread_mutex_lock(&tog_mutex);
6131 if (errcode)
6132 return got_error_set_errno(errcode, "pthread_mutex_lock");
6134 if (*a->quit) { /* user has quit the blame view */
6135 err = got_error(GOT_ERR_ITER_COMPLETED);
6136 goto done;
6139 if (lineno == -1)
6140 goto done; /* no change in this commit */
6142 line = &a->lines[lineno - 1];
6143 if (line->annotated)
6144 goto done;
6146 line->id = got_object_id_dup(id);
6147 if (line->id == NULL) {
6148 err = got_error_from_errno("got_object_id_dup");
6149 goto done;
6151 line->annotated = 1;
6152 done:
6153 errcode = pthread_mutex_unlock(&tog_mutex);
6154 if (errcode)
6155 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6156 return err;
6159 static void *
6160 blame_thread(void *arg)
6162 const struct got_error *err, *close_err;
6163 struct tog_blame_thread_args *ta = arg;
6164 struct tog_blame_cb_args *a = ta->cb_args;
6165 int errcode, fd1 = -1, fd2 = -1;
6166 FILE *f1 = NULL, *f2 = NULL;
6168 fd1 = got_opentempfd();
6169 if (fd1 == -1)
6170 return (void *)got_error_from_errno("got_opentempfd");
6172 fd2 = got_opentempfd();
6173 if (fd2 == -1) {
6174 err = got_error_from_errno("got_opentempfd");
6175 goto done;
6178 f1 = got_opentemp();
6179 if (f1 == NULL) {
6180 err = (void *)got_error_from_errno("got_opentemp");
6181 goto done;
6183 f2 = got_opentemp();
6184 if (f2 == NULL) {
6185 err = (void *)got_error_from_errno("got_opentemp");
6186 goto done;
6189 err = block_signals_used_by_main_thread();
6190 if (err)
6191 goto done;
6193 err = got_blame(ta->path, a->commit_id, ta->repo,
6194 tog_diff_algo, blame_cb, ta->cb_args,
6195 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6196 if (err && err->code == GOT_ERR_CANCELLED)
6197 err = NULL;
6199 errcode = pthread_mutex_lock(&tog_mutex);
6200 if (errcode) {
6201 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6202 goto done;
6205 close_err = got_repo_close(ta->repo);
6206 if (err == NULL)
6207 err = close_err;
6208 ta->repo = NULL;
6209 *ta->complete = 1;
6211 errcode = pthread_mutex_unlock(&tog_mutex);
6212 if (errcode && err == NULL)
6213 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6215 done:
6216 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6217 err = got_error_from_errno("close");
6218 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6219 err = got_error_from_errno("close");
6220 if (f1 && fclose(f1) == EOF && err == NULL)
6221 err = got_error_from_errno("fclose");
6222 if (f2 && fclose(f2) == EOF && err == NULL)
6223 err = got_error_from_errno("fclose");
6225 return (void *)err;
6228 static struct got_object_id *
6229 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6230 int first_displayed_line, int selected_line)
6232 struct tog_blame_line *line;
6234 if (nlines <= 0)
6235 return NULL;
6237 line = &lines[first_displayed_line - 1 + selected_line - 1];
6238 if (!line->annotated)
6239 return NULL;
6241 return line->id;
6244 static struct got_object_id *
6245 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6246 int lineno)
6248 struct tog_blame_line *line;
6250 if (nlines <= 0 || lineno >= nlines)
6251 return NULL;
6253 line = &lines[lineno - 1];
6254 if (!line->annotated)
6255 return NULL;
6257 return line->id;
6260 static const struct got_error *
6261 stop_blame(struct tog_blame *blame)
6263 const struct got_error *err = NULL;
6264 int i;
6266 if (blame->thread) {
6267 int errcode;
6268 errcode = pthread_mutex_unlock(&tog_mutex);
6269 if (errcode)
6270 return got_error_set_errno(errcode,
6271 "pthread_mutex_unlock");
6272 errcode = pthread_join(blame->thread, (void **)&err);
6273 if (errcode)
6274 return got_error_set_errno(errcode, "pthread_join");
6275 errcode = pthread_mutex_lock(&tog_mutex);
6276 if (errcode)
6277 return got_error_set_errno(errcode,
6278 "pthread_mutex_lock");
6279 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6280 err = NULL;
6281 blame->thread = NULL;
6283 if (blame->thread_args.repo) {
6284 const struct got_error *close_err;
6285 close_err = got_repo_close(blame->thread_args.repo);
6286 if (err == NULL)
6287 err = close_err;
6288 blame->thread_args.repo = NULL;
6290 if (blame->f) {
6291 if (fclose(blame->f) == EOF && err == NULL)
6292 err = got_error_from_errno("fclose");
6293 blame->f = NULL;
6295 if (blame->lines) {
6296 for (i = 0; i < blame->nlines; i++)
6297 free(blame->lines[i].id);
6298 free(blame->lines);
6299 blame->lines = NULL;
6301 free(blame->cb_args.commit_id);
6302 blame->cb_args.commit_id = NULL;
6303 if (blame->pack_fds) {
6304 const struct got_error *pack_err =
6305 got_repo_pack_fds_close(blame->pack_fds);
6306 if (err == NULL)
6307 err = pack_err;
6308 blame->pack_fds = NULL;
6310 return err;
6313 static const struct got_error *
6314 cancel_blame_view(void *arg)
6316 const struct got_error *err = NULL;
6317 int *done = arg;
6318 int errcode;
6320 errcode = pthread_mutex_lock(&tog_mutex);
6321 if (errcode)
6322 return got_error_set_errno(errcode,
6323 "pthread_mutex_unlock");
6325 if (*done)
6326 err = got_error(GOT_ERR_CANCELLED);
6328 errcode = pthread_mutex_unlock(&tog_mutex);
6329 if (errcode)
6330 return got_error_set_errno(errcode,
6331 "pthread_mutex_lock");
6333 return err;
6336 static const struct got_error *
6337 run_blame(struct tog_view *view)
6339 struct tog_blame_view_state *s = &view->state.blame;
6340 struct tog_blame *blame = &s->blame;
6341 const struct got_error *err = NULL;
6342 struct got_commit_object *commit = NULL;
6343 struct got_blob_object *blob = NULL;
6344 struct got_repository *thread_repo = NULL;
6345 struct got_object_id *obj_id = NULL;
6346 int obj_type, fd = -1;
6347 int *pack_fds = NULL;
6349 err = got_object_open_as_commit(&commit, s->repo,
6350 &s->blamed_commit->id);
6351 if (err)
6352 return err;
6354 fd = got_opentempfd();
6355 if (fd == -1) {
6356 err = got_error_from_errno("got_opentempfd");
6357 goto done;
6360 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6361 if (err)
6362 goto done;
6364 err = got_object_get_type(&obj_type, s->repo, obj_id);
6365 if (err)
6366 goto done;
6368 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6369 err = got_error(GOT_ERR_OBJ_TYPE);
6370 goto done;
6373 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6374 if (err)
6375 goto done;
6376 blame->f = got_opentemp();
6377 if (blame->f == NULL) {
6378 err = got_error_from_errno("got_opentemp");
6379 goto done;
6381 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6382 &blame->line_offsets, blame->f, blob);
6383 if (err)
6384 goto done;
6385 if (blame->nlines == 0) {
6386 s->blame_complete = 1;
6387 goto done;
6390 /* Don't include \n at EOF in the blame line count. */
6391 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6392 blame->nlines--;
6394 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6395 if (blame->lines == NULL) {
6396 err = got_error_from_errno("calloc");
6397 goto done;
6400 err = got_repo_pack_fds_open(&pack_fds);
6401 if (err)
6402 goto done;
6403 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6404 pack_fds);
6405 if (err)
6406 goto done;
6408 blame->pack_fds = pack_fds;
6409 blame->cb_args.view = view;
6410 blame->cb_args.lines = blame->lines;
6411 blame->cb_args.nlines = blame->nlines;
6412 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6413 if (blame->cb_args.commit_id == NULL) {
6414 err = got_error_from_errno("got_object_id_dup");
6415 goto done;
6417 blame->cb_args.quit = &s->done;
6419 blame->thread_args.path = s->path;
6420 blame->thread_args.repo = thread_repo;
6421 blame->thread_args.cb_args = &blame->cb_args;
6422 blame->thread_args.complete = &s->blame_complete;
6423 blame->thread_args.cancel_cb = cancel_blame_view;
6424 blame->thread_args.cancel_arg = &s->done;
6425 s->blame_complete = 0;
6427 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6428 s->first_displayed_line = 1;
6429 s->last_displayed_line = view->nlines;
6430 s->selected_line = 1;
6432 s->matched_line = 0;
6434 done:
6435 if (commit)
6436 got_object_commit_close(commit);
6437 if (fd != -1 && close(fd) == -1 && err == NULL)
6438 err = got_error_from_errno("close");
6439 if (blob)
6440 got_object_blob_close(blob);
6441 free(obj_id);
6442 if (err)
6443 stop_blame(blame);
6444 return err;
6447 static const struct got_error *
6448 open_blame_view(struct tog_view *view, char *path,
6449 struct got_object_id *commit_id, struct got_repository *repo)
6451 const struct got_error *err = NULL;
6452 struct tog_blame_view_state *s = &view->state.blame;
6454 STAILQ_INIT(&s->blamed_commits);
6456 s->path = strdup(path);
6457 if (s->path == NULL)
6458 return got_error_from_errno("strdup");
6460 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6461 if (err) {
6462 free(s->path);
6463 return err;
6466 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6467 s->first_displayed_line = 1;
6468 s->last_displayed_line = view->nlines;
6469 s->selected_line = 1;
6470 s->blame_complete = 0;
6471 s->repo = repo;
6472 s->commit_id = commit_id;
6473 memset(&s->blame, 0, sizeof(s->blame));
6475 STAILQ_INIT(&s->colors);
6476 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6477 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6478 get_color_value("TOG_COLOR_COMMIT"));
6479 if (err)
6480 return err;
6483 view->show = show_blame_view;
6484 view->input = input_blame_view;
6485 view->reset = reset_blame_view;
6486 view->close = close_blame_view;
6487 view->search_start = search_start_blame_view;
6488 view->search_setup = search_setup_blame_view;
6489 view->search_next = search_next_view_match;
6491 return run_blame(view);
6494 static const struct got_error *
6495 close_blame_view(struct tog_view *view)
6497 const struct got_error *err = NULL;
6498 struct tog_blame_view_state *s = &view->state.blame;
6500 if (s->blame.thread)
6501 err = stop_blame(&s->blame);
6503 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6504 struct got_object_qid *blamed_commit;
6505 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6506 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6507 got_object_qid_free(blamed_commit);
6510 free(s->path);
6511 free_colors(&s->colors);
6512 return err;
6515 static const struct got_error *
6516 search_start_blame_view(struct tog_view *view)
6518 struct tog_blame_view_state *s = &view->state.blame;
6520 s->matched_line = 0;
6521 return NULL;
6524 static void
6525 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6526 size_t *nlines, int **first, int **last, int **match, int **selected)
6528 struct tog_blame_view_state *s = &view->state.blame;
6530 *f = s->blame.f;
6531 *nlines = s->blame.nlines;
6532 *line_offsets = s->blame.line_offsets;
6533 *match = &s->matched_line;
6534 *first = &s->first_displayed_line;
6535 *last = &s->last_displayed_line;
6536 *selected = &s->selected_line;
6539 static const struct got_error *
6540 show_blame_view(struct tog_view *view)
6542 const struct got_error *err = NULL;
6543 struct tog_blame_view_state *s = &view->state.blame;
6544 int errcode;
6546 if (s->blame.thread == NULL && !s->blame_complete) {
6547 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6548 &s->blame.thread_args);
6549 if (errcode)
6550 return got_error_set_errno(errcode, "pthread_create");
6552 if (!using_mock_io)
6553 halfdelay(1); /* fast refresh while annotating */
6556 if (s->blame_complete && !using_mock_io)
6557 halfdelay(10); /* disable fast refresh */
6559 err = draw_blame(view);
6561 view_border(view);
6562 return err;
6565 static const struct got_error *
6566 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6567 struct got_repository *repo, struct got_object_id *id)
6569 struct tog_view *log_view;
6570 const struct got_error *err = NULL;
6572 *new_view = NULL;
6574 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6575 if (log_view == NULL)
6576 return got_error_from_errno("view_open");
6578 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6579 if (err)
6580 view_close(log_view);
6581 else
6582 *new_view = log_view;
6584 return err;
6587 static const struct got_error *
6588 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6590 const struct got_error *err = NULL, *thread_err = NULL;
6591 struct tog_view *diff_view;
6592 struct tog_blame_view_state *s = &view->state.blame;
6593 int eos, nscroll, begin_y = 0, begin_x = 0;
6595 eos = nscroll = view->nlines - 2;
6596 if (view_is_hsplit_top(view))
6597 --eos; /* border */
6599 switch (ch) {
6600 case '0':
6601 case '$':
6602 case KEY_RIGHT:
6603 case 'l':
6604 case KEY_LEFT:
6605 case 'h':
6606 horizontal_scroll_input(view, ch);
6607 break;
6608 case 'q':
6609 s->done = 1;
6610 break;
6611 case 'g':
6612 case KEY_HOME:
6613 s->selected_line = 1;
6614 s->first_displayed_line = 1;
6615 view->count = 0;
6616 break;
6617 case 'G':
6618 case KEY_END:
6619 if (s->blame.nlines < eos) {
6620 s->selected_line = s->blame.nlines;
6621 s->first_displayed_line = 1;
6622 } else {
6623 s->selected_line = eos;
6624 s->first_displayed_line = s->blame.nlines - (eos - 1);
6626 view->count = 0;
6627 break;
6628 case 'k':
6629 case KEY_UP:
6630 case CTRL('p'):
6631 if (s->selected_line > 1)
6632 s->selected_line--;
6633 else if (s->selected_line == 1 &&
6634 s->first_displayed_line > 1)
6635 s->first_displayed_line--;
6636 else
6637 view->count = 0;
6638 break;
6639 case CTRL('u'):
6640 case 'u':
6641 nscroll /= 2;
6642 /* FALL THROUGH */
6643 case KEY_PPAGE:
6644 case CTRL('b'):
6645 case 'b':
6646 if (s->first_displayed_line == 1) {
6647 if (view->count > 1)
6648 nscroll += nscroll;
6649 s->selected_line = MAX(1, s->selected_line - nscroll);
6650 view->count = 0;
6651 break;
6653 if (s->first_displayed_line > nscroll)
6654 s->first_displayed_line -= nscroll;
6655 else
6656 s->first_displayed_line = 1;
6657 break;
6658 case 'j':
6659 case KEY_DOWN:
6660 case CTRL('n'):
6661 if (s->selected_line < eos && s->first_displayed_line +
6662 s->selected_line <= s->blame.nlines)
6663 s->selected_line++;
6664 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6665 s->first_displayed_line++;
6666 else
6667 view->count = 0;
6668 break;
6669 case 'c':
6670 case 'p': {
6671 struct got_object_id *id = NULL;
6673 view->count = 0;
6674 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6675 s->first_displayed_line, s->selected_line);
6676 if (id == NULL)
6677 break;
6678 if (ch == 'p') {
6679 struct got_commit_object *commit, *pcommit;
6680 struct got_object_qid *pid;
6681 struct got_object_id *blob_id = NULL;
6682 int obj_type;
6683 err = got_object_open_as_commit(&commit,
6684 s->repo, id);
6685 if (err)
6686 break;
6687 pid = STAILQ_FIRST(
6688 got_object_commit_get_parent_ids(commit));
6689 if (pid == NULL) {
6690 got_object_commit_close(commit);
6691 break;
6693 /* Check if path history ends here. */
6694 err = got_object_open_as_commit(&pcommit,
6695 s->repo, &pid->id);
6696 if (err)
6697 break;
6698 err = got_object_id_by_path(&blob_id, s->repo,
6699 pcommit, s->path);
6700 got_object_commit_close(pcommit);
6701 if (err) {
6702 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6703 err = NULL;
6704 got_object_commit_close(commit);
6705 break;
6707 err = got_object_get_type(&obj_type, s->repo,
6708 blob_id);
6709 free(blob_id);
6710 /* Can't blame non-blob type objects. */
6711 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6712 got_object_commit_close(commit);
6713 break;
6715 err = got_object_qid_alloc(&s->blamed_commit,
6716 &pid->id);
6717 got_object_commit_close(commit);
6718 } else {
6719 if (got_object_id_cmp(id,
6720 &s->blamed_commit->id) == 0)
6721 break;
6722 err = got_object_qid_alloc(&s->blamed_commit,
6723 id);
6725 if (err)
6726 break;
6727 s->done = 1;
6728 thread_err = stop_blame(&s->blame);
6729 s->done = 0;
6730 if (thread_err)
6731 break;
6732 STAILQ_INSERT_HEAD(&s->blamed_commits,
6733 s->blamed_commit, entry);
6734 err = run_blame(view);
6735 if (err)
6736 break;
6737 break;
6739 case 'C': {
6740 struct got_object_qid *first;
6742 view->count = 0;
6743 first = STAILQ_FIRST(&s->blamed_commits);
6744 if (!got_object_id_cmp(&first->id, s->commit_id))
6745 break;
6746 s->done = 1;
6747 thread_err = stop_blame(&s->blame);
6748 s->done = 0;
6749 if (thread_err)
6750 break;
6751 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6752 got_object_qid_free(s->blamed_commit);
6753 s->blamed_commit =
6754 STAILQ_FIRST(&s->blamed_commits);
6755 err = run_blame(view);
6756 if (err)
6757 break;
6758 break;
6760 case 'L':
6761 view->count = 0;
6762 s->id_to_log = get_selected_commit_id(s->blame.lines,
6763 s->blame.nlines, s->first_displayed_line, s->selected_line);
6764 if (s->id_to_log)
6765 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6766 break;
6767 case KEY_ENTER:
6768 case '\r': {
6769 struct got_object_id *id = NULL;
6770 struct got_object_qid *pid;
6771 struct got_commit_object *commit = NULL;
6773 view->count = 0;
6774 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6775 s->first_displayed_line, s->selected_line);
6776 if (id == NULL)
6777 break;
6778 err = got_object_open_as_commit(&commit, s->repo, id);
6779 if (err)
6780 break;
6781 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6782 if (*new_view) {
6783 /* traversed from diff view, release diff resources */
6784 err = close_diff_view(*new_view);
6785 if (err)
6786 break;
6787 diff_view = *new_view;
6788 } else {
6789 if (view_is_parent_view(view))
6790 view_get_split(view, &begin_y, &begin_x);
6792 diff_view = view_open(0, 0, begin_y, begin_x,
6793 TOG_VIEW_DIFF);
6794 if (diff_view == NULL) {
6795 got_object_commit_close(commit);
6796 err = got_error_from_errno("view_open");
6797 break;
6800 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6801 id, NULL, NULL, 3, 0, 0, view, s->repo);
6802 got_object_commit_close(commit);
6803 if (err) {
6804 view_close(diff_view);
6805 break;
6807 s->last_diffed_line = s->first_displayed_line - 1 +
6808 s->selected_line;
6809 if (*new_view)
6810 break; /* still open from active diff view */
6811 if (view_is_parent_view(view) &&
6812 view->mode == TOG_VIEW_SPLIT_HRZN) {
6813 err = view_init_hsplit(view, begin_y);
6814 if (err)
6815 break;
6818 view->focussed = 0;
6819 diff_view->focussed = 1;
6820 diff_view->mode = view->mode;
6821 diff_view->nlines = view->lines - begin_y;
6822 if (view_is_parent_view(view)) {
6823 view_transfer_size(diff_view, view);
6824 err = view_close_child(view);
6825 if (err)
6826 break;
6827 err = view_set_child(view, diff_view);
6828 if (err)
6829 break;
6830 view->focus_child = 1;
6831 } else
6832 *new_view = diff_view;
6833 if (err)
6834 break;
6835 break;
6837 case CTRL('d'):
6838 case 'd':
6839 nscroll /= 2;
6840 /* FALL THROUGH */
6841 case KEY_NPAGE:
6842 case CTRL('f'):
6843 case 'f':
6844 case ' ':
6845 if (s->last_displayed_line >= s->blame.nlines &&
6846 s->selected_line >= MIN(s->blame.nlines,
6847 view->nlines - 2)) {
6848 view->count = 0;
6849 break;
6851 if (s->last_displayed_line >= s->blame.nlines &&
6852 s->selected_line < view->nlines - 2) {
6853 s->selected_line +=
6854 MIN(nscroll, s->last_displayed_line -
6855 s->first_displayed_line - s->selected_line + 1);
6857 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6858 s->first_displayed_line += nscroll;
6859 else
6860 s->first_displayed_line =
6861 s->blame.nlines - (view->nlines - 3);
6862 break;
6863 case KEY_RESIZE:
6864 if (s->selected_line > view->nlines - 2) {
6865 s->selected_line = MIN(s->blame.nlines,
6866 view->nlines - 2);
6868 break;
6869 default:
6870 view->count = 0;
6871 break;
6873 return thread_err ? thread_err : err;
6876 static const struct got_error *
6877 reset_blame_view(struct tog_view *view)
6879 const struct got_error *err;
6880 struct tog_blame_view_state *s = &view->state.blame;
6882 view->count = 0;
6883 s->done = 1;
6884 err = stop_blame(&s->blame);
6885 s->done = 0;
6886 if (err)
6887 return err;
6888 return run_blame(view);
6891 static const struct got_error *
6892 cmd_blame(int argc, char *argv[])
6894 const struct got_error *error;
6895 struct got_repository *repo = NULL;
6896 struct got_worktree *worktree = NULL;
6897 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6898 char *link_target = NULL;
6899 struct got_object_id *commit_id = NULL;
6900 struct got_commit_object *commit = NULL;
6901 char *commit_id_str = NULL;
6902 int ch;
6903 struct tog_view *view = NULL;
6904 int *pack_fds = NULL;
6906 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6907 switch (ch) {
6908 case 'c':
6909 commit_id_str = optarg;
6910 break;
6911 case 'r':
6912 repo_path = realpath(optarg, NULL);
6913 if (repo_path == NULL)
6914 return got_error_from_errno2("realpath",
6915 optarg);
6916 break;
6917 default:
6918 usage_blame();
6919 /* NOTREACHED */
6923 argc -= optind;
6924 argv += optind;
6926 if (argc != 1)
6927 usage_blame();
6929 error = got_repo_pack_fds_open(&pack_fds);
6930 if (error != NULL)
6931 goto done;
6933 if (repo_path == NULL) {
6934 cwd = getcwd(NULL, 0);
6935 if (cwd == NULL)
6936 return got_error_from_errno("getcwd");
6937 error = got_worktree_open(&worktree, cwd);
6938 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6939 goto done;
6940 if (worktree)
6941 repo_path =
6942 strdup(got_worktree_get_repo_path(worktree));
6943 else
6944 repo_path = strdup(cwd);
6945 if (repo_path == NULL) {
6946 error = got_error_from_errno("strdup");
6947 goto done;
6951 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6952 if (error != NULL)
6953 goto done;
6955 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6956 worktree);
6957 if (error)
6958 goto done;
6960 init_curses();
6962 error = apply_unveil(got_repo_get_path(repo), NULL);
6963 if (error)
6964 goto done;
6966 error = tog_load_refs(repo, 0);
6967 if (error)
6968 goto done;
6970 if (commit_id_str == NULL) {
6971 struct got_reference *head_ref;
6972 error = got_ref_open(&head_ref, repo, worktree ?
6973 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6974 if (error != NULL)
6975 goto done;
6976 error = got_ref_resolve(&commit_id, repo, head_ref);
6977 got_ref_close(head_ref);
6978 } else {
6979 error = got_repo_match_object_id(&commit_id, NULL,
6980 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6982 if (error != NULL)
6983 goto done;
6985 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6986 if (view == NULL) {
6987 error = got_error_from_errno("view_open");
6988 goto done;
6991 error = got_object_open_as_commit(&commit, repo, commit_id);
6992 if (error)
6993 goto done;
6995 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6996 commit, repo);
6997 if (error)
6998 goto done;
7000 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7001 commit_id, repo);
7002 if (error)
7003 goto done;
7004 if (worktree) {
7005 /* Release work tree lock. */
7006 got_worktree_close(worktree);
7007 worktree = NULL;
7009 error = view_loop(view);
7010 done:
7011 free(repo_path);
7012 free(in_repo_path);
7013 free(link_target);
7014 free(cwd);
7015 free(commit_id);
7016 if (error != NULL && view != NULL) {
7017 if (view->close == NULL)
7018 close_blame_view(view);
7019 view_close(view);
7021 if (commit)
7022 got_object_commit_close(commit);
7023 if (worktree)
7024 got_worktree_close(worktree);
7025 if (repo) {
7026 const struct got_error *close_err = got_repo_close(repo);
7027 if (error == NULL)
7028 error = close_err;
7030 if (pack_fds) {
7031 const struct got_error *pack_err =
7032 got_repo_pack_fds_close(pack_fds);
7033 if (error == NULL)
7034 error = pack_err;
7036 tog_free_refs();
7037 return error;
7040 static const struct got_error *
7041 draw_tree_entries(struct tog_view *view, const char *parent_path)
7043 struct tog_tree_view_state *s = &view->state.tree;
7044 const struct got_error *err = NULL;
7045 struct got_tree_entry *te;
7046 wchar_t *wline;
7047 char *index = NULL;
7048 struct tog_color *tc;
7049 int width, n, nentries, scrollx, i = 1;
7050 int limit = view->nlines;
7052 s->ndisplayed = 0;
7053 if (view_is_hsplit_top(view))
7054 --limit; /* border */
7056 werase(view->window);
7058 if (limit == 0)
7059 return NULL;
7061 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7062 0, 0);
7063 if (err)
7064 return err;
7065 if (view_needs_focus_indication(view))
7066 wstandout(view->window);
7067 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7068 if (tc)
7069 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7070 waddwstr(view->window, wline);
7071 free(wline);
7072 wline = NULL;
7073 while (width++ < view->ncols)
7074 waddch(view->window, ' ');
7075 if (tc)
7076 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7077 if (view_needs_focus_indication(view))
7078 wstandend(view->window);
7079 if (--limit <= 0)
7080 return NULL;
7082 i += s->selected;
7083 if (s->first_displayed_entry) {
7084 i += got_tree_entry_get_index(s->first_displayed_entry);
7085 if (s->tree != s->root)
7086 ++i; /* account for ".." entry */
7088 nentries = got_object_tree_get_nentries(s->tree);
7089 if (asprintf(&index, "[%d/%d] %s",
7090 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7091 return got_error_from_errno("asprintf");
7092 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7093 free(index);
7094 if (err)
7095 return err;
7096 waddwstr(view->window, wline);
7097 free(wline);
7098 wline = NULL;
7099 if (width < view->ncols - 1)
7100 waddch(view->window, '\n');
7101 if (--limit <= 0)
7102 return NULL;
7103 waddch(view->window, '\n');
7104 if (--limit <= 0)
7105 return NULL;
7107 if (s->first_displayed_entry == NULL) {
7108 te = got_object_tree_get_first_entry(s->tree);
7109 if (s->selected == 0) {
7110 if (view->focussed)
7111 wstandout(view->window);
7112 s->selected_entry = NULL;
7114 waddstr(view->window, " ..\n"); /* parent directory */
7115 if (s->selected == 0 && view->focussed)
7116 wstandend(view->window);
7117 s->ndisplayed++;
7118 if (--limit <= 0)
7119 return NULL;
7120 n = 1;
7121 } else {
7122 n = 0;
7123 te = s->first_displayed_entry;
7126 view->maxx = 0;
7127 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7128 char *line = NULL, *id_str = NULL, *link_target = NULL;
7129 const char *modestr = "";
7130 mode_t mode;
7132 te = got_object_tree_get_entry(s->tree, i);
7133 mode = got_tree_entry_get_mode(te);
7135 if (s->show_ids) {
7136 err = got_object_id_str(&id_str,
7137 got_tree_entry_get_id(te));
7138 if (err)
7139 return got_error_from_errno(
7140 "got_object_id_str");
7142 if (got_object_tree_entry_is_submodule(te))
7143 modestr = "$";
7144 else if (S_ISLNK(mode)) {
7145 int i;
7147 err = got_tree_entry_get_symlink_target(&link_target,
7148 te, s->repo);
7149 if (err) {
7150 free(id_str);
7151 return err;
7153 for (i = 0; i < strlen(link_target); i++) {
7154 if (!isprint((unsigned char)link_target[i]))
7155 link_target[i] = '?';
7157 modestr = "@";
7159 else if (S_ISDIR(mode))
7160 modestr = "/";
7161 else if (mode & S_IXUSR)
7162 modestr = "*";
7163 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7164 got_tree_entry_get_name(te), modestr,
7165 link_target ? " -> ": "",
7166 link_target ? link_target : "") == -1) {
7167 free(id_str);
7168 free(link_target);
7169 return got_error_from_errno("asprintf");
7171 free(id_str);
7172 free(link_target);
7174 /* use full line width to determine view->maxx */
7175 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7176 if (err) {
7177 free(line);
7178 break;
7180 view->maxx = MAX(view->maxx, width);
7181 free(wline);
7182 wline = NULL;
7184 err = format_line(&wline, &width, &scrollx, line, view->x,
7185 view->ncols, 0, 0);
7186 if (err) {
7187 free(line);
7188 break;
7190 if (n == s->selected) {
7191 if (view->focussed)
7192 wstandout(view->window);
7193 s->selected_entry = te;
7195 tc = match_color(&s->colors, line);
7196 if (tc)
7197 wattr_on(view->window,
7198 COLOR_PAIR(tc->colorpair), NULL);
7199 waddwstr(view->window, &wline[scrollx]);
7200 if (tc)
7201 wattr_off(view->window,
7202 COLOR_PAIR(tc->colorpair), NULL);
7203 if (width < view->ncols)
7204 waddch(view->window, '\n');
7205 if (n == s->selected && view->focussed)
7206 wstandend(view->window);
7207 free(line);
7208 free(wline);
7209 wline = NULL;
7210 n++;
7211 s->ndisplayed++;
7212 s->last_displayed_entry = te;
7213 if (--limit <= 0)
7214 break;
7217 return err;
7220 static void
7221 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7223 struct got_tree_entry *te;
7224 int isroot = s->tree == s->root;
7225 int i = 0;
7227 if (s->first_displayed_entry == NULL)
7228 return;
7230 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7231 while (i++ < maxscroll) {
7232 if (te == NULL) {
7233 if (!isroot)
7234 s->first_displayed_entry = NULL;
7235 break;
7237 s->first_displayed_entry = te;
7238 te = got_tree_entry_get_prev(s->tree, te);
7242 static const struct got_error *
7243 tree_scroll_down(struct tog_view *view, int maxscroll)
7245 struct tog_tree_view_state *s = &view->state.tree;
7246 struct got_tree_entry *next, *last;
7247 int n = 0;
7249 if (s->first_displayed_entry)
7250 next = got_tree_entry_get_next(s->tree,
7251 s->first_displayed_entry);
7252 else
7253 next = got_object_tree_get_first_entry(s->tree);
7255 last = s->last_displayed_entry;
7256 while (next && n++ < maxscroll) {
7257 if (last) {
7258 s->last_displayed_entry = last;
7259 last = got_tree_entry_get_next(s->tree, last);
7261 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7262 s->first_displayed_entry = next;
7263 next = got_tree_entry_get_next(s->tree, next);
7267 return NULL;
7270 static const struct got_error *
7271 tree_entry_path(char **path, struct tog_parent_trees *parents,
7272 struct got_tree_entry *te)
7274 const struct got_error *err = NULL;
7275 struct tog_parent_tree *pt;
7276 size_t len = 2; /* for leading slash and NUL */
7278 TAILQ_FOREACH(pt, parents, entry)
7279 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7280 + 1 /* slash */;
7281 if (te)
7282 len += strlen(got_tree_entry_get_name(te));
7284 *path = calloc(1, len);
7285 if (path == NULL)
7286 return got_error_from_errno("calloc");
7288 (*path)[0] = '/';
7289 pt = TAILQ_LAST(parents, tog_parent_trees);
7290 while (pt) {
7291 const char *name = got_tree_entry_get_name(pt->selected_entry);
7292 if (strlcat(*path, name, len) >= len) {
7293 err = got_error(GOT_ERR_NO_SPACE);
7294 goto done;
7296 if (strlcat(*path, "/", len) >= len) {
7297 err = got_error(GOT_ERR_NO_SPACE);
7298 goto done;
7300 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7302 if (te) {
7303 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7304 err = got_error(GOT_ERR_NO_SPACE);
7305 goto done;
7308 done:
7309 if (err) {
7310 free(*path);
7311 *path = NULL;
7313 return err;
7316 static const struct got_error *
7317 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7318 struct got_tree_entry *te, struct tog_parent_trees *parents,
7319 struct got_object_id *commit_id, struct got_repository *repo)
7321 const struct got_error *err = NULL;
7322 char *path;
7323 struct tog_view *blame_view;
7325 *new_view = NULL;
7327 err = tree_entry_path(&path, parents, te);
7328 if (err)
7329 return err;
7331 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7332 if (blame_view == NULL) {
7333 err = got_error_from_errno("view_open");
7334 goto done;
7337 err = open_blame_view(blame_view, path, commit_id, repo);
7338 if (err) {
7339 if (err->code == GOT_ERR_CANCELLED)
7340 err = NULL;
7341 view_close(blame_view);
7342 } else
7343 *new_view = blame_view;
7344 done:
7345 free(path);
7346 return err;
7349 static const struct got_error *
7350 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7351 struct tog_tree_view_state *s)
7353 struct tog_view *log_view;
7354 const struct got_error *err = NULL;
7355 char *path;
7357 *new_view = NULL;
7359 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7360 if (log_view == NULL)
7361 return got_error_from_errno("view_open");
7363 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7364 if (err)
7365 return err;
7367 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7368 path, 0);
7369 if (err)
7370 view_close(log_view);
7371 else
7372 *new_view = log_view;
7373 free(path);
7374 return err;
7377 static const struct got_error *
7378 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7379 const char *head_ref_name, struct got_repository *repo)
7381 const struct got_error *err = NULL;
7382 char *commit_id_str = NULL;
7383 struct tog_tree_view_state *s = &view->state.tree;
7384 struct got_commit_object *commit = NULL;
7386 TAILQ_INIT(&s->parents);
7387 STAILQ_INIT(&s->colors);
7389 s->commit_id = got_object_id_dup(commit_id);
7390 if (s->commit_id == NULL) {
7391 err = got_error_from_errno("got_object_id_dup");
7392 goto done;
7395 err = got_object_open_as_commit(&commit, repo, commit_id);
7396 if (err)
7397 goto done;
7400 * The root is opened here and will be closed when the view is closed.
7401 * Any visited subtrees and their path-wise parents are opened and
7402 * closed on demand.
7404 err = got_object_open_as_tree(&s->root, repo,
7405 got_object_commit_get_tree_id(commit));
7406 if (err)
7407 goto done;
7408 s->tree = s->root;
7410 err = got_object_id_str(&commit_id_str, commit_id);
7411 if (err != NULL)
7412 goto done;
7414 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7415 err = got_error_from_errno("asprintf");
7416 goto done;
7419 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7420 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7421 if (head_ref_name) {
7422 s->head_ref_name = strdup(head_ref_name);
7423 if (s->head_ref_name == NULL) {
7424 err = got_error_from_errno("strdup");
7425 goto done;
7428 s->repo = repo;
7430 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7431 err = add_color(&s->colors, "\\$$",
7432 TOG_COLOR_TREE_SUBMODULE,
7433 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7434 if (err)
7435 goto done;
7436 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7437 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7438 if (err)
7439 goto done;
7440 err = add_color(&s->colors, "/$",
7441 TOG_COLOR_TREE_DIRECTORY,
7442 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7443 if (err)
7444 goto done;
7446 err = add_color(&s->colors, "\\*$",
7447 TOG_COLOR_TREE_EXECUTABLE,
7448 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7449 if (err)
7450 goto done;
7452 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7453 get_color_value("TOG_COLOR_COMMIT"));
7454 if (err)
7455 goto done;
7458 view->show = show_tree_view;
7459 view->input = input_tree_view;
7460 view->close = close_tree_view;
7461 view->search_start = search_start_tree_view;
7462 view->search_next = search_next_tree_view;
7463 done:
7464 free(commit_id_str);
7465 if (commit)
7466 got_object_commit_close(commit);
7467 if (err) {
7468 if (view->close == NULL)
7469 close_tree_view(view);
7470 view_close(view);
7472 return err;
7475 static const struct got_error *
7476 close_tree_view(struct tog_view *view)
7478 struct tog_tree_view_state *s = &view->state.tree;
7480 free_colors(&s->colors);
7481 free(s->tree_label);
7482 s->tree_label = NULL;
7483 free(s->commit_id);
7484 s->commit_id = NULL;
7485 free(s->head_ref_name);
7486 s->head_ref_name = NULL;
7487 while (!TAILQ_EMPTY(&s->parents)) {
7488 struct tog_parent_tree *parent;
7489 parent = TAILQ_FIRST(&s->parents);
7490 TAILQ_REMOVE(&s->parents, parent, entry);
7491 if (parent->tree != s->root)
7492 got_object_tree_close(parent->tree);
7493 free(parent);
7496 if (s->tree != NULL && s->tree != s->root)
7497 got_object_tree_close(s->tree);
7498 if (s->root)
7499 got_object_tree_close(s->root);
7500 return NULL;
7503 static const struct got_error *
7504 search_start_tree_view(struct tog_view *view)
7506 struct tog_tree_view_state *s = &view->state.tree;
7508 s->matched_entry = NULL;
7509 return NULL;
7512 static int
7513 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7515 regmatch_t regmatch;
7517 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7518 0) == 0;
7521 static const struct got_error *
7522 search_next_tree_view(struct tog_view *view)
7524 struct tog_tree_view_state *s = &view->state.tree;
7525 struct got_tree_entry *te = NULL;
7527 if (!view->searching) {
7528 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7529 return NULL;
7532 if (s->matched_entry) {
7533 if (view->searching == TOG_SEARCH_FORWARD) {
7534 if (s->selected_entry)
7535 te = got_tree_entry_get_next(s->tree,
7536 s->selected_entry);
7537 else
7538 te = got_object_tree_get_first_entry(s->tree);
7539 } else {
7540 if (s->selected_entry == NULL)
7541 te = got_object_tree_get_last_entry(s->tree);
7542 else
7543 te = got_tree_entry_get_prev(s->tree,
7544 s->selected_entry);
7546 } else {
7547 if (s->selected_entry)
7548 te = s->selected_entry;
7549 else if (view->searching == TOG_SEARCH_FORWARD)
7550 te = got_object_tree_get_first_entry(s->tree);
7551 else
7552 te = got_object_tree_get_last_entry(s->tree);
7555 while (1) {
7556 if (te == NULL) {
7557 if (s->matched_entry == NULL) {
7558 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7559 return NULL;
7561 if (view->searching == TOG_SEARCH_FORWARD)
7562 te = got_object_tree_get_first_entry(s->tree);
7563 else
7564 te = got_object_tree_get_last_entry(s->tree);
7567 if (match_tree_entry(te, &view->regex)) {
7568 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7569 s->matched_entry = te;
7570 break;
7573 if (view->searching == TOG_SEARCH_FORWARD)
7574 te = got_tree_entry_get_next(s->tree, te);
7575 else
7576 te = got_tree_entry_get_prev(s->tree, te);
7579 if (s->matched_entry) {
7580 s->first_displayed_entry = s->matched_entry;
7581 s->selected = 0;
7584 return NULL;
7587 static const struct got_error *
7588 show_tree_view(struct tog_view *view)
7590 const struct got_error *err = NULL;
7591 struct tog_tree_view_state *s = &view->state.tree;
7592 char *parent_path;
7594 err = tree_entry_path(&parent_path, &s->parents, NULL);
7595 if (err)
7596 return err;
7598 err = draw_tree_entries(view, parent_path);
7599 free(parent_path);
7601 view_border(view);
7602 return err;
7605 static const struct got_error *
7606 tree_goto_line(struct tog_view *view, int nlines)
7608 const struct got_error *err = NULL;
7609 struct tog_tree_view_state *s = &view->state.tree;
7610 struct got_tree_entry **fte, **lte, **ste;
7611 int g, last, first = 1, i = 1;
7612 int root = s->tree == s->root;
7613 int off = root ? 1 : 2;
7615 g = view->gline;
7616 view->gline = 0;
7618 if (g == 0)
7619 g = 1;
7620 else if (g > got_object_tree_get_nentries(s->tree))
7621 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7623 fte = &s->first_displayed_entry;
7624 lte = &s->last_displayed_entry;
7625 ste = &s->selected_entry;
7627 if (*fte != NULL) {
7628 first = got_tree_entry_get_index(*fte);
7629 first += off; /* account for ".." */
7631 last = got_tree_entry_get_index(*lte);
7632 last += off;
7634 if (g >= first && g <= last && g - first < nlines) {
7635 s->selected = g - first;
7636 return NULL; /* gline is on the current page */
7639 if (*ste != NULL) {
7640 i = got_tree_entry_get_index(*ste);
7641 i += off;
7644 if (i < g) {
7645 err = tree_scroll_down(view, g - i);
7646 if (err)
7647 return err;
7648 if (got_tree_entry_get_index(*lte) >=
7649 got_object_tree_get_nentries(s->tree) - 1 &&
7650 first + s->selected < g &&
7651 s->selected < s->ndisplayed - 1) {
7652 first = got_tree_entry_get_index(*fte);
7653 first += off;
7654 s->selected = g - first;
7656 } else if (i > g)
7657 tree_scroll_up(s, i - g);
7659 if (g < nlines &&
7660 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7661 s->selected = g - 1;
7663 return NULL;
7666 static const struct got_error *
7667 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7669 const struct got_error *err = NULL;
7670 struct tog_tree_view_state *s = &view->state.tree;
7671 struct got_tree_entry *te;
7672 int n, nscroll = view->nlines - 3;
7674 if (view->gline)
7675 return tree_goto_line(view, nscroll);
7677 switch (ch) {
7678 case '0':
7679 case '$':
7680 case KEY_RIGHT:
7681 case 'l':
7682 case KEY_LEFT:
7683 case 'h':
7684 horizontal_scroll_input(view, ch);
7685 break;
7686 case 'i':
7687 s->show_ids = !s->show_ids;
7688 view->count = 0;
7689 break;
7690 case 'L':
7691 view->count = 0;
7692 if (!s->selected_entry)
7693 break;
7694 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7695 break;
7696 case 'R':
7697 view->count = 0;
7698 err = view_request_new(new_view, view, TOG_VIEW_REF);
7699 break;
7700 case 'g':
7701 case '=':
7702 case KEY_HOME:
7703 s->selected = 0;
7704 view->count = 0;
7705 if (s->tree == s->root)
7706 s->first_displayed_entry =
7707 got_object_tree_get_first_entry(s->tree);
7708 else
7709 s->first_displayed_entry = NULL;
7710 break;
7711 case 'G':
7712 case '*':
7713 case KEY_END: {
7714 int eos = view->nlines - 3;
7716 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7717 --eos; /* border */
7718 s->selected = 0;
7719 view->count = 0;
7720 te = got_object_tree_get_last_entry(s->tree);
7721 for (n = 0; n < eos; n++) {
7722 if (te == NULL) {
7723 if (s->tree != s->root) {
7724 s->first_displayed_entry = NULL;
7725 n++;
7727 break;
7729 s->first_displayed_entry = te;
7730 te = got_tree_entry_get_prev(s->tree, te);
7732 if (n > 0)
7733 s->selected = n - 1;
7734 break;
7736 case 'k':
7737 case KEY_UP:
7738 case CTRL('p'):
7739 if (s->selected > 0) {
7740 s->selected--;
7741 break;
7743 tree_scroll_up(s, 1);
7744 if (s->selected_entry == NULL ||
7745 (s->tree == s->root && s->selected_entry ==
7746 got_object_tree_get_first_entry(s->tree)))
7747 view->count = 0;
7748 break;
7749 case CTRL('u'):
7750 case 'u':
7751 nscroll /= 2;
7752 /* FALL THROUGH */
7753 case KEY_PPAGE:
7754 case CTRL('b'):
7755 case 'b':
7756 if (s->tree == s->root) {
7757 if (got_object_tree_get_first_entry(s->tree) ==
7758 s->first_displayed_entry)
7759 s->selected -= MIN(s->selected, nscroll);
7760 } else {
7761 if (s->first_displayed_entry == NULL)
7762 s->selected -= MIN(s->selected, nscroll);
7764 tree_scroll_up(s, MAX(0, nscroll));
7765 if (s->selected_entry == NULL ||
7766 (s->tree == s->root && s->selected_entry ==
7767 got_object_tree_get_first_entry(s->tree)))
7768 view->count = 0;
7769 break;
7770 case 'j':
7771 case KEY_DOWN:
7772 case CTRL('n'):
7773 if (s->selected < s->ndisplayed - 1) {
7774 s->selected++;
7775 break;
7777 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7778 == NULL) {
7779 /* can't scroll any further */
7780 view->count = 0;
7781 break;
7783 tree_scroll_down(view, 1);
7784 break;
7785 case CTRL('d'):
7786 case 'd':
7787 nscroll /= 2;
7788 /* FALL THROUGH */
7789 case KEY_NPAGE:
7790 case CTRL('f'):
7791 case 'f':
7792 case ' ':
7793 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7794 == NULL) {
7795 /* can't scroll any further; move cursor down */
7796 if (s->selected < s->ndisplayed - 1)
7797 s->selected += MIN(nscroll,
7798 s->ndisplayed - s->selected - 1);
7799 else
7800 view->count = 0;
7801 break;
7803 tree_scroll_down(view, nscroll);
7804 break;
7805 case KEY_ENTER:
7806 case '\r':
7807 case KEY_BACKSPACE:
7808 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7809 struct tog_parent_tree *parent;
7810 /* user selected '..' */
7811 if (s->tree == s->root) {
7812 view->count = 0;
7813 break;
7815 parent = TAILQ_FIRST(&s->parents);
7816 TAILQ_REMOVE(&s->parents, parent,
7817 entry);
7818 got_object_tree_close(s->tree);
7819 s->tree = parent->tree;
7820 s->first_displayed_entry =
7821 parent->first_displayed_entry;
7822 s->selected_entry =
7823 parent->selected_entry;
7824 s->selected = parent->selected;
7825 if (s->selected > view->nlines - 3) {
7826 err = offset_selection_down(view);
7827 if (err)
7828 break;
7830 free(parent);
7831 } else if (S_ISDIR(got_tree_entry_get_mode(
7832 s->selected_entry))) {
7833 struct got_tree_object *subtree;
7834 view->count = 0;
7835 err = got_object_open_as_tree(&subtree, s->repo,
7836 got_tree_entry_get_id(s->selected_entry));
7837 if (err)
7838 break;
7839 err = tree_view_visit_subtree(s, subtree);
7840 if (err) {
7841 got_object_tree_close(subtree);
7842 break;
7844 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7845 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7846 break;
7847 case KEY_RESIZE:
7848 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7849 s->selected = view->nlines - 4;
7850 view->count = 0;
7851 break;
7852 default:
7853 view->count = 0;
7854 break;
7857 return err;
7860 __dead static void
7861 usage_tree(void)
7863 endwin();
7864 fprintf(stderr,
7865 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7866 getprogname());
7867 exit(1);
7870 static const struct got_error *
7871 cmd_tree(int argc, char *argv[])
7873 const struct got_error *error;
7874 struct got_repository *repo = NULL;
7875 struct got_worktree *worktree = NULL;
7876 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7877 struct got_object_id *commit_id = NULL;
7878 struct got_commit_object *commit = NULL;
7879 const char *commit_id_arg = NULL;
7880 char *label = NULL;
7881 struct got_reference *ref = NULL;
7882 const char *head_ref_name = NULL;
7883 int ch;
7884 struct tog_view *view;
7885 int *pack_fds = NULL;
7887 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7888 switch (ch) {
7889 case 'c':
7890 commit_id_arg = optarg;
7891 break;
7892 case 'r':
7893 repo_path = realpath(optarg, NULL);
7894 if (repo_path == NULL)
7895 return got_error_from_errno2("realpath",
7896 optarg);
7897 break;
7898 default:
7899 usage_tree();
7900 /* NOTREACHED */
7904 argc -= optind;
7905 argv += optind;
7907 if (argc > 1)
7908 usage_tree();
7910 error = got_repo_pack_fds_open(&pack_fds);
7911 if (error != NULL)
7912 goto done;
7914 if (repo_path == NULL) {
7915 cwd = getcwd(NULL, 0);
7916 if (cwd == NULL)
7917 return got_error_from_errno("getcwd");
7918 error = got_worktree_open(&worktree, cwd);
7919 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7920 goto done;
7921 if (worktree)
7922 repo_path =
7923 strdup(got_worktree_get_repo_path(worktree));
7924 else
7925 repo_path = strdup(cwd);
7926 if (repo_path == NULL) {
7927 error = got_error_from_errno("strdup");
7928 goto done;
7932 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7933 if (error != NULL)
7934 goto done;
7936 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7937 repo, worktree);
7938 if (error)
7939 goto done;
7941 init_curses();
7943 error = apply_unveil(got_repo_get_path(repo), NULL);
7944 if (error)
7945 goto done;
7947 error = tog_load_refs(repo, 0);
7948 if (error)
7949 goto done;
7951 if (commit_id_arg == NULL) {
7952 error = got_repo_match_object_id(&commit_id, &label,
7953 worktree ? got_worktree_get_head_ref_name(worktree) :
7954 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7955 if (error)
7956 goto done;
7957 head_ref_name = label;
7958 } else {
7959 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7960 if (error == NULL)
7961 head_ref_name = got_ref_get_name(ref);
7962 else if (error->code != GOT_ERR_NOT_REF)
7963 goto done;
7964 error = got_repo_match_object_id(&commit_id, NULL,
7965 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7966 if (error)
7967 goto done;
7970 error = got_object_open_as_commit(&commit, repo, commit_id);
7971 if (error)
7972 goto done;
7974 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7975 if (view == NULL) {
7976 error = got_error_from_errno("view_open");
7977 goto done;
7979 error = open_tree_view(view, commit_id, head_ref_name, repo);
7980 if (error)
7981 goto done;
7982 if (!got_path_is_root_dir(in_repo_path)) {
7983 error = tree_view_walk_path(&view->state.tree, commit,
7984 in_repo_path);
7985 if (error)
7986 goto done;
7989 if (worktree) {
7990 /* Release work tree lock. */
7991 got_worktree_close(worktree);
7992 worktree = NULL;
7994 error = view_loop(view);
7995 done:
7996 free(repo_path);
7997 free(cwd);
7998 free(commit_id);
7999 free(label);
8000 if (ref)
8001 got_ref_close(ref);
8002 if (repo) {
8003 const struct got_error *close_err = got_repo_close(repo);
8004 if (error == NULL)
8005 error = close_err;
8007 if (pack_fds) {
8008 const struct got_error *pack_err =
8009 got_repo_pack_fds_close(pack_fds);
8010 if (error == NULL)
8011 error = pack_err;
8013 tog_free_refs();
8014 return error;
8017 static const struct got_error *
8018 ref_view_load_refs(struct tog_ref_view_state *s)
8020 struct got_reflist_entry *sre;
8021 struct tog_reflist_entry *re;
8023 s->nrefs = 0;
8024 TAILQ_FOREACH(sre, &tog_refs, entry) {
8025 if (strncmp(got_ref_get_name(sre->ref),
8026 "refs/got/", 9) == 0 &&
8027 strncmp(got_ref_get_name(sre->ref),
8028 "refs/got/backup/", 16) != 0)
8029 continue;
8031 re = malloc(sizeof(*re));
8032 if (re == NULL)
8033 return got_error_from_errno("malloc");
8035 re->ref = got_ref_dup(sre->ref);
8036 if (re->ref == NULL)
8037 return got_error_from_errno("got_ref_dup");
8038 re->idx = s->nrefs++;
8039 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8042 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8043 return NULL;
8046 static void
8047 ref_view_free_refs(struct tog_ref_view_state *s)
8049 struct tog_reflist_entry *re;
8051 while (!TAILQ_EMPTY(&s->refs)) {
8052 re = TAILQ_FIRST(&s->refs);
8053 TAILQ_REMOVE(&s->refs, re, entry);
8054 got_ref_close(re->ref);
8055 free(re);
8059 static const struct got_error *
8060 open_ref_view(struct tog_view *view, struct got_repository *repo)
8062 const struct got_error *err = NULL;
8063 struct tog_ref_view_state *s = &view->state.ref;
8065 s->selected_entry = 0;
8066 s->repo = repo;
8068 TAILQ_INIT(&s->refs);
8069 STAILQ_INIT(&s->colors);
8071 err = ref_view_load_refs(s);
8072 if (err)
8073 goto done;
8075 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8076 err = add_color(&s->colors, "^refs/heads/",
8077 TOG_COLOR_REFS_HEADS,
8078 get_color_value("TOG_COLOR_REFS_HEADS"));
8079 if (err)
8080 goto done;
8082 err = add_color(&s->colors, "^refs/tags/",
8083 TOG_COLOR_REFS_TAGS,
8084 get_color_value("TOG_COLOR_REFS_TAGS"));
8085 if (err)
8086 goto done;
8088 err = add_color(&s->colors, "^refs/remotes/",
8089 TOG_COLOR_REFS_REMOTES,
8090 get_color_value("TOG_COLOR_REFS_REMOTES"));
8091 if (err)
8092 goto done;
8094 err = add_color(&s->colors, "^refs/got/backup/",
8095 TOG_COLOR_REFS_BACKUP,
8096 get_color_value("TOG_COLOR_REFS_BACKUP"));
8097 if (err)
8098 goto done;
8101 view->show = show_ref_view;
8102 view->input = input_ref_view;
8103 view->close = close_ref_view;
8104 view->search_start = search_start_ref_view;
8105 view->search_next = search_next_ref_view;
8106 done:
8107 if (err) {
8108 if (view->close == NULL)
8109 close_ref_view(view);
8110 view_close(view);
8112 return err;
8115 static const struct got_error *
8116 close_ref_view(struct tog_view *view)
8118 struct tog_ref_view_state *s = &view->state.ref;
8120 ref_view_free_refs(s);
8121 free_colors(&s->colors);
8123 return NULL;
8126 static const struct got_error *
8127 resolve_reflist_entry(struct got_object_id **commit_id,
8128 struct tog_reflist_entry *re, struct got_repository *repo)
8130 const struct got_error *err = NULL;
8131 struct got_object_id *obj_id;
8132 struct got_tag_object *tag = NULL;
8133 int obj_type;
8135 *commit_id = NULL;
8137 err = got_ref_resolve(&obj_id, repo, re->ref);
8138 if (err)
8139 return err;
8141 err = got_object_get_type(&obj_type, repo, obj_id);
8142 if (err)
8143 goto done;
8145 switch (obj_type) {
8146 case GOT_OBJ_TYPE_COMMIT:
8147 *commit_id = obj_id;
8148 break;
8149 case GOT_OBJ_TYPE_TAG:
8150 err = got_object_open_as_tag(&tag, repo, obj_id);
8151 if (err)
8152 goto done;
8153 free(obj_id);
8154 err = got_object_get_type(&obj_type, repo,
8155 got_object_tag_get_object_id(tag));
8156 if (err)
8157 goto done;
8158 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8159 err = got_error(GOT_ERR_OBJ_TYPE);
8160 goto done;
8162 *commit_id = got_object_id_dup(
8163 got_object_tag_get_object_id(tag));
8164 if (*commit_id == NULL) {
8165 err = got_error_from_errno("got_object_id_dup");
8166 goto done;
8168 break;
8169 default:
8170 err = got_error(GOT_ERR_OBJ_TYPE);
8171 break;
8174 done:
8175 if (tag)
8176 got_object_tag_close(tag);
8177 if (err) {
8178 free(*commit_id);
8179 *commit_id = NULL;
8181 return err;
8184 static const struct got_error *
8185 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8186 struct tog_reflist_entry *re, struct got_repository *repo)
8188 struct tog_view *log_view;
8189 const struct got_error *err = NULL;
8190 struct got_object_id *commit_id = NULL;
8192 *new_view = NULL;
8194 err = resolve_reflist_entry(&commit_id, re, repo);
8195 if (err) {
8196 if (err->code != GOT_ERR_OBJ_TYPE)
8197 return err;
8198 else
8199 return NULL;
8202 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8203 if (log_view == NULL) {
8204 err = got_error_from_errno("view_open");
8205 goto done;
8208 err = open_log_view(log_view, commit_id, repo,
8209 got_ref_get_name(re->ref), "", 0);
8210 done:
8211 if (err)
8212 view_close(log_view);
8213 else
8214 *new_view = log_view;
8215 free(commit_id);
8216 return err;
8219 static void
8220 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8222 struct tog_reflist_entry *re;
8223 int i = 0;
8225 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8226 return;
8228 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8229 while (i++ < maxscroll) {
8230 if (re == NULL)
8231 break;
8232 s->first_displayed_entry = re;
8233 re = TAILQ_PREV(re, tog_reflist_head, entry);
8237 static const struct got_error *
8238 ref_scroll_down(struct tog_view *view, int maxscroll)
8240 struct tog_ref_view_state *s = &view->state.ref;
8241 struct tog_reflist_entry *next, *last;
8242 int n = 0;
8244 if (s->first_displayed_entry)
8245 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8246 else
8247 next = TAILQ_FIRST(&s->refs);
8249 last = s->last_displayed_entry;
8250 while (next && n++ < maxscroll) {
8251 if (last) {
8252 s->last_displayed_entry = last;
8253 last = TAILQ_NEXT(last, entry);
8255 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8256 s->first_displayed_entry = next;
8257 next = TAILQ_NEXT(next, entry);
8261 return NULL;
8264 static const struct got_error *
8265 search_start_ref_view(struct tog_view *view)
8267 struct tog_ref_view_state *s = &view->state.ref;
8269 s->matched_entry = NULL;
8270 return NULL;
8273 static int
8274 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8276 regmatch_t regmatch;
8278 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8279 0) == 0;
8282 static const struct got_error *
8283 search_next_ref_view(struct tog_view *view)
8285 struct tog_ref_view_state *s = &view->state.ref;
8286 struct tog_reflist_entry *re = NULL;
8288 if (!view->searching) {
8289 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8290 return NULL;
8293 if (s->matched_entry) {
8294 if (view->searching == TOG_SEARCH_FORWARD) {
8295 if (s->selected_entry)
8296 re = TAILQ_NEXT(s->selected_entry, entry);
8297 else
8298 re = TAILQ_PREV(s->selected_entry,
8299 tog_reflist_head, entry);
8300 } else {
8301 if (s->selected_entry == NULL)
8302 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8303 else
8304 re = TAILQ_PREV(s->selected_entry,
8305 tog_reflist_head, entry);
8307 } else {
8308 if (s->selected_entry)
8309 re = s->selected_entry;
8310 else if (view->searching == TOG_SEARCH_FORWARD)
8311 re = TAILQ_FIRST(&s->refs);
8312 else
8313 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8316 while (1) {
8317 if (re == NULL) {
8318 if (s->matched_entry == NULL) {
8319 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8320 return NULL;
8322 if (view->searching == TOG_SEARCH_FORWARD)
8323 re = TAILQ_FIRST(&s->refs);
8324 else
8325 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8328 if (match_reflist_entry(re, &view->regex)) {
8329 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8330 s->matched_entry = re;
8331 break;
8334 if (view->searching == TOG_SEARCH_FORWARD)
8335 re = TAILQ_NEXT(re, entry);
8336 else
8337 re = TAILQ_PREV(re, tog_reflist_head, entry);
8340 if (s->matched_entry) {
8341 s->first_displayed_entry = s->matched_entry;
8342 s->selected = 0;
8345 return NULL;
8348 static const struct got_error *
8349 show_ref_view(struct tog_view *view)
8351 const struct got_error *err = NULL;
8352 struct tog_ref_view_state *s = &view->state.ref;
8353 struct tog_reflist_entry *re;
8354 char *line = NULL;
8355 wchar_t *wline;
8356 struct tog_color *tc;
8357 int width, n, scrollx;
8358 int limit = view->nlines;
8360 werase(view->window);
8362 s->ndisplayed = 0;
8363 if (view_is_hsplit_top(view))
8364 --limit; /* border */
8366 if (limit == 0)
8367 return NULL;
8369 re = s->first_displayed_entry;
8371 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8372 s->nrefs) == -1)
8373 return got_error_from_errno("asprintf");
8375 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8376 if (err) {
8377 free(line);
8378 return err;
8380 if (view_needs_focus_indication(view))
8381 wstandout(view->window);
8382 waddwstr(view->window, wline);
8383 while (width++ < view->ncols)
8384 waddch(view->window, ' ');
8385 if (view_needs_focus_indication(view))
8386 wstandend(view->window);
8387 free(wline);
8388 wline = NULL;
8389 free(line);
8390 line = NULL;
8391 if (--limit <= 0)
8392 return NULL;
8394 n = 0;
8395 view->maxx = 0;
8396 while (re && limit > 0) {
8397 char *line = NULL;
8398 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8400 if (s->show_date) {
8401 struct got_commit_object *ci;
8402 struct got_tag_object *tag;
8403 struct got_object_id *id;
8404 struct tm tm;
8405 time_t t;
8407 err = got_ref_resolve(&id, s->repo, re->ref);
8408 if (err)
8409 return err;
8410 err = got_object_open_as_tag(&tag, s->repo, id);
8411 if (err) {
8412 if (err->code != GOT_ERR_OBJ_TYPE) {
8413 free(id);
8414 return err;
8416 err = got_object_open_as_commit(&ci, s->repo,
8417 id);
8418 if (err) {
8419 free(id);
8420 return err;
8422 t = got_object_commit_get_committer_time(ci);
8423 got_object_commit_close(ci);
8424 } else {
8425 t = got_object_tag_get_tagger_time(tag);
8426 got_object_tag_close(tag);
8428 free(id);
8429 if (gmtime_r(&t, &tm) == NULL)
8430 return got_error_from_errno("gmtime_r");
8431 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8432 return got_error(GOT_ERR_NO_SPACE);
8434 if (got_ref_is_symbolic(re->ref)) {
8435 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8436 ymd : "", got_ref_get_name(re->ref),
8437 got_ref_get_symref_target(re->ref)) == -1)
8438 return got_error_from_errno("asprintf");
8439 } else if (s->show_ids) {
8440 struct got_object_id *id;
8441 char *id_str;
8442 err = got_ref_resolve(&id, s->repo, re->ref);
8443 if (err)
8444 return err;
8445 err = got_object_id_str(&id_str, id);
8446 if (err) {
8447 free(id);
8448 return err;
8450 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8451 got_ref_get_name(re->ref), id_str) == -1) {
8452 err = got_error_from_errno("asprintf");
8453 free(id);
8454 free(id_str);
8455 return err;
8457 free(id);
8458 free(id_str);
8459 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8460 got_ref_get_name(re->ref)) == -1)
8461 return got_error_from_errno("asprintf");
8463 /* use full line width to determine view->maxx */
8464 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8465 if (err) {
8466 free(line);
8467 return err;
8469 view->maxx = MAX(view->maxx, width);
8470 free(wline);
8471 wline = NULL;
8473 err = format_line(&wline, &width, &scrollx, line, view->x,
8474 view->ncols, 0, 0);
8475 if (err) {
8476 free(line);
8477 return err;
8479 if (n == s->selected) {
8480 if (view->focussed)
8481 wstandout(view->window);
8482 s->selected_entry = re;
8484 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8485 if (tc)
8486 wattr_on(view->window,
8487 COLOR_PAIR(tc->colorpair), NULL);
8488 waddwstr(view->window, &wline[scrollx]);
8489 if (tc)
8490 wattr_off(view->window,
8491 COLOR_PAIR(tc->colorpair), NULL);
8492 if (width < view->ncols)
8493 waddch(view->window, '\n');
8494 if (n == s->selected && view->focussed)
8495 wstandend(view->window);
8496 free(line);
8497 free(wline);
8498 wline = NULL;
8499 n++;
8500 s->ndisplayed++;
8501 s->last_displayed_entry = re;
8503 limit--;
8504 re = TAILQ_NEXT(re, entry);
8507 view_border(view);
8508 return err;
8511 static const struct got_error *
8512 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8513 struct tog_reflist_entry *re, struct got_repository *repo)
8515 const struct got_error *err = NULL;
8516 struct got_object_id *commit_id = NULL;
8517 struct tog_view *tree_view;
8519 *new_view = NULL;
8521 err = resolve_reflist_entry(&commit_id, re, repo);
8522 if (err) {
8523 if (err->code != GOT_ERR_OBJ_TYPE)
8524 return err;
8525 else
8526 return NULL;
8530 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8531 if (tree_view == NULL) {
8532 err = got_error_from_errno("view_open");
8533 goto done;
8536 err = open_tree_view(tree_view, commit_id,
8537 got_ref_get_name(re->ref), repo);
8538 if (err)
8539 goto done;
8541 *new_view = tree_view;
8542 done:
8543 free(commit_id);
8544 return err;
8547 static const struct got_error *
8548 ref_goto_line(struct tog_view *view, int nlines)
8550 const struct got_error *err = NULL;
8551 struct tog_ref_view_state *s = &view->state.ref;
8552 int g, idx = s->selected_entry->idx;
8554 g = view->gline;
8555 view->gline = 0;
8557 if (g == 0)
8558 g = 1;
8559 else if (g > s->nrefs)
8560 g = s->nrefs;
8562 if (g >= s->first_displayed_entry->idx + 1 &&
8563 g <= s->last_displayed_entry->idx + 1 &&
8564 g - s->first_displayed_entry->idx - 1 < nlines) {
8565 s->selected = g - s->first_displayed_entry->idx - 1;
8566 return NULL;
8569 if (idx + 1 < g) {
8570 err = ref_scroll_down(view, g - idx - 1);
8571 if (err)
8572 return err;
8573 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8574 s->first_displayed_entry->idx + s->selected < g &&
8575 s->selected < s->ndisplayed - 1)
8576 s->selected = g - s->first_displayed_entry->idx - 1;
8577 } else if (idx + 1 > g)
8578 ref_scroll_up(s, idx - g + 1);
8580 if (g < nlines && s->first_displayed_entry->idx == 0)
8581 s->selected = g - 1;
8583 return NULL;
8587 static const struct got_error *
8588 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8590 const struct got_error *err = NULL;
8591 struct tog_ref_view_state *s = &view->state.ref;
8592 struct tog_reflist_entry *re;
8593 int n, nscroll = view->nlines - 1;
8595 if (view->gline)
8596 return ref_goto_line(view, nscroll);
8598 switch (ch) {
8599 case '0':
8600 case '$':
8601 case KEY_RIGHT:
8602 case 'l':
8603 case KEY_LEFT:
8604 case 'h':
8605 horizontal_scroll_input(view, ch);
8606 break;
8607 case 'i':
8608 s->show_ids = !s->show_ids;
8609 view->count = 0;
8610 break;
8611 case 'm':
8612 s->show_date = !s->show_date;
8613 view->count = 0;
8614 break;
8615 case 'o':
8616 s->sort_by_date = !s->sort_by_date;
8617 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8618 view->count = 0;
8619 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8620 got_ref_cmp_by_commit_timestamp_descending :
8621 tog_ref_cmp_by_name, s->repo);
8622 if (err)
8623 break;
8624 got_reflist_object_id_map_free(tog_refs_idmap);
8625 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8626 &tog_refs, s->repo);
8627 if (err)
8628 break;
8629 ref_view_free_refs(s);
8630 err = ref_view_load_refs(s);
8631 break;
8632 case KEY_ENTER:
8633 case '\r':
8634 view->count = 0;
8635 if (!s->selected_entry)
8636 break;
8637 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8638 break;
8639 case 'T':
8640 view->count = 0;
8641 if (!s->selected_entry)
8642 break;
8643 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8644 break;
8645 case 'g':
8646 case '=':
8647 case KEY_HOME:
8648 s->selected = 0;
8649 view->count = 0;
8650 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8651 break;
8652 case 'G':
8653 case '*':
8654 case KEY_END: {
8655 int eos = view->nlines - 1;
8657 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8658 --eos; /* border */
8659 s->selected = 0;
8660 view->count = 0;
8661 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8662 for (n = 0; n < eos; n++) {
8663 if (re == NULL)
8664 break;
8665 s->first_displayed_entry = re;
8666 re = TAILQ_PREV(re, tog_reflist_head, entry);
8668 if (n > 0)
8669 s->selected = n - 1;
8670 break;
8672 case 'k':
8673 case KEY_UP:
8674 case CTRL('p'):
8675 if (s->selected > 0) {
8676 s->selected--;
8677 break;
8679 ref_scroll_up(s, 1);
8680 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8681 view->count = 0;
8682 break;
8683 case CTRL('u'):
8684 case 'u':
8685 nscroll /= 2;
8686 /* FALL THROUGH */
8687 case KEY_PPAGE:
8688 case CTRL('b'):
8689 case 'b':
8690 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8691 s->selected -= MIN(nscroll, s->selected);
8692 ref_scroll_up(s, MAX(0, nscroll));
8693 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8694 view->count = 0;
8695 break;
8696 case 'j':
8697 case KEY_DOWN:
8698 case CTRL('n'):
8699 if (s->selected < s->ndisplayed - 1) {
8700 s->selected++;
8701 break;
8703 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8704 /* can't scroll any further */
8705 view->count = 0;
8706 break;
8708 ref_scroll_down(view, 1);
8709 break;
8710 case CTRL('d'):
8711 case 'd':
8712 nscroll /= 2;
8713 /* FALL THROUGH */
8714 case KEY_NPAGE:
8715 case CTRL('f'):
8716 case 'f':
8717 case ' ':
8718 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8719 /* can't scroll any further; move cursor down */
8720 if (s->selected < s->ndisplayed - 1)
8721 s->selected += MIN(nscroll,
8722 s->ndisplayed - s->selected - 1);
8723 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8724 s->selected += s->ndisplayed - s->selected - 1;
8725 view->count = 0;
8726 break;
8728 ref_scroll_down(view, nscroll);
8729 break;
8730 case CTRL('l'):
8731 view->count = 0;
8732 tog_free_refs();
8733 err = tog_load_refs(s->repo, s->sort_by_date);
8734 if (err)
8735 break;
8736 ref_view_free_refs(s);
8737 err = ref_view_load_refs(s);
8738 break;
8739 case KEY_RESIZE:
8740 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8741 s->selected = view->nlines - 2;
8742 break;
8743 default:
8744 view->count = 0;
8745 break;
8748 return err;
8751 __dead static void
8752 usage_ref(void)
8754 endwin();
8755 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8756 getprogname());
8757 exit(1);
8760 static const struct got_error *
8761 cmd_ref(int argc, char *argv[])
8763 const struct got_error *error;
8764 struct got_repository *repo = NULL;
8765 struct got_worktree *worktree = NULL;
8766 char *cwd = NULL, *repo_path = NULL;
8767 int ch;
8768 struct tog_view *view;
8769 int *pack_fds = NULL;
8771 while ((ch = getopt(argc, argv, "r:")) != -1) {
8772 switch (ch) {
8773 case 'r':
8774 repo_path = realpath(optarg, NULL);
8775 if (repo_path == NULL)
8776 return got_error_from_errno2("realpath",
8777 optarg);
8778 break;
8779 default:
8780 usage_ref();
8781 /* NOTREACHED */
8785 argc -= optind;
8786 argv += optind;
8788 if (argc > 1)
8789 usage_ref();
8791 error = got_repo_pack_fds_open(&pack_fds);
8792 if (error != NULL)
8793 goto done;
8795 if (repo_path == NULL) {
8796 cwd = getcwd(NULL, 0);
8797 if (cwd == NULL)
8798 return got_error_from_errno("getcwd");
8799 error = got_worktree_open(&worktree, cwd);
8800 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8801 goto done;
8802 if (worktree)
8803 repo_path =
8804 strdup(got_worktree_get_repo_path(worktree));
8805 else
8806 repo_path = strdup(cwd);
8807 if (repo_path == NULL) {
8808 error = got_error_from_errno("strdup");
8809 goto done;
8813 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8814 if (error != NULL)
8815 goto done;
8817 init_curses();
8819 error = apply_unveil(got_repo_get_path(repo), NULL);
8820 if (error)
8821 goto done;
8823 error = tog_load_refs(repo, 0);
8824 if (error)
8825 goto done;
8827 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8828 if (view == NULL) {
8829 error = got_error_from_errno("view_open");
8830 goto done;
8833 error = open_ref_view(view, repo);
8834 if (error)
8835 goto done;
8837 if (worktree) {
8838 /* Release work tree lock. */
8839 got_worktree_close(worktree);
8840 worktree = NULL;
8842 error = view_loop(view);
8843 done:
8844 free(repo_path);
8845 free(cwd);
8846 if (repo) {
8847 const struct got_error *close_err = got_repo_close(repo);
8848 if (close_err)
8849 error = close_err;
8851 if (pack_fds) {
8852 const struct got_error *pack_err =
8853 got_repo_pack_fds_close(pack_fds);
8854 if (error == NULL)
8855 error = pack_err;
8857 tog_free_refs();
8858 return error;
8861 static const struct got_error*
8862 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8863 const char *str)
8865 size_t len;
8867 if (win == NULL)
8868 win = stdscr;
8870 len = strlen(str);
8871 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8873 if (focus)
8874 wstandout(win);
8875 if (mvwprintw(win, y, x, "%s", str) == ERR)
8876 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8877 if (focus)
8878 wstandend(win);
8880 return NULL;
8883 static const struct got_error *
8884 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8886 off_t *p;
8888 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8889 if (p == NULL) {
8890 free(*line_offsets);
8891 *line_offsets = NULL;
8892 return got_error_from_errno("reallocarray");
8895 *line_offsets = p;
8896 (*line_offsets)[*nlines] = off;
8897 ++(*nlines);
8898 return NULL;
8901 static const struct got_error *
8902 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8904 *ret = 0;
8906 for (;n > 0; --n, ++km) {
8907 char *t0, *t, *k;
8908 size_t len = 1;
8910 if (km->keys == NULL)
8911 continue;
8913 t = t0 = strdup(km->keys);
8914 if (t0 == NULL)
8915 return got_error_from_errno("strdup");
8917 len += strlen(t);
8918 while ((k = strsep(&t, " ")) != NULL)
8919 len += strlen(k) > 1 ? 2 : 0;
8920 free(t0);
8921 *ret = MAX(*ret, len);
8924 return NULL;
8928 * Write keymap section headers, keys, and key info in km to f.
8929 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8930 * wrap control and symbolic keys in guillemets, else use <>.
8932 static const struct got_error *
8933 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8935 int n, len = width;
8937 if (km->keys) {
8938 static const char *u8_glyph[] = {
8939 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8940 "\xe2\x80\xba" /* U+203A (utf8 >) */
8942 char *t0, *t, *k;
8943 int cs, s, first = 1;
8945 cs = got_locale_is_utf8();
8947 t = t0 = strdup(km->keys);
8948 if (t0 == NULL)
8949 return got_error_from_errno("strdup");
8951 len = strlen(km->keys);
8952 while ((k = strsep(&t, " ")) != NULL) {
8953 s = strlen(k) > 1; /* control or symbolic key */
8954 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8955 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8956 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8957 if (n < 0) {
8958 free(t0);
8959 return got_error_from_errno("fprintf");
8961 first = 0;
8962 len += s ? 2 : 0;
8963 *off += n;
8965 free(t0);
8967 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8968 if (n < 0)
8969 return got_error_from_errno("fprintf");
8970 *off += n;
8972 return NULL;
8975 static const struct got_error *
8976 format_help(struct tog_help_view_state *s)
8978 const struct got_error *err = NULL;
8979 off_t off = 0;
8980 int i, max, n, show = s->all;
8981 static const struct tog_key_map km[] = {
8982 #define KEYMAP_(info, type) { NULL, (info), type }
8983 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8984 GENERATE_HELP
8985 #undef KEYMAP_
8986 #undef KEY_
8989 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8990 if (err)
8991 return err;
8993 n = nitems(km);
8994 err = max_key_str(&max, km, n);
8995 if (err)
8996 return err;
8998 for (i = 0; i < n; ++i) {
8999 if (km[i].keys == NULL) {
9000 show = s->all;
9001 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9002 km[i].type == s->type || s->all)
9003 show = 1;
9005 if (show) {
9006 err = format_help_line(&off, s->f, &km[i], max);
9007 if (err)
9008 return err;
9009 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9010 if (err)
9011 return err;
9014 fputc('\n', s->f);
9015 ++off;
9016 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9017 return err;
9020 static const struct got_error *
9021 create_help(struct tog_help_view_state *s)
9023 FILE *f;
9024 const struct got_error *err;
9026 free(s->line_offsets);
9027 s->line_offsets = NULL;
9028 s->nlines = 0;
9030 f = got_opentemp();
9031 if (f == NULL)
9032 return got_error_from_errno("got_opentemp");
9033 s->f = f;
9035 err = format_help(s);
9036 if (err)
9037 return err;
9039 if (s->f && fflush(s->f) != 0)
9040 return got_error_from_errno("fflush");
9042 return NULL;
9045 static const struct got_error *
9046 search_start_help_view(struct tog_view *view)
9048 view->state.help.matched_line = 0;
9049 return NULL;
9052 static void
9053 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9054 size_t *nlines, int **first, int **last, int **match, int **selected)
9056 struct tog_help_view_state *s = &view->state.help;
9058 *f = s->f;
9059 *nlines = s->nlines;
9060 *line_offsets = s->line_offsets;
9061 *match = &s->matched_line;
9062 *first = &s->first_displayed_line;
9063 *last = &s->last_displayed_line;
9064 *selected = &s->selected_line;
9067 static const struct got_error *
9068 show_help_view(struct tog_view *view)
9070 struct tog_help_view_state *s = &view->state.help;
9071 const struct got_error *err;
9072 regmatch_t *regmatch = &view->regmatch;
9073 wchar_t *wline;
9074 char *line;
9075 ssize_t linelen;
9076 size_t linesz = 0;
9077 int width, nprinted = 0, rc = 0;
9078 int eos = view->nlines;
9080 if (view_is_hsplit_top(view))
9081 --eos; /* account for border */
9083 s->lineno = 0;
9084 rewind(s->f);
9085 werase(view->window);
9087 if (view->gline > s->nlines - 1)
9088 view->gline = s->nlines - 1;
9090 err = win_draw_center(view->window, 0, 0, view->ncols,
9091 view_needs_focus_indication(view),
9092 "tog help (press q to return to tog)");
9093 if (err)
9094 return err;
9095 if (eos <= 1)
9096 return NULL;
9097 waddstr(view->window, "\n\n");
9098 eos -= 2;
9100 s->eof = 0;
9101 view->maxx = 0;
9102 line = NULL;
9103 while (eos > 0 && nprinted < eos) {
9104 attr_t attr = 0;
9106 linelen = getline(&line, &linesz, s->f);
9107 if (linelen == -1) {
9108 if (!feof(s->f)) {
9109 free(line);
9110 return got_ferror(s->f, GOT_ERR_IO);
9112 s->eof = 1;
9113 break;
9115 if (++s->lineno < s->first_displayed_line)
9116 continue;
9117 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9118 continue;
9119 if (s->lineno == view->hiline)
9120 attr = A_STANDOUT;
9122 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9123 view->x ? 1 : 0);
9124 if (err) {
9125 free(line);
9126 return err;
9128 view->maxx = MAX(view->maxx, width);
9129 free(wline);
9130 wline = NULL;
9132 if (attr)
9133 wattron(view->window, attr);
9134 if (s->first_displayed_line + nprinted == s->matched_line &&
9135 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9136 err = add_matched_line(&width, line, view->ncols - 1, 0,
9137 view->window, view->x, regmatch);
9138 if (err) {
9139 free(line);
9140 return err;
9142 } else {
9143 int skip;
9145 err = format_line(&wline, &width, &skip, line,
9146 view->x, view->ncols, 0, view->x ? 1 : 0);
9147 if (err) {
9148 free(line);
9149 return err;
9151 waddwstr(view->window, &wline[skip]);
9152 free(wline);
9153 wline = NULL;
9155 if (s->lineno == view->hiline) {
9156 while (width++ < view->ncols)
9157 waddch(view->window, ' ');
9158 } else {
9159 if (width < view->ncols)
9160 waddch(view->window, '\n');
9162 if (attr)
9163 wattroff(view->window, attr);
9164 if (++nprinted == 1)
9165 s->first_displayed_line = s->lineno;
9167 free(line);
9168 if (nprinted > 0)
9169 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9170 else
9171 s->last_displayed_line = s->first_displayed_line;
9173 view_border(view);
9175 if (s->eof) {
9176 rc = waddnstr(view->window,
9177 "See the tog(1) manual page for full documentation",
9178 view->ncols - 1);
9179 if (rc == ERR)
9180 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9181 } else {
9182 wmove(view->window, view->nlines - 1, 0);
9183 wclrtoeol(view->window);
9184 wstandout(view->window);
9185 rc = waddnstr(view->window, "scroll down for more...",
9186 view->ncols - 1);
9187 if (rc == ERR)
9188 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9189 if (getcurx(view->window) < view->ncols - 6) {
9190 rc = wprintw(view->window, "[%.0f%%]",
9191 100.00 * s->last_displayed_line / s->nlines);
9192 if (rc == ERR)
9193 return got_error_msg(GOT_ERR_IO, "wprintw");
9195 wstandend(view->window);
9198 return NULL;
9201 static const struct got_error *
9202 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9204 struct tog_help_view_state *s = &view->state.help;
9205 const struct got_error *err = NULL;
9206 char *line = NULL;
9207 ssize_t linelen;
9208 size_t linesz = 0;
9209 int eos, nscroll;
9211 eos = nscroll = view->nlines;
9212 if (view_is_hsplit_top(view))
9213 --eos; /* border */
9215 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9217 switch (ch) {
9218 case '0':
9219 case '$':
9220 case KEY_RIGHT:
9221 case 'l':
9222 case KEY_LEFT:
9223 case 'h':
9224 horizontal_scroll_input(view, ch);
9225 break;
9226 case 'g':
9227 case KEY_HOME:
9228 s->first_displayed_line = 1;
9229 view->count = 0;
9230 break;
9231 case 'G':
9232 case KEY_END:
9233 view->count = 0;
9234 if (s->eof)
9235 break;
9236 s->first_displayed_line = (s->nlines - eos) + 3;
9237 s->eof = 1;
9238 break;
9239 case 'k':
9240 case KEY_UP:
9241 if (s->first_displayed_line > 1)
9242 --s->first_displayed_line;
9243 else
9244 view->count = 0;
9245 break;
9246 case CTRL('u'):
9247 case 'u':
9248 nscroll /= 2;
9249 /* FALL THROUGH */
9250 case KEY_PPAGE:
9251 case CTRL('b'):
9252 case 'b':
9253 if (s->first_displayed_line == 1) {
9254 view->count = 0;
9255 break;
9257 while (--nscroll > 0 && s->first_displayed_line > 1)
9258 s->first_displayed_line--;
9259 break;
9260 case 'j':
9261 case KEY_DOWN:
9262 case CTRL('n'):
9263 if (!s->eof)
9264 ++s->first_displayed_line;
9265 else
9266 view->count = 0;
9267 break;
9268 case CTRL('d'):
9269 case 'd':
9270 nscroll /= 2;
9271 /* FALL THROUGH */
9272 case KEY_NPAGE:
9273 case CTRL('f'):
9274 case 'f':
9275 case ' ':
9276 if (s->eof) {
9277 view->count = 0;
9278 break;
9280 while (!s->eof && --nscroll > 0) {
9281 linelen = getline(&line, &linesz, s->f);
9282 s->first_displayed_line++;
9283 if (linelen == -1) {
9284 if (feof(s->f))
9285 s->eof = 1;
9286 else
9287 err = got_ferror(s->f, GOT_ERR_IO);
9288 break;
9291 free(line);
9292 break;
9293 default:
9294 view->count = 0;
9295 break;
9298 return err;
9301 static const struct got_error *
9302 close_help_view(struct tog_view *view)
9304 struct tog_help_view_state *s = &view->state.help;
9306 free(s->line_offsets);
9307 s->line_offsets = NULL;
9308 if (fclose(s->f) == EOF)
9309 return got_error_from_errno("fclose");
9311 return NULL;
9314 static const struct got_error *
9315 reset_help_view(struct tog_view *view)
9317 struct tog_help_view_state *s = &view->state.help;
9320 if (s->f && fclose(s->f) == EOF)
9321 return got_error_from_errno("fclose");
9323 wclear(view->window);
9324 view->count = 0;
9325 view->x = 0;
9326 s->all = !s->all;
9327 s->first_displayed_line = 1;
9328 s->last_displayed_line = view->nlines;
9329 s->matched_line = 0;
9331 return create_help(s);
9334 static const struct got_error *
9335 open_help_view(struct tog_view *view, struct tog_view *parent)
9337 const struct got_error *err = NULL;
9338 struct tog_help_view_state *s = &view->state.help;
9340 s->type = (enum tog_keymap_type)parent->type;
9341 s->first_displayed_line = 1;
9342 s->last_displayed_line = view->nlines;
9343 s->selected_line = 1;
9345 view->show = show_help_view;
9346 view->input = input_help_view;
9347 view->reset = reset_help_view;
9348 view->close = close_help_view;
9349 view->search_start = search_start_help_view;
9350 view->search_setup = search_setup_help_view;
9351 view->search_next = search_next_view_match;
9353 err = create_help(s);
9354 return err;
9357 static const struct got_error *
9358 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9359 enum tog_view_type request, int y, int x)
9361 const struct got_error *err = NULL;
9363 *new_view = NULL;
9365 switch (request) {
9366 case TOG_VIEW_DIFF:
9367 if (view->type == TOG_VIEW_LOG) {
9368 struct tog_log_view_state *s = &view->state.log;
9370 err = open_diff_view_for_commit(new_view, y, x,
9371 s->selected_entry->commit, s->selected_entry->id,
9372 view, s->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_BLAME:
9378 if (view->type == TOG_VIEW_TREE) {
9379 struct tog_tree_view_state *s = &view->state.tree;
9381 err = blame_tree_entry(new_view, y, x,
9382 s->selected_entry, &s->parents, s->commit_id,
9383 s->repo);
9384 } else
9385 return got_error_msg(GOT_ERR_NOT_IMPL,
9386 "parent/child view pair not supported");
9387 break;
9388 case TOG_VIEW_LOG:
9389 if (view->type == TOG_VIEW_BLAME)
9390 err = log_annotated_line(new_view, y, x,
9391 view->state.blame.repo, view->state.blame.id_to_log);
9392 else if (view->type == TOG_VIEW_TREE)
9393 err = log_selected_tree_entry(new_view, y, x,
9394 &view->state.tree);
9395 else if (view->type == TOG_VIEW_REF)
9396 err = log_ref_entry(new_view, y, x,
9397 view->state.ref.selected_entry,
9398 view->state.ref.repo);
9399 else
9400 return got_error_msg(GOT_ERR_NOT_IMPL,
9401 "parent/child view pair not supported");
9402 break;
9403 case TOG_VIEW_TREE:
9404 if (view->type == TOG_VIEW_LOG)
9405 err = browse_commit_tree(new_view, y, x,
9406 view->state.log.selected_entry,
9407 view->state.log.in_repo_path,
9408 view->state.log.head_ref_name,
9409 view->state.log.repo);
9410 else if (view->type == TOG_VIEW_REF)
9411 err = browse_ref_tree(new_view, y, x,
9412 view->state.ref.selected_entry,
9413 view->state.ref.repo);
9414 else
9415 return got_error_msg(GOT_ERR_NOT_IMPL,
9416 "parent/child view pair not supported");
9417 break;
9418 case TOG_VIEW_REF:
9419 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9420 if (*new_view == NULL)
9421 return got_error_from_errno("view_open");
9422 if (view->type == TOG_VIEW_LOG)
9423 err = open_ref_view(*new_view, view->state.log.repo);
9424 else if (view->type == TOG_VIEW_TREE)
9425 err = open_ref_view(*new_view, view->state.tree.repo);
9426 else
9427 err = got_error_msg(GOT_ERR_NOT_IMPL,
9428 "parent/child view pair not supported");
9429 if (err)
9430 view_close(*new_view);
9431 break;
9432 case TOG_VIEW_HELP:
9433 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9434 if (*new_view == NULL)
9435 return got_error_from_errno("view_open");
9436 err = open_help_view(*new_view, view);
9437 if (err)
9438 view_close(*new_view);
9439 break;
9440 default:
9441 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9444 return err;
9448 * If view was scrolled down to move the selected line into view when opening a
9449 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9451 static void
9452 offset_selection_up(struct tog_view *view)
9454 switch (view->type) {
9455 case TOG_VIEW_BLAME: {
9456 struct tog_blame_view_state *s = &view->state.blame;
9457 if (s->first_displayed_line == 1) {
9458 s->selected_line = MAX(s->selected_line - view->offset,
9459 1);
9460 break;
9462 if (s->first_displayed_line > view->offset)
9463 s->first_displayed_line -= view->offset;
9464 else
9465 s->first_displayed_line = 1;
9466 s->selected_line += view->offset;
9467 break;
9469 case TOG_VIEW_LOG:
9470 log_scroll_up(&view->state.log, view->offset);
9471 view->state.log.selected += view->offset;
9472 break;
9473 case TOG_VIEW_REF:
9474 ref_scroll_up(&view->state.ref, view->offset);
9475 view->state.ref.selected += view->offset;
9476 break;
9477 case TOG_VIEW_TREE:
9478 tree_scroll_up(&view->state.tree, view->offset);
9479 view->state.tree.selected += view->offset;
9480 break;
9481 default:
9482 break;
9485 view->offset = 0;
9489 * If the selected line is in the section of screen covered by the bottom split,
9490 * scroll down offset lines to move it into view and index its new position.
9492 static const struct got_error *
9493 offset_selection_down(struct tog_view *view)
9495 const struct got_error *err = NULL;
9496 const struct got_error *(*scrolld)(struct tog_view *, int);
9497 int *selected = NULL;
9498 int header, offset;
9500 switch (view->type) {
9501 case TOG_VIEW_BLAME: {
9502 struct tog_blame_view_state *s = &view->state.blame;
9503 header = 3;
9504 scrolld = NULL;
9505 if (s->selected_line > view->nlines - header) {
9506 offset = abs(view->nlines - s->selected_line - header);
9507 s->first_displayed_line += offset;
9508 s->selected_line -= offset;
9509 view->offset = offset;
9511 break;
9513 case TOG_VIEW_LOG: {
9514 struct tog_log_view_state *s = &view->state.log;
9515 scrolld = &log_scroll_down;
9516 header = view_is_parent_view(view) ? 3 : 2;
9517 selected = &s->selected;
9518 break;
9520 case TOG_VIEW_REF: {
9521 struct tog_ref_view_state *s = &view->state.ref;
9522 scrolld = &ref_scroll_down;
9523 header = 3;
9524 selected = &s->selected;
9525 break;
9527 case TOG_VIEW_TREE: {
9528 struct tog_tree_view_state *s = &view->state.tree;
9529 scrolld = &tree_scroll_down;
9530 header = 5;
9531 selected = &s->selected;
9532 break;
9534 default:
9535 selected = NULL;
9536 scrolld = NULL;
9537 header = 0;
9538 break;
9541 if (selected && *selected > view->nlines - header) {
9542 offset = abs(view->nlines - *selected - header);
9543 view->offset = offset;
9544 if (scrolld && offset) {
9545 err = scrolld(view, offset);
9546 *selected -= offset;
9550 return err;
9553 static void
9554 list_commands(FILE *fp)
9556 size_t i;
9558 fprintf(fp, "commands:");
9559 for (i = 0; i < nitems(tog_commands); i++) {
9560 const struct tog_cmd *cmd = &tog_commands[i];
9561 fprintf(fp, " %s", cmd->name);
9563 fputc('\n', fp);
9566 __dead static void
9567 usage(int hflag, int status)
9569 FILE *fp = (status == 0) ? stdout : stderr;
9571 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9572 getprogname());
9573 if (hflag) {
9574 fprintf(fp, "lazy usage: %s path\n", getprogname());
9575 list_commands(fp);
9577 exit(status);
9580 static char **
9581 make_argv(int argc, ...)
9583 va_list ap;
9584 char **argv;
9585 int i;
9587 va_start(ap, argc);
9589 argv = calloc(argc, sizeof(char *));
9590 if (argv == NULL)
9591 err(1, "calloc");
9592 for (i = 0; i < argc; i++) {
9593 argv[i] = strdup(va_arg(ap, char *));
9594 if (argv[i] == NULL)
9595 err(1, "strdup");
9598 va_end(ap);
9599 return argv;
9603 * Try to convert 'tog path' into a 'tog log path' command.
9604 * The user could simply have mistyped the command rather than knowingly
9605 * provided a path. So check whether argv[0] can in fact be resolved
9606 * to a path in the HEAD commit and print a special error if not.
9607 * This hack is for mpi@ <3
9609 static const struct got_error *
9610 tog_log_with_path(int argc, char *argv[])
9612 const struct got_error *error = NULL, *close_err;
9613 const struct tog_cmd *cmd = NULL;
9614 struct got_repository *repo = NULL;
9615 struct got_worktree *worktree = NULL;
9616 struct got_object_id *commit_id = NULL, *id = NULL;
9617 struct got_commit_object *commit = NULL;
9618 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9619 char *commit_id_str = NULL, **cmd_argv = NULL;
9620 int *pack_fds = NULL;
9622 cwd = getcwd(NULL, 0);
9623 if (cwd == NULL)
9624 return got_error_from_errno("getcwd");
9626 error = got_repo_pack_fds_open(&pack_fds);
9627 if (error != NULL)
9628 goto done;
9630 error = got_worktree_open(&worktree, cwd);
9631 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9632 goto done;
9634 if (worktree)
9635 repo_path = strdup(got_worktree_get_repo_path(worktree));
9636 else
9637 repo_path = strdup(cwd);
9638 if (repo_path == NULL) {
9639 error = got_error_from_errno("strdup");
9640 goto done;
9643 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9644 if (error != NULL)
9645 goto done;
9647 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9648 repo, worktree);
9649 if (error)
9650 goto done;
9652 error = tog_load_refs(repo, 0);
9653 if (error)
9654 goto done;
9655 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9656 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9657 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9658 if (error)
9659 goto done;
9661 if (worktree) {
9662 got_worktree_close(worktree);
9663 worktree = NULL;
9666 error = got_object_open_as_commit(&commit, repo, commit_id);
9667 if (error)
9668 goto done;
9670 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9671 if (error) {
9672 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9673 goto done;
9674 fprintf(stderr, "%s: '%s' is no known command or path\n",
9675 getprogname(), argv[0]);
9676 usage(1, 1);
9677 /* not reached */
9680 error = got_object_id_str(&commit_id_str, commit_id);
9681 if (error)
9682 goto done;
9684 cmd = &tog_commands[0]; /* log */
9685 argc = 4;
9686 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9687 error = cmd->cmd_main(argc, cmd_argv);
9688 done:
9689 if (repo) {
9690 close_err = got_repo_close(repo);
9691 if (error == NULL)
9692 error = close_err;
9694 if (commit)
9695 got_object_commit_close(commit);
9696 if (worktree)
9697 got_worktree_close(worktree);
9698 if (pack_fds) {
9699 const struct got_error *pack_err =
9700 got_repo_pack_fds_close(pack_fds);
9701 if (error == NULL)
9702 error = pack_err;
9704 free(id);
9705 free(commit_id_str);
9706 free(commit_id);
9707 free(cwd);
9708 free(repo_path);
9709 free(in_repo_path);
9710 if (cmd_argv) {
9711 int i;
9712 for (i = 0; i < argc; i++)
9713 free(cmd_argv[i]);
9714 free(cmd_argv);
9716 tog_free_refs();
9717 return error;
9720 int
9721 main(int argc, char *argv[])
9723 const struct got_error *io_err, *error = NULL;
9724 const struct tog_cmd *cmd = NULL;
9725 int ch, hflag = 0, Vflag = 0;
9726 char **cmd_argv = NULL;
9727 static const struct option longopts[] = {
9728 { "version", no_argument, NULL, 'V' },
9729 { NULL, 0, NULL, 0}
9731 char *diff_algo_str = NULL;
9732 const char *test_script_path;
9734 setlocale(LC_CTYPE, "");
9737 * Test mode init must happen before pledge() because "tty" will
9738 * not allow TTY-related ioctls to occur via regular files.
9740 test_script_path = getenv("GOT_TOG_TEST");
9741 if (test_script_path != NULL) {
9742 error = init_mock_term(test_script_path);
9743 if (error) {
9744 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9745 return 1;
9749 #if !defined(PROFILE)
9750 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9751 NULL) == -1)
9752 err(1, "pledge");
9753 #endif
9755 if (!isatty(STDIN_FILENO))
9756 errx(1, "standard input is not a tty");
9758 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9759 switch (ch) {
9760 case 'h':
9761 hflag = 1;
9762 break;
9763 case 'V':
9764 Vflag = 1;
9765 break;
9766 default:
9767 usage(hflag, 1);
9768 /* NOTREACHED */
9772 argc -= optind;
9773 argv += optind;
9774 optind = 1;
9775 optreset = 1;
9777 if (Vflag) {
9778 got_version_print_str();
9779 return 0;
9782 if (argc == 0) {
9783 if (hflag)
9784 usage(hflag, 0);
9785 /* Build an argument vector which runs a default command. */
9786 cmd = &tog_commands[0];
9787 argc = 1;
9788 cmd_argv = make_argv(argc, cmd->name);
9789 } else {
9790 size_t i;
9792 /* Did the user specify a command? */
9793 for (i = 0; i < nitems(tog_commands); i++) {
9794 if (strncmp(tog_commands[i].name, argv[0],
9795 strlen(argv[0])) == 0) {
9796 cmd = &tog_commands[i];
9797 break;
9802 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9803 if (diff_algo_str) {
9804 if (strcasecmp(diff_algo_str, "patience") == 0)
9805 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9806 if (strcasecmp(diff_algo_str, "myers") == 0)
9807 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9810 if (cmd == NULL) {
9811 if (argc != 1)
9812 usage(0, 1);
9813 /* No command specified; try log with a path */
9814 error = tog_log_with_path(argc, argv);
9815 } else {
9816 if (hflag)
9817 cmd->cmd_usage();
9818 else
9819 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9822 if (using_mock_io) {
9823 io_err = tog_io_close();
9824 if (error == NULL)
9825 error = io_err;
9827 endwin();
9828 if (cmd_argv) {
9829 int i;
9830 for (i = 0; i < argc; i++)
9831 free(cmd_argv[i]);
9832 free(cmd_argv);
9835 if (error && error->code != GOT_ERR_CANCELLED &&
9836 error->code != GOT_ERR_EOF &&
9837 error->code != GOT_ERR_PRIVSEP_EXIT &&
9838 error->code != GOT_ERR_PRIVSEP_PIPE &&
9839 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9840 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9841 return 0;