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 "got_compat.h"
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 #include <sys/ioctl.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #if defined(__FreeBSD__) || defined(__APPLE__)
26 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
27 #endif
28 #include <curses.h>
29 #include <panel.h>
30 #include <locale.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <err.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <wchar.h>
41 #include <time.h>
42 #include <pthread.h>
43 #include <libgen.h>
44 #include <regex.h>
45 #include <sched.h>
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
159 static const struct got_error *
160 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
161 struct got_reference* re2)
163 const char *name1 = got_ref_get_name(re1);
164 const char *name2 = got_ref_get_name(re2);
165 int isbackup1, isbackup2;
167 /* Sort backup refs towards the bottom of the list. */
168 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
169 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
170 if (!isbackup1 && isbackup2) {
171 *cmp = -1;
172 return NULL;
173 } else if (isbackup1 && !isbackup2) {
174 *cmp = 1;
175 return NULL;
178 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
179 return NULL;
182 static const struct got_error *
183 tog_load_refs(struct got_repository *repo, int sort_by_date)
185 const struct got_error *err;
187 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
188 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
189 repo);
190 if (err)
191 return err;
193 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
194 repo);
197 static void
198 tog_free_refs(void)
200 if (tog_refs_idmap) {
201 got_reflist_object_id_map_free(tog_refs_idmap);
202 tog_refs_idmap = NULL;
204 got_ref_list_free(&tog_refs);
207 static const struct got_error *
208 add_color(struct tog_colors *colors, const char *pattern,
209 int idx, short color)
211 const struct got_error *err = NULL;
212 struct tog_color *tc;
213 int regerr = 0;
215 if (idx < 1 || idx > COLOR_PAIRS - 1)
216 return NULL;
218 init_pair(idx, color, -1);
220 tc = calloc(1, sizeof(*tc));
221 if (tc == NULL)
222 return got_error_from_errno("calloc");
223 regerr = regcomp(&tc->regex, pattern,
224 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
225 if (regerr) {
226 static char regerr_msg[512];
227 static char err_msg[512];
228 regerror(regerr, &tc->regex, regerr_msg,
229 sizeof(regerr_msg));
230 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
231 regerr_msg);
232 err = got_error_msg(GOT_ERR_REGEX, err_msg);
233 free(tc);
234 return err;
236 tc->colorpair = idx;
237 STAILQ_INSERT_HEAD(colors, tc, entry);
238 return NULL;
241 static void
242 free_colors(struct tog_colors *colors)
244 struct tog_color *tc;
246 while (!STAILQ_EMPTY(colors)) {
247 tc = STAILQ_FIRST(colors);
248 STAILQ_REMOVE_HEAD(colors, entry);
249 regfree(&tc->regex);
250 free(tc);
254 static struct tog_color *
255 get_color(struct tog_colors *colors, int colorpair)
257 struct tog_color *tc = NULL;
259 STAILQ_FOREACH(tc, colors, entry) {
260 if (tc->colorpair == colorpair)
261 return tc;
264 return NULL;
267 static int
268 default_color_value(const char *envvar)
270 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
271 return COLOR_MAGENTA;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
273 return COLOR_CYAN;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
275 return COLOR_YELLOW;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
277 return COLOR_GREEN;
278 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
279 return COLOR_MAGENTA;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
283 return COLOR_CYAN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
285 return COLOR_GREEN;
286 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
291 return COLOR_YELLOW;
292 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
295 return COLOR_MAGENTA;
296 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
299 return COLOR_CYAN;
301 return -1;
304 static int
305 get_color_value(const char *envvar)
307 const char *val = getenv(envvar);
309 if (val == NULL)
310 return default_color_value(envvar);
312 if (strcasecmp(val, "black") == 0)
313 return COLOR_BLACK;
314 if (strcasecmp(val, "red") == 0)
315 return COLOR_RED;
316 if (strcasecmp(val, "green") == 0)
317 return COLOR_GREEN;
318 if (strcasecmp(val, "yellow") == 0)
319 return COLOR_YELLOW;
320 if (strcasecmp(val, "blue") == 0)
321 return COLOR_BLUE;
322 if (strcasecmp(val, "magenta") == 0)
323 return COLOR_MAGENTA;
324 if (strcasecmp(val, "cyan") == 0)
325 return COLOR_CYAN;
326 if (strcasecmp(val, "white") == 0)
327 return COLOR_WHITE;
328 if (strcasecmp(val, "default") == 0)
329 return -1;
331 return default_color_value(envvar);
334 struct tog_diff_view_state {
335 struct got_object_id *id1, *id2;
336 const char *label1, *label2;
337 FILE *f, *f1, *f2;
338 int fd1, fd2;
339 int lineno;
340 int first_displayed_line;
341 int last_displayed_line;
342 int eof;
343 int diff_context;
344 int ignore_whitespace;
345 int force_text_diff;
346 struct got_repository *repo;
347 struct got_diff_line *lines;
348 size_t nlines;
349 int matched_line;
350 int selected_line;
352 /* passed from log or blame view; may be NULL */
353 struct tog_view *parent_view;
354 };
356 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
357 static volatile sig_atomic_t tog_thread_error;
359 struct tog_log_thread_args {
360 pthread_cond_t need_commits;
361 pthread_cond_t commit_loaded;
362 int commits_needed;
363 int load_all;
364 struct got_commit_graph *graph;
365 struct commit_queue *real_commits;
366 const char *in_repo_path;
367 struct got_object_id *start_id;
368 struct got_repository *repo;
369 int *pack_fds;
370 int log_complete;
371 sig_atomic_t *quit;
372 struct commit_queue_entry **first_displayed_entry;
373 struct commit_queue_entry **selected_entry;
374 int *searching;
375 int *search_next_done;
376 regex_t *regex;
377 int *limiting;
378 int limit_match;
379 regex_t *limit_regex;
380 struct commit_queue *limit_commits;
381 };
383 struct tog_log_view_state {
384 struct commit_queue *commits;
385 struct commit_queue_entry *first_displayed_entry;
386 struct commit_queue_entry *last_displayed_entry;
387 struct commit_queue_entry *selected_entry;
388 struct commit_queue real_commits;
389 int selected;
390 char *in_repo_path;
391 char *head_ref_name;
392 int log_branches;
393 struct got_repository *repo;
394 struct got_object_id *start_id;
395 sig_atomic_t quit;
396 pthread_t thread;
397 struct tog_log_thread_args thread_args;
398 struct commit_queue_entry *matched_entry;
399 struct commit_queue_entry *search_entry;
400 struct tog_colors colors;
401 int use_committer;
402 int limit_view;
403 regex_t limit_regex;
404 struct commit_queue limit_commits;
405 };
407 #define TOG_COLOR_DIFF_MINUS 1
408 #define TOG_COLOR_DIFF_PLUS 2
409 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
410 #define TOG_COLOR_DIFF_META 4
411 #define TOG_COLOR_TREE_SUBMODULE 5
412 #define TOG_COLOR_TREE_SYMLINK 6
413 #define TOG_COLOR_TREE_DIRECTORY 7
414 #define TOG_COLOR_TREE_EXECUTABLE 8
415 #define TOG_COLOR_COMMIT 9
416 #define TOG_COLOR_AUTHOR 10
417 #define TOG_COLOR_DATE 11
418 #define TOG_COLOR_REFS_HEADS 12
419 #define TOG_COLOR_REFS_TAGS 13
420 #define TOG_COLOR_REFS_REMOTES 14
421 #define TOG_COLOR_REFS_BACKUP 15
423 struct tog_blame_cb_args {
424 struct tog_blame_line *lines; /* one per line */
425 int nlines;
427 struct tog_view *view;
428 struct got_object_id *commit_id;
429 int *quit;
430 };
432 struct tog_blame_thread_args {
433 const char *path;
434 struct got_repository *repo;
435 struct tog_blame_cb_args *cb_args;
436 int *complete;
437 got_cancel_cb cancel_cb;
438 void *cancel_arg;
439 };
441 struct tog_blame {
442 FILE *f;
443 off_t filesize;
444 struct tog_blame_line *lines;
445 int nlines;
446 off_t *line_offsets;
447 pthread_t thread;
448 struct tog_blame_thread_args thread_args;
449 struct tog_blame_cb_args cb_args;
450 const char *path;
451 int *pack_fds;
452 };
454 struct tog_blame_view_state {
455 int first_displayed_line;
456 int last_displayed_line;
457 int selected_line;
458 int last_diffed_line;
459 int blame_complete;
460 int eof;
461 int done;
462 struct got_object_id_queue blamed_commits;
463 struct got_object_qid *blamed_commit;
464 char *path;
465 struct got_repository *repo;
466 struct got_object_id *commit_id;
467 struct got_object_id *id_to_log;
468 struct tog_blame blame;
469 int matched_line;
470 struct tog_colors colors;
471 };
473 struct tog_parent_tree {
474 TAILQ_ENTRY(tog_parent_tree) entry;
475 struct got_tree_object *tree;
476 struct got_tree_entry *first_displayed_entry;
477 struct got_tree_entry *selected_entry;
478 int selected;
479 };
481 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
483 struct tog_tree_view_state {
484 char *tree_label;
485 struct got_object_id *commit_id;/* commit which this tree belongs to */
486 struct got_tree_object *root; /* the commit's root tree entry */
487 struct got_tree_object *tree; /* currently displayed (sub-)tree */
488 struct got_tree_entry *first_displayed_entry;
489 struct got_tree_entry *last_displayed_entry;
490 struct got_tree_entry *selected_entry;
491 int ndisplayed, selected, show_ids;
492 struct tog_parent_trees parents; /* parent trees of current sub-tree */
493 char *head_ref_name;
494 struct got_repository *repo;
495 struct got_tree_entry *matched_entry;
496 struct tog_colors colors;
497 };
499 struct tog_reflist_entry {
500 TAILQ_ENTRY(tog_reflist_entry) entry;
501 struct got_reference *ref;
502 int idx;
503 };
505 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
507 struct tog_ref_view_state {
508 struct tog_reflist_head refs;
509 struct tog_reflist_entry *first_displayed_entry;
510 struct tog_reflist_entry *last_displayed_entry;
511 struct tog_reflist_entry *selected_entry;
512 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
513 struct got_repository *repo;
514 struct tog_reflist_entry *matched_entry;
515 struct tog_colors colors;
516 };
518 struct tog_help_view_state {
519 FILE *f;
520 off_t *line_offsets;
521 size_t nlines;
522 int lineno;
523 int first_displayed_line;
524 int last_displayed_line;
525 int eof;
526 int matched_line;
527 int selected_line;
528 int all;
529 enum tog_keymap_type type;
530 };
532 #define GENERATE_HELP \
533 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
534 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
535 KEY_("k C-p Up", "Move cursor or page up one line"), \
536 KEY_("j C-n Down", "Move cursor or page down one line"), \
537 KEY_("C-b b PgUp", "Scroll the view up one page"), \
538 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
539 KEY_("C-u u", "Scroll the view up one half page"), \
540 KEY_("C-d d", "Scroll the view down one half page"), \
541 KEY_("g", "Go to line N (default: first line)"), \
542 KEY_("Home =", "Go to the first line"), \
543 KEY_("G", "Go to line N (default: last line)"), \
544 KEY_("End *", "Go to the last line"), \
545 KEY_("l Right", "Scroll the view right"), \
546 KEY_("h Left", "Scroll the view left"), \
547 KEY_("$", "Scroll view to the rightmost position"), \
548 KEY_("0", "Scroll view to the leftmost position"), \
549 KEY_("-", "Decrease size of the focussed split"), \
550 KEY_("+", "Increase size of the focussed split"), \
551 KEY_("Tab", "Switch focus between views"), \
552 KEY_("F", "Toggle fullscreen mode"), \
553 KEY_("/", "Open prompt to enter search term"), \
554 KEY_("n", "Find next line/token matching the current search term"), \
555 KEY_("N", "Find previous line/token matching the current search term"),\
556 KEY_("q", "Quit the focussed view; Quit help screen"), \
557 KEY_("Q", "Quit tog"), \
559 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
560 KEY_("< ,", "Move cursor up one commit"), \
561 KEY_("> .", "Move cursor down one commit"), \
562 KEY_("Enter", "Open diff view of the selected commit"), \
563 KEY_("B", "Reload the log view and toggle display of merged commits"), \
564 KEY_("R", "Open ref view of all repository references"), \
565 KEY_("T", "Display tree view of the repository from the selected" \
566 " commit"), \
567 KEY_("@", "Toggle between displaying author and committer name"), \
568 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
569 KEY_("C-g Backspace", "Cancel current search or log operation"), \
570 KEY_("C-l", "Reload the log view with new commits in the repository"), \
572 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
573 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
574 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
575 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
576 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
577 " data"), \
578 KEY_("(", "Go to the previous file in the diff"), \
579 KEY_(")", "Go to the next file in the diff"), \
580 KEY_("{", "Go to the previous hunk in the diff"), \
581 KEY_("}", "Go to the next hunk in the diff"), \
582 KEY_("[", "Decrease the number of context lines"), \
583 KEY_("]", "Increase the number of context lines"), \
584 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
586 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
587 KEY_("Enter", "Display diff view of the selected line's commit"), \
588 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
589 KEY_("L", "Open log view for the currently selected annotated line"), \
590 KEY_("C", "Reload view with the previously blamed commit"), \
591 KEY_("c", "Reload view with the version of the file found in the" \
592 " selected line's commit"), \
593 KEY_("p", "Reload view with the version of the file found in the" \
594 " selected line's parent commit"), \
596 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
597 KEY_("Enter", "Enter selected directory or open blame view of the" \
598 " selected file"), \
599 KEY_("L", "Open log view for the selected entry"), \
600 KEY_("R", "Open ref view of all repository references"), \
601 KEY_("i", "Show object IDs for all tree entries"), \
602 KEY_("Backspace", "Return to the parent directory"), \
604 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
605 KEY_("Enter", "Display log view of the selected reference"), \
606 KEY_("T", "Display tree view of the selected reference"), \
607 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
608 KEY_("m", "Toggle display of last modified date for each reference"), \
609 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
610 KEY_("C-l", "Reload view with all repository references")
612 struct tog_key_map {
613 const char *keys;
614 const char *info;
615 enum tog_keymap_type type;
616 };
618 /* curses io for tog regress */
619 struct tog_io {
620 FILE *cin;
621 FILE *cout;
622 FILE *f;
623 } tog_io;
624 static int using_mock_io;
626 #define TOG_SCREEN_DUMP "SCREENDUMP"
627 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
628 #define TOG_KEY_SCRDUMP SHRT_MIN
630 /*
631 * We implement two types of views: parent views and child views.
633 * The 'Tab' key switches focus between a parent view and its child view.
634 * Child views are shown side-by-side to their parent view, provided
635 * there is enough screen estate.
637 * When a new view is opened from within a parent view, this new view
638 * becomes a child view of the parent view, replacing any existing child.
640 * When a new view is opened from within a child view, this new view
641 * becomes a parent view which will obscure the views below until the
642 * user quits the new parent view by typing 'q'.
644 * This list of views contains parent views only.
645 * Child views are only pointed to by their parent view.
646 */
647 TAILQ_HEAD(tog_view_list_head, tog_view);
649 struct tog_view {
650 TAILQ_ENTRY(tog_view) entry;
651 WINDOW *window;
652 PANEL *panel;
653 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
654 int resized_y, resized_x; /* begin_y/x based on user resizing */
655 int maxx, x; /* max column and current start column */
656 int lines, cols; /* copies of LINES and COLS */
657 int nscrolled, offset; /* lines scrolled and hsplit line offset */
658 int gline, hiline; /* navigate to and highlight this nG line */
659 int ch, count; /* current keymap and count prefix */
660 int resized; /* set when in a resize event */
661 int focussed; /* Only set on one parent or child view at a time. */
662 int dying;
663 struct tog_view *parent;
664 struct tog_view *child;
666 /*
667 * This flag is initially set on parent views when a new child view
668 * is created. It gets toggled when the 'Tab' key switches focus
669 * between parent and child.
670 * The flag indicates whether focus should be passed on to our child
671 * view if this parent view gets picked for focus after another parent
672 * view was closed. This prevents child views from losing focus in such
673 * situations.
674 */
675 int focus_child;
677 enum tog_view_mode mode;
678 /* type-specific state */
679 enum tog_view_type type;
680 union {
681 struct tog_diff_view_state diff;
682 struct tog_log_view_state log;
683 struct tog_blame_view_state blame;
684 struct tog_tree_view_state tree;
685 struct tog_ref_view_state ref;
686 struct tog_help_view_state help;
687 } state;
689 const struct got_error *(*show)(struct tog_view *);
690 const struct got_error *(*input)(struct tog_view **,
691 struct tog_view *, int);
692 const struct got_error *(*reset)(struct tog_view *);
693 const struct got_error *(*resize)(struct tog_view *, int);
694 const struct got_error *(*close)(struct tog_view *);
696 const struct got_error *(*search_start)(struct tog_view *);
697 const struct got_error *(*search_next)(struct tog_view *);
698 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
699 int **, int **, int **, int **);
700 int search_started;
701 int searching;
702 #define TOG_SEARCH_FORWARD 1
703 #define TOG_SEARCH_BACKWARD 2
704 int search_next_done;
705 #define TOG_SEARCH_HAVE_MORE 1
706 #define TOG_SEARCH_NO_MORE 2
707 #define TOG_SEARCH_HAVE_NONE 3
708 regex_t regex;
709 regmatch_t regmatch;
710 const char *action;
711 };
713 static const struct got_error *open_diff_view(struct tog_view *,
714 struct got_object_id *, struct got_object_id *,
715 const char *, const char *, int, int, int, struct tog_view *,
716 struct got_repository *);
717 static const struct got_error *show_diff_view(struct tog_view *);
718 static const struct got_error *input_diff_view(struct tog_view **,
719 struct tog_view *, int);
720 static const struct got_error *reset_diff_view(struct tog_view *);
721 static const struct got_error* close_diff_view(struct tog_view *);
722 static const struct got_error *search_start_diff_view(struct tog_view *);
723 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
724 size_t *, int **, int **, int **, int **);
725 static const struct got_error *search_next_view_match(struct tog_view *);
727 static const struct got_error *open_log_view(struct tog_view *,
728 struct got_object_id *, struct got_repository *,
729 const char *, const char *, int);
730 static const struct got_error * show_log_view(struct tog_view *);
731 static const struct got_error *input_log_view(struct tog_view **,
732 struct tog_view *, int);
733 static const struct got_error *resize_log_view(struct tog_view *, int);
734 static const struct got_error *close_log_view(struct tog_view *);
735 static const struct got_error *search_start_log_view(struct tog_view *);
736 static const struct got_error *search_next_log_view(struct tog_view *);
738 static const struct got_error *open_blame_view(struct tog_view *, char *,
739 struct got_object_id *, struct got_repository *);
740 static const struct got_error *show_blame_view(struct tog_view *);
741 static const struct got_error *input_blame_view(struct tog_view **,
742 struct tog_view *, int);
743 static const struct got_error *reset_blame_view(struct tog_view *);
744 static const struct got_error *close_blame_view(struct tog_view *);
745 static const struct got_error *search_start_blame_view(struct tog_view *);
746 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
747 size_t *, int **, int **, int **, int **);
749 static const struct got_error *open_tree_view(struct tog_view *,
750 struct got_object_id *, const char *, struct got_repository *);
751 static const struct got_error *show_tree_view(struct tog_view *);
752 static const struct got_error *input_tree_view(struct tog_view **,
753 struct tog_view *, int);
754 static const struct got_error *close_tree_view(struct tog_view *);
755 static const struct got_error *search_start_tree_view(struct tog_view *);
756 static const struct got_error *search_next_tree_view(struct tog_view *);
758 static const struct got_error *open_ref_view(struct tog_view *,
759 struct got_repository *);
760 static const struct got_error *show_ref_view(struct tog_view *);
761 static const struct got_error *input_ref_view(struct tog_view **,
762 struct tog_view *, int);
763 static const struct got_error *close_ref_view(struct tog_view *);
764 static const struct got_error *search_start_ref_view(struct tog_view *);
765 static const struct got_error *search_next_ref_view(struct tog_view *);
767 static const struct got_error *open_help_view(struct tog_view *,
768 struct tog_view *);
769 static const struct got_error *show_help_view(struct tog_view *);
770 static const struct got_error *input_help_view(struct tog_view **,
771 struct tog_view *, int);
772 static const struct got_error *reset_help_view(struct tog_view *);
773 static const struct got_error* close_help_view(struct tog_view *);
774 static const struct got_error *search_start_help_view(struct tog_view *);
775 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
776 size_t *, int **, int **, int **, int **);
778 static volatile sig_atomic_t tog_sigwinch_received;
779 static volatile sig_atomic_t tog_sigpipe_received;
780 static volatile sig_atomic_t tog_sigcont_received;
781 static volatile sig_atomic_t tog_sigint_received;
782 static volatile sig_atomic_t tog_sigterm_received;
784 static void
785 tog_sigwinch(int signo)
787 tog_sigwinch_received = 1;
790 static void
791 tog_sigpipe(int signo)
793 tog_sigpipe_received = 1;
796 static void
797 tog_sigcont(int signo)
799 tog_sigcont_received = 1;
802 static void
803 tog_sigint(int signo)
805 tog_sigint_received = 1;
808 static void
809 tog_sigterm(int signo)
811 tog_sigterm_received = 1;
814 static int
815 tog_fatal_signal_received(void)
817 return (tog_sigpipe_received ||
818 tog_sigint_received || tog_sigterm_received);
821 static const struct got_error *
822 view_close(struct tog_view *view)
824 const struct got_error *err = NULL, *child_err = NULL;
826 if (view->child) {
827 child_err = view_close(view->child);
828 view->child = NULL;
830 if (view->close)
831 err = view->close(view);
832 if (view->panel)
833 del_panel(view->panel);
834 if (view->window)
835 delwin(view->window);
836 free(view);
837 return err ? err : child_err;
840 static struct tog_view *
841 view_open(int nlines, int ncols, int begin_y, int begin_x,
842 enum tog_view_type type)
844 struct tog_view *view = calloc(1, sizeof(*view));
846 if (view == NULL)
847 return NULL;
849 view->type = type;
850 view->lines = LINES;
851 view->cols = COLS;
852 view->nlines = nlines ? nlines : LINES - begin_y;
853 view->ncols = ncols ? ncols : COLS - begin_x;
854 view->begin_y = begin_y;
855 view->begin_x = begin_x;
856 view->window = newwin(nlines, ncols, begin_y, begin_x);
857 if (view->window == NULL) {
858 view_close(view);
859 return NULL;
861 view->panel = new_panel(view->window);
862 if (view->panel == NULL ||
863 set_panel_userptr(view->panel, view) != OK) {
864 view_close(view);
865 return NULL;
868 keypad(view->window, TRUE);
869 return view;
872 static int
873 view_split_begin_x(int begin_x)
875 if (begin_x > 0 || COLS < 120)
876 return 0;
877 return (COLS - MAX(COLS / 2, 80));
880 /* XXX Stub till we decide what to do. */
881 static int
882 view_split_begin_y(int lines)
884 return lines * HSPLIT_SCALE;
887 static const struct got_error *view_resize(struct tog_view *);
889 static const struct got_error *
890 view_splitscreen(struct tog_view *view)
892 const struct got_error *err = NULL;
894 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
895 if (view->resized_y && view->resized_y < view->lines)
896 view->begin_y = view->resized_y;
897 else
898 view->begin_y = view_split_begin_y(view->nlines);
899 view->begin_x = 0;
900 } else if (!view->resized) {
901 if (view->resized_x && view->resized_x < view->cols - 1 &&
902 view->cols > 119)
903 view->begin_x = view->resized_x;
904 else
905 view->begin_x = view_split_begin_x(0);
906 view->begin_y = 0;
908 view->nlines = LINES - view->begin_y;
909 view->ncols = COLS - view->begin_x;
910 view->lines = LINES;
911 view->cols = COLS;
912 err = view_resize(view);
913 if (err)
914 return err;
916 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
917 view->parent->nlines = view->begin_y;
919 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
920 return got_error_from_errno("mvwin");
922 return NULL;
925 static const struct got_error *
926 view_fullscreen(struct tog_view *view)
928 const struct got_error *err = NULL;
930 view->begin_x = 0;
931 view->begin_y = view->resized ? view->begin_y : 0;
932 view->nlines = view->resized ? view->nlines : LINES;
933 view->ncols = COLS;
934 view->lines = LINES;
935 view->cols = COLS;
936 err = view_resize(view);
937 if (err)
938 return err;
940 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
941 return got_error_from_errno("mvwin");
943 return NULL;
946 static int
947 view_is_parent_view(struct tog_view *view)
949 return view->parent == NULL;
952 static int
953 view_is_splitscreen(struct tog_view *view)
955 return view->begin_x > 0 || view->begin_y > 0;
958 static int
959 view_is_fullscreen(struct tog_view *view)
961 return view->nlines == LINES && view->ncols == COLS;
964 static int
965 view_is_hsplit_top(struct tog_view *view)
967 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
968 view_is_splitscreen(view->child);
971 static void
972 view_border(struct tog_view *view)
974 PANEL *panel;
975 const struct tog_view *view_above;
977 if (view->parent)
978 return view_border(view->parent);
980 panel = panel_above(view->panel);
981 if (panel == NULL)
982 return;
984 view_above = panel_userptr(panel);
985 if (view->mode == TOG_VIEW_SPLIT_HRZN)
986 mvwhline(view->window, view_above->begin_y - 1,
987 view->begin_x, got_locale_is_utf8() ?
988 ACS_HLINE : '-', view->ncols);
989 else
990 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
991 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
994 static const struct got_error *view_init_hsplit(struct tog_view *, int);
995 static const struct got_error *request_log_commits(struct tog_view *);
996 static const struct got_error *offset_selection_down(struct tog_view *);
997 static void offset_selection_up(struct tog_view *);
998 static void view_get_split(struct tog_view *, int *, int *);
1000 static const struct got_error *
1001 view_resize(struct tog_view *view)
1003 const struct got_error *err = NULL;
1004 int dif, nlines, ncols;
1006 dif = LINES - view->lines; /* line difference */
1008 if (view->lines > LINES)
1009 nlines = view->nlines - (view->lines - LINES);
1010 else
1011 nlines = view->nlines + (LINES - view->lines);
1012 if (view->cols > COLS)
1013 ncols = view->ncols - (view->cols - COLS);
1014 else
1015 ncols = view->ncols + (COLS - view->cols);
1017 if (view->child) {
1018 int hs = view->child->begin_y;
1020 if (!view_is_fullscreen(view))
1021 view->child->begin_x = view_split_begin_x(view->begin_x);
1022 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1023 view->child->begin_x == 0) {
1024 ncols = COLS;
1026 view_fullscreen(view->child);
1027 if (view->child->focussed)
1028 show_panel(view->child->panel);
1029 else
1030 show_panel(view->panel);
1031 } else {
1032 ncols = view->child->begin_x;
1034 view_splitscreen(view->child);
1035 show_panel(view->child->panel);
1038 * XXX This is ugly and needs to be moved into the above
1039 * logic but "works" for now and my attempts at moving it
1040 * break either 'tab' or 'F' key maps in horizontal splits.
1042 if (hs) {
1043 err = view_splitscreen(view->child);
1044 if (err)
1045 return err;
1046 if (dif < 0) { /* top split decreased */
1047 err = offset_selection_down(view);
1048 if (err)
1049 return err;
1051 view_border(view);
1052 update_panels();
1053 doupdate();
1054 show_panel(view->child->panel);
1055 nlines = view->nlines;
1057 } else if (view->parent == NULL)
1058 ncols = COLS;
1060 if (view->resize && dif > 0) {
1061 err = view->resize(view, dif);
1062 if (err)
1063 return err;
1066 if (wresize(view->window, nlines, ncols) == ERR)
1067 return got_error_from_errno("wresize");
1068 if (replace_panel(view->panel, view->window) == ERR)
1069 return got_error_from_errno("replace_panel");
1070 wclear(view->window);
1072 view->nlines = nlines;
1073 view->ncols = ncols;
1074 view->lines = LINES;
1075 view->cols = COLS;
1077 return NULL;
1080 static const struct got_error *
1081 resize_log_view(struct tog_view *view, int increase)
1083 struct tog_log_view_state *s = &view->state.log;
1084 const struct got_error *err = NULL;
1085 int n = 0;
1087 if (s->selected_entry)
1088 n = s->selected_entry->idx + view->lines - s->selected;
1091 * Request commits to account for the increased
1092 * height so we have enough to populate the view.
1094 if (s->commits->ncommits < n) {
1095 view->nscrolled = n - s->commits->ncommits + increase + 1;
1096 err = request_log_commits(view);
1099 return err;
1102 static void
1103 view_adjust_offset(struct tog_view *view, int n)
1105 if (n == 0)
1106 return;
1108 if (view->parent && view->parent->offset) {
1109 if (view->parent->offset + n >= 0)
1110 view->parent->offset += n;
1111 else
1112 view->parent->offset = 0;
1113 } else if (view->offset) {
1114 if (view->offset - n >= 0)
1115 view->offset -= n;
1116 else
1117 view->offset = 0;
1121 static const struct got_error *
1122 view_resize_split(struct tog_view *view, int resize)
1124 const struct got_error *err = NULL;
1125 struct tog_view *v = NULL;
1127 if (view->parent)
1128 v = view->parent;
1129 else
1130 v = view;
1132 if (!v->child || !view_is_splitscreen(v->child))
1133 return NULL;
1135 v->resized = v->child->resized = resize; /* lock for resize event */
1137 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1138 if (v->child->resized_y)
1139 v->child->begin_y = v->child->resized_y;
1140 if (view->parent)
1141 v->child->begin_y -= resize;
1142 else
1143 v->child->begin_y += resize;
1144 if (v->child->begin_y < 3) {
1145 view->count = 0;
1146 v->child->begin_y = 3;
1147 } else if (v->child->begin_y > LINES - 1) {
1148 view->count = 0;
1149 v->child->begin_y = LINES - 1;
1151 v->ncols = COLS;
1152 v->child->ncols = COLS;
1153 view_adjust_offset(view, resize);
1154 err = view_init_hsplit(v, v->child->begin_y);
1155 if (err)
1156 return err;
1157 v->child->resized_y = v->child->begin_y;
1158 } else {
1159 if (v->child->resized_x)
1160 v->child->begin_x = v->child->resized_x;
1161 if (view->parent)
1162 v->child->begin_x -= resize;
1163 else
1164 v->child->begin_x += resize;
1165 if (v->child->begin_x < 11) {
1166 view->count = 0;
1167 v->child->begin_x = 11;
1168 } else if (v->child->begin_x > COLS - 1) {
1169 view->count = 0;
1170 v->child->begin_x = COLS - 1;
1172 v->child->resized_x = v->child->begin_x;
1175 v->child->mode = v->mode;
1176 v->child->nlines = v->lines - v->child->begin_y;
1177 v->child->ncols = v->cols - v->child->begin_x;
1178 v->focus_child = 1;
1180 err = view_fullscreen(v);
1181 if (err)
1182 return err;
1183 err = view_splitscreen(v->child);
1184 if (err)
1185 return err;
1187 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1188 err = offset_selection_down(v->child);
1189 if (err)
1190 return err;
1193 if (v->resize)
1194 err = v->resize(v, 0);
1195 else if (v->child->resize)
1196 err = v->child->resize(v->child, 0);
1198 v->resized = v->child->resized = 0;
1200 return err;
1203 static void
1204 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1206 struct tog_view *v = src->child ? src->child : src;
1208 dst->resized_x = v->resized_x;
1209 dst->resized_y = v->resized_y;
1212 static const struct got_error *
1213 view_close_child(struct tog_view *view)
1215 const struct got_error *err = NULL;
1217 if (view->child == NULL)
1218 return NULL;
1220 err = view_close(view->child);
1221 view->child = NULL;
1222 return err;
1225 static const struct got_error *
1226 view_set_child(struct tog_view *view, struct tog_view *child)
1228 const struct got_error *err = NULL;
1230 view->child = child;
1231 child->parent = view;
1233 err = view_resize(view);
1234 if (err)
1235 return err;
1237 if (view->child->resized_x || view->child->resized_y)
1238 err = view_resize_split(view, 0);
1240 return err;
1243 static const struct got_error *view_dispatch_request(struct tog_view **,
1244 struct tog_view *, enum tog_view_type, int, int);
1246 static const struct got_error *
1247 view_request_new(struct tog_view **requested, struct tog_view *view,
1248 enum tog_view_type request)
1250 struct tog_view *new_view = NULL;
1251 const struct got_error *err;
1252 int y = 0, x = 0;
1254 *requested = NULL;
1256 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1257 view_get_split(view, &y, &x);
1259 err = view_dispatch_request(&new_view, view, request, y, x);
1260 if (err)
1261 return err;
1263 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1264 request != TOG_VIEW_HELP) {
1265 err = view_init_hsplit(view, y);
1266 if (err)
1267 return err;
1270 view->focussed = 0;
1271 new_view->focussed = 1;
1272 new_view->mode = view->mode;
1273 new_view->nlines = request == TOG_VIEW_HELP ?
1274 view->lines : view->lines - y;
1276 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1277 view_transfer_size(new_view, view);
1278 err = view_close_child(view);
1279 if (err)
1280 return err;
1281 err = view_set_child(view, new_view);
1282 if (err)
1283 return err;
1284 view->focus_child = 1;
1285 } else
1286 *requested = new_view;
1288 return NULL;
1291 static void
1292 tog_resizeterm(void)
1294 int cols, lines;
1295 struct winsize size;
1297 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1298 cols = 80; /* Default */
1299 lines = 24;
1300 } else {
1301 cols = size.ws_col;
1302 lines = size.ws_row;
1304 resize_term(lines, cols);
1307 static const struct got_error *
1308 view_search_start(struct tog_view *view, int fast_refresh)
1310 const struct got_error *err = NULL;
1311 struct tog_view *v = view;
1312 char pattern[1024];
1313 int ret;
1315 if (view->search_started) {
1316 regfree(&view->regex);
1317 view->searching = 0;
1318 memset(&view->regmatch, 0, sizeof(view->regmatch));
1320 view->search_started = 0;
1322 if (view->nlines < 1)
1323 return NULL;
1325 if (view_is_hsplit_top(view))
1326 v = view->child;
1327 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1328 v = view->parent;
1330 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1331 wclrtoeol(v->window);
1333 nodelay(v->window, FALSE); /* block for search term input */
1334 nocbreak();
1335 echo();
1336 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1337 wrefresh(v->window);
1338 cbreak();
1339 noecho();
1340 nodelay(v->window, TRUE);
1341 if (!fast_refresh && !using_mock_io)
1342 halfdelay(10);
1343 if (ret == ERR)
1344 return NULL;
1346 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1347 err = view->search_start(view);
1348 if (err) {
1349 regfree(&view->regex);
1350 return err;
1352 view->search_started = 1;
1353 view->searching = TOG_SEARCH_FORWARD;
1354 view->search_next_done = 0;
1355 view->search_next(view);
1358 return NULL;
1361 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1362 static const struct got_error *
1363 switch_split(struct tog_view *view)
1365 const struct got_error *err = NULL;
1366 struct tog_view *v = NULL;
1368 if (view->parent)
1369 v = view->parent;
1370 else
1371 v = view;
1373 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1374 v->mode = TOG_VIEW_SPLIT_VERT;
1375 else
1376 v->mode = TOG_VIEW_SPLIT_HRZN;
1378 if (!v->child)
1379 return NULL;
1380 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1381 v->mode = TOG_VIEW_SPLIT_NONE;
1383 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1384 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1385 v->child->begin_y = v->child->resized_y;
1386 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1387 v->child->begin_x = v->child->resized_x;
1390 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1391 v->ncols = COLS;
1392 v->child->ncols = COLS;
1393 v->child->nscrolled = LINES - v->child->nlines;
1395 err = view_init_hsplit(v, v->child->begin_y);
1396 if (err)
1397 return err;
1399 v->child->mode = v->mode;
1400 v->child->nlines = v->lines - v->child->begin_y;
1401 v->focus_child = 1;
1403 err = view_fullscreen(v);
1404 if (err)
1405 return err;
1406 err = view_splitscreen(v->child);
1407 if (err)
1408 return err;
1410 if (v->mode == TOG_VIEW_SPLIT_NONE)
1411 v->mode = TOG_VIEW_SPLIT_VERT;
1412 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1413 err = offset_selection_down(v);
1414 if (err)
1415 return err;
1416 err = offset_selection_down(v->child);
1417 if (err)
1418 return err;
1419 } else {
1420 offset_selection_up(v);
1421 offset_selection_up(v->child);
1423 if (v->resize)
1424 err = v->resize(v, 0);
1425 else if (v->child->resize)
1426 err = v->child->resize(v->child, 0);
1428 return err;
1432 * Strip trailing whitespace from str starting at byte *n;
1433 * if *n < 0, use strlen(str). Return new str length in *n.
1435 static void
1436 strip_trailing_ws(char *str, int *n)
1438 size_t x = *n;
1440 if (str == NULL || *str == '\0')
1441 return;
1443 if (x < 0)
1444 x = strlen(str);
1446 while (x-- > 0 && isspace((unsigned char)str[x]))
1447 str[x] = '\0';
1449 *n = x + 1;
1453 * Extract visible substring of line y from the curses screen
1454 * and strip trailing whitespace. If vline is set and locale is
1455 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1456 * character is written out as 'x'. Write the line to file f.
1458 static const struct got_error *
1459 view_write_line(FILE *f, int y, int vline)
1461 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1462 int r, w;
1464 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1465 if (r == ERR)
1466 return got_error_fmt(GOT_ERR_RANGE,
1467 "failed to extract line %d", y);
1470 * In some views, lines are padded with blanks to COLS width.
1471 * Strip them so we can diff without the -b flag when testing.
1473 strip_trailing_ws(line, &r);
1475 if (vline > 0 && got_locale_is_utf8())
1476 line[vline] = '|';
1478 w = fprintf(f, "%s\n", line);
1479 if (w != r + 1) /* \n */
1480 return got_ferror(f, GOT_ERR_IO);
1482 return NULL;
1486 * Capture the visible curses screen by writing each line to the
1487 * file at the path set via the TOG_SCR_DUMP environment variable.
1489 static const struct got_error *
1490 screendump(struct tog_view *view)
1492 const struct got_error *err;
1493 FILE *f = NULL;
1494 const char *path;
1495 int i;
1497 path = getenv("TOG_SCR_DUMP");
1498 if (path == NULL || *path == '\0')
1499 return got_error_msg(GOT_ERR_BAD_PATH,
1500 "TOG_SCR_DUMP path not set to capture screen dump");
1501 f = fopen(path, "wex");
1502 if (f == NULL)
1503 return got_error_from_errno_fmt("fopen: %s", path);
1505 if ((view->child && view->child->begin_x) ||
1506 (view->parent && view->begin_x)) {
1507 int ncols = view->child ? view->ncols : view->parent->ncols;
1509 /* vertical splitscreen */
1510 for (i = 0; i < view->nlines; ++i) {
1511 err = view_write_line(f, i, ncols - 1);
1512 if (err)
1513 goto done;
1515 } else {
1516 int hline = 0;
1518 /* fullscreen or horizontal splitscreen */
1519 if ((view->child && view->child->begin_y) ||
1520 (view->parent && view->begin_y)) /* hsplit */
1521 hline = view->child ?
1522 view->child->begin_y : view->begin_y;
1524 for (i = 0; i < view->lines; i++) {
1525 if (hline && got_locale_is_utf8() && i == hline - 1) {
1526 int c;
1528 /* ACS_HLINE writes out as 'q', overwrite it */
1529 for (c = 0; c < view->cols; ++c)
1530 fputc('-', f);
1531 fputc('\n', f);
1532 continue;
1535 err = view_write_line(f, i, 0);
1536 if (err)
1537 goto done;
1541 done:
1542 if (f && fclose(f) == EOF && err == NULL)
1543 err = got_ferror(f, GOT_ERR_IO);
1544 return err;
1548 * Compute view->count from numeric input. Assign total to view->count and
1549 * return first non-numeric key entered.
1551 static int
1552 get_compound_key(struct tog_view *view, int c)
1554 struct tog_view *v = view;
1555 int x, n = 0;
1557 if (view_is_hsplit_top(view))
1558 v = view->child;
1559 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1560 v = view->parent;
1562 view->count = 0;
1563 cbreak(); /* block for input */
1564 nodelay(view->window, FALSE);
1565 wmove(v->window, v->nlines - 1, 0);
1566 wclrtoeol(v->window);
1567 waddch(v->window, ':');
1569 do {
1570 x = getcurx(v->window);
1571 if (x != ERR && x < view->ncols) {
1572 waddch(v->window, c);
1573 wrefresh(v->window);
1577 * Don't overflow. Max valid request should be the greatest
1578 * between the longest and total lines; cap at 10 million.
1580 if (n >= 9999999)
1581 n = 9999999;
1582 else
1583 n = n * 10 + (c - '0');
1584 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1586 if (c == 'G' || c == 'g') { /* nG key map */
1587 view->gline = view->hiline = n;
1588 n = 0;
1589 c = 0;
1592 /* Massage excessive or inapplicable values at the input handler. */
1593 view->count = n;
1595 return c;
1598 static void
1599 action_report(struct tog_view *view)
1601 struct tog_view *v = view;
1603 if (view_is_hsplit_top(view))
1604 v = view->child;
1605 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1606 v = view->parent;
1608 wmove(v->window, v->nlines - 1, 0);
1609 wclrtoeol(v->window);
1610 wprintw(v->window, ":%s", view->action);
1611 wrefresh(v->window);
1614 * Clear action status report. Only clear in blame view
1615 * once annotating is complete, otherwise it's too fast.
1617 if (view->type == TOG_VIEW_BLAME) {
1618 if (view->state.blame.blame_complete)
1619 view->action = NULL;
1620 } else
1621 view->action = NULL;
1625 * Read the next line from the test script and assign
1626 * key instruction to *ch. If at EOF, set the *done flag.
1628 static const struct got_error *
1629 tog_read_script_key(FILE *script, int *ch, int *done)
1631 const struct got_error *err = NULL;
1632 char *line = NULL;
1633 size_t linesz = 0;
1635 if (getline(&line, &linesz, script) == -1) {
1636 if (feof(script)) {
1637 *done = 1;
1638 goto done;
1639 } else {
1640 err = got_ferror(script, GOT_ERR_IO);
1641 goto done;
1643 } else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1644 *ch = KEY_ENTER;
1645 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1646 *ch = KEY_RIGHT;
1647 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1648 *ch = KEY_LEFT;
1649 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1650 *ch = KEY_DOWN;
1651 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1652 *ch = KEY_UP;
1653 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1654 *ch = TOG_KEY_SCRDUMP;
1655 else
1656 *ch = *line;
1658 done:
1659 free(line);
1660 return err;
1663 static const struct got_error *
1664 view_input(struct tog_view **new, int *done, struct tog_view *view,
1665 struct tog_view_list_head *views, int fast_refresh)
1667 const struct got_error *err = NULL;
1668 struct tog_view *v;
1669 int ch, errcode;
1671 *new = NULL;
1673 if (view->action)
1674 action_report(view);
1676 /* Clear "no matches" indicator. */
1677 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1678 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1679 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1680 view->count = 0;
1683 if (view->searching && !view->search_next_done) {
1684 errcode = pthread_mutex_unlock(&tog_mutex);
1685 if (errcode)
1686 return got_error_set_errno(errcode,
1687 "pthread_mutex_unlock");
1688 sched_yield();
1689 errcode = pthread_mutex_lock(&tog_mutex);
1690 if (errcode)
1691 return got_error_set_errno(errcode,
1692 "pthread_mutex_lock");
1693 view->search_next(view);
1694 return NULL;
1697 /* Allow threads to make progress while we are waiting for input. */
1698 errcode = pthread_mutex_unlock(&tog_mutex);
1699 if (errcode)
1700 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1702 if (using_mock_io) {
1703 err = tog_read_script_key(tog_io.f, &ch, done);
1704 if (err)
1705 return err;
1706 } else if (view->count && --view->count) {
1707 cbreak();
1708 nodelay(view->window, TRUE);
1709 ch = wgetch(view->window);
1710 /* let C-g or backspace abort unfinished count */
1711 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1712 view->count = 0;
1713 else
1714 ch = view->ch;
1715 } else {
1716 ch = wgetch(view->window);
1717 if (ch >= '1' && ch <= '9')
1718 view->ch = ch = get_compound_key(view, ch);
1720 if (view->hiline && ch != ERR && ch != 0)
1721 view->hiline = 0; /* key pressed, clear line highlight */
1722 nodelay(view->window, TRUE);
1723 errcode = pthread_mutex_lock(&tog_mutex);
1724 if (errcode)
1725 return got_error_set_errno(errcode, "pthread_mutex_lock");
1727 if (tog_sigwinch_received || tog_sigcont_received) {
1728 tog_resizeterm();
1729 tog_sigwinch_received = 0;
1730 tog_sigcont_received = 0;
1731 TAILQ_FOREACH(v, views, entry) {
1732 err = view_resize(v);
1733 if (err)
1734 return err;
1735 err = v->input(new, v, KEY_RESIZE);
1736 if (err)
1737 return err;
1738 if (v->child) {
1739 err = view_resize(v->child);
1740 if (err)
1741 return err;
1742 err = v->child->input(new, v->child,
1743 KEY_RESIZE);
1744 if (err)
1745 return err;
1746 if (v->child->resized_x || v->child->resized_y) {
1747 err = view_resize_split(v, 0);
1748 if (err)
1749 return err;
1755 switch (ch) {
1756 case '?':
1757 case 'H':
1758 case KEY_F(1):
1759 if (view->type == TOG_VIEW_HELP)
1760 err = view->reset(view);
1761 else
1762 err = view_request_new(new, view, TOG_VIEW_HELP);
1763 break;
1764 case '\t':
1765 view->count = 0;
1766 if (view->child) {
1767 view->focussed = 0;
1768 view->child->focussed = 1;
1769 view->focus_child = 1;
1770 } else if (view->parent) {
1771 view->focussed = 0;
1772 view->parent->focussed = 1;
1773 view->parent->focus_child = 0;
1774 if (!view_is_splitscreen(view)) {
1775 if (view->parent->resize) {
1776 err = view->parent->resize(view->parent,
1777 0);
1778 if (err)
1779 return err;
1781 offset_selection_up(view->parent);
1782 err = view_fullscreen(view->parent);
1783 if (err)
1784 return err;
1787 break;
1788 case 'q':
1789 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1790 if (view->parent->resize) {
1791 /* might need more commits to fill fullscreen */
1792 err = view->parent->resize(view->parent, 0);
1793 if (err)
1794 break;
1796 offset_selection_up(view->parent);
1798 err = view->input(new, view, ch);
1799 view->dying = 1;
1800 break;
1801 case 'Q':
1802 *done = 1;
1803 break;
1804 case 'F':
1805 view->count = 0;
1806 if (view_is_parent_view(view)) {
1807 if (view->child == NULL)
1808 break;
1809 if (view_is_splitscreen(view->child)) {
1810 view->focussed = 0;
1811 view->child->focussed = 1;
1812 err = view_fullscreen(view->child);
1813 } else {
1814 err = view_splitscreen(view->child);
1815 if (!err)
1816 err = view_resize_split(view, 0);
1818 if (err)
1819 break;
1820 err = view->child->input(new, view->child,
1821 KEY_RESIZE);
1822 } else {
1823 if (view_is_splitscreen(view)) {
1824 view->parent->focussed = 0;
1825 view->focussed = 1;
1826 err = view_fullscreen(view);
1827 } else {
1828 err = view_splitscreen(view);
1829 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1830 err = view_resize(view->parent);
1831 if (!err)
1832 err = view_resize_split(view, 0);
1834 if (err)
1835 break;
1836 err = view->input(new, view, KEY_RESIZE);
1838 if (err)
1839 break;
1840 if (view->resize) {
1841 err = view->resize(view, 0);
1842 if (err)
1843 break;
1845 if (view->parent)
1846 err = offset_selection_down(view->parent);
1847 if (!err)
1848 err = offset_selection_down(view);
1849 break;
1850 case 'S':
1851 view->count = 0;
1852 err = switch_split(view);
1853 break;
1854 case '-':
1855 err = view_resize_split(view, -1);
1856 break;
1857 case '+':
1858 err = view_resize_split(view, 1);
1859 break;
1860 case KEY_RESIZE:
1861 break;
1862 case '/':
1863 view->count = 0;
1864 if (view->search_start)
1865 view_search_start(view, fast_refresh);
1866 else
1867 err = view->input(new, view, ch);
1868 break;
1869 case 'N':
1870 case 'n':
1871 if (view->search_started && view->search_next) {
1872 view->searching = (ch == 'n' ?
1873 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1874 view->search_next_done = 0;
1875 view->search_next(view);
1876 } else
1877 err = view->input(new, view, ch);
1878 break;
1879 case 'A':
1880 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1881 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1882 view->action = "Patience diff algorithm";
1883 } else {
1884 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1885 view->action = "Myers diff algorithm";
1887 TAILQ_FOREACH(v, views, entry) {
1888 if (v->reset) {
1889 err = v->reset(v);
1890 if (err)
1891 return err;
1893 if (v->child && v->child->reset) {
1894 err = v->child->reset(v->child);
1895 if (err)
1896 return err;
1899 break;
1900 case TOG_KEY_SCRDUMP:
1901 err = screendump(view);
1902 break;
1903 default:
1904 err = view->input(new, view, ch);
1905 break;
1908 return err;
1911 static int
1912 view_needs_focus_indication(struct tog_view *view)
1914 if (view_is_parent_view(view)) {
1915 if (view->child == NULL || view->child->focussed)
1916 return 0;
1917 if (!view_is_splitscreen(view->child))
1918 return 0;
1919 } else if (!view_is_splitscreen(view))
1920 return 0;
1922 return view->focussed;
1925 static const struct got_error *
1926 tog_io_close(void)
1928 const struct got_error *err = NULL;
1930 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1931 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1932 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1933 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1934 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1935 err = got_ferror(tog_io.f, GOT_ERR_IO);
1937 return err;
1940 static const struct got_error *
1941 view_loop(struct tog_view *view)
1943 const struct got_error *err = NULL;
1944 struct tog_view_list_head views;
1945 struct tog_view *new_view;
1946 char *mode;
1947 int fast_refresh = 10;
1948 int done = 0, errcode;
1950 mode = getenv("TOG_VIEW_SPLIT_MODE");
1951 if (!mode || !(*mode == 'h' || *mode == 'H'))
1952 view->mode = TOG_VIEW_SPLIT_VERT;
1953 else
1954 view->mode = TOG_VIEW_SPLIT_HRZN;
1956 errcode = pthread_mutex_lock(&tog_mutex);
1957 if (errcode)
1958 return got_error_set_errno(errcode, "pthread_mutex_lock");
1960 TAILQ_INIT(&views);
1961 TAILQ_INSERT_HEAD(&views, view, entry);
1963 view->focussed = 1;
1964 err = view->show(view);
1965 if (err)
1966 return err;
1967 update_panels();
1968 doupdate();
1969 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1970 !tog_fatal_signal_received()) {
1971 /* Refresh fast during initialization, then become slower. */
1972 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1973 halfdelay(10); /* switch to once per second */
1975 err = view_input(&new_view, &done, view, &views, fast_refresh);
1976 if (err)
1977 break;
1979 if (view->dying && view == TAILQ_FIRST(&views) &&
1980 TAILQ_NEXT(view, entry) == NULL)
1981 done = 1;
1982 if (done) {
1983 struct tog_view *v;
1986 * When we quit, scroll the screen up a single line
1987 * so we don't lose any information.
1989 TAILQ_FOREACH(v, &views, entry) {
1990 wmove(v->window, 0, 0);
1991 wdeleteln(v->window);
1992 wnoutrefresh(v->window);
1993 if (v->child && !view_is_fullscreen(v)) {
1994 wmove(v->child->window, 0, 0);
1995 wdeleteln(v->child->window);
1996 wnoutrefresh(v->child->window);
1999 doupdate();
2002 if (view->dying) {
2003 struct tog_view *v, *prev = NULL;
2005 if (view_is_parent_view(view))
2006 prev = TAILQ_PREV(view, tog_view_list_head,
2007 entry);
2008 else if (view->parent)
2009 prev = view->parent;
2011 if (view->parent) {
2012 view->parent->child = NULL;
2013 view->parent->focus_child = 0;
2014 /* Restore fullscreen line height. */
2015 view->parent->nlines = view->parent->lines;
2016 err = view_resize(view->parent);
2017 if (err)
2018 break;
2019 /* Make resized splits persist. */
2020 view_transfer_size(view->parent, view);
2021 } else
2022 TAILQ_REMOVE(&views, view, entry);
2024 err = view_close(view);
2025 if (err)
2026 goto done;
2028 view = NULL;
2029 TAILQ_FOREACH(v, &views, entry) {
2030 if (v->focussed)
2031 break;
2033 if (view == NULL && new_view == NULL) {
2034 /* No view has focus. Try to pick one. */
2035 if (prev)
2036 view = prev;
2037 else if (!TAILQ_EMPTY(&views)) {
2038 view = TAILQ_LAST(&views,
2039 tog_view_list_head);
2041 if (view) {
2042 if (view->focus_child) {
2043 view->child->focussed = 1;
2044 view = view->child;
2045 } else
2046 view->focussed = 1;
2050 if (new_view) {
2051 struct tog_view *v, *t;
2052 /* Only allow one parent view per type. */
2053 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2054 if (v->type != new_view->type)
2055 continue;
2056 TAILQ_REMOVE(&views, v, entry);
2057 err = view_close(v);
2058 if (err)
2059 goto done;
2060 break;
2062 TAILQ_INSERT_TAIL(&views, new_view, entry);
2063 view = new_view;
2065 if (view && !done) {
2066 if (view_is_parent_view(view)) {
2067 if (view->child && view->child->focussed)
2068 view = view->child;
2069 } else {
2070 if (view->parent && view->parent->focussed)
2071 view = view->parent;
2073 show_panel(view->panel);
2074 if (view->child && view_is_splitscreen(view->child))
2075 show_panel(view->child->panel);
2076 if (view->parent && view_is_splitscreen(view)) {
2077 err = view->parent->show(view->parent);
2078 if (err)
2079 goto done;
2081 err = view->show(view);
2082 if (err)
2083 goto done;
2084 if (view->child) {
2085 err = view->child->show(view->child);
2086 if (err)
2087 goto done;
2089 update_panels();
2090 doupdate();
2093 done:
2094 while (!TAILQ_EMPTY(&views)) {
2095 const struct got_error *close_err;
2096 view = TAILQ_FIRST(&views);
2097 TAILQ_REMOVE(&views, view, entry);
2098 close_err = view_close(view);
2099 if (close_err && err == NULL)
2100 err = close_err;
2103 errcode = pthread_mutex_unlock(&tog_mutex);
2104 if (errcode && err == NULL)
2105 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2107 return err;
2110 __dead static void
2111 usage_log(void)
2113 endwin();
2114 fprintf(stderr,
2115 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2116 getprogname());
2117 exit(1);
2120 /* Create newly allocated wide-character string equivalent to a byte string. */
2121 static const struct got_error *
2122 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2124 char *vis = NULL;
2125 const struct got_error *err = NULL;
2127 *ws = NULL;
2128 *wlen = mbstowcs(NULL, s, 0);
2129 if (*wlen == (size_t)-1) {
2130 int vislen;
2131 if (errno != EILSEQ)
2132 return got_error_from_errno("mbstowcs");
2134 /* byte string invalid in current encoding; try to "fix" it */
2135 err = got_mbsavis(&vis, &vislen, s);
2136 if (err)
2137 return err;
2138 *wlen = mbstowcs(NULL, vis, 0);
2139 if (*wlen == (size_t)-1) {
2140 err = got_error_from_errno("mbstowcs"); /* give up */
2141 goto done;
2145 *ws = calloc(*wlen + 1, sizeof(**ws));
2146 if (*ws == NULL) {
2147 err = got_error_from_errno("calloc");
2148 goto done;
2151 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2152 err = got_error_from_errno("mbstowcs");
2153 done:
2154 free(vis);
2155 if (err) {
2156 free(*ws);
2157 *ws = NULL;
2158 *wlen = 0;
2160 return err;
2163 static const struct got_error *
2164 expand_tab(char **ptr, const char *src)
2166 char *dst;
2167 size_t len, n, idx = 0, sz = 0;
2169 *ptr = NULL;
2170 n = len = strlen(src);
2171 dst = malloc(n + 1);
2172 if (dst == NULL)
2173 return got_error_from_errno("malloc");
2175 while (idx < len && src[idx]) {
2176 const char c = src[idx];
2178 if (c == '\t') {
2179 size_t nb = TABSIZE - sz % TABSIZE;
2180 char *p;
2182 p = realloc(dst, n + nb);
2183 if (p == NULL) {
2184 free(dst);
2185 return got_error_from_errno("realloc");
2188 dst = p;
2189 n += nb;
2190 memset(dst + sz, ' ', nb);
2191 sz += nb;
2192 } else
2193 dst[sz++] = src[idx];
2194 ++idx;
2197 dst[sz] = '\0';
2198 *ptr = dst;
2199 return NULL;
2203 * Advance at most n columns from wline starting at offset off.
2204 * Return the index to the first character after the span operation.
2205 * Return the combined column width of all spanned wide character in
2206 * *rcol.
2208 static int
2209 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2211 int width, i, cols = 0;
2213 if (n == 0) {
2214 *rcol = cols;
2215 return off;
2218 for (i = off; wline[i] != L'\0'; ++i) {
2219 if (wline[i] == L'\t')
2220 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2221 else
2222 width = wcwidth(wline[i]);
2224 if (width == -1) {
2225 width = 1;
2226 wline[i] = L'.';
2229 if (cols + width > n)
2230 break;
2231 cols += width;
2234 *rcol = cols;
2235 return i;
2239 * Format a line for display, ensuring that it won't overflow a width limit.
2240 * With scrolling, the width returned refers to the scrolled version of the
2241 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2243 static const struct got_error *
2244 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2245 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2247 const struct got_error *err = NULL;
2248 int cols;
2249 wchar_t *wline = NULL;
2250 char *exstr = NULL;
2251 size_t wlen;
2252 int i, scrollx;
2254 *wlinep = NULL;
2255 *widthp = 0;
2257 if (expand) {
2258 err = expand_tab(&exstr, line);
2259 if (err)
2260 return err;
2263 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2264 free(exstr);
2265 if (err)
2266 return err;
2268 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2270 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2271 wline[wlen - 1] = L'\0';
2272 wlen--;
2274 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2275 wline[wlen - 1] = L'\0';
2276 wlen--;
2279 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2280 wline[i] = L'\0';
2282 if (widthp)
2283 *widthp = cols;
2284 if (scrollxp)
2285 *scrollxp = scrollx;
2286 if (err)
2287 free(wline);
2288 else
2289 *wlinep = wline;
2290 return err;
2293 static const struct got_error*
2294 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2295 struct got_object_id *id, struct got_repository *repo)
2297 static const struct got_error *err = NULL;
2298 struct got_reflist_entry *re;
2299 char *s;
2300 const char *name;
2302 *refs_str = NULL;
2304 TAILQ_FOREACH(re, refs, entry) {
2305 struct got_tag_object *tag = NULL;
2306 struct got_object_id *ref_id;
2307 int cmp;
2309 name = got_ref_get_name(re->ref);
2310 if (strcmp(name, GOT_REF_HEAD) == 0)
2311 continue;
2312 if (strncmp(name, "refs/", 5) == 0)
2313 name += 5;
2314 if (strncmp(name, "got/", 4) == 0 &&
2315 strncmp(name, "got/backup/", 11) != 0)
2316 continue;
2317 if (strncmp(name, "heads/", 6) == 0)
2318 name += 6;
2319 if (strncmp(name, "remotes/", 8) == 0) {
2320 name += 8;
2321 s = strstr(name, "/" GOT_REF_HEAD);
2322 if (s != NULL && s[strlen(s)] == '\0')
2323 continue;
2325 err = got_ref_resolve(&ref_id, repo, re->ref);
2326 if (err)
2327 break;
2328 if (strncmp(name, "tags/", 5) == 0) {
2329 err = got_object_open_as_tag(&tag, repo, ref_id);
2330 if (err) {
2331 if (err->code != GOT_ERR_OBJ_TYPE) {
2332 free(ref_id);
2333 break;
2335 /* Ref points at something other than a tag. */
2336 err = NULL;
2337 tag = NULL;
2340 cmp = got_object_id_cmp(tag ?
2341 got_object_tag_get_object_id(tag) : ref_id, id);
2342 free(ref_id);
2343 if (tag)
2344 got_object_tag_close(tag);
2345 if (cmp != 0)
2346 continue;
2347 s = *refs_str;
2348 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2349 s ? ", " : "", name) == -1) {
2350 err = got_error_from_errno("asprintf");
2351 free(s);
2352 *refs_str = NULL;
2353 break;
2355 free(s);
2358 return err;
2361 static const struct got_error *
2362 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2363 int col_tab_align)
2365 char *smallerthan;
2367 smallerthan = strchr(author, '<');
2368 if (smallerthan && smallerthan[1] != '\0')
2369 author = smallerthan + 1;
2370 author[strcspn(author, "@>")] = '\0';
2371 return format_line(wauthor, author_width, NULL, author, 0, limit,
2372 col_tab_align, 0);
2375 static const struct got_error *
2376 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2377 struct got_object_id *id, const size_t date_display_cols,
2378 int author_display_cols)
2380 struct tog_log_view_state *s = &view->state.log;
2381 const struct got_error *err = NULL;
2382 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2383 char *logmsg0 = NULL, *logmsg = NULL;
2384 char *author = NULL;
2385 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2386 int author_width, logmsg_width;
2387 char *newline, *line = NULL;
2388 int col, limit, scrollx;
2389 const int avail = view->ncols;
2390 struct tm tm;
2391 time_t committer_time;
2392 struct tog_color *tc;
2394 committer_time = got_object_commit_get_committer_time(commit);
2395 if (gmtime_r(&committer_time, &tm) == NULL)
2396 return got_error_from_errno("gmtime_r");
2397 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2398 return got_error(GOT_ERR_NO_SPACE);
2400 if (avail <= date_display_cols)
2401 limit = MIN(sizeof(datebuf) - 1, avail);
2402 else
2403 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2404 tc = get_color(&s->colors, TOG_COLOR_DATE);
2405 if (tc)
2406 wattr_on(view->window,
2407 COLOR_PAIR(tc->colorpair), NULL);
2408 waddnstr(view->window, datebuf, limit);
2409 if (tc)
2410 wattr_off(view->window,
2411 COLOR_PAIR(tc->colorpair), NULL);
2412 col = limit;
2413 if (col > avail)
2414 goto done;
2416 if (avail >= 120) {
2417 char *id_str;
2418 err = got_object_id_str(&id_str, id);
2419 if (err)
2420 goto done;
2421 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2422 if (tc)
2423 wattr_on(view->window,
2424 COLOR_PAIR(tc->colorpair), NULL);
2425 wprintw(view->window, "%.8s ", id_str);
2426 if (tc)
2427 wattr_off(view->window,
2428 COLOR_PAIR(tc->colorpair), NULL);
2429 free(id_str);
2430 col += 9;
2431 if (col > avail)
2432 goto done;
2435 if (s->use_committer)
2436 author = strdup(got_object_commit_get_committer(commit));
2437 else
2438 author = strdup(got_object_commit_get_author(commit));
2439 if (author == NULL) {
2440 err = got_error_from_errno("strdup");
2441 goto done;
2443 err = format_author(&wauthor, &author_width, author, avail - col, col);
2444 if (err)
2445 goto done;
2446 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2447 if (tc)
2448 wattr_on(view->window,
2449 COLOR_PAIR(tc->colorpair), NULL);
2450 waddwstr(view->window, wauthor);
2451 col += author_width;
2452 while (col < avail && author_width < author_display_cols + 2) {
2453 waddch(view->window, ' ');
2454 col++;
2455 author_width++;
2457 if (tc)
2458 wattr_off(view->window,
2459 COLOR_PAIR(tc->colorpair), NULL);
2460 if (col > avail)
2461 goto done;
2463 err = got_object_commit_get_logmsg(&logmsg0, commit);
2464 if (err)
2465 goto done;
2466 logmsg = logmsg0;
2467 while (*logmsg == '\n')
2468 logmsg++;
2469 newline = strchr(logmsg, '\n');
2470 if (newline)
2471 *newline = '\0';
2472 limit = avail - col;
2473 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2474 limit--; /* for the border */
2475 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2476 limit, col, 1);
2477 if (err)
2478 goto done;
2479 waddwstr(view->window, &wlogmsg[scrollx]);
2480 col += MAX(logmsg_width, 0);
2481 while (col < avail) {
2482 waddch(view->window, ' ');
2483 col++;
2485 done:
2486 free(logmsg0);
2487 free(wlogmsg);
2488 free(author);
2489 free(wauthor);
2490 free(line);
2491 return err;
2494 static struct commit_queue_entry *
2495 alloc_commit_queue_entry(struct got_commit_object *commit,
2496 struct got_object_id *id)
2498 struct commit_queue_entry *entry;
2499 struct got_object_id *dup;
2501 entry = calloc(1, sizeof(*entry));
2502 if (entry == NULL)
2503 return NULL;
2505 dup = got_object_id_dup(id);
2506 if (dup == NULL) {
2507 free(entry);
2508 return NULL;
2511 entry->id = dup;
2512 entry->commit = commit;
2513 return entry;
2516 static void
2517 pop_commit(struct commit_queue *commits)
2519 struct commit_queue_entry *entry;
2521 entry = TAILQ_FIRST(&commits->head);
2522 TAILQ_REMOVE(&commits->head, entry, entry);
2523 got_object_commit_close(entry->commit);
2524 commits->ncommits--;
2525 free(entry->id);
2526 free(entry);
2529 static void
2530 free_commits(struct commit_queue *commits)
2532 while (!TAILQ_EMPTY(&commits->head))
2533 pop_commit(commits);
2536 static const struct got_error *
2537 match_commit(int *have_match, struct got_object_id *id,
2538 struct got_commit_object *commit, regex_t *regex)
2540 const struct got_error *err = NULL;
2541 regmatch_t regmatch;
2542 char *id_str = NULL, *logmsg = NULL;
2544 *have_match = 0;
2546 err = got_object_id_str(&id_str, id);
2547 if (err)
2548 return err;
2550 err = got_object_commit_get_logmsg(&logmsg, commit);
2551 if (err)
2552 goto done;
2554 if (regexec(regex, got_object_commit_get_author(commit), 1,
2555 &regmatch, 0) == 0 ||
2556 regexec(regex, got_object_commit_get_committer(commit), 1,
2557 &regmatch, 0) == 0 ||
2558 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2559 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2560 *have_match = 1;
2561 done:
2562 free(id_str);
2563 free(logmsg);
2564 return err;
2567 static const struct got_error *
2568 queue_commits(struct tog_log_thread_args *a)
2570 const struct got_error *err = NULL;
2573 * We keep all commits open throughout the lifetime of the log
2574 * view in order to avoid having to re-fetch commits from disk
2575 * while updating the display.
2577 do {
2578 struct got_object_id id;
2579 struct got_commit_object *commit;
2580 struct commit_queue_entry *entry;
2581 int limit_match = 0;
2582 int errcode;
2584 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2585 NULL, NULL);
2586 if (err)
2587 break;
2589 err = got_object_open_as_commit(&commit, a->repo, &id);
2590 if (err)
2591 break;
2592 entry = alloc_commit_queue_entry(commit, &id);
2593 if (entry == NULL) {
2594 err = got_error_from_errno("alloc_commit_queue_entry");
2595 break;
2598 errcode = pthread_mutex_lock(&tog_mutex);
2599 if (errcode) {
2600 err = got_error_set_errno(errcode,
2601 "pthread_mutex_lock");
2602 break;
2605 entry->idx = a->real_commits->ncommits;
2606 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2607 a->real_commits->ncommits++;
2609 if (*a->limiting) {
2610 err = match_commit(&limit_match, &id, commit,
2611 a->limit_regex);
2612 if (err)
2613 break;
2615 if (limit_match) {
2616 struct commit_queue_entry *matched;
2618 matched = alloc_commit_queue_entry(
2619 entry->commit, entry->id);
2620 if (matched == NULL) {
2621 err = got_error_from_errno(
2622 "alloc_commit_queue_entry");
2623 break;
2625 matched->commit = entry->commit;
2626 got_object_commit_retain(entry->commit);
2628 matched->idx = a->limit_commits->ncommits;
2629 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2630 matched, entry);
2631 a->limit_commits->ncommits++;
2635 * This is how we signal log_thread() that we
2636 * have found a match, and that it should be
2637 * counted as a new entry for the view.
2639 a->limit_match = limit_match;
2642 if (*a->searching == TOG_SEARCH_FORWARD &&
2643 !*a->search_next_done) {
2644 int have_match;
2645 err = match_commit(&have_match, &id, commit, a->regex);
2646 if (err)
2647 break;
2649 if (*a->limiting) {
2650 if (limit_match && have_match)
2651 *a->search_next_done =
2652 TOG_SEARCH_HAVE_MORE;
2653 } else if (have_match)
2654 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2657 errcode = pthread_mutex_unlock(&tog_mutex);
2658 if (errcode && err == NULL)
2659 err = got_error_set_errno(errcode,
2660 "pthread_mutex_unlock");
2661 if (err)
2662 break;
2663 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2665 return err;
2668 static void
2669 select_commit(struct tog_log_view_state *s)
2671 struct commit_queue_entry *entry;
2672 int ncommits = 0;
2674 entry = s->first_displayed_entry;
2675 while (entry) {
2676 if (ncommits == s->selected) {
2677 s->selected_entry = entry;
2678 break;
2680 entry = TAILQ_NEXT(entry, entry);
2681 ncommits++;
2685 static const struct got_error *
2686 draw_commits(struct tog_view *view)
2688 const struct got_error *err = NULL;
2689 struct tog_log_view_state *s = &view->state.log;
2690 struct commit_queue_entry *entry = s->selected_entry;
2691 int limit = view->nlines;
2692 int width;
2693 int ncommits, author_cols = 4;
2694 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2695 char *refs_str = NULL;
2696 wchar_t *wline;
2697 struct tog_color *tc;
2698 static const size_t date_display_cols = 12;
2700 if (view_is_hsplit_top(view))
2701 --limit; /* account for border */
2703 if (s->selected_entry &&
2704 !(view->searching && view->search_next_done == 0)) {
2705 struct got_reflist_head *refs;
2706 err = got_object_id_str(&id_str, s->selected_entry->id);
2707 if (err)
2708 return err;
2709 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2710 s->selected_entry->id);
2711 if (refs) {
2712 err = build_refs_str(&refs_str, refs,
2713 s->selected_entry->id, s->repo);
2714 if (err)
2715 goto done;
2719 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2720 halfdelay(10); /* disable fast refresh */
2722 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2723 if (asprintf(&ncommits_str, " [%d/%d] %s",
2724 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2725 (view->searching && !view->search_next_done) ?
2726 "searching..." : "loading...") == -1) {
2727 err = got_error_from_errno("asprintf");
2728 goto done;
2730 } else {
2731 const char *search_str = NULL;
2732 const char *limit_str = NULL;
2734 if (view->searching) {
2735 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2736 search_str = "no more matches";
2737 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2738 search_str = "no matches found";
2739 else if (!view->search_next_done)
2740 search_str = "searching...";
2743 if (s->limit_view && s->commits->ncommits == 0)
2744 limit_str = "no matches found";
2746 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2747 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2748 search_str ? search_str : (refs_str ? refs_str : ""),
2749 limit_str ? limit_str : "") == -1) {
2750 err = got_error_from_errno("asprintf");
2751 goto done;
2755 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2756 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2757 "........................................",
2758 s->in_repo_path, ncommits_str) == -1) {
2759 err = got_error_from_errno("asprintf");
2760 header = NULL;
2761 goto done;
2763 } else if (asprintf(&header, "commit %s%s",
2764 id_str ? id_str : "........................................",
2765 ncommits_str) == -1) {
2766 err = got_error_from_errno("asprintf");
2767 header = NULL;
2768 goto done;
2770 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2771 if (err)
2772 goto done;
2774 werase(view->window);
2776 if (view_needs_focus_indication(view))
2777 wstandout(view->window);
2778 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2779 if (tc)
2780 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2781 waddwstr(view->window, wline);
2782 while (width < view->ncols) {
2783 waddch(view->window, ' ');
2784 width++;
2786 if (tc)
2787 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2788 if (view_needs_focus_indication(view))
2789 wstandend(view->window);
2790 free(wline);
2791 if (limit <= 1)
2792 goto done;
2794 /* Grow author column size if necessary, and set view->maxx. */
2795 entry = s->first_displayed_entry;
2796 ncommits = 0;
2797 view->maxx = 0;
2798 while (entry) {
2799 struct got_commit_object *c = entry->commit;
2800 char *author, *eol, *msg, *msg0;
2801 wchar_t *wauthor, *wmsg;
2802 int width;
2803 if (ncommits >= limit - 1)
2804 break;
2805 if (s->use_committer)
2806 author = strdup(got_object_commit_get_committer(c));
2807 else
2808 author = strdup(got_object_commit_get_author(c));
2809 if (author == NULL) {
2810 err = got_error_from_errno("strdup");
2811 goto done;
2813 err = format_author(&wauthor, &width, author, COLS,
2814 date_display_cols);
2815 if (author_cols < width)
2816 author_cols = width;
2817 free(wauthor);
2818 free(author);
2819 if (err)
2820 goto done;
2821 err = got_object_commit_get_logmsg(&msg0, c);
2822 if (err)
2823 goto done;
2824 msg = msg0;
2825 while (*msg == '\n')
2826 ++msg;
2827 if ((eol = strchr(msg, '\n')))
2828 *eol = '\0';
2829 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2830 date_display_cols + author_cols, 0);
2831 if (err)
2832 goto done;
2833 view->maxx = MAX(view->maxx, width);
2834 free(msg0);
2835 free(wmsg);
2836 ncommits++;
2837 entry = TAILQ_NEXT(entry, entry);
2840 entry = s->first_displayed_entry;
2841 s->last_displayed_entry = s->first_displayed_entry;
2842 ncommits = 0;
2843 while (entry) {
2844 if (ncommits >= limit - 1)
2845 break;
2846 if (ncommits == s->selected)
2847 wstandout(view->window);
2848 err = draw_commit(view, entry->commit, entry->id,
2849 date_display_cols, author_cols);
2850 if (ncommits == s->selected)
2851 wstandend(view->window);
2852 if (err)
2853 goto done;
2854 ncommits++;
2855 s->last_displayed_entry = entry;
2856 entry = TAILQ_NEXT(entry, entry);
2859 view_border(view);
2860 done:
2861 free(id_str);
2862 free(refs_str);
2863 free(ncommits_str);
2864 free(header);
2865 return err;
2868 static void
2869 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2871 struct commit_queue_entry *entry;
2872 int nscrolled = 0;
2874 entry = TAILQ_FIRST(&s->commits->head);
2875 if (s->first_displayed_entry == entry)
2876 return;
2878 entry = s->first_displayed_entry;
2879 while (entry && nscrolled < maxscroll) {
2880 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2881 if (entry) {
2882 s->first_displayed_entry = entry;
2883 nscrolled++;
2888 static const struct got_error *
2889 trigger_log_thread(struct tog_view *view, int wait)
2891 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2892 int errcode;
2894 if (!using_mock_io)
2895 halfdelay(1); /* fast refresh while loading commits */
2897 while (!ta->log_complete && !tog_thread_error &&
2898 (ta->commits_needed > 0 || ta->load_all)) {
2899 /* Wake the log thread. */
2900 errcode = pthread_cond_signal(&ta->need_commits);
2901 if (errcode)
2902 return got_error_set_errno(errcode,
2903 "pthread_cond_signal");
2906 * The mutex will be released while the view loop waits
2907 * in wgetch(), at which time the log thread will run.
2909 if (!wait)
2910 break;
2912 /* Display progress update in log view. */
2913 show_log_view(view);
2914 update_panels();
2915 doupdate();
2917 /* Wait right here while next commit is being loaded. */
2918 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2919 if (errcode)
2920 return got_error_set_errno(errcode,
2921 "pthread_cond_wait");
2923 /* Display progress update in log view. */
2924 show_log_view(view);
2925 update_panels();
2926 doupdate();
2929 return NULL;
2932 static const struct got_error *
2933 request_log_commits(struct tog_view *view)
2935 struct tog_log_view_state *state = &view->state.log;
2936 const struct got_error *err = NULL;
2938 if (state->thread_args.log_complete)
2939 return NULL;
2941 state->thread_args.commits_needed += view->nscrolled;
2942 err = trigger_log_thread(view, 1);
2943 view->nscrolled = 0;
2945 return err;
2948 static const struct got_error *
2949 log_scroll_down(struct tog_view *view, int maxscroll)
2951 struct tog_log_view_state *s = &view->state.log;
2952 const struct got_error *err = NULL;
2953 struct commit_queue_entry *pentry;
2954 int nscrolled = 0, ncommits_needed;
2956 if (s->last_displayed_entry == NULL)
2957 return NULL;
2959 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2960 if (s->commits->ncommits < ncommits_needed &&
2961 !s->thread_args.log_complete) {
2963 * Ask the log thread for required amount of commits.
2965 s->thread_args.commits_needed +=
2966 ncommits_needed - s->commits->ncommits;
2967 err = trigger_log_thread(view, 1);
2968 if (err)
2969 return err;
2972 do {
2973 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2974 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2975 break;
2977 s->last_displayed_entry = pentry ?
2978 pentry : s->last_displayed_entry;
2980 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2981 if (pentry == NULL)
2982 break;
2983 s->first_displayed_entry = pentry;
2984 } while (++nscrolled < maxscroll);
2986 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2987 view->nscrolled += nscrolled;
2988 else
2989 view->nscrolled = 0;
2991 return err;
2994 static const struct got_error *
2995 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2996 struct got_commit_object *commit, struct got_object_id *commit_id,
2997 struct tog_view *log_view, struct got_repository *repo)
2999 const struct got_error *err;
3000 struct got_object_qid *parent_id;
3001 struct tog_view *diff_view;
3003 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3004 if (diff_view == NULL)
3005 return got_error_from_errno("view_open");
3007 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3008 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3009 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3010 if (err == NULL)
3011 *new_view = diff_view;
3012 return err;
3015 static const struct got_error *
3016 tree_view_visit_subtree(struct tog_tree_view_state *s,
3017 struct got_tree_object *subtree)
3019 struct tog_parent_tree *parent;
3021 parent = calloc(1, sizeof(*parent));
3022 if (parent == NULL)
3023 return got_error_from_errno("calloc");
3025 parent->tree = s->tree;
3026 parent->first_displayed_entry = s->first_displayed_entry;
3027 parent->selected_entry = s->selected_entry;
3028 parent->selected = s->selected;
3029 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3030 s->tree = subtree;
3031 s->selected = 0;
3032 s->first_displayed_entry = NULL;
3033 return NULL;
3036 static const struct got_error *
3037 tree_view_walk_path(struct tog_tree_view_state *s,
3038 struct got_commit_object *commit, const char *path)
3040 const struct got_error *err = NULL;
3041 struct got_tree_object *tree = NULL;
3042 const char *p;
3043 char *slash, *subpath = NULL;
3045 /* Walk the path and open corresponding tree objects. */
3046 p = path;
3047 while (*p) {
3048 struct got_tree_entry *te;
3049 struct got_object_id *tree_id;
3050 char *te_name;
3052 while (p[0] == '/')
3053 p++;
3055 /* Ensure the correct subtree entry is selected. */
3056 slash = strchr(p, '/');
3057 if (slash == NULL)
3058 te_name = strdup(p);
3059 else
3060 te_name = strndup(p, slash - p);
3061 if (te_name == NULL) {
3062 err = got_error_from_errno("strndup");
3063 break;
3065 te = got_object_tree_find_entry(s->tree, te_name);
3066 if (te == NULL) {
3067 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3068 free(te_name);
3069 break;
3071 free(te_name);
3072 s->first_displayed_entry = s->selected_entry = te;
3074 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3075 break; /* jump to this file's entry */
3077 slash = strchr(p, '/');
3078 if (slash)
3079 subpath = strndup(path, slash - path);
3080 else
3081 subpath = strdup(path);
3082 if (subpath == NULL) {
3083 err = got_error_from_errno("strdup");
3084 break;
3087 err = got_object_id_by_path(&tree_id, s->repo, commit,
3088 subpath);
3089 if (err)
3090 break;
3092 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3093 free(tree_id);
3094 if (err)
3095 break;
3097 err = tree_view_visit_subtree(s, tree);
3098 if (err) {
3099 got_object_tree_close(tree);
3100 break;
3102 if (slash == NULL)
3103 break;
3104 free(subpath);
3105 subpath = NULL;
3106 p = slash;
3109 free(subpath);
3110 return err;
3113 static const struct got_error *
3114 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3115 struct commit_queue_entry *entry, const char *path,
3116 const char *head_ref_name, struct got_repository *repo)
3118 const struct got_error *err = NULL;
3119 struct tog_tree_view_state *s;
3120 struct tog_view *tree_view;
3122 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3123 if (tree_view == NULL)
3124 return got_error_from_errno("view_open");
3126 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3127 if (err)
3128 return err;
3129 s = &tree_view->state.tree;
3131 *new_view = tree_view;
3133 if (got_path_is_root_dir(path))
3134 return NULL;
3136 return tree_view_walk_path(s, entry->commit, path);
3139 static const struct got_error *
3140 block_signals_used_by_main_thread(void)
3142 sigset_t sigset;
3143 int errcode;
3145 if (sigemptyset(&sigset) == -1)
3146 return got_error_from_errno("sigemptyset");
3148 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3149 if (sigaddset(&sigset, SIGWINCH) == -1)
3150 return got_error_from_errno("sigaddset");
3151 if (sigaddset(&sigset, SIGCONT) == -1)
3152 return got_error_from_errno("sigaddset");
3153 if (sigaddset(&sigset, SIGINT) == -1)
3154 return got_error_from_errno("sigaddset");
3155 if (sigaddset(&sigset, SIGTERM) == -1)
3156 return got_error_from_errno("sigaddset");
3158 /* ncurses handles SIGTSTP */
3159 if (sigaddset(&sigset, SIGTSTP) == -1)
3160 return got_error_from_errno("sigaddset");
3162 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3163 if (errcode)
3164 return got_error_set_errno(errcode, "pthread_sigmask");
3166 return NULL;
3169 static void *
3170 log_thread(void *arg)
3172 const struct got_error *err = NULL;
3173 int errcode = 0;
3174 struct tog_log_thread_args *a = arg;
3175 int done = 0;
3178 * Sync startup with main thread such that we begin our
3179 * work once view_input() has released the mutex.
3181 errcode = pthread_mutex_lock(&tog_mutex);
3182 if (errcode) {
3183 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3184 return (void *)err;
3187 err = block_signals_used_by_main_thread();
3188 if (err) {
3189 pthread_mutex_unlock(&tog_mutex);
3190 goto done;
3193 while (!done && !err && !tog_fatal_signal_received()) {
3194 errcode = pthread_mutex_unlock(&tog_mutex);
3195 if (errcode) {
3196 err = got_error_set_errno(errcode,
3197 "pthread_mutex_unlock");
3198 goto done;
3200 err = queue_commits(a);
3201 if (err) {
3202 if (err->code != GOT_ERR_ITER_COMPLETED)
3203 goto done;
3204 err = NULL;
3205 done = 1;
3206 } else if (a->commits_needed > 0 && !a->load_all) {
3207 if (*a->limiting) {
3208 if (a->limit_match)
3209 a->commits_needed--;
3210 } else
3211 a->commits_needed--;
3214 errcode = pthread_mutex_lock(&tog_mutex);
3215 if (errcode) {
3216 err = got_error_set_errno(errcode,
3217 "pthread_mutex_lock");
3218 goto done;
3219 } else if (*a->quit)
3220 done = 1;
3221 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3222 *a->first_displayed_entry =
3223 TAILQ_FIRST(&a->limit_commits->head);
3224 *a->selected_entry = *a->first_displayed_entry;
3225 } else if (*a->first_displayed_entry == NULL) {
3226 *a->first_displayed_entry =
3227 TAILQ_FIRST(&a->real_commits->head);
3228 *a->selected_entry = *a->first_displayed_entry;
3231 errcode = pthread_cond_signal(&a->commit_loaded);
3232 if (errcode) {
3233 err = got_error_set_errno(errcode,
3234 "pthread_cond_signal");
3235 pthread_mutex_unlock(&tog_mutex);
3236 goto done;
3239 if (done)
3240 a->commits_needed = 0;
3241 else {
3242 if (a->commits_needed == 0 && !a->load_all) {
3243 errcode = pthread_cond_wait(&a->need_commits,
3244 &tog_mutex);
3245 if (errcode) {
3246 err = got_error_set_errno(errcode,
3247 "pthread_cond_wait");
3248 pthread_mutex_unlock(&tog_mutex);
3249 goto done;
3251 if (*a->quit)
3252 done = 1;
3256 a->log_complete = 1;
3257 errcode = pthread_mutex_unlock(&tog_mutex);
3258 if (errcode)
3259 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3260 done:
3261 if (err) {
3262 tog_thread_error = 1;
3263 pthread_cond_signal(&a->commit_loaded);
3265 return (void *)err;
3268 static const struct got_error *
3269 stop_log_thread(struct tog_log_view_state *s)
3271 const struct got_error *err = NULL, *thread_err = NULL;
3272 int errcode;
3274 if (s->thread) {
3275 s->quit = 1;
3276 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3277 if (errcode)
3278 return got_error_set_errno(errcode,
3279 "pthread_cond_signal");
3280 errcode = pthread_mutex_unlock(&tog_mutex);
3281 if (errcode)
3282 return got_error_set_errno(errcode,
3283 "pthread_mutex_unlock");
3284 errcode = pthread_join(s->thread, (void **)&thread_err);
3285 if (errcode)
3286 return got_error_set_errno(errcode, "pthread_join");
3287 errcode = pthread_mutex_lock(&tog_mutex);
3288 if (errcode)
3289 return got_error_set_errno(errcode,
3290 "pthread_mutex_lock");
3291 s->thread = 0; //NULL;
3294 if (s->thread_args.repo) {
3295 err = got_repo_close(s->thread_args.repo);
3296 s->thread_args.repo = NULL;
3299 if (s->thread_args.pack_fds) {
3300 const struct got_error *pack_err =
3301 got_repo_pack_fds_close(s->thread_args.pack_fds);
3302 if (err == NULL)
3303 err = pack_err;
3304 s->thread_args.pack_fds = NULL;
3307 if (s->thread_args.graph) {
3308 got_commit_graph_close(s->thread_args.graph);
3309 s->thread_args.graph = NULL;
3312 return err ? err : thread_err;
3315 static const struct got_error *
3316 close_log_view(struct tog_view *view)
3318 const struct got_error *err = NULL;
3319 struct tog_log_view_state *s = &view->state.log;
3320 int errcode;
3322 err = stop_log_thread(s);
3324 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3325 if (errcode && err == NULL)
3326 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3328 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3329 if (errcode && err == NULL)
3330 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3332 free_commits(&s->limit_commits);
3333 free_commits(&s->real_commits);
3334 free(s->in_repo_path);
3335 s->in_repo_path = NULL;
3336 free(s->start_id);
3337 s->start_id = NULL;
3338 free(s->head_ref_name);
3339 s->head_ref_name = NULL;
3340 return err;
3344 * We use two queues to implement the limit feature: first consists of
3345 * commits matching the current limit_regex; second is the real queue
3346 * of all known commits (real_commits). When the user starts limiting,
3347 * we swap queues such that all movement and displaying functionality
3348 * works with very slight change.
3350 static const struct got_error *
3351 limit_log_view(struct tog_view *view)
3353 struct tog_log_view_state *s = &view->state.log;
3354 struct commit_queue_entry *entry;
3355 struct tog_view *v = view;
3356 const struct got_error *err = NULL;
3357 char pattern[1024];
3358 int ret;
3360 if (view_is_hsplit_top(view))
3361 v = view->child;
3362 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3363 v = view->parent;
3365 /* Get the pattern */
3366 wmove(v->window, v->nlines - 1, 0);
3367 wclrtoeol(v->window);
3368 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3369 nodelay(v->window, FALSE);
3370 nocbreak();
3371 echo();
3372 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3373 cbreak();
3374 noecho();
3375 nodelay(v->window, TRUE);
3376 if (ret == ERR)
3377 return NULL;
3379 if (*pattern == '\0') {
3381 * Safety measure for the situation where the user
3382 * resets limit without previously limiting anything.
3384 if (!s->limit_view)
3385 return NULL;
3388 * User could have pressed Ctrl+L, which refreshed the
3389 * commit queues, it means we can't save previously
3390 * (before limit took place) displayed entries,
3391 * because they would point to already free'ed memory,
3392 * so we are forced to always select first entry of
3393 * the queue.
3395 s->commits = &s->real_commits;
3396 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3397 s->selected_entry = s->first_displayed_entry;
3398 s->selected = 0;
3399 s->limit_view = 0;
3401 return NULL;
3404 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3405 return NULL;
3407 s->limit_view = 1;
3409 /* Clear the screen while loading limit view */
3410 s->first_displayed_entry = NULL;
3411 s->last_displayed_entry = NULL;
3412 s->selected_entry = NULL;
3413 s->commits = &s->limit_commits;
3415 /* Prepare limit queue for new search */
3416 free_commits(&s->limit_commits);
3417 s->limit_commits.ncommits = 0;
3419 /* First process commits, which are in queue already */
3420 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3421 int have_match = 0;
3423 err = match_commit(&have_match, entry->id,
3424 entry->commit, &s->limit_regex);
3425 if (err)
3426 return err;
3428 if (have_match) {
3429 struct commit_queue_entry *matched;
3431 matched = alloc_commit_queue_entry(entry->commit,
3432 entry->id);
3433 if (matched == NULL) {
3434 err = got_error_from_errno(
3435 "alloc_commit_queue_entry");
3436 break;
3438 matched->commit = entry->commit;
3439 got_object_commit_retain(entry->commit);
3441 matched->idx = s->limit_commits.ncommits;
3442 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3443 matched, entry);
3444 s->limit_commits.ncommits++;
3448 /* Second process all the commits, until we fill the screen */
3449 if (s->limit_commits.ncommits < view->nlines - 1 &&
3450 !s->thread_args.log_complete) {
3451 s->thread_args.commits_needed +=
3452 view->nlines - s->limit_commits.ncommits - 1;
3453 err = trigger_log_thread(view, 1);
3454 if (err)
3455 return err;
3458 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3459 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3460 s->selected = 0;
3462 return NULL;
3465 static const struct got_error *
3466 search_start_log_view(struct tog_view *view)
3468 struct tog_log_view_state *s = &view->state.log;
3470 s->matched_entry = NULL;
3471 s->search_entry = NULL;
3472 return NULL;
3475 static const struct got_error *
3476 search_next_log_view(struct tog_view *view)
3478 const struct got_error *err = NULL;
3479 struct tog_log_view_state *s = &view->state.log;
3480 struct commit_queue_entry *entry;
3482 /* Display progress update in log view. */
3483 show_log_view(view);
3484 update_panels();
3485 doupdate();
3487 if (s->search_entry) {
3488 int errcode, ch;
3489 errcode = pthread_mutex_unlock(&tog_mutex);
3490 if (errcode)
3491 return got_error_set_errno(errcode,
3492 "pthread_mutex_unlock");
3493 ch = wgetch(view->window);
3494 errcode = pthread_mutex_lock(&tog_mutex);
3495 if (errcode)
3496 return got_error_set_errno(errcode,
3497 "pthread_mutex_lock");
3498 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3499 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3500 return NULL;
3502 if (view->searching == TOG_SEARCH_FORWARD)
3503 entry = TAILQ_NEXT(s->search_entry, entry);
3504 else
3505 entry = TAILQ_PREV(s->search_entry,
3506 commit_queue_head, entry);
3507 } else if (s->matched_entry) {
3509 * If the user has moved the cursor after we hit a match,
3510 * the position from where we should continue searching
3511 * might have changed.
3513 if (view->searching == TOG_SEARCH_FORWARD)
3514 entry = TAILQ_NEXT(s->selected_entry, entry);
3515 else
3516 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3517 entry);
3518 } else {
3519 entry = s->selected_entry;
3522 while (1) {
3523 int have_match = 0;
3525 if (entry == NULL) {
3526 if (s->thread_args.log_complete ||
3527 view->searching == TOG_SEARCH_BACKWARD) {
3528 view->search_next_done =
3529 (s->matched_entry == NULL ?
3530 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3531 s->search_entry = NULL;
3532 return NULL;
3535 * Poke the log thread for more commits and return,
3536 * allowing the main loop to make progress. Search
3537 * will resume at s->search_entry once we come back.
3539 s->thread_args.commits_needed++;
3540 return trigger_log_thread(view, 0);
3543 err = match_commit(&have_match, entry->id, entry->commit,
3544 &view->regex);
3545 if (err)
3546 break;
3547 if (have_match) {
3548 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3549 s->matched_entry = entry;
3550 break;
3553 s->search_entry = entry;
3554 if (view->searching == TOG_SEARCH_FORWARD)
3555 entry = TAILQ_NEXT(entry, entry);
3556 else
3557 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3560 if (s->matched_entry) {
3561 int cur = s->selected_entry->idx;
3562 while (cur < s->matched_entry->idx) {
3563 err = input_log_view(NULL, view, KEY_DOWN);
3564 if (err)
3565 return err;
3566 cur++;
3568 while (cur > s->matched_entry->idx) {
3569 err = input_log_view(NULL, view, KEY_UP);
3570 if (err)
3571 return err;
3572 cur--;
3576 s->search_entry = NULL;
3578 return NULL;
3581 static const struct got_error *
3582 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3583 struct got_repository *repo, const char *head_ref_name,
3584 const char *in_repo_path, int log_branches)
3586 const struct got_error *err = NULL;
3587 struct tog_log_view_state *s = &view->state.log;
3588 struct got_repository *thread_repo = NULL;
3589 struct got_commit_graph *thread_graph = NULL;
3590 int errcode;
3592 if (in_repo_path != s->in_repo_path) {
3593 free(s->in_repo_path);
3594 s->in_repo_path = strdup(in_repo_path);
3595 if (s->in_repo_path == NULL) {
3596 err = got_error_from_errno("strdup");
3597 goto done;
3601 /* The commit queue only contains commits being displayed. */
3602 TAILQ_INIT(&s->real_commits.head);
3603 s->real_commits.ncommits = 0;
3604 s->commits = &s->real_commits;
3606 TAILQ_INIT(&s->limit_commits.head);
3607 s->limit_view = 0;
3608 s->limit_commits.ncommits = 0;
3610 s->repo = repo;
3611 if (head_ref_name) {
3612 s->head_ref_name = strdup(head_ref_name);
3613 if (s->head_ref_name == NULL) {
3614 err = got_error_from_errno("strdup");
3615 goto done;
3618 s->start_id = got_object_id_dup(start_id);
3619 if (s->start_id == NULL) {
3620 err = got_error_from_errno("got_object_id_dup");
3621 goto done;
3623 s->log_branches = log_branches;
3624 s->use_committer = 1;
3626 STAILQ_INIT(&s->colors);
3627 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3628 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3629 get_color_value("TOG_COLOR_COMMIT"));
3630 if (err)
3631 goto done;
3632 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3633 get_color_value("TOG_COLOR_AUTHOR"));
3634 if (err) {
3635 free_colors(&s->colors);
3636 goto done;
3638 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3639 get_color_value("TOG_COLOR_DATE"));
3640 if (err) {
3641 free_colors(&s->colors);
3642 goto done;
3646 view->show = show_log_view;
3647 view->input = input_log_view;
3648 view->resize = resize_log_view;
3649 view->close = close_log_view;
3650 view->search_start = search_start_log_view;
3651 view->search_next = search_next_log_view;
3653 if (s->thread_args.pack_fds == NULL) {
3654 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3655 if (err)
3656 goto done;
3658 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3659 s->thread_args.pack_fds);
3660 if (err)
3661 goto done;
3662 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3663 !s->log_branches);
3664 if (err)
3665 goto done;
3666 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3667 s->repo, NULL, NULL);
3668 if (err)
3669 goto done;
3671 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3672 if (errcode) {
3673 err = got_error_set_errno(errcode, "pthread_cond_init");
3674 goto done;
3676 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3677 if (errcode) {
3678 err = got_error_set_errno(errcode, "pthread_cond_init");
3679 goto done;
3682 s->thread_args.commits_needed = view->nlines;
3683 s->thread_args.graph = thread_graph;
3684 s->thread_args.real_commits = &s->real_commits;
3685 s->thread_args.limit_commits = &s->limit_commits;
3686 s->thread_args.in_repo_path = s->in_repo_path;
3687 s->thread_args.start_id = s->start_id;
3688 s->thread_args.repo = thread_repo;
3689 s->thread_args.log_complete = 0;
3690 s->thread_args.quit = &s->quit;
3691 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3692 s->thread_args.selected_entry = &s->selected_entry;
3693 s->thread_args.searching = &view->searching;
3694 s->thread_args.search_next_done = &view->search_next_done;
3695 s->thread_args.regex = &view->regex;
3696 s->thread_args.limiting = &s->limit_view;
3697 s->thread_args.limit_regex = &s->limit_regex;
3698 s->thread_args.limit_commits = &s->limit_commits;
3699 done:
3700 if (err) {
3701 if (view->close == NULL)
3702 close_log_view(view);
3703 view_close(view);
3705 return err;
3708 static const struct got_error *
3709 show_log_view(struct tog_view *view)
3711 const struct got_error *err;
3712 struct tog_log_view_state *s = &view->state.log;
3714 if (s->thread == 0) { //NULL) {
3715 int errcode = pthread_create(&s->thread, NULL, log_thread,
3716 &s->thread_args);
3717 if (errcode)
3718 return got_error_set_errno(errcode, "pthread_create");
3719 if (s->thread_args.commits_needed > 0) {
3720 err = trigger_log_thread(view, 1);
3721 if (err)
3722 return err;
3726 return draw_commits(view);
3729 static void
3730 log_move_cursor_up(struct tog_view *view, int page, int home)
3732 struct tog_log_view_state *s = &view->state.log;
3734 if (s->first_displayed_entry == NULL)
3735 return;
3736 if (s->selected_entry->idx == 0)
3737 view->count = 0;
3739 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3740 || home)
3741 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3743 if (!page && !home && s->selected > 0)
3744 --s->selected;
3745 else
3746 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3748 select_commit(s);
3749 return;
3752 static const struct got_error *
3753 log_move_cursor_down(struct tog_view *view, int page)
3755 struct tog_log_view_state *s = &view->state.log;
3756 const struct got_error *err = NULL;
3757 int eos = view->nlines - 2;
3759 if (s->first_displayed_entry == NULL)
3760 return NULL;
3762 if (s->thread_args.log_complete &&
3763 s->selected_entry->idx >= s->commits->ncommits - 1)
3764 return NULL;
3766 if (view_is_hsplit_top(view))
3767 --eos; /* border consumes the last line */
3769 if (!page) {
3770 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3771 ++s->selected;
3772 else
3773 err = log_scroll_down(view, 1);
3774 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3775 struct commit_queue_entry *entry;
3776 int n;
3778 s->selected = 0;
3779 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3780 s->last_displayed_entry = entry;
3781 for (n = 0; n <= eos; n++) {
3782 if (entry == NULL)
3783 break;
3784 s->first_displayed_entry = entry;
3785 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3787 if (n > 0)
3788 s->selected = n - 1;
3789 } else {
3790 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3791 s->thread_args.log_complete)
3792 s->selected += MIN(page,
3793 s->commits->ncommits - s->selected_entry->idx - 1);
3794 else
3795 err = log_scroll_down(view, page);
3797 if (err)
3798 return err;
3801 * We might necessarily overshoot in horizontal
3802 * splits; if so, select the last displayed commit.
3804 if (s->first_displayed_entry && s->last_displayed_entry) {
3805 s->selected = MIN(s->selected,
3806 s->last_displayed_entry->idx -
3807 s->first_displayed_entry->idx);
3810 select_commit(s);
3812 if (s->thread_args.log_complete &&
3813 s->selected_entry->idx == s->commits->ncommits - 1)
3814 view->count = 0;
3816 return NULL;
3819 static void
3820 view_get_split(struct tog_view *view, int *y, int *x)
3822 *x = 0;
3823 *y = 0;
3825 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3826 if (view->child && view->child->resized_y)
3827 *y = view->child->resized_y;
3828 else if (view->resized_y)
3829 *y = view->resized_y;
3830 else
3831 *y = view_split_begin_y(view->lines);
3832 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3833 if (view->child && view->child->resized_x)
3834 *x = view->child->resized_x;
3835 else if (view->resized_x)
3836 *x = view->resized_x;
3837 else
3838 *x = view_split_begin_x(view->begin_x);
3842 /* Split view horizontally at y and offset view->state->selected line. */
3843 static const struct got_error *
3844 view_init_hsplit(struct tog_view *view, int y)
3846 const struct got_error *err = NULL;
3848 view->nlines = y;
3849 view->ncols = COLS;
3850 err = view_resize(view);
3851 if (err)
3852 return err;
3854 err = offset_selection_down(view);
3856 return err;
3859 static const struct got_error *
3860 log_goto_line(struct tog_view *view, int nlines)
3862 const struct got_error *err = NULL;
3863 struct tog_log_view_state *s = &view->state.log;
3864 int g, idx = s->selected_entry->idx;
3866 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3867 return NULL;
3869 g = view->gline;
3870 view->gline = 0;
3872 if (g >= s->first_displayed_entry->idx + 1 &&
3873 g <= s->last_displayed_entry->idx + 1 &&
3874 g - s->first_displayed_entry->idx - 1 < nlines) {
3875 s->selected = g - s->first_displayed_entry->idx - 1;
3876 select_commit(s);
3877 return NULL;
3880 if (idx + 1 < g) {
3881 err = log_move_cursor_down(view, g - idx - 1);
3882 if (!err && g > s->selected_entry->idx + 1)
3883 err = log_move_cursor_down(view,
3884 g - s->first_displayed_entry->idx - 1);
3885 if (err)
3886 return err;
3887 } else if (idx + 1 > g)
3888 log_move_cursor_up(view, idx - g + 1, 0);
3890 if (g < nlines && s->first_displayed_entry->idx == 0)
3891 s->selected = g - 1;
3893 select_commit(s);
3894 return NULL;
3898 static void
3899 horizontal_scroll_input(struct tog_view *view, int ch)
3902 switch (ch) {
3903 case KEY_LEFT:
3904 case 'h':
3905 view->x -= MIN(view->x, 2);
3906 if (view->x <= 0)
3907 view->count = 0;
3908 break;
3909 case KEY_RIGHT:
3910 case 'l':
3911 if (view->x + view->ncols / 2 < view->maxx)
3912 view->x += 2;
3913 else
3914 view->count = 0;
3915 break;
3916 case '0':
3917 view->x = 0;
3918 break;
3919 case '$':
3920 view->x = MAX(view->maxx - view->ncols / 2, 0);
3921 view->count = 0;
3922 break;
3923 default:
3924 break;
3928 static const struct got_error *
3929 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3931 const struct got_error *err = NULL;
3932 struct tog_log_view_state *s = &view->state.log;
3933 int eos, nscroll;
3935 if (s->thread_args.load_all) {
3936 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3937 s->thread_args.load_all = 0;
3938 else if (s->thread_args.log_complete) {
3939 err = log_move_cursor_down(view, s->commits->ncommits);
3940 s->thread_args.load_all = 0;
3942 if (err)
3943 return err;
3946 eos = nscroll = view->nlines - 1;
3947 if (view_is_hsplit_top(view))
3948 --eos; /* border */
3950 if (view->gline)
3951 return log_goto_line(view, eos);
3953 switch (ch) {
3954 case '&':
3955 err = limit_log_view(view);
3956 break;
3957 case 'q':
3958 s->quit = 1;
3959 break;
3960 case '0':
3961 case '$':
3962 case KEY_RIGHT:
3963 case 'l':
3964 case KEY_LEFT:
3965 case 'h':
3966 horizontal_scroll_input(view, ch);
3967 break;
3968 case 'k':
3969 case KEY_UP:
3970 case '<':
3971 case ',':
3972 case CTRL('p'):
3973 log_move_cursor_up(view, 0, 0);
3974 break;
3975 case 'g':
3976 case '=':
3977 case KEY_HOME:
3978 log_move_cursor_up(view, 0, 1);
3979 view->count = 0;
3980 break;
3981 case CTRL('u'):
3982 case 'u':
3983 nscroll /= 2;
3984 /* FALL THROUGH */
3985 case KEY_PPAGE:
3986 case CTRL('b'):
3987 case 'b':
3988 log_move_cursor_up(view, nscroll, 0);
3989 break;
3990 case 'j':
3991 case KEY_DOWN:
3992 case '>':
3993 case '.':
3994 case CTRL('n'):
3995 err = log_move_cursor_down(view, 0);
3996 break;
3997 case '@':
3998 s->use_committer = !s->use_committer;
3999 view->action = s->use_committer ?
4000 "show committer" : "show commit author";
4001 break;
4002 case 'G':
4003 case '*':
4004 case KEY_END: {
4005 /* We don't know yet how many commits, so we're forced to
4006 * traverse them all. */
4007 view->count = 0;
4008 s->thread_args.load_all = 1;
4009 if (!s->thread_args.log_complete)
4010 return trigger_log_thread(view, 0);
4011 err = log_move_cursor_down(view, s->commits->ncommits);
4012 s->thread_args.load_all = 0;
4013 break;
4015 case CTRL('d'):
4016 case 'd':
4017 nscroll /= 2;
4018 /* FALL THROUGH */
4019 case KEY_NPAGE:
4020 case CTRL('f'):
4021 case 'f':
4022 case ' ':
4023 err = log_move_cursor_down(view, nscroll);
4024 break;
4025 case KEY_RESIZE:
4026 if (s->selected > view->nlines - 2)
4027 s->selected = view->nlines - 2;
4028 if (s->selected > s->commits->ncommits - 1)
4029 s->selected = s->commits->ncommits - 1;
4030 select_commit(s);
4031 if (s->commits->ncommits < view->nlines - 1 &&
4032 !s->thread_args.log_complete) {
4033 s->thread_args.commits_needed += (view->nlines - 1) -
4034 s->commits->ncommits;
4035 err = trigger_log_thread(view, 1);
4037 break;
4038 case KEY_ENTER:
4039 case '\r':
4040 view->count = 0;
4041 if (s->selected_entry == NULL)
4042 break;
4043 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4044 break;
4045 case 'T':
4046 view->count = 0;
4047 if (s->selected_entry == NULL)
4048 break;
4049 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4050 break;
4051 case KEY_BACKSPACE:
4052 case CTRL('l'):
4053 case 'B':
4054 view->count = 0;
4055 if (ch == KEY_BACKSPACE &&
4056 got_path_is_root_dir(s->in_repo_path))
4057 break;
4058 err = stop_log_thread(s);
4059 if (err)
4060 return err;
4061 if (ch == KEY_BACKSPACE) {
4062 char *parent_path;
4063 err = got_path_dirname(&parent_path, s->in_repo_path);
4064 if (err)
4065 return err;
4066 free(s->in_repo_path);
4067 s->in_repo_path = parent_path;
4068 s->thread_args.in_repo_path = s->in_repo_path;
4069 } else if (ch == CTRL('l')) {
4070 struct got_object_id *start_id;
4071 err = got_repo_match_object_id(&start_id, NULL,
4072 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4073 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4074 if (err) {
4075 if (s->head_ref_name == NULL ||
4076 err->code != GOT_ERR_NOT_REF)
4077 return err;
4078 /* Try to cope with deleted references. */
4079 free(s->head_ref_name);
4080 s->head_ref_name = NULL;
4081 err = got_repo_match_object_id(&start_id,
4082 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4083 &tog_refs, s->repo);
4084 if (err)
4085 return err;
4087 free(s->start_id);
4088 s->start_id = start_id;
4089 s->thread_args.start_id = s->start_id;
4090 } else /* 'B' */
4091 s->log_branches = !s->log_branches;
4093 if (s->thread_args.pack_fds == NULL) {
4094 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4095 if (err)
4096 return err;
4098 err = got_repo_open(&s->thread_args.repo,
4099 got_repo_get_path(s->repo), NULL,
4100 s->thread_args.pack_fds);
4101 if (err)
4102 return err;
4103 tog_free_refs();
4104 err = tog_load_refs(s->repo, 0);
4105 if (err)
4106 return err;
4107 err = got_commit_graph_open(&s->thread_args.graph,
4108 s->in_repo_path, !s->log_branches);
4109 if (err)
4110 return err;
4111 err = got_commit_graph_iter_start(s->thread_args.graph,
4112 s->start_id, s->repo, NULL, NULL);
4113 if (err)
4114 return err;
4115 free_commits(&s->real_commits);
4116 free_commits(&s->limit_commits);
4117 s->first_displayed_entry = NULL;
4118 s->last_displayed_entry = NULL;
4119 s->selected_entry = NULL;
4120 s->selected = 0;
4121 s->thread_args.log_complete = 0;
4122 s->quit = 0;
4123 s->thread_args.commits_needed = view->lines;
4124 s->matched_entry = NULL;
4125 s->search_entry = NULL;
4126 view->offset = 0;
4127 break;
4128 case 'R':
4129 view->count = 0;
4130 err = view_request_new(new_view, view, TOG_VIEW_REF);
4131 break;
4132 default:
4133 view->count = 0;
4134 break;
4137 return err;
4140 static const struct got_error *
4141 apply_unveil(const char *repo_path, const char *worktree_path)
4143 const struct got_error *error;
4145 #ifdef PROFILE
4146 if (unveil("gmon.out", "rwc") != 0)
4147 return got_error_from_errno2("unveil", "gmon.out");
4148 #endif
4149 if (repo_path && unveil(repo_path, "r") != 0)
4150 return got_error_from_errno2("unveil", repo_path);
4152 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4153 return got_error_from_errno2("unveil", worktree_path);
4155 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4156 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4158 error = got_privsep_unveil_exec_helpers();
4159 if (error != NULL)
4160 return error;
4162 if (unveil(NULL, NULL) != 0)
4163 return got_error_from_errno("unveil");
4165 return NULL;
4168 static const struct got_error *
4169 init_mock_term(const char *test_script_path)
4171 const struct got_error *err = NULL;
4173 if (test_script_path == NULL || *test_script_path == '\0')
4174 return got_error_msg(GOT_ERR_IO, "GOT_TOG_TEST not defined");
4176 tog_io.f = fopen(test_script_path, "re");
4177 if (tog_io.f == NULL) {
4178 err = got_error_from_errno_fmt("fopen: %s",
4179 test_script_path);
4180 goto done;
4183 /* test mode, we don't want any output */
4184 tog_io.cout = fopen("/dev/null", "w+");
4185 if (tog_io.cout == NULL) {
4186 err = got_error_from_errno("fopen: /dev/null");
4187 goto done;
4190 tog_io.cin = fopen("/dev/tty", "r+");
4191 if (tog_io.cin == NULL) {
4192 err = got_error_from_errno("fopen: /dev/tty");
4193 goto done;
4196 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4197 err = got_error_from_errno("fseeko");
4198 goto done;
4201 /* use local TERM so we test in different environments */
4202 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4203 err = got_error_msg(GOT_ERR_IO,
4204 "newterm: failed to initialise curses");
4206 using_mock_io = 1;
4207 done:
4208 if (err)
4209 tog_io_close();
4210 return err;
4213 static void
4214 init_curses(void)
4217 * Override default signal handlers before starting ncurses.
4218 * This should prevent ncurses from installing its own
4219 * broken cleanup() signal handler.
4221 signal(SIGWINCH, tog_sigwinch);
4222 signal(SIGPIPE, tog_sigpipe);
4223 signal(SIGCONT, tog_sigcont);
4224 signal(SIGINT, tog_sigint);
4225 signal(SIGTERM, tog_sigterm);
4227 if (using_mock_io) /* In test mode we use a fake terminal */
4228 return;
4230 initscr();
4232 cbreak();
4233 halfdelay(1); /* Fast refresh while initial view is loading. */
4234 noecho();
4235 nonl();
4236 intrflush(stdscr, FALSE);
4237 keypad(stdscr, TRUE);
4238 curs_set(0);
4239 if (getenv("TOG_COLORS") != NULL) {
4240 start_color();
4241 use_default_colors();
4244 return;
4247 static const struct got_error *
4248 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4249 struct got_repository *repo, struct got_worktree *worktree)
4251 const struct got_error *err = NULL;
4253 if (argc == 0) {
4254 *in_repo_path = strdup("/");
4255 if (*in_repo_path == NULL)
4256 return got_error_from_errno("strdup");
4257 return NULL;
4260 if (worktree) {
4261 const char *prefix = got_worktree_get_path_prefix(worktree);
4262 char *p;
4264 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4265 if (err)
4266 return err;
4267 if (asprintf(in_repo_path, "%s%s%s", prefix,
4268 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4269 p) == -1) {
4270 err = got_error_from_errno("asprintf");
4271 *in_repo_path = NULL;
4273 free(p);
4274 } else
4275 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4277 return err;
4280 static const struct got_error *
4281 cmd_log(int argc, char *argv[])
4283 const struct got_error *error;
4284 struct got_repository *repo = NULL;
4285 struct got_worktree *worktree = NULL;
4286 struct got_object_id *start_id = NULL;
4287 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4288 char *start_commit = NULL, *label = NULL;
4289 struct got_reference *ref = NULL;
4290 const char *head_ref_name = NULL;
4291 int ch, log_branches = 0;
4292 struct tog_view *view;
4293 int *pack_fds = NULL;
4295 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4296 switch (ch) {
4297 case 'b':
4298 log_branches = 1;
4299 break;
4300 case 'c':
4301 start_commit = optarg;
4302 break;
4303 case 'r':
4304 repo_path = realpath(optarg, NULL);
4305 if (repo_path == NULL)
4306 return got_error_from_errno2("realpath",
4307 optarg);
4308 break;
4309 default:
4310 usage_log();
4311 /* NOTREACHED */
4315 argc -= optind;
4316 argv += optind;
4318 if (argc > 1)
4319 usage_log();
4321 error = got_repo_pack_fds_open(&pack_fds);
4322 if (error != NULL)
4323 goto done;
4325 if (repo_path == NULL) {
4326 cwd = getcwd(NULL, 0);
4327 if (cwd == NULL)
4328 return got_error_from_errno("getcwd");
4329 error = got_worktree_open(&worktree, cwd);
4330 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4331 goto done;
4332 if (worktree)
4333 repo_path =
4334 strdup(got_worktree_get_repo_path(worktree));
4335 else
4336 repo_path = strdup(cwd);
4337 if (repo_path == NULL) {
4338 error = got_error_from_errno("strdup");
4339 goto done;
4343 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4344 if (error != NULL)
4345 goto done;
4347 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4348 repo, worktree);
4349 if (error)
4350 goto done;
4352 init_curses();
4354 error = apply_unveil(got_repo_get_path(repo),
4355 worktree ? got_worktree_get_root_path(worktree) : NULL);
4356 if (error)
4357 goto done;
4359 /* already loaded by tog_log_with_path()? */
4360 if (TAILQ_EMPTY(&tog_refs)) {
4361 error = tog_load_refs(repo, 0);
4362 if (error)
4363 goto done;
4366 if (start_commit == NULL) {
4367 error = got_repo_match_object_id(&start_id, &label,
4368 worktree ? got_worktree_get_head_ref_name(worktree) :
4369 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4370 if (error)
4371 goto done;
4372 head_ref_name = label;
4373 } else {
4374 error = got_ref_open(&ref, repo, start_commit, 0);
4375 if (error == NULL)
4376 head_ref_name = got_ref_get_name(ref);
4377 else if (error->code != GOT_ERR_NOT_REF)
4378 goto done;
4379 error = got_repo_match_object_id(&start_id, NULL,
4380 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4381 if (error)
4382 goto done;
4385 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4386 if (view == NULL) {
4387 error = got_error_from_errno("view_open");
4388 goto done;
4390 error = open_log_view(view, start_id, repo, head_ref_name,
4391 in_repo_path, log_branches);
4392 if (error)
4393 goto done;
4394 if (worktree) {
4395 /* Release work tree lock. */
4396 got_worktree_close(worktree);
4397 worktree = NULL;
4399 error = view_loop(view);
4400 done:
4401 free(in_repo_path);
4402 free(repo_path);
4403 free(cwd);
4404 free(start_id);
4405 free(label);
4406 if (ref)
4407 got_ref_close(ref);
4408 if (repo) {
4409 const struct got_error *close_err = got_repo_close(repo);
4410 if (error == NULL)
4411 error = close_err;
4413 if (worktree)
4414 got_worktree_close(worktree);
4415 if (pack_fds) {
4416 const struct got_error *pack_err =
4417 got_repo_pack_fds_close(pack_fds);
4418 if (error == NULL)
4419 error = pack_err;
4421 tog_free_refs();
4422 return error;
4425 __dead static void
4426 usage_diff(void)
4428 endwin();
4429 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4430 "object1 object2\n", getprogname());
4431 exit(1);
4434 static int
4435 match_line(const char *line, regex_t *regex, size_t nmatch,
4436 regmatch_t *regmatch)
4438 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4441 static struct tog_color *
4442 match_color(struct tog_colors *colors, const char *line)
4444 struct tog_color *tc = NULL;
4446 STAILQ_FOREACH(tc, colors, entry) {
4447 if (match_line(line, &tc->regex, 0, NULL))
4448 return tc;
4451 return NULL;
4454 static const struct got_error *
4455 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4456 WINDOW *window, int skipcol, regmatch_t *regmatch)
4458 const struct got_error *err = NULL;
4459 char *exstr = NULL;
4460 wchar_t *wline = NULL;
4461 int rme, rms, n, width, scrollx;
4462 int width0 = 0, width1 = 0, width2 = 0;
4463 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4465 *wtotal = 0;
4467 rms = regmatch->rm_so;
4468 rme = regmatch->rm_eo;
4470 err = expand_tab(&exstr, line);
4471 if (err)
4472 return err;
4474 /* Split the line into 3 segments, according to match offsets. */
4475 seg0 = strndup(exstr, rms);
4476 if (seg0 == NULL) {
4477 err = got_error_from_errno("strndup");
4478 goto done;
4480 seg1 = strndup(exstr + rms, rme - rms);
4481 if (seg1 == NULL) {
4482 err = got_error_from_errno("strndup");
4483 goto done;
4485 seg2 = strdup(exstr + rme);
4486 if (seg2 == NULL) {
4487 err = got_error_from_errno("strndup");
4488 goto done;
4491 /* draw up to matched token if we haven't scrolled past it */
4492 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4493 col_tab_align, 1);
4494 if (err)
4495 goto done;
4496 n = MAX(width0 - skipcol, 0);
4497 if (n) {
4498 free(wline);
4499 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4500 wlimit, col_tab_align, 1);
4501 if (err)
4502 goto done;
4503 waddwstr(window, &wline[scrollx]);
4504 wlimit -= width;
4505 *wtotal += width;
4508 if (wlimit > 0) {
4509 int i = 0, w = 0;
4510 size_t wlen;
4512 free(wline);
4513 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4514 col_tab_align, 1);
4515 if (err)
4516 goto done;
4517 wlen = wcslen(wline);
4518 while (i < wlen) {
4519 width = wcwidth(wline[i]);
4520 if (width == -1) {
4521 /* should not happen, tabs are expanded */
4522 err = got_error(GOT_ERR_RANGE);
4523 goto done;
4525 if (width0 + w + width > skipcol)
4526 break;
4527 w += width;
4528 i++;
4530 /* draw (visible part of) matched token (if scrolled into it) */
4531 if (width1 - w > 0) {
4532 wattron(window, A_STANDOUT);
4533 waddwstr(window, &wline[i]);
4534 wattroff(window, A_STANDOUT);
4535 wlimit -= (width1 - w);
4536 *wtotal += (width1 - w);
4540 if (wlimit > 0) { /* draw rest of line */
4541 free(wline);
4542 if (skipcol > width0 + width1) {
4543 err = format_line(&wline, &width2, &scrollx, seg2,
4544 skipcol - (width0 + width1), wlimit,
4545 col_tab_align, 1);
4546 if (err)
4547 goto done;
4548 waddwstr(window, &wline[scrollx]);
4549 } else {
4550 err = format_line(&wline, &width2, NULL, seg2, 0,
4551 wlimit, col_tab_align, 1);
4552 if (err)
4553 goto done;
4554 waddwstr(window, wline);
4556 *wtotal += width2;
4558 done:
4559 free(wline);
4560 free(exstr);
4561 free(seg0);
4562 free(seg1);
4563 free(seg2);
4564 return err;
4567 static int
4568 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4570 FILE *f = NULL;
4571 int *eof, *first, *selected;
4573 if (view->type == TOG_VIEW_DIFF) {
4574 struct tog_diff_view_state *s = &view->state.diff;
4576 first = &s->first_displayed_line;
4577 selected = first;
4578 eof = &s->eof;
4579 f = s->f;
4580 } else if (view->type == TOG_VIEW_HELP) {
4581 struct tog_help_view_state *s = &view->state.help;
4583 first = &s->first_displayed_line;
4584 selected = first;
4585 eof = &s->eof;
4586 f = s->f;
4587 } else if (view->type == TOG_VIEW_BLAME) {
4588 struct tog_blame_view_state *s = &view->state.blame;
4590 first = &s->first_displayed_line;
4591 selected = &s->selected_line;
4592 eof = &s->eof;
4593 f = s->blame.f;
4594 } else
4595 return 0;
4597 /* Center gline in the middle of the page like vi(1). */
4598 if (*lineno < view->gline - (view->nlines - 3) / 2)
4599 return 0;
4600 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4601 rewind(f);
4602 *eof = 0;
4603 *first = 1;
4604 *lineno = 0;
4605 *nprinted = 0;
4606 return 0;
4609 *selected = view->gline <= (view->nlines - 3) / 2 ?
4610 view->gline : (view->nlines - 3) / 2 + 1;
4611 view->gline = 0;
4613 return 1;
4616 static const struct got_error *
4617 draw_file(struct tog_view *view, const char *header)
4619 struct tog_diff_view_state *s = &view->state.diff;
4620 regmatch_t *regmatch = &view->regmatch;
4621 const struct got_error *err;
4622 int nprinted = 0;
4623 char *line;
4624 size_t linesize = 0;
4625 ssize_t linelen;
4626 wchar_t *wline;
4627 int width;
4628 int max_lines = view->nlines;
4629 int nlines = s->nlines;
4630 off_t line_offset;
4632 s->lineno = s->first_displayed_line - 1;
4633 line_offset = s->lines[s->first_displayed_line - 1].offset;
4634 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4635 return got_error_from_errno("fseek");
4637 werase(view->window);
4639 if (view->gline > s->nlines - 1)
4640 view->gline = s->nlines - 1;
4642 if (header) {
4643 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4644 1 : view->gline - (view->nlines - 3) / 2 :
4645 s->lineno + s->selected_line;
4647 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4648 return got_error_from_errno("asprintf");
4649 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4650 0, 0);
4651 free(line);
4652 if (err)
4653 return err;
4655 if (view_needs_focus_indication(view))
4656 wstandout(view->window);
4657 waddwstr(view->window, wline);
4658 free(wline);
4659 wline = NULL;
4660 while (width++ < view->ncols)
4661 waddch(view->window, ' ');
4662 if (view_needs_focus_indication(view))
4663 wstandend(view->window);
4665 if (max_lines <= 1)
4666 return NULL;
4667 max_lines--;
4670 s->eof = 0;
4671 view->maxx = 0;
4672 line = NULL;
4673 while (max_lines > 0 && nprinted < max_lines) {
4674 enum got_diff_line_type linetype;
4675 attr_t attr = 0;
4677 linelen = getline(&line, &linesize, s->f);
4678 if (linelen == -1) {
4679 if (feof(s->f)) {
4680 s->eof = 1;
4681 break;
4683 free(line);
4684 return got_ferror(s->f, GOT_ERR_IO);
4687 if (++s->lineno < s->first_displayed_line)
4688 continue;
4689 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4690 continue;
4691 if (s->lineno == view->hiline)
4692 attr = A_STANDOUT;
4694 /* Set view->maxx based on full line length. */
4695 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4696 view->x ? 1 : 0);
4697 if (err) {
4698 free(line);
4699 return err;
4701 view->maxx = MAX(view->maxx, width);
4702 free(wline);
4703 wline = NULL;
4705 linetype = s->lines[s->lineno].type;
4706 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4707 linetype < GOT_DIFF_LINE_CONTEXT)
4708 attr |= COLOR_PAIR(linetype);
4709 if (attr)
4710 wattron(view->window, attr);
4711 if (s->first_displayed_line + nprinted == s->matched_line &&
4712 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4713 err = add_matched_line(&width, line, view->ncols, 0,
4714 view->window, view->x, regmatch);
4715 if (err) {
4716 free(line);
4717 return err;
4719 } else {
4720 int skip;
4721 err = format_line(&wline, &width, &skip, line,
4722 view->x, view->ncols, 0, view->x ? 1 : 0);
4723 if (err) {
4724 free(line);
4725 return err;
4727 waddwstr(view->window, &wline[skip]);
4728 free(wline);
4729 wline = NULL;
4731 if (s->lineno == view->hiline) {
4732 /* highlight full gline length */
4733 while (width++ < view->ncols)
4734 waddch(view->window, ' ');
4735 } else {
4736 if (width <= view->ncols - 1)
4737 waddch(view->window, '\n');
4739 if (attr)
4740 wattroff(view->window, attr);
4741 if (++nprinted == 1)
4742 s->first_displayed_line = s->lineno;
4744 free(line);
4745 if (nprinted >= 1)
4746 s->last_displayed_line = s->first_displayed_line +
4747 (nprinted - 1);
4748 else
4749 s->last_displayed_line = s->first_displayed_line;
4751 view_border(view);
4753 if (s->eof) {
4754 while (nprinted < view->nlines) {
4755 waddch(view->window, '\n');
4756 nprinted++;
4759 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4760 view->ncols, 0, 0);
4761 if (err) {
4762 return err;
4765 wstandout(view->window);
4766 waddwstr(view->window, wline);
4767 free(wline);
4768 wline = NULL;
4769 wstandend(view->window);
4772 return NULL;
4775 static char *
4776 get_datestr(time_t *time, char *datebuf)
4778 struct tm mytm, *tm;
4779 char *p, *s;
4781 tm = gmtime_r(time, &mytm);
4782 if (tm == NULL)
4783 return NULL;
4784 s = asctime_r(tm, datebuf);
4785 if (s == NULL)
4786 return NULL;
4787 p = strchr(s, '\n');
4788 if (p)
4789 *p = '\0';
4790 return s;
4793 static const struct got_error *
4794 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4795 off_t off, uint8_t type)
4797 struct got_diff_line *p;
4799 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4800 if (p == NULL)
4801 return got_error_from_errno("reallocarray");
4802 *lines = p;
4803 (*lines)[*nlines].offset = off;
4804 (*lines)[*nlines].type = type;
4805 (*nlines)++;
4807 return NULL;
4810 static const struct got_error *
4811 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4812 struct got_diff_line *s_lines, size_t s_nlines)
4814 struct got_diff_line *p;
4815 char buf[BUFSIZ];
4816 size_t i, r;
4818 if (fseeko(src, 0L, SEEK_SET) == -1)
4819 return got_error_from_errno("fseeko");
4821 for (;;) {
4822 r = fread(buf, 1, sizeof(buf), src);
4823 if (r == 0) {
4824 if (ferror(src))
4825 return got_error_from_errno("fread");
4826 if (feof(src))
4827 break;
4829 if (fwrite(buf, 1, r, dst) != r)
4830 return got_ferror(dst, GOT_ERR_IO);
4833 if (s_nlines == 0 && *d_nlines == 0)
4834 return NULL;
4837 * If commit info was in dst, increment line offsets
4838 * of the appended diff content, but skip s_lines[0]
4839 * because offset zero is already in *d_lines.
4841 if (*d_nlines > 0) {
4842 for (i = 1; i < s_nlines; ++i)
4843 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4845 if (s_nlines > 0) {
4846 --s_nlines;
4847 ++s_lines;
4851 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4852 if (p == NULL) {
4853 /* d_lines is freed in close_diff_view() */
4854 return got_error_from_errno("reallocarray");
4857 *d_lines = p;
4859 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4860 *d_nlines += s_nlines;
4862 return NULL;
4865 static const struct got_error *
4866 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4867 struct got_object_id *commit_id, struct got_reflist_head *refs,
4868 struct got_repository *repo, int ignore_ws, int force_text_diff,
4869 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4871 const struct got_error *err = NULL;
4872 char datebuf[26], *datestr;
4873 struct got_commit_object *commit;
4874 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4875 time_t committer_time;
4876 const char *author, *committer;
4877 char *refs_str = NULL;
4878 struct got_pathlist_entry *pe;
4879 off_t outoff = 0;
4880 int n;
4882 if (refs) {
4883 err = build_refs_str(&refs_str, refs, commit_id, repo);
4884 if (err)
4885 return err;
4888 err = got_object_open_as_commit(&commit, repo, commit_id);
4889 if (err)
4890 return err;
4892 err = got_object_id_str(&id_str, commit_id);
4893 if (err) {
4894 err = got_error_from_errno("got_object_id_str");
4895 goto done;
4898 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4899 if (err)
4900 goto done;
4902 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4903 refs_str ? refs_str : "", refs_str ? ")" : "");
4904 if (n < 0) {
4905 err = got_error_from_errno("fprintf");
4906 goto done;
4908 outoff += n;
4909 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4910 if (err)
4911 goto done;
4913 n = fprintf(outfile, "from: %s\n",
4914 got_object_commit_get_author(commit));
4915 if (n < 0) {
4916 err = got_error_from_errno("fprintf");
4917 goto done;
4919 outoff += n;
4920 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4921 if (err)
4922 goto done;
4924 author = got_object_commit_get_author(commit);
4925 committer = got_object_commit_get_committer(commit);
4926 if (strcmp(author, committer) != 0) {
4927 n = fprintf(outfile, "via: %s\n", committer);
4928 if (n < 0) {
4929 err = got_error_from_errno("fprintf");
4930 goto done;
4932 outoff += n;
4933 err = add_line_metadata(lines, nlines, outoff,
4934 GOT_DIFF_LINE_AUTHOR);
4935 if (err)
4936 goto done;
4938 committer_time = got_object_commit_get_committer_time(commit);
4939 datestr = get_datestr(&committer_time, datebuf);
4940 if (datestr) {
4941 n = fprintf(outfile, "date: %s UTC\n", datestr);
4942 if (n < 0) {
4943 err = got_error_from_errno("fprintf");
4944 goto done;
4946 outoff += n;
4947 err = add_line_metadata(lines, nlines, outoff,
4948 GOT_DIFF_LINE_DATE);
4949 if (err)
4950 goto done;
4952 if (got_object_commit_get_nparents(commit) > 1) {
4953 const struct got_object_id_queue *parent_ids;
4954 struct got_object_qid *qid;
4955 int pn = 1;
4956 parent_ids = got_object_commit_get_parent_ids(commit);
4957 STAILQ_FOREACH(qid, parent_ids, entry) {
4958 err = got_object_id_str(&id_str, &qid->id);
4959 if (err)
4960 goto done;
4961 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4962 if (n < 0) {
4963 err = got_error_from_errno("fprintf");
4964 goto done;
4966 outoff += n;
4967 err = add_line_metadata(lines, nlines, outoff,
4968 GOT_DIFF_LINE_META);
4969 if (err)
4970 goto done;
4971 free(id_str);
4972 id_str = NULL;
4976 err = got_object_commit_get_logmsg(&logmsg, commit);
4977 if (err)
4978 goto done;
4979 s = logmsg;
4980 while ((line = strsep(&s, "\n")) != NULL) {
4981 n = fprintf(outfile, "%s\n", line);
4982 if (n < 0) {
4983 err = got_error_from_errno("fprintf");
4984 goto done;
4986 outoff += n;
4987 err = add_line_metadata(lines, nlines, outoff,
4988 GOT_DIFF_LINE_LOGMSG);
4989 if (err)
4990 goto done;
4993 TAILQ_FOREACH(pe, dsa->paths, entry) {
4994 struct got_diff_changed_path *cp = pe->data;
4995 int pad = dsa->max_path_len - pe->path_len + 1;
4997 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4998 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4999 dsa->rm_cols + 1, cp->rm);
5000 if (n < 0) {
5001 err = got_error_from_errno("fprintf");
5002 goto done;
5004 outoff += n;
5005 err = add_line_metadata(lines, nlines, outoff,
5006 GOT_DIFF_LINE_CHANGES);
5007 if (err)
5008 goto done;
5011 fputc('\n', outfile);
5012 outoff++;
5013 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5014 if (err)
5015 goto done;
5017 n = fprintf(outfile,
5018 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5019 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5020 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5021 if (n < 0) {
5022 err = got_error_from_errno("fprintf");
5023 goto done;
5025 outoff += n;
5026 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5027 if (err)
5028 goto done;
5030 fputc('\n', outfile);
5031 outoff++;
5032 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5033 done:
5034 free(id_str);
5035 free(logmsg);
5036 free(refs_str);
5037 got_object_commit_close(commit);
5038 if (err) {
5039 free(*lines);
5040 *lines = NULL;
5041 *nlines = 0;
5043 return err;
5046 static const struct got_error *
5047 create_diff(struct tog_diff_view_state *s)
5049 const struct got_error *err = NULL;
5050 FILE *f = NULL, *tmp_diff_file = NULL;
5051 int obj_type;
5052 struct got_diff_line *lines = NULL;
5053 struct got_pathlist_head changed_paths;
5055 TAILQ_INIT(&changed_paths);
5057 free(s->lines);
5058 s->lines = malloc(sizeof(*s->lines));
5059 if (s->lines == NULL)
5060 return got_error_from_errno("malloc");
5061 s->nlines = 0;
5063 f = got_opentemp();
5064 if (f == NULL) {
5065 err = got_error_from_errno("got_opentemp");
5066 goto done;
5068 tmp_diff_file = got_opentemp();
5069 if (tmp_diff_file == NULL) {
5070 err = got_error_from_errno("got_opentemp");
5071 goto done;
5073 if (s->f && fclose(s->f) == EOF) {
5074 err = got_error_from_errno("fclose");
5075 goto done;
5077 s->f = f;
5079 if (s->id1)
5080 err = got_object_get_type(&obj_type, s->repo, s->id1);
5081 else
5082 err = got_object_get_type(&obj_type, s->repo, s->id2);
5083 if (err)
5084 goto done;
5086 switch (obj_type) {
5087 case GOT_OBJ_TYPE_BLOB:
5088 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5089 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5090 s->label1, s->label2, tog_diff_algo, s->diff_context,
5091 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5092 s->f);
5093 break;
5094 case GOT_OBJ_TYPE_TREE:
5095 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5096 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5097 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5098 s->force_text_diff, NULL, s->repo, s->f);
5099 break;
5100 case GOT_OBJ_TYPE_COMMIT: {
5101 const struct got_object_id_queue *parent_ids;
5102 struct got_object_qid *pid;
5103 struct got_commit_object *commit2;
5104 struct got_reflist_head *refs;
5105 size_t nlines = 0;
5106 struct got_diffstat_cb_arg dsa = {
5107 0, 0, 0, 0, 0, 0,
5108 &changed_paths,
5109 s->ignore_whitespace,
5110 s->force_text_diff,
5111 tog_diff_algo
5114 lines = malloc(sizeof(*lines));
5115 if (lines == NULL) {
5116 err = got_error_from_errno("malloc");
5117 goto done;
5120 /* build diff first in tmp file then append to commit info */
5121 err = got_diff_objects_as_commits(&lines, &nlines,
5122 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5123 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5124 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5125 if (err)
5126 break;
5128 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5129 if (err)
5130 goto done;
5131 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5132 /* Show commit info if we're diffing to a parent/root commit. */
5133 if (s->id1 == NULL) {
5134 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5135 refs, s->repo, s->ignore_whitespace,
5136 s->force_text_diff, &dsa, s->f);
5137 if (err)
5138 goto done;
5139 } else {
5140 parent_ids = got_object_commit_get_parent_ids(commit2);
5141 STAILQ_FOREACH(pid, parent_ids, entry) {
5142 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5143 err = write_commit_info(&s->lines,
5144 &s->nlines, s->id2, refs, s->repo,
5145 s->ignore_whitespace,
5146 s->force_text_diff, &dsa, s->f);
5147 if (err)
5148 goto done;
5149 break;
5153 got_object_commit_close(commit2);
5155 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5156 lines, nlines);
5157 break;
5159 default:
5160 err = got_error(GOT_ERR_OBJ_TYPE);
5161 break;
5163 done:
5164 free(lines);
5165 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5166 if (s->f && fflush(s->f) != 0 && err == NULL)
5167 err = got_error_from_errno("fflush");
5168 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5169 err = got_error_from_errno("fclose");
5170 return err;
5173 static void
5174 diff_view_indicate_progress(struct tog_view *view)
5176 mvwaddstr(view->window, 0, 0, "diffing...");
5177 update_panels();
5178 doupdate();
5181 static const struct got_error *
5182 search_start_diff_view(struct tog_view *view)
5184 struct tog_diff_view_state *s = &view->state.diff;
5186 s->matched_line = 0;
5187 return NULL;
5190 static void
5191 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5192 size_t *nlines, int **first, int **last, int **match, int **selected)
5194 struct tog_diff_view_state *s = &view->state.diff;
5196 *f = s->f;
5197 *nlines = s->nlines;
5198 *line_offsets = NULL;
5199 *match = &s->matched_line;
5200 *first = &s->first_displayed_line;
5201 *last = &s->last_displayed_line;
5202 *selected = &s->selected_line;
5205 static const struct got_error *
5206 search_next_view_match(struct tog_view *view)
5208 const struct got_error *err = NULL;
5209 FILE *f;
5210 int lineno;
5211 char *line = NULL;
5212 size_t linesize = 0;
5213 ssize_t linelen;
5214 off_t *line_offsets;
5215 size_t nlines = 0;
5216 int *first, *last, *match, *selected;
5218 if (!view->search_setup)
5219 return got_error_msg(GOT_ERR_NOT_IMPL,
5220 "view search not supported");
5221 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5222 &match, &selected);
5224 if (!view->searching) {
5225 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5226 return NULL;
5229 if (*match) {
5230 if (view->searching == TOG_SEARCH_FORWARD)
5231 lineno = *first + 1;
5232 else
5233 lineno = *first - 1;
5234 } else
5235 lineno = *first - 1 + *selected;
5237 while (1) {
5238 off_t offset;
5240 if (lineno <= 0 || lineno > nlines) {
5241 if (*match == 0) {
5242 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5243 break;
5246 if (view->searching == TOG_SEARCH_FORWARD)
5247 lineno = 1;
5248 else
5249 lineno = nlines;
5252 offset = view->type == TOG_VIEW_DIFF ?
5253 view->state.diff.lines[lineno - 1].offset :
5254 line_offsets[lineno - 1];
5255 if (fseeko(f, offset, SEEK_SET) != 0) {
5256 free(line);
5257 return got_error_from_errno("fseeko");
5259 linelen = getline(&line, &linesize, f);
5260 if (linelen != -1) {
5261 char *exstr;
5262 err = expand_tab(&exstr, line);
5263 if (err)
5264 break;
5265 if (match_line(exstr, &view->regex, 1,
5266 &view->regmatch)) {
5267 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5268 *match = lineno;
5269 free(exstr);
5270 break;
5272 free(exstr);
5274 if (view->searching == TOG_SEARCH_FORWARD)
5275 lineno++;
5276 else
5277 lineno--;
5279 free(line);
5281 if (*match) {
5282 *first = *match;
5283 *selected = 1;
5286 return err;
5289 static const struct got_error *
5290 close_diff_view(struct tog_view *view)
5292 const struct got_error *err = NULL;
5293 struct tog_diff_view_state *s = &view->state.diff;
5295 free(s->id1);
5296 s->id1 = NULL;
5297 free(s->id2);
5298 s->id2 = NULL;
5299 if (s->f && fclose(s->f) == EOF)
5300 err = got_error_from_errno("fclose");
5301 s->f = NULL;
5302 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5303 err = got_error_from_errno("fclose");
5304 s->f1 = NULL;
5305 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5306 err = got_error_from_errno("fclose");
5307 s->f2 = NULL;
5308 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5309 err = got_error_from_errno("close");
5310 s->fd1 = -1;
5311 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5312 err = got_error_from_errno("close");
5313 s->fd2 = -1;
5314 free(s->lines);
5315 s->lines = NULL;
5316 s->nlines = 0;
5317 return err;
5320 static const struct got_error *
5321 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5322 struct got_object_id *id2, const char *label1, const char *label2,
5323 int diff_context, int ignore_whitespace, int force_text_diff,
5324 struct tog_view *parent_view, struct got_repository *repo)
5326 const struct got_error *err;
5327 struct tog_diff_view_state *s = &view->state.diff;
5329 memset(s, 0, sizeof(*s));
5330 s->fd1 = -1;
5331 s->fd2 = -1;
5333 if (id1 != NULL && id2 != NULL) {
5334 int type1, type2;
5336 err = got_object_get_type(&type1, repo, id1);
5337 if (err)
5338 goto done;
5339 err = got_object_get_type(&type2, repo, id2);
5340 if (err)
5341 goto done;
5343 if (type1 != type2) {
5344 err = got_error(GOT_ERR_OBJ_TYPE);
5345 goto done;
5348 s->first_displayed_line = 1;
5349 s->last_displayed_line = view->nlines;
5350 s->selected_line = 1;
5351 s->repo = repo;
5352 s->id1 = id1;
5353 s->id2 = id2;
5354 s->label1 = label1;
5355 s->label2 = label2;
5357 if (id1) {
5358 s->id1 = got_object_id_dup(id1);
5359 if (s->id1 == NULL) {
5360 err = got_error_from_errno("got_object_id_dup");
5361 goto done;
5363 } else
5364 s->id1 = NULL;
5366 s->id2 = got_object_id_dup(id2);
5367 if (s->id2 == NULL) {
5368 err = got_error_from_errno("got_object_id_dup");
5369 goto done;
5372 s->f1 = got_opentemp();
5373 if (s->f1 == NULL) {
5374 err = got_error_from_errno("got_opentemp");
5375 goto done;
5378 s->f2 = got_opentemp();
5379 if (s->f2 == NULL) {
5380 err = got_error_from_errno("got_opentemp");
5381 goto done;
5384 s->fd1 = got_opentempfd();
5385 if (s->fd1 == -1) {
5386 err = got_error_from_errno("got_opentempfd");
5387 goto done;
5390 s->fd2 = got_opentempfd();
5391 if (s->fd2 == -1) {
5392 err = got_error_from_errno("got_opentempfd");
5393 goto done;
5396 s->diff_context = diff_context;
5397 s->ignore_whitespace = ignore_whitespace;
5398 s->force_text_diff = force_text_diff;
5399 s->parent_view = parent_view;
5400 s->repo = repo;
5402 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5403 int rc;
5405 rc = init_pair(GOT_DIFF_LINE_MINUS,
5406 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5407 if (rc != ERR)
5408 rc = init_pair(GOT_DIFF_LINE_PLUS,
5409 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5410 if (rc != ERR)
5411 rc = init_pair(GOT_DIFF_LINE_HUNK,
5412 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5413 if (rc != ERR)
5414 rc = init_pair(GOT_DIFF_LINE_META,
5415 get_color_value("TOG_COLOR_DIFF_META"), -1);
5416 if (rc != ERR)
5417 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5418 get_color_value("TOG_COLOR_DIFF_META"), -1);
5419 if (rc != ERR)
5420 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5421 get_color_value("TOG_COLOR_DIFF_META"), -1);
5422 if (rc != ERR)
5423 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5424 get_color_value("TOG_COLOR_DIFF_META"), -1);
5425 if (rc != ERR)
5426 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5427 get_color_value("TOG_COLOR_AUTHOR"), -1);
5428 if (rc != ERR)
5429 rc = init_pair(GOT_DIFF_LINE_DATE,
5430 get_color_value("TOG_COLOR_DATE"), -1);
5431 if (rc == ERR) {
5432 err = got_error(GOT_ERR_RANGE);
5433 goto done;
5437 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5438 view_is_splitscreen(view))
5439 show_log_view(parent_view); /* draw border */
5440 diff_view_indicate_progress(view);
5442 err = create_diff(s);
5444 view->show = show_diff_view;
5445 view->input = input_diff_view;
5446 view->reset = reset_diff_view;
5447 view->close = close_diff_view;
5448 view->search_start = search_start_diff_view;
5449 view->search_setup = search_setup_diff_view;
5450 view->search_next = search_next_view_match;
5451 done:
5452 if (err) {
5453 if (view->close == NULL)
5454 close_diff_view(view);
5455 view_close(view);
5457 return err;
5460 static const struct got_error *
5461 show_diff_view(struct tog_view *view)
5463 const struct got_error *err;
5464 struct tog_diff_view_state *s = &view->state.diff;
5465 char *id_str1 = NULL, *id_str2, *header;
5466 const char *label1, *label2;
5468 if (s->id1) {
5469 err = got_object_id_str(&id_str1, s->id1);
5470 if (err)
5471 return err;
5472 label1 = s->label1 ? s->label1 : id_str1;
5473 } else
5474 label1 = "/dev/null";
5476 err = got_object_id_str(&id_str2, s->id2);
5477 if (err)
5478 return err;
5479 label2 = s->label2 ? s->label2 : id_str2;
5481 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5482 err = got_error_from_errno("asprintf");
5483 free(id_str1);
5484 free(id_str2);
5485 return err;
5487 free(id_str1);
5488 free(id_str2);
5490 err = draw_file(view, header);
5491 free(header);
5492 return err;
5495 static const struct got_error *
5496 set_selected_commit(struct tog_diff_view_state *s,
5497 struct commit_queue_entry *entry)
5499 const struct got_error *err;
5500 const struct got_object_id_queue *parent_ids;
5501 struct got_commit_object *selected_commit;
5502 struct got_object_qid *pid;
5504 free(s->id2);
5505 s->id2 = got_object_id_dup(entry->id);
5506 if (s->id2 == NULL)
5507 return got_error_from_errno("got_object_id_dup");
5509 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5510 if (err)
5511 return err;
5512 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5513 free(s->id1);
5514 pid = STAILQ_FIRST(parent_ids);
5515 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5516 got_object_commit_close(selected_commit);
5517 return NULL;
5520 static const struct got_error *
5521 reset_diff_view(struct tog_view *view)
5523 struct tog_diff_view_state *s = &view->state.diff;
5525 view->count = 0;
5526 wclear(view->window);
5527 s->first_displayed_line = 1;
5528 s->last_displayed_line = view->nlines;
5529 s->matched_line = 0;
5530 diff_view_indicate_progress(view);
5531 return create_diff(s);
5534 static void
5535 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5537 int start, i;
5539 i = start = s->first_displayed_line - 1;
5541 while (s->lines[i].type != type) {
5542 if (i == 0)
5543 i = s->nlines - 1;
5544 if (--i == start)
5545 return; /* do nothing, requested type not in file */
5548 s->selected_line = 1;
5549 s->first_displayed_line = i;
5552 static void
5553 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5555 int start, i;
5557 i = start = s->first_displayed_line + 1;
5559 while (s->lines[i].type != type) {
5560 if (i == s->nlines - 1)
5561 i = 0;
5562 if (++i == start)
5563 return; /* do nothing, requested type not in file */
5566 s->selected_line = 1;
5567 s->first_displayed_line = i;
5570 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5571 int, int, int);
5572 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5573 int, int);
5575 static const struct got_error *
5576 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5578 const struct got_error *err = NULL;
5579 struct tog_diff_view_state *s = &view->state.diff;
5580 struct tog_log_view_state *ls;
5581 struct commit_queue_entry *old_selected_entry;
5582 char *line = NULL;
5583 size_t linesize = 0;
5584 ssize_t linelen;
5585 int i, nscroll = view->nlines - 1, up = 0;
5587 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5589 switch (ch) {
5590 case '0':
5591 case '$':
5592 case KEY_RIGHT:
5593 case 'l':
5594 case KEY_LEFT:
5595 case 'h':
5596 horizontal_scroll_input(view, ch);
5597 break;
5598 case 'a':
5599 case 'w':
5600 if (ch == 'a') {
5601 s->force_text_diff = !s->force_text_diff;
5602 view->action = s->force_text_diff ?
5603 "force ASCII text enabled" :
5604 "force ASCII text disabled";
5606 else if (ch == 'w') {
5607 s->ignore_whitespace = !s->ignore_whitespace;
5608 view->action = s->ignore_whitespace ?
5609 "ignore whitespace enabled" :
5610 "ignore whitespace disabled";
5612 err = reset_diff_view(view);
5613 break;
5614 case 'g':
5615 case KEY_HOME:
5616 s->first_displayed_line = 1;
5617 view->count = 0;
5618 break;
5619 case 'G':
5620 case KEY_END:
5621 view->count = 0;
5622 if (s->eof)
5623 break;
5625 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5626 s->eof = 1;
5627 break;
5628 case 'k':
5629 case KEY_UP:
5630 case CTRL('p'):
5631 if (s->first_displayed_line > 1)
5632 s->first_displayed_line--;
5633 else
5634 view->count = 0;
5635 break;
5636 case CTRL('u'):
5637 case 'u':
5638 nscroll /= 2;
5639 /* FALL THROUGH */
5640 case KEY_PPAGE:
5641 case CTRL('b'):
5642 case 'b':
5643 if (s->first_displayed_line == 1) {
5644 view->count = 0;
5645 break;
5647 i = 0;
5648 while (i++ < nscroll && s->first_displayed_line > 1)
5649 s->first_displayed_line--;
5650 break;
5651 case 'j':
5652 case KEY_DOWN:
5653 case CTRL('n'):
5654 if (!s->eof)
5655 s->first_displayed_line++;
5656 else
5657 view->count = 0;
5658 break;
5659 case CTRL('d'):
5660 case 'd':
5661 nscroll /= 2;
5662 /* FALL THROUGH */
5663 case KEY_NPAGE:
5664 case CTRL('f'):
5665 case 'f':
5666 case ' ':
5667 if (s->eof) {
5668 view->count = 0;
5669 break;
5671 i = 0;
5672 while (!s->eof && i++ < nscroll) {
5673 linelen = getline(&line, &linesize, s->f);
5674 s->first_displayed_line++;
5675 if (linelen == -1) {
5676 if (feof(s->f)) {
5677 s->eof = 1;
5678 } else
5679 err = got_ferror(s->f, GOT_ERR_IO);
5680 break;
5683 free(line);
5684 break;
5685 case '(':
5686 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5687 break;
5688 case ')':
5689 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5690 break;
5691 case '{':
5692 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5693 break;
5694 case '}':
5695 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5696 break;
5697 case '[':
5698 if (s->diff_context > 0) {
5699 s->diff_context--;
5700 s->matched_line = 0;
5701 diff_view_indicate_progress(view);
5702 err = create_diff(s);
5703 if (s->first_displayed_line + view->nlines - 1 >
5704 s->nlines) {
5705 s->first_displayed_line = 1;
5706 s->last_displayed_line = view->nlines;
5708 } else
5709 view->count = 0;
5710 break;
5711 case ']':
5712 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5713 s->diff_context++;
5714 s->matched_line = 0;
5715 diff_view_indicate_progress(view);
5716 err = create_diff(s);
5717 } else
5718 view->count = 0;
5719 break;
5720 case '<':
5721 case ',':
5722 case 'K':
5723 up = 1;
5724 /* FALL THROUGH */
5725 case '>':
5726 case '.':
5727 case 'J':
5728 if (s->parent_view == NULL) {
5729 view->count = 0;
5730 break;
5732 s->parent_view->count = view->count;
5734 if (s->parent_view->type == TOG_VIEW_LOG) {
5735 ls = &s->parent_view->state.log;
5736 old_selected_entry = ls->selected_entry;
5738 err = input_log_view(NULL, s->parent_view,
5739 up ? KEY_UP : KEY_DOWN);
5740 if (err)
5741 break;
5742 view->count = s->parent_view->count;
5744 if (old_selected_entry == ls->selected_entry)
5745 break;
5747 err = set_selected_commit(s, ls->selected_entry);
5748 if (err)
5749 break;
5750 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5751 struct tog_blame_view_state *bs;
5752 struct got_object_id *id, *prev_id;
5754 bs = &s->parent_view->state.blame;
5755 prev_id = get_annotation_for_line(bs->blame.lines,
5756 bs->blame.nlines, bs->last_diffed_line);
5758 err = input_blame_view(&view, s->parent_view,
5759 up ? KEY_UP : KEY_DOWN);
5760 if (err)
5761 break;
5762 view->count = s->parent_view->count;
5764 if (prev_id == NULL)
5765 break;
5766 id = get_selected_commit_id(bs->blame.lines,
5767 bs->blame.nlines, bs->first_displayed_line,
5768 bs->selected_line);
5769 if (id == NULL)
5770 break;
5772 if (!got_object_id_cmp(prev_id, id))
5773 break;
5775 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5776 if (err)
5777 break;
5779 s->first_displayed_line = 1;
5780 s->last_displayed_line = view->nlines;
5781 s->matched_line = 0;
5782 view->x = 0;
5784 diff_view_indicate_progress(view);
5785 err = create_diff(s);
5786 break;
5787 default:
5788 view->count = 0;
5789 break;
5792 return err;
5795 static const struct got_error *
5796 cmd_diff(int argc, char *argv[])
5798 const struct got_error *error;
5799 struct got_repository *repo = NULL;
5800 struct got_worktree *worktree = NULL;
5801 struct got_object_id *id1 = NULL, *id2 = NULL;
5802 char *repo_path = NULL, *cwd = NULL;
5803 char *id_str1 = NULL, *id_str2 = NULL;
5804 char *label1 = NULL, *label2 = NULL;
5805 int diff_context = 3, ignore_whitespace = 0;
5806 int ch, force_text_diff = 0;
5807 const char *errstr;
5808 struct tog_view *view;
5809 int *pack_fds = NULL;
5811 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5812 switch (ch) {
5813 case 'a':
5814 force_text_diff = 1;
5815 break;
5816 case 'C':
5817 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5818 &errstr);
5819 if (errstr != NULL)
5820 errx(1, "number of context lines is %s: %s",
5821 errstr, errstr);
5822 break;
5823 case 'r':
5824 repo_path = realpath(optarg, NULL);
5825 if (repo_path == NULL)
5826 return got_error_from_errno2("realpath",
5827 optarg);
5828 got_path_strip_trailing_slashes(repo_path);
5829 break;
5830 case 'w':
5831 ignore_whitespace = 1;
5832 break;
5833 default:
5834 usage_diff();
5835 /* NOTREACHED */
5839 argc -= optind;
5840 argv += optind;
5842 if (argc == 0) {
5843 usage_diff(); /* TODO show local worktree changes */
5844 } else if (argc == 2) {
5845 id_str1 = argv[0];
5846 id_str2 = argv[1];
5847 } else
5848 usage_diff();
5850 error = got_repo_pack_fds_open(&pack_fds);
5851 if (error)
5852 goto done;
5854 if (repo_path == NULL) {
5855 cwd = getcwd(NULL, 0);
5856 if (cwd == NULL)
5857 return got_error_from_errno("getcwd");
5858 error = got_worktree_open(&worktree, cwd);
5859 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5860 goto done;
5861 if (worktree)
5862 repo_path =
5863 strdup(got_worktree_get_repo_path(worktree));
5864 else
5865 repo_path = strdup(cwd);
5866 if (repo_path == NULL) {
5867 error = got_error_from_errno("strdup");
5868 goto done;
5872 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5873 if (error)
5874 goto done;
5876 init_curses();
5878 error = apply_unveil(got_repo_get_path(repo), NULL);
5879 if (error)
5880 goto done;
5882 error = tog_load_refs(repo, 0);
5883 if (error)
5884 goto done;
5886 error = got_repo_match_object_id(&id1, &label1, id_str1,
5887 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5888 if (error)
5889 goto done;
5891 error = got_repo_match_object_id(&id2, &label2, id_str2,
5892 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5893 if (error)
5894 goto done;
5896 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5897 if (view == NULL) {
5898 error = got_error_from_errno("view_open");
5899 goto done;
5901 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5902 ignore_whitespace, force_text_diff, NULL, repo);
5903 if (error)
5904 goto done;
5905 error = view_loop(view);
5906 done:
5907 free(label1);
5908 free(label2);
5909 free(repo_path);
5910 free(cwd);
5911 if (repo) {
5912 const struct got_error *close_err = got_repo_close(repo);
5913 if (error == NULL)
5914 error = close_err;
5916 if (worktree)
5917 got_worktree_close(worktree);
5918 if (pack_fds) {
5919 const struct got_error *pack_err =
5920 got_repo_pack_fds_close(pack_fds);
5921 if (error == NULL)
5922 error = pack_err;
5924 tog_free_refs();
5925 return error;
5928 __dead static void
5929 usage_blame(void)
5931 endwin();
5932 fprintf(stderr,
5933 "usage: %s blame [-c commit] [-r repository-path] path\n",
5934 getprogname());
5935 exit(1);
5938 struct tog_blame_line {
5939 int annotated;
5940 struct got_object_id *id;
5943 static const struct got_error *
5944 draw_blame(struct tog_view *view)
5946 struct tog_blame_view_state *s = &view->state.blame;
5947 struct tog_blame *blame = &s->blame;
5948 regmatch_t *regmatch = &view->regmatch;
5949 const struct got_error *err;
5950 int lineno = 0, nprinted = 0;
5951 char *line = NULL;
5952 size_t linesize = 0;
5953 ssize_t linelen;
5954 wchar_t *wline;
5955 int width;
5956 struct tog_blame_line *blame_line;
5957 struct got_object_id *prev_id = NULL;
5958 char *id_str;
5959 struct tog_color *tc;
5961 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5962 if (err)
5963 return err;
5965 rewind(blame->f);
5966 werase(view->window);
5968 if (asprintf(&line, "commit %s", id_str) == -1) {
5969 err = got_error_from_errno("asprintf");
5970 free(id_str);
5971 return err;
5974 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5975 free(line);
5976 line = NULL;
5977 if (err)
5978 return err;
5979 if (view_needs_focus_indication(view))
5980 wstandout(view->window);
5981 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5982 if (tc)
5983 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5984 waddwstr(view->window, wline);
5985 while (width++ < view->ncols)
5986 waddch(view->window, ' ');
5987 if (tc)
5988 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5989 if (view_needs_focus_indication(view))
5990 wstandend(view->window);
5991 free(wline);
5992 wline = NULL;
5994 if (view->gline > blame->nlines)
5995 view->gline = blame->nlines;
5997 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5998 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5999 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6000 free(id_str);
6001 return got_error_from_errno("asprintf");
6003 free(id_str);
6004 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6005 free(line);
6006 line = NULL;
6007 if (err)
6008 return err;
6009 waddwstr(view->window, wline);
6010 free(wline);
6011 wline = NULL;
6012 if (width < view->ncols - 1)
6013 waddch(view->window, '\n');
6015 s->eof = 0;
6016 view->maxx = 0;
6017 while (nprinted < view->nlines - 2) {
6018 linelen = getline(&line, &linesize, blame->f);
6019 if (linelen == -1) {
6020 if (feof(blame->f)) {
6021 s->eof = 1;
6022 break;
6024 free(line);
6025 return got_ferror(blame->f, GOT_ERR_IO);
6027 if (++lineno < s->first_displayed_line)
6028 continue;
6029 if (view->gline && !gotoline(view, &lineno, &nprinted))
6030 continue;
6032 /* Set view->maxx based on full line length. */
6033 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6034 if (err) {
6035 free(line);
6036 return err;
6038 free(wline);
6039 wline = NULL;
6040 view->maxx = MAX(view->maxx, width);
6042 if (nprinted == s->selected_line - 1)
6043 wstandout(view->window);
6045 if (blame->nlines > 0) {
6046 blame_line = &blame->lines[lineno - 1];
6047 if (blame_line->annotated && prev_id &&
6048 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6049 !(nprinted == s->selected_line - 1)) {
6050 waddstr(view->window, " ");
6051 } else if (blame_line->annotated) {
6052 char *id_str;
6053 err = got_object_id_str(&id_str,
6054 blame_line->id);
6055 if (err) {
6056 free(line);
6057 return err;
6059 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6060 if (tc)
6061 wattr_on(view->window,
6062 COLOR_PAIR(tc->colorpair), NULL);
6063 wprintw(view->window, "%.8s", id_str);
6064 if (tc)
6065 wattr_off(view->window,
6066 COLOR_PAIR(tc->colorpair), NULL);
6067 free(id_str);
6068 prev_id = blame_line->id;
6069 } else {
6070 waddstr(view->window, "........");
6071 prev_id = NULL;
6073 } else {
6074 waddstr(view->window, "........");
6075 prev_id = NULL;
6078 if (nprinted == s->selected_line - 1)
6079 wstandend(view->window);
6080 waddstr(view->window, " ");
6082 if (view->ncols <= 9) {
6083 width = 9;
6084 } else if (s->first_displayed_line + nprinted ==
6085 s->matched_line &&
6086 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6087 err = add_matched_line(&width, line, view->ncols - 9, 9,
6088 view->window, view->x, regmatch);
6089 if (err) {
6090 free(line);
6091 return err;
6093 width += 9;
6094 } else {
6095 int skip;
6096 err = format_line(&wline, &width, &skip, line,
6097 view->x, view->ncols - 9, 9, 1);
6098 if (err) {
6099 free(line);
6100 return err;
6102 waddwstr(view->window, &wline[skip]);
6103 width += 9;
6104 free(wline);
6105 wline = NULL;
6108 if (width <= view->ncols - 1)
6109 waddch(view->window, '\n');
6110 if (++nprinted == 1)
6111 s->first_displayed_line = lineno;
6113 free(line);
6114 s->last_displayed_line = lineno;
6116 view_border(view);
6118 return NULL;
6121 static const struct got_error *
6122 blame_cb(void *arg, int nlines, int lineno,
6123 struct got_commit_object *commit, struct got_object_id *id)
6125 const struct got_error *err = NULL;
6126 struct tog_blame_cb_args *a = arg;
6127 struct tog_blame_line *line;
6128 int errcode;
6130 if (nlines != a->nlines ||
6131 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6132 return got_error(GOT_ERR_RANGE);
6134 errcode = pthread_mutex_lock(&tog_mutex);
6135 if (errcode)
6136 return got_error_set_errno(errcode, "pthread_mutex_lock");
6138 if (*a->quit) { /* user has quit the blame view */
6139 err = got_error(GOT_ERR_ITER_COMPLETED);
6140 goto done;
6143 if (lineno == -1)
6144 goto done; /* no change in this commit */
6146 line = &a->lines[lineno - 1];
6147 if (line->annotated)
6148 goto done;
6150 line->id = got_object_id_dup(id);
6151 if (line->id == NULL) {
6152 err = got_error_from_errno("got_object_id_dup");
6153 goto done;
6155 line->annotated = 1;
6156 done:
6157 errcode = pthread_mutex_unlock(&tog_mutex);
6158 if (errcode)
6159 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6160 return err;
6163 static void *
6164 blame_thread(void *arg)
6166 const struct got_error *err, *close_err;
6167 struct tog_blame_thread_args *ta = arg;
6168 struct tog_blame_cb_args *a = ta->cb_args;
6169 int errcode, fd1 = -1, fd2 = -1;
6170 FILE *f1 = NULL, *f2 = NULL;
6172 fd1 = got_opentempfd();
6173 if (fd1 == -1)
6174 return (void *)got_error_from_errno("got_opentempfd");
6176 fd2 = got_opentempfd();
6177 if (fd2 == -1) {
6178 err = got_error_from_errno("got_opentempfd");
6179 goto done;
6182 f1 = got_opentemp();
6183 if (f1 == NULL) {
6184 err = (void *)got_error_from_errno("got_opentemp");
6185 goto done;
6187 f2 = got_opentemp();
6188 if (f2 == NULL) {
6189 err = (void *)got_error_from_errno("got_opentemp");
6190 goto done;
6193 err = block_signals_used_by_main_thread();
6194 if (err)
6195 goto done;
6197 err = got_blame(ta->path, a->commit_id, ta->repo,
6198 tog_diff_algo, blame_cb, ta->cb_args,
6199 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6200 if (err && err->code == GOT_ERR_CANCELLED)
6201 err = NULL;
6203 errcode = pthread_mutex_lock(&tog_mutex);
6204 if (errcode) {
6205 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6206 goto done;
6209 close_err = got_repo_close(ta->repo);
6210 if (err == NULL)
6211 err = close_err;
6212 ta->repo = NULL;
6213 *ta->complete = 1;
6215 errcode = pthread_mutex_unlock(&tog_mutex);
6216 if (errcode && err == NULL)
6217 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6219 done:
6220 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6221 err = got_error_from_errno("close");
6222 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6223 err = got_error_from_errno("close");
6224 if (f1 && fclose(f1) == EOF && err == NULL)
6225 err = got_error_from_errno("fclose");
6226 if (f2 && fclose(f2) == EOF && err == NULL)
6227 err = got_error_from_errno("fclose");
6229 return (void *)err;
6232 static struct got_object_id *
6233 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6234 int first_displayed_line, int selected_line)
6236 struct tog_blame_line *line;
6238 if (nlines <= 0)
6239 return NULL;
6241 line = &lines[first_displayed_line - 1 + selected_line - 1];
6242 if (!line->annotated)
6243 return NULL;
6245 return line->id;
6248 static struct got_object_id *
6249 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6250 int lineno)
6252 struct tog_blame_line *line;
6254 if (nlines <= 0 || lineno >= nlines)
6255 return NULL;
6257 line = &lines[lineno - 1];
6258 if (!line->annotated)
6259 return NULL;
6261 return line->id;
6264 static const struct got_error *
6265 stop_blame(struct tog_blame *blame)
6267 const struct got_error *err = NULL;
6268 int i;
6270 if (blame->thread) {
6271 int errcode;
6272 errcode = pthread_mutex_unlock(&tog_mutex);
6273 if (errcode)
6274 return got_error_set_errno(errcode,
6275 "pthread_mutex_unlock");
6276 errcode = pthread_join(blame->thread, (void **)&err);
6277 if (errcode)
6278 return got_error_set_errno(errcode, "pthread_join");
6279 errcode = pthread_mutex_lock(&tog_mutex);
6280 if (errcode)
6281 return got_error_set_errno(errcode,
6282 "pthread_mutex_lock");
6283 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6284 err = NULL;
6285 blame->thread = 0; //NULL;
6287 if (blame->thread_args.repo) {
6288 const struct got_error *close_err;
6289 close_err = got_repo_close(blame->thread_args.repo);
6290 if (err == NULL)
6291 err = close_err;
6292 blame->thread_args.repo = NULL;
6294 if (blame->f) {
6295 if (fclose(blame->f) == EOF && err == NULL)
6296 err = got_error_from_errno("fclose");
6297 blame->f = NULL;
6299 if (blame->lines) {
6300 for (i = 0; i < blame->nlines; i++)
6301 free(blame->lines[i].id);
6302 free(blame->lines);
6303 blame->lines = NULL;
6305 free(blame->cb_args.commit_id);
6306 blame->cb_args.commit_id = NULL;
6307 if (blame->pack_fds) {
6308 const struct got_error *pack_err =
6309 got_repo_pack_fds_close(blame->pack_fds);
6310 if (err == NULL)
6311 err = pack_err;
6312 blame->pack_fds = NULL;
6314 return err;
6317 static const struct got_error *
6318 cancel_blame_view(void *arg)
6320 const struct got_error *err = NULL;
6321 int *done = arg;
6322 int errcode;
6324 errcode = pthread_mutex_lock(&tog_mutex);
6325 if (errcode)
6326 return got_error_set_errno(errcode,
6327 "pthread_mutex_unlock");
6329 if (*done)
6330 err = got_error(GOT_ERR_CANCELLED);
6332 errcode = pthread_mutex_unlock(&tog_mutex);
6333 if (errcode)
6334 return got_error_set_errno(errcode,
6335 "pthread_mutex_lock");
6337 return err;
6340 static const struct got_error *
6341 run_blame(struct tog_view *view)
6343 struct tog_blame_view_state *s = &view->state.blame;
6344 struct tog_blame *blame = &s->blame;
6345 const struct got_error *err = NULL;
6346 struct got_commit_object *commit = NULL;
6347 struct got_blob_object *blob = NULL;
6348 struct got_repository *thread_repo = NULL;
6349 struct got_object_id *obj_id = NULL;
6350 int obj_type, fd = -1;
6351 int *pack_fds = NULL;
6353 err = got_object_open_as_commit(&commit, s->repo,
6354 &s->blamed_commit->id);
6355 if (err)
6356 return err;
6358 fd = got_opentempfd();
6359 if (fd == -1) {
6360 err = got_error_from_errno("got_opentempfd");
6361 goto done;
6364 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6365 if (err)
6366 goto done;
6368 err = got_object_get_type(&obj_type, s->repo, obj_id);
6369 if (err)
6370 goto done;
6372 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6373 err = got_error(GOT_ERR_OBJ_TYPE);
6374 goto done;
6377 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6378 if (err)
6379 goto done;
6380 blame->f = got_opentemp();
6381 if (blame->f == NULL) {
6382 err = got_error_from_errno("got_opentemp");
6383 goto done;
6385 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6386 &blame->line_offsets, blame->f, blob);
6387 if (err)
6388 goto done;
6389 if (blame->nlines == 0) {
6390 s->blame_complete = 1;
6391 goto done;
6394 /* Don't include \n at EOF in the blame line count. */
6395 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6396 blame->nlines--;
6398 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6399 if (blame->lines == NULL) {
6400 err = got_error_from_errno("calloc");
6401 goto done;
6404 err = got_repo_pack_fds_open(&pack_fds);
6405 if (err)
6406 goto done;
6407 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6408 pack_fds);
6409 if (err)
6410 goto done;
6412 blame->pack_fds = pack_fds;
6413 blame->cb_args.view = view;
6414 blame->cb_args.lines = blame->lines;
6415 blame->cb_args.nlines = blame->nlines;
6416 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6417 if (blame->cb_args.commit_id == NULL) {
6418 err = got_error_from_errno("got_object_id_dup");
6419 goto done;
6421 blame->cb_args.quit = &s->done;
6423 blame->thread_args.path = s->path;
6424 blame->thread_args.repo = thread_repo;
6425 blame->thread_args.cb_args = &blame->cb_args;
6426 blame->thread_args.complete = &s->blame_complete;
6427 blame->thread_args.cancel_cb = cancel_blame_view;
6428 blame->thread_args.cancel_arg = &s->done;
6429 s->blame_complete = 0;
6431 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6432 s->first_displayed_line = 1;
6433 s->last_displayed_line = view->nlines;
6434 s->selected_line = 1;
6436 s->matched_line = 0;
6438 done:
6439 if (commit)
6440 got_object_commit_close(commit);
6441 if (fd != -1 && close(fd) == -1 && err == NULL)
6442 err = got_error_from_errno("close");
6443 if (blob)
6444 got_object_blob_close(blob);
6445 free(obj_id);
6446 if (err)
6447 stop_blame(blame);
6448 return err;
6451 static const struct got_error *
6452 open_blame_view(struct tog_view *view, char *path,
6453 struct got_object_id *commit_id, struct got_repository *repo)
6455 const struct got_error *err = NULL;
6456 struct tog_blame_view_state *s = &view->state.blame;
6458 STAILQ_INIT(&s->blamed_commits);
6460 s->path = strdup(path);
6461 if (s->path == NULL)
6462 return got_error_from_errno("strdup");
6464 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6465 if (err) {
6466 free(s->path);
6467 return err;
6470 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6471 s->first_displayed_line = 1;
6472 s->last_displayed_line = view->nlines;
6473 s->selected_line = 1;
6474 s->blame_complete = 0;
6475 s->repo = repo;
6476 s->commit_id = commit_id;
6477 memset(&s->blame, 0, sizeof(s->blame));
6479 STAILQ_INIT(&s->colors);
6480 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6481 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6482 get_color_value("TOG_COLOR_COMMIT"));
6483 if (err)
6484 return err;
6487 view->show = show_blame_view;
6488 view->input = input_blame_view;
6489 view->reset = reset_blame_view;
6490 view->close = close_blame_view;
6491 view->search_start = search_start_blame_view;
6492 view->search_setup = search_setup_blame_view;
6493 view->search_next = search_next_view_match;
6495 return run_blame(view);
6498 static const struct got_error *
6499 close_blame_view(struct tog_view *view)
6501 const struct got_error *err = NULL;
6502 struct tog_blame_view_state *s = &view->state.blame;
6504 if (s->blame.thread)
6505 err = stop_blame(&s->blame);
6507 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6508 struct got_object_qid *blamed_commit;
6509 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6510 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6511 got_object_qid_free(blamed_commit);
6514 free(s->path);
6515 free_colors(&s->colors);
6516 return err;
6519 static const struct got_error *
6520 search_start_blame_view(struct tog_view *view)
6522 struct tog_blame_view_state *s = &view->state.blame;
6524 s->matched_line = 0;
6525 return NULL;
6528 static void
6529 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6530 size_t *nlines, int **first, int **last, int **match, int **selected)
6532 struct tog_blame_view_state *s = &view->state.blame;
6534 *f = s->blame.f;
6535 *nlines = s->blame.nlines;
6536 *line_offsets = s->blame.line_offsets;
6537 *match = &s->matched_line;
6538 *first = &s->first_displayed_line;
6539 *last = &s->last_displayed_line;
6540 *selected = &s->selected_line;
6543 static const struct got_error *
6544 show_blame_view(struct tog_view *view)
6546 const struct got_error *err = NULL;
6547 struct tog_blame_view_state *s = &view->state.blame;
6548 int errcode;
6550 if (s->blame.thread == 0 && !s->blame_complete) {
6551 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6552 &s->blame.thread_args);
6553 if (errcode)
6554 return got_error_set_errno(errcode, "pthread_create");
6556 if (!using_mock_io)
6557 halfdelay(1); /* fast refresh while annotating */
6560 if (s->blame_complete && !using_mock_io)
6561 halfdelay(10); /* disable fast refresh */
6563 err = draw_blame(view);
6565 view_border(view);
6566 return err;
6569 static const struct got_error *
6570 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6571 struct got_repository *repo, struct got_object_id *id)
6573 struct tog_view *log_view;
6574 const struct got_error *err = NULL;
6576 *new_view = NULL;
6578 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6579 if (log_view == NULL)
6580 return got_error_from_errno("view_open");
6582 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6583 if (err)
6584 view_close(log_view);
6585 else
6586 *new_view = log_view;
6588 return err;
6591 static const struct got_error *
6592 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6594 const struct got_error *err = NULL, *thread_err = NULL;
6595 struct tog_view *diff_view;
6596 struct tog_blame_view_state *s = &view->state.blame;
6597 int eos, nscroll, begin_y = 0, begin_x = 0;
6599 eos = nscroll = view->nlines - 2;
6600 if (view_is_hsplit_top(view))
6601 --eos; /* border */
6603 switch (ch) {
6604 case '0':
6605 case '$':
6606 case KEY_RIGHT:
6607 case 'l':
6608 case KEY_LEFT:
6609 case 'h':
6610 horizontal_scroll_input(view, ch);
6611 break;
6612 case 'q':
6613 s->done = 1;
6614 break;
6615 case 'g':
6616 case KEY_HOME:
6617 s->selected_line = 1;
6618 s->first_displayed_line = 1;
6619 view->count = 0;
6620 break;
6621 case 'G':
6622 case KEY_END:
6623 if (s->blame.nlines < eos) {
6624 s->selected_line = s->blame.nlines;
6625 s->first_displayed_line = 1;
6626 } else {
6627 s->selected_line = eos;
6628 s->first_displayed_line = s->blame.nlines - (eos - 1);
6630 view->count = 0;
6631 break;
6632 case 'k':
6633 case KEY_UP:
6634 case CTRL('p'):
6635 if (s->selected_line > 1)
6636 s->selected_line--;
6637 else if (s->selected_line == 1 &&
6638 s->first_displayed_line > 1)
6639 s->first_displayed_line--;
6640 else
6641 view->count = 0;
6642 break;
6643 case CTRL('u'):
6644 case 'u':
6645 nscroll /= 2;
6646 /* FALL THROUGH */
6647 case KEY_PPAGE:
6648 case CTRL('b'):
6649 case 'b':
6650 if (s->first_displayed_line == 1) {
6651 if (view->count > 1)
6652 nscroll += nscroll;
6653 s->selected_line = MAX(1, s->selected_line - nscroll);
6654 view->count = 0;
6655 break;
6657 if (s->first_displayed_line > nscroll)
6658 s->first_displayed_line -= nscroll;
6659 else
6660 s->first_displayed_line = 1;
6661 break;
6662 case 'j':
6663 case KEY_DOWN:
6664 case CTRL('n'):
6665 if (s->selected_line < eos && s->first_displayed_line +
6666 s->selected_line <= s->blame.nlines)
6667 s->selected_line++;
6668 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6669 s->first_displayed_line++;
6670 else
6671 view->count = 0;
6672 break;
6673 case 'c':
6674 case 'p': {
6675 struct got_object_id *id = NULL;
6677 view->count = 0;
6678 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6679 s->first_displayed_line, s->selected_line);
6680 if (id == NULL)
6681 break;
6682 if (ch == 'p') {
6683 struct got_commit_object *commit, *pcommit;
6684 struct got_object_qid *pid;
6685 struct got_object_id *blob_id = NULL;
6686 int obj_type;
6687 err = got_object_open_as_commit(&commit,
6688 s->repo, id);
6689 if (err)
6690 break;
6691 pid = STAILQ_FIRST(
6692 got_object_commit_get_parent_ids(commit));
6693 if (pid == NULL) {
6694 got_object_commit_close(commit);
6695 break;
6697 /* Check if path history ends here. */
6698 err = got_object_open_as_commit(&pcommit,
6699 s->repo, &pid->id);
6700 if (err)
6701 break;
6702 err = got_object_id_by_path(&blob_id, s->repo,
6703 pcommit, s->path);
6704 got_object_commit_close(pcommit);
6705 if (err) {
6706 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6707 err = NULL;
6708 got_object_commit_close(commit);
6709 break;
6711 err = got_object_get_type(&obj_type, s->repo,
6712 blob_id);
6713 free(blob_id);
6714 /* Can't blame non-blob type objects. */
6715 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6716 got_object_commit_close(commit);
6717 break;
6719 err = got_object_qid_alloc(&s->blamed_commit,
6720 &pid->id);
6721 got_object_commit_close(commit);
6722 } else {
6723 if (got_object_id_cmp(id,
6724 &s->blamed_commit->id) == 0)
6725 break;
6726 err = got_object_qid_alloc(&s->blamed_commit,
6727 id);
6729 if (err)
6730 break;
6731 s->done = 1;
6732 thread_err = stop_blame(&s->blame);
6733 s->done = 0;
6734 if (thread_err)
6735 break;
6736 STAILQ_INSERT_HEAD(&s->blamed_commits,
6737 s->blamed_commit, entry);
6738 err = run_blame(view);
6739 if (err)
6740 break;
6741 break;
6743 case 'C': {
6744 struct got_object_qid *first;
6746 view->count = 0;
6747 first = STAILQ_FIRST(&s->blamed_commits);
6748 if (!got_object_id_cmp(&first->id, s->commit_id))
6749 break;
6750 s->done = 1;
6751 thread_err = stop_blame(&s->blame);
6752 s->done = 0;
6753 if (thread_err)
6754 break;
6755 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6756 got_object_qid_free(s->blamed_commit);
6757 s->blamed_commit =
6758 STAILQ_FIRST(&s->blamed_commits);
6759 err = run_blame(view);
6760 if (err)
6761 break;
6762 break;
6764 case 'L':
6765 view->count = 0;
6766 s->id_to_log = get_selected_commit_id(s->blame.lines,
6767 s->blame.nlines, s->first_displayed_line, s->selected_line);
6768 if (s->id_to_log)
6769 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6770 break;
6771 case KEY_ENTER:
6772 case '\r': {
6773 struct got_object_id *id = NULL;
6774 struct got_object_qid *pid;
6775 struct got_commit_object *commit = NULL;
6777 view->count = 0;
6778 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6779 s->first_displayed_line, s->selected_line);
6780 if (id == NULL)
6781 break;
6782 err = got_object_open_as_commit(&commit, s->repo, id);
6783 if (err)
6784 break;
6785 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6786 if (*new_view) {
6787 /* traversed from diff view, release diff resources */
6788 err = close_diff_view(*new_view);
6789 if (err)
6790 break;
6791 diff_view = *new_view;
6792 } else {
6793 if (view_is_parent_view(view))
6794 view_get_split(view, &begin_y, &begin_x);
6796 diff_view = view_open(0, 0, begin_y, begin_x,
6797 TOG_VIEW_DIFF);
6798 if (diff_view == NULL) {
6799 got_object_commit_close(commit);
6800 err = got_error_from_errno("view_open");
6801 break;
6804 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6805 id, NULL, NULL, 3, 0, 0, view, s->repo);
6806 got_object_commit_close(commit);
6807 if (err) {
6808 view_close(diff_view);
6809 break;
6811 s->last_diffed_line = s->first_displayed_line - 1 +
6812 s->selected_line;
6813 if (*new_view)
6814 break; /* still open from active diff view */
6815 if (view_is_parent_view(view) &&
6816 view->mode == TOG_VIEW_SPLIT_HRZN) {
6817 err = view_init_hsplit(view, begin_y);
6818 if (err)
6819 break;
6822 view->focussed = 0;
6823 diff_view->focussed = 1;
6824 diff_view->mode = view->mode;
6825 diff_view->nlines = view->lines - begin_y;
6826 if (view_is_parent_view(view)) {
6827 view_transfer_size(diff_view, view);
6828 err = view_close_child(view);
6829 if (err)
6830 break;
6831 err = view_set_child(view, diff_view);
6832 if (err)
6833 break;
6834 view->focus_child = 1;
6835 } else
6836 *new_view = diff_view;
6837 if (err)
6838 break;
6839 break;
6841 case CTRL('d'):
6842 case 'd':
6843 nscroll /= 2;
6844 /* FALL THROUGH */
6845 case KEY_NPAGE:
6846 case CTRL('f'):
6847 case 'f':
6848 case ' ':
6849 if (s->last_displayed_line >= s->blame.nlines &&
6850 s->selected_line >= MIN(s->blame.nlines,
6851 view->nlines - 2)) {
6852 view->count = 0;
6853 break;
6855 if (s->last_displayed_line >= s->blame.nlines &&
6856 s->selected_line < view->nlines - 2) {
6857 s->selected_line +=
6858 MIN(nscroll, s->last_displayed_line -
6859 s->first_displayed_line - s->selected_line + 1);
6861 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6862 s->first_displayed_line += nscroll;
6863 else
6864 s->first_displayed_line =
6865 s->blame.nlines - (view->nlines - 3);
6866 break;
6867 case KEY_RESIZE:
6868 if (s->selected_line > view->nlines - 2) {
6869 s->selected_line = MIN(s->blame.nlines,
6870 view->nlines - 2);
6872 break;
6873 default:
6874 view->count = 0;
6875 break;
6877 return thread_err ? thread_err : err;
6880 static const struct got_error *
6881 reset_blame_view(struct tog_view *view)
6883 const struct got_error *err;
6884 struct tog_blame_view_state *s = &view->state.blame;
6886 view->count = 0;
6887 s->done = 1;
6888 err = stop_blame(&s->blame);
6889 s->done = 0;
6890 if (err)
6891 return err;
6892 return run_blame(view);
6895 static const struct got_error *
6896 cmd_blame(int argc, char *argv[])
6898 const struct got_error *error;
6899 struct got_repository *repo = NULL;
6900 struct got_worktree *worktree = NULL;
6901 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6902 char *link_target = NULL;
6903 struct got_object_id *commit_id = NULL;
6904 struct got_commit_object *commit = NULL;
6905 char *commit_id_str = NULL;
6906 int ch;
6907 struct tog_view *view = NULL;
6908 int *pack_fds = NULL;
6910 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6911 switch (ch) {
6912 case 'c':
6913 commit_id_str = optarg;
6914 break;
6915 case 'r':
6916 repo_path = realpath(optarg, NULL);
6917 if (repo_path == NULL)
6918 return got_error_from_errno2("realpath",
6919 optarg);
6920 break;
6921 default:
6922 usage_blame();
6923 /* NOTREACHED */
6927 argc -= optind;
6928 argv += optind;
6930 if (argc != 1)
6931 usage_blame();
6933 error = got_repo_pack_fds_open(&pack_fds);
6934 if (error != NULL)
6935 goto done;
6937 if (repo_path == NULL) {
6938 cwd = getcwd(NULL, 0);
6939 if (cwd == NULL)
6940 return got_error_from_errno("getcwd");
6941 error = got_worktree_open(&worktree, cwd);
6942 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6943 goto done;
6944 if (worktree)
6945 repo_path =
6946 strdup(got_worktree_get_repo_path(worktree));
6947 else
6948 repo_path = strdup(cwd);
6949 if (repo_path == NULL) {
6950 error = got_error_from_errno("strdup");
6951 goto done;
6955 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6956 if (error != NULL)
6957 goto done;
6959 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6960 worktree);
6961 if (error)
6962 goto done;
6964 init_curses();
6966 error = apply_unveil(got_repo_get_path(repo), NULL);
6967 if (error)
6968 goto done;
6970 error = tog_load_refs(repo, 0);
6971 if (error)
6972 goto done;
6974 if (commit_id_str == NULL) {
6975 struct got_reference *head_ref;
6976 error = got_ref_open(&head_ref, repo, worktree ?
6977 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6978 if (error != NULL)
6979 goto done;
6980 error = got_ref_resolve(&commit_id, repo, head_ref);
6981 got_ref_close(head_ref);
6982 } else {
6983 error = got_repo_match_object_id(&commit_id, NULL,
6984 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6986 if (error != NULL)
6987 goto done;
6989 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6990 if (view == NULL) {
6991 error = got_error_from_errno("view_open");
6992 goto done;
6995 error = got_object_open_as_commit(&commit, repo, commit_id);
6996 if (error)
6997 goto done;
6999 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7000 commit, repo);
7001 if (error)
7002 goto done;
7004 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7005 commit_id, repo);
7006 if (error)
7007 goto done;
7008 if (worktree) {
7009 /* Release work tree lock. */
7010 got_worktree_close(worktree);
7011 worktree = NULL;
7013 error = view_loop(view);
7014 done:
7015 free(repo_path);
7016 free(in_repo_path);
7017 free(link_target);
7018 free(cwd);
7019 free(commit_id);
7020 if (error != NULL && view != NULL) {
7021 if (view->close == NULL)
7022 close_blame_view(view);
7023 view_close(view);
7025 if (commit)
7026 got_object_commit_close(commit);
7027 if (worktree)
7028 got_worktree_close(worktree);
7029 if (repo) {
7030 const struct got_error *close_err = got_repo_close(repo);
7031 if (error == NULL)
7032 error = close_err;
7034 if (pack_fds) {
7035 const struct got_error *pack_err =
7036 got_repo_pack_fds_close(pack_fds);
7037 if (error == NULL)
7038 error = pack_err;
7040 tog_free_refs();
7041 return error;
7044 static const struct got_error *
7045 draw_tree_entries(struct tog_view *view, const char *parent_path)
7047 struct tog_tree_view_state *s = &view->state.tree;
7048 const struct got_error *err = NULL;
7049 struct got_tree_entry *te;
7050 wchar_t *wline;
7051 char *index = NULL;
7052 struct tog_color *tc;
7053 int width, n, nentries, scrollx, i = 1;
7054 int limit = view->nlines;
7056 s->ndisplayed = 0;
7057 if (view_is_hsplit_top(view))
7058 --limit; /* border */
7060 werase(view->window);
7062 if (limit == 0)
7063 return NULL;
7065 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7066 0, 0);
7067 if (err)
7068 return err;
7069 if (view_needs_focus_indication(view))
7070 wstandout(view->window);
7071 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7072 if (tc)
7073 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7074 waddwstr(view->window, wline);
7075 free(wline);
7076 wline = NULL;
7077 while (width++ < view->ncols)
7078 waddch(view->window, ' ');
7079 if (tc)
7080 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7081 if (view_needs_focus_indication(view))
7082 wstandend(view->window);
7083 if (--limit <= 0)
7084 return NULL;
7086 i += s->selected;
7087 if (s->first_displayed_entry) {
7088 i += got_tree_entry_get_index(s->first_displayed_entry);
7089 if (s->tree != s->root)
7090 ++i; /* account for ".." entry */
7092 nentries = got_object_tree_get_nentries(s->tree);
7093 if (asprintf(&index, "[%d/%d] %s",
7094 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7095 return got_error_from_errno("asprintf");
7096 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7097 free(index);
7098 if (err)
7099 return err;
7100 waddwstr(view->window, wline);
7101 free(wline);
7102 wline = NULL;
7103 if (width < view->ncols - 1)
7104 waddch(view->window, '\n');
7105 if (--limit <= 0)
7106 return NULL;
7107 waddch(view->window, '\n');
7108 if (--limit <= 0)
7109 return NULL;
7111 if (s->first_displayed_entry == NULL) {
7112 te = got_object_tree_get_first_entry(s->tree);
7113 if (s->selected == 0) {
7114 if (view->focussed)
7115 wstandout(view->window);
7116 s->selected_entry = NULL;
7118 waddstr(view->window, " ..\n"); /* parent directory */
7119 if (s->selected == 0 && view->focussed)
7120 wstandend(view->window);
7121 s->ndisplayed++;
7122 if (--limit <= 0)
7123 return NULL;
7124 n = 1;
7125 } else {
7126 n = 0;
7127 te = s->first_displayed_entry;
7130 view->maxx = 0;
7131 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7132 char *line = NULL, *id_str = NULL, *link_target = NULL;
7133 const char *modestr = "";
7134 mode_t mode;
7136 te = got_object_tree_get_entry(s->tree, i);
7137 mode = got_tree_entry_get_mode(te);
7139 if (s->show_ids) {
7140 err = got_object_id_str(&id_str,
7141 got_tree_entry_get_id(te));
7142 if (err)
7143 return got_error_from_errno(
7144 "got_object_id_str");
7146 if (got_object_tree_entry_is_submodule(te))
7147 modestr = "$";
7148 else if (S_ISLNK(mode)) {
7149 int i;
7151 err = got_tree_entry_get_symlink_target(&link_target,
7152 te, s->repo);
7153 if (err) {
7154 free(id_str);
7155 return err;
7157 for (i = 0; i < strlen(link_target); i++) {
7158 if (!isprint((unsigned char)link_target[i]))
7159 link_target[i] = '?';
7161 modestr = "@";
7163 else if (S_ISDIR(mode))
7164 modestr = "/";
7165 else if (mode & S_IXUSR)
7166 modestr = "*";
7167 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7168 got_tree_entry_get_name(te), modestr,
7169 link_target ? " -> ": "",
7170 link_target ? link_target : "") == -1) {
7171 free(id_str);
7172 free(link_target);
7173 return got_error_from_errno("asprintf");
7175 free(id_str);
7176 free(link_target);
7178 /* use full line width to determine view->maxx */
7179 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7180 if (err) {
7181 free(line);
7182 break;
7184 view->maxx = MAX(view->maxx, width);
7185 free(wline);
7186 wline = NULL;
7188 err = format_line(&wline, &width, &scrollx, line, view->x,
7189 view->ncols, 0, 0);
7190 if (err) {
7191 free(line);
7192 break;
7194 if (n == s->selected) {
7195 if (view->focussed)
7196 wstandout(view->window);
7197 s->selected_entry = te;
7199 tc = match_color(&s->colors, line);
7200 if (tc)
7201 wattr_on(view->window,
7202 COLOR_PAIR(tc->colorpair), NULL);
7203 waddwstr(view->window, &wline[scrollx]);
7204 if (tc)
7205 wattr_off(view->window,
7206 COLOR_PAIR(tc->colorpair), NULL);
7207 if (width < view->ncols)
7208 waddch(view->window, '\n');
7209 if (n == s->selected && view->focussed)
7210 wstandend(view->window);
7211 free(line);
7212 free(wline);
7213 wline = NULL;
7214 n++;
7215 s->ndisplayed++;
7216 s->last_displayed_entry = te;
7217 if (--limit <= 0)
7218 break;
7221 return err;
7224 static void
7225 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7227 struct got_tree_entry *te;
7228 int isroot = s->tree == s->root;
7229 int i = 0;
7231 if (s->first_displayed_entry == NULL)
7232 return;
7234 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7235 while (i++ < maxscroll) {
7236 if (te == NULL) {
7237 if (!isroot)
7238 s->first_displayed_entry = NULL;
7239 break;
7241 s->first_displayed_entry = te;
7242 te = got_tree_entry_get_prev(s->tree, te);
7246 static const struct got_error *
7247 tree_scroll_down(struct tog_view *view, int maxscroll)
7249 struct tog_tree_view_state *s = &view->state.tree;
7250 struct got_tree_entry *next, *last;
7251 int n = 0;
7253 if (s->first_displayed_entry)
7254 next = got_tree_entry_get_next(s->tree,
7255 s->first_displayed_entry);
7256 else
7257 next = got_object_tree_get_first_entry(s->tree);
7259 last = s->last_displayed_entry;
7260 while (next && n++ < maxscroll) {
7261 if (last) {
7262 s->last_displayed_entry = last;
7263 last = got_tree_entry_get_next(s->tree, last);
7265 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7266 s->first_displayed_entry = next;
7267 next = got_tree_entry_get_next(s->tree, next);
7271 return NULL;
7274 static const struct got_error *
7275 tree_entry_path(char **path, struct tog_parent_trees *parents,
7276 struct got_tree_entry *te)
7278 const struct got_error *err = NULL;
7279 struct tog_parent_tree *pt;
7280 size_t len = 2; /* for leading slash and NUL */
7282 TAILQ_FOREACH(pt, parents, entry)
7283 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7284 + 1 /* slash */;
7285 if (te)
7286 len += strlen(got_tree_entry_get_name(te));
7288 *path = calloc(1, len);
7289 if (path == NULL)
7290 return got_error_from_errno("calloc");
7292 (*path)[0] = '/';
7293 pt = TAILQ_LAST(parents, tog_parent_trees);
7294 while (pt) {
7295 const char *name = got_tree_entry_get_name(pt->selected_entry);
7296 if (strlcat(*path, name, len) >= len) {
7297 err = got_error(GOT_ERR_NO_SPACE);
7298 goto done;
7300 if (strlcat(*path, "/", len) >= len) {
7301 err = got_error(GOT_ERR_NO_SPACE);
7302 goto done;
7304 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7306 if (te) {
7307 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7308 err = got_error(GOT_ERR_NO_SPACE);
7309 goto done;
7312 done:
7313 if (err) {
7314 free(*path);
7315 *path = NULL;
7317 return err;
7320 static const struct got_error *
7321 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7322 struct got_tree_entry *te, struct tog_parent_trees *parents,
7323 struct got_object_id *commit_id, struct got_repository *repo)
7325 const struct got_error *err = NULL;
7326 char *path;
7327 struct tog_view *blame_view;
7329 *new_view = NULL;
7331 err = tree_entry_path(&path, parents, te);
7332 if (err)
7333 return err;
7335 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7336 if (blame_view == NULL) {
7337 err = got_error_from_errno("view_open");
7338 goto done;
7341 err = open_blame_view(blame_view, path, commit_id, repo);
7342 if (err) {
7343 if (err->code == GOT_ERR_CANCELLED)
7344 err = NULL;
7345 view_close(blame_view);
7346 } else
7347 *new_view = blame_view;
7348 done:
7349 free(path);
7350 return err;
7353 static const struct got_error *
7354 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7355 struct tog_tree_view_state *s)
7357 struct tog_view *log_view;
7358 const struct got_error *err = NULL;
7359 char *path;
7361 *new_view = NULL;
7363 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7364 if (log_view == NULL)
7365 return got_error_from_errno("view_open");
7367 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7368 if (err)
7369 return err;
7371 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7372 path, 0);
7373 if (err)
7374 view_close(log_view);
7375 else
7376 *new_view = log_view;
7377 free(path);
7378 return err;
7381 static const struct got_error *
7382 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7383 const char *head_ref_name, struct got_repository *repo)
7385 const struct got_error *err = NULL;
7386 char *commit_id_str = NULL;
7387 struct tog_tree_view_state *s = &view->state.tree;
7388 struct got_commit_object *commit = NULL;
7390 TAILQ_INIT(&s->parents);
7391 STAILQ_INIT(&s->colors);
7393 s->commit_id = got_object_id_dup(commit_id);
7394 if (s->commit_id == NULL) {
7395 err = got_error_from_errno("got_object_id_dup");
7396 goto done;
7399 err = got_object_open_as_commit(&commit, repo, commit_id);
7400 if (err)
7401 goto done;
7404 * The root is opened here and will be closed when the view is closed.
7405 * Any visited subtrees and their path-wise parents are opened and
7406 * closed on demand.
7408 err = got_object_open_as_tree(&s->root, repo,
7409 got_object_commit_get_tree_id(commit));
7410 if (err)
7411 goto done;
7412 s->tree = s->root;
7414 err = got_object_id_str(&commit_id_str, commit_id);
7415 if (err != NULL)
7416 goto done;
7418 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7419 err = got_error_from_errno("asprintf");
7420 goto done;
7423 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7424 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7425 if (head_ref_name) {
7426 s->head_ref_name = strdup(head_ref_name);
7427 if (s->head_ref_name == NULL) {
7428 err = got_error_from_errno("strdup");
7429 goto done;
7432 s->repo = repo;
7434 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7435 err = add_color(&s->colors, "\\$$",
7436 TOG_COLOR_TREE_SUBMODULE,
7437 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7438 if (err)
7439 goto done;
7440 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7441 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7442 if (err)
7443 goto done;
7444 err = add_color(&s->colors, "/$",
7445 TOG_COLOR_TREE_DIRECTORY,
7446 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7447 if (err)
7448 goto done;
7450 err = add_color(&s->colors, "\\*$",
7451 TOG_COLOR_TREE_EXECUTABLE,
7452 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7453 if (err)
7454 goto done;
7456 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7457 get_color_value("TOG_COLOR_COMMIT"));
7458 if (err)
7459 goto done;
7462 view->show = show_tree_view;
7463 view->input = input_tree_view;
7464 view->close = close_tree_view;
7465 view->search_start = search_start_tree_view;
7466 view->search_next = search_next_tree_view;
7467 done:
7468 free(commit_id_str);
7469 if (commit)
7470 got_object_commit_close(commit);
7471 if (err) {
7472 if (view->close == NULL)
7473 close_tree_view(view);
7474 view_close(view);
7476 return err;
7479 static const struct got_error *
7480 close_tree_view(struct tog_view *view)
7482 struct tog_tree_view_state *s = &view->state.tree;
7484 free_colors(&s->colors);
7485 free(s->tree_label);
7486 s->tree_label = NULL;
7487 free(s->commit_id);
7488 s->commit_id = NULL;
7489 free(s->head_ref_name);
7490 s->head_ref_name = NULL;
7491 while (!TAILQ_EMPTY(&s->parents)) {
7492 struct tog_parent_tree *parent;
7493 parent = TAILQ_FIRST(&s->parents);
7494 TAILQ_REMOVE(&s->parents, parent, entry);
7495 if (parent->tree != s->root)
7496 got_object_tree_close(parent->tree);
7497 free(parent);
7500 if (s->tree != NULL && s->tree != s->root)
7501 got_object_tree_close(s->tree);
7502 if (s->root)
7503 got_object_tree_close(s->root);
7504 return NULL;
7507 static const struct got_error *
7508 search_start_tree_view(struct tog_view *view)
7510 struct tog_tree_view_state *s = &view->state.tree;
7512 s->matched_entry = NULL;
7513 return NULL;
7516 static int
7517 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7519 regmatch_t regmatch;
7521 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7522 0) == 0;
7525 static const struct got_error *
7526 search_next_tree_view(struct tog_view *view)
7528 struct tog_tree_view_state *s = &view->state.tree;
7529 struct got_tree_entry *te = NULL;
7531 if (!view->searching) {
7532 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7533 return NULL;
7536 if (s->matched_entry) {
7537 if (view->searching == TOG_SEARCH_FORWARD) {
7538 if (s->selected_entry)
7539 te = got_tree_entry_get_next(s->tree,
7540 s->selected_entry);
7541 else
7542 te = got_object_tree_get_first_entry(s->tree);
7543 } else {
7544 if (s->selected_entry == NULL)
7545 te = got_object_tree_get_last_entry(s->tree);
7546 else
7547 te = got_tree_entry_get_prev(s->tree,
7548 s->selected_entry);
7550 } else {
7551 if (s->selected_entry)
7552 te = s->selected_entry;
7553 else if (view->searching == TOG_SEARCH_FORWARD)
7554 te = got_object_tree_get_first_entry(s->tree);
7555 else
7556 te = got_object_tree_get_last_entry(s->tree);
7559 while (1) {
7560 if (te == NULL) {
7561 if (s->matched_entry == NULL) {
7562 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7563 return NULL;
7565 if (view->searching == TOG_SEARCH_FORWARD)
7566 te = got_object_tree_get_first_entry(s->tree);
7567 else
7568 te = got_object_tree_get_last_entry(s->tree);
7571 if (match_tree_entry(te, &view->regex)) {
7572 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7573 s->matched_entry = te;
7574 break;
7577 if (view->searching == TOG_SEARCH_FORWARD)
7578 te = got_tree_entry_get_next(s->tree, te);
7579 else
7580 te = got_tree_entry_get_prev(s->tree, te);
7583 if (s->matched_entry) {
7584 s->first_displayed_entry = s->matched_entry;
7585 s->selected = 0;
7588 return NULL;
7591 static const struct got_error *
7592 show_tree_view(struct tog_view *view)
7594 const struct got_error *err = NULL;
7595 struct tog_tree_view_state *s = &view->state.tree;
7596 char *parent_path;
7598 err = tree_entry_path(&parent_path, &s->parents, NULL);
7599 if (err)
7600 return err;
7602 err = draw_tree_entries(view, parent_path);
7603 free(parent_path);
7605 view_border(view);
7606 return err;
7609 static const struct got_error *
7610 tree_goto_line(struct tog_view *view, int nlines)
7612 const struct got_error *err = NULL;
7613 struct tog_tree_view_state *s = &view->state.tree;
7614 struct got_tree_entry **fte, **lte, **ste;
7615 int g, last, first = 1, i = 1;
7616 int root = s->tree == s->root;
7617 int off = root ? 1 : 2;
7619 g = view->gline;
7620 view->gline = 0;
7622 if (g == 0)
7623 g = 1;
7624 else if (g > got_object_tree_get_nentries(s->tree))
7625 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7627 fte = &s->first_displayed_entry;
7628 lte = &s->last_displayed_entry;
7629 ste = &s->selected_entry;
7631 if (*fte != NULL) {
7632 first = got_tree_entry_get_index(*fte);
7633 first += off; /* account for ".." */
7635 last = got_tree_entry_get_index(*lte);
7636 last += off;
7638 if (g >= first && g <= last && g - first < nlines) {
7639 s->selected = g - first;
7640 return NULL; /* gline is on the current page */
7643 if (*ste != NULL) {
7644 i = got_tree_entry_get_index(*ste);
7645 i += off;
7648 if (i < g) {
7649 err = tree_scroll_down(view, g - i);
7650 if (err)
7651 return err;
7652 if (got_tree_entry_get_index(*lte) >=
7653 got_object_tree_get_nentries(s->tree) - 1 &&
7654 first + s->selected < g &&
7655 s->selected < s->ndisplayed - 1) {
7656 first = got_tree_entry_get_index(*fte);
7657 first += off;
7658 s->selected = g - first;
7660 } else if (i > g)
7661 tree_scroll_up(s, i - g);
7663 if (g < nlines &&
7664 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7665 s->selected = g - 1;
7667 return NULL;
7670 static const struct got_error *
7671 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7673 const struct got_error *err = NULL;
7674 struct tog_tree_view_state *s = &view->state.tree;
7675 struct got_tree_entry *te;
7676 int n, nscroll = view->nlines - 3;
7678 if (view->gline)
7679 return tree_goto_line(view, nscroll);
7681 switch (ch) {
7682 case '0':
7683 case '$':
7684 case KEY_RIGHT:
7685 case 'l':
7686 case KEY_LEFT:
7687 case 'h':
7688 horizontal_scroll_input(view, ch);
7689 break;
7690 case 'i':
7691 s->show_ids = !s->show_ids;
7692 view->count = 0;
7693 break;
7694 case 'L':
7695 view->count = 0;
7696 if (!s->selected_entry)
7697 break;
7698 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7699 break;
7700 case 'R':
7701 view->count = 0;
7702 err = view_request_new(new_view, view, TOG_VIEW_REF);
7703 break;
7704 case 'g':
7705 case '=':
7706 case KEY_HOME:
7707 s->selected = 0;
7708 view->count = 0;
7709 if (s->tree == s->root)
7710 s->first_displayed_entry =
7711 got_object_tree_get_first_entry(s->tree);
7712 else
7713 s->first_displayed_entry = NULL;
7714 break;
7715 case 'G':
7716 case '*':
7717 case KEY_END: {
7718 int eos = view->nlines - 3;
7720 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7721 --eos; /* border */
7722 s->selected = 0;
7723 view->count = 0;
7724 te = got_object_tree_get_last_entry(s->tree);
7725 for (n = 0; n < eos; n++) {
7726 if (te == NULL) {
7727 if (s->tree != s->root) {
7728 s->first_displayed_entry = NULL;
7729 n++;
7731 break;
7733 s->first_displayed_entry = te;
7734 te = got_tree_entry_get_prev(s->tree, te);
7736 if (n > 0)
7737 s->selected = n - 1;
7738 break;
7740 case 'k':
7741 case KEY_UP:
7742 case CTRL('p'):
7743 if (s->selected > 0) {
7744 s->selected--;
7745 break;
7747 tree_scroll_up(s, 1);
7748 if (s->selected_entry == NULL ||
7749 (s->tree == s->root && s->selected_entry ==
7750 got_object_tree_get_first_entry(s->tree)))
7751 view->count = 0;
7752 break;
7753 case CTRL('u'):
7754 case 'u':
7755 nscroll /= 2;
7756 /* FALL THROUGH */
7757 case KEY_PPAGE:
7758 case CTRL('b'):
7759 case 'b':
7760 if (s->tree == s->root) {
7761 if (got_object_tree_get_first_entry(s->tree) ==
7762 s->first_displayed_entry)
7763 s->selected -= MIN(s->selected, nscroll);
7764 } else {
7765 if (s->first_displayed_entry == NULL)
7766 s->selected -= MIN(s->selected, nscroll);
7768 tree_scroll_up(s, MAX(0, nscroll));
7769 if (s->selected_entry == NULL ||
7770 (s->tree == s->root && s->selected_entry ==
7771 got_object_tree_get_first_entry(s->tree)))
7772 view->count = 0;
7773 break;
7774 case 'j':
7775 case KEY_DOWN:
7776 case CTRL('n'):
7777 if (s->selected < s->ndisplayed - 1) {
7778 s->selected++;
7779 break;
7781 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7782 == NULL) {
7783 /* can't scroll any further */
7784 view->count = 0;
7785 break;
7787 tree_scroll_down(view, 1);
7788 break;
7789 case CTRL('d'):
7790 case 'd':
7791 nscroll /= 2;
7792 /* FALL THROUGH */
7793 case KEY_NPAGE:
7794 case CTRL('f'):
7795 case 'f':
7796 case ' ':
7797 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7798 == NULL) {
7799 /* can't scroll any further; move cursor down */
7800 if (s->selected < s->ndisplayed - 1)
7801 s->selected += MIN(nscroll,
7802 s->ndisplayed - s->selected - 1);
7803 else
7804 view->count = 0;
7805 break;
7807 tree_scroll_down(view, nscroll);
7808 break;
7809 case KEY_ENTER:
7810 case '\r':
7811 case KEY_BACKSPACE:
7812 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7813 struct tog_parent_tree *parent;
7814 /* user selected '..' */
7815 if (s->tree == s->root) {
7816 view->count = 0;
7817 break;
7819 parent = TAILQ_FIRST(&s->parents);
7820 TAILQ_REMOVE(&s->parents, parent,
7821 entry);
7822 got_object_tree_close(s->tree);
7823 s->tree = parent->tree;
7824 s->first_displayed_entry =
7825 parent->first_displayed_entry;
7826 s->selected_entry =
7827 parent->selected_entry;
7828 s->selected = parent->selected;
7829 if (s->selected > view->nlines - 3) {
7830 err = offset_selection_down(view);
7831 if (err)
7832 break;
7834 free(parent);
7835 } else if (S_ISDIR(got_tree_entry_get_mode(
7836 s->selected_entry))) {
7837 struct got_tree_object *subtree;
7838 view->count = 0;
7839 err = got_object_open_as_tree(&subtree, s->repo,
7840 got_tree_entry_get_id(s->selected_entry));
7841 if (err)
7842 break;
7843 err = tree_view_visit_subtree(s, subtree);
7844 if (err) {
7845 got_object_tree_close(subtree);
7846 break;
7848 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7849 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7850 break;
7851 case KEY_RESIZE:
7852 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7853 s->selected = view->nlines - 4;
7854 view->count = 0;
7855 break;
7856 default:
7857 view->count = 0;
7858 break;
7861 return err;
7864 __dead static void
7865 usage_tree(void)
7867 endwin();
7868 fprintf(stderr,
7869 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7870 getprogname());
7871 exit(1);
7874 static const struct got_error *
7875 cmd_tree(int argc, char *argv[])
7877 const struct got_error *error;
7878 struct got_repository *repo = NULL;
7879 struct got_worktree *worktree = NULL;
7880 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7881 struct got_object_id *commit_id = NULL;
7882 struct got_commit_object *commit = NULL;
7883 const char *commit_id_arg = NULL;
7884 char *label = NULL;
7885 struct got_reference *ref = NULL;
7886 const char *head_ref_name = NULL;
7887 int ch;
7888 struct tog_view *view;
7889 int *pack_fds = NULL;
7891 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7892 switch (ch) {
7893 case 'c':
7894 commit_id_arg = optarg;
7895 break;
7896 case 'r':
7897 repo_path = realpath(optarg, NULL);
7898 if (repo_path == NULL)
7899 return got_error_from_errno2("realpath",
7900 optarg);
7901 break;
7902 default:
7903 usage_tree();
7904 /* NOTREACHED */
7908 argc -= optind;
7909 argv += optind;
7911 if (argc > 1)
7912 usage_tree();
7914 error = got_repo_pack_fds_open(&pack_fds);
7915 if (error != NULL)
7916 goto done;
7918 if (repo_path == NULL) {
7919 cwd = getcwd(NULL, 0);
7920 if (cwd == NULL)
7921 return got_error_from_errno("getcwd");
7922 error = got_worktree_open(&worktree, cwd);
7923 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7924 goto done;
7925 if (worktree)
7926 repo_path =
7927 strdup(got_worktree_get_repo_path(worktree));
7928 else
7929 repo_path = strdup(cwd);
7930 if (repo_path == NULL) {
7931 error = got_error_from_errno("strdup");
7932 goto done;
7936 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7937 if (error != NULL)
7938 goto done;
7940 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7941 repo, worktree);
7942 if (error)
7943 goto done;
7945 init_curses();
7947 error = apply_unveil(got_repo_get_path(repo), NULL);
7948 if (error)
7949 goto done;
7951 error = tog_load_refs(repo, 0);
7952 if (error)
7953 goto done;
7955 if (commit_id_arg == NULL) {
7956 error = got_repo_match_object_id(&commit_id, &label,
7957 worktree ? got_worktree_get_head_ref_name(worktree) :
7958 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7959 if (error)
7960 goto done;
7961 head_ref_name = label;
7962 } else {
7963 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7964 if (error == NULL)
7965 head_ref_name = got_ref_get_name(ref);
7966 else if (error->code != GOT_ERR_NOT_REF)
7967 goto done;
7968 error = got_repo_match_object_id(&commit_id, NULL,
7969 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7970 if (error)
7971 goto done;
7974 error = got_object_open_as_commit(&commit, repo, commit_id);
7975 if (error)
7976 goto done;
7978 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7979 if (view == NULL) {
7980 error = got_error_from_errno("view_open");
7981 goto done;
7983 error = open_tree_view(view, commit_id, head_ref_name, repo);
7984 if (error)
7985 goto done;
7986 if (!got_path_is_root_dir(in_repo_path)) {
7987 error = tree_view_walk_path(&view->state.tree, commit,
7988 in_repo_path);
7989 if (error)
7990 goto done;
7993 if (worktree) {
7994 /* Release work tree lock. */
7995 got_worktree_close(worktree);
7996 worktree = NULL;
7998 error = view_loop(view);
7999 done:
8000 free(repo_path);
8001 free(cwd);
8002 free(commit_id);
8003 free(label);
8004 if (ref)
8005 got_ref_close(ref);
8006 if (repo) {
8007 const struct got_error *close_err = got_repo_close(repo);
8008 if (error == NULL)
8009 error = close_err;
8011 if (pack_fds) {
8012 const struct got_error *pack_err =
8013 got_repo_pack_fds_close(pack_fds);
8014 if (error == NULL)
8015 error = pack_err;
8017 tog_free_refs();
8018 return error;
8021 static const struct got_error *
8022 ref_view_load_refs(struct tog_ref_view_state *s)
8024 struct got_reflist_entry *sre;
8025 struct tog_reflist_entry *re;
8027 s->nrefs = 0;
8028 TAILQ_FOREACH(sre, &tog_refs, entry) {
8029 if (strncmp(got_ref_get_name(sre->ref),
8030 "refs/got/", 9) == 0 &&
8031 strncmp(got_ref_get_name(sre->ref),
8032 "refs/got/backup/", 16) != 0)
8033 continue;
8035 re = malloc(sizeof(*re));
8036 if (re == NULL)
8037 return got_error_from_errno("malloc");
8039 re->ref = got_ref_dup(sre->ref);
8040 if (re->ref == NULL)
8041 return got_error_from_errno("got_ref_dup");
8042 re->idx = s->nrefs++;
8043 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8046 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8047 return NULL;
8050 static void
8051 ref_view_free_refs(struct tog_ref_view_state *s)
8053 struct tog_reflist_entry *re;
8055 while (!TAILQ_EMPTY(&s->refs)) {
8056 re = TAILQ_FIRST(&s->refs);
8057 TAILQ_REMOVE(&s->refs, re, entry);
8058 got_ref_close(re->ref);
8059 free(re);
8063 static const struct got_error *
8064 open_ref_view(struct tog_view *view, struct got_repository *repo)
8066 const struct got_error *err = NULL;
8067 struct tog_ref_view_state *s = &view->state.ref;
8069 s->selected_entry = 0;
8070 s->repo = repo;
8072 TAILQ_INIT(&s->refs);
8073 STAILQ_INIT(&s->colors);
8075 err = ref_view_load_refs(s);
8076 if (err)
8077 goto done;
8079 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8080 err = add_color(&s->colors, "^refs/heads/",
8081 TOG_COLOR_REFS_HEADS,
8082 get_color_value("TOG_COLOR_REFS_HEADS"));
8083 if (err)
8084 goto done;
8086 err = add_color(&s->colors, "^refs/tags/",
8087 TOG_COLOR_REFS_TAGS,
8088 get_color_value("TOG_COLOR_REFS_TAGS"));
8089 if (err)
8090 goto done;
8092 err = add_color(&s->colors, "^refs/remotes/",
8093 TOG_COLOR_REFS_REMOTES,
8094 get_color_value("TOG_COLOR_REFS_REMOTES"));
8095 if (err)
8096 goto done;
8098 err = add_color(&s->colors, "^refs/got/backup/",
8099 TOG_COLOR_REFS_BACKUP,
8100 get_color_value("TOG_COLOR_REFS_BACKUP"));
8101 if (err)
8102 goto done;
8105 view->show = show_ref_view;
8106 view->input = input_ref_view;
8107 view->close = close_ref_view;
8108 view->search_start = search_start_ref_view;
8109 view->search_next = search_next_ref_view;
8110 done:
8111 if (err) {
8112 if (view->close == NULL)
8113 close_ref_view(view);
8114 view_close(view);
8116 return err;
8119 static const struct got_error *
8120 close_ref_view(struct tog_view *view)
8122 struct tog_ref_view_state *s = &view->state.ref;
8124 ref_view_free_refs(s);
8125 free_colors(&s->colors);
8127 return NULL;
8130 static const struct got_error *
8131 resolve_reflist_entry(struct got_object_id **commit_id,
8132 struct tog_reflist_entry *re, struct got_repository *repo)
8134 const struct got_error *err = NULL;
8135 struct got_object_id *obj_id;
8136 struct got_tag_object *tag = NULL;
8137 int obj_type;
8139 *commit_id = NULL;
8141 err = got_ref_resolve(&obj_id, repo, re->ref);
8142 if (err)
8143 return err;
8145 err = got_object_get_type(&obj_type, repo, obj_id);
8146 if (err)
8147 goto done;
8149 switch (obj_type) {
8150 case GOT_OBJ_TYPE_COMMIT:
8151 *commit_id = obj_id;
8152 break;
8153 case GOT_OBJ_TYPE_TAG:
8154 err = got_object_open_as_tag(&tag, repo, obj_id);
8155 if (err)
8156 goto done;
8157 free(obj_id);
8158 err = got_object_get_type(&obj_type, repo,
8159 got_object_tag_get_object_id(tag));
8160 if (err)
8161 goto done;
8162 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8163 err = got_error(GOT_ERR_OBJ_TYPE);
8164 goto done;
8166 *commit_id = got_object_id_dup(
8167 got_object_tag_get_object_id(tag));
8168 if (*commit_id == NULL) {
8169 err = got_error_from_errno("got_object_id_dup");
8170 goto done;
8172 break;
8173 default:
8174 err = got_error(GOT_ERR_OBJ_TYPE);
8175 break;
8178 done:
8179 if (tag)
8180 got_object_tag_close(tag);
8181 if (err) {
8182 free(*commit_id);
8183 *commit_id = NULL;
8185 return err;
8188 static const struct got_error *
8189 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8190 struct tog_reflist_entry *re, struct got_repository *repo)
8192 struct tog_view *log_view;
8193 const struct got_error *err = NULL;
8194 struct got_object_id *commit_id = NULL;
8196 *new_view = NULL;
8198 err = resolve_reflist_entry(&commit_id, re, repo);
8199 if (err) {
8200 if (err->code != GOT_ERR_OBJ_TYPE)
8201 return err;
8202 else
8203 return NULL;
8206 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8207 if (log_view == NULL) {
8208 err = got_error_from_errno("view_open");
8209 goto done;
8212 err = open_log_view(log_view, commit_id, repo,
8213 got_ref_get_name(re->ref), "", 0);
8214 done:
8215 if (err)
8216 view_close(log_view);
8217 else
8218 *new_view = log_view;
8219 free(commit_id);
8220 return err;
8223 static void
8224 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8226 struct tog_reflist_entry *re;
8227 int i = 0;
8229 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8230 return;
8232 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8233 while (i++ < maxscroll) {
8234 if (re == NULL)
8235 break;
8236 s->first_displayed_entry = re;
8237 re = TAILQ_PREV(re, tog_reflist_head, entry);
8241 static const struct got_error *
8242 ref_scroll_down(struct tog_view *view, int maxscroll)
8244 struct tog_ref_view_state *s = &view->state.ref;
8245 struct tog_reflist_entry *next, *last;
8246 int n = 0;
8248 if (s->first_displayed_entry)
8249 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8250 else
8251 next = TAILQ_FIRST(&s->refs);
8253 last = s->last_displayed_entry;
8254 while (next && n++ < maxscroll) {
8255 if (last) {
8256 s->last_displayed_entry = last;
8257 last = TAILQ_NEXT(last, entry);
8259 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8260 s->first_displayed_entry = next;
8261 next = TAILQ_NEXT(next, entry);
8265 return NULL;
8268 static const struct got_error *
8269 search_start_ref_view(struct tog_view *view)
8271 struct tog_ref_view_state *s = &view->state.ref;
8273 s->matched_entry = NULL;
8274 return NULL;
8277 static int
8278 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8280 regmatch_t regmatch;
8282 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8283 0) == 0;
8286 static const struct got_error *
8287 search_next_ref_view(struct tog_view *view)
8289 struct tog_ref_view_state *s = &view->state.ref;
8290 struct tog_reflist_entry *re = NULL;
8292 if (!view->searching) {
8293 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8294 return NULL;
8297 if (s->matched_entry) {
8298 if (view->searching == TOG_SEARCH_FORWARD) {
8299 if (s->selected_entry)
8300 re = TAILQ_NEXT(s->selected_entry, entry);
8301 else
8302 re = TAILQ_PREV(s->selected_entry,
8303 tog_reflist_head, entry);
8304 } else {
8305 if (s->selected_entry == NULL)
8306 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8307 else
8308 re = TAILQ_PREV(s->selected_entry,
8309 tog_reflist_head, entry);
8311 } else {
8312 if (s->selected_entry)
8313 re = s->selected_entry;
8314 else if (view->searching == TOG_SEARCH_FORWARD)
8315 re = TAILQ_FIRST(&s->refs);
8316 else
8317 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8320 while (1) {
8321 if (re == NULL) {
8322 if (s->matched_entry == NULL) {
8323 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8324 return NULL;
8326 if (view->searching == TOG_SEARCH_FORWARD)
8327 re = TAILQ_FIRST(&s->refs);
8328 else
8329 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8332 if (match_reflist_entry(re, &view->regex)) {
8333 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8334 s->matched_entry = re;
8335 break;
8338 if (view->searching == TOG_SEARCH_FORWARD)
8339 re = TAILQ_NEXT(re, entry);
8340 else
8341 re = TAILQ_PREV(re, tog_reflist_head, entry);
8344 if (s->matched_entry) {
8345 s->first_displayed_entry = s->matched_entry;
8346 s->selected = 0;
8349 return NULL;
8352 static const struct got_error *
8353 show_ref_view(struct tog_view *view)
8355 const struct got_error *err = NULL;
8356 struct tog_ref_view_state *s = &view->state.ref;
8357 struct tog_reflist_entry *re;
8358 char *line = NULL;
8359 wchar_t *wline;
8360 struct tog_color *tc;
8361 int width, n, scrollx;
8362 int limit = view->nlines;
8364 werase(view->window);
8366 s->ndisplayed = 0;
8367 if (view_is_hsplit_top(view))
8368 --limit; /* border */
8370 if (limit == 0)
8371 return NULL;
8373 re = s->first_displayed_entry;
8375 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8376 s->nrefs) == -1)
8377 return got_error_from_errno("asprintf");
8379 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8380 if (err) {
8381 free(line);
8382 return err;
8384 if (view_needs_focus_indication(view))
8385 wstandout(view->window);
8386 waddwstr(view->window, wline);
8387 while (width++ < view->ncols)
8388 waddch(view->window, ' ');
8389 if (view_needs_focus_indication(view))
8390 wstandend(view->window);
8391 free(wline);
8392 wline = NULL;
8393 free(line);
8394 line = NULL;
8395 if (--limit <= 0)
8396 return NULL;
8398 n = 0;
8399 view->maxx = 0;
8400 while (re && limit > 0) {
8401 char *line = NULL;
8402 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8404 if (s->show_date) {
8405 struct got_commit_object *ci;
8406 struct got_tag_object *tag;
8407 struct got_object_id *id;
8408 struct tm tm;
8409 time_t t;
8411 err = got_ref_resolve(&id, s->repo, re->ref);
8412 if (err)
8413 return err;
8414 err = got_object_open_as_tag(&tag, s->repo, id);
8415 if (err) {
8416 if (err->code != GOT_ERR_OBJ_TYPE) {
8417 free(id);
8418 return err;
8420 err = got_object_open_as_commit(&ci, s->repo,
8421 id);
8422 if (err) {
8423 free(id);
8424 return err;
8426 t = got_object_commit_get_committer_time(ci);
8427 got_object_commit_close(ci);
8428 } else {
8429 t = got_object_tag_get_tagger_time(tag);
8430 got_object_tag_close(tag);
8432 free(id);
8433 if (gmtime_r(&t, &tm) == NULL)
8434 return got_error_from_errno("gmtime_r");
8435 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8436 return got_error(GOT_ERR_NO_SPACE);
8438 if (got_ref_is_symbolic(re->ref)) {
8439 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8440 ymd : "", got_ref_get_name(re->ref),
8441 got_ref_get_symref_target(re->ref)) == -1)
8442 return got_error_from_errno("asprintf");
8443 } else if (s->show_ids) {
8444 struct got_object_id *id;
8445 char *id_str;
8446 err = got_ref_resolve(&id, s->repo, re->ref);
8447 if (err)
8448 return err;
8449 err = got_object_id_str(&id_str, id);
8450 if (err) {
8451 free(id);
8452 return err;
8454 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8455 got_ref_get_name(re->ref), id_str) == -1) {
8456 err = got_error_from_errno("asprintf");
8457 free(id);
8458 free(id_str);
8459 return err;
8461 free(id);
8462 free(id_str);
8463 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8464 got_ref_get_name(re->ref)) == -1)
8465 return got_error_from_errno("asprintf");
8467 /* use full line width to determine view->maxx */
8468 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8469 if (err) {
8470 free(line);
8471 return err;
8473 view->maxx = MAX(view->maxx, width);
8474 free(wline);
8475 wline = NULL;
8477 err = format_line(&wline, &width, &scrollx, line, view->x,
8478 view->ncols, 0, 0);
8479 if (err) {
8480 free(line);
8481 return err;
8483 if (n == s->selected) {
8484 if (view->focussed)
8485 wstandout(view->window);
8486 s->selected_entry = re;
8488 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8489 if (tc)
8490 wattr_on(view->window,
8491 COLOR_PAIR(tc->colorpair), NULL);
8492 waddwstr(view->window, &wline[scrollx]);
8493 if (tc)
8494 wattr_off(view->window,
8495 COLOR_PAIR(tc->colorpair), NULL);
8496 if (width < view->ncols)
8497 waddch(view->window, '\n');
8498 if (n == s->selected && view->focussed)
8499 wstandend(view->window);
8500 free(line);
8501 free(wline);
8502 wline = NULL;
8503 n++;
8504 s->ndisplayed++;
8505 s->last_displayed_entry = re;
8507 limit--;
8508 re = TAILQ_NEXT(re, entry);
8511 view_border(view);
8512 return err;
8515 static const struct got_error *
8516 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8517 struct tog_reflist_entry *re, struct got_repository *repo)
8519 const struct got_error *err = NULL;
8520 struct got_object_id *commit_id = NULL;
8521 struct tog_view *tree_view;
8523 *new_view = NULL;
8525 err = resolve_reflist_entry(&commit_id, re, repo);
8526 if (err) {
8527 if (err->code != GOT_ERR_OBJ_TYPE)
8528 return err;
8529 else
8530 return NULL;
8534 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8535 if (tree_view == NULL) {
8536 err = got_error_from_errno("view_open");
8537 goto done;
8540 err = open_tree_view(tree_view, commit_id,
8541 got_ref_get_name(re->ref), repo);
8542 if (err)
8543 goto done;
8545 *new_view = tree_view;
8546 done:
8547 free(commit_id);
8548 return err;
8551 static const struct got_error *
8552 ref_goto_line(struct tog_view *view, int nlines)
8554 const struct got_error *err = NULL;
8555 struct tog_ref_view_state *s = &view->state.ref;
8556 int g, idx = s->selected_entry->idx;
8558 g = view->gline;
8559 view->gline = 0;
8561 if (g == 0)
8562 g = 1;
8563 else if (g > s->nrefs)
8564 g = s->nrefs;
8566 if (g >= s->first_displayed_entry->idx + 1 &&
8567 g <= s->last_displayed_entry->idx + 1 &&
8568 g - s->first_displayed_entry->idx - 1 < nlines) {
8569 s->selected = g - s->first_displayed_entry->idx - 1;
8570 return NULL;
8573 if (idx + 1 < g) {
8574 err = ref_scroll_down(view, g - idx - 1);
8575 if (err)
8576 return err;
8577 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8578 s->first_displayed_entry->idx + s->selected < g &&
8579 s->selected < s->ndisplayed - 1)
8580 s->selected = g - s->first_displayed_entry->idx - 1;
8581 } else if (idx + 1 > g)
8582 ref_scroll_up(s, idx - g + 1);
8584 if (g < nlines && s->first_displayed_entry->idx == 0)
8585 s->selected = g - 1;
8587 return NULL;
8591 static const struct got_error *
8592 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8594 const struct got_error *err = NULL;
8595 struct tog_ref_view_state *s = &view->state.ref;
8596 struct tog_reflist_entry *re;
8597 int n, nscroll = view->nlines - 1;
8599 if (view->gline)
8600 return ref_goto_line(view, nscroll);
8602 switch (ch) {
8603 case '0':
8604 case '$':
8605 case KEY_RIGHT:
8606 case 'l':
8607 case KEY_LEFT:
8608 case 'h':
8609 horizontal_scroll_input(view, ch);
8610 break;
8611 case 'i':
8612 s->show_ids = !s->show_ids;
8613 view->count = 0;
8614 break;
8615 case 'm':
8616 s->show_date = !s->show_date;
8617 view->count = 0;
8618 break;
8619 case 'o':
8620 s->sort_by_date = !s->sort_by_date;
8621 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8622 view->count = 0;
8623 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8624 got_ref_cmp_by_commit_timestamp_descending :
8625 tog_ref_cmp_by_name, s->repo);
8626 if (err)
8627 break;
8628 got_reflist_object_id_map_free(tog_refs_idmap);
8629 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8630 &tog_refs, s->repo);
8631 if (err)
8632 break;
8633 ref_view_free_refs(s);
8634 err = ref_view_load_refs(s);
8635 break;
8636 case KEY_ENTER:
8637 case '\r':
8638 view->count = 0;
8639 if (!s->selected_entry)
8640 break;
8641 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8642 break;
8643 case 'T':
8644 view->count = 0;
8645 if (!s->selected_entry)
8646 break;
8647 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8648 break;
8649 case 'g':
8650 case '=':
8651 case KEY_HOME:
8652 s->selected = 0;
8653 view->count = 0;
8654 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8655 break;
8656 case 'G':
8657 case '*':
8658 case KEY_END: {
8659 int eos = view->nlines - 1;
8661 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8662 --eos; /* border */
8663 s->selected = 0;
8664 view->count = 0;
8665 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8666 for (n = 0; n < eos; n++) {
8667 if (re == NULL)
8668 break;
8669 s->first_displayed_entry = re;
8670 re = TAILQ_PREV(re, tog_reflist_head, entry);
8672 if (n > 0)
8673 s->selected = n - 1;
8674 break;
8676 case 'k':
8677 case KEY_UP:
8678 case CTRL('p'):
8679 if (s->selected > 0) {
8680 s->selected--;
8681 break;
8683 ref_scroll_up(s, 1);
8684 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8685 view->count = 0;
8686 break;
8687 case CTRL('u'):
8688 case 'u':
8689 nscroll /= 2;
8690 /* FALL THROUGH */
8691 case KEY_PPAGE:
8692 case CTRL('b'):
8693 case 'b':
8694 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8695 s->selected -= MIN(nscroll, s->selected);
8696 ref_scroll_up(s, MAX(0, nscroll));
8697 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8698 view->count = 0;
8699 break;
8700 case 'j':
8701 case KEY_DOWN:
8702 case CTRL('n'):
8703 if (s->selected < s->ndisplayed - 1) {
8704 s->selected++;
8705 break;
8707 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8708 /* can't scroll any further */
8709 view->count = 0;
8710 break;
8712 ref_scroll_down(view, 1);
8713 break;
8714 case CTRL('d'):
8715 case 'd':
8716 nscroll /= 2;
8717 /* FALL THROUGH */
8718 case KEY_NPAGE:
8719 case CTRL('f'):
8720 case 'f':
8721 case ' ':
8722 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8723 /* can't scroll any further; move cursor down */
8724 if (s->selected < s->ndisplayed - 1)
8725 s->selected += MIN(nscroll,
8726 s->ndisplayed - s->selected - 1);
8727 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8728 s->selected += s->ndisplayed - s->selected - 1;
8729 view->count = 0;
8730 break;
8732 ref_scroll_down(view, nscroll);
8733 break;
8734 case CTRL('l'):
8735 view->count = 0;
8736 tog_free_refs();
8737 err = tog_load_refs(s->repo, s->sort_by_date);
8738 if (err)
8739 break;
8740 ref_view_free_refs(s);
8741 err = ref_view_load_refs(s);
8742 break;
8743 case KEY_RESIZE:
8744 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8745 s->selected = view->nlines - 2;
8746 break;
8747 default:
8748 view->count = 0;
8749 break;
8752 return err;
8755 __dead static void
8756 usage_ref(void)
8758 endwin();
8759 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8760 getprogname());
8761 exit(1);
8764 static const struct got_error *
8765 cmd_ref(int argc, char *argv[])
8767 const struct got_error *error;
8768 struct got_repository *repo = NULL;
8769 struct got_worktree *worktree = NULL;
8770 char *cwd = NULL, *repo_path = NULL;
8771 int ch;
8772 struct tog_view *view;
8773 int *pack_fds = NULL;
8775 while ((ch = getopt(argc, argv, "r:")) != -1) {
8776 switch (ch) {
8777 case 'r':
8778 repo_path = realpath(optarg, NULL);
8779 if (repo_path == NULL)
8780 return got_error_from_errno2("realpath",
8781 optarg);
8782 break;
8783 default:
8784 usage_ref();
8785 /* NOTREACHED */
8789 argc -= optind;
8790 argv += optind;
8792 if (argc > 1)
8793 usage_ref();
8795 error = got_repo_pack_fds_open(&pack_fds);
8796 if (error != NULL)
8797 goto done;
8799 if (repo_path == NULL) {
8800 cwd = getcwd(NULL, 0);
8801 if (cwd == NULL)
8802 return got_error_from_errno("getcwd");
8803 error = got_worktree_open(&worktree, cwd);
8804 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8805 goto done;
8806 if (worktree)
8807 repo_path =
8808 strdup(got_worktree_get_repo_path(worktree));
8809 else
8810 repo_path = strdup(cwd);
8811 if (repo_path == NULL) {
8812 error = got_error_from_errno("strdup");
8813 goto done;
8817 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8818 if (error != NULL)
8819 goto done;
8821 init_curses();
8823 error = apply_unveil(got_repo_get_path(repo), NULL);
8824 if (error)
8825 goto done;
8827 error = tog_load_refs(repo, 0);
8828 if (error)
8829 goto done;
8831 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8832 if (view == NULL) {
8833 error = got_error_from_errno("view_open");
8834 goto done;
8837 error = open_ref_view(view, repo);
8838 if (error)
8839 goto done;
8841 if (worktree) {
8842 /* Release work tree lock. */
8843 got_worktree_close(worktree);
8844 worktree = NULL;
8846 error = view_loop(view);
8847 done:
8848 free(repo_path);
8849 free(cwd);
8850 if (repo) {
8851 const struct got_error *close_err = got_repo_close(repo);
8852 if (close_err)
8853 error = close_err;
8855 if (pack_fds) {
8856 const struct got_error *pack_err =
8857 got_repo_pack_fds_close(pack_fds);
8858 if (error == NULL)
8859 error = pack_err;
8861 tog_free_refs();
8862 return error;
8865 static const struct got_error*
8866 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8867 const char *str)
8869 size_t len;
8871 if (win == NULL)
8872 win = stdscr;
8874 len = strlen(str);
8875 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8877 if (focus)
8878 wstandout(win);
8879 if (mvwprintw(win, y, x, "%s", str) == ERR)
8880 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8881 if (focus)
8882 wstandend(win);
8884 return NULL;
8887 static const struct got_error *
8888 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8890 off_t *p;
8892 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8893 if (p == NULL) {
8894 free(*line_offsets);
8895 *line_offsets = NULL;
8896 return got_error_from_errno("reallocarray");
8899 *line_offsets = p;
8900 (*line_offsets)[*nlines] = off;
8901 ++(*nlines);
8902 return NULL;
8905 static const struct got_error *
8906 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8908 *ret = 0;
8910 for (;n > 0; --n, ++km) {
8911 char *t0, *t, *k;
8912 size_t len = 1;
8914 if (km->keys == NULL)
8915 continue;
8917 t = t0 = strdup(km->keys);
8918 if (t0 == NULL)
8919 return got_error_from_errno("strdup");
8921 len += strlen(t);
8922 while ((k = strsep(&t, " ")) != NULL)
8923 len += strlen(k) > 1 ? 2 : 0;
8924 free(t0);
8925 *ret = MAX(*ret, len);
8928 return NULL;
8932 * Write keymap section headers, keys, and key info in km to f.
8933 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8934 * wrap control and symbolic keys in guillemets, else use <>.
8936 static const struct got_error *
8937 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8939 int n, len = width;
8941 if (km->keys) {
8942 static const char *u8_glyph[] = {
8943 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8944 "\xe2\x80\xba" /* U+203A (utf8 >) */
8946 char *t0, *t, *k;
8947 int cs, s, first = 1;
8949 cs = got_locale_is_utf8();
8951 t = t0 = strdup(km->keys);
8952 if (t0 == NULL)
8953 return got_error_from_errno("strdup");
8955 len = strlen(km->keys);
8956 while ((k = strsep(&t, " ")) != NULL) {
8957 s = strlen(k) > 1; /* control or symbolic key */
8958 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8959 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8960 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8961 if (n < 0) {
8962 free(t0);
8963 return got_error_from_errno("fprintf");
8965 first = 0;
8966 len += s ? 2 : 0;
8967 *off += n;
8969 free(t0);
8971 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8972 if (n < 0)
8973 return got_error_from_errno("fprintf");
8974 *off += n;
8976 return NULL;
8979 static const struct got_error *
8980 format_help(struct tog_help_view_state *s)
8982 const struct got_error *err = NULL;
8983 off_t off = 0;
8984 int i, max, n, show = s->all;
8985 static const struct tog_key_map km[] = {
8986 #define KEYMAP_(info, type) { NULL, (info), type }
8987 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8988 GENERATE_HELP
8989 #undef KEYMAP_
8990 #undef KEY_
8993 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8994 if (err)
8995 return err;
8997 n = nitems(km);
8998 err = max_key_str(&max, km, n);
8999 if (err)
9000 return err;
9002 for (i = 0; i < n; ++i) {
9003 if (km[i].keys == NULL) {
9004 show = s->all;
9005 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9006 km[i].type == s->type || s->all)
9007 show = 1;
9009 if (show) {
9010 err = format_help_line(&off, s->f, &km[i], max);
9011 if (err)
9012 return err;
9013 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9014 if (err)
9015 return err;
9018 fputc('\n', s->f);
9019 ++off;
9020 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9021 return err;
9024 static const struct got_error *
9025 create_help(struct tog_help_view_state *s)
9027 FILE *f;
9028 const struct got_error *err;
9030 free(s->line_offsets);
9031 s->line_offsets = NULL;
9032 s->nlines = 0;
9034 f = got_opentemp();
9035 if (f == NULL)
9036 return got_error_from_errno("got_opentemp");
9037 s->f = f;
9039 err = format_help(s);
9040 if (err)
9041 return err;
9043 if (s->f && fflush(s->f) != 0)
9044 return got_error_from_errno("fflush");
9046 return NULL;
9049 static const struct got_error *
9050 search_start_help_view(struct tog_view *view)
9052 view->state.help.matched_line = 0;
9053 return NULL;
9056 static void
9057 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9058 size_t *nlines, int **first, int **last, int **match, int **selected)
9060 struct tog_help_view_state *s = &view->state.help;
9062 *f = s->f;
9063 *nlines = s->nlines;
9064 *line_offsets = s->line_offsets;
9065 *match = &s->matched_line;
9066 *first = &s->first_displayed_line;
9067 *last = &s->last_displayed_line;
9068 *selected = &s->selected_line;
9071 static const struct got_error *
9072 show_help_view(struct tog_view *view)
9074 struct tog_help_view_state *s = &view->state.help;
9075 const struct got_error *err;
9076 regmatch_t *regmatch = &view->regmatch;
9077 wchar_t *wline;
9078 char *line;
9079 ssize_t linelen;
9080 size_t linesz = 0;
9081 int width, nprinted = 0, rc = 0;
9082 int eos = view->nlines;
9084 if (view_is_hsplit_top(view))
9085 --eos; /* account for border */
9087 s->lineno = 0;
9088 rewind(s->f);
9089 werase(view->window);
9091 if (view->gline > s->nlines - 1)
9092 view->gline = s->nlines - 1;
9094 err = win_draw_center(view->window, 0, 0, view->ncols,
9095 view_needs_focus_indication(view),
9096 "tog help (press q to return to tog)");
9097 if (err)
9098 return err;
9099 if (eos <= 1)
9100 return NULL;
9101 waddstr(view->window, "\n\n");
9102 eos -= 2;
9104 s->eof = 0;
9105 view->maxx = 0;
9106 line = NULL;
9107 while (eos > 0 && nprinted < eos) {
9108 attr_t attr = 0;
9110 linelen = getline(&line, &linesz, s->f);
9111 if (linelen == -1) {
9112 if (!feof(s->f)) {
9113 free(line);
9114 return got_ferror(s->f, GOT_ERR_IO);
9116 s->eof = 1;
9117 break;
9119 if (++s->lineno < s->first_displayed_line)
9120 continue;
9121 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9122 continue;
9123 if (s->lineno == view->hiline)
9124 attr = A_STANDOUT;
9126 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9127 view->x ? 1 : 0);
9128 if (err) {
9129 free(line);
9130 return err;
9132 view->maxx = MAX(view->maxx, width);
9133 free(wline);
9134 wline = NULL;
9136 if (attr)
9137 wattron(view->window, attr);
9138 if (s->first_displayed_line + nprinted == s->matched_line &&
9139 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9140 err = add_matched_line(&width, line, view->ncols - 1, 0,
9141 view->window, view->x, regmatch);
9142 if (err) {
9143 free(line);
9144 return err;
9146 } else {
9147 int skip;
9149 err = format_line(&wline, &width, &skip, line,
9150 view->x, view->ncols, 0, view->x ? 1 : 0);
9151 if (err) {
9152 free(line);
9153 return err;
9155 waddwstr(view->window, &wline[skip]);
9156 free(wline);
9157 wline = NULL;
9159 if (s->lineno == view->hiline) {
9160 while (width++ < view->ncols)
9161 waddch(view->window, ' ');
9162 } else {
9163 if (width < view->ncols)
9164 waddch(view->window, '\n');
9166 if (attr)
9167 wattroff(view->window, attr);
9168 if (++nprinted == 1)
9169 s->first_displayed_line = s->lineno;
9171 free(line);
9172 if (nprinted > 0)
9173 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9174 else
9175 s->last_displayed_line = s->first_displayed_line;
9177 view_border(view);
9179 if (s->eof) {
9180 rc = waddnstr(view->window,
9181 "See the tog(1) manual page for full documentation",
9182 view->ncols - 1);
9183 if (rc == ERR)
9184 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9185 } else {
9186 wmove(view->window, view->nlines - 1, 0);
9187 wclrtoeol(view->window);
9188 wstandout(view->window);
9189 rc = waddnstr(view->window, "scroll down for more...",
9190 view->ncols - 1);
9191 if (rc == ERR)
9192 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9193 if (getcurx(view->window) < view->ncols - 6) {
9194 rc = wprintw(view->window, "[%.0f%%]",
9195 100.00 * s->last_displayed_line / s->nlines);
9196 if (rc == ERR)
9197 return got_error_msg(GOT_ERR_IO, "wprintw");
9199 wstandend(view->window);
9202 return NULL;
9205 static const struct got_error *
9206 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9208 struct tog_help_view_state *s = &view->state.help;
9209 const struct got_error *err = NULL;
9210 char *line = NULL;
9211 ssize_t linelen;
9212 size_t linesz = 0;
9213 int eos, nscroll;
9215 eos = nscroll = view->nlines;
9216 if (view_is_hsplit_top(view))
9217 --eos; /* border */
9219 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9221 switch (ch) {
9222 case '0':
9223 case '$':
9224 case KEY_RIGHT:
9225 case 'l':
9226 case KEY_LEFT:
9227 case 'h':
9228 horizontal_scroll_input(view, ch);
9229 break;
9230 case 'g':
9231 case KEY_HOME:
9232 s->first_displayed_line = 1;
9233 view->count = 0;
9234 break;
9235 case 'G':
9236 case KEY_END:
9237 view->count = 0;
9238 if (s->eof)
9239 break;
9240 s->first_displayed_line = (s->nlines - eos) + 3;
9241 s->eof = 1;
9242 break;
9243 case 'k':
9244 case KEY_UP:
9245 if (s->first_displayed_line > 1)
9246 --s->first_displayed_line;
9247 else
9248 view->count = 0;
9249 break;
9250 case CTRL('u'):
9251 case 'u':
9252 nscroll /= 2;
9253 /* FALL THROUGH */
9254 case KEY_PPAGE:
9255 case CTRL('b'):
9256 case 'b':
9257 if (s->first_displayed_line == 1) {
9258 view->count = 0;
9259 break;
9261 while (--nscroll > 0 && s->first_displayed_line > 1)
9262 s->first_displayed_line--;
9263 break;
9264 case 'j':
9265 case KEY_DOWN:
9266 case CTRL('n'):
9267 if (!s->eof)
9268 ++s->first_displayed_line;
9269 else
9270 view->count = 0;
9271 break;
9272 case CTRL('d'):
9273 case 'd':
9274 nscroll /= 2;
9275 /* FALL THROUGH */
9276 case KEY_NPAGE:
9277 case CTRL('f'):
9278 case 'f':
9279 case ' ':
9280 if (s->eof) {
9281 view->count = 0;
9282 break;
9284 while (!s->eof && --nscroll > 0) {
9285 linelen = getline(&line, &linesz, s->f);
9286 s->first_displayed_line++;
9287 if (linelen == -1) {
9288 if (feof(s->f))
9289 s->eof = 1;
9290 else
9291 err = got_ferror(s->f, GOT_ERR_IO);
9292 break;
9295 free(line);
9296 break;
9297 default:
9298 view->count = 0;
9299 break;
9302 return err;
9305 static const struct got_error *
9306 close_help_view(struct tog_view *view)
9308 struct tog_help_view_state *s = &view->state.help;
9310 free(s->line_offsets);
9311 s->line_offsets = NULL;
9312 if (fclose(s->f) == EOF)
9313 return got_error_from_errno("fclose");
9315 return NULL;
9318 static const struct got_error *
9319 reset_help_view(struct tog_view *view)
9321 struct tog_help_view_state *s = &view->state.help;
9324 if (s->f && fclose(s->f) == EOF)
9325 return got_error_from_errno("fclose");
9327 wclear(view->window);
9328 view->count = 0;
9329 view->x = 0;
9330 s->all = !s->all;
9331 s->first_displayed_line = 1;
9332 s->last_displayed_line = view->nlines;
9333 s->matched_line = 0;
9335 return create_help(s);
9338 static const struct got_error *
9339 open_help_view(struct tog_view *view, struct tog_view *parent)
9341 const struct got_error *err = NULL;
9342 struct tog_help_view_state *s = &view->state.help;
9344 s->type = (enum tog_keymap_type)parent->type;
9345 s->first_displayed_line = 1;
9346 s->last_displayed_line = view->nlines;
9347 s->selected_line = 1;
9349 view->show = show_help_view;
9350 view->input = input_help_view;
9351 view->reset = reset_help_view;
9352 view->close = close_help_view;
9353 view->search_start = search_start_help_view;
9354 view->search_setup = search_setup_help_view;
9355 view->search_next = search_next_view_match;
9357 err = create_help(s);
9358 return err;
9361 static const struct got_error *
9362 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9363 enum tog_view_type request, int y, int x)
9365 const struct got_error *err = NULL;
9367 *new_view = NULL;
9369 switch (request) {
9370 case TOG_VIEW_DIFF:
9371 if (view->type == TOG_VIEW_LOG) {
9372 struct tog_log_view_state *s = &view->state.log;
9374 err = open_diff_view_for_commit(new_view, y, x,
9375 s->selected_entry->commit, s->selected_entry->id,
9376 view, s->repo);
9377 } else
9378 return got_error_msg(GOT_ERR_NOT_IMPL,
9379 "parent/child view pair not supported");
9380 break;
9381 case TOG_VIEW_BLAME:
9382 if (view->type == TOG_VIEW_TREE) {
9383 struct tog_tree_view_state *s = &view->state.tree;
9385 err = blame_tree_entry(new_view, y, x,
9386 s->selected_entry, &s->parents, s->commit_id,
9387 s->repo);
9388 } else
9389 return got_error_msg(GOT_ERR_NOT_IMPL,
9390 "parent/child view pair not supported");
9391 break;
9392 case TOG_VIEW_LOG:
9393 if (view->type == TOG_VIEW_BLAME)
9394 err = log_annotated_line(new_view, y, x,
9395 view->state.blame.repo, view->state.blame.id_to_log);
9396 else if (view->type == TOG_VIEW_TREE)
9397 err = log_selected_tree_entry(new_view, y, x,
9398 &view->state.tree);
9399 else if (view->type == TOG_VIEW_REF)
9400 err = log_ref_entry(new_view, y, x,
9401 view->state.ref.selected_entry,
9402 view->state.ref.repo);
9403 else
9404 return got_error_msg(GOT_ERR_NOT_IMPL,
9405 "parent/child view pair not supported");
9406 break;
9407 case TOG_VIEW_TREE:
9408 if (view->type == TOG_VIEW_LOG)
9409 err = browse_commit_tree(new_view, y, x,
9410 view->state.log.selected_entry,
9411 view->state.log.in_repo_path,
9412 view->state.log.head_ref_name,
9413 view->state.log.repo);
9414 else if (view->type == TOG_VIEW_REF)
9415 err = browse_ref_tree(new_view, y, x,
9416 view->state.ref.selected_entry,
9417 view->state.ref.repo);
9418 else
9419 return got_error_msg(GOT_ERR_NOT_IMPL,
9420 "parent/child view pair not supported");
9421 break;
9422 case TOG_VIEW_REF:
9423 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9424 if (*new_view == NULL)
9425 return got_error_from_errno("view_open");
9426 if (view->type == TOG_VIEW_LOG)
9427 err = open_ref_view(*new_view, view->state.log.repo);
9428 else if (view->type == TOG_VIEW_TREE)
9429 err = open_ref_view(*new_view, view->state.tree.repo);
9430 else
9431 err = got_error_msg(GOT_ERR_NOT_IMPL,
9432 "parent/child view pair not supported");
9433 if (err)
9434 view_close(*new_view);
9435 break;
9436 case TOG_VIEW_HELP:
9437 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9438 if (*new_view == NULL)
9439 return got_error_from_errno("view_open");
9440 err = open_help_view(*new_view, view);
9441 if (err)
9442 view_close(*new_view);
9443 break;
9444 default:
9445 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9448 return err;
9452 * If view was scrolled down to move the selected line into view when opening a
9453 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9455 static void
9456 offset_selection_up(struct tog_view *view)
9458 switch (view->type) {
9459 case TOG_VIEW_BLAME: {
9460 struct tog_blame_view_state *s = &view->state.blame;
9461 if (s->first_displayed_line == 1) {
9462 s->selected_line = MAX(s->selected_line - view->offset,
9463 1);
9464 break;
9466 if (s->first_displayed_line > view->offset)
9467 s->first_displayed_line -= view->offset;
9468 else
9469 s->first_displayed_line = 1;
9470 s->selected_line += view->offset;
9471 break;
9473 case TOG_VIEW_LOG:
9474 log_scroll_up(&view->state.log, view->offset);
9475 view->state.log.selected += view->offset;
9476 break;
9477 case TOG_VIEW_REF:
9478 ref_scroll_up(&view->state.ref, view->offset);
9479 view->state.ref.selected += view->offset;
9480 break;
9481 case TOG_VIEW_TREE:
9482 tree_scroll_up(&view->state.tree, view->offset);
9483 view->state.tree.selected += view->offset;
9484 break;
9485 default:
9486 break;
9489 view->offset = 0;
9493 * If the selected line is in the section of screen covered by the bottom split,
9494 * scroll down offset lines to move it into view and index its new position.
9496 static const struct got_error *
9497 offset_selection_down(struct tog_view *view)
9499 const struct got_error *err = NULL;
9500 const struct got_error *(*scrolld)(struct tog_view *, int);
9501 int *selected = NULL;
9502 int header, offset;
9504 switch (view->type) {
9505 case TOG_VIEW_BLAME: {
9506 struct tog_blame_view_state *s = &view->state.blame;
9507 header = 3;
9508 scrolld = NULL;
9509 if (s->selected_line > view->nlines - header) {
9510 offset = abs(view->nlines - s->selected_line - header);
9511 s->first_displayed_line += offset;
9512 s->selected_line -= offset;
9513 view->offset = offset;
9515 break;
9517 case TOG_VIEW_LOG: {
9518 struct tog_log_view_state *s = &view->state.log;
9519 scrolld = &log_scroll_down;
9520 header = view_is_parent_view(view) ? 3 : 2;
9521 selected = &s->selected;
9522 break;
9524 case TOG_VIEW_REF: {
9525 struct tog_ref_view_state *s = &view->state.ref;
9526 scrolld = &ref_scroll_down;
9527 header = 3;
9528 selected = &s->selected;
9529 break;
9531 case TOG_VIEW_TREE: {
9532 struct tog_tree_view_state *s = &view->state.tree;
9533 scrolld = &tree_scroll_down;
9534 header = 5;
9535 selected = &s->selected;
9536 break;
9538 default:
9539 selected = NULL;
9540 scrolld = NULL;
9541 header = 0;
9542 break;
9545 if (selected && *selected > view->nlines - header) {
9546 offset = abs(view->nlines - *selected - header);
9547 view->offset = offset;
9548 if (scrolld && offset) {
9549 err = scrolld(view, offset);
9550 *selected -= offset;
9554 return err;
9557 static void
9558 list_commands(FILE *fp)
9560 size_t i;
9562 fprintf(fp, "commands:");
9563 for (i = 0; i < nitems(tog_commands); i++) {
9564 const struct tog_cmd *cmd = &tog_commands[i];
9565 fprintf(fp, " %s", cmd->name);
9567 fputc('\n', fp);
9570 __dead static void
9571 usage(int hflag, int status)
9573 FILE *fp = (status == 0) ? stdout : stderr;
9575 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9576 getprogname());
9577 if (hflag) {
9578 fprintf(fp, "lazy usage: %s path\n", getprogname());
9579 list_commands(fp);
9581 exit(status);
9584 static char **
9585 make_argv(int argc, ...)
9587 va_list ap;
9588 char **argv;
9589 int i;
9591 va_start(ap, argc);
9593 argv = calloc(argc, sizeof(char *));
9594 if (argv == NULL)
9595 err(1, "calloc");
9596 for (i = 0; i < argc; i++) {
9597 argv[i] = strdup(va_arg(ap, char *));
9598 if (argv[i] == NULL)
9599 err(1, "strdup");
9602 va_end(ap);
9603 return argv;
9607 * Try to convert 'tog path' into a 'tog log path' command.
9608 * The user could simply have mistyped the command rather than knowingly
9609 * provided a path. So check whether argv[0] can in fact be resolved
9610 * to a path in the HEAD commit and print a special error if not.
9611 * This hack is for mpi@ <3
9613 static const struct got_error *
9614 tog_log_with_path(int argc, char *argv[])
9616 const struct got_error *error = NULL, *close_err;
9617 const struct tog_cmd *cmd = NULL;
9618 struct got_repository *repo = NULL;
9619 struct got_worktree *worktree = NULL;
9620 struct got_object_id *commit_id = NULL, *id = NULL;
9621 struct got_commit_object *commit = NULL;
9622 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9623 char *commit_id_str = NULL, **cmd_argv = NULL;
9624 int *pack_fds = NULL;
9626 cwd = getcwd(NULL, 0);
9627 if (cwd == NULL)
9628 return got_error_from_errno("getcwd");
9630 error = got_repo_pack_fds_open(&pack_fds);
9631 if (error != NULL)
9632 goto done;
9634 error = got_worktree_open(&worktree, cwd);
9635 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9636 goto done;
9638 if (worktree)
9639 repo_path = strdup(got_worktree_get_repo_path(worktree));
9640 else
9641 repo_path = strdup(cwd);
9642 if (repo_path == NULL) {
9643 error = got_error_from_errno("strdup");
9644 goto done;
9647 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9648 if (error != NULL)
9649 goto done;
9651 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9652 repo, worktree);
9653 if (error)
9654 goto done;
9656 error = tog_load_refs(repo, 0);
9657 if (error)
9658 goto done;
9659 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9660 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9661 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9662 if (error)
9663 goto done;
9665 if (worktree) {
9666 got_worktree_close(worktree);
9667 worktree = NULL;
9670 error = got_object_open_as_commit(&commit, repo, commit_id);
9671 if (error)
9672 goto done;
9674 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9675 if (error) {
9676 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9677 goto done;
9678 fprintf(stderr, "%s: '%s' is no known command or path\n",
9679 getprogname(), argv[0]);
9680 usage(1, 1);
9681 /* not reached */
9684 error = got_object_id_str(&commit_id_str, commit_id);
9685 if (error)
9686 goto done;
9688 cmd = &tog_commands[0]; /* log */
9689 argc = 4;
9690 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9691 error = cmd->cmd_main(argc, cmd_argv);
9692 done:
9693 if (repo) {
9694 close_err = got_repo_close(repo);
9695 if (error == NULL)
9696 error = close_err;
9698 if (commit)
9699 got_object_commit_close(commit);
9700 if (worktree)
9701 got_worktree_close(worktree);
9702 if (pack_fds) {
9703 const struct got_error *pack_err =
9704 got_repo_pack_fds_close(pack_fds);
9705 if (error == NULL)
9706 error = pack_err;
9708 free(id);
9709 free(commit_id_str);
9710 free(commit_id);
9711 free(cwd);
9712 free(repo_path);
9713 free(in_repo_path);
9714 if (cmd_argv) {
9715 int i;
9716 for (i = 0; i < argc; i++)
9717 free(cmd_argv[i]);
9718 free(cmd_argv);
9720 tog_free_refs();
9721 return error;
9724 int
9725 main(int argc, char *argv[])
9727 const struct got_error *io_err, *error = NULL;
9728 const struct tog_cmd *cmd = NULL;
9729 int ch, hflag = 0, Vflag = 0;
9730 char **cmd_argv = NULL;
9731 static const struct option longopts[] = {
9732 { "version", no_argument, NULL, 'V' },
9733 { NULL, 0, NULL, 0}
9735 char *diff_algo_str = NULL;
9736 const char *test_script_path;
9738 setlocale(LC_CTYPE, "");
9741 * Test mode init must happen before pledge() because "tty" will
9742 * not allow TTY-related ioctls to occur via regular files.
9744 test_script_path = getenv("GOT_TOG_TEST");
9745 if (test_script_path != NULL) {
9746 error = init_mock_term(test_script_path);
9747 if (error) {
9748 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9749 return 1;
9753 #if !defined(PROFILE)
9754 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9755 NULL) == -1)
9756 err(1, "pledge");
9757 #endif
9759 if (!isatty(STDIN_FILENO))
9760 errx(1, "standard input is not a tty");
9762 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9763 switch (ch) {
9764 case 'h':
9765 hflag = 1;
9766 break;
9767 case 'V':
9768 Vflag = 1;
9769 break;
9770 default:
9771 usage(hflag, 1);
9772 /* NOTREACHED */
9776 argc -= optind;
9777 argv += optind;
9778 optind = 1;
9779 optreset = 1;
9781 if (Vflag) {
9782 got_version_print_str();
9783 return 0;
9786 if (argc == 0) {
9787 if (hflag)
9788 usage(hflag, 0);
9789 /* Build an argument vector which runs a default command. */
9790 cmd = &tog_commands[0];
9791 argc = 1;
9792 cmd_argv = make_argv(argc, cmd->name);
9793 } else {
9794 size_t i;
9796 /* Did the user specify a command? */
9797 for (i = 0; i < nitems(tog_commands); i++) {
9798 if (strncmp(tog_commands[i].name, argv[0],
9799 strlen(argv[0])) == 0) {
9800 cmd = &tog_commands[i];
9801 break;
9806 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9807 if (diff_algo_str) {
9808 if (strcasecmp(diff_algo_str, "patience") == 0)
9809 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9810 if (strcasecmp(diff_algo_str, "myers") == 0)
9811 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9814 if (cmd == NULL) {
9815 if (argc != 1)
9816 usage(0, 1);
9817 /* No command specified; try log with a path */
9818 error = tog_log_with_path(argc, argv);
9819 } else {
9820 if (hflag)
9821 cmd->cmd_usage();
9822 else
9823 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9826 if (using_mock_io) {
9827 io_err = tog_io_close();
9828 if (error == NULL)
9829 error = io_err;
9831 endwin();
9832 if (cmd_argv) {
9833 int i;
9834 for (i = 0; i < argc; i++)
9835 free(cmd_argv[i]);
9836 free(cmd_argv);
9839 if (error && error->code != GOT_ERR_CANCELLED &&
9840 error->code != GOT_ERR_EOF &&
9841 error->code != GOT_ERR_PRIVSEP_EXIT &&
9842 error->code != GOT_ERR_PRIVSEP_PIPE &&
9843 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9844 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9845 return 0;