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 };
625 #define TOG_SCREEN_DUMP "SCREENDUMP"
626 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
627 #define TOG_KEY_SCRDUMP SHRT_MIN
629 /*
630 * We implement two types of views: parent views and child views.
632 * The 'Tab' key switches focus between a parent view and its child view.
633 * Child views are shown side-by-side to their parent view, provided
634 * there is enough screen estate.
636 * When a new view is opened from within a parent view, this new view
637 * becomes a child view of the parent view, replacing any existing child.
639 * When a new view is opened from within a child view, this new view
640 * becomes a parent view which will obscure the views below until the
641 * user quits the new parent view by typing 'q'.
643 * This list of views contains parent views only.
644 * Child views are only pointed to by their parent view.
645 */
646 TAILQ_HEAD(tog_view_list_head, tog_view);
648 struct tog_view {
649 TAILQ_ENTRY(tog_view) entry;
650 WINDOW *window;
651 PANEL *panel;
652 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
653 int resized_y, resized_x; /* begin_y/x based on user resizing */
654 int maxx, x; /* max column and current start column */
655 int lines, cols; /* copies of LINES and COLS */
656 int nscrolled, offset; /* lines scrolled and hsplit line offset */
657 int gline, hiline; /* navigate to and highlight this nG line */
658 int ch, count; /* current keymap and count prefix */
659 int resized; /* set when in a resize event */
660 int focussed; /* Only set on one parent or child view at a time. */
661 int dying;
662 struct tog_view *parent;
663 struct tog_view *child;
665 /*
666 * This flag is initially set on parent views when a new child view
667 * is created. It gets toggled when the 'Tab' key switches focus
668 * between parent and child.
669 * The flag indicates whether focus should be passed on to our child
670 * view if this parent view gets picked for focus after another parent
671 * view was closed. This prevents child views from losing focus in such
672 * situations.
673 */
674 int focus_child;
676 enum tog_view_mode mode;
677 /* type-specific state */
678 enum tog_view_type type;
679 union {
680 struct tog_diff_view_state diff;
681 struct tog_log_view_state log;
682 struct tog_blame_view_state blame;
683 struct tog_tree_view_state tree;
684 struct tog_ref_view_state ref;
685 struct tog_help_view_state help;
686 } state;
688 const struct got_error *(*show)(struct tog_view *);
689 const struct got_error *(*input)(struct tog_view **,
690 struct tog_view *, int);
691 const struct got_error *(*reset)(struct tog_view *);
692 const struct got_error *(*resize)(struct tog_view *, int);
693 const struct got_error *(*close)(struct tog_view *);
695 const struct got_error *(*search_start)(struct tog_view *);
696 const struct got_error *(*search_next)(struct tog_view *);
697 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
698 int **, int **, int **, int **);
699 int search_started;
700 int searching;
701 #define TOG_SEARCH_FORWARD 1
702 #define TOG_SEARCH_BACKWARD 2
703 int search_next_done;
704 #define TOG_SEARCH_HAVE_MORE 1
705 #define TOG_SEARCH_NO_MORE 2
706 #define TOG_SEARCH_HAVE_NONE 3
707 regex_t regex;
708 regmatch_t regmatch;
709 const char *action;
710 };
712 static const struct got_error *open_diff_view(struct tog_view *,
713 struct got_object_id *, struct got_object_id *,
714 const char *, const char *, int, int, int, struct tog_view *,
715 struct got_repository *);
716 static const struct got_error *show_diff_view(struct tog_view *);
717 static const struct got_error *input_diff_view(struct tog_view **,
718 struct tog_view *, int);
719 static const struct got_error *reset_diff_view(struct tog_view *);
720 static const struct got_error* close_diff_view(struct tog_view *);
721 static const struct got_error *search_start_diff_view(struct tog_view *);
722 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
723 size_t *, int **, int **, int **, int **);
724 static const struct got_error *search_next_view_match(struct tog_view *);
726 static const struct got_error *open_log_view(struct tog_view *,
727 struct got_object_id *, struct got_repository *,
728 const char *, const char *, int);
729 static const struct got_error * show_log_view(struct tog_view *);
730 static const struct got_error *input_log_view(struct tog_view **,
731 struct tog_view *, int);
732 static const struct got_error *resize_log_view(struct tog_view *, int);
733 static const struct got_error *close_log_view(struct tog_view *);
734 static const struct got_error *search_start_log_view(struct tog_view *);
735 static const struct got_error *search_next_log_view(struct tog_view *);
737 static const struct got_error *open_blame_view(struct tog_view *, char *,
738 struct got_object_id *, struct got_repository *);
739 static const struct got_error *show_blame_view(struct tog_view *);
740 static const struct got_error *input_blame_view(struct tog_view **,
741 struct tog_view *, int);
742 static const struct got_error *reset_blame_view(struct tog_view *);
743 static const struct got_error *close_blame_view(struct tog_view *);
744 static const struct got_error *search_start_blame_view(struct tog_view *);
745 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
746 size_t *, int **, int **, int **, int **);
748 static const struct got_error *open_tree_view(struct tog_view *,
749 struct got_object_id *, const char *, struct got_repository *);
750 static const struct got_error *show_tree_view(struct tog_view *);
751 static const struct got_error *input_tree_view(struct tog_view **,
752 struct tog_view *, int);
753 static const struct got_error *close_tree_view(struct tog_view *);
754 static const struct got_error *search_start_tree_view(struct tog_view *);
755 static const struct got_error *search_next_tree_view(struct tog_view *);
757 static const struct got_error *open_ref_view(struct tog_view *,
758 struct got_repository *);
759 static const struct got_error *show_ref_view(struct tog_view *);
760 static const struct got_error *input_ref_view(struct tog_view **,
761 struct tog_view *, int);
762 static const struct got_error *close_ref_view(struct tog_view *);
763 static const struct got_error *search_start_ref_view(struct tog_view *);
764 static const struct got_error *search_next_ref_view(struct tog_view *);
766 static const struct got_error *open_help_view(struct tog_view *,
767 struct tog_view *);
768 static const struct got_error *show_help_view(struct tog_view *);
769 static const struct got_error *input_help_view(struct tog_view **,
770 struct tog_view *, int);
771 static const struct got_error *reset_help_view(struct tog_view *);
772 static const struct got_error* close_help_view(struct tog_view *);
773 static const struct got_error *search_start_help_view(struct tog_view *);
774 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
775 size_t *, int **, int **, int **, int **);
777 static volatile sig_atomic_t tog_sigwinch_received;
778 static volatile sig_atomic_t tog_sigpipe_received;
779 static volatile sig_atomic_t tog_sigcont_received;
780 static volatile sig_atomic_t tog_sigint_received;
781 static volatile sig_atomic_t tog_sigterm_received;
783 static void
784 tog_sigwinch(int signo)
786 tog_sigwinch_received = 1;
789 static void
790 tog_sigpipe(int signo)
792 tog_sigpipe_received = 1;
795 static void
796 tog_sigcont(int signo)
798 tog_sigcont_received = 1;
801 static void
802 tog_sigint(int signo)
804 tog_sigint_received = 1;
807 static void
808 tog_sigterm(int signo)
810 tog_sigterm_received = 1;
813 static int
814 tog_fatal_signal_received(void)
816 return (tog_sigpipe_received ||
817 tog_sigint_received || tog_sigterm_received);
820 static const struct got_error *
821 view_close(struct tog_view *view)
823 const struct got_error *err = NULL, *child_err = NULL;
825 if (view->child) {
826 child_err = view_close(view->child);
827 view->child = NULL;
829 if (view->close)
830 err = view->close(view);
831 if (view->panel)
832 del_panel(view->panel);
833 if (view->window)
834 delwin(view->window);
835 free(view);
836 return err ? err : child_err;
839 static struct tog_view *
840 view_open(int nlines, int ncols, int begin_y, int begin_x,
841 enum tog_view_type type)
843 struct tog_view *view = calloc(1, sizeof(*view));
845 if (view == NULL)
846 return NULL;
848 view->type = type;
849 view->lines = LINES;
850 view->cols = COLS;
851 view->nlines = nlines ? nlines : LINES - begin_y;
852 view->ncols = ncols ? ncols : COLS - begin_x;
853 view->begin_y = begin_y;
854 view->begin_x = begin_x;
855 view->window = newwin(nlines, ncols, begin_y, begin_x);
856 if (view->window == NULL) {
857 view_close(view);
858 return NULL;
860 view->panel = new_panel(view->window);
861 if (view->panel == NULL ||
862 set_panel_userptr(view->panel, view) != OK) {
863 view_close(view);
864 return NULL;
867 keypad(view->window, TRUE);
868 return view;
871 static int
872 view_split_begin_x(int begin_x)
874 if (begin_x > 0 || COLS < 120)
875 return 0;
876 return (COLS - MAX(COLS / 2, 80));
879 /* XXX Stub till we decide what to do. */
880 static int
881 view_split_begin_y(int lines)
883 return lines * HSPLIT_SCALE;
886 static const struct got_error *view_resize(struct tog_view *);
888 static const struct got_error *
889 view_splitscreen(struct tog_view *view)
891 const struct got_error *err = NULL;
893 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
894 if (view->resized_y && view->resized_y < view->lines)
895 view->begin_y = view->resized_y;
896 else
897 view->begin_y = view_split_begin_y(view->nlines);
898 view->begin_x = 0;
899 } else if (!view->resized) {
900 if (view->resized_x && view->resized_x < view->cols - 1 &&
901 view->cols > 119)
902 view->begin_x = view->resized_x;
903 else
904 view->begin_x = view_split_begin_x(0);
905 view->begin_y = 0;
907 view->nlines = LINES - view->begin_y;
908 view->ncols = COLS - view->begin_x;
909 view->lines = LINES;
910 view->cols = COLS;
911 err = view_resize(view);
912 if (err)
913 return err;
915 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
916 view->parent->nlines = view->begin_y;
918 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
919 return got_error_from_errno("mvwin");
921 return NULL;
924 static const struct got_error *
925 view_fullscreen(struct tog_view *view)
927 const struct got_error *err = NULL;
929 view->begin_x = 0;
930 view->begin_y = view->resized ? view->begin_y : 0;
931 view->nlines = view->resized ? view->nlines : LINES;
932 view->ncols = COLS;
933 view->lines = LINES;
934 view->cols = COLS;
935 err = view_resize(view);
936 if (err)
937 return err;
939 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
940 return got_error_from_errno("mvwin");
942 return NULL;
945 static int
946 view_is_parent_view(struct tog_view *view)
948 return view->parent == NULL;
951 static int
952 view_is_splitscreen(struct tog_view *view)
954 return view->begin_x > 0 || view->begin_y > 0;
957 static int
958 view_is_fullscreen(struct tog_view *view)
960 return view->nlines == LINES && view->ncols == COLS;
963 static int
964 view_is_hsplit_top(struct tog_view *view)
966 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
967 view_is_splitscreen(view->child);
970 static void
971 view_border(struct tog_view *view)
973 PANEL *panel;
974 const struct tog_view *view_above;
976 if (view->parent)
977 return view_border(view->parent);
979 panel = panel_above(view->panel);
980 if (panel == NULL)
981 return;
983 view_above = panel_userptr(panel);
984 if (view->mode == TOG_VIEW_SPLIT_HRZN)
985 mvwhline(view->window, view_above->begin_y - 1,
986 view->begin_x, got_locale_is_utf8() ?
987 ACS_HLINE : '-', view->ncols);
988 else
989 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
990 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
993 static const struct got_error *view_init_hsplit(struct tog_view *, int);
994 static const struct got_error *request_log_commits(struct tog_view *);
995 static const struct got_error *offset_selection_down(struct tog_view *);
996 static void offset_selection_up(struct tog_view *);
997 static void view_get_split(struct tog_view *, int *, int *);
999 static const struct got_error *
1000 view_resize(struct tog_view *view)
1002 const struct got_error *err = NULL;
1003 int dif, nlines, ncols;
1005 dif = LINES - view->lines; /* line difference */
1007 if (view->lines > LINES)
1008 nlines = view->nlines - (view->lines - LINES);
1009 else
1010 nlines = view->nlines + (LINES - view->lines);
1011 if (view->cols > COLS)
1012 ncols = view->ncols - (view->cols - COLS);
1013 else
1014 ncols = view->ncols + (COLS - view->cols);
1016 if (view->child) {
1017 int hs = view->child->begin_y;
1019 if (!view_is_fullscreen(view))
1020 view->child->begin_x = view_split_begin_x(view->begin_x);
1021 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1022 view->child->begin_x == 0) {
1023 ncols = COLS;
1025 view_fullscreen(view->child);
1026 if (view->child->focussed)
1027 show_panel(view->child->panel);
1028 else
1029 show_panel(view->panel);
1030 } else {
1031 ncols = view->child->begin_x;
1033 view_splitscreen(view->child);
1034 show_panel(view->child->panel);
1037 * XXX This is ugly and needs to be moved into the above
1038 * logic but "works" for now and my attempts at moving it
1039 * break either 'tab' or 'F' key maps in horizontal splits.
1041 if (hs) {
1042 err = view_splitscreen(view->child);
1043 if (err)
1044 return err;
1045 if (dif < 0) { /* top split decreased */
1046 err = offset_selection_down(view);
1047 if (err)
1048 return err;
1050 view_border(view);
1051 update_panels();
1052 doupdate();
1053 show_panel(view->child->panel);
1054 nlines = view->nlines;
1056 } else if (view->parent == NULL)
1057 ncols = COLS;
1059 if (view->resize && dif > 0) {
1060 err = view->resize(view, dif);
1061 if (err)
1062 return err;
1065 if (wresize(view->window, nlines, ncols) == ERR)
1066 return got_error_from_errno("wresize");
1067 if (replace_panel(view->panel, view->window) == ERR)
1068 return got_error_from_errno("replace_panel");
1069 wclear(view->window);
1071 view->nlines = nlines;
1072 view->ncols = ncols;
1073 view->lines = LINES;
1074 view->cols = COLS;
1076 return NULL;
1079 static const struct got_error *
1080 resize_log_view(struct tog_view *view, int increase)
1082 struct tog_log_view_state *s = &view->state.log;
1083 const struct got_error *err = NULL;
1084 int n = 0;
1086 if (s->selected_entry)
1087 n = s->selected_entry->idx + view->lines - s->selected;
1090 * Request commits to account for the increased
1091 * height so we have enough to populate the view.
1093 if (s->commits->ncommits < n) {
1094 view->nscrolled = n - s->commits->ncommits + increase + 1;
1095 err = request_log_commits(view);
1098 return err;
1101 static void
1102 view_adjust_offset(struct tog_view *view, int n)
1104 if (n == 0)
1105 return;
1107 if (view->parent && view->parent->offset) {
1108 if (view->parent->offset + n >= 0)
1109 view->parent->offset += n;
1110 else
1111 view->parent->offset = 0;
1112 } else if (view->offset) {
1113 if (view->offset - n >= 0)
1114 view->offset -= n;
1115 else
1116 view->offset = 0;
1120 static const struct got_error *
1121 view_resize_split(struct tog_view *view, int resize)
1123 const struct got_error *err = NULL;
1124 struct tog_view *v = NULL;
1126 if (view->parent)
1127 v = view->parent;
1128 else
1129 v = view;
1131 if (!v->child || !view_is_splitscreen(v->child))
1132 return NULL;
1134 v->resized = v->child->resized = resize; /* lock for resize event */
1136 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1137 if (v->child->resized_y)
1138 v->child->begin_y = v->child->resized_y;
1139 if (view->parent)
1140 v->child->begin_y -= resize;
1141 else
1142 v->child->begin_y += resize;
1143 if (v->child->begin_y < 3) {
1144 view->count = 0;
1145 v->child->begin_y = 3;
1146 } else if (v->child->begin_y > LINES - 1) {
1147 view->count = 0;
1148 v->child->begin_y = LINES - 1;
1150 v->ncols = COLS;
1151 v->child->ncols = COLS;
1152 view_adjust_offset(view, resize);
1153 err = view_init_hsplit(v, v->child->begin_y);
1154 if (err)
1155 return err;
1156 v->child->resized_y = v->child->begin_y;
1157 } else {
1158 if (v->child->resized_x)
1159 v->child->begin_x = v->child->resized_x;
1160 if (view->parent)
1161 v->child->begin_x -= resize;
1162 else
1163 v->child->begin_x += resize;
1164 if (v->child->begin_x < 11) {
1165 view->count = 0;
1166 v->child->begin_x = 11;
1167 } else if (v->child->begin_x > COLS - 1) {
1168 view->count = 0;
1169 v->child->begin_x = COLS - 1;
1171 v->child->resized_x = v->child->begin_x;
1174 v->child->mode = v->mode;
1175 v->child->nlines = v->lines - v->child->begin_y;
1176 v->child->ncols = v->cols - v->child->begin_x;
1177 v->focus_child = 1;
1179 err = view_fullscreen(v);
1180 if (err)
1181 return err;
1182 err = view_splitscreen(v->child);
1183 if (err)
1184 return err;
1186 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1187 err = offset_selection_down(v->child);
1188 if (err)
1189 return err;
1192 if (v->resize)
1193 err = v->resize(v, 0);
1194 else if (v->child->resize)
1195 err = v->child->resize(v->child, 0);
1197 v->resized = v->child->resized = 0;
1199 return err;
1202 static void
1203 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1205 struct tog_view *v = src->child ? src->child : src;
1207 dst->resized_x = v->resized_x;
1208 dst->resized_y = v->resized_y;
1211 static const struct got_error *
1212 view_close_child(struct tog_view *view)
1214 const struct got_error *err = NULL;
1216 if (view->child == NULL)
1217 return NULL;
1219 err = view_close(view->child);
1220 view->child = NULL;
1221 return err;
1224 static const struct got_error *
1225 view_set_child(struct tog_view *view, struct tog_view *child)
1227 const struct got_error *err = NULL;
1229 view->child = child;
1230 child->parent = view;
1232 err = view_resize(view);
1233 if (err)
1234 return err;
1236 if (view->child->resized_x || view->child->resized_y)
1237 err = view_resize_split(view, 0);
1239 return err;
1242 static const struct got_error *view_dispatch_request(struct tog_view **,
1243 struct tog_view *, enum tog_view_type, int, int);
1245 static const struct got_error *
1246 view_request_new(struct tog_view **requested, struct tog_view *view,
1247 enum tog_view_type request)
1249 struct tog_view *new_view = NULL;
1250 const struct got_error *err;
1251 int y = 0, x = 0;
1253 *requested = NULL;
1255 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1256 view_get_split(view, &y, &x);
1258 err = view_dispatch_request(&new_view, view, request, y, x);
1259 if (err)
1260 return err;
1262 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1263 request != TOG_VIEW_HELP) {
1264 err = view_init_hsplit(view, y);
1265 if (err)
1266 return err;
1269 view->focussed = 0;
1270 new_view->focussed = 1;
1271 new_view->mode = view->mode;
1272 new_view->nlines = request == TOG_VIEW_HELP ?
1273 view->lines : view->lines - y;
1275 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1276 view_transfer_size(new_view, view);
1277 err = view_close_child(view);
1278 if (err)
1279 return err;
1280 err = view_set_child(view, new_view);
1281 if (err)
1282 return err;
1283 view->focus_child = 1;
1284 } else
1285 *requested = new_view;
1287 return NULL;
1290 static void
1291 tog_resizeterm(void)
1293 int cols, lines;
1294 struct winsize size;
1296 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1297 cols = 80; /* Default */
1298 lines = 24;
1299 } else {
1300 cols = size.ws_col;
1301 lines = size.ws_row;
1303 resize_term(lines, cols);
1306 static const struct got_error *
1307 view_search_start(struct tog_view *view, int fast_refresh)
1309 const struct got_error *err = NULL;
1310 struct tog_view *v = view;
1311 char pattern[1024];
1312 int ret;
1314 if (view->search_started) {
1315 regfree(&view->regex);
1316 view->searching = 0;
1317 memset(&view->regmatch, 0, sizeof(view->regmatch));
1319 view->search_started = 0;
1321 if (view->nlines < 1)
1322 return NULL;
1324 if (view_is_hsplit_top(view))
1325 v = view->child;
1326 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1327 v = view->parent;
1329 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1330 wclrtoeol(v->window);
1332 nodelay(v->window, FALSE); /* block for search term input */
1333 nocbreak();
1334 echo();
1335 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1336 wrefresh(v->window);
1337 cbreak();
1338 noecho();
1339 nodelay(v->window, TRUE);
1340 if (!fast_refresh)
1341 halfdelay(10);
1342 if (ret == ERR)
1343 return NULL;
1345 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1346 err = view->search_start(view);
1347 if (err) {
1348 regfree(&view->regex);
1349 return err;
1351 view->search_started = 1;
1352 view->searching = TOG_SEARCH_FORWARD;
1353 view->search_next_done = 0;
1354 view->search_next(view);
1357 return NULL;
1360 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1361 static const struct got_error *
1362 switch_split(struct tog_view *view)
1364 const struct got_error *err = NULL;
1365 struct tog_view *v = NULL;
1367 if (view->parent)
1368 v = view->parent;
1369 else
1370 v = view;
1372 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1373 v->mode = TOG_VIEW_SPLIT_VERT;
1374 else
1375 v->mode = TOG_VIEW_SPLIT_HRZN;
1377 if (!v->child)
1378 return NULL;
1379 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1380 v->mode = TOG_VIEW_SPLIT_NONE;
1382 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1383 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1384 v->child->begin_y = v->child->resized_y;
1385 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1386 v->child->begin_x = v->child->resized_x;
1389 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1390 v->ncols = COLS;
1391 v->child->ncols = COLS;
1392 v->child->nscrolled = LINES - v->child->nlines;
1394 err = view_init_hsplit(v, v->child->begin_y);
1395 if (err)
1396 return err;
1398 v->child->mode = v->mode;
1399 v->child->nlines = v->lines - v->child->begin_y;
1400 v->focus_child = 1;
1402 err = view_fullscreen(v);
1403 if (err)
1404 return err;
1405 err = view_splitscreen(v->child);
1406 if (err)
1407 return err;
1409 if (v->mode == TOG_VIEW_SPLIT_NONE)
1410 v->mode = TOG_VIEW_SPLIT_VERT;
1411 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1412 err = offset_selection_down(v);
1413 if (err)
1414 return err;
1415 err = offset_selection_down(v->child);
1416 if (err)
1417 return err;
1418 } else {
1419 offset_selection_up(v);
1420 offset_selection_up(v->child);
1422 if (v->resize)
1423 err = v->resize(v, 0);
1424 else if (v->child->resize)
1425 err = v->child->resize(v->child, 0);
1427 return err;
1431 * Strip trailing whitespace from str starting at byte *n;
1432 * if *n < 0, use strlen(str). Return new str length in *n.
1434 static void
1435 strip_trailing_ws(char *str, int *n)
1437 size_t x = *n;
1439 if (str == NULL || *str == '\0')
1440 return;
1442 if (x < 0)
1443 x = strlen(str);
1445 while (x-- > 0 && isspace((unsigned char)str[x]))
1446 str[x] = '\0';
1448 *n = x + 1;
1452 * Extract visible substring of line y from the curses screen
1453 * and strip trailing whitespace. If vline is set and locale is
1454 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1455 * character is written out as 'x'. Write the line to file f.
1457 static const struct got_error *
1458 view_write_line(FILE *f, int y, int vline)
1460 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1461 int r, w;
1463 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1464 if (r == ERR)
1465 return got_error_fmt(GOT_ERR_RANGE,
1466 "failed to extract line %d", y);
1469 * In some views, lines are padded with blanks to COLS width.
1470 * Strip them so we can diff without the -b flag when testing.
1472 strip_trailing_ws(line, &r);
1474 if (vline > 0 && got_locale_is_utf8())
1475 line[vline] = '|';
1477 w = fprintf(f, "%s\n", line);
1478 if (w != r + 1) /* \n */
1479 return got_ferror(f, GOT_ERR_IO);
1481 return NULL;
1485 * Capture the visible curses screen by writing each line to the
1486 * file at the path set via the TOG_SCR_DUMP environment variable.
1488 static const struct got_error *
1489 screendump(struct tog_view *view)
1491 const struct got_error *err;
1492 FILE *f = NULL;
1493 const char *path;
1494 int i;
1496 path = getenv("TOG_SCR_DUMP");
1497 if (path == NULL || *path == '\0')
1498 return got_error_msg(GOT_ERR_BAD_PATH,
1499 "TOG_SCR_DUMP path not set to capture screen dump");
1500 f = fopen(path, "wex");
1501 if (f == NULL)
1502 return got_error_from_errno_fmt("fopen: %s", path);
1504 if ((view->child && view->child->begin_x) ||
1505 (view->parent && view->begin_x)) {
1506 int ncols = view->child ? view->ncols : view->parent->ncols;
1508 /* vertical splitscreen */
1509 for (i = 0; i < view->nlines; ++i) {
1510 err = view_write_line(f, i, ncols - 1);
1511 if (err)
1512 goto done;
1514 } else {
1515 int hline = 0;
1517 /* fullscreen or horizontal splitscreen */
1518 if ((view->child && view->child->begin_y) ||
1519 (view->parent && view->begin_y)) /* hsplit */
1520 hline = view->child ?
1521 view->child->begin_y : view->begin_y;
1523 for (i = 0; i < view->lines; i++) {
1524 if (hline && got_locale_is_utf8() && i == hline - 1) {
1525 int c;
1527 /* ACS_HLINE writes out as 'q', overwrite it */
1528 for (c = 0; c < view->cols; ++c)
1529 fputc('-', f);
1530 fputc('\n', f);
1531 continue;
1534 err = view_write_line(f, i, 0);
1535 if (err)
1536 goto done;
1540 done:
1541 if (f && fclose(f) == EOF && err == NULL)
1542 err = got_ferror(f, GOT_ERR_IO);
1543 return err;
1547 * Compute view->count from numeric input. Assign total to view->count and
1548 * return first non-numeric key entered.
1550 static int
1551 get_compound_key(struct tog_view *view, int c)
1553 struct tog_view *v = view;
1554 int x, n = 0;
1556 if (view_is_hsplit_top(view))
1557 v = view->child;
1558 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1559 v = view->parent;
1561 view->count = 0;
1562 cbreak(); /* block for input */
1563 nodelay(view->window, FALSE);
1564 wmove(v->window, v->nlines - 1, 0);
1565 wclrtoeol(v->window);
1566 waddch(v->window, ':');
1568 do {
1569 x = getcurx(v->window);
1570 if (x != ERR && x < view->ncols) {
1571 waddch(v->window, c);
1572 wrefresh(v->window);
1576 * Don't overflow. Max valid request should be the greatest
1577 * between the longest and total lines; cap at 10 million.
1579 if (n >= 9999999)
1580 n = 9999999;
1581 else
1582 n = n * 10 + (c - '0');
1583 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1585 if (c == 'G' || c == 'g') { /* nG key map */
1586 view->gline = view->hiline = n;
1587 n = 0;
1588 c = 0;
1591 /* Massage excessive or inapplicable values at the input handler. */
1592 view->count = n;
1594 return c;
1597 static void
1598 action_report(struct tog_view *view)
1600 struct tog_view *v = view;
1602 if (view_is_hsplit_top(view))
1603 v = view->child;
1604 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1605 v = view->parent;
1607 wmove(v->window, v->nlines - 1, 0);
1608 wclrtoeol(v->window);
1609 wprintw(v->window, ":%s", view->action);
1610 wrefresh(v->window);
1613 * Clear action status report. Only clear in blame view
1614 * once annotating is complete, otherwise it's too fast.
1616 if (view->type == TOG_VIEW_BLAME) {
1617 if (view->state.blame.blame_complete)
1618 view->action = NULL;
1619 } else
1620 view->action = NULL;
1624 * Read the next line from the test script and assign
1625 * key instruction to *ch. If at EOF, set the *done flag.
1627 static const struct got_error *
1628 tog_read_script_key(FILE *script, int *ch, int *done)
1630 const struct got_error *err = NULL;
1631 char *line = NULL;
1632 size_t linesz = 0;
1634 if (getline(&line, &linesz, script) == -1) {
1635 if (feof(script)) {
1636 *done = 1;
1637 goto done;
1638 } else {
1639 err = got_ferror(script, GOT_ERR_IO);
1640 goto done;
1642 } else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1643 *ch = KEY_ENTER;
1644 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1645 *ch = KEY_RIGHT;
1646 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1647 *ch = KEY_LEFT;
1648 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1649 *ch = KEY_DOWN;
1650 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1651 *ch = KEY_UP;
1652 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1653 *ch = TOG_KEY_SCRDUMP;
1654 else
1655 *ch = *line;
1657 done:
1658 free(line);
1659 return err;
1662 static const struct got_error *
1663 view_input(struct tog_view **new, int *done, struct tog_view *view,
1664 struct tog_view_list_head *views, struct tog_io *tog_io, int fast_refresh)
1666 const struct got_error *err = NULL;
1667 struct tog_view *v;
1668 int ch, errcode;
1670 *new = NULL;
1672 if (view->action)
1673 action_report(view);
1675 /* Clear "no matches" indicator. */
1676 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1677 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1678 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1679 view->count = 0;
1682 if (view->searching && !view->search_next_done) {
1683 errcode = pthread_mutex_unlock(&tog_mutex);
1684 if (errcode)
1685 return got_error_set_errno(errcode,
1686 "pthread_mutex_unlock");
1687 sched_yield();
1688 errcode = pthread_mutex_lock(&tog_mutex);
1689 if (errcode)
1690 return got_error_set_errno(errcode,
1691 "pthread_mutex_lock");
1692 view->search_next(view);
1693 return NULL;
1696 /* Allow threads to make progress while we are waiting for input. */
1697 errcode = pthread_mutex_unlock(&tog_mutex);
1698 if (errcode)
1699 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1701 if (tog_io && tog_io->f) {
1702 err = tog_read_script_key(tog_io->f, &ch, done);
1703 if (err)
1704 return err;
1705 } else if (view->count && --view->count) {
1706 cbreak();
1707 nodelay(view->window, TRUE);
1708 ch = wgetch(view->window);
1709 /* let C-g or backspace abort unfinished count */
1710 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1711 view->count = 0;
1712 else
1713 ch = view->ch;
1714 } else {
1715 ch = wgetch(view->window);
1716 if (ch >= '1' && ch <= '9')
1717 view->ch = ch = get_compound_key(view, ch);
1719 if (view->hiline && ch != ERR && ch != 0)
1720 view->hiline = 0; /* key pressed, clear line highlight */
1721 nodelay(view->window, TRUE);
1722 errcode = pthread_mutex_lock(&tog_mutex);
1723 if (errcode)
1724 return got_error_set_errno(errcode, "pthread_mutex_lock");
1726 if (tog_sigwinch_received || tog_sigcont_received) {
1727 tog_resizeterm();
1728 tog_sigwinch_received = 0;
1729 tog_sigcont_received = 0;
1730 TAILQ_FOREACH(v, views, entry) {
1731 err = view_resize(v);
1732 if (err)
1733 return err;
1734 err = v->input(new, v, KEY_RESIZE);
1735 if (err)
1736 return err;
1737 if (v->child) {
1738 err = view_resize(v->child);
1739 if (err)
1740 return err;
1741 err = v->child->input(new, v->child,
1742 KEY_RESIZE);
1743 if (err)
1744 return err;
1745 if (v->child->resized_x || v->child->resized_y) {
1746 err = view_resize_split(v, 0);
1747 if (err)
1748 return err;
1754 switch (ch) {
1755 case '?':
1756 case 'H':
1757 case KEY_F(1):
1758 if (view->type == TOG_VIEW_HELP)
1759 err = view->reset(view);
1760 else
1761 err = view_request_new(new, view, TOG_VIEW_HELP);
1762 break;
1763 case '\t':
1764 view->count = 0;
1765 if (view->child) {
1766 view->focussed = 0;
1767 view->child->focussed = 1;
1768 view->focus_child = 1;
1769 } else if (view->parent) {
1770 view->focussed = 0;
1771 view->parent->focussed = 1;
1772 view->parent->focus_child = 0;
1773 if (!view_is_splitscreen(view)) {
1774 if (view->parent->resize) {
1775 err = view->parent->resize(view->parent,
1776 0);
1777 if (err)
1778 return err;
1780 offset_selection_up(view->parent);
1781 err = view_fullscreen(view->parent);
1782 if (err)
1783 return err;
1786 break;
1787 case 'q':
1788 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1789 if (view->parent->resize) {
1790 /* might need more commits to fill fullscreen */
1791 err = view->parent->resize(view->parent, 0);
1792 if (err)
1793 break;
1795 offset_selection_up(view->parent);
1797 err = view->input(new, view, ch);
1798 view->dying = 1;
1799 break;
1800 case 'Q':
1801 *done = 1;
1802 break;
1803 case 'F':
1804 view->count = 0;
1805 if (view_is_parent_view(view)) {
1806 if (view->child == NULL)
1807 break;
1808 if (view_is_splitscreen(view->child)) {
1809 view->focussed = 0;
1810 view->child->focussed = 1;
1811 err = view_fullscreen(view->child);
1812 } else {
1813 err = view_splitscreen(view->child);
1814 if (!err)
1815 err = view_resize_split(view, 0);
1817 if (err)
1818 break;
1819 err = view->child->input(new, view->child,
1820 KEY_RESIZE);
1821 } else {
1822 if (view_is_splitscreen(view)) {
1823 view->parent->focussed = 0;
1824 view->focussed = 1;
1825 err = view_fullscreen(view);
1826 } else {
1827 err = view_splitscreen(view);
1828 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1829 err = view_resize(view->parent);
1830 if (!err)
1831 err = view_resize_split(view, 0);
1833 if (err)
1834 break;
1835 err = view->input(new, view, KEY_RESIZE);
1837 if (err)
1838 break;
1839 if (view->resize) {
1840 err = view->resize(view, 0);
1841 if (err)
1842 break;
1844 if (view->parent)
1845 err = offset_selection_down(view->parent);
1846 if (!err)
1847 err = offset_selection_down(view);
1848 break;
1849 case 'S':
1850 view->count = 0;
1851 err = switch_split(view);
1852 break;
1853 case '-':
1854 err = view_resize_split(view, -1);
1855 break;
1856 case '+':
1857 err = view_resize_split(view, 1);
1858 break;
1859 case KEY_RESIZE:
1860 break;
1861 case '/':
1862 view->count = 0;
1863 if (view->search_start)
1864 view_search_start(view, fast_refresh);
1865 else
1866 err = view->input(new, view, ch);
1867 break;
1868 case 'N':
1869 case 'n':
1870 if (view->search_started && view->search_next) {
1871 view->searching = (ch == 'n' ?
1872 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1873 view->search_next_done = 0;
1874 view->search_next(view);
1875 } else
1876 err = view->input(new, view, ch);
1877 break;
1878 case 'A':
1879 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1880 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1881 view->action = "Patience diff algorithm";
1882 } else {
1883 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1884 view->action = "Myers diff algorithm";
1886 TAILQ_FOREACH(v, views, entry) {
1887 if (v->reset) {
1888 err = v->reset(v);
1889 if (err)
1890 return err;
1892 if (v->child && v->child->reset) {
1893 err = v->child->reset(v->child);
1894 if (err)
1895 return err;
1898 break;
1899 case TOG_KEY_SCRDUMP:
1900 err = screendump(view);
1901 break;
1902 default:
1903 err = view->input(new, view, ch);
1904 break;
1907 return err;
1910 static int
1911 view_needs_focus_indication(struct tog_view *view)
1913 if (view_is_parent_view(view)) {
1914 if (view->child == NULL || view->child->focussed)
1915 return 0;
1916 if (!view_is_splitscreen(view->child))
1917 return 0;
1918 } else if (!view_is_splitscreen(view))
1919 return 0;
1921 return view->focussed;
1924 static const struct got_error *
1925 tog_io_close(struct tog_io *tog_io)
1927 const struct got_error *err = NULL;
1929 if (tog_io->cin && fclose(tog_io->cin) == EOF)
1930 err = got_ferror(tog_io->cin, GOT_ERR_IO);
1931 if (tog_io->cout && fclose(tog_io->cout) == EOF && err == NULL)
1932 err = got_ferror(tog_io->cout, GOT_ERR_IO);
1933 if (tog_io->f && fclose(tog_io->f) == EOF && err == NULL)
1934 err = got_ferror(tog_io->f, GOT_ERR_IO);
1935 free(tog_io);
1936 tog_io = NULL;
1938 return err;
1941 static const struct got_error *
1942 view_loop(struct tog_view *view, struct tog_io *tog_io)
1944 const struct got_error *err = NULL;
1945 struct tog_view_list_head views;
1946 struct tog_view *new_view;
1947 char *mode;
1948 int fast_refresh = 10;
1949 int done = 0, errcode;
1951 mode = getenv("TOG_VIEW_SPLIT_MODE");
1952 if (!mode || !(*mode == 'h' || *mode == 'H'))
1953 view->mode = TOG_VIEW_SPLIT_VERT;
1954 else
1955 view->mode = TOG_VIEW_SPLIT_HRZN;
1957 errcode = pthread_mutex_lock(&tog_mutex);
1958 if (errcode)
1959 return got_error_set_errno(errcode, "pthread_mutex_lock");
1961 TAILQ_INIT(&views);
1962 TAILQ_INSERT_HEAD(&views, view, entry);
1964 view->focussed = 1;
1965 err = view->show(view);
1966 if (err)
1967 return err;
1968 update_panels();
1969 doupdate();
1970 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1971 !tog_fatal_signal_received()) {
1972 /* Refresh fast during initialization, then become slower. */
1973 if (fast_refresh && --fast_refresh == 0)
1974 halfdelay(10); /* switch to once per second */
1976 err = view_input(&new_view, &done, view, &views, tog_io,
1977 fast_refresh);
1978 if (err)
1979 break;
1981 if (view->dying && view == TAILQ_FIRST(&views) &&
1982 TAILQ_NEXT(view, entry) == NULL)
1983 done = 1;
1984 if (done) {
1985 struct tog_view *v;
1988 * When we quit, scroll the screen up a single line
1989 * so we don't lose any information.
1991 TAILQ_FOREACH(v, &views, entry) {
1992 wmove(v->window, 0, 0);
1993 wdeleteln(v->window);
1994 wnoutrefresh(v->window);
1995 if (v->child && !view_is_fullscreen(v)) {
1996 wmove(v->child->window, 0, 0);
1997 wdeleteln(v->child->window);
1998 wnoutrefresh(v->child->window);
2001 doupdate();
2004 if (view->dying) {
2005 struct tog_view *v, *prev = NULL;
2007 if (view_is_parent_view(view))
2008 prev = TAILQ_PREV(view, tog_view_list_head,
2009 entry);
2010 else if (view->parent)
2011 prev = view->parent;
2013 if (view->parent) {
2014 view->parent->child = NULL;
2015 view->parent->focus_child = 0;
2016 /* Restore fullscreen line height. */
2017 view->parent->nlines = view->parent->lines;
2018 err = view_resize(view->parent);
2019 if (err)
2020 break;
2021 /* Make resized splits persist. */
2022 view_transfer_size(view->parent, view);
2023 } else
2024 TAILQ_REMOVE(&views, view, entry);
2026 err = view_close(view);
2027 if (err)
2028 goto done;
2030 view = NULL;
2031 TAILQ_FOREACH(v, &views, entry) {
2032 if (v->focussed)
2033 break;
2035 if (view == NULL && new_view == NULL) {
2036 /* No view has focus. Try to pick one. */
2037 if (prev)
2038 view = prev;
2039 else if (!TAILQ_EMPTY(&views)) {
2040 view = TAILQ_LAST(&views,
2041 tog_view_list_head);
2043 if (view) {
2044 if (view->focus_child) {
2045 view->child->focussed = 1;
2046 view = view->child;
2047 } else
2048 view->focussed = 1;
2052 if (new_view) {
2053 struct tog_view *v, *t;
2054 /* Only allow one parent view per type. */
2055 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2056 if (v->type != new_view->type)
2057 continue;
2058 TAILQ_REMOVE(&views, v, entry);
2059 err = view_close(v);
2060 if (err)
2061 goto done;
2062 break;
2064 TAILQ_INSERT_TAIL(&views, new_view, entry);
2065 view = new_view;
2067 if (view && !done) {
2068 if (view_is_parent_view(view)) {
2069 if (view->child && view->child->focussed)
2070 view = view->child;
2071 } else {
2072 if (view->parent && view->parent->focussed)
2073 view = view->parent;
2075 show_panel(view->panel);
2076 if (view->child && view_is_splitscreen(view->child))
2077 show_panel(view->child->panel);
2078 if (view->parent && view_is_splitscreen(view)) {
2079 err = view->parent->show(view->parent);
2080 if (err)
2081 goto done;
2083 err = view->show(view);
2084 if (err)
2085 goto done;
2086 if (view->child) {
2087 err = view->child->show(view->child);
2088 if (err)
2089 goto done;
2091 update_panels();
2092 doupdate();
2095 done:
2096 while (!TAILQ_EMPTY(&views)) {
2097 const struct got_error *close_err;
2098 view = TAILQ_FIRST(&views);
2099 TAILQ_REMOVE(&views, view, entry);
2100 close_err = view_close(view);
2101 if (close_err && err == NULL)
2102 err = close_err;
2105 errcode = pthread_mutex_unlock(&tog_mutex);
2106 if (errcode && err == NULL)
2107 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2109 return err;
2112 __dead static void
2113 usage_log(void)
2115 endwin();
2116 fprintf(stderr,
2117 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2118 getprogname());
2119 exit(1);
2122 /* Create newly allocated wide-character string equivalent to a byte string. */
2123 static const struct got_error *
2124 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2126 char *vis = NULL;
2127 const struct got_error *err = NULL;
2129 *ws = NULL;
2130 *wlen = mbstowcs(NULL, s, 0);
2131 if (*wlen == (size_t)-1) {
2132 int vislen;
2133 if (errno != EILSEQ)
2134 return got_error_from_errno("mbstowcs");
2136 /* byte string invalid in current encoding; try to "fix" it */
2137 err = got_mbsavis(&vis, &vislen, s);
2138 if (err)
2139 return err;
2140 *wlen = mbstowcs(NULL, vis, 0);
2141 if (*wlen == (size_t)-1) {
2142 err = got_error_from_errno("mbstowcs"); /* give up */
2143 goto done;
2147 *ws = calloc(*wlen + 1, sizeof(**ws));
2148 if (*ws == NULL) {
2149 err = got_error_from_errno("calloc");
2150 goto done;
2153 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2154 err = got_error_from_errno("mbstowcs");
2155 done:
2156 free(vis);
2157 if (err) {
2158 free(*ws);
2159 *ws = NULL;
2160 *wlen = 0;
2162 return err;
2165 static const struct got_error *
2166 expand_tab(char **ptr, const char *src)
2168 char *dst;
2169 size_t len, n, idx = 0, sz = 0;
2171 *ptr = NULL;
2172 n = len = strlen(src);
2173 dst = malloc(n + 1);
2174 if (dst == NULL)
2175 return got_error_from_errno("malloc");
2177 while (idx < len && src[idx]) {
2178 const char c = src[idx];
2180 if (c == '\t') {
2181 size_t nb = TABSIZE - sz % TABSIZE;
2182 char *p;
2184 p = realloc(dst, n + nb);
2185 if (p == NULL) {
2186 free(dst);
2187 return got_error_from_errno("realloc");
2190 dst = p;
2191 n += nb;
2192 memset(dst + sz, ' ', nb);
2193 sz += nb;
2194 } else
2195 dst[sz++] = src[idx];
2196 ++idx;
2199 dst[sz] = '\0';
2200 *ptr = dst;
2201 return NULL;
2205 * Advance at most n columns from wline starting at offset off.
2206 * Return the index to the first character after the span operation.
2207 * Return the combined column width of all spanned wide character in
2208 * *rcol.
2210 static int
2211 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2213 int width, i, cols = 0;
2215 if (n == 0) {
2216 *rcol = cols;
2217 return off;
2220 for (i = off; wline[i] != L'\0'; ++i) {
2221 if (wline[i] == L'\t')
2222 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2223 else
2224 width = wcwidth(wline[i]);
2226 if (width == -1) {
2227 width = 1;
2228 wline[i] = L'.';
2231 if (cols + width > n)
2232 break;
2233 cols += width;
2236 *rcol = cols;
2237 return i;
2241 * Format a line for display, ensuring that it won't overflow a width limit.
2242 * With scrolling, the width returned refers to the scrolled version of the
2243 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2245 static const struct got_error *
2246 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2247 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2249 const struct got_error *err = NULL;
2250 int cols;
2251 wchar_t *wline = NULL;
2252 char *exstr = NULL;
2253 size_t wlen;
2254 int i, scrollx;
2256 *wlinep = NULL;
2257 *widthp = 0;
2259 if (expand) {
2260 err = expand_tab(&exstr, line);
2261 if (err)
2262 return err;
2265 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2266 free(exstr);
2267 if (err)
2268 return err;
2270 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2272 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2273 wline[wlen - 1] = L'\0';
2274 wlen--;
2276 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2277 wline[wlen - 1] = L'\0';
2278 wlen--;
2281 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2282 wline[i] = L'\0';
2284 if (widthp)
2285 *widthp = cols;
2286 if (scrollxp)
2287 *scrollxp = scrollx;
2288 if (err)
2289 free(wline);
2290 else
2291 *wlinep = wline;
2292 return err;
2295 static const struct got_error*
2296 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2297 struct got_object_id *id, struct got_repository *repo)
2299 static const struct got_error *err = NULL;
2300 struct got_reflist_entry *re;
2301 char *s;
2302 const char *name;
2304 *refs_str = NULL;
2306 TAILQ_FOREACH(re, refs, entry) {
2307 struct got_tag_object *tag = NULL;
2308 struct got_object_id *ref_id;
2309 int cmp;
2311 name = got_ref_get_name(re->ref);
2312 if (strcmp(name, GOT_REF_HEAD) == 0)
2313 continue;
2314 if (strncmp(name, "refs/", 5) == 0)
2315 name += 5;
2316 if (strncmp(name, "got/", 4) == 0 &&
2317 strncmp(name, "got/backup/", 11) != 0)
2318 continue;
2319 if (strncmp(name, "heads/", 6) == 0)
2320 name += 6;
2321 if (strncmp(name, "remotes/", 8) == 0) {
2322 name += 8;
2323 s = strstr(name, "/" GOT_REF_HEAD);
2324 if (s != NULL && s[strlen(s)] == '\0')
2325 continue;
2327 err = got_ref_resolve(&ref_id, repo, re->ref);
2328 if (err)
2329 break;
2330 if (strncmp(name, "tags/", 5) == 0) {
2331 err = got_object_open_as_tag(&tag, repo, ref_id);
2332 if (err) {
2333 if (err->code != GOT_ERR_OBJ_TYPE) {
2334 free(ref_id);
2335 break;
2337 /* Ref points at something other than a tag. */
2338 err = NULL;
2339 tag = NULL;
2342 cmp = got_object_id_cmp(tag ?
2343 got_object_tag_get_object_id(tag) : ref_id, id);
2344 free(ref_id);
2345 if (tag)
2346 got_object_tag_close(tag);
2347 if (cmp != 0)
2348 continue;
2349 s = *refs_str;
2350 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2351 s ? ", " : "", name) == -1) {
2352 err = got_error_from_errno("asprintf");
2353 free(s);
2354 *refs_str = NULL;
2355 break;
2357 free(s);
2360 return err;
2363 static const struct got_error *
2364 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2365 int col_tab_align)
2367 char *smallerthan;
2369 smallerthan = strchr(author, '<');
2370 if (smallerthan && smallerthan[1] != '\0')
2371 author = smallerthan + 1;
2372 author[strcspn(author, "@>")] = '\0';
2373 return format_line(wauthor, author_width, NULL, author, 0, limit,
2374 col_tab_align, 0);
2377 static const struct got_error *
2378 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2379 struct got_object_id *id, const size_t date_display_cols,
2380 int author_display_cols)
2382 struct tog_log_view_state *s = &view->state.log;
2383 const struct got_error *err = NULL;
2384 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2385 char *logmsg0 = NULL, *logmsg = NULL;
2386 char *author = NULL;
2387 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2388 int author_width, logmsg_width;
2389 char *newline, *line = NULL;
2390 int col, limit, scrollx;
2391 const int avail = view->ncols;
2392 struct tm tm;
2393 time_t committer_time;
2394 struct tog_color *tc;
2396 committer_time = got_object_commit_get_committer_time(commit);
2397 if (gmtime_r(&committer_time, &tm) == NULL)
2398 return got_error_from_errno("gmtime_r");
2399 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2400 return got_error(GOT_ERR_NO_SPACE);
2402 if (avail <= date_display_cols)
2403 limit = MIN(sizeof(datebuf) - 1, avail);
2404 else
2405 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2406 tc = get_color(&s->colors, TOG_COLOR_DATE);
2407 if (tc)
2408 wattr_on(view->window,
2409 COLOR_PAIR(tc->colorpair), NULL);
2410 waddnstr(view->window, datebuf, limit);
2411 if (tc)
2412 wattr_off(view->window,
2413 COLOR_PAIR(tc->colorpair), NULL);
2414 col = limit;
2415 if (col > avail)
2416 goto done;
2418 if (avail >= 120) {
2419 char *id_str;
2420 err = got_object_id_str(&id_str, id);
2421 if (err)
2422 goto done;
2423 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2424 if (tc)
2425 wattr_on(view->window,
2426 COLOR_PAIR(tc->colorpair), NULL);
2427 wprintw(view->window, "%.8s ", id_str);
2428 if (tc)
2429 wattr_off(view->window,
2430 COLOR_PAIR(tc->colorpair), NULL);
2431 free(id_str);
2432 col += 9;
2433 if (col > avail)
2434 goto done;
2437 if (s->use_committer)
2438 author = strdup(got_object_commit_get_committer(commit));
2439 else
2440 author = strdup(got_object_commit_get_author(commit));
2441 if (author == NULL) {
2442 err = got_error_from_errno("strdup");
2443 goto done;
2445 err = format_author(&wauthor, &author_width, author, avail - col, col);
2446 if (err)
2447 goto done;
2448 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2449 if (tc)
2450 wattr_on(view->window,
2451 COLOR_PAIR(tc->colorpair), NULL);
2452 waddwstr(view->window, wauthor);
2453 col += author_width;
2454 while (col < avail && author_width < author_display_cols + 2) {
2455 waddch(view->window, ' ');
2456 col++;
2457 author_width++;
2459 if (tc)
2460 wattr_off(view->window,
2461 COLOR_PAIR(tc->colorpair), NULL);
2462 if (col > avail)
2463 goto done;
2465 err = got_object_commit_get_logmsg(&logmsg0, commit);
2466 if (err)
2467 goto done;
2468 logmsg = logmsg0;
2469 while (*logmsg == '\n')
2470 logmsg++;
2471 newline = strchr(logmsg, '\n');
2472 if (newline)
2473 *newline = '\0';
2474 limit = avail - col;
2475 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2476 limit--; /* for the border */
2477 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2478 limit, col, 1);
2479 if (err)
2480 goto done;
2481 waddwstr(view->window, &wlogmsg[scrollx]);
2482 col += MAX(logmsg_width, 0);
2483 while (col < avail) {
2484 waddch(view->window, ' ');
2485 col++;
2487 done:
2488 free(logmsg0);
2489 free(wlogmsg);
2490 free(author);
2491 free(wauthor);
2492 free(line);
2493 return err;
2496 static struct commit_queue_entry *
2497 alloc_commit_queue_entry(struct got_commit_object *commit,
2498 struct got_object_id *id)
2500 struct commit_queue_entry *entry;
2501 struct got_object_id *dup;
2503 entry = calloc(1, sizeof(*entry));
2504 if (entry == NULL)
2505 return NULL;
2507 dup = got_object_id_dup(id);
2508 if (dup == NULL) {
2509 free(entry);
2510 return NULL;
2513 entry->id = dup;
2514 entry->commit = commit;
2515 return entry;
2518 static void
2519 pop_commit(struct commit_queue *commits)
2521 struct commit_queue_entry *entry;
2523 entry = TAILQ_FIRST(&commits->head);
2524 TAILQ_REMOVE(&commits->head, entry, entry);
2525 got_object_commit_close(entry->commit);
2526 commits->ncommits--;
2527 free(entry->id);
2528 free(entry);
2531 static void
2532 free_commits(struct commit_queue *commits)
2534 while (!TAILQ_EMPTY(&commits->head))
2535 pop_commit(commits);
2538 static const struct got_error *
2539 match_commit(int *have_match, struct got_object_id *id,
2540 struct got_commit_object *commit, regex_t *regex)
2542 const struct got_error *err = NULL;
2543 regmatch_t regmatch;
2544 char *id_str = NULL, *logmsg = NULL;
2546 *have_match = 0;
2548 err = got_object_id_str(&id_str, id);
2549 if (err)
2550 return err;
2552 err = got_object_commit_get_logmsg(&logmsg, commit);
2553 if (err)
2554 goto done;
2556 if (regexec(regex, got_object_commit_get_author(commit), 1,
2557 &regmatch, 0) == 0 ||
2558 regexec(regex, got_object_commit_get_committer(commit), 1,
2559 &regmatch, 0) == 0 ||
2560 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2561 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2562 *have_match = 1;
2563 done:
2564 free(id_str);
2565 free(logmsg);
2566 return err;
2569 static const struct got_error *
2570 queue_commits(struct tog_log_thread_args *a)
2572 const struct got_error *err = NULL;
2575 * We keep all commits open throughout the lifetime of the log
2576 * view in order to avoid having to re-fetch commits from disk
2577 * while updating the display.
2579 do {
2580 struct got_object_id id;
2581 struct got_commit_object *commit;
2582 struct commit_queue_entry *entry;
2583 int limit_match = 0;
2584 int errcode;
2586 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2587 NULL, NULL);
2588 if (err)
2589 break;
2591 err = got_object_open_as_commit(&commit, a->repo, &id);
2592 if (err)
2593 break;
2594 entry = alloc_commit_queue_entry(commit, &id);
2595 if (entry == NULL) {
2596 err = got_error_from_errno("alloc_commit_queue_entry");
2597 break;
2600 errcode = pthread_mutex_lock(&tog_mutex);
2601 if (errcode) {
2602 err = got_error_set_errno(errcode,
2603 "pthread_mutex_lock");
2604 break;
2607 entry->idx = a->real_commits->ncommits;
2608 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2609 a->real_commits->ncommits++;
2611 if (*a->limiting) {
2612 err = match_commit(&limit_match, &id, commit,
2613 a->limit_regex);
2614 if (err)
2615 break;
2617 if (limit_match) {
2618 struct commit_queue_entry *matched;
2620 matched = alloc_commit_queue_entry(
2621 entry->commit, entry->id);
2622 if (matched == NULL) {
2623 err = got_error_from_errno(
2624 "alloc_commit_queue_entry");
2625 break;
2627 matched->commit = entry->commit;
2628 got_object_commit_retain(entry->commit);
2630 matched->idx = a->limit_commits->ncommits;
2631 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2632 matched, entry);
2633 a->limit_commits->ncommits++;
2637 * This is how we signal log_thread() that we
2638 * have found a match, and that it should be
2639 * counted as a new entry for the view.
2641 a->limit_match = limit_match;
2644 if (*a->searching == TOG_SEARCH_FORWARD &&
2645 !*a->search_next_done) {
2646 int have_match;
2647 err = match_commit(&have_match, &id, commit, a->regex);
2648 if (err)
2649 break;
2651 if (*a->limiting) {
2652 if (limit_match && have_match)
2653 *a->search_next_done =
2654 TOG_SEARCH_HAVE_MORE;
2655 } else if (have_match)
2656 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2659 errcode = pthread_mutex_unlock(&tog_mutex);
2660 if (errcode && err == NULL)
2661 err = got_error_set_errno(errcode,
2662 "pthread_mutex_unlock");
2663 if (err)
2664 break;
2665 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2667 return err;
2670 static void
2671 select_commit(struct tog_log_view_state *s)
2673 struct commit_queue_entry *entry;
2674 int ncommits = 0;
2676 entry = s->first_displayed_entry;
2677 while (entry) {
2678 if (ncommits == s->selected) {
2679 s->selected_entry = entry;
2680 break;
2682 entry = TAILQ_NEXT(entry, entry);
2683 ncommits++;
2687 static const struct got_error *
2688 draw_commits(struct tog_view *view)
2690 const struct got_error *err = NULL;
2691 struct tog_log_view_state *s = &view->state.log;
2692 struct commit_queue_entry *entry = s->selected_entry;
2693 int limit = view->nlines;
2694 int width;
2695 int ncommits, author_cols = 4;
2696 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2697 char *refs_str = NULL;
2698 wchar_t *wline;
2699 struct tog_color *tc;
2700 static const size_t date_display_cols = 12;
2702 if (view_is_hsplit_top(view))
2703 --limit; /* account for border */
2705 if (s->selected_entry &&
2706 !(view->searching && view->search_next_done == 0)) {
2707 struct got_reflist_head *refs;
2708 err = got_object_id_str(&id_str, s->selected_entry->id);
2709 if (err)
2710 return err;
2711 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2712 s->selected_entry->id);
2713 if (refs) {
2714 err = build_refs_str(&refs_str, refs,
2715 s->selected_entry->id, s->repo);
2716 if (err)
2717 goto done;
2721 if (s->thread_args.commits_needed == 0)
2722 halfdelay(10); /* disable fast refresh */
2724 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2725 if (asprintf(&ncommits_str, " [%d/%d] %s",
2726 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2727 (view->searching && !view->search_next_done) ?
2728 "searching..." : "loading...") == -1) {
2729 err = got_error_from_errno("asprintf");
2730 goto done;
2732 } else {
2733 const char *search_str = NULL;
2734 const char *limit_str = NULL;
2736 if (view->searching) {
2737 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2738 search_str = "no more matches";
2739 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2740 search_str = "no matches found";
2741 else if (!view->search_next_done)
2742 search_str = "searching...";
2745 if (s->limit_view && s->commits->ncommits == 0)
2746 limit_str = "no matches found";
2748 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2749 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2750 search_str ? search_str : (refs_str ? refs_str : ""),
2751 limit_str ? limit_str : "") == -1) {
2752 err = got_error_from_errno("asprintf");
2753 goto done;
2757 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2758 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2759 "........................................",
2760 s->in_repo_path, ncommits_str) == -1) {
2761 err = got_error_from_errno("asprintf");
2762 header = NULL;
2763 goto done;
2765 } else if (asprintf(&header, "commit %s%s",
2766 id_str ? id_str : "........................................",
2767 ncommits_str) == -1) {
2768 err = got_error_from_errno("asprintf");
2769 header = NULL;
2770 goto done;
2772 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2773 if (err)
2774 goto done;
2776 werase(view->window);
2778 if (view_needs_focus_indication(view))
2779 wstandout(view->window);
2780 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2781 if (tc)
2782 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2783 waddwstr(view->window, wline);
2784 while (width < view->ncols) {
2785 waddch(view->window, ' ');
2786 width++;
2788 if (tc)
2789 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2790 if (view_needs_focus_indication(view))
2791 wstandend(view->window);
2792 free(wline);
2793 if (limit <= 1)
2794 goto done;
2796 /* Grow author column size if necessary, and set view->maxx. */
2797 entry = s->first_displayed_entry;
2798 ncommits = 0;
2799 view->maxx = 0;
2800 while (entry) {
2801 struct got_commit_object *c = entry->commit;
2802 char *author, *eol, *msg, *msg0;
2803 wchar_t *wauthor, *wmsg;
2804 int width;
2805 if (ncommits >= limit - 1)
2806 break;
2807 if (s->use_committer)
2808 author = strdup(got_object_commit_get_committer(c));
2809 else
2810 author = strdup(got_object_commit_get_author(c));
2811 if (author == NULL) {
2812 err = got_error_from_errno("strdup");
2813 goto done;
2815 err = format_author(&wauthor, &width, author, COLS,
2816 date_display_cols);
2817 if (author_cols < width)
2818 author_cols = width;
2819 free(wauthor);
2820 free(author);
2821 if (err)
2822 goto done;
2823 err = got_object_commit_get_logmsg(&msg0, c);
2824 if (err)
2825 goto done;
2826 msg = msg0;
2827 while (*msg == '\n')
2828 ++msg;
2829 if ((eol = strchr(msg, '\n')))
2830 *eol = '\0';
2831 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2832 date_display_cols + author_cols, 0);
2833 if (err)
2834 goto done;
2835 view->maxx = MAX(view->maxx, width);
2836 free(msg0);
2837 free(wmsg);
2838 ncommits++;
2839 entry = TAILQ_NEXT(entry, entry);
2842 entry = s->first_displayed_entry;
2843 s->last_displayed_entry = s->first_displayed_entry;
2844 ncommits = 0;
2845 while (entry) {
2846 if (ncommits >= limit - 1)
2847 break;
2848 if (ncommits == s->selected)
2849 wstandout(view->window);
2850 err = draw_commit(view, entry->commit, entry->id,
2851 date_display_cols, author_cols);
2852 if (ncommits == s->selected)
2853 wstandend(view->window);
2854 if (err)
2855 goto done;
2856 ncommits++;
2857 s->last_displayed_entry = entry;
2858 entry = TAILQ_NEXT(entry, entry);
2861 view_border(view);
2862 done:
2863 free(id_str);
2864 free(refs_str);
2865 free(ncommits_str);
2866 free(header);
2867 return err;
2870 static void
2871 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2873 struct commit_queue_entry *entry;
2874 int nscrolled = 0;
2876 entry = TAILQ_FIRST(&s->commits->head);
2877 if (s->first_displayed_entry == entry)
2878 return;
2880 entry = s->first_displayed_entry;
2881 while (entry && nscrolled < maxscroll) {
2882 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2883 if (entry) {
2884 s->first_displayed_entry = entry;
2885 nscrolled++;
2890 static const struct got_error *
2891 trigger_log_thread(struct tog_view *view, int wait)
2893 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2894 int errcode;
2896 halfdelay(1); /* fast refresh while loading commits */
2898 while (!ta->log_complete && !tog_thread_error &&
2899 (ta->commits_needed > 0 || ta->load_all)) {
2900 /* Wake the log thread. */
2901 errcode = pthread_cond_signal(&ta->need_commits);
2902 if (errcode)
2903 return got_error_set_errno(errcode,
2904 "pthread_cond_signal");
2907 * The mutex will be released while the view loop waits
2908 * in wgetch(), at which time the log thread will run.
2910 if (!wait)
2911 break;
2913 /* Display progress update in log view. */
2914 show_log_view(view);
2915 update_panels();
2916 doupdate();
2918 /* Wait right here while next commit is being loaded. */
2919 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2920 if (errcode)
2921 return got_error_set_errno(errcode,
2922 "pthread_cond_wait");
2924 /* Display progress update in log view. */
2925 show_log_view(view);
2926 update_panels();
2927 doupdate();
2930 return NULL;
2933 static const struct got_error *
2934 request_log_commits(struct tog_view *view)
2936 struct tog_log_view_state *state = &view->state.log;
2937 const struct got_error *err = NULL;
2939 if (state->thread_args.log_complete)
2940 return NULL;
2942 state->thread_args.commits_needed += view->nscrolled;
2943 err = trigger_log_thread(view, 1);
2944 view->nscrolled = 0;
2946 return err;
2949 static const struct got_error *
2950 log_scroll_down(struct tog_view *view, int maxscroll)
2952 struct tog_log_view_state *s = &view->state.log;
2953 const struct got_error *err = NULL;
2954 struct commit_queue_entry *pentry;
2955 int nscrolled = 0, ncommits_needed;
2957 if (s->last_displayed_entry == NULL)
2958 return NULL;
2960 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2961 if (s->commits->ncommits < ncommits_needed &&
2962 !s->thread_args.log_complete) {
2964 * Ask the log thread for required amount of commits.
2966 s->thread_args.commits_needed +=
2967 ncommits_needed - s->commits->ncommits;
2968 err = trigger_log_thread(view, 1);
2969 if (err)
2970 return err;
2973 do {
2974 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2975 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2976 break;
2978 s->last_displayed_entry = pentry ?
2979 pentry : s->last_displayed_entry;
2981 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2982 if (pentry == NULL)
2983 break;
2984 s->first_displayed_entry = pentry;
2985 } while (++nscrolled < maxscroll);
2987 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2988 view->nscrolled += nscrolled;
2989 else
2990 view->nscrolled = 0;
2992 return err;
2995 static const struct got_error *
2996 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2997 struct got_commit_object *commit, struct got_object_id *commit_id,
2998 struct tog_view *log_view, struct got_repository *repo)
3000 const struct got_error *err;
3001 struct got_object_qid *parent_id;
3002 struct tog_view *diff_view;
3004 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3005 if (diff_view == NULL)
3006 return got_error_from_errno("view_open");
3008 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3009 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3010 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3011 if (err == NULL)
3012 *new_view = diff_view;
3013 return err;
3016 static const struct got_error *
3017 tree_view_visit_subtree(struct tog_tree_view_state *s,
3018 struct got_tree_object *subtree)
3020 struct tog_parent_tree *parent;
3022 parent = calloc(1, sizeof(*parent));
3023 if (parent == NULL)
3024 return got_error_from_errno("calloc");
3026 parent->tree = s->tree;
3027 parent->first_displayed_entry = s->first_displayed_entry;
3028 parent->selected_entry = s->selected_entry;
3029 parent->selected = s->selected;
3030 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3031 s->tree = subtree;
3032 s->selected = 0;
3033 s->first_displayed_entry = NULL;
3034 return NULL;
3037 static const struct got_error *
3038 tree_view_walk_path(struct tog_tree_view_state *s,
3039 struct got_commit_object *commit, const char *path)
3041 const struct got_error *err = NULL;
3042 struct got_tree_object *tree = NULL;
3043 const char *p;
3044 char *slash, *subpath = NULL;
3046 /* Walk the path and open corresponding tree objects. */
3047 p = path;
3048 while (*p) {
3049 struct got_tree_entry *te;
3050 struct got_object_id *tree_id;
3051 char *te_name;
3053 while (p[0] == '/')
3054 p++;
3056 /* Ensure the correct subtree entry is selected. */
3057 slash = strchr(p, '/');
3058 if (slash == NULL)
3059 te_name = strdup(p);
3060 else
3061 te_name = strndup(p, slash - p);
3062 if (te_name == NULL) {
3063 err = got_error_from_errno("strndup");
3064 break;
3066 te = got_object_tree_find_entry(s->tree, te_name);
3067 if (te == NULL) {
3068 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3069 free(te_name);
3070 break;
3072 free(te_name);
3073 s->first_displayed_entry = s->selected_entry = te;
3075 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3076 break; /* jump to this file's entry */
3078 slash = strchr(p, '/');
3079 if (slash)
3080 subpath = strndup(path, slash - path);
3081 else
3082 subpath = strdup(path);
3083 if (subpath == NULL) {
3084 err = got_error_from_errno("strdup");
3085 break;
3088 err = got_object_id_by_path(&tree_id, s->repo, commit,
3089 subpath);
3090 if (err)
3091 break;
3093 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3094 free(tree_id);
3095 if (err)
3096 break;
3098 err = tree_view_visit_subtree(s, tree);
3099 if (err) {
3100 got_object_tree_close(tree);
3101 break;
3103 if (slash == NULL)
3104 break;
3105 free(subpath);
3106 subpath = NULL;
3107 p = slash;
3110 free(subpath);
3111 return err;
3114 static const struct got_error *
3115 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3116 struct commit_queue_entry *entry, const char *path,
3117 const char *head_ref_name, struct got_repository *repo)
3119 const struct got_error *err = NULL;
3120 struct tog_tree_view_state *s;
3121 struct tog_view *tree_view;
3123 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3124 if (tree_view == NULL)
3125 return got_error_from_errno("view_open");
3127 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3128 if (err)
3129 return err;
3130 s = &tree_view->state.tree;
3132 *new_view = tree_view;
3134 if (got_path_is_root_dir(path))
3135 return NULL;
3137 return tree_view_walk_path(s, entry->commit, path);
3140 static const struct got_error *
3141 block_signals_used_by_main_thread(void)
3143 sigset_t sigset;
3144 int errcode;
3146 if (sigemptyset(&sigset) == -1)
3147 return got_error_from_errno("sigemptyset");
3149 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3150 if (sigaddset(&sigset, SIGWINCH) == -1)
3151 return got_error_from_errno("sigaddset");
3152 if (sigaddset(&sigset, SIGCONT) == -1)
3153 return got_error_from_errno("sigaddset");
3154 if (sigaddset(&sigset, SIGINT) == -1)
3155 return got_error_from_errno("sigaddset");
3156 if (sigaddset(&sigset, SIGTERM) == -1)
3157 return got_error_from_errno("sigaddset");
3159 /* ncurses handles SIGTSTP */
3160 if (sigaddset(&sigset, SIGTSTP) == -1)
3161 return got_error_from_errno("sigaddset");
3163 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3164 if (errcode)
3165 return got_error_set_errno(errcode, "pthread_sigmask");
3167 return NULL;
3170 static void *
3171 log_thread(void *arg)
3173 const struct got_error *err = NULL;
3174 int errcode = 0;
3175 struct tog_log_thread_args *a = arg;
3176 int done = 0;
3179 * Sync startup with main thread such that we begin our
3180 * work once view_input() has released the mutex.
3182 errcode = pthread_mutex_lock(&tog_mutex);
3183 if (errcode) {
3184 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3185 return (void *)err;
3188 err = block_signals_used_by_main_thread();
3189 if (err) {
3190 pthread_mutex_unlock(&tog_mutex);
3191 goto done;
3194 while (!done && !err && !tog_fatal_signal_received()) {
3195 errcode = pthread_mutex_unlock(&tog_mutex);
3196 if (errcode) {
3197 err = got_error_set_errno(errcode,
3198 "pthread_mutex_unlock");
3199 goto done;
3201 err = queue_commits(a);
3202 if (err) {
3203 if (err->code != GOT_ERR_ITER_COMPLETED)
3204 goto done;
3205 err = NULL;
3206 done = 1;
3207 } else if (a->commits_needed > 0 && !a->load_all) {
3208 if (*a->limiting) {
3209 if (a->limit_match)
3210 a->commits_needed--;
3211 } else
3212 a->commits_needed--;
3215 errcode = pthread_mutex_lock(&tog_mutex);
3216 if (errcode) {
3217 err = got_error_set_errno(errcode,
3218 "pthread_mutex_lock");
3219 goto done;
3220 } else if (*a->quit)
3221 done = 1;
3222 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3223 *a->first_displayed_entry =
3224 TAILQ_FIRST(&a->limit_commits->head);
3225 *a->selected_entry = *a->first_displayed_entry;
3226 } else if (*a->first_displayed_entry == NULL) {
3227 *a->first_displayed_entry =
3228 TAILQ_FIRST(&a->real_commits->head);
3229 *a->selected_entry = *a->first_displayed_entry;
3232 errcode = pthread_cond_signal(&a->commit_loaded);
3233 if (errcode) {
3234 err = got_error_set_errno(errcode,
3235 "pthread_cond_signal");
3236 pthread_mutex_unlock(&tog_mutex);
3237 goto done;
3240 if (done)
3241 a->commits_needed = 0;
3242 else {
3243 if (a->commits_needed == 0 && !a->load_all) {
3244 errcode = pthread_cond_wait(&a->need_commits,
3245 &tog_mutex);
3246 if (errcode) {
3247 err = got_error_set_errno(errcode,
3248 "pthread_cond_wait");
3249 pthread_mutex_unlock(&tog_mutex);
3250 goto done;
3252 if (*a->quit)
3253 done = 1;
3257 a->log_complete = 1;
3258 errcode = pthread_mutex_unlock(&tog_mutex);
3259 if (errcode)
3260 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3261 done:
3262 if (err) {
3263 tog_thread_error = 1;
3264 pthread_cond_signal(&a->commit_loaded);
3266 return (void *)err;
3269 static const struct got_error *
3270 stop_log_thread(struct tog_log_view_state *s)
3272 const struct got_error *err = NULL, *thread_err = NULL;
3273 int errcode;
3275 if (s->thread) {
3276 s->quit = 1;
3277 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3278 if (errcode)
3279 return got_error_set_errno(errcode,
3280 "pthread_cond_signal");
3281 errcode = pthread_mutex_unlock(&tog_mutex);
3282 if (errcode)
3283 return got_error_set_errno(errcode,
3284 "pthread_mutex_unlock");
3285 errcode = pthread_join(s->thread, (void **)&thread_err);
3286 if (errcode)
3287 return got_error_set_errno(errcode, "pthread_join");
3288 errcode = pthread_mutex_lock(&tog_mutex);
3289 if (errcode)
3290 return got_error_set_errno(errcode,
3291 "pthread_mutex_lock");
3292 s->thread = 0; //NULL;
3295 if (s->thread_args.repo) {
3296 err = got_repo_close(s->thread_args.repo);
3297 s->thread_args.repo = NULL;
3300 if (s->thread_args.pack_fds) {
3301 const struct got_error *pack_err =
3302 got_repo_pack_fds_close(s->thread_args.pack_fds);
3303 if (err == NULL)
3304 err = pack_err;
3305 s->thread_args.pack_fds = NULL;
3308 if (s->thread_args.graph) {
3309 got_commit_graph_close(s->thread_args.graph);
3310 s->thread_args.graph = NULL;
3313 return err ? err : thread_err;
3316 static const struct got_error *
3317 close_log_view(struct tog_view *view)
3319 const struct got_error *err = NULL;
3320 struct tog_log_view_state *s = &view->state.log;
3321 int errcode;
3323 err = stop_log_thread(s);
3325 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3326 if (errcode && err == NULL)
3327 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3329 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3330 if (errcode && err == NULL)
3331 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3333 free_commits(&s->limit_commits);
3334 free_commits(&s->real_commits);
3335 free(s->in_repo_path);
3336 s->in_repo_path = NULL;
3337 free(s->start_id);
3338 s->start_id = NULL;
3339 free(s->head_ref_name);
3340 s->head_ref_name = NULL;
3341 return err;
3345 * We use two queues to implement the limit feature: first consists of
3346 * commits matching the current limit_regex; second is the real queue
3347 * of all known commits (real_commits). When the user starts limiting,
3348 * we swap queues such that all movement and displaying functionality
3349 * works with very slight change.
3351 static const struct got_error *
3352 limit_log_view(struct tog_view *view)
3354 struct tog_log_view_state *s = &view->state.log;
3355 struct commit_queue_entry *entry;
3356 struct tog_view *v = view;
3357 const struct got_error *err = NULL;
3358 char pattern[1024];
3359 int ret;
3361 if (view_is_hsplit_top(view))
3362 v = view->child;
3363 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3364 v = view->parent;
3366 /* Get the pattern */
3367 wmove(v->window, v->nlines - 1, 0);
3368 wclrtoeol(v->window);
3369 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3370 nodelay(v->window, FALSE);
3371 nocbreak();
3372 echo();
3373 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3374 cbreak();
3375 noecho();
3376 nodelay(v->window, TRUE);
3377 if (ret == ERR)
3378 return NULL;
3380 if (*pattern == '\0') {
3382 * Safety measure for the situation where the user
3383 * resets limit without previously limiting anything.
3385 if (!s->limit_view)
3386 return NULL;
3389 * User could have pressed Ctrl+L, which refreshed the
3390 * commit queues, it means we can't save previously
3391 * (before limit took place) displayed entries,
3392 * because they would point to already free'ed memory,
3393 * so we are forced to always select first entry of
3394 * the queue.
3396 s->commits = &s->real_commits;
3397 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3398 s->selected_entry = s->first_displayed_entry;
3399 s->selected = 0;
3400 s->limit_view = 0;
3402 return NULL;
3405 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3406 return NULL;
3408 s->limit_view = 1;
3410 /* Clear the screen while loading limit view */
3411 s->first_displayed_entry = NULL;
3412 s->last_displayed_entry = NULL;
3413 s->selected_entry = NULL;
3414 s->commits = &s->limit_commits;
3416 /* Prepare limit queue for new search */
3417 free_commits(&s->limit_commits);
3418 s->limit_commits.ncommits = 0;
3420 /* First process commits, which are in queue already */
3421 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3422 int have_match = 0;
3424 err = match_commit(&have_match, entry->id,
3425 entry->commit, &s->limit_regex);
3426 if (err)
3427 return err;
3429 if (have_match) {
3430 struct commit_queue_entry *matched;
3432 matched = alloc_commit_queue_entry(entry->commit,
3433 entry->id);
3434 if (matched == NULL) {
3435 err = got_error_from_errno(
3436 "alloc_commit_queue_entry");
3437 break;
3439 matched->commit = entry->commit;
3440 got_object_commit_retain(entry->commit);
3442 matched->idx = s->limit_commits.ncommits;
3443 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3444 matched, entry);
3445 s->limit_commits.ncommits++;
3449 /* Second process all the commits, until we fill the screen */
3450 if (s->limit_commits.ncommits < view->nlines - 1 &&
3451 !s->thread_args.log_complete) {
3452 s->thread_args.commits_needed +=
3453 view->nlines - s->limit_commits.ncommits - 1;
3454 err = trigger_log_thread(view, 1);
3455 if (err)
3456 return err;
3459 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3460 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3461 s->selected = 0;
3463 return NULL;
3466 static const struct got_error *
3467 search_start_log_view(struct tog_view *view)
3469 struct tog_log_view_state *s = &view->state.log;
3471 s->matched_entry = NULL;
3472 s->search_entry = NULL;
3473 return NULL;
3476 static const struct got_error *
3477 search_next_log_view(struct tog_view *view)
3479 const struct got_error *err = NULL;
3480 struct tog_log_view_state *s = &view->state.log;
3481 struct commit_queue_entry *entry;
3483 /* Display progress update in log view. */
3484 show_log_view(view);
3485 update_panels();
3486 doupdate();
3488 if (s->search_entry) {
3489 int errcode, ch;
3490 errcode = pthread_mutex_unlock(&tog_mutex);
3491 if (errcode)
3492 return got_error_set_errno(errcode,
3493 "pthread_mutex_unlock");
3494 ch = wgetch(view->window);
3495 errcode = pthread_mutex_lock(&tog_mutex);
3496 if (errcode)
3497 return got_error_set_errno(errcode,
3498 "pthread_mutex_lock");
3499 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3500 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3501 return NULL;
3503 if (view->searching == TOG_SEARCH_FORWARD)
3504 entry = TAILQ_NEXT(s->search_entry, entry);
3505 else
3506 entry = TAILQ_PREV(s->search_entry,
3507 commit_queue_head, entry);
3508 } else if (s->matched_entry) {
3510 * If the user has moved the cursor after we hit a match,
3511 * the position from where we should continue searching
3512 * might have changed.
3514 if (view->searching == TOG_SEARCH_FORWARD)
3515 entry = TAILQ_NEXT(s->selected_entry, entry);
3516 else
3517 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3518 entry);
3519 } else {
3520 entry = s->selected_entry;
3523 while (1) {
3524 int have_match = 0;
3526 if (entry == NULL) {
3527 if (s->thread_args.log_complete ||
3528 view->searching == TOG_SEARCH_BACKWARD) {
3529 view->search_next_done =
3530 (s->matched_entry == NULL ?
3531 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3532 s->search_entry = NULL;
3533 return NULL;
3536 * Poke the log thread for more commits and return,
3537 * allowing the main loop to make progress. Search
3538 * will resume at s->search_entry once we come back.
3540 s->thread_args.commits_needed++;
3541 return trigger_log_thread(view, 0);
3544 err = match_commit(&have_match, entry->id, entry->commit,
3545 &view->regex);
3546 if (err)
3547 break;
3548 if (have_match) {
3549 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3550 s->matched_entry = entry;
3551 break;
3554 s->search_entry = entry;
3555 if (view->searching == TOG_SEARCH_FORWARD)
3556 entry = TAILQ_NEXT(entry, entry);
3557 else
3558 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3561 if (s->matched_entry) {
3562 int cur = s->selected_entry->idx;
3563 while (cur < s->matched_entry->idx) {
3564 err = input_log_view(NULL, view, KEY_DOWN);
3565 if (err)
3566 return err;
3567 cur++;
3569 while (cur > s->matched_entry->idx) {
3570 err = input_log_view(NULL, view, KEY_UP);
3571 if (err)
3572 return err;
3573 cur--;
3577 s->search_entry = NULL;
3579 return NULL;
3582 static const struct got_error *
3583 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3584 struct got_repository *repo, const char *head_ref_name,
3585 const char *in_repo_path, int log_branches)
3587 const struct got_error *err = NULL;
3588 struct tog_log_view_state *s = &view->state.log;
3589 struct got_repository *thread_repo = NULL;
3590 struct got_commit_graph *thread_graph = NULL;
3591 int errcode;
3593 if (in_repo_path != s->in_repo_path) {
3594 free(s->in_repo_path);
3595 s->in_repo_path = strdup(in_repo_path);
3596 if (s->in_repo_path == NULL)
3597 return got_error_from_errno("strdup");
3600 /* The commit queue only contains commits being displayed. */
3601 TAILQ_INIT(&s->real_commits.head);
3602 s->real_commits.ncommits = 0;
3603 s->commits = &s->real_commits;
3605 TAILQ_INIT(&s->limit_commits.head);
3606 s->limit_view = 0;
3607 s->limit_commits.ncommits = 0;
3609 s->repo = repo;
3610 if (head_ref_name) {
3611 s->head_ref_name = strdup(head_ref_name);
3612 if (s->head_ref_name == NULL) {
3613 err = got_error_from_errno("strdup");
3614 goto done;
3617 s->start_id = got_object_id_dup(start_id);
3618 if (s->start_id == NULL) {
3619 err = got_error_from_errno("got_object_id_dup");
3620 goto done;
3622 s->log_branches = log_branches;
3623 s->use_committer = 1;
3625 STAILQ_INIT(&s->colors);
3626 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3627 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3628 get_color_value("TOG_COLOR_COMMIT"));
3629 if (err)
3630 goto done;
3631 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3632 get_color_value("TOG_COLOR_AUTHOR"));
3633 if (err) {
3634 free_colors(&s->colors);
3635 goto done;
3637 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3638 get_color_value("TOG_COLOR_DATE"));
3639 if (err) {
3640 free_colors(&s->colors);
3641 goto done;
3645 view->show = show_log_view;
3646 view->input = input_log_view;
3647 view->resize = resize_log_view;
3648 view->close = close_log_view;
3649 view->search_start = search_start_log_view;
3650 view->search_next = search_next_log_view;
3652 if (s->thread_args.pack_fds == NULL) {
3653 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3654 if (err)
3655 goto done;
3657 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3658 s->thread_args.pack_fds);
3659 if (err)
3660 goto done;
3661 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3662 !s->log_branches);
3663 if (err)
3664 goto done;
3665 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3666 s->repo, NULL, NULL);
3667 if (err)
3668 goto done;
3670 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3671 if (errcode) {
3672 err = got_error_set_errno(errcode, "pthread_cond_init");
3673 goto done;
3675 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3676 if (errcode) {
3677 err = got_error_set_errno(errcode, "pthread_cond_init");
3678 goto done;
3681 s->thread_args.commits_needed = view->nlines;
3682 s->thread_args.graph = thread_graph;
3683 s->thread_args.real_commits = &s->real_commits;
3684 s->thread_args.limit_commits = &s->limit_commits;
3685 s->thread_args.in_repo_path = s->in_repo_path;
3686 s->thread_args.start_id = s->start_id;
3687 s->thread_args.repo = thread_repo;
3688 s->thread_args.log_complete = 0;
3689 s->thread_args.quit = &s->quit;
3690 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3691 s->thread_args.selected_entry = &s->selected_entry;
3692 s->thread_args.searching = &view->searching;
3693 s->thread_args.search_next_done = &view->search_next_done;
3694 s->thread_args.regex = &view->regex;
3695 s->thread_args.limiting = &s->limit_view;
3696 s->thread_args.limit_regex = &s->limit_regex;
3697 s->thread_args.limit_commits = &s->limit_commits;
3698 done:
3699 if (err)
3700 close_log_view(view);
3701 return err;
3704 static const struct got_error *
3705 show_log_view(struct tog_view *view)
3707 const struct got_error *err;
3708 struct tog_log_view_state *s = &view->state.log;
3710 if (s->thread == 0) { //NULL) {
3711 int errcode = pthread_create(&s->thread, NULL, log_thread,
3712 &s->thread_args);
3713 if (errcode)
3714 return got_error_set_errno(errcode, "pthread_create");
3715 if (s->thread_args.commits_needed > 0) {
3716 err = trigger_log_thread(view, 1);
3717 if (err)
3718 return err;
3722 return draw_commits(view);
3725 static void
3726 log_move_cursor_up(struct tog_view *view, int page, int home)
3728 struct tog_log_view_state *s = &view->state.log;
3730 if (s->first_displayed_entry == NULL)
3731 return;
3732 if (s->selected_entry->idx == 0)
3733 view->count = 0;
3735 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3736 || home)
3737 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3739 if (!page && !home && s->selected > 0)
3740 --s->selected;
3741 else
3742 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3744 select_commit(s);
3745 return;
3748 static const struct got_error *
3749 log_move_cursor_down(struct tog_view *view, int page)
3751 struct tog_log_view_state *s = &view->state.log;
3752 const struct got_error *err = NULL;
3753 int eos = view->nlines - 2;
3755 if (s->first_displayed_entry == NULL)
3756 return NULL;
3758 if (s->thread_args.log_complete &&
3759 s->selected_entry->idx >= s->commits->ncommits - 1)
3760 return NULL;
3762 if (view_is_hsplit_top(view))
3763 --eos; /* border consumes the last line */
3765 if (!page) {
3766 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3767 ++s->selected;
3768 else
3769 err = log_scroll_down(view, 1);
3770 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3771 struct commit_queue_entry *entry;
3772 int n;
3774 s->selected = 0;
3775 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3776 s->last_displayed_entry = entry;
3777 for (n = 0; n <= eos; n++) {
3778 if (entry == NULL)
3779 break;
3780 s->first_displayed_entry = entry;
3781 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3783 if (n > 0)
3784 s->selected = n - 1;
3785 } else {
3786 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3787 s->thread_args.log_complete)
3788 s->selected += MIN(page,
3789 s->commits->ncommits - s->selected_entry->idx - 1);
3790 else
3791 err = log_scroll_down(view, page);
3793 if (err)
3794 return err;
3797 * We might necessarily overshoot in horizontal
3798 * splits; if so, select the last displayed commit.
3800 if (s->first_displayed_entry && s->last_displayed_entry) {
3801 s->selected = MIN(s->selected,
3802 s->last_displayed_entry->idx -
3803 s->first_displayed_entry->idx);
3806 select_commit(s);
3808 if (s->thread_args.log_complete &&
3809 s->selected_entry->idx == s->commits->ncommits - 1)
3810 view->count = 0;
3812 return NULL;
3815 static void
3816 view_get_split(struct tog_view *view, int *y, int *x)
3818 *x = 0;
3819 *y = 0;
3821 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3822 if (view->child && view->child->resized_y)
3823 *y = view->child->resized_y;
3824 else if (view->resized_y)
3825 *y = view->resized_y;
3826 else
3827 *y = view_split_begin_y(view->lines);
3828 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3829 if (view->child && view->child->resized_x)
3830 *x = view->child->resized_x;
3831 else if (view->resized_x)
3832 *x = view->resized_x;
3833 else
3834 *x = view_split_begin_x(view->begin_x);
3838 /* Split view horizontally at y and offset view->state->selected line. */
3839 static const struct got_error *
3840 view_init_hsplit(struct tog_view *view, int y)
3842 const struct got_error *err = NULL;
3844 view->nlines = y;
3845 view->ncols = COLS;
3846 err = view_resize(view);
3847 if (err)
3848 return err;
3850 err = offset_selection_down(view);
3852 return err;
3855 static const struct got_error *
3856 log_goto_line(struct tog_view *view, int nlines)
3858 const struct got_error *err = NULL;
3859 struct tog_log_view_state *s = &view->state.log;
3860 int g, idx = s->selected_entry->idx;
3862 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3863 return NULL;
3865 g = view->gline;
3866 view->gline = 0;
3868 if (g >= s->first_displayed_entry->idx + 1 &&
3869 g <= s->last_displayed_entry->idx + 1 &&
3870 g - s->first_displayed_entry->idx - 1 < nlines) {
3871 s->selected = g - s->first_displayed_entry->idx - 1;
3872 select_commit(s);
3873 return NULL;
3876 if (idx + 1 < g) {
3877 err = log_move_cursor_down(view, g - idx - 1);
3878 if (!err && g > s->selected_entry->idx + 1)
3879 err = log_move_cursor_down(view,
3880 g - s->first_displayed_entry->idx - 1);
3881 if (err)
3882 return err;
3883 } else if (idx + 1 > g)
3884 log_move_cursor_up(view, idx - g + 1, 0);
3886 if (g < nlines && s->first_displayed_entry->idx == 0)
3887 s->selected = g - 1;
3889 select_commit(s);
3890 return NULL;
3894 static void
3895 horizontal_scroll_input(struct tog_view *view, int ch)
3898 switch (ch) {
3899 case KEY_LEFT:
3900 case 'h':
3901 view->x -= MIN(view->x, 2);
3902 if (view->x <= 0)
3903 view->count = 0;
3904 break;
3905 case KEY_RIGHT:
3906 case 'l':
3907 if (view->x + view->ncols / 2 < view->maxx)
3908 view->x += 2;
3909 else
3910 view->count = 0;
3911 break;
3912 case '0':
3913 view->x = 0;
3914 break;
3915 case '$':
3916 view->x = MAX(view->maxx - view->ncols / 2, 0);
3917 view->count = 0;
3918 break;
3919 default:
3920 break;
3924 static const struct got_error *
3925 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3927 const struct got_error *err = NULL;
3928 struct tog_log_view_state *s = &view->state.log;
3929 int eos, nscroll;
3931 if (s->thread_args.load_all) {
3932 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3933 s->thread_args.load_all = 0;
3934 else if (s->thread_args.log_complete) {
3935 err = log_move_cursor_down(view, s->commits->ncommits);
3936 s->thread_args.load_all = 0;
3938 if (err)
3939 return err;
3942 eos = nscroll = view->nlines - 1;
3943 if (view_is_hsplit_top(view))
3944 --eos; /* border */
3946 if (view->gline)
3947 return log_goto_line(view, eos);
3949 switch (ch) {
3950 case '&':
3951 err = limit_log_view(view);
3952 break;
3953 case 'q':
3954 s->quit = 1;
3955 break;
3956 case '0':
3957 case '$':
3958 case KEY_RIGHT:
3959 case 'l':
3960 case KEY_LEFT:
3961 case 'h':
3962 horizontal_scroll_input(view, ch);
3963 break;
3964 case 'k':
3965 case KEY_UP:
3966 case '<':
3967 case ',':
3968 case CTRL('p'):
3969 log_move_cursor_up(view, 0, 0);
3970 break;
3971 case 'g':
3972 case '=':
3973 case KEY_HOME:
3974 log_move_cursor_up(view, 0, 1);
3975 view->count = 0;
3976 break;
3977 case CTRL('u'):
3978 case 'u':
3979 nscroll /= 2;
3980 /* FALL THROUGH */
3981 case KEY_PPAGE:
3982 case CTRL('b'):
3983 case 'b':
3984 log_move_cursor_up(view, nscroll, 0);
3985 break;
3986 case 'j':
3987 case KEY_DOWN:
3988 case '>':
3989 case '.':
3990 case CTRL('n'):
3991 err = log_move_cursor_down(view, 0);
3992 break;
3993 case '@':
3994 s->use_committer = !s->use_committer;
3995 view->action = s->use_committer ?
3996 "show committer" : "show commit author";
3997 break;
3998 case 'G':
3999 case '*':
4000 case KEY_END: {
4001 /* We don't know yet how many commits, so we're forced to
4002 * traverse them all. */
4003 view->count = 0;
4004 s->thread_args.load_all = 1;
4005 if (!s->thread_args.log_complete)
4006 return trigger_log_thread(view, 0);
4007 err = log_move_cursor_down(view, s->commits->ncommits);
4008 s->thread_args.load_all = 0;
4009 break;
4011 case CTRL('d'):
4012 case 'd':
4013 nscroll /= 2;
4014 /* FALL THROUGH */
4015 case KEY_NPAGE:
4016 case CTRL('f'):
4017 case 'f':
4018 case ' ':
4019 err = log_move_cursor_down(view, nscroll);
4020 break;
4021 case KEY_RESIZE:
4022 if (s->selected > view->nlines - 2)
4023 s->selected = view->nlines - 2;
4024 if (s->selected > s->commits->ncommits - 1)
4025 s->selected = s->commits->ncommits - 1;
4026 select_commit(s);
4027 if (s->commits->ncommits < view->nlines - 1 &&
4028 !s->thread_args.log_complete) {
4029 s->thread_args.commits_needed += (view->nlines - 1) -
4030 s->commits->ncommits;
4031 err = trigger_log_thread(view, 1);
4033 break;
4034 case KEY_ENTER:
4035 case '\r':
4036 view->count = 0;
4037 if (s->selected_entry == NULL)
4038 break;
4039 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4040 break;
4041 case 'T':
4042 view->count = 0;
4043 if (s->selected_entry == NULL)
4044 break;
4045 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4046 break;
4047 case KEY_BACKSPACE:
4048 case CTRL('l'):
4049 case 'B':
4050 view->count = 0;
4051 if (ch == KEY_BACKSPACE &&
4052 got_path_is_root_dir(s->in_repo_path))
4053 break;
4054 err = stop_log_thread(s);
4055 if (err)
4056 return err;
4057 if (ch == KEY_BACKSPACE) {
4058 char *parent_path;
4059 err = got_path_dirname(&parent_path, s->in_repo_path);
4060 if (err)
4061 return err;
4062 free(s->in_repo_path);
4063 s->in_repo_path = parent_path;
4064 s->thread_args.in_repo_path = s->in_repo_path;
4065 } else if (ch == CTRL('l')) {
4066 struct got_object_id *start_id;
4067 err = got_repo_match_object_id(&start_id, NULL,
4068 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4069 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4070 if (err) {
4071 if (s->head_ref_name == NULL ||
4072 err->code != GOT_ERR_NOT_REF)
4073 return err;
4074 /* Try to cope with deleted references. */
4075 free(s->head_ref_name);
4076 s->head_ref_name = NULL;
4077 err = got_repo_match_object_id(&start_id,
4078 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4079 &tog_refs, s->repo);
4080 if (err)
4081 return err;
4083 free(s->start_id);
4084 s->start_id = start_id;
4085 s->thread_args.start_id = s->start_id;
4086 } else /* 'B' */
4087 s->log_branches = !s->log_branches;
4089 if (s->thread_args.pack_fds == NULL) {
4090 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4091 if (err)
4092 return err;
4094 err = got_repo_open(&s->thread_args.repo,
4095 got_repo_get_path(s->repo), NULL,
4096 s->thread_args.pack_fds);
4097 if (err)
4098 return err;
4099 tog_free_refs();
4100 err = tog_load_refs(s->repo, 0);
4101 if (err)
4102 return err;
4103 err = got_commit_graph_open(&s->thread_args.graph,
4104 s->in_repo_path, !s->log_branches);
4105 if (err)
4106 return err;
4107 err = got_commit_graph_iter_start(s->thread_args.graph,
4108 s->start_id, s->repo, NULL, NULL);
4109 if (err)
4110 return err;
4111 free_commits(&s->real_commits);
4112 free_commits(&s->limit_commits);
4113 s->first_displayed_entry = NULL;
4114 s->last_displayed_entry = NULL;
4115 s->selected_entry = NULL;
4116 s->selected = 0;
4117 s->thread_args.log_complete = 0;
4118 s->quit = 0;
4119 s->thread_args.commits_needed = view->lines;
4120 s->matched_entry = NULL;
4121 s->search_entry = NULL;
4122 view->offset = 0;
4123 break;
4124 case 'R':
4125 view->count = 0;
4126 err = view_request_new(new_view, view, TOG_VIEW_REF);
4127 break;
4128 default:
4129 view->count = 0;
4130 break;
4133 return err;
4136 static const struct got_error *
4137 apply_unveil(const char *repo_path, const char *worktree_path)
4139 const struct got_error *error;
4141 #ifdef PROFILE
4142 if (unveil("gmon.out", "rwc") != 0)
4143 return got_error_from_errno2("unveil", "gmon.out");
4144 #endif
4145 if (repo_path && unveil(repo_path, "r") != 0)
4146 return got_error_from_errno2("unveil", repo_path);
4148 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4149 return got_error_from_errno2("unveil", worktree_path);
4151 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4152 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4154 error = got_privsep_unveil_exec_helpers();
4155 if (error != NULL)
4156 return error;
4158 if (unveil(NULL, NULL) != 0)
4159 return got_error_from_errno("unveil");
4161 return NULL;
4164 static const struct got_error *
4165 init_mock_term(struct tog_io **tog_io, const char *test_script_path)
4167 const struct got_error *err = NULL;
4168 struct tog_io *io;
4170 if (*tog_io)
4171 *tog_io = 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 io = calloc(1, sizeof(*io));
4177 if (io == NULL)
4178 return got_error_from_errno("calloc");
4180 io->f = fopen(test_script_path, "re");
4181 if (io->f == NULL) {
4182 err = got_error_from_errno_fmt("fopen: %s",
4183 test_script_path);
4184 goto done;
4187 /* test mode, we don't want any output */
4188 io->cout = fopen("/dev/null", "w+");
4189 if (io->cout == NULL) {
4190 err = got_error_from_errno("fopen: /dev/null");
4191 goto done;
4194 io->cin = fopen("/dev/tty", "r+");
4195 if (io->cin == NULL) {
4196 err = got_error_from_errno("fopen: /dev/tty");
4197 goto done;
4200 if (fseeko(io->f, 0L, SEEK_SET) == -1) {
4201 err = got_error_from_errno("fseeko");
4202 goto done;
4206 * XXX Perhaps we should define "xterm" as the terminal
4207 * type for standardised testing instead of using $TERM?
4209 if (newterm(NULL, io->cout, io->cin) == NULL)
4210 err = got_error_msg(GOT_ERR_IO,
4211 "newterm: failed to initialise curses");
4212 done:
4213 if (err)
4214 tog_io_close(io);
4215 else
4216 *tog_io = io;
4217 return err;
4220 static const struct got_error *
4221 init_curses(struct tog_io **tog_io)
4223 const struct got_error *err = NULL;
4224 const char *test_script_path;
4227 * Override default signal handlers before starting ncurses.
4228 * This should prevent ncurses from installing its own
4229 * broken cleanup() signal handler.
4231 signal(SIGWINCH, tog_sigwinch);
4232 signal(SIGPIPE, tog_sigpipe);
4233 signal(SIGCONT, tog_sigcont);
4234 signal(SIGINT, tog_sigint);
4235 signal(SIGTERM, tog_sigterm);
4237 test_script_path = getenv("GOT_TOG_TEST");
4238 if (test_script_path != NULL) {
4239 err = init_mock_term(tog_io, test_script_path);
4240 if (err)
4241 return err;
4242 } else
4243 initscr();
4245 cbreak();
4246 halfdelay(1); /* Do fast refresh while initial view is loading. */
4247 noecho();
4248 nonl();
4249 intrflush(stdscr, FALSE);
4250 keypad(stdscr, TRUE);
4251 curs_set(0);
4252 if (getenv("TOG_COLORS") != NULL) {
4253 start_color();
4254 use_default_colors();
4257 return NULL;
4260 static const struct got_error *
4261 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4262 struct got_repository *repo, struct got_worktree *worktree)
4264 const struct got_error *err = NULL;
4266 if (argc == 0) {
4267 *in_repo_path = strdup("/");
4268 if (*in_repo_path == NULL)
4269 return got_error_from_errno("strdup");
4270 return NULL;
4273 if (worktree) {
4274 const char *prefix = got_worktree_get_path_prefix(worktree);
4275 char *p;
4277 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4278 if (err)
4279 return err;
4280 if (asprintf(in_repo_path, "%s%s%s", prefix,
4281 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4282 p) == -1) {
4283 err = got_error_from_errno("asprintf");
4284 *in_repo_path = NULL;
4286 free(p);
4287 } else
4288 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4290 return err;
4293 static const struct got_error *
4294 cmd_log(int argc, char *argv[])
4296 const struct got_error *io_err, *error;
4297 struct got_repository *repo = NULL;
4298 struct got_worktree *worktree = NULL;
4299 struct got_object_id *start_id = NULL;
4300 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4301 char *start_commit = NULL, *label = NULL;
4302 struct got_reference *ref = NULL;
4303 const char *head_ref_name = NULL;
4304 int ch, log_branches = 0;
4305 struct tog_view *view;
4306 struct tog_io *tog_io = NULL;
4307 int *pack_fds = NULL;
4309 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4310 switch (ch) {
4311 case 'b':
4312 log_branches = 1;
4313 break;
4314 case 'c':
4315 start_commit = optarg;
4316 break;
4317 case 'r':
4318 repo_path = realpath(optarg, NULL);
4319 if (repo_path == NULL)
4320 return got_error_from_errno2("realpath",
4321 optarg);
4322 break;
4323 default:
4324 usage_log();
4325 /* NOTREACHED */
4329 argc -= optind;
4330 argv += optind;
4332 if (argc > 1)
4333 usage_log();
4335 error = got_repo_pack_fds_open(&pack_fds);
4336 if (error != NULL)
4337 goto done;
4339 if (repo_path == NULL) {
4340 cwd = getcwd(NULL, 0);
4341 if (cwd == NULL)
4342 return got_error_from_errno("getcwd");
4343 error = got_worktree_open(&worktree, cwd);
4344 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4345 goto done;
4346 if (worktree)
4347 repo_path =
4348 strdup(got_worktree_get_repo_path(worktree));
4349 else
4350 repo_path = strdup(cwd);
4351 if (repo_path == NULL) {
4352 error = got_error_from_errno("strdup");
4353 goto done;
4357 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4358 if (error != NULL)
4359 goto done;
4361 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4362 repo, worktree);
4363 if (error)
4364 goto done;
4366 error = init_curses(&tog_io);
4367 if (error)
4368 goto done;
4370 error = apply_unveil(got_repo_get_path(repo),
4371 worktree ? got_worktree_get_root_path(worktree) : NULL);
4372 if (error)
4373 goto done;
4375 /* already loaded by tog_log_with_path()? */
4376 if (TAILQ_EMPTY(&tog_refs)) {
4377 error = tog_load_refs(repo, 0);
4378 if (error)
4379 goto done;
4382 if (start_commit == NULL) {
4383 error = got_repo_match_object_id(&start_id, &label,
4384 worktree ? got_worktree_get_head_ref_name(worktree) :
4385 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4386 if (error)
4387 goto done;
4388 head_ref_name = label;
4389 } else {
4390 error = got_ref_open(&ref, repo, start_commit, 0);
4391 if (error == NULL)
4392 head_ref_name = got_ref_get_name(ref);
4393 else if (error->code != GOT_ERR_NOT_REF)
4394 goto done;
4395 error = got_repo_match_object_id(&start_id, NULL,
4396 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4397 if (error)
4398 goto done;
4401 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4402 if (view == NULL) {
4403 error = got_error_from_errno("view_open");
4404 goto done;
4406 error = open_log_view(view, start_id, repo, head_ref_name,
4407 in_repo_path, log_branches);
4408 if (error)
4409 goto done;
4410 if (worktree) {
4411 /* Release work tree lock. */
4412 got_worktree_close(worktree);
4413 worktree = NULL;
4415 error = view_loop(view, tog_io);
4416 done:
4417 free(in_repo_path);
4418 free(repo_path);
4419 free(cwd);
4420 free(start_id);
4421 free(label);
4422 if (ref)
4423 got_ref_close(ref);
4424 if (repo) {
4425 const struct got_error *close_err = got_repo_close(repo);
4426 if (error == NULL)
4427 error = close_err;
4429 if (worktree)
4430 got_worktree_close(worktree);
4431 if (pack_fds) {
4432 const struct got_error *pack_err =
4433 got_repo_pack_fds_close(pack_fds);
4434 if (error == NULL)
4435 error = pack_err;
4437 if (tog_io != NULL) {
4438 io_err = tog_io_close(tog_io);
4439 if (error == NULL)
4440 error = io_err;
4442 tog_free_refs();
4443 return error;
4446 __dead static void
4447 usage_diff(void)
4449 endwin();
4450 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4451 "object1 object2\n", getprogname());
4452 exit(1);
4455 static int
4456 match_line(const char *line, regex_t *regex, size_t nmatch,
4457 regmatch_t *regmatch)
4459 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4462 static struct tog_color *
4463 match_color(struct tog_colors *colors, const char *line)
4465 struct tog_color *tc = NULL;
4467 STAILQ_FOREACH(tc, colors, entry) {
4468 if (match_line(line, &tc->regex, 0, NULL))
4469 return tc;
4472 return NULL;
4475 static const struct got_error *
4476 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4477 WINDOW *window, int skipcol, regmatch_t *regmatch)
4479 const struct got_error *err = NULL;
4480 char *exstr = NULL;
4481 wchar_t *wline = NULL;
4482 int rme, rms, n, width, scrollx;
4483 int width0 = 0, width1 = 0, width2 = 0;
4484 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4486 *wtotal = 0;
4488 rms = regmatch->rm_so;
4489 rme = regmatch->rm_eo;
4491 err = expand_tab(&exstr, line);
4492 if (err)
4493 return err;
4495 /* Split the line into 3 segments, according to match offsets. */
4496 seg0 = strndup(exstr, rms);
4497 if (seg0 == NULL) {
4498 err = got_error_from_errno("strndup");
4499 goto done;
4501 seg1 = strndup(exstr + rms, rme - rms);
4502 if (seg1 == NULL) {
4503 err = got_error_from_errno("strndup");
4504 goto done;
4506 seg2 = strdup(exstr + rme);
4507 if (seg2 == NULL) {
4508 err = got_error_from_errno("strndup");
4509 goto done;
4512 /* draw up to matched token if we haven't scrolled past it */
4513 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4514 col_tab_align, 1);
4515 if (err)
4516 goto done;
4517 n = MAX(width0 - skipcol, 0);
4518 if (n) {
4519 free(wline);
4520 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4521 wlimit, col_tab_align, 1);
4522 if (err)
4523 goto done;
4524 waddwstr(window, &wline[scrollx]);
4525 wlimit -= width;
4526 *wtotal += width;
4529 if (wlimit > 0) {
4530 int i = 0, w = 0;
4531 size_t wlen;
4533 free(wline);
4534 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4535 col_tab_align, 1);
4536 if (err)
4537 goto done;
4538 wlen = wcslen(wline);
4539 while (i < wlen) {
4540 width = wcwidth(wline[i]);
4541 if (width == -1) {
4542 /* should not happen, tabs are expanded */
4543 err = got_error(GOT_ERR_RANGE);
4544 goto done;
4546 if (width0 + w + width > skipcol)
4547 break;
4548 w += width;
4549 i++;
4551 /* draw (visible part of) matched token (if scrolled into it) */
4552 if (width1 - w > 0) {
4553 wattron(window, A_STANDOUT);
4554 waddwstr(window, &wline[i]);
4555 wattroff(window, A_STANDOUT);
4556 wlimit -= (width1 - w);
4557 *wtotal += (width1 - w);
4561 if (wlimit > 0) { /* draw rest of line */
4562 free(wline);
4563 if (skipcol > width0 + width1) {
4564 err = format_line(&wline, &width2, &scrollx, seg2,
4565 skipcol - (width0 + width1), wlimit,
4566 col_tab_align, 1);
4567 if (err)
4568 goto done;
4569 waddwstr(window, &wline[scrollx]);
4570 } else {
4571 err = format_line(&wline, &width2, NULL, seg2, 0,
4572 wlimit, col_tab_align, 1);
4573 if (err)
4574 goto done;
4575 waddwstr(window, wline);
4577 *wtotal += width2;
4579 done:
4580 free(wline);
4581 free(exstr);
4582 free(seg0);
4583 free(seg1);
4584 free(seg2);
4585 return err;
4588 static int
4589 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4591 FILE *f = NULL;
4592 int *eof, *first, *selected;
4594 if (view->type == TOG_VIEW_DIFF) {
4595 struct tog_diff_view_state *s = &view->state.diff;
4597 first = &s->first_displayed_line;
4598 selected = first;
4599 eof = &s->eof;
4600 f = s->f;
4601 } else if (view->type == TOG_VIEW_HELP) {
4602 struct tog_help_view_state *s = &view->state.help;
4604 first = &s->first_displayed_line;
4605 selected = first;
4606 eof = &s->eof;
4607 f = s->f;
4608 } else if (view->type == TOG_VIEW_BLAME) {
4609 struct tog_blame_view_state *s = &view->state.blame;
4611 first = &s->first_displayed_line;
4612 selected = &s->selected_line;
4613 eof = &s->eof;
4614 f = s->blame.f;
4615 } else
4616 return 0;
4618 /* Center gline in the middle of the page like vi(1). */
4619 if (*lineno < view->gline - (view->nlines - 3) / 2)
4620 return 0;
4621 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4622 rewind(f);
4623 *eof = 0;
4624 *first = 1;
4625 *lineno = 0;
4626 *nprinted = 0;
4627 return 0;
4630 *selected = view->gline <= (view->nlines - 3) / 2 ?
4631 view->gline : (view->nlines - 3) / 2 + 1;
4632 view->gline = 0;
4634 return 1;
4637 static const struct got_error *
4638 draw_file(struct tog_view *view, const char *header)
4640 struct tog_diff_view_state *s = &view->state.diff;
4641 regmatch_t *regmatch = &view->regmatch;
4642 const struct got_error *err;
4643 int nprinted = 0;
4644 char *line;
4645 size_t linesize = 0;
4646 ssize_t linelen;
4647 wchar_t *wline;
4648 int width;
4649 int max_lines = view->nlines;
4650 int nlines = s->nlines;
4651 off_t line_offset;
4653 s->lineno = s->first_displayed_line - 1;
4654 line_offset = s->lines[s->first_displayed_line - 1].offset;
4655 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4656 return got_error_from_errno("fseek");
4658 werase(view->window);
4660 if (view->gline > s->nlines - 1)
4661 view->gline = s->nlines - 1;
4663 if (header) {
4664 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4665 1 : view->gline - (view->nlines - 3) / 2 :
4666 s->lineno + s->selected_line;
4668 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4669 return got_error_from_errno("asprintf");
4670 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4671 0, 0);
4672 free(line);
4673 if (err)
4674 return err;
4676 if (view_needs_focus_indication(view))
4677 wstandout(view->window);
4678 waddwstr(view->window, wline);
4679 free(wline);
4680 wline = NULL;
4681 while (width++ < view->ncols)
4682 waddch(view->window, ' ');
4683 if (view_needs_focus_indication(view))
4684 wstandend(view->window);
4686 if (max_lines <= 1)
4687 return NULL;
4688 max_lines--;
4691 s->eof = 0;
4692 view->maxx = 0;
4693 line = NULL;
4694 while (max_lines > 0 && nprinted < max_lines) {
4695 enum got_diff_line_type linetype;
4696 attr_t attr = 0;
4698 linelen = getline(&line, &linesize, s->f);
4699 if (linelen == -1) {
4700 if (feof(s->f)) {
4701 s->eof = 1;
4702 break;
4704 free(line);
4705 return got_ferror(s->f, GOT_ERR_IO);
4708 if (++s->lineno < s->first_displayed_line)
4709 continue;
4710 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4711 continue;
4712 if (s->lineno == view->hiline)
4713 attr = A_STANDOUT;
4715 /* Set view->maxx based on full line length. */
4716 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4717 view->x ? 1 : 0);
4718 if (err) {
4719 free(line);
4720 return err;
4722 view->maxx = MAX(view->maxx, width);
4723 free(wline);
4724 wline = NULL;
4726 linetype = s->lines[s->lineno].type;
4727 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4728 linetype < GOT_DIFF_LINE_CONTEXT)
4729 attr |= COLOR_PAIR(linetype);
4730 if (attr)
4731 wattron(view->window, attr);
4732 if (s->first_displayed_line + nprinted == s->matched_line &&
4733 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4734 err = add_matched_line(&width, line, view->ncols, 0,
4735 view->window, view->x, regmatch);
4736 if (err) {
4737 free(line);
4738 return err;
4740 } else {
4741 int skip;
4742 err = format_line(&wline, &width, &skip, line,
4743 view->x, view->ncols, 0, view->x ? 1 : 0);
4744 if (err) {
4745 free(line);
4746 return err;
4748 waddwstr(view->window, &wline[skip]);
4749 free(wline);
4750 wline = NULL;
4752 if (s->lineno == view->hiline) {
4753 /* highlight full gline length */
4754 while (width++ < view->ncols)
4755 waddch(view->window, ' ');
4756 } else {
4757 if (width <= view->ncols - 1)
4758 waddch(view->window, '\n');
4760 if (attr)
4761 wattroff(view->window, attr);
4762 if (++nprinted == 1)
4763 s->first_displayed_line = s->lineno;
4765 free(line);
4766 if (nprinted >= 1)
4767 s->last_displayed_line = s->first_displayed_line +
4768 (nprinted - 1);
4769 else
4770 s->last_displayed_line = s->first_displayed_line;
4772 view_border(view);
4774 if (s->eof) {
4775 while (nprinted < view->nlines) {
4776 waddch(view->window, '\n');
4777 nprinted++;
4780 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4781 view->ncols, 0, 0);
4782 if (err) {
4783 return err;
4786 wstandout(view->window);
4787 waddwstr(view->window, wline);
4788 free(wline);
4789 wline = NULL;
4790 wstandend(view->window);
4793 return NULL;
4796 static char *
4797 get_datestr(time_t *time, char *datebuf)
4799 struct tm mytm, *tm;
4800 char *p, *s;
4802 tm = gmtime_r(time, &mytm);
4803 if (tm == NULL)
4804 return NULL;
4805 s = asctime_r(tm, datebuf);
4806 if (s == NULL)
4807 return NULL;
4808 p = strchr(s, '\n');
4809 if (p)
4810 *p = '\0';
4811 return s;
4814 static const struct got_error *
4815 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4816 off_t off, uint8_t type)
4818 struct got_diff_line *p;
4820 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4821 if (p == NULL)
4822 return got_error_from_errno("reallocarray");
4823 *lines = p;
4824 (*lines)[*nlines].offset = off;
4825 (*lines)[*nlines].type = type;
4826 (*nlines)++;
4828 return NULL;
4831 static const struct got_error *
4832 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4833 struct got_diff_line *s_lines, size_t s_nlines)
4835 struct got_diff_line *p;
4836 char buf[BUFSIZ];
4837 size_t i, r;
4839 if (fseeko(src, 0L, SEEK_SET) == -1)
4840 return got_error_from_errno("fseeko");
4842 for (;;) {
4843 r = fread(buf, 1, sizeof(buf), src);
4844 if (r == 0) {
4845 if (ferror(src))
4846 return got_error_from_errno("fread");
4847 if (feof(src))
4848 break;
4850 if (fwrite(buf, 1, r, dst) != r)
4851 return got_ferror(dst, GOT_ERR_IO);
4854 if (s_nlines == 0 && *d_nlines == 0)
4855 return NULL;
4858 * If commit info was in dst, increment line offsets
4859 * of the appended diff content, but skip s_lines[0]
4860 * because offset zero is already in *d_lines.
4862 if (*d_nlines > 0) {
4863 for (i = 1; i < s_nlines; ++i)
4864 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4866 if (s_nlines > 0) {
4867 --s_nlines;
4868 ++s_lines;
4872 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4873 if (p == NULL) {
4874 /* d_lines is freed in close_diff_view() */
4875 return got_error_from_errno("reallocarray");
4878 *d_lines = p;
4880 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4881 *d_nlines += s_nlines;
4883 return NULL;
4886 static const struct got_error *
4887 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4888 struct got_object_id *commit_id, struct got_reflist_head *refs,
4889 struct got_repository *repo, int ignore_ws, int force_text_diff,
4890 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4892 const struct got_error *err = NULL;
4893 char datebuf[26], *datestr;
4894 struct got_commit_object *commit;
4895 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4896 time_t committer_time;
4897 const char *author, *committer;
4898 char *refs_str = NULL;
4899 struct got_pathlist_entry *pe;
4900 off_t outoff = 0;
4901 int n;
4903 if (refs) {
4904 err = build_refs_str(&refs_str, refs, commit_id, repo);
4905 if (err)
4906 return err;
4909 err = got_object_open_as_commit(&commit, repo, commit_id);
4910 if (err)
4911 return err;
4913 err = got_object_id_str(&id_str, commit_id);
4914 if (err) {
4915 err = got_error_from_errno("got_object_id_str");
4916 goto done;
4919 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4920 if (err)
4921 goto done;
4923 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4924 refs_str ? refs_str : "", refs_str ? ")" : "");
4925 if (n < 0) {
4926 err = got_error_from_errno("fprintf");
4927 goto done;
4929 outoff += n;
4930 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4931 if (err)
4932 goto done;
4934 n = fprintf(outfile, "from: %s\n",
4935 got_object_commit_get_author(commit));
4936 if (n < 0) {
4937 err = got_error_from_errno("fprintf");
4938 goto done;
4940 outoff += n;
4941 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4942 if (err)
4943 goto done;
4945 author = got_object_commit_get_author(commit);
4946 committer = got_object_commit_get_committer(commit);
4947 if (strcmp(author, committer) != 0) {
4948 n = fprintf(outfile, "via: %s\n", committer);
4949 if (n < 0) {
4950 err = got_error_from_errno("fprintf");
4951 goto done;
4953 outoff += n;
4954 err = add_line_metadata(lines, nlines, outoff,
4955 GOT_DIFF_LINE_AUTHOR);
4956 if (err)
4957 goto done;
4959 committer_time = got_object_commit_get_committer_time(commit);
4960 datestr = get_datestr(&committer_time, datebuf);
4961 if (datestr) {
4962 n = fprintf(outfile, "date: %s UTC\n", datestr);
4963 if (n < 0) {
4964 err = got_error_from_errno("fprintf");
4965 goto done;
4967 outoff += n;
4968 err = add_line_metadata(lines, nlines, outoff,
4969 GOT_DIFF_LINE_DATE);
4970 if (err)
4971 goto done;
4973 if (got_object_commit_get_nparents(commit) > 1) {
4974 const struct got_object_id_queue *parent_ids;
4975 struct got_object_qid *qid;
4976 int pn = 1;
4977 parent_ids = got_object_commit_get_parent_ids(commit);
4978 STAILQ_FOREACH(qid, parent_ids, entry) {
4979 err = got_object_id_str(&id_str, &qid->id);
4980 if (err)
4981 goto done;
4982 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4983 if (n < 0) {
4984 err = got_error_from_errno("fprintf");
4985 goto done;
4987 outoff += n;
4988 err = add_line_metadata(lines, nlines, outoff,
4989 GOT_DIFF_LINE_META);
4990 if (err)
4991 goto done;
4992 free(id_str);
4993 id_str = NULL;
4997 err = got_object_commit_get_logmsg(&logmsg, commit);
4998 if (err)
4999 goto done;
5000 s = logmsg;
5001 while ((line = strsep(&s, "\n")) != NULL) {
5002 n = fprintf(outfile, "%s\n", line);
5003 if (n < 0) {
5004 err = got_error_from_errno("fprintf");
5005 goto done;
5007 outoff += n;
5008 err = add_line_metadata(lines, nlines, outoff,
5009 GOT_DIFF_LINE_LOGMSG);
5010 if (err)
5011 goto done;
5014 TAILQ_FOREACH(pe, dsa->paths, entry) {
5015 struct got_diff_changed_path *cp = pe->data;
5016 int pad = dsa->max_path_len - pe->path_len + 1;
5018 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5019 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5020 dsa->rm_cols + 1, cp->rm);
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,
5027 GOT_DIFF_LINE_CHANGES);
5028 if (err)
5029 goto done;
5032 fputc('\n', outfile);
5033 outoff++;
5034 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5035 if (err)
5036 goto done;
5038 n = fprintf(outfile,
5039 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5040 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5041 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5042 if (n < 0) {
5043 err = got_error_from_errno("fprintf");
5044 goto done;
5046 outoff += n;
5047 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5048 if (err)
5049 goto done;
5051 fputc('\n', outfile);
5052 outoff++;
5053 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5054 done:
5055 free(id_str);
5056 free(logmsg);
5057 free(refs_str);
5058 got_object_commit_close(commit);
5059 if (err) {
5060 free(*lines);
5061 *lines = NULL;
5062 *nlines = 0;
5064 return err;
5067 static const struct got_error *
5068 create_diff(struct tog_diff_view_state *s)
5070 const struct got_error *err = NULL;
5071 FILE *f = NULL, *tmp_diff_file = NULL;
5072 int obj_type;
5073 struct got_diff_line *lines = NULL;
5074 struct got_pathlist_head changed_paths;
5076 TAILQ_INIT(&changed_paths);
5078 free(s->lines);
5079 s->lines = malloc(sizeof(*s->lines));
5080 if (s->lines == NULL)
5081 return got_error_from_errno("malloc");
5082 s->nlines = 0;
5084 f = got_opentemp();
5085 if (f == NULL) {
5086 err = got_error_from_errno("got_opentemp");
5087 goto done;
5089 tmp_diff_file = got_opentemp();
5090 if (tmp_diff_file == NULL) {
5091 err = got_error_from_errno("got_opentemp");
5092 goto done;
5094 if (s->f && fclose(s->f) == EOF) {
5095 err = got_error_from_errno("fclose");
5096 goto done;
5098 s->f = f;
5100 if (s->id1)
5101 err = got_object_get_type(&obj_type, s->repo, s->id1);
5102 else
5103 err = got_object_get_type(&obj_type, s->repo, s->id2);
5104 if (err)
5105 goto done;
5107 switch (obj_type) {
5108 case GOT_OBJ_TYPE_BLOB:
5109 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5110 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5111 s->label1, s->label2, tog_diff_algo, s->diff_context,
5112 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5113 s->f);
5114 break;
5115 case GOT_OBJ_TYPE_TREE:
5116 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5117 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5118 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5119 s->force_text_diff, NULL, s->repo, s->f);
5120 break;
5121 case GOT_OBJ_TYPE_COMMIT: {
5122 const struct got_object_id_queue *parent_ids;
5123 struct got_object_qid *pid;
5124 struct got_commit_object *commit2;
5125 struct got_reflist_head *refs;
5126 size_t nlines = 0;
5127 struct got_diffstat_cb_arg dsa = {
5128 0, 0, 0, 0, 0, 0,
5129 &changed_paths,
5130 s->ignore_whitespace,
5131 s->force_text_diff,
5132 tog_diff_algo
5135 lines = malloc(sizeof(*lines));
5136 if (lines == NULL) {
5137 err = got_error_from_errno("malloc");
5138 goto done;
5141 /* build diff first in tmp file then append to commit info */
5142 err = got_diff_objects_as_commits(&lines, &nlines,
5143 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5144 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5145 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5146 if (err)
5147 break;
5149 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5150 if (err)
5151 goto done;
5152 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5153 /* Show commit info if we're diffing to a parent/root commit. */
5154 if (s->id1 == NULL) {
5155 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5156 refs, s->repo, s->ignore_whitespace,
5157 s->force_text_diff, &dsa, s->f);
5158 if (err)
5159 goto done;
5160 } else {
5161 parent_ids = got_object_commit_get_parent_ids(commit2);
5162 STAILQ_FOREACH(pid, parent_ids, entry) {
5163 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5164 err = write_commit_info(&s->lines,
5165 &s->nlines, s->id2, refs, s->repo,
5166 s->ignore_whitespace,
5167 s->force_text_diff, &dsa, s->f);
5168 if (err)
5169 goto done;
5170 break;
5174 got_object_commit_close(commit2);
5176 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5177 lines, nlines);
5178 break;
5180 default:
5181 err = got_error(GOT_ERR_OBJ_TYPE);
5182 break;
5184 done:
5185 free(lines);
5186 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5187 if (s->f && fflush(s->f) != 0 && err == NULL)
5188 err = got_error_from_errno("fflush");
5189 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5190 err = got_error_from_errno("fclose");
5191 return err;
5194 static void
5195 diff_view_indicate_progress(struct tog_view *view)
5197 mvwaddstr(view->window, 0, 0, "diffing...");
5198 update_panels();
5199 doupdate();
5202 static const struct got_error *
5203 search_start_diff_view(struct tog_view *view)
5205 struct tog_diff_view_state *s = &view->state.diff;
5207 s->matched_line = 0;
5208 return NULL;
5211 static void
5212 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5213 size_t *nlines, int **first, int **last, int **match, int **selected)
5215 struct tog_diff_view_state *s = &view->state.diff;
5217 *f = s->f;
5218 *nlines = s->nlines;
5219 *line_offsets = NULL;
5220 *match = &s->matched_line;
5221 *first = &s->first_displayed_line;
5222 *last = &s->last_displayed_line;
5223 *selected = &s->selected_line;
5226 static const struct got_error *
5227 search_next_view_match(struct tog_view *view)
5229 const struct got_error *err = NULL;
5230 FILE *f;
5231 int lineno;
5232 char *line = NULL;
5233 size_t linesize = 0;
5234 ssize_t linelen;
5235 off_t *line_offsets;
5236 size_t nlines = 0;
5237 int *first, *last, *match, *selected;
5239 if (!view->search_setup)
5240 return got_error_msg(GOT_ERR_NOT_IMPL,
5241 "view search not supported");
5242 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5243 &match, &selected);
5245 if (!view->searching) {
5246 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5247 return NULL;
5250 if (*match) {
5251 if (view->searching == TOG_SEARCH_FORWARD)
5252 lineno = *first + 1;
5253 else
5254 lineno = *first - 1;
5255 } else
5256 lineno = *first - 1 + *selected;
5258 while (1) {
5259 off_t offset;
5261 if (lineno <= 0 || lineno > nlines) {
5262 if (*match == 0) {
5263 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5264 break;
5267 if (view->searching == TOG_SEARCH_FORWARD)
5268 lineno = 1;
5269 else
5270 lineno = nlines;
5273 offset = view->type == TOG_VIEW_DIFF ?
5274 view->state.diff.lines[lineno - 1].offset :
5275 line_offsets[lineno - 1];
5276 if (fseeko(f, offset, SEEK_SET) != 0) {
5277 free(line);
5278 return got_error_from_errno("fseeko");
5280 linelen = getline(&line, &linesize, f);
5281 if (linelen != -1) {
5282 char *exstr;
5283 err = expand_tab(&exstr, line);
5284 if (err)
5285 break;
5286 if (match_line(exstr, &view->regex, 1,
5287 &view->regmatch)) {
5288 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5289 *match = lineno;
5290 free(exstr);
5291 break;
5293 free(exstr);
5295 if (view->searching == TOG_SEARCH_FORWARD)
5296 lineno++;
5297 else
5298 lineno--;
5300 free(line);
5302 if (*match) {
5303 *first = *match;
5304 *selected = 1;
5307 return err;
5310 static const struct got_error *
5311 close_diff_view(struct tog_view *view)
5313 const struct got_error *err = NULL;
5314 struct tog_diff_view_state *s = &view->state.diff;
5316 free(s->id1);
5317 s->id1 = NULL;
5318 free(s->id2);
5319 s->id2 = NULL;
5320 if (s->f && fclose(s->f) == EOF)
5321 err = got_error_from_errno("fclose");
5322 s->f = NULL;
5323 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5324 err = got_error_from_errno("fclose");
5325 s->f1 = NULL;
5326 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5327 err = got_error_from_errno("fclose");
5328 s->f2 = NULL;
5329 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5330 err = got_error_from_errno("close");
5331 s->fd1 = -1;
5332 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5333 err = got_error_from_errno("close");
5334 s->fd2 = -1;
5335 free(s->lines);
5336 s->lines = NULL;
5337 s->nlines = 0;
5338 return err;
5341 static const struct got_error *
5342 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5343 struct got_object_id *id2, const char *label1, const char *label2,
5344 int diff_context, int ignore_whitespace, int force_text_diff,
5345 struct tog_view *parent_view, struct got_repository *repo)
5347 const struct got_error *err;
5348 struct tog_diff_view_state *s = &view->state.diff;
5350 memset(s, 0, sizeof(*s));
5351 s->fd1 = -1;
5352 s->fd2 = -1;
5354 if (id1 != NULL && id2 != NULL) {
5355 int type1, type2;
5356 err = got_object_get_type(&type1, repo, id1);
5357 if (err)
5358 return err;
5359 err = got_object_get_type(&type2, repo, id2);
5360 if (err)
5361 return err;
5363 if (type1 != type2)
5364 return got_error(GOT_ERR_OBJ_TYPE);
5366 s->first_displayed_line = 1;
5367 s->last_displayed_line = view->nlines;
5368 s->selected_line = 1;
5369 s->repo = repo;
5370 s->id1 = id1;
5371 s->id2 = id2;
5372 s->label1 = label1;
5373 s->label2 = label2;
5375 if (id1) {
5376 s->id1 = got_object_id_dup(id1);
5377 if (s->id1 == NULL)
5378 return got_error_from_errno("got_object_id_dup");
5379 } else
5380 s->id1 = NULL;
5382 s->id2 = got_object_id_dup(id2);
5383 if (s->id2 == NULL) {
5384 err = got_error_from_errno("got_object_id_dup");
5385 goto done;
5388 s->f1 = got_opentemp();
5389 if (s->f1 == NULL) {
5390 err = got_error_from_errno("got_opentemp");
5391 goto done;
5394 s->f2 = got_opentemp();
5395 if (s->f2 == NULL) {
5396 err = got_error_from_errno("got_opentemp");
5397 goto done;
5400 s->fd1 = got_opentempfd();
5401 if (s->fd1 == -1) {
5402 err = got_error_from_errno("got_opentempfd");
5403 goto done;
5406 s->fd2 = got_opentempfd();
5407 if (s->fd2 == -1) {
5408 err = got_error_from_errno("got_opentempfd");
5409 goto done;
5412 s->diff_context = diff_context;
5413 s->ignore_whitespace = ignore_whitespace;
5414 s->force_text_diff = force_text_diff;
5415 s->parent_view = parent_view;
5416 s->repo = repo;
5418 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5419 int rc;
5421 rc = init_pair(GOT_DIFF_LINE_MINUS,
5422 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5423 if (rc != ERR)
5424 rc = init_pair(GOT_DIFF_LINE_PLUS,
5425 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5426 if (rc != ERR)
5427 rc = init_pair(GOT_DIFF_LINE_HUNK,
5428 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5429 if (rc != ERR)
5430 rc = init_pair(GOT_DIFF_LINE_META,
5431 get_color_value("TOG_COLOR_DIFF_META"), -1);
5432 if (rc != ERR)
5433 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5434 get_color_value("TOG_COLOR_DIFF_META"), -1);
5435 if (rc != ERR)
5436 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5437 get_color_value("TOG_COLOR_DIFF_META"), -1);
5438 if (rc != ERR)
5439 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5440 get_color_value("TOG_COLOR_DIFF_META"), -1);
5441 if (rc != ERR)
5442 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5443 get_color_value("TOG_COLOR_AUTHOR"), -1);
5444 if (rc != ERR)
5445 rc = init_pair(GOT_DIFF_LINE_DATE,
5446 get_color_value("TOG_COLOR_DATE"), -1);
5447 if (rc == ERR) {
5448 err = got_error(GOT_ERR_RANGE);
5449 goto done;
5453 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5454 view_is_splitscreen(view))
5455 show_log_view(parent_view); /* draw border */
5456 diff_view_indicate_progress(view);
5458 err = create_diff(s);
5460 view->show = show_diff_view;
5461 view->input = input_diff_view;
5462 view->reset = reset_diff_view;
5463 view->close = close_diff_view;
5464 view->search_start = search_start_diff_view;
5465 view->search_setup = search_setup_diff_view;
5466 view->search_next = search_next_view_match;
5467 done:
5468 if (err)
5469 close_diff_view(view);
5470 return err;
5473 static const struct got_error *
5474 show_diff_view(struct tog_view *view)
5476 const struct got_error *err;
5477 struct tog_diff_view_state *s = &view->state.diff;
5478 char *id_str1 = NULL, *id_str2, *header;
5479 const char *label1, *label2;
5481 if (s->id1) {
5482 err = got_object_id_str(&id_str1, s->id1);
5483 if (err)
5484 return err;
5485 label1 = s->label1 ? s->label1 : id_str1;
5486 } else
5487 label1 = "/dev/null";
5489 err = got_object_id_str(&id_str2, s->id2);
5490 if (err)
5491 return err;
5492 label2 = s->label2 ? s->label2 : id_str2;
5494 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5495 err = got_error_from_errno("asprintf");
5496 free(id_str1);
5497 free(id_str2);
5498 return err;
5500 free(id_str1);
5501 free(id_str2);
5503 err = draw_file(view, header);
5504 free(header);
5505 return err;
5508 static const struct got_error *
5509 set_selected_commit(struct tog_diff_view_state *s,
5510 struct commit_queue_entry *entry)
5512 const struct got_error *err;
5513 const struct got_object_id_queue *parent_ids;
5514 struct got_commit_object *selected_commit;
5515 struct got_object_qid *pid;
5517 free(s->id2);
5518 s->id2 = got_object_id_dup(entry->id);
5519 if (s->id2 == NULL)
5520 return got_error_from_errno("got_object_id_dup");
5522 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5523 if (err)
5524 return err;
5525 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5526 free(s->id1);
5527 pid = STAILQ_FIRST(parent_ids);
5528 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5529 got_object_commit_close(selected_commit);
5530 return NULL;
5533 static const struct got_error *
5534 reset_diff_view(struct tog_view *view)
5536 struct tog_diff_view_state *s = &view->state.diff;
5538 view->count = 0;
5539 wclear(view->window);
5540 s->first_displayed_line = 1;
5541 s->last_displayed_line = view->nlines;
5542 s->matched_line = 0;
5543 diff_view_indicate_progress(view);
5544 return create_diff(s);
5547 static void
5548 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5550 int start, i;
5552 i = start = s->first_displayed_line - 1;
5554 while (s->lines[i].type != type) {
5555 if (i == 0)
5556 i = s->nlines - 1;
5557 if (--i == start)
5558 return; /* do nothing, requested type not in file */
5561 s->selected_line = 1;
5562 s->first_displayed_line = i;
5565 static void
5566 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5568 int start, i;
5570 i = start = s->first_displayed_line + 1;
5572 while (s->lines[i].type != type) {
5573 if (i == s->nlines - 1)
5574 i = 0;
5575 if (++i == start)
5576 return; /* do nothing, requested type not in file */
5579 s->selected_line = 1;
5580 s->first_displayed_line = i;
5583 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5584 int, int, int);
5585 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5586 int, int);
5588 static const struct got_error *
5589 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5591 const struct got_error *err = NULL;
5592 struct tog_diff_view_state *s = &view->state.diff;
5593 struct tog_log_view_state *ls;
5594 struct commit_queue_entry *old_selected_entry;
5595 char *line = NULL;
5596 size_t linesize = 0;
5597 ssize_t linelen;
5598 int i, nscroll = view->nlines - 1, up = 0;
5600 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5602 switch (ch) {
5603 case '0':
5604 case '$':
5605 case KEY_RIGHT:
5606 case 'l':
5607 case KEY_LEFT:
5608 case 'h':
5609 horizontal_scroll_input(view, ch);
5610 break;
5611 case 'a':
5612 case 'w':
5613 if (ch == 'a') {
5614 s->force_text_diff = !s->force_text_diff;
5615 view->action = s->force_text_diff ?
5616 "force ASCII text enabled" :
5617 "force ASCII text disabled";
5619 else if (ch == 'w') {
5620 s->ignore_whitespace = !s->ignore_whitespace;
5621 view->action = s->ignore_whitespace ?
5622 "ignore whitespace enabled" :
5623 "ignore whitespace disabled";
5625 err = reset_diff_view(view);
5626 break;
5627 case 'g':
5628 case KEY_HOME:
5629 s->first_displayed_line = 1;
5630 view->count = 0;
5631 break;
5632 case 'G':
5633 case KEY_END:
5634 view->count = 0;
5635 if (s->eof)
5636 break;
5638 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5639 s->eof = 1;
5640 break;
5641 case 'k':
5642 case KEY_UP:
5643 case CTRL('p'):
5644 if (s->first_displayed_line > 1)
5645 s->first_displayed_line--;
5646 else
5647 view->count = 0;
5648 break;
5649 case CTRL('u'):
5650 case 'u':
5651 nscroll /= 2;
5652 /* FALL THROUGH */
5653 case KEY_PPAGE:
5654 case CTRL('b'):
5655 case 'b':
5656 if (s->first_displayed_line == 1) {
5657 view->count = 0;
5658 break;
5660 i = 0;
5661 while (i++ < nscroll && s->first_displayed_line > 1)
5662 s->first_displayed_line--;
5663 break;
5664 case 'j':
5665 case KEY_DOWN:
5666 case CTRL('n'):
5667 if (!s->eof)
5668 s->first_displayed_line++;
5669 else
5670 view->count = 0;
5671 break;
5672 case CTRL('d'):
5673 case 'd':
5674 nscroll /= 2;
5675 /* FALL THROUGH */
5676 case KEY_NPAGE:
5677 case CTRL('f'):
5678 case 'f':
5679 case ' ':
5680 if (s->eof) {
5681 view->count = 0;
5682 break;
5684 i = 0;
5685 while (!s->eof && i++ < nscroll) {
5686 linelen = getline(&line, &linesize, s->f);
5687 s->first_displayed_line++;
5688 if (linelen == -1) {
5689 if (feof(s->f)) {
5690 s->eof = 1;
5691 } else
5692 err = got_ferror(s->f, GOT_ERR_IO);
5693 break;
5696 free(line);
5697 break;
5698 case '(':
5699 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5700 break;
5701 case ')':
5702 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5703 break;
5704 case '{':
5705 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5706 break;
5707 case '}':
5708 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5709 break;
5710 case '[':
5711 if (s->diff_context > 0) {
5712 s->diff_context--;
5713 s->matched_line = 0;
5714 diff_view_indicate_progress(view);
5715 err = create_diff(s);
5716 if (s->first_displayed_line + view->nlines - 1 >
5717 s->nlines) {
5718 s->first_displayed_line = 1;
5719 s->last_displayed_line = view->nlines;
5721 } else
5722 view->count = 0;
5723 break;
5724 case ']':
5725 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5726 s->diff_context++;
5727 s->matched_line = 0;
5728 diff_view_indicate_progress(view);
5729 err = create_diff(s);
5730 } else
5731 view->count = 0;
5732 break;
5733 case '<':
5734 case ',':
5735 case 'K':
5736 up = 1;
5737 /* FALL THROUGH */
5738 case '>':
5739 case '.':
5740 case 'J':
5741 if (s->parent_view == NULL) {
5742 view->count = 0;
5743 break;
5745 s->parent_view->count = view->count;
5747 if (s->parent_view->type == TOG_VIEW_LOG) {
5748 ls = &s->parent_view->state.log;
5749 old_selected_entry = ls->selected_entry;
5751 err = input_log_view(NULL, s->parent_view,
5752 up ? KEY_UP : KEY_DOWN);
5753 if (err)
5754 break;
5755 view->count = s->parent_view->count;
5757 if (old_selected_entry == ls->selected_entry)
5758 break;
5760 err = set_selected_commit(s, ls->selected_entry);
5761 if (err)
5762 break;
5763 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5764 struct tog_blame_view_state *bs;
5765 struct got_object_id *id, *prev_id;
5767 bs = &s->parent_view->state.blame;
5768 prev_id = get_annotation_for_line(bs->blame.lines,
5769 bs->blame.nlines, bs->last_diffed_line);
5771 err = input_blame_view(&view, s->parent_view,
5772 up ? KEY_UP : KEY_DOWN);
5773 if (err)
5774 break;
5775 view->count = s->parent_view->count;
5777 if (prev_id == NULL)
5778 break;
5779 id = get_selected_commit_id(bs->blame.lines,
5780 bs->blame.nlines, bs->first_displayed_line,
5781 bs->selected_line);
5782 if (id == NULL)
5783 break;
5785 if (!got_object_id_cmp(prev_id, id))
5786 break;
5788 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5789 if (err)
5790 break;
5792 s->first_displayed_line = 1;
5793 s->last_displayed_line = view->nlines;
5794 s->matched_line = 0;
5795 view->x = 0;
5797 diff_view_indicate_progress(view);
5798 err = create_diff(s);
5799 break;
5800 default:
5801 view->count = 0;
5802 break;
5805 return err;
5808 static const struct got_error *
5809 cmd_diff(int argc, char *argv[])
5811 const struct got_error *io_err, *error;
5812 struct got_repository *repo = NULL;
5813 struct got_worktree *worktree = NULL;
5814 struct got_object_id *id1 = NULL, *id2 = NULL;
5815 char *repo_path = NULL, *cwd = NULL;
5816 char *id_str1 = NULL, *id_str2 = NULL;
5817 char *label1 = NULL, *label2 = NULL;
5818 int diff_context = 3, ignore_whitespace = 0;
5819 int ch, force_text_diff = 0;
5820 const char *errstr;
5821 struct tog_view *view;
5822 struct tog_io *tog_io = NULL;
5823 int *pack_fds = NULL;
5825 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5826 switch (ch) {
5827 case 'a':
5828 force_text_diff = 1;
5829 break;
5830 case 'C':
5831 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5832 &errstr);
5833 if (errstr != NULL)
5834 errx(1, "number of context lines is %s: %s",
5835 errstr, errstr);
5836 break;
5837 case 'r':
5838 repo_path = realpath(optarg, NULL);
5839 if (repo_path == NULL)
5840 return got_error_from_errno2("realpath",
5841 optarg);
5842 got_path_strip_trailing_slashes(repo_path);
5843 break;
5844 case 'w':
5845 ignore_whitespace = 1;
5846 break;
5847 default:
5848 usage_diff();
5849 /* NOTREACHED */
5853 argc -= optind;
5854 argv += optind;
5856 if (argc == 0) {
5857 usage_diff(); /* TODO show local worktree changes */
5858 } else if (argc == 2) {
5859 id_str1 = argv[0];
5860 id_str2 = argv[1];
5861 } else
5862 usage_diff();
5864 error = got_repo_pack_fds_open(&pack_fds);
5865 if (error)
5866 goto done;
5868 if (repo_path == NULL) {
5869 cwd = getcwd(NULL, 0);
5870 if (cwd == NULL)
5871 return got_error_from_errno("getcwd");
5872 error = got_worktree_open(&worktree, cwd);
5873 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5874 goto done;
5875 if (worktree)
5876 repo_path =
5877 strdup(got_worktree_get_repo_path(worktree));
5878 else
5879 repo_path = strdup(cwd);
5880 if (repo_path == NULL) {
5881 error = got_error_from_errno("strdup");
5882 goto done;
5886 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5887 if (error)
5888 goto done;
5890 error = init_curses(&tog_io);
5891 if (error)
5892 goto done;
5894 error = apply_unveil(got_repo_get_path(repo), NULL);
5895 if (error)
5896 goto done;
5898 error = tog_load_refs(repo, 0);
5899 if (error)
5900 goto done;
5902 error = got_repo_match_object_id(&id1, &label1, id_str1,
5903 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5904 if (error)
5905 goto done;
5907 error = got_repo_match_object_id(&id2, &label2, id_str2,
5908 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5909 if (error)
5910 goto done;
5912 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5913 if (view == NULL) {
5914 error = got_error_from_errno("view_open");
5915 goto done;
5917 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5918 ignore_whitespace, force_text_diff, NULL, repo);
5919 if (error)
5920 goto done;
5921 error = view_loop(view, tog_io);
5922 done:
5923 free(label1);
5924 free(label2);
5925 free(repo_path);
5926 free(cwd);
5927 if (repo) {
5928 const struct got_error *close_err = got_repo_close(repo);
5929 if (error == NULL)
5930 error = close_err;
5932 if (worktree)
5933 got_worktree_close(worktree);
5934 if (pack_fds) {
5935 const struct got_error *pack_err =
5936 got_repo_pack_fds_close(pack_fds);
5937 if (error == NULL)
5938 error = pack_err;
5940 if (tog_io != NULL) {
5941 io_err = tog_io_close(tog_io);
5942 if (error == NULL)
5943 error = io_err;
5945 tog_free_refs();
5946 return error;
5949 __dead static void
5950 usage_blame(void)
5952 endwin();
5953 fprintf(stderr,
5954 "usage: %s blame [-c commit] [-r repository-path] path\n",
5955 getprogname());
5956 exit(1);
5959 struct tog_blame_line {
5960 int annotated;
5961 struct got_object_id *id;
5964 static const struct got_error *
5965 draw_blame(struct tog_view *view)
5967 struct tog_blame_view_state *s = &view->state.blame;
5968 struct tog_blame *blame = &s->blame;
5969 regmatch_t *regmatch = &view->regmatch;
5970 const struct got_error *err;
5971 int lineno = 0, nprinted = 0;
5972 char *line = NULL;
5973 size_t linesize = 0;
5974 ssize_t linelen;
5975 wchar_t *wline;
5976 int width;
5977 struct tog_blame_line *blame_line;
5978 struct got_object_id *prev_id = NULL;
5979 char *id_str;
5980 struct tog_color *tc;
5982 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5983 if (err)
5984 return err;
5986 rewind(blame->f);
5987 werase(view->window);
5989 if (asprintf(&line, "commit %s", id_str) == -1) {
5990 err = got_error_from_errno("asprintf");
5991 free(id_str);
5992 return err;
5995 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5996 free(line);
5997 line = NULL;
5998 if (err)
5999 return err;
6000 if (view_needs_focus_indication(view))
6001 wstandout(view->window);
6002 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6003 if (tc)
6004 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6005 waddwstr(view->window, wline);
6006 while (width++ < view->ncols)
6007 waddch(view->window, ' ');
6008 if (tc)
6009 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6010 if (view_needs_focus_indication(view))
6011 wstandend(view->window);
6012 free(wline);
6013 wline = NULL;
6015 if (view->gline > blame->nlines)
6016 view->gline = blame->nlines;
6018 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6019 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6020 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6021 free(id_str);
6022 return got_error_from_errno("asprintf");
6024 free(id_str);
6025 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6026 free(line);
6027 line = NULL;
6028 if (err)
6029 return err;
6030 waddwstr(view->window, wline);
6031 free(wline);
6032 wline = NULL;
6033 if (width < view->ncols - 1)
6034 waddch(view->window, '\n');
6036 s->eof = 0;
6037 view->maxx = 0;
6038 while (nprinted < view->nlines - 2) {
6039 linelen = getline(&line, &linesize, blame->f);
6040 if (linelen == -1) {
6041 if (feof(blame->f)) {
6042 s->eof = 1;
6043 break;
6045 free(line);
6046 return got_ferror(blame->f, GOT_ERR_IO);
6048 if (++lineno < s->first_displayed_line)
6049 continue;
6050 if (view->gline && !gotoline(view, &lineno, &nprinted))
6051 continue;
6053 /* Set view->maxx based on full line length. */
6054 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6055 if (err) {
6056 free(line);
6057 return err;
6059 free(wline);
6060 wline = NULL;
6061 view->maxx = MAX(view->maxx, width);
6063 if (nprinted == s->selected_line - 1)
6064 wstandout(view->window);
6066 if (blame->nlines > 0) {
6067 blame_line = &blame->lines[lineno - 1];
6068 if (blame_line->annotated && prev_id &&
6069 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6070 !(nprinted == s->selected_line - 1)) {
6071 waddstr(view->window, " ");
6072 } else if (blame_line->annotated) {
6073 char *id_str;
6074 err = got_object_id_str(&id_str,
6075 blame_line->id);
6076 if (err) {
6077 free(line);
6078 return err;
6080 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6081 if (tc)
6082 wattr_on(view->window,
6083 COLOR_PAIR(tc->colorpair), NULL);
6084 wprintw(view->window, "%.8s", id_str);
6085 if (tc)
6086 wattr_off(view->window,
6087 COLOR_PAIR(tc->colorpair), NULL);
6088 free(id_str);
6089 prev_id = blame_line->id;
6090 } else {
6091 waddstr(view->window, "........");
6092 prev_id = NULL;
6094 } else {
6095 waddstr(view->window, "........");
6096 prev_id = NULL;
6099 if (nprinted == s->selected_line - 1)
6100 wstandend(view->window);
6101 waddstr(view->window, " ");
6103 if (view->ncols <= 9) {
6104 width = 9;
6105 } else if (s->first_displayed_line + nprinted ==
6106 s->matched_line &&
6107 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6108 err = add_matched_line(&width, line, view->ncols - 9, 9,
6109 view->window, view->x, regmatch);
6110 if (err) {
6111 free(line);
6112 return err;
6114 width += 9;
6115 } else {
6116 int skip;
6117 err = format_line(&wline, &width, &skip, line,
6118 view->x, view->ncols - 9, 9, 1);
6119 if (err) {
6120 free(line);
6121 return err;
6123 waddwstr(view->window, &wline[skip]);
6124 width += 9;
6125 free(wline);
6126 wline = NULL;
6129 if (width <= view->ncols - 1)
6130 waddch(view->window, '\n');
6131 if (++nprinted == 1)
6132 s->first_displayed_line = lineno;
6134 free(line);
6135 s->last_displayed_line = lineno;
6137 view_border(view);
6139 return NULL;
6142 static const struct got_error *
6143 blame_cb(void *arg, int nlines, int lineno,
6144 struct got_commit_object *commit, struct got_object_id *id)
6146 const struct got_error *err = NULL;
6147 struct tog_blame_cb_args *a = arg;
6148 struct tog_blame_line *line;
6149 int errcode;
6151 if (nlines != a->nlines ||
6152 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6153 return got_error(GOT_ERR_RANGE);
6155 errcode = pthread_mutex_lock(&tog_mutex);
6156 if (errcode)
6157 return got_error_set_errno(errcode, "pthread_mutex_lock");
6159 if (*a->quit) { /* user has quit the blame view */
6160 err = got_error(GOT_ERR_ITER_COMPLETED);
6161 goto done;
6164 if (lineno == -1)
6165 goto done; /* no change in this commit */
6167 line = &a->lines[lineno - 1];
6168 if (line->annotated)
6169 goto done;
6171 line->id = got_object_id_dup(id);
6172 if (line->id == NULL) {
6173 err = got_error_from_errno("got_object_id_dup");
6174 goto done;
6176 line->annotated = 1;
6177 done:
6178 errcode = pthread_mutex_unlock(&tog_mutex);
6179 if (errcode)
6180 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6181 return err;
6184 static void *
6185 blame_thread(void *arg)
6187 const struct got_error *err, *close_err;
6188 struct tog_blame_thread_args *ta = arg;
6189 struct tog_blame_cb_args *a = ta->cb_args;
6190 int errcode, fd1 = -1, fd2 = -1;
6191 FILE *f1 = NULL, *f2 = NULL;
6193 fd1 = got_opentempfd();
6194 if (fd1 == -1)
6195 return (void *)got_error_from_errno("got_opentempfd");
6197 fd2 = got_opentempfd();
6198 if (fd2 == -1) {
6199 err = got_error_from_errno("got_opentempfd");
6200 goto done;
6203 f1 = got_opentemp();
6204 if (f1 == NULL) {
6205 err = (void *)got_error_from_errno("got_opentemp");
6206 goto done;
6208 f2 = got_opentemp();
6209 if (f2 == NULL) {
6210 err = (void *)got_error_from_errno("got_opentemp");
6211 goto done;
6214 err = block_signals_used_by_main_thread();
6215 if (err)
6216 goto done;
6218 err = got_blame(ta->path, a->commit_id, ta->repo,
6219 tog_diff_algo, blame_cb, ta->cb_args,
6220 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6221 if (err && err->code == GOT_ERR_CANCELLED)
6222 err = NULL;
6224 errcode = pthread_mutex_lock(&tog_mutex);
6225 if (errcode) {
6226 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6227 goto done;
6230 close_err = got_repo_close(ta->repo);
6231 if (err == NULL)
6232 err = close_err;
6233 ta->repo = NULL;
6234 *ta->complete = 1;
6236 errcode = pthread_mutex_unlock(&tog_mutex);
6237 if (errcode && err == NULL)
6238 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6240 done:
6241 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6242 err = got_error_from_errno("close");
6243 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6244 err = got_error_from_errno("close");
6245 if (f1 && fclose(f1) == EOF && err == NULL)
6246 err = got_error_from_errno("fclose");
6247 if (f2 && fclose(f2) == EOF && err == NULL)
6248 err = got_error_from_errno("fclose");
6250 return (void *)err;
6253 static struct got_object_id *
6254 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6255 int first_displayed_line, int selected_line)
6257 struct tog_blame_line *line;
6259 if (nlines <= 0)
6260 return NULL;
6262 line = &lines[first_displayed_line - 1 + selected_line - 1];
6263 if (!line->annotated)
6264 return NULL;
6266 return line->id;
6269 static struct got_object_id *
6270 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6271 int lineno)
6273 struct tog_blame_line *line;
6275 if (nlines <= 0 || lineno >= nlines)
6276 return NULL;
6278 line = &lines[lineno - 1];
6279 if (!line->annotated)
6280 return NULL;
6282 return line->id;
6285 static const struct got_error *
6286 stop_blame(struct tog_blame *blame)
6288 const struct got_error *err = NULL;
6289 int i;
6291 if (blame->thread) {
6292 int errcode;
6293 errcode = pthread_mutex_unlock(&tog_mutex);
6294 if (errcode)
6295 return got_error_set_errno(errcode,
6296 "pthread_mutex_unlock");
6297 errcode = pthread_join(blame->thread, (void **)&err);
6298 if (errcode)
6299 return got_error_set_errno(errcode, "pthread_join");
6300 errcode = pthread_mutex_lock(&tog_mutex);
6301 if (errcode)
6302 return got_error_set_errno(errcode,
6303 "pthread_mutex_lock");
6304 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6305 err = NULL;
6306 blame->thread = 0; //NULL;
6308 if (blame->thread_args.repo) {
6309 const struct got_error *close_err;
6310 close_err = got_repo_close(blame->thread_args.repo);
6311 if (err == NULL)
6312 err = close_err;
6313 blame->thread_args.repo = NULL;
6315 if (blame->f) {
6316 if (fclose(blame->f) == EOF && err == NULL)
6317 err = got_error_from_errno("fclose");
6318 blame->f = NULL;
6320 if (blame->lines) {
6321 for (i = 0; i < blame->nlines; i++)
6322 free(blame->lines[i].id);
6323 free(blame->lines);
6324 blame->lines = NULL;
6326 free(blame->cb_args.commit_id);
6327 blame->cb_args.commit_id = NULL;
6328 if (blame->pack_fds) {
6329 const struct got_error *pack_err =
6330 got_repo_pack_fds_close(blame->pack_fds);
6331 if (err == NULL)
6332 err = pack_err;
6333 blame->pack_fds = NULL;
6335 return err;
6338 static const struct got_error *
6339 cancel_blame_view(void *arg)
6341 const struct got_error *err = NULL;
6342 int *done = arg;
6343 int errcode;
6345 errcode = pthread_mutex_lock(&tog_mutex);
6346 if (errcode)
6347 return got_error_set_errno(errcode,
6348 "pthread_mutex_unlock");
6350 if (*done)
6351 err = got_error(GOT_ERR_CANCELLED);
6353 errcode = pthread_mutex_unlock(&tog_mutex);
6354 if (errcode)
6355 return got_error_set_errno(errcode,
6356 "pthread_mutex_lock");
6358 return err;
6361 static const struct got_error *
6362 run_blame(struct tog_view *view)
6364 struct tog_blame_view_state *s = &view->state.blame;
6365 struct tog_blame *blame = &s->blame;
6366 const struct got_error *err = NULL;
6367 struct got_commit_object *commit = NULL;
6368 struct got_blob_object *blob = NULL;
6369 struct got_repository *thread_repo = NULL;
6370 struct got_object_id *obj_id = NULL;
6371 int obj_type, fd = -1;
6372 int *pack_fds = NULL;
6374 err = got_object_open_as_commit(&commit, s->repo,
6375 &s->blamed_commit->id);
6376 if (err)
6377 return err;
6379 fd = got_opentempfd();
6380 if (fd == -1) {
6381 err = got_error_from_errno("got_opentempfd");
6382 goto done;
6385 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6386 if (err)
6387 goto done;
6389 err = got_object_get_type(&obj_type, s->repo, obj_id);
6390 if (err)
6391 goto done;
6393 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6394 err = got_error(GOT_ERR_OBJ_TYPE);
6395 goto done;
6398 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6399 if (err)
6400 goto done;
6401 blame->f = got_opentemp();
6402 if (blame->f == NULL) {
6403 err = got_error_from_errno("got_opentemp");
6404 goto done;
6406 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6407 &blame->line_offsets, blame->f, blob);
6408 if (err)
6409 goto done;
6410 if (blame->nlines == 0) {
6411 s->blame_complete = 1;
6412 goto done;
6415 /* Don't include \n at EOF in the blame line count. */
6416 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6417 blame->nlines--;
6419 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6420 if (blame->lines == NULL) {
6421 err = got_error_from_errno("calloc");
6422 goto done;
6425 err = got_repo_pack_fds_open(&pack_fds);
6426 if (err)
6427 goto done;
6428 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6429 pack_fds);
6430 if (err)
6431 goto done;
6433 blame->pack_fds = pack_fds;
6434 blame->cb_args.view = view;
6435 blame->cb_args.lines = blame->lines;
6436 blame->cb_args.nlines = blame->nlines;
6437 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6438 if (blame->cb_args.commit_id == NULL) {
6439 err = got_error_from_errno("got_object_id_dup");
6440 goto done;
6442 blame->cb_args.quit = &s->done;
6444 blame->thread_args.path = s->path;
6445 blame->thread_args.repo = thread_repo;
6446 blame->thread_args.cb_args = &blame->cb_args;
6447 blame->thread_args.complete = &s->blame_complete;
6448 blame->thread_args.cancel_cb = cancel_blame_view;
6449 blame->thread_args.cancel_arg = &s->done;
6450 s->blame_complete = 0;
6452 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6453 s->first_displayed_line = 1;
6454 s->last_displayed_line = view->nlines;
6455 s->selected_line = 1;
6457 s->matched_line = 0;
6459 done:
6460 if (commit)
6461 got_object_commit_close(commit);
6462 if (fd != -1 && close(fd) == -1 && err == NULL)
6463 err = got_error_from_errno("close");
6464 if (blob)
6465 got_object_blob_close(blob);
6466 free(obj_id);
6467 if (err)
6468 stop_blame(blame);
6469 return err;
6472 static const struct got_error *
6473 open_blame_view(struct tog_view *view, char *path,
6474 struct got_object_id *commit_id, struct got_repository *repo)
6476 const struct got_error *err = NULL;
6477 struct tog_blame_view_state *s = &view->state.blame;
6479 STAILQ_INIT(&s->blamed_commits);
6481 s->path = strdup(path);
6482 if (s->path == NULL)
6483 return got_error_from_errno("strdup");
6485 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6486 if (err) {
6487 free(s->path);
6488 return err;
6491 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6492 s->first_displayed_line = 1;
6493 s->last_displayed_line = view->nlines;
6494 s->selected_line = 1;
6495 s->blame_complete = 0;
6496 s->repo = repo;
6497 s->commit_id = commit_id;
6498 memset(&s->blame, 0, sizeof(s->blame));
6500 STAILQ_INIT(&s->colors);
6501 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6502 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6503 get_color_value("TOG_COLOR_COMMIT"));
6504 if (err)
6505 return err;
6508 view->show = show_blame_view;
6509 view->input = input_blame_view;
6510 view->reset = reset_blame_view;
6511 view->close = close_blame_view;
6512 view->search_start = search_start_blame_view;
6513 view->search_setup = search_setup_blame_view;
6514 view->search_next = search_next_view_match;
6516 return run_blame(view);
6519 static const struct got_error *
6520 close_blame_view(struct tog_view *view)
6522 const struct got_error *err = NULL;
6523 struct tog_blame_view_state *s = &view->state.blame;
6525 if (s->blame.thread)
6526 err = stop_blame(&s->blame);
6528 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6529 struct got_object_qid *blamed_commit;
6530 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6531 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6532 got_object_qid_free(blamed_commit);
6535 free(s->path);
6536 free_colors(&s->colors);
6537 return err;
6540 static const struct got_error *
6541 search_start_blame_view(struct tog_view *view)
6543 struct tog_blame_view_state *s = &view->state.blame;
6545 s->matched_line = 0;
6546 return NULL;
6549 static void
6550 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6551 size_t *nlines, int **first, int **last, int **match, int **selected)
6553 struct tog_blame_view_state *s = &view->state.blame;
6555 *f = s->blame.f;
6556 *nlines = s->blame.nlines;
6557 *line_offsets = s->blame.line_offsets;
6558 *match = &s->matched_line;
6559 *first = &s->first_displayed_line;
6560 *last = &s->last_displayed_line;
6561 *selected = &s->selected_line;
6564 static const struct got_error *
6565 show_blame_view(struct tog_view *view)
6567 const struct got_error *err = NULL;
6568 struct tog_blame_view_state *s = &view->state.blame;
6569 int errcode;
6571 if (s->blame.thread == 0 && !s->blame_complete) {
6572 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6573 &s->blame.thread_args);
6574 if (errcode)
6575 return got_error_set_errno(errcode, "pthread_create");
6577 halfdelay(1); /* fast refresh while annotating */
6580 if (s->blame_complete)
6581 halfdelay(10); /* disable fast refresh */
6583 err = draw_blame(view);
6585 view_border(view);
6586 return err;
6589 static const struct got_error *
6590 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6591 struct got_repository *repo, struct got_object_id *id)
6593 struct tog_view *log_view;
6594 const struct got_error *err = NULL;
6596 *new_view = NULL;
6598 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6599 if (log_view == NULL)
6600 return got_error_from_errno("view_open");
6602 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6603 if (err)
6604 view_close(log_view);
6605 else
6606 *new_view = log_view;
6608 return err;
6611 static const struct got_error *
6612 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6614 const struct got_error *err = NULL, *thread_err = NULL;
6615 struct tog_view *diff_view;
6616 struct tog_blame_view_state *s = &view->state.blame;
6617 int eos, nscroll, begin_y = 0, begin_x = 0;
6619 eos = nscroll = view->nlines - 2;
6620 if (view_is_hsplit_top(view))
6621 --eos; /* border */
6623 switch (ch) {
6624 case '0':
6625 case '$':
6626 case KEY_RIGHT:
6627 case 'l':
6628 case KEY_LEFT:
6629 case 'h':
6630 horizontal_scroll_input(view, ch);
6631 break;
6632 case 'q':
6633 s->done = 1;
6634 break;
6635 case 'g':
6636 case KEY_HOME:
6637 s->selected_line = 1;
6638 s->first_displayed_line = 1;
6639 view->count = 0;
6640 break;
6641 case 'G':
6642 case KEY_END:
6643 if (s->blame.nlines < eos) {
6644 s->selected_line = s->blame.nlines;
6645 s->first_displayed_line = 1;
6646 } else {
6647 s->selected_line = eos;
6648 s->first_displayed_line = s->blame.nlines - (eos - 1);
6650 view->count = 0;
6651 break;
6652 case 'k':
6653 case KEY_UP:
6654 case CTRL('p'):
6655 if (s->selected_line > 1)
6656 s->selected_line--;
6657 else if (s->selected_line == 1 &&
6658 s->first_displayed_line > 1)
6659 s->first_displayed_line--;
6660 else
6661 view->count = 0;
6662 break;
6663 case CTRL('u'):
6664 case 'u':
6665 nscroll /= 2;
6666 /* FALL THROUGH */
6667 case KEY_PPAGE:
6668 case CTRL('b'):
6669 case 'b':
6670 if (s->first_displayed_line == 1) {
6671 if (view->count > 1)
6672 nscroll += nscroll;
6673 s->selected_line = MAX(1, s->selected_line - nscroll);
6674 view->count = 0;
6675 break;
6677 if (s->first_displayed_line > nscroll)
6678 s->first_displayed_line -= nscroll;
6679 else
6680 s->first_displayed_line = 1;
6681 break;
6682 case 'j':
6683 case KEY_DOWN:
6684 case CTRL('n'):
6685 if (s->selected_line < eos && s->first_displayed_line +
6686 s->selected_line <= s->blame.nlines)
6687 s->selected_line++;
6688 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6689 s->first_displayed_line++;
6690 else
6691 view->count = 0;
6692 break;
6693 case 'c':
6694 case 'p': {
6695 struct got_object_id *id = NULL;
6697 view->count = 0;
6698 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6699 s->first_displayed_line, s->selected_line);
6700 if (id == NULL)
6701 break;
6702 if (ch == 'p') {
6703 struct got_commit_object *commit, *pcommit;
6704 struct got_object_qid *pid;
6705 struct got_object_id *blob_id = NULL;
6706 int obj_type;
6707 err = got_object_open_as_commit(&commit,
6708 s->repo, id);
6709 if (err)
6710 break;
6711 pid = STAILQ_FIRST(
6712 got_object_commit_get_parent_ids(commit));
6713 if (pid == NULL) {
6714 got_object_commit_close(commit);
6715 break;
6717 /* Check if path history ends here. */
6718 err = got_object_open_as_commit(&pcommit,
6719 s->repo, &pid->id);
6720 if (err)
6721 break;
6722 err = got_object_id_by_path(&blob_id, s->repo,
6723 pcommit, s->path);
6724 got_object_commit_close(pcommit);
6725 if (err) {
6726 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6727 err = NULL;
6728 got_object_commit_close(commit);
6729 break;
6731 err = got_object_get_type(&obj_type, s->repo,
6732 blob_id);
6733 free(blob_id);
6734 /* Can't blame non-blob type objects. */
6735 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6736 got_object_commit_close(commit);
6737 break;
6739 err = got_object_qid_alloc(&s->blamed_commit,
6740 &pid->id);
6741 got_object_commit_close(commit);
6742 } else {
6743 if (got_object_id_cmp(id,
6744 &s->blamed_commit->id) == 0)
6745 break;
6746 err = got_object_qid_alloc(&s->blamed_commit,
6747 id);
6749 if (err)
6750 break;
6751 s->done = 1;
6752 thread_err = stop_blame(&s->blame);
6753 s->done = 0;
6754 if (thread_err)
6755 break;
6756 STAILQ_INSERT_HEAD(&s->blamed_commits,
6757 s->blamed_commit, entry);
6758 err = run_blame(view);
6759 if (err)
6760 break;
6761 break;
6763 case 'C': {
6764 struct got_object_qid *first;
6766 view->count = 0;
6767 first = STAILQ_FIRST(&s->blamed_commits);
6768 if (!got_object_id_cmp(&first->id, s->commit_id))
6769 break;
6770 s->done = 1;
6771 thread_err = stop_blame(&s->blame);
6772 s->done = 0;
6773 if (thread_err)
6774 break;
6775 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6776 got_object_qid_free(s->blamed_commit);
6777 s->blamed_commit =
6778 STAILQ_FIRST(&s->blamed_commits);
6779 err = run_blame(view);
6780 if (err)
6781 break;
6782 break;
6784 case 'L':
6785 view->count = 0;
6786 s->id_to_log = get_selected_commit_id(s->blame.lines,
6787 s->blame.nlines, s->first_displayed_line, s->selected_line);
6788 if (s->id_to_log)
6789 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6790 break;
6791 case KEY_ENTER:
6792 case '\r': {
6793 struct got_object_id *id = NULL;
6794 struct got_object_qid *pid;
6795 struct got_commit_object *commit = NULL;
6797 view->count = 0;
6798 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6799 s->first_displayed_line, s->selected_line);
6800 if (id == NULL)
6801 break;
6802 err = got_object_open_as_commit(&commit, s->repo, id);
6803 if (err)
6804 break;
6805 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6806 if (*new_view) {
6807 /* traversed from diff view, release diff resources */
6808 err = close_diff_view(*new_view);
6809 if (err)
6810 break;
6811 diff_view = *new_view;
6812 } else {
6813 if (view_is_parent_view(view))
6814 view_get_split(view, &begin_y, &begin_x);
6816 diff_view = view_open(0, 0, begin_y, begin_x,
6817 TOG_VIEW_DIFF);
6818 if (diff_view == NULL) {
6819 got_object_commit_close(commit);
6820 err = got_error_from_errno("view_open");
6821 break;
6824 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6825 id, NULL, NULL, 3, 0, 0, view, s->repo);
6826 got_object_commit_close(commit);
6827 if (err) {
6828 view_close(diff_view);
6829 break;
6831 s->last_diffed_line = s->first_displayed_line - 1 +
6832 s->selected_line;
6833 if (*new_view)
6834 break; /* still open from active diff view */
6835 if (view_is_parent_view(view) &&
6836 view->mode == TOG_VIEW_SPLIT_HRZN) {
6837 err = view_init_hsplit(view, begin_y);
6838 if (err)
6839 break;
6842 view->focussed = 0;
6843 diff_view->focussed = 1;
6844 diff_view->mode = view->mode;
6845 diff_view->nlines = view->lines - begin_y;
6846 if (view_is_parent_view(view)) {
6847 view_transfer_size(diff_view, view);
6848 err = view_close_child(view);
6849 if (err)
6850 break;
6851 err = view_set_child(view, diff_view);
6852 if (err)
6853 break;
6854 view->focus_child = 1;
6855 } else
6856 *new_view = diff_view;
6857 if (err)
6858 break;
6859 break;
6861 case CTRL('d'):
6862 case 'd':
6863 nscroll /= 2;
6864 /* FALL THROUGH */
6865 case KEY_NPAGE:
6866 case CTRL('f'):
6867 case 'f':
6868 case ' ':
6869 if (s->last_displayed_line >= s->blame.nlines &&
6870 s->selected_line >= MIN(s->blame.nlines,
6871 view->nlines - 2)) {
6872 view->count = 0;
6873 break;
6875 if (s->last_displayed_line >= s->blame.nlines &&
6876 s->selected_line < view->nlines - 2) {
6877 s->selected_line +=
6878 MIN(nscroll, s->last_displayed_line -
6879 s->first_displayed_line - s->selected_line + 1);
6881 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6882 s->first_displayed_line += nscroll;
6883 else
6884 s->first_displayed_line =
6885 s->blame.nlines - (view->nlines - 3);
6886 break;
6887 case KEY_RESIZE:
6888 if (s->selected_line > view->nlines - 2) {
6889 s->selected_line = MIN(s->blame.nlines,
6890 view->nlines - 2);
6892 break;
6893 default:
6894 view->count = 0;
6895 break;
6897 return thread_err ? thread_err : err;
6900 static const struct got_error *
6901 reset_blame_view(struct tog_view *view)
6903 const struct got_error *err;
6904 struct tog_blame_view_state *s = &view->state.blame;
6906 view->count = 0;
6907 s->done = 1;
6908 err = stop_blame(&s->blame);
6909 s->done = 0;
6910 if (err)
6911 return err;
6912 return run_blame(view);
6915 static const struct got_error *
6916 cmd_blame(int argc, char *argv[])
6918 const struct got_error *io_err, *error;
6919 struct got_repository *repo = NULL;
6920 struct got_worktree *worktree = NULL;
6921 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6922 char *link_target = NULL;
6923 struct got_object_id *commit_id = NULL;
6924 struct got_commit_object *commit = NULL;
6925 char *commit_id_str = NULL;
6926 int ch;
6927 struct tog_view *view;
6928 struct tog_io *tog_io = NULL;
6929 int *pack_fds = NULL;
6931 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6932 switch (ch) {
6933 case 'c':
6934 commit_id_str = optarg;
6935 break;
6936 case 'r':
6937 repo_path = realpath(optarg, NULL);
6938 if (repo_path == NULL)
6939 return got_error_from_errno2("realpath",
6940 optarg);
6941 break;
6942 default:
6943 usage_blame();
6944 /* NOTREACHED */
6948 argc -= optind;
6949 argv += optind;
6951 if (argc != 1)
6952 usage_blame();
6954 error = got_repo_pack_fds_open(&pack_fds);
6955 if (error != NULL)
6956 goto done;
6958 if (repo_path == NULL) {
6959 cwd = getcwd(NULL, 0);
6960 if (cwd == NULL)
6961 return got_error_from_errno("getcwd");
6962 error = got_worktree_open(&worktree, cwd);
6963 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6964 goto done;
6965 if (worktree)
6966 repo_path =
6967 strdup(got_worktree_get_repo_path(worktree));
6968 else
6969 repo_path = strdup(cwd);
6970 if (repo_path == NULL) {
6971 error = got_error_from_errno("strdup");
6972 goto done;
6976 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6977 if (error != NULL)
6978 goto done;
6980 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6981 worktree);
6982 if (error)
6983 goto done;
6985 error = init_curses(&tog_io);
6986 if (error)
6987 goto done;
6989 error = apply_unveil(got_repo_get_path(repo), NULL);
6990 if (error)
6991 goto done;
6993 error = tog_load_refs(repo, 0);
6994 if (error)
6995 goto done;
6997 if (commit_id_str == NULL) {
6998 struct got_reference *head_ref;
6999 error = got_ref_open(&head_ref, repo, worktree ?
7000 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7001 if (error != NULL)
7002 goto done;
7003 error = got_ref_resolve(&commit_id, repo, head_ref);
7004 got_ref_close(head_ref);
7005 } else {
7006 error = got_repo_match_object_id(&commit_id, NULL,
7007 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7009 if (error != NULL)
7010 goto done;
7012 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7013 if (view == NULL) {
7014 error = got_error_from_errno("view_open");
7015 goto done;
7018 error = got_object_open_as_commit(&commit, repo, commit_id);
7019 if (error)
7020 goto done;
7022 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7023 commit, repo);
7024 if (error)
7025 goto done;
7027 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7028 commit_id, repo);
7029 if (error)
7030 goto done;
7031 if (worktree) {
7032 /* Release work tree lock. */
7033 got_worktree_close(worktree);
7034 worktree = NULL;
7036 error = view_loop(view, tog_io);
7037 done:
7038 free(repo_path);
7039 free(in_repo_path);
7040 free(link_target);
7041 free(cwd);
7042 free(commit_id);
7043 if (commit)
7044 got_object_commit_close(commit);
7045 if (worktree)
7046 got_worktree_close(worktree);
7047 if (repo) {
7048 const struct got_error *close_err = got_repo_close(repo);
7049 if (error == NULL)
7050 error = close_err;
7052 if (pack_fds) {
7053 const struct got_error *pack_err =
7054 got_repo_pack_fds_close(pack_fds);
7055 if (error == NULL)
7056 error = pack_err;
7058 if (tog_io != NULL) {
7059 io_err = tog_io_close(tog_io);
7060 if (error == NULL)
7061 error = io_err;
7063 tog_free_refs();
7064 return error;
7067 static const struct got_error *
7068 draw_tree_entries(struct tog_view *view, const char *parent_path)
7070 struct tog_tree_view_state *s = &view->state.tree;
7071 const struct got_error *err = NULL;
7072 struct got_tree_entry *te;
7073 wchar_t *wline;
7074 char *index = NULL;
7075 struct tog_color *tc;
7076 int width, n, nentries, scrollx, i = 1;
7077 int limit = view->nlines;
7079 s->ndisplayed = 0;
7080 if (view_is_hsplit_top(view))
7081 --limit; /* border */
7083 werase(view->window);
7085 if (limit == 0)
7086 return NULL;
7088 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7089 0, 0);
7090 if (err)
7091 return err;
7092 if (view_needs_focus_indication(view))
7093 wstandout(view->window);
7094 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7095 if (tc)
7096 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7097 waddwstr(view->window, wline);
7098 free(wline);
7099 wline = NULL;
7100 while (width++ < view->ncols)
7101 waddch(view->window, ' ');
7102 if (tc)
7103 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7104 if (view_needs_focus_indication(view))
7105 wstandend(view->window);
7106 if (--limit <= 0)
7107 return NULL;
7109 i += s->selected;
7110 if (s->first_displayed_entry) {
7111 i += got_tree_entry_get_index(s->first_displayed_entry);
7112 if (s->tree != s->root)
7113 ++i; /* account for ".." entry */
7115 nentries = got_object_tree_get_nentries(s->tree);
7116 if (asprintf(&index, "[%d/%d] %s",
7117 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7118 return got_error_from_errno("asprintf");
7119 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7120 free(index);
7121 if (err)
7122 return err;
7123 waddwstr(view->window, wline);
7124 free(wline);
7125 wline = NULL;
7126 if (width < view->ncols - 1)
7127 waddch(view->window, '\n');
7128 if (--limit <= 0)
7129 return NULL;
7130 waddch(view->window, '\n');
7131 if (--limit <= 0)
7132 return NULL;
7134 if (s->first_displayed_entry == NULL) {
7135 te = got_object_tree_get_first_entry(s->tree);
7136 if (s->selected == 0) {
7137 if (view->focussed)
7138 wstandout(view->window);
7139 s->selected_entry = NULL;
7141 waddstr(view->window, " ..\n"); /* parent directory */
7142 if (s->selected == 0 && view->focussed)
7143 wstandend(view->window);
7144 s->ndisplayed++;
7145 if (--limit <= 0)
7146 return NULL;
7147 n = 1;
7148 } else {
7149 n = 0;
7150 te = s->first_displayed_entry;
7153 view->maxx = 0;
7154 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7155 char *line = NULL, *id_str = NULL, *link_target = NULL;
7156 const char *modestr = "";
7157 mode_t mode;
7159 te = got_object_tree_get_entry(s->tree, i);
7160 mode = got_tree_entry_get_mode(te);
7162 if (s->show_ids) {
7163 err = got_object_id_str(&id_str,
7164 got_tree_entry_get_id(te));
7165 if (err)
7166 return got_error_from_errno(
7167 "got_object_id_str");
7169 if (got_object_tree_entry_is_submodule(te))
7170 modestr = "$";
7171 else if (S_ISLNK(mode)) {
7172 int i;
7174 err = got_tree_entry_get_symlink_target(&link_target,
7175 te, s->repo);
7176 if (err) {
7177 free(id_str);
7178 return err;
7180 for (i = 0; i < strlen(link_target); i++) {
7181 if (!isprint((unsigned char)link_target[i]))
7182 link_target[i] = '?';
7184 modestr = "@";
7186 else if (S_ISDIR(mode))
7187 modestr = "/";
7188 else if (mode & S_IXUSR)
7189 modestr = "*";
7190 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7191 got_tree_entry_get_name(te), modestr,
7192 link_target ? " -> ": "",
7193 link_target ? link_target : "") == -1) {
7194 free(id_str);
7195 free(link_target);
7196 return got_error_from_errno("asprintf");
7198 free(id_str);
7199 free(link_target);
7201 /* use full line width to determine view->maxx */
7202 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7203 if (err) {
7204 free(line);
7205 break;
7207 view->maxx = MAX(view->maxx, width);
7208 free(wline);
7209 wline = NULL;
7211 err = format_line(&wline, &width, &scrollx, line, view->x,
7212 view->ncols, 0, 0);
7213 if (err) {
7214 free(line);
7215 break;
7217 if (n == s->selected) {
7218 if (view->focussed)
7219 wstandout(view->window);
7220 s->selected_entry = te;
7222 tc = match_color(&s->colors, line);
7223 if (tc)
7224 wattr_on(view->window,
7225 COLOR_PAIR(tc->colorpair), NULL);
7226 waddwstr(view->window, &wline[scrollx]);
7227 if (tc)
7228 wattr_off(view->window,
7229 COLOR_PAIR(tc->colorpair), NULL);
7230 if (width < view->ncols)
7231 waddch(view->window, '\n');
7232 if (n == s->selected && view->focussed)
7233 wstandend(view->window);
7234 free(line);
7235 free(wline);
7236 wline = NULL;
7237 n++;
7238 s->ndisplayed++;
7239 s->last_displayed_entry = te;
7240 if (--limit <= 0)
7241 break;
7244 return err;
7247 static void
7248 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7250 struct got_tree_entry *te;
7251 int isroot = s->tree == s->root;
7252 int i = 0;
7254 if (s->first_displayed_entry == NULL)
7255 return;
7257 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7258 while (i++ < maxscroll) {
7259 if (te == NULL) {
7260 if (!isroot)
7261 s->first_displayed_entry = NULL;
7262 break;
7264 s->first_displayed_entry = te;
7265 te = got_tree_entry_get_prev(s->tree, te);
7269 static const struct got_error *
7270 tree_scroll_down(struct tog_view *view, int maxscroll)
7272 struct tog_tree_view_state *s = &view->state.tree;
7273 struct got_tree_entry *next, *last;
7274 int n = 0;
7276 if (s->first_displayed_entry)
7277 next = got_tree_entry_get_next(s->tree,
7278 s->first_displayed_entry);
7279 else
7280 next = got_object_tree_get_first_entry(s->tree);
7282 last = s->last_displayed_entry;
7283 while (next && n++ < maxscroll) {
7284 if (last) {
7285 s->last_displayed_entry = last;
7286 last = got_tree_entry_get_next(s->tree, last);
7288 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7289 s->first_displayed_entry = next;
7290 next = got_tree_entry_get_next(s->tree, next);
7294 return NULL;
7297 static const struct got_error *
7298 tree_entry_path(char **path, struct tog_parent_trees *parents,
7299 struct got_tree_entry *te)
7301 const struct got_error *err = NULL;
7302 struct tog_parent_tree *pt;
7303 size_t len = 2; /* for leading slash and NUL */
7305 TAILQ_FOREACH(pt, parents, entry)
7306 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7307 + 1 /* slash */;
7308 if (te)
7309 len += strlen(got_tree_entry_get_name(te));
7311 *path = calloc(1, len);
7312 if (path == NULL)
7313 return got_error_from_errno("calloc");
7315 (*path)[0] = '/';
7316 pt = TAILQ_LAST(parents, tog_parent_trees);
7317 while (pt) {
7318 const char *name = got_tree_entry_get_name(pt->selected_entry);
7319 if (strlcat(*path, name, len) >= len) {
7320 err = got_error(GOT_ERR_NO_SPACE);
7321 goto done;
7323 if (strlcat(*path, "/", len) >= len) {
7324 err = got_error(GOT_ERR_NO_SPACE);
7325 goto done;
7327 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7329 if (te) {
7330 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7331 err = got_error(GOT_ERR_NO_SPACE);
7332 goto done;
7335 done:
7336 if (err) {
7337 free(*path);
7338 *path = NULL;
7340 return err;
7343 static const struct got_error *
7344 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7345 struct got_tree_entry *te, struct tog_parent_trees *parents,
7346 struct got_object_id *commit_id, struct got_repository *repo)
7348 const struct got_error *err = NULL;
7349 char *path;
7350 struct tog_view *blame_view;
7352 *new_view = NULL;
7354 err = tree_entry_path(&path, parents, te);
7355 if (err)
7356 return err;
7358 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7359 if (blame_view == NULL) {
7360 err = got_error_from_errno("view_open");
7361 goto done;
7364 err = open_blame_view(blame_view, path, commit_id, repo);
7365 if (err) {
7366 if (err->code == GOT_ERR_CANCELLED)
7367 err = NULL;
7368 view_close(blame_view);
7369 } else
7370 *new_view = blame_view;
7371 done:
7372 free(path);
7373 return err;
7376 static const struct got_error *
7377 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7378 struct tog_tree_view_state *s)
7380 struct tog_view *log_view;
7381 const struct got_error *err = NULL;
7382 char *path;
7384 *new_view = NULL;
7386 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7387 if (log_view == NULL)
7388 return got_error_from_errno("view_open");
7390 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7391 if (err)
7392 return err;
7394 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7395 path, 0);
7396 if (err)
7397 view_close(log_view);
7398 else
7399 *new_view = log_view;
7400 free(path);
7401 return err;
7404 static const struct got_error *
7405 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7406 const char *head_ref_name, struct got_repository *repo)
7408 const struct got_error *err = NULL;
7409 char *commit_id_str = NULL;
7410 struct tog_tree_view_state *s = &view->state.tree;
7411 struct got_commit_object *commit = NULL;
7413 TAILQ_INIT(&s->parents);
7414 STAILQ_INIT(&s->colors);
7416 s->commit_id = got_object_id_dup(commit_id);
7417 if (s->commit_id == NULL)
7418 return got_error_from_errno("got_object_id_dup");
7420 err = got_object_open_as_commit(&commit, repo, commit_id);
7421 if (err)
7422 goto done;
7425 * The root is opened here and will be closed when the view is closed.
7426 * Any visited subtrees and their path-wise parents are opened and
7427 * closed on demand.
7429 err = got_object_open_as_tree(&s->root, repo,
7430 got_object_commit_get_tree_id(commit));
7431 if (err)
7432 goto done;
7433 s->tree = s->root;
7435 err = got_object_id_str(&commit_id_str, commit_id);
7436 if (err != NULL)
7437 goto done;
7439 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7440 err = got_error_from_errno("asprintf");
7441 goto done;
7444 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7445 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7446 if (head_ref_name) {
7447 s->head_ref_name = strdup(head_ref_name);
7448 if (s->head_ref_name == NULL) {
7449 err = got_error_from_errno("strdup");
7450 goto done;
7453 s->repo = repo;
7455 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7456 err = add_color(&s->colors, "\\$$",
7457 TOG_COLOR_TREE_SUBMODULE,
7458 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7459 if (err)
7460 goto done;
7461 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7462 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7463 if (err)
7464 goto done;
7465 err = add_color(&s->colors, "/$",
7466 TOG_COLOR_TREE_DIRECTORY,
7467 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7468 if (err)
7469 goto done;
7471 err = add_color(&s->colors, "\\*$",
7472 TOG_COLOR_TREE_EXECUTABLE,
7473 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7474 if (err)
7475 goto done;
7477 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7478 get_color_value("TOG_COLOR_COMMIT"));
7479 if (err)
7480 goto done;
7483 view->show = show_tree_view;
7484 view->input = input_tree_view;
7485 view->close = close_tree_view;
7486 view->search_start = search_start_tree_view;
7487 view->search_next = search_next_tree_view;
7488 done:
7489 free(commit_id_str);
7490 if (commit)
7491 got_object_commit_close(commit);
7492 if (err)
7493 close_tree_view(view);
7494 return err;
7497 static const struct got_error *
7498 close_tree_view(struct tog_view *view)
7500 struct tog_tree_view_state *s = &view->state.tree;
7502 free_colors(&s->colors);
7503 free(s->tree_label);
7504 s->tree_label = NULL;
7505 free(s->commit_id);
7506 s->commit_id = NULL;
7507 free(s->head_ref_name);
7508 s->head_ref_name = NULL;
7509 while (!TAILQ_EMPTY(&s->parents)) {
7510 struct tog_parent_tree *parent;
7511 parent = TAILQ_FIRST(&s->parents);
7512 TAILQ_REMOVE(&s->parents, parent, entry);
7513 if (parent->tree != s->root)
7514 got_object_tree_close(parent->tree);
7515 free(parent);
7518 if (s->tree != NULL && s->tree != s->root)
7519 got_object_tree_close(s->tree);
7520 if (s->root)
7521 got_object_tree_close(s->root);
7522 return NULL;
7525 static const struct got_error *
7526 search_start_tree_view(struct tog_view *view)
7528 struct tog_tree_view_state *s = &view->state.tree;
7530 s->matched_entry = NULL;
7531 return NULL;
7534 static int
7535 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7537 regmatch_t regmatch;
7539 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7540 0) == 0;
7543 static const struct got_error *
7544 search_next_tree_view(struct tog_view *view)
7546 struct tog_tree_view_state *s = &view->state.tree;
7547 struct got_tree_entry *te = NULL;
7549 if (!view->searching) {
7550 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7551 return NULL;
7554 if (s->matched_entry) {
7555 if (view->searching == TOG_SEARCH_FORWARD) {
7556 if (s->selected_entry)
7557 te = got_tree_entry_get_next(s->tree,
7558 s->selected_entry);
7559 else
7560 te = got_object_tree_get_first_entry(s->tree);
7561 } else {
7562 if (s->selected_entry == NULL)
7563 te = got_object_tree_get_last_entry(s->tree);
7564 else
7565 te = got_tree_entry_get_prev(s->tree,
7566 s->selected_entry);
7568 } else {
7569 if (s->selected_entry)
7570 te = s->selected_entry;
7571 else if (view->searching == TOG_SEARCH_FORWARD)
7572 te = got_object_tree_get_first_entry(s->tree);
7573 else
7574 te = got_object_tree_get_last_entry(s->tree);
7577 while (1) {
7578 if (te == NULL) {
7579 if (s->matched_entry == NULL) {
7580 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7581 return NULL;
7583 if (view->searching == TOG_SEARCH_FORWARD)
7584 te = got_object_tree_get_first_entry(s->tree);
7585 else
7586 te = got_object_tree_get_last_entry(s->tree);
7589 if (match_tree_entry(te, &view->regex)) {
7590 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7591 s->matched_entry = te;
7592 break;
7595 if (view->searching == TOG_SEARCH_FORWARD)
7596 te = got_tree_entry_get_next(s->tree, te);
7597 else
7598 te = got_tree_entry_get_prev(s->tree, te);
7601 if (s->matched_entry) {
7602 s->first_displayed_entry = s->matched_entry;
7603 s->selected = 0;
7606 return NULL;
7609 static const struct got_error *
7610 show_tree_view(struct tog_view *view)
7612 const struct got_error *err = NULL;
7613 struct tog_tree_view_state *s = &view->state.tree;
7614 char *parent_path;
7616 err = tree_entry_path(&parent_path, &s->parents, NULL);
7617 if (err)
7618 return err;
7620 err = draw_tree_entries(view, parent_path);
7621 free(parent_path);
7623 view_border(view);
7624 return err;
7627 static const struct got_error *
7628 tree_goto_line(struct tog_view *view, int nlines)
7630 const struct got_error *err = NULL;
7631 struct tog_tree_view_state *s = &view->state.tree;
7632 struct got_tree_entry **fte, **lte, **ste;
7633 int g, last, first = 1, i = 1;
7634 int root = s->tree == s->root;
7635 int off = root ? 1 : 2;
7637 g = view->gline;
7638 view->gline = 0;
7640 if (g == 0)
7641 g = 1;
7642 else if (g > got_object_tree_get_nentries(s->tree))
7643 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7645 fte = &s->first_displayed_entry;
7646 lte = &s->last_displayed_entry;
7647 ste = &s->selected_entry;
7649 if (*fte != NULL) {
7650 first = got_tree_entry_get_index(*fte);
7651 first += off; /* account for ".." */
7653 last = got_tree_entry_get_index(*lte);
7654 last += off;
7656 if (g >= first && g <= last && g - first < nlines) {
7657 s->selected = g - first;
7658 return NULL; /* gline is on the current page */
7661 if (*ste != NULL) {
7662 i = got_tree_entry_get_index(*ste);
7663 i += off;
7666 if (i < g) {
7667 err = tree_scroll_down(view, g - i);
7668 if (err)
7669 return err;
7670 if (got_tree_entry_get_index(*lte) >=
7671 got_object_tree_get_nentries(s->tree) - 1 &&
7672 first + s->selected < g &&
7673 s->selected < s->ndisplayed - 1) {
7674 first = got_tree_entry_get_index(*fte);
7675 first += off;
7676 s->selected = g - first;
7678 } else if (i > g)
7679 tree_scroll_up(s, i - g);
7681 if (g < nlines &&
7682 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7683 s->selected = g - 1;
7685 return NULL;
7688 static const struct got_error *
7689 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7691 const struct got_error *err = NULL;
7692 struct tog_tree_view_state *s = &view->state.tree;
7693 struct got_tree_entry *te;
7694 int n, nscroll = view->nlines - 3;
7696 if (view->gline)
7697 return tree_goto_line(view, nscroll);
7699 switch (ch) {
7700 case '0':
7701 case '$':
7702 case KEY_RIGHT:
7703 case 'l':
7704 case KEY_LEFT:
7705 case 'h':
7706 horizontal_scroll_input(view, ch);
7707 break;
7708 case 'i':
7709 s->show_ids = !s->show_ids;
7710 view->count = 0;
7711 break;
7712 case 'L':
7713 view->count = 0;
7714 if (!s->selected_entry)
7715 break;
7716 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7717 break;
7718 case 'R':
7719 view->count = 0;
7720 err = view_request_new(new_view, view, TOG_VIEW_REF);
7721 break;
7722 case 'g':
7723 case '=':
7724 case KEY_HOME:
7725 s->selected = 0;
7726 view->count = 0;
7727 if (s->tree == s->root)
7728 s->first_displayed_entry =
7729 got_object_tree_get_first_entry(s->tree);
7730 else
7731 s->first_displayed_entry = NULL;
7732 break;
7733 case 'G':
7734 case '*':
7735 case KEY_END: {
7736 int eos = view->nlines - 3;
7738 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7739 --eos; /* border */
7740 s->selected = 0;
7741 view->count = 0;
7742 te = got_object_tree_get_last_entry(s->tree);
7743 for (n = 0; n < eos; n++) {
7744 if (te == NULL) {
7745 if (s->tree != s->root) {
7746 s->first_displayed_entry = NULL;
7747 n++;
7749 break;
7751 s->first_displayed_entry = te;
7752 te = got_tree_entry_get_prev(s->tree, te);
7754 if (n > 0)
7755 s->selected = n - 1;
7756 break;
7758 case 'k':
7759 case KEY_UP:
7760 case CTRL('p'):
7761 if (s->selected > 0) {
7762 s->selected--;
7763 break;
7765 tree_scroll_up(s, 1);
7766 if (s->selected_entry == NULL ||
7767 (s->tree == s->root && s->selected_entry ==
7768 got_object_tree_get_first_entry(s->tree)))
7769 view->count = 0;
7770 break;
7771 case CTRL('u'):
7772 case 'u':
7773 nscroll /= 2;
7774 /* FALL THROUGH */
7775 case KEY_PPAGE:
7776 case CTRL('b'):
7777 case 'b':
7778 if (s->tree == s->root) {
7779 if (got_object_tree_get_first_entry(s->tree) ==
7780 s->first_displayed_entry)
7781 s->selected -= MIN(s->selected, nscroll);
7782 } else {
7783 if (s->first_displayed_entry == NULL)
7784 s->selected -= MIN(s->selected, nscroll);
7786 tree_scroll_up(s, MAX(0, nscroll));
7787 if (s->selected_entry == NULL ||
7788 (s->tree == s->root && s->selected_entry ==
7789 got_object_tree_get_first_entry(s->tree)))
7790 view->count = 0;
7791 break;
7792 case 'j':
7793 case KEY_DOWN:
7794 case CTRL('n'):
7795 if (s->selected < s->ndisplayed - 1) {
7796 s->selected++;
7797 break;
7799 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7800 == NULL) {
7801 /* can't scroll any further */
7802 view->count = 0;
7803 break;
7805 tree_scroll_down(view, 1);
7806 break;
7807 case CTRL('d'):
7808 case 'd':
7809 nscroll /= 2;
7810 /* FALL THROUGH */
7811 case KEY_NPAGE:
7812 case CTRL('f'):
7813 case 'f':
7814 case ' ':
7815 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7816 == NULL) {
7817 /* can't scroll any further; move cursor down */
7818 if (s->selected < s->ndisplayed - 1)
7819 s->selected += MIN(nscroll,
7820 s->ndisplayed - s->selected - 1);
7821 else
7822 view->count = 0;
7823 break;
7825 tree_scroll_down(view, nscroll);
7826 break;
7827 case KEY_ENTER:
7828 case '\r':
7829 case KEY_BACKSPACE:
7830 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7831 struct tog_parent_tree *parent;
7832 /* user selected '..' */
7833 if (s->tree == s->root) {
7834 view->count = 0;
7835 break;
7837 parent = TAILQ_FIRST(&s->parents);
7838 TAILQ_REMOVE(&s->parents, parent,
7839 entry);
7840 got_object_tree_close(s->tree);
7841 s->tree = parent->tree;
7842 s->first_displayed_entry =
7843 parent->first_displayed_entry;
7844 s->selected_entry =
7845 parent->selected_entry;
7846 s->selected = parent->selected;
7847 if (s->selected > view->nlines - 3) {
7848 err = offset_selection_down(view);
7849 if (err)
7850 break;
7852 free(parent);
7853 } else if (S_ISDIR(got_tree_entry_get_mode(
7854 s->selected_entry))) {
7855 struct got_tree_object *subtree;
7856 view->count = 0;
7857 err = got_object_open_as_tree(&subtree, s->repo,
7858 got_tree_entry_get_id(s->selected_entry));
7859 if (err)
7860 break;
7861 err = tree_view_visit_subtree(s, subtree);
7862 if (err) {
7863 got_object_tree_close(subtree);
7864 break;
7866 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7867 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7868 break;
7869 case KEY_RESIZE:
7870 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7871 s->selected = view->nlines - 4;
7872 view->count = 0;
7873 break;
7874 default:
7875 view->count = 0;
7876 break;
7879 return err;
7882 __dead static void
7883 usage_tree(void)
7885 endwin();
7886 fprintf(stderr,
7887 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7888 getprogname());
7889 exit(1);
7892 static const struct got_error *
7893 cmd_tree(int argc, char *argv[])
7895 const struct got_error *io_err, *error;
7896 struct got_repository *repo = NULL;
7897 struct got_worktree *worktree = NULL;
7898 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7899 struct got_object_id *commit_id = NULL;
7900 struct got_commit_object *commit = NULL;
7901 const char *commit_id_arg = NULL;
7902 char *label = NULL;
7903 struct got_reference *ref = NULL;
7904 const char *head_ref_name = NULL;
7905 int ch;
7906 struct tog_view *view;
7907 struct tog_io *tog_io = NULL;
7908 int *pack_fds = NULL;
7910 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7911 switch (ch) {
7912 case 'c':
7913 commit_id_arg = optarg;
7914 break;
7915 case 'r':
7916 repo_path = realpath(optarg, NULL);
7917 if (repo_path == NULL)
7918 return got_error_from_errno2("realpath",
7919 optarg);
7920 break;
7921 default:
7922 usage_tree();
7923 /* NOTREACHED */
7927 argc -= optind;
7928 argv += optind;
7930 if (argc > 1)
7931 usage_tree();
7933 error = got_repo_pack_fds_open(&pack_fds);
7934 if (error != NULL)
7935 goto done;
7937 if (repo_path == NULL) {
7938 cwd = getcwd(NULL, 0);
7939 if (cwd == NULL)
7940 return got_error_from_errno("getcwd");
7941 error = got_worktree_open(&worktree, cwd);
7942 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7943 goto done;
7944 if (worktree)
7945 repo_path =
7946 strdup(got_worktree_get_repo_path(worktree));
7947 else
7948 repo_path = strdup(cwd);
7949 if (repo_path == NULL) {
7950 error = got_error_from_errno("strdup");
7951 goto done;
7955 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7956 if (error != NULL)
7957 goto done;
7959 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7960 repo, worktree);
7961 if (error)
7962 goto done;
7964 error = init_curses(&tog_io);
7965 if (error)
7966 goto done;
7968 error = apply_unveil(got_repo_get_path(repo), NULL);
7969 if (error)
7970 goto done;
7972 error = tog_load_refs(repo, 0);
7973 if (error)
7974 goto done;
7976 if (commit_id_arg == NULL) {
7977 error = got_repo_match_object_id(&commit_id, &label,
7978 worktree ? got_worktree_get_head_ref_name(worktree) :
7979 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7980 if (error)
7981 goto done;
7982 head_ref_name = label;
7983 } else {
7984 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7985 if (error == NULL)
7986 head_ref_name = got_ref_get_name(ref);
7987 else if (error->code != GOT_ERR_NOT_REF)
7988 goto done;
7989 error = got_repo_match_object_id(&commit_id, NULL,
7990 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7991 if (error)
7992 goto done;
7995 error = got_object_open_as_commit(&commit, repo, commit_id);
7996 if (error)
7997 goto done;
7999 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8000 if (view == NULL) {
8001 error = got_error_from_errno("view_open");
8002 goto done;
8004 error = open_tree_view(view, commit_id, head_ref_name, repo);
8005 if (error)
8006 goto done;
8007 if (!got_path_is_root_dir(in_repo_path)) {
8008 error = tree_view_walk_path(&view->state.tree, commit,
8009 in_repo_path);
8010 if (error)
8011 goto done;
8014 if (worktree) {
8015 /* Release work tree lock. */
8016 got_worktree_close(worktree);
8017 worktree = NULL;
8019 error = view_loop(view, tog_io);
8020 done:
8021 free(repo_path);
8022 free(cwd);
8023 free(commit_id);
8024 free(label);
8025 if (ref)
8026 got_ref_close(ref);
8027 if (repo) {
8028 const struct got_error *close_err = got_repo_close(repo);
8029 if (error == NULL)
8030 error = close_err;
8032 if (pack_fds) {
8033 const struct got_error *pack_err =
8034 got_repo_pack_fds_close(pack_fds);
8035 if (error == NULL)
8036 error = pack_err;
8038 if (tog_io != NULL) {
8039 io_err = tog_io_close(tog_io);
8040 if (error == NULL)
8041 error = io_err;
8043 tog_free_refs();
8044 return error;
8047 static const struct got_error *
8048 ref_view_load_refs(struct tog_ref_view_state *s)
8050 struct got_reflist_entry *sre;
8051 struct tog_reflist_entry *re;
8053 s->nrefs = 0;
8054 TAILQ_FOREACH(sre, &tog_refs, entry) {
8055 if (strncmp(got_ref_get_name(sre->ref),
8056 "refs/got/", 9) == 0 &&
8057 strncmp(got_ref_get_name(sre->ref),
8058 "refs/got/backup/", 16) != 0)
8059 continue;
8061 re = malloc(sizeof(*re));
8062 if (re == NULL)
8063 return got_error_from_errno("malloc");
8065 re->ref = got_ref_dup(sre->ref);
8066 if (re->ref == NULL)
8067 return got_error_from_errno("got_ref_dup");
8068 re->idx = s->nrefs++;
8069 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8072 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8073 return NULL;
8076 static void
8077 ref_view_free_refs(struct tog_ref_view_state *s)
8079 struct tog_reflist_entry *re;
8081 while (!TAILQ_EMPTY(&s->refs)) {
8082 re = TAILQ_FIRST(&s->refs);
8083 TAILQ_REMOVE(&s->refs, re, entry);
8084 got_ref_close(re->ref);
8085 free(re);
8089 static const struct got_error *
8090 open_ref_view(struct tog_view *view, struct got_repository *repo)
8092 const struct got_error *err = NULL;
8093 struct tog_ref_view_state *s = &view->state.ref;
8095 s->selected_entry = 0;
8096 s->repo = repo;
8098 TAILQ_INIT(&s->refs);
8099 STAILQ_INIT(&s->colors);
8101 err = ref_view_load_refs(s);
8102 if (err)
8103 return err;
8105 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8106 err = add_color(&s->colors, "^refs/heads/",
8107 TOG_COLOR_REFS_HEADS,
8108 get_color_value("TOG_COLOR_REFS_HEADS"));
8109 if (err)
8110 goto done;
8112 err = add_color(&s->colors, "^refs/tags/",
8113 TOG_COLOR_REFS_TAGS,
8114 get_color_value("TOG_COLOR_REFS_TAGS"));
8115 if (err)
8116 goto done;
8118 err = add_color(&s->colors, "^refs/remotes/",
8119 TOG_COLOR_REFS_REMOTES,
8120 get_color_value("TOG_COLOR_REFS_REMOTES"));
8121 if (err)
8122 goto done;
8124 err = add_color(&s->colors, "^refs/got/backup/",
8125 TOG_COLOR_REFS_BACKUP,
8126 get_color_value("TOG_COLOR_REFS_BACKUP"));
8127 if (err)
8128 goto done;
8131 view->show = show_ref_view;
8132 view->input = input_ref_view;
8133 view->close = close_ref_view;
8134 view->search_start = search_start_ref_view;
8135 view->search_next = search_next_ref_view;
8136 done:
8137 if (err)
8138 free_colors(&s->colors);
8139 return err;
8142 static const struct got_error *
8143 close_ref_view(struct tog_view *view)
8145 struct tog_ref_view_state *s = &view->state.ref;
8147 ref_view_free_refs(s);
8148 free_colors(&s->colors);
8150 return NULL;
8153 static const struct got_error *
8154 resolve_reflist_entry(struct got_object_id **commit_id,
8155 struct tog_reflist_entry *re, struct got_repository *repo)
8157 const struct got_error *err = NULL;
8158 struct got_object_id *obj_id;
8159 struct got_tag_object *tag = NULL;
8160 int obj_type;
8162 *commit_id = NULL;
8164 err = got_ref_resolve(&obj_id, repo, re->ref);
8165 if (err)
8166 return err;
8168 err = got_object_get_type(&obj_type, repo, obj_id);
8169 if (err)
8170 goto done;
8172 switch (obj_type) {
8173 case GOT_OBJ_TYPE_COMMIT:
8174 *commit_id = obj_id;
8175 break;
8176 case GOT_OBJ_TYPE_TAG:
8177 err = got_object_open_as_tag(&tag, repo, obj_id);
8178 if (err)
8179 goto done;
8180 free(obj_id);
8181 err = got_object_get_type(&obj_type, repo,
8182 got_object_tag_get_object_id(tag));
8183 if (err)
8184 goto done;
8185 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8186 err = got_error(GOT_ERR_OBJ_TYPE);
8187 goto done;
8189 *commit_id = got_object_id_dup(
8190 got_object_tag_get_object_id(tag));
8191 if (*commit_id == NULL) {
8192 err = got_error_from_errno("got_object_id_dup");
8193 goto done;
8195 break;
8196 default:
8197 err = got_error(GOT_ERR_OBJ_TYPE);
8198 break;
8201 done:
8202 if (tag)
8203 got_object_tag_close(tag);
8204 if (err) {
8205 free(*commit_id);
8206 *commit_id = NULL;
8208 return err;
8211 static const struct got_error *
8212 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8213 struct tog_reflist_entry *re, struct got_repository *repo)
8215 struct tog_view *log_view;
8216 const struct got_error *err = NULL;
8217 struct got_object_id *commit_id = NULL;
8219 *new_view = NULL;
8221 err = resolve_reflist_entry(&commit_id, re, repo);
8222 if (err) {
8223 if (err->code != GOT_ERR_OBJ_TYPE)
8224 return err;
8225 else
8226 return NULL;
8229 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8230 if (log_view == NULL) {
8231 err = got_error_from_errno("view_open");
8232 goto done;
8235 err = open_log_view(log_view, commit_id, repo,
8236 got_ref_get_name(re->ref), "", 0);
8237 done:
8238 if (err)
8239 view_close(log_view);
8240 else
8241 *new_view = log_view;
8242 free(commit_id);
8243 return err;
8246 static void
8247 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8249 struct tog_reflist_entry *re;
8250 int i = 0;
8252 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8253 return;
8255 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8256 while (i++ < maxscroll) {
8257 if (re == NULL)
8258 break;
8259 s->first_displayed_entry = re;
8260 re = TAILQ_PREV(re, tog_reflist_head, entry);
8264 static const struct got_error *
8265 ref_scroll_down(struct tog_view *view, int maxscroll)
8267 struct tog_ref_view_state *s = &view->state.ref;
8268 struct tog_reflist_entry *next, *last;
8269 int n = 0;
8271 if (s->first_displayed_entry)
8272 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8273 else
8274 next = TAILQ_FIRST(&s->refs);
8276 last = s->last_displayed_entry;
8277 while (next && n++ < maxscroll) {
8278 if (last) {
8279 s->last_displayed_entry = last;
8280 last = TAILQ_NEXT(last, entry);
8282 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8283 s->first_displayed_entry = next;
8284 next = TAILQ_NEXT(next, entry);
8288 return NULL;
8291 static const struct got_error *
8292 search_start_ref_view(struct tog_view *view)
8294 struct tog_ref_view_state *s = &view->state.ref;
8296 s->matched_entry = NULL;
8297 return NULL;
8300 static int
8301 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8303 regmatch_t regmatch;
8305 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8306 0) == 0;
8309 static const struct got_error *
8310 search_next_ref_view(struct tog_view *view)
8312 struct tog_ref_view_state *s = &view->state.ref;
8313 struct tog_reflist_entry *re = NULL;
8315 if (!view->searching) {
8316 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8317 return NULL;
8320 if (s->matched_entry) {
8321 if (view->searching == TOG_SEARCH_FORWARD) {
8322 if (s->selected_entry)
8323 re = TAILQ_NEXT(s->selected_entry, entry);
8324 else
8325 re = TAILQ_PREV(s->selected_entry,
8326 tog_reflist_head, entry);
8327 } else {
8328 if (s->selected_entry == NULL)
8329 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8330 else
8331 re = TAILQ_PREV(s->selected_entry,
8332 tog_reflist_head, entry);
8334 } else {
8335 if (s->selected_entry)
8336 re = s->selected_entry;
8337 else if (view->searching == TOG_SEARCH_FORWARD)
8338 re = TAILQ_FIRST(&s->refs);
8339 else
8340 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8343 while (1) {
8344 if (re == NULL) {
8345 if (s->matched_entry == NULL) {
8346 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8347 return NULL;
8349 if (view->searching == TOG_SEARCH_FORWARD)
8350 re = TAILQ_FIRST(&s->refs);
8351 else
8352 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8355 if (match_reflist_entry(re, &view->regex)) {
8356 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8357 s->matched_entry = re;
8358 break;
8361 if (view->searching == TOG_SEARCH_FORWARD)
8362 re = TAILQ_NEXT(re, entry);
8363 else
8364 re = TAILQ_PREV(re, tog_reflist_head, entry);
8367 if (s->matched_entry) {
8368 s->first_displayed_entry = s->matched_entry;
8369 s->selected = 0;
8372 return NULL;
8375 static const struct got_error *
8376 show_ref_view(struct tog_view *view)
8378 const struct got_error *err = NULL;
8379 struct tog_ref_view_state *s = &view->state.ref;
8380 struct tog_reflist_entry *re;
8381 char *line = NULL;
8382 wchar_t *wline;
8383 struct tog_color *tc;
8384 int width, n, scrollx;
8385 int limit = view->nlines;
8387 werase(view->window);
8389 s->ndisplayed = 0;
8390 if (view_is_hsplit_top(view))
8391 --limit; /* border */
8393 if (limit == 0)
8394 return NULL;
8396 re = s->first_displayed_entry;
8398 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8399 s->nrefs) == -1)
8400 return got_error_from_errno("asprintf");
8402 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8403 if (err) {
8404 free(line);
8405 return err;
8407 if (view_needs_focus_indication(view))
8408 wstandout(view->window);
8409 waddwstr(view->window, wline);
8410 while (width++ < view->ncols)
8411 waddch(view->window, ' ');
8412 if (view_needs_focus_indication(view))
8413 wstandend(view->window);
8414 free(wline);
8415 wline = NULL;
8416 free(line);
8417 line = NULL;
8418 if (--limit <= 0)
8419 return NULL;
8421 n = 0;
8422 view->maxx = 0;
8423 while (re && limit > 0) {
8424 char *line = NULL;
8425 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8427 if (s->show_date) {
8428 struct got_commit_object *ci;
8429 struct got_tag_object *tag;
8430 struct got_object_id *id;
8431 struct tm tm;
8432 time_t t;
8434 err = got_ref_resolve(&id, s->repo, re->ref);
8435 if (err)
8436 return err;
8437 err = got_object_open_as_tag(&tag, s->repo, id);
8438 if (err) {
8439 if (err->code != GOT_ERR_OBJ_TYPE) {
8440 free(id);
8441 return err;
8443 err = got_object_open_as_commit(&ci, s->repo,
8444 id);
8445 if (err) {
8446 free(id);
8447 return err;
8449 t = got_object_commit_get_committer_time(ci);
8450 got_object_commit_close(ci);
8451 } else {
8452 t = got_object_tag_get_tagger_time(tag);
8453 got_object_tag_close(tag);
8455 free(id);
8456 if (gmtime_r(&t, &tm) == NULL)
8457 return got_error_from_errno("gmtime_r");
8458 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8459 return got_error(GOT_ERR_NO_SPACE);
8461 if (got_ref_is_symbolic(re->ref)) {
8462 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8463 ymd : "", got_ref_get_name(re->ref),
8464 got_ref_get_symref_target(re->ref)) == -1)
8465 return got_error_from_errno("asprintf");
8466 } else if (s->show_ids) {
8467 struct got_object_id *id;
8468 char *id_str;
8469 err = got_ref_resolve(&id, s->repo, re->ref);
8470 if (err)
8471 return err;
8472 err = got_object_id_str(&id_str, id);
8473 if (err) {
8474 free(id);
8475 return err;
8477 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8478 got_ref_get_name(re->ref), id_str) == -1) {
8479 err = got_error_from_errno("asprintf");
8480 free(id);
8481 free(id_str);
8482 return err;
8484 free(id);
8485 free(id_str);
8486 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8487 got_ref_get_name(re->ref)) == -1)
8488 return got_error_from_errno("asprintf");
8490 /* use full line width to determine view->maxx */
8491 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8492 if (err) {
8493 free(line);
8494 return err;
8496 view->maxx = MAX(view->maxx, width);
8497 free(wline);
8498 wline = NULL;
8500 err = format_line(&wline, &width, &scrollx, line, view->x,
8501 view->ncols, 0, 0);
8502 if (err) {
8503 free(line);
8504 return err;
8506 if (n == s->selected) {
8507 if (view->focussed)
8508 wstandout(view->window);
8509 s->selected_entry = re;
8511 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8512 if (tc)
8513 wattr_on(view->window,
8514 COLOR_PAIR(tc->colorpair), NULL);
8515 waddwstr(view->window, &wline[scrollx]);
8516 if (tc)
8517 wattr_off(view->window,
8518 COLOR_PAIR(tc->colorpair), NULL);
8519 if (width < view->ncols)
8520 waddch(view->window, '\n');
8521 if (n == s->selected && view->focussed)
8522 wstandend(view->window);
8523 free(line);
8524 free(wline);
8525 wline = NULL;
8526 n++;
8527 s->ndisplayed++;
8528 s->last_displayed_entry = re;
8530 limit--;
8531 re = TAILQ_NEXT(re, entry);
8534 view_border(view);
8535 return err;
8538 static const struct got_error *
8539 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8540 struct tog_reflist_entry *re, struct got_repository *repo)
8542 const struct got_error *err = NULL;
8543 struct got_object_id *commit_id = NULL;
8544 struct tog_view *tree_view;
8546 *new_view = NULL;
8548 err = resolve_reflist_entry(&commit_id, re, repo);
8549 if (err) {
8550 if (err->code != GOT_ERR_OBJ_TYPE)
8551 return err;
8552 else
8553 return NULL;
8557 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8558 if (tree_view == NULL) {
8559 err = got_error_from_errno("view_open");
8560 goto done;
8563 err = open_tree_view(tree_view, commit_id,
8564 got_ref_get_name(re->ref), repo);
8565 if (err)
8566 goto done;
8568 *new_view = tree_view;
8569 done:
8570 free(commit_id);
8571 return err;
8574 static const struct got_error *
8575 ref_goto_line(struct tog_view *view, int nlines)
8577 const struct got_error *err = NULL;
8578 struct tog_ref_view_state *s = &view->state.ref;
8579 int g, idx = s->selected_entry->idx;
8581 g = view->gline;
8582 view->gline = 0;
8584 if (g == 0)
8585 g = 1;
8586 else if (g > s->nrefs)
8587 g = s->nrefs;
8589 if (g >= s->first_displayed_entry->idx + 1 &&
8590 g <= s->last_displayed_entry->idx + 1 &&
8591 g - s->first_displayed_entry->idx - 1 < nlines) {
8592 s->selected = g - s->first_displayed_entry->idx - 1;
8593 return NULL;
8596 if (idx + 1 < g) {
8597 err = ref_scroll_down(view, g - idx - 1);
8598 if (err)
8599 return err;
8600 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8601 s->first_displayed_entry->idx + s->selected < g &&
8602 s->selected < s->ndisplayed - 1)
8603 s->selected = g - s->first_displayed_entry->idx - 1;
8604 } else if (idx + 1 > g)
8605 ref_scroll_up(s, idx - g + 1);
8607 if (g < nlines && s->first_displayed_entry->idx == 0)
8608 s->selected = g - 1;
8610 return NULL;
8614 static const struct got_error *
8615 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8617 const struct got_error *err = NULL;
8618 struct tog_ref_view_state *s = &view->state.ref;
8619 struct tog_reflist_entry *re;
8620 int n, nscroll = view->nlines - 1;
8622 if (view->gline)
8623 return ref_goto_line(view, nscroll);
8625 switch (ch) {
8626 case '0':
8627 case '$':
8628 case KEY_RIGHT:
8629 case 'l':
8630 case KEY_LEFT:
8631 case 'h':
8632 horizontal_scroll_input(view, ch);
8633 break;
8634 case 'i':
8635 s->show_ids = !s->show_ids;
8636 view->count = 0;
8637 break;
8638 case 'm':
8639 s->show_date = !s->show_date;
8640 view->count = 0;
8641 break;
8642 case 'o':
8643 s->sort_by_date = !s->sort_by_date;
8644 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8645 view->count = 0;
8646 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8647 got_ref_cmp_by_commit_timestamp_descending :
8648 tog_ref_cmp_by_name, s->repo);
8649 if (err)
8650 break;
8651 got_reflist_object_id_map_free(tog_refs_idmap);
8652 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8653 &tog_refs, s->repo);
8654 if (err)
8655 break;
8656 ref_view_free_refs(s);
8657 err = ref_view_load_refs(s);
8658 break;
8659 case KEY_ENTER:
8660 case '\r':
8661 view->count = 0;
8662 if (!s->selected_entry)
8663 break;
8664 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8665 break;
8666 case 'T':
8667 view->count = 0;
8668 if (!s->selected_entry)
8669 break;
8670 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8671 break;
8672 case 'g':
8673 case '=':
8674 case KEY_HOME:
8675 s->selected = 0;
8676 view->count = 0;
8677 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8678 break;
8679 case 'G':
8680 case '*':
8681 case KEY_END: {
8682 int eos = view->nlines - 1;
8684 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8685 --eos; /* border */
8686 s->selected = 0;
8687 view->count = 0;
8688 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8689 for (n = 0; n < eos; n++) {
8690 if (re == NULL)
8691 break;
8692 s->first_displayed_entry = re;
8693 re = TAILQ_PREV(re, tog_reflist_head, entry);
8695 if (n > 0)
8696 s->selected = n - 1;
8697 break;
8699 case 'k':
8700 case KEY_UP:
8701 case CTRL('p'):
8702 if (s->selected > 0) {
8703 s->selected--;
8704 break;
8706 ref_scroll_up(s, 1);
8707 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8708 view->count = 0;
8709 break;
8710 case CTRL('u'):
8711 case 'u':
8712 nscroll /= 2;
8713 /* FALL THROUGH */
8714 case KEY_PPAGE:
8715 case CTRL('b'):
8716 case 'b':
8717 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8718 s->selected -= MIN(nscroll, s->selected);
8719 ref_scroll_up(s, MAX(0, nscroll));
8720 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8721 view->count = 0;
8722 break;
8723 case 'j':
8724 case KEY_DOWN:
8725 case CTRL('n'):
8726 if (s->selected < s->ndisplayed - 1) {
8727 s->selected++;
8728 break;
8730 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8731 /* can't scroll any further */
8732 view->count = 0;
8733 break;
8735 ref_scroll_down(view, 1);
8736 break;
8737 case CTRL('d'):
8738 case 'd':
8739 nscroll /= 2;
8740 /* FALL THROUGH */
8741 case KEY_NPAGE:
8742 case CTRL('f'):
8743 case 'f':
8744 case ' ':
8745 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8746 /* can't scroll any further; move cursor down */
8747 if (s->selected < s->ndisplayed - 1)
8748 s->selected += MIN(nscroll,
8749 s->ndisplayed - s->selected - 1);
8750 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8751 s->selected += s->ndisplayed - s->selected - 1;
8752 view->count = 0;
8753 break;
8755 ref_scroll_down(view, nscroll);
8756 break;
8757 case CTRL('l'):
8758 view->count = 0;
8759 tog_free_refs();
8760 err = tog_load_refs(s->repo, s->sort_by_date);
8761 if (err)
8762 break;
8763 ref_view_free_refs(s);
8764 err = ref_view_load_refs(s);
8765 break;
8766 case KEY_RESIZE:
8767 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8768 s->selected = view->nlines - 2;
8769 break;
8770 default:
8771 view->count = 0;
8772 break;
8775 return err;
8778 __dead static void
8779 usage_ref(void)
8781 endwin();
8782 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8783 getprogname());
8784 exit(1);
8787 static const struct got_error *
8788 cmd_ref(int argc, char *argv[])
8790 const struct got_error *io_err, *error;
8791 struct got_repository *repo = NULL;
8792 struct got_worktree *worktree = NULL;
8793 char *cwd = NULL, *repo_path = NULL;
8794 int ch;
8795 struct tog_view *view;
8796 struct tog_io *tog_io = NULL;
8797 int *pack_fds = NULL;
8799 while ((ch = getopt(argc, argv, "r:")) != -1) {
8800 switch (ch) {
8801 case 'r':
8802 repo_path = realpath(optarg, NULL);
8803 if (repo_path == NULL)
8804 return got_error_from_errno2("realpath",
8805 optarg);
8806 break;
8807 default:
8808 usage_ref();
8809 /* NOTREACHED */
8813 argc -= optind;
8814 argv += optind;
8816 if (argc > 1)
8817 usage_ref();
8819 error = got_repo_pack_fds_open(&pack_fds);
8820 if (error != NULL)
8821 goto done;
8823 if (repo_path == NULL) {
8824 cwd = getcwd(NULL, 0);
8825 if (cwd == NULL)
8826 return got_error_from_errno("getcwd");
8827 error = got_worktree_open(&worktree, cwd);
8828 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8829 goto done;
8830 if (worktree)
8831 repo_path =
8832 strdup(got_worktree_get_repo_path(worktree));
8833 else
8834 repo_path = strdup(cwd);
8835 if (repo_path == NULL) {
8836 error = got_error_from_errno("strdup");
8837 goto done;
8841 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8842 if (error != NULL)
8843 goto done;
8845 error = init_curses(&tog_io);
8846 if (error)
8847 goto done;
8849 error = apply_unveil(got_repo_get_path(repo), NULL);
8850 if (error)
8851 goto done;
8853 error = tog_load_refs(repo, 0);
8854 if (error)
8855 goto done;
8857 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8858 if (view == NULL) {
8859 error = got_error_from_errno("view_open");
8860 goto done;
8863 error = open_ref_view(view, repo);
8864 if (error)
8865 goto done;
8867 if (worktree) {
8868 /* Release work tree lock. */
8869 got_worktree_close(worktree);
8870 worktree = NULL;
8872 error = view_loop(view, tog_io);
8873 done:
8874 free(repo_path);
8875 free(cwd);
8876 if (repo) {
8877 const struct got_error *close_err = got_repo_close(repo);
8878 if (close_err)
8879 error = close_err;
8881 if (pack_fds) {
8882 const struct got_error *pack_err =
8883 got_repo_pack_fds_close(pack_fds);
8884 if (error == NULL)
8885 error = pack_err;
8887 if (tog_io != NULL) {
8888 io_err = tog_io_close(tog_io);
8889 if (error == NULL)
8890 error = io_err;
8892 tog_free_refs();
8893 return error;
8896 static const struct got_error*
8897 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8898 const char *str)
8900 size_t len;
8902 if (win == NULL)
8903 win = stdscr;
8905 len = strlen(str);
8906 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8908 if (focus)
8909 wstandout(win);
8910 if (mvwprintw(win, y, x, "%s", str) == ERR)
8911 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8912 if (focus)
8913 wstandend(win);
8915 return NULL;
8918 static const struct got_error *
8919 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8921 off_t *p;
8923 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8924 if (p == NULL) {
8925 free(*line_offsets);
8926 *line_offsets = NULL;
8927 return got_error_from_errno("reallocarray");
8930 *line_offsets = p;
8931 (*line_offsets)[*nlines] = off;
8932 ++(*nlines);
8933 return NULL;
8936 static const struct got_error *
8937 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8939 *ret = 0;
8941 for (;n > 0; --n, ++km) {
8942 char *t0, *t, *k;
8943 size_t len = 1;
8945 if (km->keys == NULL)
8946 continue;
8948 t = t0 = strdup(km->keys);
8949 if (t0 == NULL)
8950 return got_error_from_errno("strdup");
8952 len += strlen(t);
8953 while ((k = strsep(&t, " ")) != NULL)
8954 len += strlen(k) > 1 ? 2 : 0;
8955 free(t0);
8956 *ret = MAX(*ret, len);
8959 return NULL;
8963 * Write keymap section headers, keys, and key info in km to f.
8964 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8965 * wrap control and symbolic keys in guillemets, else use <>.
8967 static const struct got_error *
8968 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8970 int n, len = width;
8972 if (km->keys) {
8973 static const char *u8_glyph[] = {
8974 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8975 "\xe2\x80\xba" /* U+203A (utf8 >) */
8977 char *t0, *t, *k;
8978 int cs, s, first = 1;
8980 cs = got_locale_is_utf8();
8982 t = t0 = strdup(km->keys);
8983 if (t0 == NULL)
8984 return got_error_from_errno("strdup");
8986 len = strlen(km->keys);
8987 while ((k = strsep(&t, " ")) != NULL) {
8988 s = strlen(k) > 1; /* control or symbolic key */
8989 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8990 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8991 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8992 if (n < 0) {
8993 free(t0);
8994 return got_error_from_errno("fprintf");
8996 first = 0;
8997 len += s ? 2 : 0;
8998 *off += n;
9000 free(t0);
9002 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9003 if (n < 0)
9004 return got_error_from_errno("fprintf");
9005 *off += n;
9007 return NULL;
9010 static const struct got_error *
9011 format_help(struct tog_help_view_state *s)
9013 const struct got_error *err = NULL;
9014 off_t off = 0;
9015 int i, max, n, show = s->all;
9016 static const struct tog_key_map km[] = {
9017 #define KEYMAP_(info, type) { NULL, (info), type }
9018 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9019 GENERATE_HELP
9020 #undef KEYMAP_
9021 #undef KEY_
9024 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9025 if (err)
9026 return err;
9028 n = nitems(km);
9029 err = max_key_str(&max, km, n);
9030 if (err)
9031 return err;
9033 for (i = 0; i < n; ++i) {
9034 if (km[i].keys == NULL) {
9035 show = s->all;
9036 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9037 km[i].type == s->type || s->all)
9038 show = 1;
9040 if (show) {
9041 err = format_help_line(&off, s->f, &km[i], max);
9042 if (err)
9043 return err;
9044 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9045 if (err)
9046 return err;
9049 fputc('\n', s->f);
9050 ++off;
9051 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9052 return err;
9055 static const struct got_error *
9056 create_help(struct tog_help_view_state *s)
9058 FILE *f;
9059 const struct got_error *err;
9061 free(s->line_offsets);
9062 s->line_offsets = NULL;
9063 s->nlines = 0;
9065 f = got_opentemp();
9066 if (f == NULL)
9067 return got_error_from_errno("got_opentemp");
9068 s->f = f;
9070 err = format_help(s);
9071 if (err)
9072 return err;
9074 if (s->f && fflush(s->f) != 0)
9075 return got_error_from_errno("fflush");
9077 return NULL;
9080 static const struct got_error *
9081 search_start_help_view(struct tog_view *view)
9083 view->state.help.matched_line = 0;
9084 return NULL;
9087 static void
9088 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9089 size_t *nlines, int **first, int **last, int **match, int **selected)
9091 struct tog_help_view_state *s = &view->state.help;
9093 *f = s->f;
9094 *nlines = s->nlines;
9095 *line_offsets = s->line_offsets;
9096 *match = &s->matched_line;
9097 *first = &s->first_displayed_line;
9098 *last = &s->last_displayed_line;
9099 *selected = &s->selected_line;
9102 static const struct got_error *
9103 show_help_view(struct tog_view *view)
9105 struct tog_help_view_state *s = &view->state.help;
9106 const struct got_error *err;
9107 regmatch_t *regmatch = &view->regmatch;
9108 wchar_t *wline;
9109 char *line;
9110 ssize_t linelen;
9111 size_t linesz = 0;
9112 int width, nprinted = 0, rc = 0;
9113 int eos = view->nlines;
9115 if (view_is_hsplit_top(view))
9116 --eos; /* account for border */
9118 s->lineno = 0;
9119 rewind(s->f);
9120 werase(view->window);
9122 if (view->gline > s->nlines - 1)
9123 view->gline = s->nlines - 1;
9125 err = win_draw_center(view->window, 0, 0, view->ncols,
9126 view_needs_focus_indication(view),
9127 "tog help (press q to return to tog)");
9128 if (err)
9129 return err;
9130 if (eos <= 1)
9131 return NULL;
9132 waddstr(view->window, "\n\n");
9133 eos -= 2;
9135 s->eof = 0;
9136 view->maxx = 0;
9137 line = NULL;
9138 while (eos > 0 && nprinted < eos) {
9139 attr_t attr = 0;
9141 linelen = getline(&line, &linesz, s->f);
9142 if (linelen == -1) {
9143 if (!feof(s->f)) {
9144 free(line);
9145 return got_ferror(s->f, GOT_ERR_IO);
9147 s->eof = 1;
9148 break;
9150 if (++s->lineno < s->first_displayed_line)
9151 continue;
9152 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9153 continue;
9154 if (s->lineno == view->hiline)
9155 attr = A_STANDOUT;
9157 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9158 view->x ? 1 : 0);
9159 if (err) {
9160 free(line);
9161 return err;
9163 view->maxx = MAX(view->maxx, width);
9164 free(wline);
9165 wline = NULL;
9167 if (attr)
9168 wattron(view->window, attr);
9169 if (s->first_displayed_line + nprinted == s->matched_line &&
9170 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9171 err = add_matched_line(&width, line, view->ncols - 1, 0,
9172 view->window, view->x, regmatch);
9173 if (err) {
9174 free(line);
9175 return err;
9177 } else {
9178 int skip;
9180 err = format_line(&wline, &width, &skip, line,
9181 view->x, view->ncols, 0, view->x ? 1 : 0);
9182 if (err) {
9183 free(line);
9184 return err;
9186 waddwstr(view->window, &wline[skip]);
9187 free(wline);
9188 wline = NULL;
9190 if (s->lineno == view->hiline) {
9191 while (width++ < view->ncols)
9192 waddch(view->window, ' ');
9193 } else {
9194 if (width < view->ncols)
9195 waddch(view->window, '\n');
9197 if (attr)
9198 wattroff(view->window, attr);
9199 if (++nprinted == 1)
9200 s->first_displayed_line = s->lineno;
9202 free(line);
9203 if (nprinted > 0)
9204 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9205 else
9206 s->last_displayed_line = s->first_displayed_line;
9208 view_border(view);
9210 if (s->eof) {
9211 rc = waddnstr(view->window,
9212 "See the tog(1) manual page for full documentation",
9213 view->ncols - 1);
9214 if (rc == ERR)
9215 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9216 } else {
9217 wmove(view->window, view->nlines - 1, 0);
9218 wclrtoeol(view->window);
9219 wstandout(view->window);
9220 rc = waddnstr(view->window, "scroll down for more...",
9221 view->ncols - 1);
9222 if (rc == ERR)
9223 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9224 if (getcurx(view->window) < view->ncols - 6) {
9225 rc = wprintw(view->window, "[%.0f%%]",
9226 100.00 * s->last_displayed_line / s->nlines);
9227 if (rc == ERR)
9228 return got_error_msg(GOT_ERR_IO, "wprintw");
9230 wstandend(view->window);
9233 return NULL;
9236 static const struct got_error *
9237 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9239 struct tog_help_view_state *s = &view->state.help;
9240 const struct got_error *err = NULL;
9241 char *line = NULL;
9242 ssize_t linelen;
9243 size_t linesz = 0;
9244 int eos, nscroll;
9246 eos = nscroll = view->nlines;
9247 if (view_is_hsplit_top(view))
9248 --eos; /* border */
9250 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9252 switch (ch) {
9253 case '0':
9254 case '$':
9255 case KEY_RIGHT:
9256 case 'l':
9257 case KEY_LEFT:
9258 case 'h':
9259 horizontal_scroll_input(view, ch);
9260 break;
9261 case 'g':
9262 case KEY_HOME:
9263 s->first_displayed_line = 1;
9264 view->count = 0;
9265 break;
9266 case 'G':
9267 case KEY_END:
9268 view->count = 0;
9269 if (s->eof)
9270 break;
9271 s->first_displayed_line = (s->nlines - eos) + 3;
9272 s->eof = 1;
9273 break;
9274 case 'k':
9275 case KEY_UP:
9276 if (s->first_displayed_line > 1)
9277 --s->first_displayed_line;
9278 else
9279 view->count = 0;
9280 break;
9281 case CTRL('u'):
9282 case 'u':
9283 nscroll /= 2;
9284 /* FALL THROUGH */
9285 case KEY_PPAGE:
9286 case CTRL('b'):
9287 case 'b':
9288 if (s->first_displayed_line == 1) {
9289 view->count = 0;
9290 break;
9292 while (--nscroll > 0 && s->first_displayed_line > 1)
9293 s->first_displayed_line--;
9294 break;
9295 case 'j':
9296 case KEY_DOWN:
9297 case CTRL('n'):
9298 if (!s->eof)
9299 ++s->first_displayed_line;
9300 else
9301 view->count = 0;
9302 break;
9303 case CTRL('d'):
9304 case 'd':
9305 nscroll /= 2;
9306 /* FALL THROUGH */
9307 case KEY_NPAGE:
9308 case CTRL('f'):
9309 case 'f':
9310 case ' ':
9311 if (s->eof) {
9312 view->count = 0;
9313 break;
9315 while (!s->eof && --nscroll > 0) {
9316 linelen = getline(&line, &linesz, s->f);
9317 s->first_displayed_line++;
9318 if (linelen == -1) {
9319 if (feof(s->f))
9320 s->eof = 1;
9321 else
9322 err = got_ferror(s->f, GOT_ERR_IO);
9323 break;
9326 free(line);
9327 break;
9328 default:
9329 view->count = 0;
9330 break;
9333 return err;
9336 static const struct got_error *
9337 close_help_view(struct tog_view *view)
9339 struct tog_help_view_state *s = &view->state.help;
9341 free(s->line_offsets);
9342 s->line_offsets = NULL;
9343 if (fclose(s->f) == EOF)
9344 return got_error_from_errno("fclose");
9346 return NULL;
9349 static const struct got_error *
9350 reset_help_view(struct tog_view *view)
9352 struct tog_help_view_state *s = &view->state.help;
9355 if (s->f && fclose(s->f) == EOF)
9356 return got_error_from_errno("fclose");
9358 wclear(view->window);
9359 view->count = 0;
9360 view->x = 0;
9361 s->all = !s->all;
9362 s->first_displayed_line = 1;
9363 s->last_displayed_line = view->nlines;
9364 s->matched_line = 0;
9366 return create_help(s);
9369 static const struct got_error *
9370 open_help_view(struct tog_view *view, struct tog_view *parent)
9372 const struct got_error *err = NULL;
9373 struct tog_help_view_state *s = &view->state.help;
9375 s->type = (enum tog_keymap_type)parent->type;
9376 s->first_displayed_line = 1;
9377 s->last_displayed_line = view->nlines;
9378 s->selected_line = 1;
9380 view->show = show_help_view;
9381 view->input = input_help_view;
9382 view->reset = reset_help_view;
9383 view->close = close_help_view;
9384 view->search_start = search_start_help_view;
9385 view->search_setup = search_setup_help_view;
9386 view->search_next = search_next_view_match;
9388 err = create_help(s);
9389 return err;
9392 static const struct got_error *
9393 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9394 enum tog_view_type request, int y, int x)
9396 const struct got_error *err = NULL;
9398 *new_view = NULL;
9400 switch (request) {
9401 case TOG_VIEW_DIFF:
9402 if (view->type == TOG_VIEW_LOG) {
9403 struct tog_log_view_state *s = &view->state.log;
9405 err = open_diff_view_for_commit(new_view, y, x,
9406 s->selected_entry->commit, s->selected_entry->id,
9407 view, s->repo);
9408 } else
9409 return got_error_msg(GOT_ERR_NOT_IMPL,
9410 "parent/child view pair not supported");
9411 break;
9412 case TOG_VIEW_BLAME:
9413 if (view->type == TOG_VIEW_TREE) {
9414 struct tog_tree_view_state *s = &view->state.tree;
9416 err = blame_tree_entry(new_view, y, x,
9417 s->selected_entry, &s->parents, s->commit_id,
9418 s->repo);
9419 } else
9420 return got_error_msg(GOT_ERR_NOT_IMPL,
9421 "parent/child view pair not supported");
9422 break;
9423 case TOG_VIEW_LOG:
9424 if (view->type == TOG_VIEW_BLAME)
9425 err = log_annotated_line(new_view, y, x,
9426 view->state.blame.repo, view->state.blame.id_to_log);
9427 else if (view->type == TOG_VIEW_TREE)
9428 err = log_selected_tree_entry(new_view, y, x,
9429 &view->state.tree);
9430 else if (view->type == TOG_VIEW_REF)
9431 err = log_ref_entry(new_view, y, x,
9432 view->state.ref.selected_entry,
9433 view->state.ref.repo);
9434 else
9435 return got_error_msg(GOT_ERR_NOT_IMPL,
9436 "parent/child view pair not supported");
9437 break;
9438 case TOG_VIEW_TREE:
9439 if (view->type == TOG_VIEW_LOG)
9440 err = browse_commit_tree(new_view, y, x,
9441 view->state.log.selected_entry,
9442 view->state.log.in_repo_path,
9443 view->state.log.head_ref_name,
9444 view->state.log.repo);
9445 else if (view->type == TOG_VIEW_REF)
9446 err = browse_ref_tree(new_view, y, x,
9447 view->state.ref.selected_entry,
9448 view->state.ref.repo);
9449 else
9450 return got_error_msg(GOT_ERR_NOT_IMPL,
9451 "parent/child view pair not supported");
9452 break;
9453 case TOG_VIEW_REF:
9454 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9455 if (*new_view == NULL)
9456 return got_error_from_errno("view_open");
9457 if (view->type == TOG_VIEW_LOG)
9458 err = open_ref_view(*new_view, view->state.log.repo);
9459 else if (view->type == TOG_VIEW_TREE)
9460 err = open_ref_view(*new_view, view->state.tree.repo);
9461 else
9462 err = got_error_msg(GOT_ERR_NOT_IMPL,
9463 "parent/child view pair not supported");
9464 if (err)
9465 view_close(*new_view);
9466 break;
9467 case TOG_VIEW_HELP:
9468 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9469 if (*new_view == NULL)
9470 return got_error_from_errno("view_open");
9471 err = open_help_view(*new_view, view);
9472 if (err)
9473 view_close(*new_view);
9474 break;
9475 default:
9476 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9479 return err;
9483 * If view was scrolled down to move the selected line into view when opening a
9484 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9486 static void
9487 offset_selection_up(struct tog_view *view)
9489 switch (view->type) {
9490 case TOG_VIEW_BLAME: {
9491 struct tog_blame_view_state *s = &view->state.blame;
9492 if (s->first_displayed_line == 1) {
9493 s->selected_line = MAX(s->selected_line - view->offset,
9494 1);
9495 break;
9497 if (s->first_displayed_line > view->offset)
9498 s->first_displayed_line -= view->offset;
9499 else
9500 s->first_displayed_line = 1;
9501 s->selected_line += view->offset;
9502 break;
9504 case TOG_VIEW_LOG:
9505 log_scroll_up(&view->state.log, view->offset);
9506 view->state.log.selected += view->offset;
9507 break;
9508 case TOG_VIEW_REF:
9509 ref_scroll_up(&view->state.ref, view->offset);
9510 view->state.ref.selected += view->offset;
9511 break;
9512 case TOG_VIEW_TREE:
9513 tree_scroll_up(&view->state.tree, view->offset);
9514 view->state.tree.selected += view->offset;
9515 break;
9516 default:
9517 break;
9520 view->offset = 0;
9524 * If the selected line is in the section of screen covered by the bottom split,
9525 * scroll down offset lines to move it into view and index its new position.
9527 static const struct got_error *
9528 offset_selection_down(struct tog_view *view)
9530 const struct got_error *err = NULL;
9531 const struct got_error *(*scrolld)(struct tog_view *, int);
9532 int *selected = NULL;
9533 int header, offset;
9535 switch (view->type) {
9536 case TOG_VIEW_BLAME: {
9537 struct tog_blame_view_state *s = &view->state.blame;
9538 header = 3;
9539 scrolld = NULL;
9540 if (s->selected_line > view->nlines - header) {
9541 offset = abs(view->nlines - s->selected_line - header);
9542 s->first_displayed_line += offset;
9543 s->selected_line -= offset;
9544 view->offset = offset;
9546 break;
9548 case TOG_VIEW_LOG: {
9549 struct tog_log_view_state *s = &view->state.log;
9550 scrolld = &log_scroll_down;
9551 header = view_is_parent_view(view) ? 3 : 2;
9552 selected = &s->selected;
9553 break;
9555 case TOG_VIEW_REF: {
9556 struct tog_ref_view_state *s = &view->state.ref;
9557 scrolld = &ref_scroll_down;
9558 header = 3;
9559 selected = &s->selected;
9560 break;
9562 case TOG_VIEW_TREE: {
9563 struct tog_tree_view_state *s = &view->state.tree;
9564 scrolld = &tree_scroll_down;
9565 header = 5;
9566 selected = &s->selected;
9567 break;
9569 default:
9570 selected = NULL;
9571 scrolld = NULL;
9572 header = 0;
9573 break;
9576 if (selected && *selected > view->nlines - header) {
9577 offset = abs(view->nlines - *selected - header);
9578 view->offset = offset;
9579 if (scrolld && offset) {
9580 err = scrolld(view, offset);
9581 *selected -= offset;
9585 return err;
9588 static void
9589 list_commands(FILE *fp)
9591 size_t i;
9593 fprintf(fp, "commands:");
9594 for (i = 0; i < nitems(tog_commands); i++) {
9595 const struct tog_cmd *cmd = &tog_commands[i];
9596 fprintf(fp, " %s", cmd->name);
9598 fputc('\n', fp);
9601 __dead static void
9602 usage(int hflag, int status)
9604 FILE *fp = (status == 0) ? stdout : stderr;
9606 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9607 getprogname());
9608 if (hflag) {
9609 fprintf(fp, "lazy usage: %s path\n", getprogname());
9610 list_commands(fp);
9612 exit(status);
9615 static char **
9616 make_argv(int argc, ...)
9618 va_list ap;
9619 char **argv;
9620 int i;
9622 va_start(ap, argc);
9624 argv = calloc(argc, sizeof(char *));
9625 if (argv == NULL)
9626 err(1, "calloc");
9627 for (i = 0; i < argc; i++) {
9628 argv[i] = strdup(va_arg(ap, char *));
9629 if (argv[i] == NULL)
9630 err(1, "strdup");
9633 va_end(ap);
9634 return argv;
9638 * Try to convert 'tog path' into a 'tog log path' command.
9639 * The user could simply have mistyped the command rather than knowingly
9640 * provided a path. So check whether argv[0] can in fact be resolved
9641 * to a path in the HEAD commit and print a special error if not.
9642 * This hack is for mpi@ <3
9644 static const struct got_error *
9645 tog_log_with_path(int argc, char *argv[])
9647 const struct got_error *error = NULL, *close_err;
9648 const struct tog_cmd *cmd = NULL;
9649 struct got_repository *repo = NULL;
9650 struct got_worktree *worktree = NULL;
9651 struct got_object_id *commit_id = NULL, *id = NULL;
9652 struct got_commit_object *commit = NULL;
9653 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9654 char *commit_id_str = NULL, **cmd_argv = NULL;
9655 int *pack_fds = NULL;
9657 cwd = getcwd(NULL, 0);
9658 if (cwd == NULL)
9659 return got_error_from_errno("getcwd");
9661 error = got_repo_pack_fds_open(&pack_fds);
9662 if (error != NULL)
9663 goto done;
9665 error = got_worktree_open(&worktree, cwd);
9666 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9667 goto done;
9669 if (worktree)
9670 repo_path = strdup(got_worktree_get_repo_path(worktree));
9671 else
9672 repo_path = strdup(cwd);
9673 if (repo_path == NULL) {
9674 error = got_error_from_errno("strdup");
9675 goto done;
9678 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9679 if (error != NULL)
9680 goto done;
9682 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9683 repo, worktree);
9684 if (error)
9685 goto done;
9687 error = tog_load_refs(repo, 0);
9688 if (error)
9689 goto done;
9690 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9691 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9692 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9693 if (error)
9694 goto done;
9696 if (worktree) {
9697 got_worktree_close(worktree);
9698 worktree = NULL;
9701 error = got_object_open_as_commit(&commit, repo, commit_id);
9702 if (error)
9703 goto done;
9705 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9706 if (error) {
9707 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9708 goto done;
9709 fprintf(stderr, "%s: '%s' is no known command or path\n",
9710 getprogname(), argv[0]);
9711 usage(1, 1);
9712 /* not reached */
9715 error = got_object_id_str(&commit_id_str, commit_id);
9716 if (error)
9717 goto done;
9719 cmd = &tog_commands[0]; /* log */
9720 argc = 4;
9721 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9722 error = cmd->cmd_main(argc, cmd_argv);
9723 done:
9724 if (repo) {
9725 close_err = got_repo_close(repo);
9726 if (error == NULL)
9727 error = close_err;
9729 if (commit)
9730 got_object_commit_close(commit);
9731 if (worktree)
9732 got_worktree_close(worktree);
9733 if (pack_fds) {
9734 const struct got_error *pack_err =
9735 got_repo_pack_fds_close(pack_fds);
9736 if (error == NULL)
9737 error = pack_err;
9739 free(id);
9740 free(commit_id_str);
9741 free(commit_id);
9742 free(cwd);
9743 free(repo_path);
9744 free(in_repo_path);
9745 if (cmd_argv) {
9746 int i;
9747 for (i = 0; i < argc; i++)
9748 free(cmd_argv[i]);
9749 free(cmd_argv);
9751 tog_free_refs();
9752 return error;
9755 int
9756 main(int argc, char *argv[])
9758 const struct got_error *error = NULL;
9759 const struct tog_cmd *cmd = NULL;
9760 int ch, hflag = 0, Vflag = 0;
9761 char **cmd_argv = NULL;
9762 static const struct option longopts[] = {
9763 { "version", no_argument, NULL, 'V' },
9764 { NULL, 0, NULL, 0}
9766 char *diff_algo_str = NULL;
9768 setlocale(LC_CTYPE, "");
9770 #if !defined(PROFILE) && !defined(TOG_REGRESS)
9771 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9772 NULL) == -1)
9773 err(1, "pledge");
9774 #endif
9776 if (!isatty(STDIN_FILENO))
9777 errx(1, "standard input is not a tty");
9779 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9780 switch (ch) {
9781 case 'h':
9782 hflag = 1;
9783 break;
9784 case 'V':
9785 Vflag = 1;
9786 break;
9787 default:
9788 usage(hflag, 1);
9789 /* NOTREACHED */
9793 argc -= optind;
9794 argv += optind;
9795 optind = 1;
9796 optreset = 1;
9798 if (Vflag) {
9799 got_version_print_str();
9800 return 0;
9803 if (argc == 0) {
9804 if (hflag)
9805 usage(hflag, 0);
9806 /* Build an argument vector which runs a default command. */
9807 cmd = &tog_commands[0];
9808 argc = 1;
9809 cmd_argv = make_argv(argc, cmd->name);
9810 } else {
9811 size_t i;
9813 /* Did the user specify a command? */
9814 for (i = 0; i < nitems(tog_commands); i++) {
9815 if (strncmp(tog_commands[i].name, argv[0],
9816 strlen(argv[0])) == 0) {
9817 cmd = &tog_commands[i];
9818 break;
9823 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9824 if (diff_algo_str) {
9825 if (strcasecmp(diff_algo_str, "patience") == 0)
9826 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9827 if (strcasecmp(diff_algo_str, "myers") == 0)
9828 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9831 if (cmd == NULL) {
9832 if (argc != 1)
9833 usage(0, 1);
9834 /* No command specified; try log with a path */
9835 error = tog_log_with_path(argc, argv);
9836 } else {
9837 if (hflag)
9838 cmd->cmd_usage();
9839 else
9840 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9843 endwin();
9844 if (cmd_argv) {
9845 int i;
9846 for (i = 0; i < argc; i++)
9847 free(cmd_argv[i]);
9848 free(cmd_argv);
9851 if (error && error->code != GOT_ERR_CANCELLED &&
9852 error->code != GOT_ERR_EOF &&
9853 error->code != GOT_ERR_PRIVSEP_EXIT &&
9854 error->code != GOT_ERR_PRIVSEP_PIPE &&
9855 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9856 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9857 return 0;