Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
60 #ifndef MIN
61 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
62 #endif
64 #ifndef MAX
65 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
66 #endif
68 #define CTRL(x) ((x) & 0x1f)
70 #ifndef nitems
71 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
72 #endif
74 struct tog_cmd {
75 const char *name;
76 const struct got_error *(*cmd_main)(int, char *[]);
77 void (*cmd_usage)(void);
78 };
80 __dead static void usage(int, int);
81 __dead static void usage_log(void);
82 __dead static void usage_diff(void);
83 __dead static void usage_blame(void);
84 __dead static void usage_tree(void);
85 __dead static void usage_ref(void);
87 static const struct got_error* cmd_log(int, char *[]);
88 static const struct got_error* cmd_diff(int, char *[]);
89 static const struct got_error* cmd_blame(int, char *[]);
90 static const struct got_error* cmd_tree(int, char *[]);
91 static const struct got_error* cmd_ref(int, char *[]);
93 static const struct tog_cmd tog_commands[] = {
94 { "log", cmd_log, usage_log },
95 { "diff", cmd_diff, usage_diff },
96 { "blame", cmd_blame, usage_blame },
97 { "tree", cmd_tree, usage_tree },
98 { "ref", cmd_ref, usage_ref },
99 };
101 enum tog_view_type {
102 TOG_VIEW_DIFF,
103 TOG_VIEW_LOG,
104 TOG_VIEW_BLAME,
105 TOG_VIEW_TREE,
106 TOG_VIEW_REF,
107 TOG_VIEW_HELP
108 };
110 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
111 enum tog_keymap_type {
112 TOG_KEYMAP_KEYS = -2,
113 TOG_KEYMAP_GLOBAL,
114 TOG_KEYMAP_DIFF,
115 TOG_KEYMAP_LOG,
116 TOG_KEYMAP_BLAME,
117 TOG_KEYMAP_TREE,
118 TOG_KEYMAP_REF,
119 TOG_KEYMAP_HELP
120 };
122 enum tog_view_mode {
123 TOG_VIEW_SPLIT_NONE,
124 TOG_VIEW_SPLIT_VERT,
125 TOG_VIEW_SPLIT_HRZN
126 };
128 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
130 #define TOG_EOF_STRING "(END)"
132 struct commit_queue_entry {
133 TAILQ_ENTRY(commit_queue_entry) entry;
134 struct got_object_id *id;
135 struct got_commit_object *commit;
136 int idx;
137 };
138 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
139 struct commit_queue {
140 int ncommits;
141 struct commit_queue_head head;
142 };
144 struct tog_color {
145 STAILQ_ENTRY(tog_color) entry;
146 regex_t regex;
147 short colorpair;
148 };
149 STAILQ_HEAD(tog_colors, tog_color);
151 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
152 static struct got_reflist_object_id_map *tog_refs_idmap;
153 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
155 static const struct got_error *
156 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
157 struct got_reference* re2)
159 const char *name1 = got_ref_get_name(re1);
160 const char *name2 = got_ref_get_name(re2);
161 int isbackup1, isbackup2;
163 /* Sort backup refs towards the bottom of the list. */
164 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
165 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
166 if (!isbackup1 && isbackup2) {
167 *cmp = -1;
168 return NULL;
169 } else if (isbackup1 && !isbackup2) {
170 *cmp = 1;
171 return NULL;
174 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
175 return NULL;
178 static const struct got_error *
179 tog_load_refs(struct got_repository *repo, int sort_by_date)
181 const struct got_error *err;
183 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
184 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
185 repo);
186 if (err)
187 return err;
189 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
190 repo);
193 static void
194 tog_free_refs(void)
196 if (tog_refs_idmap) {
197 got_reflist_object_id_map_free(tog_refs_idmap);
198 tog_refs_idmap = NULL;
200 got_ref_list_free(&tog_refs);
203 static const struct got_error *
204 add_color(struct tog_colors *colors, const char *pattern,
205 int idx, short color)
207 const struct got_error *err = NULL;
208 struct tog_color *tc;
209 int regerr = 0;
211 if (idx < 1 || idx > COLOR_PAIRS - 1)
212 return NULL;
214 init_pair(idx, color, -1);
216 tc = calloc(1, sizeof(*tc));
217 if (tc == NULL)
218 return got_error_from_errno("calloc");
219 regerr = regcomp(&tc->regex, pattern,
220 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
221 if (regerr) {
222 static char regerr_msg[512];
223 static char err_msg[512];
224 regerror(regerr, &tc->regex, regerr_msg,
225 sizeof(regerr_msg));
226 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
227 regerr_msg);
228 err = got_error_msg(GOT_ERR_REGEX, err_msg);
229 free(tc);
230 return err;
232 tc->colorpair = idx;
233 STAILQ_INSERT_HEAD(colors, tc, entry);
234 return NULL;
237 static void
238 free_colors(struct tog_colors *colors)
240 struct tog_color *tc;
242 while (!STAILQ_EMPTY(colors)) {
243 tc = STAILQ_FIRST(colors);
244 STAILQ_REMOVE_HEAD(colors, entry);
245 regfree(&tc->regex);
246 free(tc);
250 static struct tog_color *
251 get_color(struct tog_colors *colors, int colorpair)
253 struct tog_color *tc = NULL;
255 STAILQ_FOREACH(tc, colors, entry) {
256 if (tc->colorpair == colorpair)
257 return tc;
260 return NULL;
263 static int
264 default_color_value(const char *envvar)
266 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
281 return COLOR_GREEN;
282 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
287 return COLOR_YELLOW;
288 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
291 return COLOR_MAGENTA;
292 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
295 return COLOR_CYAN;
297 return -1;
300 static int
301 get_color_value(const char *envvar)
303 const char *val = getenv(envvar);
305 if (val == NULL)
306 return default_color_value(envvar);
308 if (strcasecmp(val, "black") == 0)
309 return COLOR_BLACK;
310 if (strcasecmp(val, "red") == 0)
311 return COLOR_RED;
312 if (strcasecmp(val, "green") == 0)
313 return COLOR_GREEN;
314 if (strcasecmp(val, "yellow") == 0)
315 return COLOR_YELLOW;
316 if (strcasecmp(val, "blue") == 0)
317 return COLOR_BLUE;
318 if (strcasecmp(val, "magenta") == 0)
319 return COLOR_MAGENTA;
320 if (strcasecmp(val, "cyan") == 0)
321 return COLOR_CYAN;
322 if (strcasecmp(val, "white") == 0)
323 return COLOR_WHITE;
324 if (strcasecmp(val, "default") == 0)
325 return -1;
327 return default_color_value(envvar);
330 struct tog_diff_view_state {
331 struct got_object_id *id1, *id2;
332 const char *label1, *label2;
333 FILE *f, *f1, *f2;
334 int fd1, fd2;
335 int lineno;
336 int first_displayed_line;
337 int last_displayed_line;
338 int eof;
339 int diff_context;
340 int ignore_whitespace;
341 int force_text_diff;
342 struct got_repository *repo;
343 struct got_diff_line *lines;
344 size_t nlines;
345 int matched_line;
346 int selected_line;
348 /* passed from log or blame view; may be NULL */
349 struct tog_view *parent_view;
350 };
352 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
353 static volatile sig_atomic_t tog_thread_error;
355 struct tog_log_thread_args {
356 pthread_cond_t need_commits;
357 pthread_cond_t commit_loaded;
358 int commits_needed;
359 int load_all;
360 struct got_commit_graph *graph;
361 struct commit_queue *real_commits;
362 const char *in_repo_path;
363 struct got_object_id *start_id;
364 struct got_repository *repo;
365 int *pack_fds;
366 int log_complete;
367 sig_atomic_t *quit;
368 struct commit_queue_entry **first_displayed_entry;
369 struct commit_queue_entry **selected_entry;
370 int *searching;
371 int *search_next_done;
372 regex_t *regex;
373 int *limiting;
374 int limit_match;
375 regex_t *limit_regex;
376 struct commit_queue *limit_commits;
377 };
379 struct tog_log_view_state {
380 struct commit_queue *commits;
381 struct commit_queue_entry *first_displayed_entry;
382 struct commit_queue_entry *last_displayed_entry;
383 struct commit_queue_entry *selected_entry;
384 struct commit_queue real_commits;
385 int selected;
386 char *in_repo_path;
387 char *head_ref_name;
388 int log_branches;
389 struct got_repository *repo;
390 struct got_object_id *start_id;
391 sig_atomic_t quit;
392 pthread_t thread;
393 struct tog_log_thread_args thread_args;
394 struct commit_queue_entry *matched_entry;
395 struct commit_queue_entry *search_entry;
396 struct tog_colors colors;
397 int use_committer;
398 int limit_view;
399 regex_t limit_regex;
400 struct commit_queue limit_commits;
401 };
403 #define TOG_COLOR_DIFF_MINUS 1
404 #define TOG_COLOR_DIFF_PLUS 2
405 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
406 #define TOG_COLOR_DIFF_META 4
407 #define TOG_COLOR_TREE_SUBMODULE 5
408 #define TOG_COLOR_TREE_SYMLINK 6
409 #define TOG_COLOR_TREE_DIRECTORY 7
410 #define TOG_COLOR_TREE_EXECUTABLE 8
411 #define TOG_COLOR_COMMIT 9
412 #define TOG_COLOR_AUTHOR 10
413 #define TOG_COLOR_DATE 11
414 #define TOG_COLOR_REFS_HEADS 12
415 #define TOG_COLOR_REFS_TAGS 13
416 #define TOG_COLOR_REFS_REMOTES 14
417 #define TOG_COLOR_REFS_BACKUP 15
419 struct tog_blame_cb_args {
420 struct tog_blame_line *lines; /* one per line */
421 int nlines;
423 struct tog_view *view;
424 struct got_object_id *commit_id;
425 int *quit;
426 };
428 struct tog_blame_thread_args {
429 const char *path;
430 struct got_repository *repo;
431 struct tog_blame_cb_args *cb_args;
432 int *complete;
433 got_cancel_cb cancel_cb;
434 void *cancel_arg;
435 };
437 struct tog_blame {
438 FILE *f;
439 off_t filesize;
440 struct tog_blame_line *lines;
441 int nlines;
442 off_t *line_offsets;
443 pthread_t thread;
444 struct tog_blame_thread_args thread_args;
445 struct tog_blame_cb_args cb_args;
446 const char *path;
447 int *pack_fds;
448 };
450 struct tog_blame_view_state {
451 int first_displayed_line;
452 int last_displayed_line;
453 int selected_line;
454 int last_diffed_line;
455 int blame_complete;
456 int eof;
457 int done;
458 struct got_object_id_queue blamed_commits;
459 struct got_object_qid *blamed_commit;
460 char *path;
461 struct got_repository *repo;
462 struct got_object_id *commit_id;
463 struct got_object_id *id_to_log;
464 struct tog_blame blame;
465 int matched_line;
466 struct tog_colors colors;
467 };
469 struct tog_parent_tree {
470 TAILQ_ENTRY(tog_parent_tree) entry;
471 struct got_tree_object *tree;
472 struct got_tree_entry *first_displayed_entry;
473 struct got_tree_entry *selected_entry;
474 int selected;
475 };
477 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
479 struct tog_tree_view_state {
480 char *tree_label;
481 struct got_object_id *commit_id;/* commit which this tree belongs to */
482 struct got_tree_object *root; /* the commit's root tree entry */
483 struct got_tree_object *tree; /* currently displayed (sub-)tree */
484 struct got_tree_entry *first_displayed_entry;
485 struct got_tree_entry *last_displayed_entry;
486 struct got_tree_entry *selected_entry;
487 int ndisplayed, selected, show_ids;
488 struct tog_parent_trees parents; /* parent trees of current sub-tree */
489 char *head_ref_name;
490 struct got_repository *repo;
491 struct got_tree_entry *matched_entry;
492 struct tog_colors colors;
493 };
495 struct tog_reflist_entry {
496 TAILQ_ENTRY(tog_reflist_entry) entry;
497 struct got_reference *ref;
498 int idx;
499 };
501 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
503 struct tog_ref_view_state {
504 struct tog_reflist_head refs;
505 struct tog_reflist_entry *first_displayed_entry;
506 struct tog_reflist_entry *last_displayed_entry;
507 struct tog_reflist_entry *selected_entry;
508 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
509 struct got_repository *repo;
510 struct tog_reflist_entry *matched_entry;
511 struct tog_colors colors;
512 };
514 struct tog_help_view_state {
515 FILE *f;
516 off_t *line_offsets;
517 size_t nlines;
518 int lineno;
519 int first_displayed_line;
520 int last_displayed_line;
521 int eof;
522 int matched_line;
523 int selected_line;
524 int all;
525 enum tog_keymap_type type;
526 };
528 #define GENERATE_HELP \
529 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
530 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
531 KEY_("k C-p Up", "Move cursor or page up one line"), \
532 KEY_("j C-n Down", "Move cursor or page down one line"), \
533 KEY_("C-b b PgUp", "Scroll the view up one page"), \
534 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
535 KEY_("C-u u", "Scroll the view up one half page"), \
536 KEY_("C-d d", "Scroll the view down one half page"), \
537 KEY_("g", "Go to line N (default: first line)"), \
538 KEY_("Home =", "Go to the first line"), \
539 KEY_("G", "Go to line N (default: last line)"), \
540 KEY_("End *", "Go to the last line"), \
541 KEY_("l Right", "Scroll the view right"), \
542 KEY_("h Left", "Scroll the view left"), \
543 KEY_("$", "Scroll view to the rightmost position"), \
544 KEY_("0", "Scroll view to the leftmost position"), \
545 KEY_("-", "Decrease size of the focussed split"), \
546 KEY_("+", "Increase size of the focussed split"), \
547 KEY_("Tab", "Switch focus between views"), \
548 KEY_("F", "Toggle fullscreen mode"), \
549 KEY_("/", "Open prompt to enter search term"), \
550 KEY_("n", "Find next line/token matching the current search term"), \
551 KEY_("N", "Find previous line/token matching the current search term"),\
552 KEY_("q", "Quit the focussed view; Quit help screen"), \
553 KEY_("Q", "Quit tog"), \
555 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
556 KEY_("< ,", "Move cursor up one commit"), \
557 KEY_("> .", "Move cursor down one commit"), \
558 KEY_("Enter", "Open diff view of the selected commit"), \
559 KEY_("B", "Reload the log view and toggle display of merged commits"), \
560 KEY_("R", "Open ref view of all repository references"), \
561 KEY_("T", "Display tree view of the repository from the selected" \
562 " commit"), \
563 KEY_("@", "Toggle between displaying author and committer name"), \
564 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
565 KEY_("C-g Backspace", "Cancel current search or log operation"), \
566 KEY_("C-l", "Reload the log view with new commits in the repository"), \
568 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
569 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
570 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
571 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
572 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
573 " data"), \
574 KEY_("(", "Go to the previous file in the diff"), \
575 KEY_(")", "Go to the next file in the diff"), \
576 KEY_("{", "Go to the previous hunk in the diff"), \
577 KEY_("}", "Go to the next hunk in the diff"), \
578 KEY_("[", "Decrease the number of context lines"), \
579 KEY_("]", "Increase the number of context lines"), \
580 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
582 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
583 KEY_("Enter", "Display diff view of the selected line's commit"), \
584 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
585 KEY_("L", "Open log view for the currently selected annotated line"), \
586 KEY_("C", "Reload view with the previously blamed commit"), \
587 KEY_("c", "Reload view with the version of the file found in the" \
588 " selected line's commit"), \
589 KEY_("p", "Reload view with the version of the file found in the" \
590 " selected line's parent commit"), \
592 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
593 KEY_("Enter", "Enter selected directory or open blame view of the" \
594 " selected file"), \
595 KEY_("L", "Open log view for the selected entry"), \
596 KEY_("R", "Open ref view of all repository references"), \
597 KEY_("i", "Show object IDs for all tree entries"), \
598 KEY_("Backspace", "Return to the parent directory"), \
600 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
601 KEY_("Enter", "Display log view of the selected reference"), \
602 KEY_("T", "Display tree view of the selected reference"), \
603 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
604 KEY_("m", "Toggle display of last modified date for each reference"), \
605 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
606 KEY_("C-l", "Reload view with all repository references")
608 struct tog_key_map {
609 const char *keys;
610 const char *info;
611 enum tog_keymap_type type;
612 };
614 /* curses io for tog regress */
615 struct tog_io {
616 FILE *cin;
617 FILE *cout;
618 FILE *f;
619 };
621 #define TOG_SCREEN_DUMP "SCREENDUMP"
622 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
623 #define TOG_KEY_SCRDUMP SHRT_MIN
625 /*
626 * We implement two types of views: parent views and child views.
628 * The 'Tab' key switches focus between a parent view and its child view.
629 * Child views are shown side-by-side to their parent view, provided
630 * there is enough screen estate.
632 * When a new view is opened from within a parent view, this new view
633 * becomes a child view of the parent view, replacing any existing child.
635 * When a new view is opened from within a child view, this new view
636 * becomes a parent view which will obscure the views below until the
637 * user quits the new parent view by typing 'q'.
639 * This list of views contains parent views only.
640 * Child views are only pointed to by their parent view.
641 */
642 TAILQ_HEAD(tog_view_list_head, tog_view);
644 struct tog_view {
645 TAILQ_ENTRY(tog_view) entry;
646 WINDOW *window;
647 PANEL *panel;
648 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
649 int resized_y, resized_x; /* begin_y/x based on user resizing */
650 int maxx, x; /* max column and current start column */
651 int lines, cols; /* copies of LINES and COLS */
652 int nscrolled, offset; /* lines scrolled and hsplit line offset */
653 int gline, hiline; /* navigate to and highlight this nG line */
654 int ch, count; /* current keymap and count prefix */
655 int resized; /* set when in a resize event */
656 int focussed; /* Only set on one parent or child view at a time. */
657 int dying;
658 struct tog_view *parent;
659 struct tog_view *child;
661 /*
662 * This flag is initially set on parent views when a new child view
663 * is created. It gets toggled when the 'Tab' key switches focus
664 * between parent and child.
665 * The flag indicates whether focus should be passed on to our child
666 * view if this parent view gets picked for focus after another parent
667 * view was closed. This prevents child views from losing focus in such
668 * situations.
669 */
670 int focus_child;
672 enum tog_view_mode mode;
673 /* type-specific state */
674 enum tog_view_type type;
675 union {
676 struct tog_diff_view_state diff;
677 struct tog_log_view_state log;
678 struct tog_blame_view_state blame;
679 struct tog_tree_view_state tree;
680 struct tog_ref_view_state ref;
681 struct tog_help_view_state help;
682 } state;
684 const struct got_error *(*show)(struct tog_view *);
685 const struct got_error *(*input)(struct tog_view **,
686 struct tog_view *, int);
687 const struct got_error *(*reset)(struct tog_view *);
688 const struct got_error *(*resize)(struct tog_view *, int);
689 const struct got_error *(*close)(struct tog_view *);
691 const struct got_error *(*search_start)(struct tog_view *);
692 const struct got_error *(*search_next)(struct tog_view *);
693 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
694 int **, int **, int **, int **);
695 int search_started;
696 int searching;
697 #define TOG_SEARCH_FORWARD 1
698 #define TOG_SEARCH_BACKWARD 2
699 int search_next_done;
700 #define TOG_SEARCH_HAVE_MORE 1
701 #define TOG_SEARCH_NO_MORE 2
702 #define TOG_SEARCH_HAVE_NONE 3
703 regex_t regex;
704 regmatch_t regmatch;
705 const char *action;
706 };
708 static const struct got_error *open_diff_view(struct tog_view *,
709 struct got_object_id *, struct got_object_id *,
710 const char *, const char *, int, int, int, struct tog_view *,
711 struct got_repository *);
712 static const struct got_error *show_diff_view(struct tog_view *);
713 static const struct got_error *input_diff_view(struct tog_view **,
714 struct tog_view *, int);
715 static const struct got_error *reset_diff_view(struct tog_view *);
716 static const struct got_error* close_diff_view(struct tog_view *);
717 static const struct got_error *search_start_diff_view(struct tog_view *);
718 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
719 size_t *, int **, int **, int **, int **);
720 static const struct got_error *search_next_view_match(struct tog_view *);
722 static const struct got_error *open_log_view(struct tog_view *,
723 struct got_object_id *, struct got_repository *,
724 const char *, const char *, int);
725 static const struct got_error * show_log_view(struct tog_view *);
726 static const struct got_error *input_log_view(struct tog_view **,
727 struct tog_view *, int);
728 static const struct got_error *resize_log_view(struct tog_view *, int);
729 static const struct got_error *close_log_view(struct tog_view *);
730 static const struct got_error *search_start_log_view(struct tog_view *);
731 static const struct got_error *search_next_log_view(struct tog_view *);
733 static const struct got_error *open_blame_view(struct tog_view *, char *,
734 struct got_object_id *, struct got_repository *);
735 static const struct got_error *show_blame_view(struct tog_view *);
736 static const struct got_error *input_blame_view(struct tog_view **,
737 struct tog_view *, int);
738 static const struct got_error *reset_blame_view(struct tog_view *);
739 static const struct got_error *close_blame_view(struct tog_view *);
740 static const struct got_error *search_start_blame_view(struct tog_view *);
741 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
742 size_t *, int **, int **, int **, int **);
744 static const struct got_error *open_tree_view(struct tog_view *,
745 struct got_object_id *, const char *, struct got_repository *);
746 static const struct got_error *show_tree_view(struct tog_view *);
747 static const struct got_error *input_tree_view(struct tog_view **,
748 struct tog_view *, int);
749 static const struct got_error *close_tree_view(struct tog_view *);
750 static const struct got_error *search_start_tree_view(struct tog_view *);
751 static const struct got_error *search_next_tree_view(struct tog_view *);
753 static const struct got_error *open_ref_view(struct tog_view *,
754 struct got_repository *);
755 static const struct got_error *show_ref_view(struct tog_view *);
756 static const struct got_error *input_ref_view(struct tog_view **,
757 struct tog_view *, int);
758 static const struct got_error *close_ref_view(struct tog_view *);
759 static const struct got_error *search_start_ref_view(struct tog_view *);
760 static const struct got_error *search_next_ref_view(struct tog_view *);
762 static const struct got_error *open_help_view(struct tog_view *,
763 struct tog_view *);
764 static const struct got_error *show_help_view(struct tog_view *);
765 static const struct got_error *input_help_view(struct tog_view **,
766 struct tog_view *, int);
767 static const struct got_error *reset_help_view(struct tog_view *);
768 static const struct got_error* close_help_view(struct tog_view *);
769 static const struct got_error *search_start_help_view(struct tog_view *);
770 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
771 size_t *, int **, int **, int **, int **);
773 static volatile sig_atomic_t tog_sigwinch_received;
774 static volatile sig_atomic_t tog_sigpipe_received;
775 static volatile sig_atomic_t tog_sigcont_received;
776 static volatile sig_atomic_t tog_sigint_received;
777 static volatile sig_atomic_t tog_sigterm_received;
779 static void
780 tog_sigwinch(int signo)
782 tog_sigwinch_received = 1;
785 static void
786 tog_sigpipe(int signo)
788 tog_sigpipe_received = 1;
791 static void
792 tog_sigcont(int signo)
794 tog_sigcont_received = 1;
797 static void
798 tog_sigint(int signo)
800 tog_sigint_received = 1;
803 static void
804 tog_sigterm(int signo)
806 tog_sigterm_received = 1;
809 static int
810 tog_fatal_signal_received(void)
812 return (tog_sigpipe_received ||
813 tog_sigint_received || tog_sigterm_received);
816 static const struct got_error *
817 view_close(struct tog_view *view)
819 const struct got_error *err = NULL, *child_err = NULL;
821 if (view->child) {
822 child_err = view_close(view->child);
823 view->child = NULL;
825 if (view->close)
826 err = view->close(view);
827 if (view->panel)
828 del_panel(view->panel);
829 if (view->window)
830 delwin(view->window);
831 free(view);
832 return err ? err : child_err;
835 static struct tog_view *
836 view_open(int nlines, int ncols, int begin_y, int begin_x,
837 enum tog_view_type type)
839 struct tog_view *view = calloc(1, sizeof(*view));
841 if (view == NULL)
842 return NULL;
844 view->type = type;
845 view->lines = LINES;
846 view->cols = COLS;
847 view->nlines = nlines ? nlines : LINES - begin_y;
848 view->ncols = ncols ? ncols : COLS - begin_x;
849 view->begin_y = begin_y;
850 view->begin_x = begin_x;
851 view->window = newwin(nlines, ncols, begin_y, begin_x);
852 if (view->window == NULL) {
853 view_close(view);
854 return NULL;
856 view->panel = new_panel(view->window);
857 if (view->panel == NULL ||
858 set_panel_userptr(view->panel, view) != OK) {
859 view_close(view);
860 return NULL;
863 keypad(view->window, TRUE);
864 return view;
867 static int
868 view_split_begin_x(int begin_x)
870 if (begin_x > 0 || COLS < 120)
871 return 0;
872 return (COLS - MAX(COLS / 2, 80));
875 /* XXX Stub till we decide what to do. */
876 static int
877 view_split_begin_y(int lines)
879 return lines * HSPLIT_SCALE;
882 static const struct got_error *view_resize(struct tog_view *);
884 static const struct got_error *
885 view_splitscreen(struct tog_view *view)
887 const struct got_error *err = NULL;
889 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
890 if (view->resized_y && view->resized_y < view->lines)
891 view->begin_y = view->resized_y;
892 else
893 view->begin_y = view_split_begin_y(view->nlines);
894 view->begin_x = 0;
895 } else if (!view->resized) {
896 if (view->resized_x && view->resized_x < view->cols - 1 &&
897 view->cols > 119)
898 view->begin_x = view->resized_x;
899 else
900 view->begin_x = view_split_begin_x(0);
901 view->begin_y = 0;
903 view->nlines = LINES - view->begin_y;
904 view->ncols = COLS - view->begin_x;
905 view->lines = LINES;
906 view->cols = COLS;
907 err = view_resize(view);
908 if (err)
909 return err;
911 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
912 view->parent->nlines = view->begin_y;
914 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
915 return got_error_from_errno("mvwin");
917 return NULL;
920 static const struct got_error *
921 view_fullscreen(struct tog_view *view)
923 const struct got_error *err = NULL;
925 view->begin_x = 0;
926 view->begin_y = view->resized ? view->begin_y : 0;
927 view->nlines = view->resized ? view->nlines : LINES;
928 view->ncols = COLS;
929 view->lines = LINES;
930 view->cols = COLS;
931 err = view_resize(view);
932 if (err)
933 return err;
935 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
936 return got_error_from_errno("mvwin");
938 return NULL;
941 static int
942 view_is_parent_view(struct tog_view *view)
944 return view->parent == NULL;
947 static int
948 view_is_splitscreen(struct tog_view *view)
950 return view->begin_x > 0 || view->begin_y > 0;
953 static int
954 view_is_fullscreen(struct tog_view *view)
956 return view->nlines == LINES && view->ncols == COLS;
959 static int
960 view_is_hsplit_top(struct tog_view *view)
962 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
963 view_is_splitscreen(view->child);
966 static void
967 view_border(struct tog_view *view)
969 PANEL *panel;
970 const struct tog_view *view_above;
972 if (view->parent)
973 return view_border(view->parent);
975 panel = panel_above(view->panel);
976 if (panel == NULL)
977 return;
979 view_above = panel_userptr(panel);
980 if (view->mode == TOG_VIEW_SPLIT_HRZN)
981 mvwhline(view->window, view_above->begin_y - 1,
982 view->begin_x, got_locale_is_utf8() ?
983 ACS_HLINE : '-', view->ncols);
984 else
985 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
986 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
989 static const struct got_error *view_init_hsplit(struct tog_view *, int);
990 static const struct got_error *request_log_commits(struct tog_view *);
991 static const struct got_error *offset_selection_down(struct tog_view *);
992 static void offset_selection_up(struct tog_view *);
993 static void view_get_split(struct tog_view *, int *, int *);
995 static const struct got_error *
996 view_resize(struct tog_view *view)
998 const struct got_error *err = NULL;
999 int dif, nlines, ncols;
1001 dif = LINES - view->lines; /* line difference */
1003 if (view->lines > LINES)
1004 nlines = view->nlines - (view->lines - LINES);
1005 else
1006 nlines = view->nlines + (LINES - view->lines);
1007 if (view->cols > COLS)
1008 ncols = view->ncols - (view->cols - COLS);
1009 else
1010 ncols = view->ncols + (COLS - view->cols);
1012 if (view->child) {
1013 int hs = view->child->begin_y;
1015 if (!view_is_fullscreen(view))
1016 view->child->begin_x = view_split_begin_x(view->begin_x);
1017 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1018 view->child->begin_x == 0) {
1019 ncols = COLS;
1021 view_fullscreen(view->child);
1022 if (view->child->focussed)
1023 show_panel(view->child->panel);
1024 else
1025 show_panel(view->panel);
1026 } else {
1027 ncols = view->child->begin_x;
1029 view_splitscreen(view->child);
1030 show_panel(view->child->panel);
1033 * XXX This is ugly and needs to be moved into the above
1034 * logic but "works" for now and my attempts at moving it
1035 * break either 'tab' or 'F' key maps in horizontal splits.
1037 if (hs) {
1038 err = view_splitscreen(view->child);
1039 if (err)
1040 return err;
1041 if (dif < 0) { /* top split decreased */
1042 err = offset_selection_down(view);
1043 if (err)
1044 return err;
1046 view_border(view);
1047 update_panels();
1048 doupdate();
1049 show_panel(view->child->panel);
1050 nlines = view->nlines;
1052 } else if (view->parent == NULL)
1053 ncols = COLS;
1055 if (view->resize && dif > 0) {
1056 err = view->resize(view, dif);
1057 if (err)
1058 return err;
1061 if (wresize(view->window, nlines, ncols) == ERR)
1062 return got_error_from_errno("wresize");
1063 if (replace_panel(view->panel, view->window) == ERR)
1064 return got_error_from_errno("replace_panel");
1065 wclear(view->window);
1067 view->nlines = nlines;
1068 view->ncols = ncols;
1069 view->lines = LINES;
1070 view->cols = COLS;
1072 return NULL;
1075 static const struct got_error *
1076 resize_log_view(struct tog_view *view, int increase)
1078 struct tog_log_view_state *s = &view->state.log;
1079 const struct got_error *err = NULL;
1080 int n = 0;
1082 if (s->selected_entry)
1083 n = s->selected_entry->idx + view->lines - s->selected;
1086 * Request commits to account for the increased
1087 * height so we have enough to populate the view.
1089 if (s->commits->ncommits < n) {
1090 view->nscrolled = n - s->commits->ncommits + increase + 1;
1091 err = request_log_commits(view);
1094 return err;
1097 static void
1098 view_adjust_offset(struct tog_view *view, int n)
1100 if (n == 0)
1101 return;
1103 if (view->parent && view->parent->offset) {
1104 if (view->parent->offset + n >= 0)
1105 view->parent->offset += n;
1106 else
1107 view->parent->offset = 0;
1108 } else if (view->offset) {
1109 if (view->offset - n >= 0)
1110 view->offset -= n;
1111 else
1112 view->offset = 0;
1116 static const struct got_error *
1117 view_resize_split(struct tog_view *view, int resize)
1119 const struct got_error *err = NULL;
1120 struct tog_view *v = NULL;
1122 if (view->parent)
1123 v = view->parent;
1124 else
1125 v = view;
1127 if (!v->child || !view_is_splitscreen(v->child))
1128 return NULL;
1130 v->resized = v->child->resized = resize; /* lock for resize event */
1132 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1133 if (v->child->resized_y)
1134 v->child->begin_y = v->child->resized_y;
1135 if (view->parent)
1136 v->child->begin_y -= resize;
1137 else
1138 v->child->begin_y += resize;
1139 if (v->child->begin_y < 3) {
1140 view->count = 0;
1141 v->child->begin_y = 3;
1142 } else if (v->child->begin_y > LINES - 1) {
1143 view->count = 0;
1144 v->child->begin_y = LINES - 1;
1146 v->ncols = COLS;
1147 v->child->ncols = COLS;
1148 view_adjust_offset(view, resize);
1149 err = view_init_hsplit(v, v->child->begin_y);
1150 if (err)
1151 return err;
1152 v->child->resized_y = v->child->begin_y;
1153 } else {
1154 if (v->child->resized_x)
1155 v->child->begin_x = v->child->resized_x;
1156 if (view->parent)
1157 v->child->begin_x -= resize;
1158 else
1159 v->child->begin_x += resize;
1160 if (v->child->begin_x < 11) {
1161 view->count = 0;
1162 v->child->begin_x = 11;
1163 } else if (v->child->begin_x > COLS - 1) {
1164 view->count = 0;
1165 v->child->begin_x = COLS - 1;
1167 v->child->resized_x = v->child->begin_x;
1170 v->child->mode = v->mode;
1171 v->child->nlines = v->lines - v->child->begin_y;
1172 v->child->ncols = v->cols - v->child->begin_x;
1173 v->focus_child = 1;
1175 err = view_fullscreen(v);
1176 if (err)
1177 return err;
1178 err = view_splitscreen(v->child);
1179 if (err)
1180 return err;
1182 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1183 err = offset_selection_down(v->child);
1184 if (err)
1185 return err;
1188 if (v->resize)
1189 err = v->resize(v, 0);
1190 else if (v->child->resize)
1191 err = v->child->resize(v->child, 0);
1193 v->resized = v->child->resized = 0;
1195 return err;
1198 static void
1199 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1201 struct tog_view *v = src->child ? src->child : src;
1203 dst->resized_x = v->resized_x;
1204 dst->resized_y = v->resized_y;
1207 static const struct got_error *
1208 view_close_child(struct tog_view *view)
1210 const struct got_error *err = NULL;
1212 if (view->child == NULL)
1213 return NULL;
1215 err = view_close(view->child);
1216 view->child = NULL;
1217 return err;
1220 static const struct got_error *
1221 view_set_child(struct tog_view *view, struct tog_view *child)
1223 const struct got_error *err = NULL;
1225 view->child = child;
1226 child->parent = view;
1228 err = view_resize(view);
1229 if (err)
1230 return err;
1232 if (view->child->resized_x || view->child->resized_y)
1233 err = view_resize_split(view, 0);
1235 return err;
1238 static const struct got_error *view_dispatch_request(struct tog_view **,
1239 struct tog_view *, enum tog_view_type, int, int);
1241 static const struct got_error *
1242 view_request_new(struct tog_view **requested, struct tog_view *view,
1243 enum tog_view_type request)
1245 struct tog_view *new_view = NULL;
1246 const struct got_error *err;
1247 int y = 0, x = 0;
1249 *requested = NULL;
1251 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1252 view_get_split(view, &y, &x);
1254 err = view_dispatch_request(&new_view, view, request, y, x);
1255 if (err)
1256 return err;
1258 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1259 request != TOG_VIEW_HELP) {
1260 err = view_init_hsplit(view, y);
1261 if (err)
1262 return err;
1265 view->focussed = 0;
1266 new_view->focussed = 1;
1267 new_view->mode = view->mode;
1268 new_view->nlines = request == TOG_VIEW_HELP ?
1269 view->lines : view->lines - y;
1271 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1272 view_transfer_size(new_view, view);
1273 err = view_close_child(view);
1274 if (err)
1275 return err;
1276 err = view_set_child(view, new_view);
1277 if (err)
1278 return err;
1279 view->focus_child = 1;
1280 } else
1281 *requested = new_view;
1283 return NULL;
1286 static void
1287 tog_resizeterm(void)
1289 int cols, lines;
1290 struct winsize size;
1292 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1293 cols = 80; /* Default */
1294 lines = 24;
1295 } else {
1296 cols = size.ws_col;
1297 lines = size.ws_row;
1299 resize_term(lines, cols);
1302 static const struct got_error *
1303 view_search_start(struct tog_view *view, int fast_refresh)
1305 const struct got_error *err = NULL;
1306 struct tog_view *v = view;
1307 char pattern[1024];
1308 int ret;
1310 if (view->search_started) {
1311 regfree(&view->regex);
1312 view->searching = 0;
1313 memset(&view->regmatch, 0, sizeof(view->regmatch));
1315 view->search_started = 0;
1317 if (view->nlines < 1)
1318 return NULL;
1320 if (view_is_hsplit_top(view))
1321 v = view->child;
1322 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1323 v = view->parent;
1325 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1326 wclrtoeol(v->window);
1328 nodelay(v->window, FALSE); /* block for search term input */
1329 nocbreak();
1330 echo();
1331 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1332 wrefresh(v->window);
1333 cbreak();
1334 noecho();
1335 nodelay(v->window, TRUE);
1336 if (!fast_refresh)
1337 halfdelay(10);
1338 if (ret == ERR)
1339 return NULL;
1341 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1342 err = view->search_start(view);
1343 if (err) {
1344 regfree(&view->regex);
1345 return err;
1347 view->search_started = 1;
1348 view->searching = TOG_SEARCH_FORWARD;
1349 view->search_next_done = 0;
1350 view->search_next(view);
1353 return NULL;
1356 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1357 static const struct got_error *
1358 switch_split(struct tog_view *view)
1360 const struct got_error *err = NULL;
1361 struct tog_view *v = NULL;
1363 if (view->parent)
1364 v = view->parent;
1365 else
1366 v = view;
1368 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1369 v->mode = TOG_VIEW_SPLIT_VERT;
1370 else
1371 v->mode = TOG_VIEW_SPLIT_HRZN;
1373 if (!v->child)
1374 return NULL;
1375 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1376 v->mode = TOG_VIEW_SPLIT_NONE;
1378 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1379 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1380 v->child->begin_y = v->child->resized_y;
1381 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1382 v->child->begin_x = v->child->resized_x;
1385 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1386 v->ncols = COLS;
1387 v->child->ncols = COLS;
1388 v->child->nscrolled = LINES - v->child->nlines;
1390 err = view_init_hsplit(v, v->child->begin_y);
1391 if (err)
1392 return err;
1394 v->child->mode = v->mode;
1395 v->child->nlines = v->lines - v->child->begin_y;
1396 v->focus_child = 1;
1398 err = view_fullscreen(v);
1399 if (err)
1400 return err;
1401 err = view_splitscreen(v->child);
1402 if (err)
1403 return err;
1405 if (v->mode == TOG_VIEW_SPLIT_NONE)
1406 v->mode = TOG_VIEW_SPLIT_VERT;
1407 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1408 err = offset_selection_down(v);
1409 if (err)
1410 return err;
1411 err = offset_selection_down(v->child);
1412 if (err)
1413 return err;
1414 } else {
1415 offset_selection_up(v);
1416 offset_selection_up(v->child);
1418 if (v->resize)
1419 err = v->resize(v, 0);
1420 else if (v->child->resize)
1421 err = v->child->resize(v->child, 0);
1423 return err;
1427 * Strip trailing whitespace from str starting at byte *n;
1428 * if *n < 0, use strlen(str). Return new str length in *n.
1430 static void
1431 strip_trailing_ws(char *str, int *n)
1433 size_t x = *n;
1435 if (str == NULL || *str == '\0')
1436 return;
1438 if (x < 0)
1439 x = strlen(str);
1441 while (x-- > 0 && isspace((unsigned char)str[x]))
1442 str[x] = '\0';
1444 *n = x + 1;
1448 * Extract visible substring of line y from the curses screen
1449 * and strip trailing whitespace. If vline is set and locale is
1450 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1451 * character is written out as 'x'. Write the line to file f.
1453 static const struct got_error *
1454 view_write_line(FILE *f, int y, int vline)
1456 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1457 int r, w;
1459 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1460 if (r == ERR)
1461 return got_error_fmt(GOT_ERR_RANGE,
1462 "failed to extract line %d", y);
1465 * In some views, lines are padded with blanks to COLS width.
1466 * Strip them so we can diff without the -b flag when testing.
1468 strip_trailing_ws(line, &r);
1470 if (vline > 0 && got_locale_is_utf8())
1471 line[vline] = '|';
1473 w = fprintf(f, "%s\n", line);
1474 if (w != r + 1) /* \n */
1475 return got_ferror(f, GOT_ERR_IO);
1477 return NULL;
1481 * Capture the visible curses screen by writing each line to the
1482 * file at the path set via the TOG_SCR_DUMP environment variable.
1484 static const struct got_error *
1485 screendump(struct tog_view *view)
1487 const struct got_error *err;
1488 FILE *f = NULL;
1489 const char *path;
1490 int i;
1492 path = getenv("TOG_SCR_DUMP");
1493 if (path == NULL || *path == '\0')
1494 return got_error_msg(GOT_ERR_BAD_PATH,
1495 "TOG_SCR_DUMP path not set to capture screen dump");
1496 f = fopen(path, "wex");
1497 if (f == NULL)
1498 return got_error_from_errno_fmt("fopen: %s", path);
1500 if ((view->child && view->child->begin_x) ||
1501 (view->parent && view->begin_x)) {
1502 int ncols = view->child ? view->ncols : view->parent->ncols;
1504 /* vertical splitscreen */
1505 for (i = 0; i < view->nlines; ++i) {
1506 err = view_write_line(f, i, ncols - 1);
1507 if (err)
1508 goto done;
1510 } else {
1511 int hline = 0;
1513 /* fullscreen or horizontal splitscreen */
1514 if ((view->child && view->child->begin_y) ||
1515 (view->parent && view->begin_y)) /* hsplit */
1516 hline = view->child ?
1517 view->child->begin_y : view->begin_y;
1519 for (i = 0; i < view->lines; i++) {
1520 if (hline && got_locale_is_utf8() && i == hline - 1) {
1521 int c;
1523 /* ACS_HLINE writes out as 'q', overwrite it */
1524 for (c = 0; c < view->cols; ++c)
1525 fputc('-', f);
1526 fputc('\n', f);
1527 continue;
1530 err = view_write_line(f, i, 0);
1531 if (err)
1532 goto done;
1536 done:
1537 if (f && fclose(f) == EOF && err == NULL)
1538 err = got_ferror(f, GOT_ERR_IO);
1539 return err;
1543 * Compute view->count from numeric input. Assign total to view->count and
1544 * return first non-numeric key entered.
1546 static int
1547 get_compound_key(struct tog_view *view, int c)
1549 struct tog_view *v = view;
1550 int x, n = 0;
1552 if (view_is_hsplit_top(view))
1553 v = view->child;
1554 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1555 v = view->parent;
1557 view->count = 0;
1558 cbreak(); /* block for input */
1559 nodelay(view->window, FALSE);
1560 wmove(v->window, v->nlines - 1, 0);
1561 wclrtoeol(v->window);
1562 waddch(v->window, ':');
1564 do {
1565 x = getcurx(v->window);
1566 if (x != ERR && x < view->ncols) {
1567 waddch(v->window, c);
1568 wrefresh(v->window);
1572 * Don't overflow. Max valid request should be the greatest
1573 * between the longest and total lines; cap at 10 million.
1575 if (n >= 9999999)
1576 n = 9999999;
1577 else
1578 n = n * 10 + (c - '0');
1579 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1581 if (c == 'G' || c == 'g') { /* nG key map */
1582 view->gline = view->hiline = n;
1583 n = 0;
1584 c = 0;
1587 /* Massage excessive or inapplicable values at the input handler. */
1588 view->count = n;
1590 return c;
1593 static void
1594 action_report(struct tog_view *view)
1596 struct tog_view *v = view;
1598 if (view_is_hsplit_top(view))
1599 v = view->child;
1600 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1601 v = view->parent;
1603 wmove(v->window, v->nlines - 1, 0);
1604 wclrtoeol(v->window);
1605 wprintw(v->window, ":%s", view->action);
1606 wrefresh(v->window);
1609 * Clear action status report. Only clear in blame view
1610 * once annotating is complete, otherwise it's too fast.
1612 if (view->type == TOG_VIEW_BLAME) {
1613 if (view->state.blame.blame_complete)
1614 view->action = NULL;
1615 } else
1616 view->action = NULL;
1620 * Read the next line from the test script and assign
1621 * key instruction to *ch. If at EOF, set the *done flag.
1623 static const struct got_error *
1624 tog_read_script_key(FILE *script, int *ch, int *done)
1626 const struct got_error *err = NULL;
1627 char *line = NULL;
1628 size_t linesz = 0;
1630 if (getline(&line, &linesz, script) == -1) {
1631 if (feof(script)) {
1632 *done = 1;
1633 goto done;
1634 } else {
1635 err = got_ferror(script, GOT_ERR_IO);
1636 goto done;
1638 } else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1639 *ch = KEY_ENTER;
1640 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1641 *ch = KEY_RIGHT;
1642 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1643 *ch = KEY_LEFT;
1644 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1645 *ch = KEY_DOWN;
1646 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1647 *ch = KEY_UP;
1648 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1649 *ch = TOG_KEY_SCRDUMP;
1650 else
1651 *ch = *line;
1653 done:
1654 free(line);
1655 return err;
1658 static const struct got_error *
1659 view_input(struct tog_view **new, int *done, struct tog_view *view,
1660 struct tog_view_list_head *views, struct tog_io *tog_io, int fast_refresh)
1662 const struct got_error *err = NULL;
1663 struct tog_view *v;
1664 int ch, errcode;
1666 *new = NULL;
1668 if (view->action)
1669 action_report(view);
1671 /* Clear "no matches" indicator. */
1672 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1673 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1674 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1675 view->count = 0;
1678 if (view->searching && !view->search_next_done) {
1679 errcode = pthread_mutex_unlock(&tog_mutex);
1680 if (errcode)
1681 return got_error_set_errno(errcode,
1682 "pthread_mutex_unlock");
1683 sched_yield();
1684 errcode = pthread_mutex_lock(&tog_mutex);
1685 if (errcode)
1686 return got_error_set_errno(errcode,
1687 "pthread_mutex_lock");
1688 view->search_next(view);
1689 return NULL;
1692 /* Allow threads to make progress while we are waiting for input. */
1693 errcode = pthread_mutex_unlock(&tog_mutex);
1694 if (errcode)
1695 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1697 if (tog_io && tog_io->f) {
1698 err = tog_read_script_key(tog_io->f, &ch, done);
1699 if (err)
1700 return err;
1701 } else if (view->count && --view->count) {
1702 cbreak();
1703 nodelay(view->window, TRUE);
1704 ch = wgetch(view->window);
1705 /* let C-g or backspace abort unfinished count */
1706 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1707 view->count = 0;
1708 else
1709 ch = view->ch;
1710 } else {
1711 ch = wgetch(view->window);
1712 if (ch >= '1' && ch <= '9')
1713 view->ch = ch = get_compound_key(view, ch);
1715 if (view->hiline && ch != ERR && ch != 0)
1716 view->hiline = 0; /* key pressed, clear line highlight */
1717 nodelay(view->window, TRUE);
1718 errcode = pthread_mutex_lock(&tog_mutex);
1719 if (errcode)
1720 return got_error_set_errno(errcode, "pthread_mutex_lock");
1722 if (tog_sigwinch_received || tog_sigcont_received) {
1723 tog_resizeterm();
1724 tog_sigwinch_received = 0;
1725 tog_sigcont_received = 0;
1726 TAILQ_FOREACH(v, views, entry) {
1727 err = view_resize(v);
1728 if (err)
1729 return err;
1730 err = v->input(new, v, KEY_RESIZE);
1731 if (err)
1732 return err;
1733 if (v->child) {
1734 err = view_resize(v->child);
1735 if (err)
1736 return err;
1737 err = v->child->input(new, v->child,
1738 KEY_RESIZE);
1739 if (err)
1740 return err;
1741 if (v->child->resized_x || v->child->resized_y) {
1742 err = view_resize_split(v, 0);
1743 if (err)
1744 return err;
1750 switch (ch) {
1751 case '?':
1752 case 'H':
1753 case KEY_F(1):
1754 if (view->type == TOG_VIEW_HELP)
1755 err = view->reset(view);
1756 else
1757 err = view_request_new(new, view, TOG_VIEW_HELP);
1758 break;
1759 case '\t':
1760 view->count = 0;
1761 if (view->child) {
1762 view->focussed = 0;
1763 view->child->focussed = 1;
1764 view->focus_child = 1;
1765 } else if (view->parent) {
1766 view->focussed = 0;
1767 view->parent->focussed = 1;
1768 view->parent->focus_child = 0;
1769 if (!view_is_splitscreen(view)) {
1770 if (view->parent->resize) {
1771 err = view->parent->resize(view->parent,
1772 0);
1773 if (err)
1774 return err;
1776 offset_selection_up(view->parent);
1777 err = view_fullscreen(view->parent);
1778 if (err)
1779 return err;
1782 break;
1783 case 'q':
1784 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1785 if (view->parent->resize) {
1786 /* might need more commits to fill fullscreen */
1787 err = view->parent->resize(view->parent, 0);
1788 if (err)
1789 break;
1791 offset_selection_up(view->parent);
1793 err = view->input(new, view, ch);
1794 view->dying = 1;
1795 break;
1796 case 'Q':
1797 *done = 1;
1798 break;
1799 case 'F':
1800 view->count = 0;
1801 if (view_is_parent_view(view)) {
1802 if (view->child == NULL)
1803 break;
1804 if (view_is_splitscreen(view->child)) {
1805 view->focussed = 0;
1806 view->child->focussed = 1;
1807 err = view_fullscreen(view->child);
1808 } else {
1809 err = view_splitscreen(view->child);
1810 if (!err)
1811 err = view_resize_split(view, 0);
1813 if (err)
1814 break;
1815 err = view->child->input(new, view->child,
1816 KEY_RESIZE);
1817 } else {
1818 if (view_is_splitscreen(view)) {
1819 view->parent->focussed = 0;
1820 view->focussed = 1;
1821 err = view_fullscreen(view);
1822 } else {
1823 err = view_splitscreen(view);
1824 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1825 err = view_resize(view->parent);
1826 if (!err)
1827 err = view_resize_split(view, 0);
1829 if (err)
1830 break;
1831 err = view->input(new, view, KEY_RESIZE);
1833 if (err)
1834 break;
1835 if (view->resize) {
1836 err = view->resize(view, 0);
1837 if (err)
1838 break;
1840 if (view->parent)
1841 err = offset_selection_down(view->parent);
1842 if (!err)
1843 err = offset_selection_down(view);
1844 break;
1845 case 'S':
1846 view->count = 0;
1847 err = switch_split(view);
1848 break;
1849 case '-':
1850 err = view_resize_split(view, -1);
1851 break;
1852 case '+':
1853 err = view_resize_split(view, 1);
1854 break;
1855 case KEY_RESIZE:
1856 break;
1857 case '/':
1858 view->count = 0;
1859 if (view->search_start)
1860 view_search_start(view, fast_refresh);
1861 else
1862 err = view->input(new, view, ch);
1863 break;
1864 case 'N':
1865 case 'n':
1866 if (view->search_started && view->search_next) {
1867 view->searching = (ch == 'n' ?
1868 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1869 view->search_next_done = 0;
1870 view->search_next(view);
1871 } else
1872 err = view->input(new, view, ch);
1873 break;
1874 case 'A':
1875 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1876 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1877 view->action = "Patience diff algorithm";
1878 } else {
1879 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1880 view->action = "Myers diff algorithm";
1882 TAILQ_FOREACH(v, views, entry) {
1883 if (v->reset) {
1884 err = v->reset(v);
1885 if (err)
1886 return err;
1888 if (v->child && v->child->reset) {
1889 err = v->child->reset(v->child);
1890 if (err)
1891 return err;
1894 break;
1895 case TOG_KEY_SCRDUMP:
1896 err = screendump(view);
1897 break;
1898 default:
1899 err = view->input(new, view, ch);
1900 break;
1903 return err;
1906 static int
1907 view_needs_focus_indication(struct tog_view *view)
1909 if (view_is_parent_view(view)) {
1910 if (view->child == NULL || view->child->focussed)
1911 return 0;
1912 if (!view_is_splitscreen(view->child))
1913 return 0;
1914 } else if (!view_is_splitscreen(view))
1915 return 0;
1917 return view->focussed;
1920 static const struct got_error *
1921 tog_io_close(struct tog_io *tog_io)
1923 const struct got_error *err = NULL;
1925 if (tog_io->cin && fclose(tog_io->cin) == EOF)
1926 err = got_ferror(tog_io->cin, GOT_ERR_IO);
1927 if (tog_io->cout && fclose(tog_io->cout) == EOF && err == NULL)
1928 err = got_ferror(tog_io->cout, GOT_ERR_IO);
1929 if (tog_io->f && fclose(tog_io->f) == EOF && err == NULL)
1930 err = got_ferror(tog_io->f, GOT_ERR_IO);
1931 free(tog_io);
1932 tog_io = NULL;
1934 return err;
1937 static const struct got_error *
1938 view_loop(struct tog_view *view, struct tog_io *tog_io)
1940 const struct got_error *err = NULL;
1941 struct tog_view_list_head views;
1942 struct tog_view *new_view;
1943 char *mode;
1944 int fast_refresh = 10;
1945 int done = 0, errcode;
1947 mode = getenv("TOG_VIEW_SPLIT_MODE");
1948 if (!mode || !(*mode == 'h' || *mode == 'H'))
1949 view->mode = TOG_VIEW_SPLIT_VERT;
1950 else
1951 view->mode = TOG_VIEW_SPLIT_HRZN;
1953 errcode = pthread_mutex_lock(&tog_mutex);
1954 if (errcode)
1955 return got_error_set_errno(errcode, "pthread_mutex_lock");
1957 TAILQ_INIT(&views);
1958 TAILQ_INSERT_HEAD(&views, view, entry);
1960 view->focussed = 1;
1961 err = view->show(view);
1962 if (err)
1963 return err;
1964 update_panels();
1965 doupdate();
1966 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1967 !tog_fatal_signal_received()) {
1968 /* Refresh fast during initialization, then become slower. */
1969 if (fast_refresh && --fast_refresh == 0)
1970 halfdelay(10); /* switch to once per second */
1972 err = view_input(&new_view, &done, view, &views, tog_io,
1973 fast_refresh);
1974 if (err)
1975 break;
1977 if (view->dying && view == TAILQ_FIRST(&views) &&
1978 TAILQ_NEXT(view, entry) == NULL)
1979 done = 1;
1980 if (done) {
1981 struct tog_view *v;
1984 * When we quit, scroll the screen up a single line
1985 * so we don't lose any information.
1987 TAILQ_FOREACH(v, &views, entry) {
1988 wmove(v->window, 0, 0);
1989 wdeleteln(v->window);
1990 wnoutrefresh(v->window);
1991 if (v->child && !view_is_fullscreen(v)) {
1992 wmove(v->child->window, 0, 0);
1993 wdeleteln(v->child->window);
1994 wnoutrefresh(v->child->window);
1997 doupdate();
2000 if (view->dying) {
2001 struct tog_view *v, *prev = NULL;
2003 if (view_is_parent_view(view))
2004 prev = TAILQ_PREV(view, tog_view_list_head,
2005 entry);
2006 else if (view->parent)
2007 prev = view->parent;
2009 if (view->parent) {
2010 view->parent->child = NULL;
2011 view->parent->focus_child = 0;
2012 /* Restore fullscreen line height. */
2013 view->parent->nlines = view->parent->lines;
2014 err = view_resize(view->parent);
2015 if (err)
2016 break;
2017 /* Make resized splits persist. */
2018 view_transfer_size(view->parent, view);
2019 } else
2020 TAILQ_REMOVE(&views, view, entry);
2022 err = view_close(view);
2023 if (err)
2024 goto done;
2026 view = NULL;
2027 TAILQ_FOREACH(v, &views, entry) {
2028 if (v->focussed)
2029 break;
2031 if (view == NULL && new_view == NULL) {
2032 /* No view has focus. Try to pick one. */
2033 if (prev)
2034 view = prev;
2035 else if (!TAILQ_EMPTY(&views)) {
2036 view = TAILQ_LAST(&views,
2037 tog_view_list_head);
2039 if (view) {
2040 if (view->focus_child) {
2041 view->child->focussed = 1;
2042 view = view->child;
2043 } else
2044 view->focussed = 1;
2048 if (new_view) {
2049 struct tog_view *v, *t;
2050 /* Only allow one parent view per type. */
2051 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2052 if (v->type != new_view->type)
2053 continue;
2054 TAILQ_REMOVE(&views, v, entry);
2055 err = view_close(v);
2056 if (err)
2057 goto done;
2058 break;
2060 TAILQ_INSERT_TAIL(&views, new_view, entry);
2061 view = new_view;
2063 if (view && !done) {
2064 if (view_is_parent_view(view)) {
2065 if (view->child && view->child->focussed)
2066 view = view->child;
2067 } else {
2068 if (view->parent && view->parent->focussed)
2069 view = view->parent;
2071 show_panel(view->panel);
2072 if (view->child && view_is_splitscreen(view->child))
2073 show_panel(view->child->panel);
2074 if (view->parent && view_is_splitscreen(view)) {
2075 err = view->parent->show(view->parent);
2076 if (err)
2077 goto done;
2079 err = view->show(view);
2080 if (err)
2081 goto done;
2082 if (view->child) {
2083 err = view->child->show(view->child);
2084 if (err)
2085 goto done;
2087 update_panels();
2088 doupdate();
2091 done:
2092 while (!TAILQ_EMPTY(&views)) {
2093 const struct got_error *close_err;
2094 view = TAILQ_FIRST(&views);
2095 TAILQ_REMOVE(&views, view, entry);
2096 close_err = view_close(view);
2097 if (close_err && err == NULL)
2098 err = close_err;
2101 errcode = pthread_mutex_unlock(&tog_mutex);
2102 if (errcode && err == NULL)
2103 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2105 return err;
2108 __dead static void
2109 usage_log(void)
2111 endwin();
2112 fprintf(stderr,
2113 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2114 getprogname());
2115 exit(1);
2118 /* Create newly allocated wide-character string equivalent to a byte string. */
2119 static const struct got_error *
2120 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2122 char *vis = NULL;
2123 const struct got_error *err = NULL;
2125 *ws = NULL;
2126 *wlen = mbstowcs(NULL, s, 0);
2127 if (*wlen == (size_t)-1) {
2128 int vislen;
2129 if (errno != EILSEQ)
2130 return got_error_from_errno("mbstowcs");
2132 /* byte string invalid in current encoding; try to "fix" it */
2133 err = got_mbsavis(&vis, &vislen, s);
2134 if (err)
2135 return err;
2136 *wlen = mbstowcs(NULL, vis, 0);
2137 if (*wlen == (size_t)-1) {
2138 err = got_error_from_errno("mbstowcs"); /* give up */
2139 goto done;
2143 *ws = calloc(*wlen + 1, sizeof(**ws));
2144 if (*ws == NULL) {
2145 err = got_error_from_errno("calloc");
2146 goto done;
2149 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2150 err = got_error_from_errno("mbstowcs");
2151 done:
2152 free(vis);
2153 if (err) {
2154 free(*ws);
2155 *ws = NULL;
2156 *wlen = 0;
2158 return err;
2161 static const struct got_error *
2162 expand_tab(char **ptr, const char *src)
2164 char *dst;
2165 size_t len, n, idx = 0, sz = 0;
2167 *ptr = NULL;
2168 n = len = strlen(src);
2169 dst = malloc(n + 1);
2170 if (dst == NULL)
2171 return got_error_from_errno("malloc");
2173 while (idx < len && src[idx]) {
2174 const char c = src[idx];
2176 if (c == '\t') {
2177 size_t nb = TABSIZE - sz % TABSIZE;
2178 char *p;
2180 p = realloc(dst, n + nb);
2181 if (p == NULL) {
2182 free(dst);
2183 return got_error_from_errno("realloc");
2186 dst = p;
2187 n += nb;
2188 memset(dst + sz, ' ', nb);
2189 sz += nb;
2190 } else
2191 dst[sz++] = src[idx];
2192 ++idx;
2195 dst[sz] = '\0';
2196 *ptr = dst;
2197 return NULL;
2201 * Advance at most n columns from wline starting at offset off.
2202 * Return the index to the first character after the span operation.
2203 * Return the combined column width of all spanned wide character in
2204 * *rcol.
2206 static int
2207 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2209 int width, i, cols = 0;
2211 if (n == 0) {
2212 *rcol = cols;
2213 return off;
2216 for (i = off; wline[i] != L'\0'; ++i) {
2217 if (wline[i] == L'\t')
2218 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2219 else
2220 width = wcwidth(wline[i]);
2222 if (width == -1) {
2223 width = 1;
2224 wline[i] = L'.';
2227 if (cols + width > n)
2228 break;
2229 cols += width;
2232 *rcol = cols;
2233 return i;
2237 * Format a line for display, ensuring that it won't overflow a width limit.
2238 * With scrolling, the width returned refers to the scrolled version of the
2239 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2241 static const struct got_error *
2242 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2243 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2245 const struct got_error *err = NULL;
2246 int cols;
2247 wchar_t *wline = NULL;
2248 char *exstr = NULL;
2249 size_t wlen;
2250 int i, scrollx;
2252 *wlinep = NULL;
2253 *widthp = 0;
2255 if (expand) {
2256 err = expand_tab(&exstr, line);
2257 if (err)
2258 return err;
2261 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2262 free(exstr);
2263 if (err)
2264 return err;
2266 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2268 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2269 wline[wlen - 1] = L'\0';
2270 wlen--;
2272 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2273 wline[wlen - 1] = L'\0';
2274 wlen--;
2277 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2278 wline[i] = L'\0';
2280 if (widthp)
2281 *widthp = cols;
2282 if (scrollxp)
2283 *scrollxp = scrollx;
2284 if (err)
2285 free(wline);
2286 else
2287 *wlinep = wline;
2288 return err;
2291 static const struct got_error*
2292 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2293 struct got_object_id *id, struct got_repository *repo)
2295 static const struct got_error *err = NULL;
2296 struct got_reflist_entry *re;
2297 char *s;
2298 const char *name;
2300 *refs_str = NULL;
2302 TAILQ_FOREACH(re, refs, entry) {
2303 struct got_tag_object *tag = NULL;
2304 struct got_object_id *ref_id;
2305 int cmp;
2307 name = got_ref_get_name(re->ref);
2308 if (strcmp(name, GOT_REF_HEAD) == 0)
2309 continue;
2310 if (strncmp(name, "refs/", 5) == 0)
2311 name += 5;
2312 if (strncmp(name, "got/", 4) == 0 &&
2313 strncmp(name, "got/backup/", 11) != 0)
2314 continue;
2315 if (strncmp(name, "heads/", 6) == 0)
2316 name += 6;
2317 if (strncmp(name, "remotes/", 8) == 0) {
2318 name += 8;
2319 s = strstr(name, "/" GOT_REF_HEAD);
2320 if (s != NULL && s[strlen(s)] == '\0')
2321 continue;
2323 err = got_ref_resolve(&ref_id, repo, re->ref);
2324 if (err)
2325 break;
2326 if (strncmp(name, "tags/", 5) == 0) {
2327 err = got_object_open_as_tag(&tag, repo, ref_id);
2328 if (err) {
2329 if (err->code != GOT_ERR_OBJ_TYPE) {
2330 free(ref_id);
2331 break;
2333 /* Ref points at something other than a tag. */
2334 err = NULL;
2335 tag = NULL;
2338 cmp = got_object_id_cmp(tag ?
2339 got_object_tag_get_object_id(tag) : ref_id, id);
2340 free(ref_id);
2341 if (tag)
2342 got_object_tag_close(tag);
2343 if (cmp != 0)
2344 continue;
2345 s = *refs_str;
2346 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2347 s ? ", " : "", name) == -1) {
2348 err = got_error_from_errno("asprintf");
2349 free(s);
2350 *refs_str = NULL;
2351 break;
2353 free(s);
2356 return err;
2359 static const struct got_error *
2360 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2361 int col_tab_align)
2363 char *smallerthan;
2365 smallerthan = strchr(author, '<');
2366 if (smallerthan && smallerthan[1] != '\0')
2367 author = smallerthan + 1;
2368 author[strcspn(author, "@>")] = '\0';
2369 return format_line(wauthor, author_width, NULL, author, 0, limit,
2370 col_tab_align, 0);
2373 static const struct got_error *
2374 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2375 struct got_object_id *id, const size_t date_display_cols,
2376 int author_display_cols)
2378 struct tog_log_view_state *s = &view->state.log;
2379 const struct got_error *err = NULL;
2380 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2381 char *logmsg0 = NULL, *logmsg = NULL;
2382 char *author = NULL;
2383 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2384 int author_width, logmsg_width;
2385 char *newline, *line = NULL;
2386 int col, limit, scrollx;
2387 const int avail = view->ncols;
2388 struct tm tm;
2389 time_t committer_time;
2390 struct tog_color *tc;
2392 committer_time = got_object_commit_get_committer_time(commit);
2393 if (gmtime_r(&committer_time, &tm) == NULL)
2394 return got_error_from_errno("gmtime_r");
2395 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2396 return got_error(GOT_ERR_NO_SPACE);
2398 if (avail <= date_display_cols)
2399 limit = MIN(sizeof(datebuf) - 1, avail);
2400 else
2401 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2402 tc = get_color(&s->colors, TOG_COLOR_DATE);
2403 if (tc)
2404 wattr_on(view->window,
2405 COLOR_PAIR(tc->colorpair), NULL);
2406 waddnstr(view->window, datebuf, limit);
2407 if (tc)
2408 wattr_off(view->window,
2409 COLOR_PAIR(tc->colorpair), NULL);
2410 col = limit;
2411 if (col > avail)
2412 goto done;
2414 if (avail >= 120) {
2415 char *id_str;
2416 err = got_object_id_str(&id_str, id);
2417 if (err)
2418 goto done;
2419 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2420 if (tc)
2421 wattr_on(view->window,
2422 COLOR_PAIR(tc->colorpair), NULL);
2423 wprintw(view->window, "%.8s ", id_str);
2424 if (tc)
2425 wattr_off(view->window,
2426 COLOR_PAIR(tc->colorpair), NULL);
2427 free(id_str);
2428 col += 9;
2429 if (col > avail)
2430 goto done;
2433 if (s->use_committer)
2434 author = strdup(got_object_commit_get_committer(commit));
2435 else
2436 author = strdup(got_object_commit_get_author(commit));
2437 if (author == NULL) {
2438 err = got_error_from_errno("strdup");
2439 goto done;
2441 err = format_author(&wauthor, &author_width, author, avail - col, col);
2442 if (err)
2443 goto done;
2444 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2445 if (tc)
2446 wattr_on(view->window,
2447 COLOR_PAIR(tc->colorpair), NULL);
2448 waddwstr(view->window, wauthor);
2449 col += author_width;
2450 while (col < avail && author_width < author_display_cols + 2) {
2451 waddch(view->window, ' ');
2452 col++;
2453 author_width++;
2455 if (tc)
2456 wattr_off(view->window,
2457 COLOR_PAIR(tc->colorpair), NULL);
2458 if (col > avail)
2459 goto done;
2461 err = got_object_commit_get_logmsg(&logmsg0, commit);
2462 if (err)
2463 goto done;
2464 logmsg = logmsg0;
2465 while (*logmsg == '\n')
2466 logmsg++;
2467 newline = strchr(logmsg, '\n');
2468 if (newline)
2469 *newline = '\0';
2470 limit = avail - col;
2471 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2472 limit--; /* for the border */
2473 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2474 limit, col, 1);
2475 if (err)
2476 goto done;
2477 waddwstr(view->window, &wlogmsg[scrollx]);
2478 col += MAX(logmsg_width, 0);
2479 while (col < avail) {
2480 waddch(view->window, ' ');
2481 col++;
2483 done:
2484 free(logmsg0);
2485 free(wlogmsg);
2486 free(author);
2487 free(wauthor);
2488 free(line);
2489 return err;
2492 static struct commit_queue_entry *
2493 alloc_commit_queue_entry(struct got_commit_object *commit,
2494 struct got_object_id *id)
2496 struct commit_queue_entry *entry;
2497 struct got_object_id *dup;
2499 entry = calloc(1, sizeof(*entry));
2500 if (entry == NULL)
2501 return NULL;
2503 dup = got_object_id_dup(id);
2504 if (dup == NULL) {
2505 free(entry);
2506 return NULL;
2509 entry->id = dup;
2510 entry->commit = commit;
2511 return entry;
2514 static void
2515 pop_commit(struct commit_queue *commits)
2517 struct commit_queue_entry *entry;
2519 entry = TAILQ_FIRST(&commits->head);
2520 TAILQ_REMOVE(&commits->head, entry, entry);
2521 got_object_commit_close(entry->commit);
2522 commits->ncommits--;
2523 free(entry->id);
2524 free(entry);
2527 static void
2528 free_commits(struct commit_queue *commits)
2530 while (!TAILQ_EMPTY(&commits->head))
2531 pop_commit(commits);
2534 static const struct got_error *
2535 match_commit(int *have_match, struct got_object_id *id,
2536 struct got_commit_object *commit, regex_t *regex)
2538 const struct got_error *err = NULL;
2539 regmatch_t regmatch;
2540 char *id_str = NULL, *logmsg = NULL;
2542 *have_match = 0;
2544 err = got_object_id_str(&id_str, id);
2545 if (err)
2546 return err;
2548 err = got_object_commit_get_logmsg(&logmsg, commit);
2549 if (err)
2550 goto done;
2552 if (regexec(regex, got_object_commit_get_author(commit), 1,
2553 &regmatch, 0) == 0 ||
2554 regexec(regex, got_object_commit_get_committer(commit), 1,
2555 &regmatch, 0) == 0 ||
2556 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2557 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2558 *have_match = 1;
2559 done:
2560 free(id_str);
2561 free(logmsg);
2562 return err;
2565 static const struct got_error *
2566 queue_commits(struct tog_log_thread_args *a)
2568 const struct got_error *err = NULL;
2571 * We keep all commits open throughout the lifetime of the log
2572 * view in order to avoid having to re-fetch commits from disk
2573 * while updating the display.
2575 do {
2576 struct got_object_id id;
2577 struct got_commit_object *commit;
2578 struct commit_queue_entry *entry;
2579 int limit_match = 0;
2580 int errcode;
2582 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2583 NULL, NULL);
2584 if (err)
2585 break;
2587 err = got_object_open_as_commit(&commit, a->repo, &id);
2588 if (err)
2589 break;
2590 entry = alloc_commit_queue_entry(commit, &id);
2591 if (entry == NULL) {
2592 err = got_error_from_errno("alloc_commit_queue_entry");
2593 break;
2596 errcode = pthread_mutex_lock(&tog_mutex);
2597 if (errcode) {
2598 err = got_error_set_errno(errcode,
2599 "pthread_mutex_lock");
2600 break;
2603 entry->idx = a->real_commits->ncommits;
2604 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2605 a->real_commits->ncommits++;
2607 if (*a->limiting) {
2608 err = match_commit(&limit_match, &id, commit,
2609 a->limit_regex);
2610 if (err)
2611 break;
2613 if (limit_match) {
2614 struct commit_queue_entry *matched;
2616 matched = alloc_commit_queue_entry(
2617 entry->commit, entry->id);
2618 if (matched == NULL) {
2619 err = got_error_from_errno(
2620 "alloc_commit_queue_entry");
2621 break;
2623 matched->commit = entry->commit;
2624 got_object_commit_retain(entry->commit);
2626 matched->idx = a->limit_commits->ncommits;
2627 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2628 matched, entry);
2629 a->limit_commits->ncommits++;
2633 * This is how we signal log_thread() that we
2634 * have found a match, and that it should be
2635 * counted as a new entry for the view.
2637 a->limit_match = limit_match;
2640 if (*a->searching == TOG_SEARCH_FORWARD &&
2641 !*a->search_next_done) {
2642 int have_match;
2643 err = match_commit(&have_match, &id, commit, a->regex);
2644 if (err)
2645 break;
2647 if (*a->limiting) {
2648 if (limit_match && have_match)
2649 *a->search_next_done =
2650 TOG_SEARCH_HAVE_MORE;
2651 } else if (have_match)
2652 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2655 errcode = pthread_mutex_unlock(&tog_mutex);
2656 if (errcode && err == NULL)
2657 err = got_error_set_errno(errcode,
2658 "pthread_mutex_unlock");
2659 if (err)
2660 break;
2661 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2663 return err;
2666 static void
2667 select_commit(struct tog_log_view_state *s)
2669 struct commit_queue_entry *entry;
2670 int ncommits = 0;
2672 entry = s->first_displayed_entry;
2673 while (entry) {
2674 if (ncommits == s->selected) {
2675 s->selected_entry = entry;
2676 break;
2678 entry = TAILQ_NEXT(entry, entry);
2679 ncommits++;
2683 static const struct got_error *
2684 draw_commits(struct tog_view *view)
2686 const struct got_error *err = NULL;
2687 struct tog_log_view_state *s = &view->state.log;
2688 struct commit_queue_entry *entry = s->selected_entry;
2689 int limit = view->nlines;
2690 int width;
2691 int ncommits, author_cols = 4;
2692 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2693 char *refs_str = NULL;
2694 wchar_t *wline;
2695 struct tog_color *tc;
2696 static const size_t date_display_cols = 12;
2698 if (view_is_hsplit_top(view))
2699 --limit; /* account for border */
2701 if (s->selected_entry &&
2702 !(view->searching && view->search_next_done == 0)) {
2703 struct got_reflist_head *refs;
2704 err = got_object_id_str(&id_str, s->selected_entry->id);
2705 if (err)
2706 return err;
2707 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2708 s->selected_entry->id);
2709 if (refs) {
2710 err = build_refs_str(&refs_str, refs,
2711 s->selected_entry->id, s->repo);
2712 if (err)
2713 goto done;
2717 if (s->thread_args.commits_needed == 0)
2718 halfdelay(10); /* disable fast refresh */
2720 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2721 if (asprintf(&ncommits_str, " [%d/%d] %s",
2722 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2723 (view->searching && !view->search_next_done) ?
2724 "searching..." : "loading...") == -1) {
2725 err = got_error_from_errno("asprintf");
2726 goto done;
2728 } else {
2729 const char *search_str = NULL;
2730 const char *limit_str = NULL;
2732 if (view->searching) {
2733 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2734 search_str = "no more matches";
2735 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2736 search_str = "no matches found";
2737 else if (!view->search_next_done)
2738 search_str = "searching...";
2741 if (s->limit_view && s->commits->ncommits == 0)
2742 limit_str = "no matches found";
2744 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2745 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2746 search_str ? search_str : (refs_str ? refs_str : ""),
2747 limit_str ? limit_str : "") == -1) {
2748 err = got_error_from_errno("asprintf");
2749 goto done;
2753 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2754 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2755 "........................................",
2756 s->in_repo_path, ncommits_str) == -1) {
2757 err = got_error_from_errno("asprintf");
2758 header = NULL;
2759 goto done;
2761 } else if (asprintf(&header, "commit %s%s",
2762 id_str ? id_str : "........................................",
2763 ncommits_str) == -1) {
2764 err = got_error_from_errno("asprintf");
2765 header = NULL;
2766 goto done;
2768 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2769 if (err)
2770 goto done;
2772 werase(view->window);
2774 if (view_needs_focus_indication(view))
2775 wstandout(view->window);
2776 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2777 if (tc)
2778 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2779 waddwstr(view->window, wline);
2780 while (width < view->ncols) {
2781 waddch(view->window, ' ');
2782 width++;
2784 if (tc)
2785 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2786 if (view_needs_focus_indication(view))
2787 wstandend(view->window);
2788 free(wline);
2789 if (limit <= 1)
2790 goto done;
2792 /* Grow author column size if necessary, and set view->maxx. */
2793 entry = s->first_displayed_entry;
2794 ncommits = 0;
2795 view->maxx = 0;
2796 while (entry) {
2797 struct got_commit_object *c = entry->commit;
2798 char *author, *eol, *msg, *msg0;
2799 wchar_t *wauthor, *wmsg;
2800 int width;
2801 if (ncommits >= limit - 1)
2802 break;
2803 if (s->use_committer)
2804 author = strdup(got_object_commit_get_committer(c));
2805 else
2806 author = strdup(got_object_commit_get_author(c));
2807 if (author == NULL) {
2808 err = got_error_from_errno("strdup");
2809 goto done;
2811 err = format_author(&wauthor, &width, author, COLS,
2812 date_display_cols);
2813 if (author_cols < width)
2814 author_cols = width;
2815 free(wauthor);
2816 free(author);
2817 if (err)
2818 goto done;
2819 err = got_object_commit_get_logmsg(&msg0, c);
2820 if (err)
2821 goto done;
2822 msg = msg0;
2823 while (*msg == '\n')
2824 ++msg;
2825 if ((eol = strchr(msg, '\n')))
2826 *eol = '\0';
2827 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2828 date_display_cols + author_cols, 0);
2829 if (err)
2830 goto done;
2831 view->maxx = MAX(view->maxx, width);
2832 free(msg0);
2833 free(wmsg);
2834 ncommits++;
2835 entry = TAILQ_NEXT(entry, entry);
2838 entry = s->first_displayed_entry;
2839 s->last_displayed_entry = s->first_displayed_entry;
2840 ncommits = 0;
2841 while (entry) {
2842 if (ncommits >= limit - 1)
2843 break;
2844 if (ncommits == s->selected)
2845 wstandout(view->window);
2846 err = draw_commit(view, entry->commit, entry->id,
2847 date_display_cols, author_cols);
2848 if (ncommits == s->selected)
2849 wstandend(view->window);
2850 if (err)
2851 goto done;
2852 ncommits++;
2853 s->last_displayed_entry = entry;
2854 entry = TAILQ_NEXT(entry, entry);
2857 view_border(view);
2858 done:
2859 free(id_str);
2860 free(refs_str);
2861 free(ncommits_str);
2862 free(header);
2863 return err;
2866 static void
2867 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2869 struct commit_queue_entry *entry;
2870 int nscrolled = 0;
2872 entry = TAILQ_FIRST(&s->commits->head);
2873 if (s->first_displayed_entry == entry)
2874 return;
2876 entry = s->first_displayed_entry;
2877 while (entry && nscrolled < maxscroll) {
2878 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2879 if (entry) {
2880 s->first_displayed_entry = entry;
2881 nscrolled++;
2886 static const struct got_error *
2887 trigger_log_thread(struct tog_view *view, int wait)
2889 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2890 int errcode;
2892 halfdelay(1); /* fast refresh while loading commits */
2894 while (!ta->log_complete && !tog_thread_error &&
2895 (ta->commits_needed > 0 || ta->load_all)) {
2896 /* Wake the log thread. */
2897 errcode = pthread_cond_signal(&ta->need_commits);
2898 if (errcode)
2899 return got_error_set_errno(errcode,
2900 "pthread_cond_signal");
2903 * The mutex will be released while the view loop waits
2904 * in wgetch(), at which time the log thread will run.
2906 if (!wait)
2907 break;
2909 /* Display progress update in log view. */
2910 show_log_view(view);
2911 update_panels();
2912 doupdate();
2914 /* Wait right here while next commit is being loaded. */
2915 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2916 if (errcode)
2917 return got_error_set_errno(errcode,
2918 "pthread_cond_wait");
2920 /* Display progress update in log view. */
2921 show_log_view(view);
2922 update_panels();
2923 doupdate();
2926 return NULL;
2929 static const struct got_error *
2930 request_log_commits(struct tog_view *view)
2932 struct tog_log_view_state *state = &view->state.log;
2933 const struct got_error *err = NULL;
2935 if (state->thread_args.log_complete)
2936 return NULL;
2938 state->thread_args.commits_needed += view->nscrolled;
2939 err = trigger_log_thread(view, 1);
2940 view->nscrolled = 0;
2942 return err;
2945 static const struct got_error *
2946 log_scroll_down(struct tog_view *view, int maxscroll)
2948 struct tog_log_view_state *s = &view->state.log;
2949 const struct got_error *err = NULL;
2950 struct commit_queue_entry *pentry;
2951 int nscrolled = 0, ncommits_needed;
2953 if (s->last_displayed_entry == NULL)
2954 return NULL;
2956 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2957 if (s->commits->ncommits < ncommits_needed &&
2958 !s->thread_args.log_complete) {
2960 * Ask the log thread for required amount of commits.
2962 s->thread_args.commits_needed +=
2963 ncommits_needed - s->commits->ncommits;
2964 err = trigger_log_thread(view, 1);
2965 if (err)
2966 return err;
2969 do {
2970 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2971 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2972 break;
2974 s->last_displayed_entry = pentry ?
2975 pentry : s->last_displayed_entry;
2977 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2978 if (pentry == NULL)
2979 break;
2980 s->first_displayed_entry = pentry;
2981 } while (++nscrolled < maxscroll);
2983 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2984 view->nscrolled += nscrolled;
2985 else
2986 view->nscrolled = 0;
2988 return err;
2991 static const struct got_error *
2992 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2993 struct got_commit_object *commit, struct got_object_id *commit_id,
2994 struct tog_view *log_view, struct got_repository *repo)
2996 const struct got_error *err;
2997 struct got_object_qid *parent_id;
2998 struct tog_view *diff_view;
3000 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3001 if (diff_view == NULL)
3002 return got_error_from_errno("view_open");
3004 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3005 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3006 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3007 if (err == NULL)
3008 *new_view = diff_view;
3009 return err;
3012 static const struct got_error *
3013 tree_view_visit_subtree(struct tog_tree_view_state *s,
3014 struct got_tree_object *subtree)
3016 struct tog_parent_tree *parent;
3018 parent = calloc(1, sizeof(*parent));
3019 if (parent == NULL)
3020 return got_error_from_errno("calloc");
3022 parent->tree = s->tree;
3023 parent->first_displayed_entry = s->first_displayed_entry;
3024 parent->selected_entry = s->selected_entry;
3025 parent->selected = s->selected;
3026 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3027 s->tree = subtree;
3028 s->selected = 0;
3029 s->first_displayed_entry = NULL;
3030 return NULL;
3033 static const struct got_error *
3034 tree_view_walk_path(struct tog_tree_view_state *s,
3035 struct got_commit_object *commit, const char *path)
3037 const struct got_error *err = NULL;
3038 struct got_tree_object *tree = NULL;
3039 const char *p;
3040 char *slash, *subpath = NULL;
3042 /* Walk the path and open corresponding tree objects. */
3043 p = path;
3044 while (*p) {
3045 struct got_tree_entry *te;
3046 struct got_object_id *tree_id;
3047 char *te_name;
3049 while (p[0] == '/')
3050 p++;
3052 /* Ensure the correct subtree entry is selected. */
3053 slash = strchr(p, '/');
3054 if (slash == NULL)
3055 te_name = strdup(p);
3056 else
3057 te_name = strndup(p, slash - p);
3058 if (te_name == NULL) {
3059 err = got_error_from_errno("strndup");
3060 break;
3062 te = got_object_tree_find_entry(s->tree, te_name);
3063 if (te == NULL) {
3064 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3065 free(te_name);
3066 break;
3068 free(te_name);
3069 s->first_displayed_entry = s->selected_entry = te;
3071 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3072 break; /* jump to this file's entry */
3074 slash = strchr(p, '/');
3075 if (slash)
3076 subpath = strndup(path, slash - path);
3077 else
3078 subpath = strdup(path);
3079 if (subpath == NULL) {
3080 err = got_error_from_errno("strdup");
3081 break;
3084 err = got_object_id_by_path(&tree_id, s->repo, commit,
3085 subpath);
3086 if (err)
3087 break;
3089 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3090 free(tree_id);
3091 if (err)
3092 break;
3094 err = tree_view_visit_subtree(s, tree);
3095 if (err) {
3096 got_object_tree_close(tree);
3097 break;
3099 if (slash == NULL)
3100 break;
3101 free(subpath);
3102 subpath = NULL;
3103 p = slash;
3106 free(subpath);
3107 return err;
3110 static const struct got_error *
3111 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3112 struct commit_queue_entry *entry, const char *path,
3113 const char *head_ref_name, struct got_repository *repo)
3115 const struct got_error *err = NULL;
3116 struct tog_tree_view_state *s;
3117 struct tog_view *tree_view;
3119 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3120 if (tree_view == NULL)
3121 return got_error_from_errno("view_open");
3123 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3124 if (err)
3125 return err;
3126 s = &tree_view->state.tree;
3128 *new_view = tree_view;
3130 if (got_path_is_root_dir(path))
3131 return NULL;
3133 return tree_view_walk_path(s, entry->commit, path);
3136 static const struct got_error *
3137 block_signals_used_by_main_thread(void)
3139 sigset_t sigset;
3140 int errcode;
3142 if (sigemptyset(&sigset) == -1)
3143 return got_error_from_errno("sigemptyset");
3145 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3146 if (sigaddset(&sigset, SIGWINCH) == -1)
3147 return got_error_from_errno("sigaddset");
3148 if (sigaddset(&sigset, SIGCONT) == -1)
3149 return got_error_from_errno("sigaddset");
3150 if (sigaddset(&sigset, SIGINT) == -1)
3151 return got_error_from_errno("sigaddset");
3152 if (sigaddset(&sigset, SIGTERM) == -1)
3153 return got_error_from_errno("sigaddset");
3155 /* ncurses handles SIGTSTP */
3156 if (sigaddset(&sigset, SIGTSTP) == -1)
3157 return got_error_from_errno("sigaddset");
3159 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3160 if (errcode)
3161 return got_error_set_errno(errcode, "pthread_sigmask");
3163 return NULL;
3166 static void *
3167 log_thread(void *arg)
3169 const struct got_error *err = NULL;
3170 int errcode = 0;
3171 struct tog_log_thread_args *a = arg;
3172 int done = 0;
3175 * Sync startup with main thread such that we begin our
3176 * work once view_input() has released the mutex.
3178 errcode = pthread_mutex_lock(&tog_mutex);
3179 if (errcode) {
3180 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3181 return (void *)err;
3184 err = block_signals_used_by_main_thread();
3185 if (err) {
3186 pthread_mutex_unlock(&tog_mutex);
3187 goto done;
3190 while (!done && !err && !tog_fatal_signal_received()) {
3191 errcode = pthread_mutex_unlock(&tog_mutex);
3192 if (errcode) {
3193 err = got_error_set_errno(errcode,
3194 "pthread_mutex_unlock");
3195 goto done;
3197 err = queue_commits(a);
3198 if (err) {
3199 if (err->code != GOT_ERR_ITER_COMPLETED)
3200 goto done;
3201 err = NULL;
3202 done = 1;
3203 } else if (a->commits_needed > 0 && !a->load_all) {
3204 if (*a->limiting) {
3205 if (a->limit_match)
3206 a->commits_needed--;
3207 } else
3208 a->commits_needed--;
3211 errcode = pthread_mutex_lock(&tog_mutex);
3212 if (errcode) {
3213 err = got_error_set_errno(errcode,
3214 "pthread_mutex_lock");
3215 goto done;
3216 } else if (*a->quit)
3217 done = 1;
3218 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3219 *a->first_displayed_entry =
3220 TAILQ_FIRST(&a->limit_commits->head);
3221 *a->selected_entry = *a->first_displayed_entry;
3222 } else if (*a->first_displayed_entry == NULL) {
3223 *a->first_displayed_entry =
3224 TAILQ_FIRST(&a->real_commits->head);
3225 *a->selected_entry = *a->first_displayed_entry;
3228 errcode = pthread_cond_signal(&a->commit_loaded);
3229 if (errcode) {
3230 err = got_error_set_errno(errcode,
3231 "pthread_cond_signal");
3232 pthread_mutex_unlock(&tog_mutex);
3233 goto done;
3236 if (done)
3237 a->commits_needed = 0;
3238 else {
3239 if (a->commits_needed == 0 && !a->load_all) {
3240 errcode = pthread_cond_wait(&a->need_commits,
3241 &tog_mutex);
3242 if (errcode) {
3243 err = got_error_set_errno(errcode,
3244 "pthread_cond_wait");
3245 pthread_mutex_unlock(&tog_mutex);
3246 goto done;
3248 if (*a->quit)
3249 done = 1;
3253 a->log_complete = 1;
3254 errcode = pthread_mutex_unlock(&tog_mutex);
3255 if (errcode)
3256 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3257 done:
3258 if (err) {
3259 tog_thread_error = 1;
3260 pthread_cond_signal(&a->commit_loaded);
3262 return (void *)err;
3265 static const struct got_error *
3266 stop_log_thread(struct tog_log_view_state *s)
3268 const struct got_error *err = NULL, *thread_err = NULL;
3269 int errcode;
3271 if (s->thread) {
3272 s->quit = 1;
3273 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3274 if (errcode)
3275 return got_error_set_errno(errcode,
3276 "pthread_cond_signal");
3277 errcode = pthread_mutex_unlock(&tog_mutex);
3278 if (errcode)
3279 return got_error_set_errno(errcode,
3280 "pthread_mutex_unlock");
3281 errcode = pthread_join(s->thread, (void **)&thread_err);
3282 if (errcode)
3283 return got_error_set_errno(errcode, "pthread_join");
3284 errcode = pthread_mutex_lock(&tog_mutex);
3285 if (errcode)
3286 return got_error_set_errno(errcode,
3287 "pthread_mutex_lock");
3288 s->thread = NULL;
3291 if (s->thread_args.repo) {
3292 err = got_repo_close(s->thread_args.repo);
3293 s->thread_args.repo = NULL;
3296 if (s->thread_args.pack_fds) {
3297 const struct got_error *pack_err =
3298 got_repo_pack_fds_close(s->thread_args.pack_fds);
3299 if (err == NULL)
3300 err = pack_err;
3301 s->thread_args.pack_fds = NULL;
3304 if (s->thread_args.graph) {
3305 got_commit_graph_close(s->thread_args.graph);
3306 s->thread_args.graph = NULL;
3309 return err ? err : thread_err;
3312 static const struct got_error *
3313 close_log_view(struct tog_view *view)
3315 const struct got_error *err = NULL;
3316 struct tog_log_view_state *s = &view->state.log;
3317 int errcode;
3319 err = stop_log_thread(s);
3321 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3322 if (errcode && err == NULL)
3323 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3325 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3326 if (errcode && err == NULL)
3327 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3329 free_commits(&s->limit_commits);
3330 free_commits(&s->real_commits);
3331 free(s->in_repo_path);
3332 s->in_repo_path = NULL;
3333 free(s->start_id);
3334 s->start_id = NULL;
3335 free(s->head_ref_name);
3336 s->head_ref_name = NULL;
3337 return err;
3341 * We use two queues to implement the limit feature: first consists of
3342 * commits matching the current limit_regex; second is the real queue
3343 * of all known commits (real_commits). When the user starts limiting,
3344 * we swap queues such that all movement and displaying functionality
3345 * works with very slight change.
3347 static const struct got_error *
3348 limit_log_view(struct tog_view *view)
3350 struct tog_log_view_state *s = &view->state.log;
3351 struct commit_queue_entry *entry;
3352 struct tog_view *v = view;
3353 const struct got_error *err = NULL;
3354 char pattern[1024];
3355 int ret;
3357 if (view_is_hsplit_top(view))
3358 v = view->child;
3359 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3360 v = view->parent;
3362 /* Get the pattern */
3363 wmove(v->window, v->nlines - 1, 0);
3364 wclrtoeol(v->window);
3365 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3366 nodelay(v->window, FALSE);
3367 nocbreak();
3368 echo();
3369 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3370 cbreak();
3371 noecho();
3372 nodelay(v->window, TRUE);
3373 if (ret == ERR)
3374 return NULL;
3376 if (*pattern == '\0') {
3378 * Safety measure for the situation where the user
3379 * resets limit without previously limiting anything.
3381 if (!s->limit_view)
3382 return NULL;
3385 * User could have pressed Ctrl+L, which refreshed the
3386 * commit queues, it means we can't save previously
3387 * (before limit took place) displayed entries,
3388 * because they would point to already free'ed memory,
3389 * so we are forced to always select first entry of
3390 * the queue.
3392 s->commits = &s->real_commits;
3393 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3394 s->selected_entry = s->first_displayed_entry;
3395 s->selected = 0;
3396 s->limit_view = 0;
3398 return NULL;
3401 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3402 return NULL;
3404 s->limit_view = 1;
3406 /* Clear the screen while loading limit view */
3407 s->first_displayed_entry = NULL;
3408 s->last_displayed_entry = NULL;
3409 s->selected_entry = NULL;
3410 s->commits = &s->limit_commits;
3412 /* Prepare limit queue for new search */
3413 free_commits(&s->limit_commits);
3414 s->limit_commits.ncommits = 0;
3416 /* First process commits, which are in queue already */
3417 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3418 int have_match = 0;
3420 err = match_commit(&have_match, entry->id,
3421 entry->commit, &s->limit_regex);
3422 if (err)
3423 return err;
3425 if (have_match) {
3426 struct commit_queue_entry *matched;
3428 matched = alloc_commit_queue_entry(entry->commit,
3429 entry->id);
3430 if (matched == NULL) {
3431 err = got_error_from_errno(
3432 "alloc_commit_queue_entry");
3433 break;
3435 matched->commit = entry->commit;
3436 got_object_commit_retain(entry->commit);
3438 matched->idx = s->limit_commits.ncommits;
3439 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3440 matched, entry);
3441 s->limit_commits.ncommits++;
3445 /* Second process all the commits, until we fill the screen */
3446 if (s->limit_commits.ncommits < view->nlines - 1 &&
3447 !s->thread_args.log_complete) {
3448 s->thread_args.commits_needed +=
3449 view->nlines - s->limit_commits.ncommits - 1;
3450 err = trigger_log_thread(view, 1);
3451 if (err)
3452 return err;
3455 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3456 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3457 s->selected = 0;
3459 return NULL;
3462 static const struct got_error *
3463 search_start_log_view(struct tog_view *view)
3465 struct tog_log_view_state *s = &view->state.log;
3467 s->matched_entry = NULL;
3468 s->search_entry = NULL;
3469 return NULL;
3472 static const struct got_error *
3473 search_next_log_view(struct tog_view *view)
3475 const struct got_error *err = NULL;
3476 struct tog_log_view_state *s = &view->state.log;
3477 struct commit_queue_entry *entry;
3479 /* Display progress update in log view. */
3480 show_log_view(view);
3481 update_panels();
3482 doupdate();
3484 if (s->search_entry) {
3485 int errcode, ch;
3486 errcode = pthread_mutex_unlock(&tog_mutex);
3487 if (errcode)
3488 return got_error_set_errno(errcode,
3489 "pthread_mutex_unlock");
3490 ch = wgetch(view->window);
3491 errcode = pthread_mutex_lock(&tog_mutex);
3492 if (errcode)
3493 return got_error_set_errno(errcode,
3494 "pthread_mutex_lock");
3495 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3496 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3497 return NULL;
3499 if (view->searching == TOG_SEARCH_FORWARD)
3500 entry = TAILQ_NEXT(s->search_entry, entry);
3501 else
3502 entry = TAILQ_PREV(s->search_entry,
3503 commit_queue_head, entry);
3504 } else if (s->matched_entry) {
3506 * If the user has moved the cursor after we hit a match,
3507 * the position from where we should continue searching
3508 * might have changed.
3510 if (view->searching == TOG_SEARCH_FORWARD)
3511 entry = TAILQ_NEXT(s->selected_entry, entry);
3512 else
3513 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3514 entry);
3515 } else {
3516 entry = s->selected_entry;
3519 while (1) {
3520 int have_match = 0;
3522 if (entry == NULL) {
3523 if (s->thread_args.log_complete ||
3524 view->searching == TOG_SEARCH_BACKWARD) {
3525 view->search_next_done =
3526 (s->matched_entry == NULL ?
3527 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3528 s->search_entry = NULL;
3529 return NULL;
3532 * Poke the log thread for more commits and return,
3533 * allowing the main loop to make progress. Search
3534 * will resume at s->search_entry once we come back.
3536 s->thread_args.commits_needed++;
3537 return trigger_log_thread(view, 0);
3540 err = match_commit(&have_match, entry->id, entry->commit,
3541 &view->regex);
3542 if (err)
3543 break;
3544 if (have_match) {
3545 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3546 s->matched_entry = entry;
3547 break;
3550 s->search_entry = entry;
3551 if (view->searching == TOG_SEARCH_FORWARD)
3552 entry = TAILQ_NEXT(entry, entry);
3553 else
3554 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3557 if (s->matched_entry) {
3558 int cur = s->selected_entry->idx;
3559 while (cur < s->matched_entry->idx) {
3560 err = input_log_view(NULL, view, KEY_DOWN);
3561 if (err)
3562 return err;
3563 cur++;
3565 while (cur > s->matched_entry->idx) {
3566 err = input_log_view(NULL, view, KEY_UP);
3567 if (err)
3568 return err;
3569 cur--;
3573 s->search_entry = NULL;
3575 return NULL;
3578 static const struct got_error *
3579 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3580 struct got_repository *repo, const char *head_ref_name,
3581 const char *in_repo_path, int log_branches)
3583 const struct got_error *err = NULL;
3584 struct tog_log_view_state *s = &view->state.log;
3585 struct got_repository *thread_repo = NULL;
3586 struct got_commit_graph *thread_graph = NULL;
3587 int errcode;
3589 if (in_repo_path != s->in_repo_path) {
3590 free(s->in_repo_path);
3591 s->in_repo_path = strdup(in_repo_path);
3592 if (s->in_repo_path == NULL)
3593 return got_error_from_errno("strdup");
3596 /* The commit queue only contains commits being displayed. */
3597 TAILQ_INIT(&s->real_commits.head);
3598 s->real_commits.ncommits = 0;
3599 s->commits = &s->real_commits;
3601 TAILQ_INIT(&s->limit_commits.head);
3602 s->limit_view = 0;
3603 s->limit_commits.ncommits = 0;
3605 s->repo = repo;
3606 if (head_ref_name) {
3607 s->head_ref_name = strdup(head_ref_name);
3608 if (s->head_ref_name == NULL) {
3609 err = got_error_from_errno("strdup");
3610 goto done;
3613 s->start_id = got_object_id_dup(start_id);
3614 if (s->start_id == NULL) {
3615 err = got_error_from_errno("got_object_id_dup");
3616 goto done;
3618 s->log_branches = log_branches;
3619 s->use_committer = 1;
3621 STAILQ_INIT(&s->colors);
3622 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3623 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3624 get_color_value("TOG_COLOR_COMMIT"));
3625 if (err)
3626 goto done;
3627 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3628 get_color_value("TOG_COLOR_AUTHOR"));
3629 if (err) {
3630 free_colors(&s->colors);
3631 goto done;
3633 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3634 get_color_value("TOG_COLOR_DATE"));
3635 if (err) {
3636 free_colors(&s->colors);
3637 goto done;
3641 view->show = show_log_view;
3642 view->input = input_log_view;
3643 view->resize = resize_log_view;
3644 view->close = close_log_view;
3645 view->search_start = search_start_log_view;
3646 view->search_next = search_next_log_view;
3648 if (s->thread_args.pack_fds == NULL) {
3649 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3650 if (err)
3651 goto done;
3653 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3654 s->thread_args.pack_fds);
3655 if (err)
3656 goto done;
3657 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3658 !s->log_branches);
3659 if (err)
3660 goto done;
3661 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3662 s->repo, NULL, NULL);
3663 if (err)
3664 goto done;
3666 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3667 if (errcode) {
3668 err = got_error_set_errno(errcode, "pthread_cond_init");
3669 goto done;
3671 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3672 if (errcode) {
3673 err = got_error_set_errno(errcode, "pthread_cond_init");
3674 goto done;
3677 s->thread_args.commits_needed = view->nlines;
3678 s->thread_args.graph = thread_graph;
3679 s->thread_args.real_commits = &s->real_commits;
3680 s->thread_args.limit_commits = &s->limit_commits;
3681 s->thread_args.in_repo_path = s->in_repo_path;
3682 s->thread_args.start_id = s->start_id;
3683 s->thread_args.repo = thread_repo;
3684 s->thread_args.log_complete = 0;
3685 s->thread_args.quit = &s->quit;
3686 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3687 s->thread_args.selected_entry = &s->selected_entry;
3688 s->thread_args.searching = &view->searching;
3689 s->thread_args.search_next_done = &view->search_next_done;
3690 s->thread_args.regex = &view->regex;
3691 s->thread_args.limiting = &s->limit_view;
3692 s->thread_args.limit_regex = &s->limit_regex;
3693 s->thread_args.limit_commits = &s->limit_commits;
3694 done:
3695 if (err)
3696 close_log_view(view);
3697 return err;
3700 static const struct got_error *
3701 show_log_view(struct tog_view *view)
3703 const struct got_error *err;
3704 struct tog_log_view_state *s = &view->state.log;
3706 if (s->thread == NULL) {
3707 int errcode = pthread_create(&s->thread, NULL, log_thread,
3708 &s->thread_args);
3709 if (errcode)
3710 return got_error_set_errno(errcode, "pthread_create");
3711 if (s->thread_args.commits_needed > 0) {
3712 err = trigger_log_thread(view, 1);
3713 if (err)
3714 return err;
3718 return draw_commits(view);
3721 static void
3722 log_move_cursor_up(struct tog_view *view, int page, int home)
3724 struct tog_log_view_state *s = &view->state.log;
3726 if (s->first_displayed_entry == NULL)
3727 return;
3728 if (s->selected_entry->idx == 0)
3729 view->count = 0;
3731 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3732 || home)
3733 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3735 if (!page && !home && s->selected > 0)
3736 --s->selected;
3737 else
3738 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3740 select_commit(s);
3741 return;
3744 static const struct got_error *
3745 log_move_cursor_down(struct tog_view *view, int page)
3747 struct tog_log_view_state *s = &view->state.log;
3748 const struct got_error *err = NULL;
3749 int eos = view->nlines - 2;
3751 if (s->first_displayed_entry == NULL)
3752 return NULL;
3754 if (s->thread_args.log_complete &&
3755 s->selected_entry->idx >= s->commits->ncommits - 1)
3756 return NULL;
3758 if (view_is_hsplit_top(view))
3759 --eos; /* border consumes the last line */
3761 if (!page) {
3762 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3763 ++s->selected;
3764 else
3765 err = log_scroll_down(view, 1);
3766 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3767 struct commit_queue_entry *entry;
3768 int n;
3770 s->selected = 0;
3771 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3772 s->last_displayed_entry = entry;
3773 for (n = 0; n <= eos; n++) {
3774 if (entry == NULL)
3775 break;
3776 s->first_displayed_entry = entry;
3777 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3779 if (n > 0)
3780 s->selected = n - 1;
3781 } else {
3782 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3783 s->thread_args.log_complete)
3784 s->selected += MIN(page,
3785 s->commits->ncommits - s->selected_entry->idx - 1);
3786 else
3787 err = log_scroll_down(view, page);
3789 if (err)
3790 return err;
3793 * We might necessarily overshoot in horizontal
3794 * splits; if so, select the last displayed commit.
3796 if (s->first_displayed_entry && s->last_displayed_entry) {
3797 s->selected = MIN(s->selected,
3798 s->last_displayed_entry->idx -
3799 s->first_displayed_entry->idx);
3802 select_commit(s);
3804 if (s->thread_args.log_complete &&
3805 s->selected_entry->idx == s->commits->ncommits - 1)
3806 view->count = 0;
3808 return NULL;
3811 static void
3812 view_get_split(struct tog_view *view, int *y, int *x)
3814 *x = 0;
3815 *y = 0;
3817 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3818 if (view->child && view->child->resized_y)
3819 *y = view->child->resized_y;
3820 else if (view->resized_y)
3821 *y = view->resized_y;
3822 else
3823 *y = view_split_begin_y(view->lines);
3824 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3825 if (view->child && view->child->resized_x)
3826 *x = view->child->resized_x;
3827 else if (view->resized_x)
3828 *x = view->resized_x;
3829 else
3830 *x = view_split_begin_x(view->begin_x);
3834 /* Split view horizontally at y and offset view->state->selected line. */
3835 static const struct got_error *
3836 view_init_hsplit(struct tog_view *view, int y)
3838 const struct got_error *err = NULL;
3840 view->nlines = y;
3841 view->ncols = COLS;
3842 err = view_resize(view);
3843 if (err)
3844 return err;
3846 err = offset_selection_down(view);
3848 return err;
3851 static const struct got_error *
3852 log_goto_line(struct tog_view *view, int nlines)
3854 const struct got_error *err = NULL;
3855 struct tog_log_view_state *s = &view->state.log;
3856 int g, idx = s->selected_entry->idx;
3858 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3859 return NULL;
3861 g = view->gline;
3862 view->gline = 0;
3864 if (g >= s->first_displayed_entry->idx + 1 &&
3865 g <= s->last_displayed_entry->idx + 1 &&
3866 g - s->first_displayed_entry->idx - 1 < nlines) {
3867 s->selected = g - s->first_displayed_entry->idx - 1;
3868 select_commit(s);
3869 return NULL;
3872 if (idx + 1 < g) {
3873 err = log_move_cursor_down(view, g - idx - 1);
3874 if (!err && g > s->selected_entry->idx + 1)
3875 err = log_move_cursor_down(view,
3876 g - s->first_displayed_entry->idx - 1);
3877 if (err)
3878 return err;
3879 } else if (idx + 1 > g)
3880 log_move_cursor_up(view, idx - g + 1, 0);
3882 if (g < nlines && s->first_displayed_entry->idx == 0)
3883 s->selected = g - 1;
3885 select_commit(s);
3886 return NULL;
3890 static void
3891 horizontal_scroll_input(struct tog_view *view, int ch)
3894 switch (ch) {
3895 case KEY_LEFT:
3896 case 'h':
3897 view->x -= MIN(view->x, 2);
3898 if (view->x <= 0)
3899 view->count = 0;
3900 break;
3901 case KEY_RIGHT:
3902 case 'l':
3903 if (view->x + view->ncols / 2 < view->maxx)
3904 view->x += 2;
3905 else
3906 view->count = 0;
3907 break;
3908 case '0':
3909 view->x = 0;
3910 break;
3911 case '$':
3912 view->x = MAX(view->maxx - view->ncols / 2, 0);
3913 view->count = 0;
3914 break;
3915 default:
3916 break;
3920 static const struct got_error *
3921 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3923 const struct got_error *err = NULL;
3924 struct tog_log_view_state *s = &view->state.log;
3925 int eos, nscroll;
3927 if (s->thread_args.load_all) {
3928 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3929 s->thread_args.load_all = 0;
3930 else if (s->thread_args.log_complete) {
3931 err = log_move_cursor_down(view, s->commits->ncommits);
3932 s->thread_args.load_all = 0;
3934 if (err)
3935 return err;
3938 eos = nscroll = view->nlines - 1;
3939 if (view_is_hsplit_top(view))
3940 --eos; /* border */
3942 if (view->gline)
3943 return log_goto_line(view, eos);
3945 switch (ch) {
3946 case '&':
3947 err = limit_log_view(view);
3948 break;
3949 case 'q':
3950 s->quit = 1;
3951 break;
3952 case '0':
3953 case '$':
3954 case KEY_RIGHT:
3955 case 'l':
3956 case KEY_LEFT:
3957 case 'h':
3958 horizontal_scroll_input(view, ch);
3959 break;
3960 case 'k':
3961 case KEY_UP:
3962 case '<':
3963 case ',':
3964 case CTRL('p'):
3965 log_move_cursor_up(view, 0, 0);
3966 break;
3967 case 'g':
3968 case '=':
3969 case KEY_HOME:
3970 log_move_cursor_up(view, 0, 1);
3971 view->count = 0;
3972 break;
3973 case CTRL('u'):
3974 case 'u':
3975 nscroll /= 2;
3976 /* FALL THROUGH */
3977 case KEY_PPAGE:
3978 case CTRL('b'):
3979 case 'b':
3980 log_move_cursor_up(view, nscroll, 0);
3981 break;
3982 case 'j':
3983 case KEY_DOWN:
3984 case '>':
3985 case '.':
3986 case CTRL('n'):
3987 err = log_move_cursor_down(view, 0);
3988 break;
3989 case '@':
3990 s->use_committer = !s->use_committer;
3991 view->action = s->use_committer ?
3992 "show committer" : "show commit author";
3993 break;
3994 case 'G':
3995 case '*':
3996 case KEY_END: {
3997 /* We don't know yet how many commits, so we're forced to
3998 * traverse them all. */
3999 view->count = 0;
4000 s->thread_args.load_all = 1;
4001 if (!s->thread_args.log_complete)
4002 return trigger_log_thread(view, 0);
4003 err = log_move_cursor_down(view, s->commits->ncommits);
4004 s->thread_args.load_all = 0;
4005 break;
4007 case CTRL('d'):
4008 case 'd':
4009 nscroll /= 2;
4010 /* FALL THROUGH */
4011 case KEY_NPAGE:
4012 case CTRL('f'):
4013 case 'f':
4014 case ' ':
4015 err = log_move_cursor_down(view, nscroll);
4016 break;
4017 case KEY_RESIZE:
4018 if (s->selected > view->nlines - 2)
4019 s->selected = view->nlines - 2;
4020 if (s->selected > s->commits->ncommits - 1)
4021 s->selected = s->commits->ncommits - 1;
4022 select_commit(s);
4023 if (s->commits->ncommits < view->nlines - 1 &&
4024 !s->thread_args.log_complete) {
4025 s->thread_args.commits_needed += (view->nlines - 1) -
4026 s->commits->ncommits;
4027 err = trigger_log_thread(view, 1);
4029 break;
4030 case KEY_ENTER:
4031 case '\r':
4032 view->count = 0;
4033 if (s->selected_entry == NULL)
4034 break;
4035 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4036 break;
4037 case 'T':
4038 view->count = 0;
4039 if (s->selected_entry == NULL)
4040 break;
4041 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4042 break;
4043 case KEY_BACKSPACE:
4044 case CTRL('l'):
4045 case 'B':
4046 view->count = 0;
4047 if (ch == KEY_BACKSPACE &&
4048 got_path_is_root_dir(s->in_repo_path))
4049 break;
4050 err = stop_log_thread(s);
4051 if (err)
4052 return err;
4053 if (ch == KEY_BACKSPACE) {
4054 char *parent_path;
4055 err = got_path_dirname(&parent_path, s->in_repo_path);
4056 if (err)
4057 return err;
4058 free(s->in_repo_path);
4059 s->in_repo_path = parent_path;
4060 s->thread_args.in_repo_path = s->in_repo_path;
4061 } else if (ch == CTRL('l')) {
4062 struct got_object_id *start_id;
4063 err = got_repo_match_object_id(&start_id, NULL,
4064 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4065 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4066 if (err) {
4067 if (s->head_ref_name == NULL ||
4068 err->code != GOT_ERR_NOT_REF)
4069 return err;
4070 /* Try to cope with deleted references. */
4071 free(s->head_ref_name);
4072 s->head_ref_name = NULL;
4073 err = got_repo_match_object_id(&start_id,
4074 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4075 &tog_refs, s->repo);
4076 if (err)
4077 return err;
4079 free(s->start_id);
4080 s->start_id = start_id;
4081 s->thread_args.start_id = s->start_id;
4082 } else /* 'B' */
4083 s->log_branches = !s->log_branches;
4085 if (s->thread_args.pack_fds == NULL) {
4086 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4087 if (err)
4088 return err;
4090 err = got_repo_open(&s->thread_args.repo,
4091 got_repo_get_path(s->repo), NULL,
4092 s->thread_args.pack_fds);
4093 if (err)
4094 return err;
4095 tog_free_refs();
4096 err = tog_load_refs(s->repo, 0);
4097 if (err)
4098 return err;
4099 err = got_commit_graph_open(&s->thread_args.graph,
4100 s->in_repo_path, !s->log_branches);
4101 if (err)
4102 return err;
4103 err = got_commit_graph_iter_start(s->thread_args.graph,
4104 s->start_id, s->repo, NULL, NULL);
4105 if (err)
4106 return err;
4107 free_commits(&s->real_commits);
4108 free_commits(&s->limit_commits);
4109 s->first_displayed_entry = NULL;
4110 s->last_displayed_entry = NULL;
4111 s->selected_entry = NULL;
4112 s->selected = 0;
4113 s->thread_args.log_complete = 0;
4114 s->quit = 0;
4115 s->thread_args.commits_needed = view->lines;
4116 s->matched_entry = NULL;
4117 s->search_entry = NULL;
4118 view->offset = 0;
4119 break;
4120 case 'R':
4121 view->count = 0;
4122 err = view_request_new(new_view, view, TOG_VIEW_REF);
4123 break;
4124 default:
4125 view->count = 0;
4126 break;
4129 return err;
4132 static const struct got_error *
4133 apply_unveil(const char *repo_path, const char *worktree_path)
4135 const struct got_error *error;
4137 #ifdef PROFILE
4138 if (unveil("gmon.out", "rwc") != 0)
4139 return got_error_from_errno2("unveil", "gmon.out");
4140 #endif
4141 if (repo_path && unveil(repo_path, "r") != 0)
4142 return got_error_from_errno2("unveil", repo_path);
4144 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4145 return got_error_from_errno2("unveil", worktree_path);
4147 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4148 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4150 error = got_privsep_unveil_exec_helpers();
4151 if (error != NULL)
4152 return error;
4154 if (unveil(NULL, NULL) != 0)
4155 return got_error_from_errno("unveil");
4157 return NULL;
4160 static const struct got_error *
4161 init_mock_term(struct tog_io **tog_io, const char *test_script_path)
4163 const struct got_error *err = NULL;
4164 struct tog_io *io;
4166 if (*tog_io)
4167 *tog_io = NULL;
4169 if (test_script_path == NULL || *test_script_path == '\0')
4170 return got_error_msg(GOT_ERR_IO, "GOT_TOG_TEST not defined");
4172 io = calloc(1, sizeof(*io));
4173 if (io == NULL)
4174 return got_error_from_errno("calloc");
4176 io->f = fopen(test_script_path, "re");
4177 if (io->f == NULL) {
4178 err = got_error_from_errno_fmt("fopen: %s",
4179 test_script_path);
4180 goto done;
4183 /* test mode, we don't want any output */
4184 io->cout = fopen("/dev/null", "w+");
4185 if (io->cout == NULL) {
4186 err = got_error_from_errno("fopen: /dev/null");
4187 goto done;
4190 io->cin = fopen("/dev/tty", "r+");
4191 if (io->cin == NULL) {
4192 err = got_error_from_errno("fopen: /dev/tty");
4193 goto done;
4196 if (fseeko(io->f, 0L, SEEK_SET) == -1) {
4197 err = got_error_from_errno("fseeko");
4198 goto done;
4202 * XXX Perhaps we should define "xterm" as the terminal
4203 * type for standardised testing instead of using $TERM?
4205 if (newterm(NULL, io->cout, io->cin) == NULL)
4206 err = got_error_msg(GOT_ERR_IO,
4207 "newterm: failed to initialise curses");
4208 done:
4209 if (err)
4210 tog_io_close(io);
4211 else
4212 *tog_io = io;
4213 return err;
4216 static const struct got_error *
4217 init_curses(struct tog_io **tog_io)
4219 const struct got_error *err = NULL;
4220 const char *test_script_path;
4223 * Override default signal handlers before starting ncurses.
4224 * This should prevent ncurses from installing its own
4225 * broken cleanup() signal handler.
4227 signal(SIGWINCH, tog_sigwinch);
4228 signal(SIGPIPE, tog_sigpipe);
4229 signal(SIGCONT, tog_sigcont);
4230 signal(SIGINT, tog_sigint);
4231 signal(SIGTERM, tog_sigterm);
4233 test_script_path = getenv("GOT_TOG_TEST");
4234 if (test_script_path != NULL) {
4235 err = init_mock_term(tog_io, test_script_path);
4236 if (err)
4237 return err;
4238 } else
4239 initscr();
4241 cbreak();
4242 halfdelay(1); /* Do fast refresh while initial view is loading. */
4243 noecho();
4244 nonl();
4245 intrflush(stdscr, FALSE);
4246 keypad(stdscr, TRUE);
4247 curs_set(0);
4248 if (getenv("TOG_COLORS") != NULL) {
4249 start_color();
4250 use_default_colors();
4253 return NULL;
4256 static const struct got_error *
4257 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4258 struct got_repository *repo, struct got_worktree *worktree)
4260 const struct got_error *err = NULL;
4262 if (argc == 0) {
4263 *in_repo_path = strdup("/");
4264 if (*in_repo_path == NULL)
4265 return got_error_from_errno("strdup");
4266 return NULL;
4269 if (worktree) {
4270 const char *prefix = got_worktree_get_path_prefix(worktree);
4271 char *p;
4273 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4274 if (err)
4275 return err;
4276 if (asprintf(in_repo_path, "%s%s%s", prefix,
4277 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4278 p) == -1) {
4279 err = got_error_from_errno("asprintf");
4280 *in_repo_path = NULL;
4282 free(p);
4283 } else
4284 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4286 return err;
4289 static const struct got_error *
4290 cmd_log(int argc, char *argv[])
4292 const struct got_error *io_err, *error;
4293 struct got_repository *repo = NULL;
4294 struct got_worktree *worktree = NULL;
4295 struct got_object_id *start_id = NULL;
4296 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4297 char *start_commit = NULL, *label = NULL;
4298 struct got_reference *ref = NULL;
4299 const char *head_ref_name = NULL;
4300 int ch, log_branches = 0;
4301 struct tog_view *view;
4302 struct tog_io *tog_io = NULL;
4303 int *pack_fds = NULL;
4305 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4306 switch (ch) {
4307 case 'b':
4308 log_branches = 1;
4309 break;
4310 case 'c':
4311 start_commit = optarg;
4312 break;
4313 case 'r':
4314 repo_path = realpath(optarg, NULL);
4315 if (repo_path == NULL)
4316 return got_error_from_errno2("realpath",
4317 optarg);
4318 break;
4319 default:
4320 usage_log();
4321 /* NOTREACHED */
4325 argc -= optind;
4326 argv += optind;
4328 if (argc > 1)
4329 usage_log();
4331 error = got_repo_pack_fds_open(&pack_fds);
4332 if (error != NULL)
4333 goto done;
4335 if (repo_path == NULL) {
4336 cwd = getcwd(NULL, 0);
4337 if (cwd == NULL)
4338 return got_error_from_errno("getcwd");
4339 error = got_worktree_open(&worktree, cwd);
4340 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4341 goto done;
4342 if (worktree)
4343 repo_path =
4344 strdup(got_worktree_get_repo_path(worktree));
4345 else
4346 repo_path = strdup(cwd);
4347 if (repo_path == NULL) {
4348 error = got_error_from_errno("strdup");
4349 goto done;
4353 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4354 if (error != NULL)
4355 goto done;
4357 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4358 repo, worktree);
4359 if (error)
4360 goto done;
4362 error = init_curses(&tog_io);
4363 if (error)
4364 goto done;
4366 error = apply_unveil(got_repo_get_path(repo),
4367 worktree ? got_worktree_get_root_path(worktree) : NULL);
4368 if (error)
4369 goto done;
4371 /* already loaded by tog_log_with_path()? */
4372 if (TAILQ_EMPTY(&tog_refs)) {
4373 error = tog_load_refs(repo, 0);
4374 if (error)
4375 goto done;
4378 if (start_commit == NULL) {
4379 error = got_repo_match_object_id(&start_id, &label,
4380 worktree ? got_worktree_get_head_ref_name(worktree) :
4381 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4382 if (error)
4383 goto done;
4384 head_ref_name = label;
4385 } else {
4386 error = got_ref_open(&ref, repo, start_commit, 0);
4387 if (error == NULL)
4388 head_ref_name = got_ref_get_name(ref);
4389 else if (error->code != GOT_ERR_NOT_REF)
4390 goto done;
4391 error = got_repo_match_object_id(&start_id, NULL,
4392 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4393 if (error)
4394 goto done;
4397 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4398 if (view == NULL) {
4399 error = got_error_from_errno("view_open");
4400 goto done;
4402 error = open_log_view(view, start_id, repo, head_ref_name,
4403 in_repo_path, log_branches);
4404 if (error)
4405 goto done;
4406 if (worktree) {
4407 /* Release work tree lock. */
4408 got_worktree_close(worktree);
4409 worktree = NULL;
4411 error = view_loop(view, tog_io);
4412 done:
4413 free(in_repo_path);
4414 free(repo_path);
4415 free(cwd);
4416 free(start_id);
4417 free(label);
4418 if (ref)
4419 got_ref_close(ref);
4420 if (repo) {
4421 const struct got_error *close_err = got_repo_close(repo);
4422 if (error == NULL)
4423 error = close_err;
4425 if (worktree)
4426 got_worktree_close(worktree);
4427 if (pack_fds) {
4428 const struct got_error *pack_err =
4429 got_repo_pack_fds_close(pack_fds);
4430 if (error == NULL)
4431 error = pack_err;
4433 if (tog_io != NULL) {
4434 io_err = tog_io_close(tog_io);
4435 if (error == NULL)
4436 error = io_err;
4438 tog_free_refs();
4439 return error;
4442 __dead static void
4443 usage_diff(void)
4445 endwin();
4446 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4447 "object1 object2\n", getprogname());
4448 exit(1);
4451 static int
4452 match_line(const char *line, regex_t *regex, size_t nmatch,
4453 regmatch_t *regmatch)
4455 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4458 static struct tog_color *
4459 match_color(struct tog_colors *colors, const char *line)
4461 struct tog_color *tc = NULL;
4463 STAILQ_FOREACH(tc, colors, entry) {
4464 if (match_line(line, &tc->regex, 0, NULL))
4465 return tc;
4468 return NULL;
4471 static const struct got_error *
4472 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4473 WINDOW *window, int skipcol, regmatch_t *regmatch)
4475 const struct got_error *err = NULL;
4476 char *exstr = NULL;
4477 wchar_t *wline = NULL;
4478 int rme, rms, n, width, scrollx;
4479 int width0 = 0, width1 = 0, width2 = 0;
4480 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4482 *wtotal = 0;
4484 rms = regmatch->rm_so;
4485 rme = regmatch->rm_eo;
4487 err = expand_tab(&exstr, line);
4488 if (err)
4489 return err;
4491 /* Split the line into 3 segments, according to match offsets. */
4492 seg0 = strndup(exstr, rms);
4493 if (seg0 == NULL) {
4494 err = got_error_from_errno("strndup");
4495 goto done;
4497 seg1 = strndup(exstr + rms, rme - rms);
4498 if (seg1 == NULL) {
4499 err = got_error_from_errno("strndup");
4500 goto done;
4502 seg2 = strdup(exstr + rme);
4503 if (seg2 == NULL) {
4504 err = got_error_from_errno("strndup");
4505 goto done;
4508 /* draw up to matched token if we haven't scrolled past it */
4509 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4510 col_tab_align, 1);
4511 if (err)
4512 goto done;
4513 n = MAX(width0 - skipcol, 0);
4514 if (n) {
4515 free(wline);
4516 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4517 wlimit, col_tab_align, 1);
4518 if (err)
4519 goto done;
4520 waddwstr(window, &wline[scrollx]);
4521 wlimit -= width;
4522 *wtotal += width;
4525 if (wlimit > 0) {
4526 int i = 0, w = 0;
4527 size_t wlen;
4529 free(wline);
4530 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4531 col_tab_align, 1);
4532 if (err)
4533 goto done;
4534 wlen = wcslen(wline);
4535 while (i < wlen) {
4536 width = wcwidth(wline[i]);
4537 if (width == -1) {
4538 /* should not happen, tabs are expanded */
4539 err = got_error(GOT_ERR_RANGE);
4540 goto done;
4542 if (width0 + w + width > skipcol)
4543 break;
4544 w += width;
4545 i++;
4547 /* draw (visible part of) matched token (if scrolled into it) */
4548 if (width1 - w > 0) {
4549 wattron(window, A_STANDOUT);
4550 waddwstr(window, &wline[i]);
4551 wattroff(window, A_STANDOUT);
4552 wlimit -= (width1 - w);
4553 *wtotal += (width1 - w);
4557 if (wlimit > 0) { /* draw rest of line */
4558 free(wline);
4559 if (skipcol > width0 + width1) {
4560 err = format_line(&wline, &width2, &scrollx, seg2,
4561 skipcol - (width0 + width1), wlimit,
4562 col_tab_align, 1);
4563 if (err)
4564 goto done;
4565 waddwstr(window, &wline[scrollx]);
4566 } else {
4567 err = format_line(&wline, &width2, NULL, seg2, 0,
4568 wlimit, col_tab_align, 1);
4569 if (err)
4570 goto done;
4571 waddwstr(window, wline);
4573 *wtotal += width2;
4575 done:
4576 free(wline);
4577 free(exstr);
4578 free(seg0);
4579 free(seg1);
4580 free(seg2);
4581 return err;
4584 static int
4585 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4587 FILE *f = NULL;
4588 int *eof, *first, *selected;
4590 if (view->type == TOG_VIEW_DIFF) {
4591 struct tog_diff_view_state *s = &view->state.diff;
4593 first = &s->first_displayed_line;
4594 selected = first;
4595 eof = &s->eof;
4596 f = s->f;
4597 } else if (view->type == TOG_VIEW_HELP) {
4598 struct tog_help_view_state *s = &view->state.help;
4600 first = &s->first_displayed_line;
4601 selected = first;
4602 eof = &s->eof;
4603 f = s->f;
4604 } else if (view->type == TOG_VIEW_BLAME) {
4605 struct tog_blame_view_state *s = &view->state.blame;
4607 first = &s->first_displayed_line;
4608 selected = &s->selected_line;
4609 eof = &s->eof;
4610 f = s->blame.f;
4611 } else
4612 return 0;
4614 /* Center gline in the middle of the page like vi(1). */
4615 if (*lineno < view->gline - (view->nlines - 3) / 2)
4616 return 0;
4617 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4618 rewind(f);
4619 *eof = 0;
4620 *first = 1;
4621 *lineno = 0;
4622 *nprinted = 0;
4623 return 0;
4626 *selected = view->gline <= (view->nlines - 3) / 2 ?
4627 view->gline : (view->nlines - 3) / 2 + 1;
4628 view->gline = 0;
4630 return 1;
4633 static const struct got_error *
4634 draw_file(struct tog_view *view, const char *header)
4636 struct tog_diff_view_state *s = &view->state.diff;
4637 regmatch_t *regmatch = &view->regmatch;
4638 const struct got_error *err;
4639 int nprinted = 0;
4640 char *line;
4641 size_t linesize = 0;
4642 ssize_t linelen;
4643 wchar_t *wline;
4644 int width;
4645 int max_lines = view->nlines;
4646 int nlines = s->nlines;
4647 off_t line_offset;
4649 s->lineno = s->first_displayed_line - 1;
4650 line_offset = s->lines[s->first_displayed_line - 1].offset;
4651 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4652 return got_error_from_errno("fseek");
4654 werase(view->window);
4656 if (view->gline > s->nlines - 1)
4657 view->gline = s->nlines - 1;
4659 if (header) {
4660 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4661 1 : view->gline - (view->nlines - 3) / 2 :
4662 s->lineno + s->selected_line;
4664 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4665 return got_error_from_errno("asprintf");
4666 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4667 0, 0);
4668 free(line);
4669 if (err)
4670 return err;
4672 if (view_needs_focus_indication(view))
4673 wstandout(view->window);
4674 waddwstr(view->window, wline);
4675 free(wline);
4676 wline = NULL;
4677 while (width++ < view->ncols)
4678 waddch(view->window, ' ');
4679 if (view_needs_focus_indication(view))
4680 wstandend(view->window);
4682 if (max_lines <= 1)
4683 return NULL;
4684 max_lines--;
4687 s->eof = 0;
4688 view->maxx = 0;
4689 line = NULL;
4690 while (max_lines > 0 && nprinted < max_lines) {
4691 enum got_diff_line_type linetype;
4692 attr_t attr = 0;
4694 linelen = getline(&line, &linesize, s->f);
4695 if (linelen == -1) {
4696 if (feof(s->f)) {
4697 s->eof = 1;
4698 break;
4700 free(line);
4701 return got_ferror(s->f, GOT_ERR_IO);
4704 if (++s->lineno < s->first_displayed_line)
4705 continue;
4706 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4707 continue;
4708 if (s->lineno == view->hiline)
4709 attr = A_STANDOUT;
4711 /* Set view->maxx based on full line length. */
4712 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4713 view->x ? 1 : 0);
4714 if (err) {
4715 free(line);
4716 return err;
4718 view->maxx = MAX(view->maxx, width);
4719 free(wline);
4720 wline = NULL;
4722 linetype = s->lines[s->lineno].type;
4723 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4724 linetype < GOT_DIFF_LINE_CONTEXT)
4725 attr |= COLOR_PAIR(linetype);
4726 if (attr)
4727 wattron(view->window, attr);
4728 if (s->first_displayed_line + nprinted == s->matched_line &&
4729 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4730 err = add_matched_line(&width, line, view->ncols, 0,
4731 view->window, view->x, regmatch);
4732 if (err) {
4733 free(line);
4734 return err;
4736 } else {
4737 int skip;
4738 err = format_line(&wline, &width, &skip, line,
4739 view->x, view->ncols, 0, view->x ? 1 : 0);
4740 if (err) {
4741 free(line);
4742 return err;
4744 waddwstr(view->window, &wline[skip]);
4745 free(wline);
4746 wline = NULL;
4748 if (s->lineno == view->hiline) {
4749 /* highlight full gline length */
4750 while (width++ < view->ncols)
4751 waddch(view->window, ' ');
4752 } else {
4753 if (width <= view->ncols - 1)
4754 waddch(view->window, '\n');
4756 if (attr)
4757 wattroff(view->window, attr);
4758 if (++nprinted == 1)
4759 s->first_displayed_line = s->lineno;
4761 free(line);
4762 if (nprinted >= 1)
4763 s->last_displayed_line = s->first_displayed_line +
4764 (nprinted - 1);
4765 else
4766 s->last_displayed_line = s->first_displayed_line;
4768 view_border(view);
4770 if (s->eof) {
4771 while (nprinted < view->nlines) {
4772 waddch(view->window, '\n');
4773 nprinted++;
4776 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4777 view->ncols, 0, 0);
4778 if (err) {
4779 return err;
4782 wstandout(view->window);
4783 waddwstr(view->window, wline);
4784 free(wline);
4785 wline = NULL;
4786 wstandend(view->window);
4789 return NULL;
4792 static char *
4793 get_datestr(time_t *time, char *datebuf)
4795 struct tm mytm, *tm;
4796 char *p, *s;
4798 tm = gmtime_r(time, &mytm);
4799 if (tm == NULL)
4800 return NULL;
4801 s = asctime_r(tm, datebuf);
4802 if (s == NULL)
4803 return NULL;
4804 p = strchr(s, '\n');
4805 if (p)
4806 *p = '\0';
4807 return s;
4810 static const struct got_error *
4811 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4812 off_t off, uint8_t type)
4814 struct got_diff_line *p;
4816 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4817 if (p == NULL)
4818 return got_error_from_errno("reallocarray");
4819 *lines = p;
4820 (*lines)[*nlines].offset = off;
4821 (*lines)[*nlines].type = type;
4822 (*nlines)++;
4824 return NULL;
4827 static const struct got_error *
4828 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4829 struct got_diff_line *s_lines, size_t s_nlines)
4831 struct got_diff_line *p;
4832 char buf[BUFSIZ];
4833 size_t i, r;
4835 if (fseeko(src, 0L, SEEK_SET) == -1)
4836 return got_error_from_errno("fseeko");
4838 for (;;) {
4839 r = fread(buf, 1, sizeof(buf), src);
4840 if (r == 0) {
4841 if (ferror(src))
4842 return got_error_from_errno("fread");
4843 if (feof(src))
4844 break;
4846 if (fwrite(buf, 1, r, dst) != r)
4847 return got_ferror(dst, GOT_ERR_IO);
4850 if (s_nlines == 0 && *d_nlines == 0)
4851 return NULL;
4854 * If commit info was in dst, increment line offsets
4855 * of the appended diff content, but skip s_lines[0]
4856 * because offset zero is already in *d_lines.
4858 if (*d_nlines > 0) {
4859 for (i = 1; i < s_nlines; ++i)
4860 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4862 if (s_nlines > 0) {
4863 --s_nlines;
4864 ++s_lines;
4868 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4869 if (p == NULL) {
4870 /* d_lines is freed in close_diff_view() */
4871 return got_error_from_errno("reallocarray");
4874 *d_lines = p;
4876 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4877 *d_nlines += s_nlines;
4879 return NULL;
4882 static const struct got_error *
4883 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4884 struct got_object_id *commit_id, struct got_reflist_head *refs,
4885 struct got_repository *repo, int ignore_ws, int force_text_diff,
4886 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4888 const struct got_error *err = NULL;
4889 char datebuf[26], *datestr;
4890 struct got_commit_object *commit;
4891 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4892 time_t committer_time;
4893 const char *author, *committer;
4894 char *refs_str = NULL;
4895 struct got_pathlist_entry *pe;
4896 off_t outoff = 0;
4897 int n;
4899 if (refs) {
4900 err = build_refs_str(&refs_str, refs, commit_id, repo);
4901 if (err)
4902 return err;
4905 err = got_object_open_as_commit(&commit, repo, commit_id);
4906 if (err)
4907 return err;
4909 err = got_object_id_str(&id_str, commit_id);
4910 if (err) {
4911 err = got_error_from_errno("got_object_id_str");
4912 goto done;
4915 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4916 if (err)
4917 goto done;
4919 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4920 refs_str ? refs_str : "", refs_str ? ")" : "");
4921 if (n < 0) {
4922 err = got_error_from_errno("fprintf");
4923 goto done;
4925 outoff += n;
4926 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4927 if (err)
4928 goto done;
4930 n = fprintf(outfile, "from: %s\n",
4931 got_object_commit_get_author(commit));
4932 if (n < 0) {
4933 err = got_error_from_errno("fprintf");
4934 goto done;
4936 outoff += n;
4937 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4938 if (err)
4939 goto done;
4941 author = got_object_commit_get_author(commit);
4942 committer = got_object_commit_get_committer(commit);
4943 if (strcmp(author, committer) != 0) {
4944 n = fprintf(outfile, "via: %s\n", committer);
4945 if (n < 0) {
4946 err = got_error_from_errno("fprintf");
4947 goto done;
4949 outoff += n;
4950 err = add_line_metadata(lines, nlines, outoff,
4951 GOT_DIFF_LINE_AUTHOR);
4952 if (err)
4953 goto done;
4955 committer_time = got_object_commit_get_committer_time(commit);
4956 datestr = get_datestr(&committer_time, datebuf);
4957 if (datestr) {
4958 n = fprintf(outfile, "date: %s UTC\n", datestr);
4959 if (n < 0) {
4960 err = got_error_from_errno("fprintf");
4961 goto done;
4963 outoff += n;
4964 err = add_line_metadata(lines, nlines, outoff,
4965 GOT_DIFF_LINE_DATE);
4966 if (err)
4967 goto done;
4969 if (got_object_commit_get_nparents(commit) > 1) {
4970 const struct got_object_id_queue *parent_ids;
4971 struct got_object_qid *qid;
4972 int pn = 1;
4973 parent_ids = got_object_commit_get_parent_ids(commit);
4974 STAILQ_FOREACH(qid, parent_ids, entry) {
4975 err = got_object_id_str(&id_str, &qid->id);
4976 if (err)
4977 goto done;
4978 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4979 if (n < 0) {
4980 err = got_error_from_errno("fprintf");
4981 goto done;
4983 outoff += n;
4984 err = add_line_metadata(lines, nlines, outoff,
4985 GOT_DIFF_LINE_META);
4986 if (err)
4987 goto done;
4988 free(id_str);
4989 id_str = NULL;
4993 err = got_object_commit_get_logmsg(&logmsg, commit);
4994 if (err)
4995 goto done;
4996 s = logmsg;
4997 while ((line = strsep(&s, "\n")) != NULL) {
4998 n = fprintf(outfile, "%s\n", line);
4999 if (n < 0) {
5000 err = got_error_from_errno("fprintf");
5001 goto done;
5003 outoff += n;
5004 err = add_line_metadata(lines, nlines, outoff,
5005 GOT_DIFF_LINE_LOGMSG);
5006 if (err)
5007 goto done;
5010 TAILQ_FOREACH(pe, dsa->paths, entry) {
5011 struct got_diff_changed_path *cp = pe->data;
5012 int pad = dsa->max_path_len - pe->path_len + 1;
5014 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5015 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5016 dsa->rm_cols + 1, cp->rm);
5017 if (n < 0) {
5018 err = got_error_from_errno("fprintf");
5019 goto done;
5021 outoff += n;
5022 err = add_line_metadata(lines, nlines, outoff,
5023 GOT_DIFF_LINE_CHANGES);
5024 if (err)
5025 goto done;
5028 fputc('\n', outfile);
5029 outoff++;
5030 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5031 if (err)
5032 goto done;
5034 n = fprintf(outfile,
5035 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5036 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5037 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5038 if (n < 0) {
5039 err = got_error_from_errno("fprintf");
5040 goto done;
5042 outoff += n;
5043 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5044 if (err)
5045 goto done;
5047 fputc('\n', outfile);
5048 outoff++;
5049 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5050 done:
5051 free(id_str);
5052 free(logmsg);
5053 free(refs_str);
5054 got_object_commit_close(commit);
5055 if (err) {
5056 free(*lines);
5057 *lines = NULL;
5058 *nlines = 0;
5060 return err;
5063 static const struct got_error *
5064 create_diff(struct tog_diff_view_state *s)
5066 const struct got_error *err = NULL;
5067 FILE *f = NULL, *tmp_diff_file = NULL;
5068 int obj_type;
5069 struct got_diff_line *lines = NULL;
5070 struct got_pathlist_head changed_paths;
5072 TAILQ_INIT(&changed_paths);
5074 free(s->lines);
5075 s->lines = malloc(sizeof(*s->lines));
5076 if (s->lines == NULL)
5077 return got_error_from_errno("malloc");
5078 s->nlines = 0;
5080 f = got_opentemp();
5081 if (f == NULL) {
5082 err = got_error_from_errno("got_opentemp");
5083 goto done;
5085 tmp_diff_file = got_opentemp();
5086 if (tmp_diff_file == NULL) {
5087 err = got_error_from_errno("got_opentemp");
5088 goto done;
5090 if (s->f && fclose(s->f) == EOF) {
5091 err = got_error_from_errno("fclose");
5092 goto done;
5094 s->f = f;
5096 if (s->id1)
5097 err = got_object_get_type(&obj_type, s->repo, s->id1);
5098 else
5099 err = got_object_get_type(&obj_type, s->repo, s->id2);
5100 if (err)
5101 goto done;
5103 switch (obj_type) {
5104 case GOT_OBJ_TYPE_BLOB:
5105 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5106 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5107 s->label1, s->label2, tog_diff_algo, s->diff_context,
5108 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5109 s->f);
5110 break;
5111 case GOT_OBJ_TYPE_TREE:
5112 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5113 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5114 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5115 s->force_text_diff, NULL, s->repo, s->f);
5116 break;
5117 case GOT_OBJ_TYPE_COMMIT: {
5118 const struct got_object_id_queue *parent_ids;
5119 struct got_object_qid *pid;
5120 struct got_commit_object *commit2;
5121 struct got_reflist_head *refs;
5122 size_t nlines = 0;
5123 struct got_diffstat_cb_arg dsa = {
5124 0, 0, 0, 0, 0, 0,
5125 &changed_paths,
5126 s->ignore_whitespace,
5127 s->force_text_diff,
5128 tog_diff_algo
5131 lines = malloc(sizeof(*lines));
5132 if (lines == NULL) {
5133 err = got_error_from_errno("malloc");
5134 goto done;
5137 /* build diff first in tmp file then append to commit info */
5138 err = got_diff_objects_as_commits(&lines, &nlines,
5139 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5140 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5141 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5142 if (err)
5143 break;
5145 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5146 if (err)
5147 goto done;
5148 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5149 /* Show commit info if we're diffing to a parent/root commit. */
5150 if (s->id1 == NULL) {
5151 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5152 refs, s->repo, s->ignore_whitespace,
5153 s->force_text_diff, &dsa, s->f);
5154 if (err)
5155 goto done;
5156 } else {
5157 parent_ids = got_object_commit_get_parent_ids(commit2);
5158 STAILQ_FOREACH(pid, parent_ids, entry) {
5159 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5160 err = write_commit_info(&s->lines,
5161 &s->nlines, s->id2, refs, s->repo,
5162 s->ignore_whitespace,
5163 s->force_text_diff, &dsa, s->f);
5164 if (err)
5165 goto done;
5166 break;
5170 got_object_commit_close(commit2);
5172 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5173 lines, nlines);
5174 break;
5176 default:
5177 err = got_error(GOT_ERR_OBJ_TYPE);
5178 break;
5180 done:
5181 free(lines);
5182 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5183 if (s->f && fflush(s->f) != 0 && err == NULL)
5184 err = got_error_from_errno("fflush");
5185 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5186 err = got_error_from_errno("fclose");
5187 return err;
5190 static void
5191 diff_view_indicate_progress(struct tog_view *view)
5193 mvwaddstr(view->window, 0, 0, "diffing...");
5194 update_panels();
5195 doupdate();
5198 static const struct got_error *
5199 search_start_diff_view(struct tog_view *view)
5201 struct tog_diff_view_state *s = &view->state.diff;
5203 s->matched_line = 0;
5204 return NULL;
5207 static void
5208 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5209 size_t *nlines, int **first, int **last, int **match, int **selected)
5211 struct tog_diff_view_state *s = &view->state.diff;
5213 *f = s->f;
5214 *nlines = s->nlines;
5215 *line_offsets = NULL;
5216 *match = &s->matched_line;
5217 *first = &s->first_displayed_line;
5218 *last = &s->last_displayed_line;
5219 *selected = &s->selected_line;
5222 static const struct got_error *
5223 search_next_view_match(struct tog_view *view)
5225 const struct got_error *err = NULL;
5226 FILE *f;
5227 int lineno;
5228 char *line = NULL;
5229 size_t linesize = 0;
5230 ssize_t linelen;
5231 off_t *line_offsets;
5232 size_t nlines = 0;
5233 int *first, *last, *match, *selected;
5235 if (!view->search_setup)
5236 return got_error_msg(GOT_ERR_NOT_IMPL,
5237 "view search not supported");
5238 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5239 &match, &selected);
5241 if (!view->searching) {
5242 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5243 return NULL;
5246 if (*match) {
5247 if (view->searching == TOG_SEARCH_FORWARD)
5248 lineno = *first + 1;
5249 else
5250 lineno = *first - 1;
5251 } else
5252 lineno = *first - 1 + *selected;
5254 while (1) {
5255 off_t offset;
5257 if (lineno <= 0 || lineno > nlines) {
5258 if (*match == 0) {
5259 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5260 break;
5263 if (view->searching == TOG_SEARCH_FORWARD)
5264 lineno = 1;
5265 else
5266 lineno = nlines;
5269 offset = view->type == TOG_VIEW_DIFF ?
5270 view->state.diff.lines[lineno - 1].offset :
5271 line_offsets[lineno - 1];
5272 if (fseeko(f, offset, SEEK_SET) != 0) {
5273 free(line);
5274 return got_error_from_errno("fseeko");
5276 linelen = getline(&line, &linesize, f);
5277 if (linelen != -1) {
5278 char *exstr;
5279 err = expand_tab(&exstr, line);
5280 if (err)
5281 break;
5282 if (match_line(exstr, &view->regex, 1,
5283 &view->regmatch)) {
5284 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5285 *match = lineno;
5286 free(exstr);
5287 break;
5289 free(exstr);
5291 if (view->searching == TOG_SEARCH_FORWARD)
5292 lineno++;
5293 else
5294 lineno--;
5296 free(line);
5298 if (*match) {
5299 *first = *match;
5300 *selected = 1;
5303 return err;
5306 static const struct got_error *
5307 close_diff_view(struct tog_view *view)
5309 const struct got_error *err = NULL;
5310 struct tog_diff_view_state *s = &view->state.diff;
5312 free(s->id1);
5313 s->id1 = NULL;
5314 free(s->id2);
5315 s->id2 = NULL;
5316 if (s->f && fclose(s->f) == EOF)
5317 err = got_error_from_errno("fclose");
5318 s->f = NULL;
5319 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5320 err = got_error_from_errno("fclose");
5321 s->f1 = NULL;
5322 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5323 err = got_error_from_errno("fclose");
5324 s->f2 = NULL;
5325 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5326 err = got_error_from_errno("close");
5327 s->fd1 = -1;
5328 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5329 err = got_error_from_errno("close");
5330 s->fd2 = -1;
5331 free(s->lines);
5332 s->lines = NULL;
5333 s->nlines = 0;
5334 return err;
5337 static const struct got_error *
5338 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5339 struct got_object_id *id2, const char *label1, const char *label2,
5340 int diff_context, int ignore_whitespace, int force_text_diff,
5341 struct tog_view *parent_view, struct got_repository *repo)
5343 const struct got_error *err;
5344 struct tog_diff_view_state *s = &view->state.diff;
5346 memset(s, 0, sizeof(*s));
5347 s->fd1 = -1;
5348 s->fd2 = -1;
5350 if (id1 != NULL && id2 != NULL) {
5351 int type1, type2;
5352 err = got_object_get_type(&type1, repo, id1);
5353 if (err)
5354 return err;
5355 err = got_object_get_type(&type2, repo, id2);
5356 if (err)
5357 return err;
5359 if (type1 != type2)
5360 return got_error(GOT_ERR_OBJ_TYPE);
5362 s->first_displayed_line = 1;
5363 s->last_displayed_line = view->nlines;
5364 s->selected_line = 1;
5365 s->repo = repo;
5366 s->id1 = id1;
5367 s->id2 = id2;
5368 s->label1 = label1;
5369 s->label2 = label2;
5371 if (id1) {
5372 s->id1 = got_object_id_dup(id1);
5373 if (s->id1 == NULL)
5374 return got_error_from_errno("got_object_id_dup");
5375 } else
5376 s->id1 = NULL;
5378 s->id2 = got_object_id_dup(id2);
5379 if (s->id2 == NULL) {
5380 err = got_error_from_errno("got_object_id_dup");
5381 goto done;
5384 s->f1 = got_opentemp();
5385 if (s->f1 == NULL) {
5386 err = got_error_from_errno("got_opentemp");
5387 goto done;
5390 s->f2 = got_opentemp();
5391 if (s->f2 == NULL) {
5392 err = got_error_from_errno("got_opentemp");
5393 goto done;
5396 s->fd1 = got_opentempfd();
5397 if (s->fd1 == -1) {
5398 err = got_error_from_errno("got_opentempfd");
5399 goto done;
5402 s->fd2 = got_opentempfd();
5403 if (s->fd2 == -1) {
5404 err = got_error_from_errno("got_opentempfd");
5405 goto done;
5408 s->diff_context = diff_context;
5409 s->ignore_whitespace = ignore_whitespace;
5410 s->force_text_diff = force_text_diff;
5411 s->parent_view = parent_view;
5412 s->repo = repo;
5414 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5415 int rc;
5417 rc = init_pair(GOT_DIFF_LINE_MINUS,
5418 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5419 if (rc != ERR)
5420 rc = init_pair(GOT_DIFF_LINE_PLUS,
5421 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5422 if (rc != ERR)
5423 rc = init_pair(GOT_DIFF_LINE_HUNK,
5424 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5425 if (rc != ERR)
5426 rc = init_pair(GOT_DIFF_LINE_META,
5427 get_color_value("TOG_COLOR_DIFF_META"), -1);
5428 if (rc != ERR)
5429 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5430 get_color_value("TOG_COLOR_DIFF_META"), -1);
5431 if (rc != ERR)
5432 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5433 get_color_value("TOG_COLOR_DIFF_META"), -1);
5434 if (rc != ERR)
5435 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5436 get_color_value("TOG_COLOR_DIFF_META"), -1);
5437 if (rc != ERR)
5438 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5439 get_color_value("TOG_COLOR_AUTHOR"), -1);
5440 if (rc != ERR)
5441 rc = init_pair(GOT_DIFF_LINE_DATE,
5442 get_color_value("TOG_COLOR_DATE"), -1);
5443 if (rc == ERR) {
5444 err = got_error(GOT_ERR_RANGE);
5445 goto done;
5449 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5450 view_is_splitscreen(view))
5451 show_log_view(parent_view); /* draw border */
5452 diff_view_indicate_progress(view);
5454 err = create_diff(s);
5456 view->show = show_diff_view;
5457 view->input = input_diff_view;
5458 view->reset = reset_diff_view;
5459 view->close = close_diff_view;
5460 view->search_start = search_start_diff_view;
5461 view->search_setup = search_setup_diff_view;
5462 view->search_next = search_next_view_match;
5463 done:
5464 if (err)
5465 close_diff_view(view);
5466 return err;
5469 static const struct got_error *
5470 show_diff_view(struct tog_view *view)
5472 const struct got_error *err;
5473 struct tog_diff_view_state *s = &view->state.diff;
5474 char *id_str1 = NULL, *id_str2, *header;
5475 const char *label1, *label2;
5477 if (s->id1) {
5478 err = got_object_id_str(&id_str1, s->id1);
5479 if (err)
5480 return err;
5481 label1 = s->label1 ? s->label1 : id_str1;
5482 } else
5483 label1 = "/dev/null";
5485 err = got_object_id_str(&id_str2, s->id2);
5486 if (err)
5487 return err;
5488 label2 = s->label2 ? s->label2 : id_str2;
5490 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5491 err = got_error_from_errno("asprintf");
5492 free(id_str1);
5493 free(id_str2);
5494 return err;
5496 free(id_str1);
5497 free(id_str2);
5499 err = draw_file(view, header);
5500 free(header);
5501 return err;
5504 static const struct got_error *
5505 set_selected_commit(struct tog_diff_view_state *s,
5506 struct commit_queue_entry *entry)
5508 const struct got_error *err;
5509 const struct got_object_id_queue *parent_ids;
5510 struct got_commit_object *selected_commit;
5511 struct got_object_qid *pid;
5513 free(s->id2);
5514 s->id2 = got_object_id_dup(entry->id);
5515 if (s->id2 == NULL)
5516 return got_error_from_errno("got_object_id_dup");
5518 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5519 if (err)
5520 return err;
5521 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5522 free(s->id1);
5523 pid = STAILQ_FIRST(parent_ids);
5524 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5525 got_object_commit_close(selected_commit);
5526 return NULL;
5529 static const struct got_error *
5530 reset_diff_view(struct tog_view *view)
5532 struct tog_diff_view_state *s = &view->state.diff;
5534 view->count = 0;
5535 wclear(view->window);
5536 s->first_displayed_line = 1;
5537 s->last_displayed_line = view->nlines;
5538 s->matched_line = 0;
5539 diff_view_indicate_progress(view);
5540 return create_diff(s);
5543 static void
5544 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5546 int start, i;
5548 i = start = s->first_displayed_line - 1;
5550 while (s->lines[i].type != type) {
5551 if (i == 0)
5552 i = s->nlines - 1;
5553 if (--i == start)
5554 return; /* do nothing, requested type not in file */
5557 s->selected_line = 1;
5558 s->first_displayed_line = i;
5561 static void
5562 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5564 int start, i;
5566 i = start = s->first_displayed_line + 1;
5568 while (s->lines[i].type != type) {
5569 if (i == s->nlines - 1)
5570 i = 0;
5571 if (++i == start)
5572 return; /* do nothing, requested type not in file */
5575 s->selected_line = 1;
5576 s->first_displayed_line = i;
5579 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5580 int, int, int);
5581 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5582 int, int);
5584 static const struct got_error *
5585 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5587 const struct got_error *err = NULL;
5588 struct tog_diff_view_state *s = &view->state.diff;
5589 struct tog_log_view_state *ls;
5590 struct commit_queue_entry *old_selected_entry;
5591 char *line = NULL;
5592 size_t linesize = 0;
5593 ssize_t linelen;
5594 int i, nscroll = view->nlines - 1, up = 0;
5596 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5598 switch (ch) {
5599 case '0':
5600 case '$':
5601 case KEY_RIGHT:
5602 case 'l':
5603 case KEY_LEFT:
5604 case 'h':
5605 horizontal_scroll_input(view, ch);
5606 break;
5607 case 'a':
5608 case 'w':
5609 if (ch == 'a') {
5610 s->force_text_diff = !s->force_text_diff;
5611 view->action = s->force_text_diff ?
5612 "force ASCII text enabled" :
5613 "force ASCII text disabled";
5615 else if (ch == 'w') {
5616 s->ignore_whitespace = !s->ignore_whitespace;
5617 view->action = s->ignore_whitespace ?
5618 "ignore whitespace enabled" :
5619 "ignore whitespace disabled";
5621 err = reset_diff_view(view);
5622 break;
5623 case 'g':
5624 case KEY_HOME:
5625 s->first_displayed_line = 1;
5626 view->count = 0;
5627 break;
5628 case 'G':
5629 case KEY_END:
5630 view->count = 0;
5631 if (s->eof)
5632 break;
5634 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5635 s->eof = 1;
5636 break;
5637 case 'k':
5638 case KEY_UP:
5639 case CTRL('p'):
5640 if (s->first_displayed_line > 1)
5641 s->first_displayed_line--;
5642 else
5643 view->count = 0;
5644 break;
5645 case CTRL('u'):
5646 case 'u':
5647 nscroll /= 2;
5648 /* FALL THROUGH */
5649 case KEY_PPAGE:
5650 case CTRL('b'):
5651 case 'b':
5652 if (s->first_displayed_line == 1) {
5653 view->count = 0;
5654 break;
5656 i = 0;
5657 while (i++ < nscroll && s->first_displayed_line > 1)
5658 s->first_displayed_line--;
5659 break;
5660 case 'j':
5661 case KEY_DOWN:
5662 case CTRL('n'):
5663 if (!s->eof)
5664 s->first_displayed_line++;
5665 else
5666 view->count = 0;
5667 break;
5668 case CTRL('d'):
5669 case 'd':
5670 nscroll /= 2;
5671 /* FALL THROUGH */
5672 case KEY_NPAGE:
5673 case CTRL('f'):
5674 case 'f':
5675 case ' ':
5676 if (s->eof) {
5677 view->count = 0;
5678 break;
5680 i = 0;
5681 while (!s->eof && i++ < nscroll) {
5682 linelen = getline(&line, &linesize, s->f);
5683 s->first_displayed_line++;
5684 if (linelen == -1) {
5685 if (feof(s->f)) {
5686 s->eof = 1;
5687 } else
5688 err = got_ferror(s->f, GOT_ERR_IO);
5689 break;
5692 free(line);
5693 break;
5694 case '(':
5695 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5696 break;
5697 case ')':
5698 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5699 break;
5700 case '{':
5701 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5702 break;
5703 case '}':
5704 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5705 break;
5706 case '[':
5707 if (s->diff_context > 0) {
5708 s->diff_context--;
5709 s->matched_line = 0;
5710 diff_view_indicate_progress(view);
5711 err = create_diff(s);
5712 if (s->first_displayed_line + view->nlines - 1 >
5713 s->nlines) {
5714 s->first_displayed_line = 1;
5715 s->last_displayed_line = view->nlines;
5717 } else
5718 view->count = 0;
5719 break;
5720 case ']':
5721 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5722 s->diff_context++;
5723 s->matched_line = 0;
5724 diff_view_indicate_progress(view);
5725 err = create_diff(s);
5726 } else
5727 view->count = 0;
5728 break;
5729 case '<':
5730 case ',':
5731 case 'K':
5732 up = 1;
5733 /* FALL THROUGH */
5734 case '>':
5735 case '.':
5736 case 'J':
5737 if (s->parent_view == NULL) {
5738 view->count = 0;
5739 break;
5741 s->parent_view->count = view->count;
5743 if (s->parent_view->type == TOG_VIEW_LOG) {
5744 ls = &s->parent_view->state.log;
5745 old_selected_entry = ls->selected_entry;
5747 err = input_log_view(NULL, s->parent_view,
5748 up ? KEY_UP : KEY_DOWN);
5749 if (err)
5750 break;
5751 view->count = s->parent_view->count;
5753 if (old_selected_entry == ls->selected_entry)
5754 break;
5756 err = set_selected_commit(s, ls->selected_entry);
5757 if (err)
5758 break;
5759 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5760 struct tog_blame_view_state *bs;
5761 struct got_object_id *id, *prev_id;
5763 bs = &s->parent_view->state.blame;
5764 prev_id = get_annotation_for_line(bs->blame.lines,
5765 bs->blame.nlines, bs->last_diffed_line);
5767 err = input_blame_view(&view, s->parent_view,
5768 up ? KEY_UP : KEY_DOWN);
5769 if (err)
5770 break;
5771 view->count = s->parent_view->count;
5773 if (prev_id == NULL)
5774 break;
5775 id = get_selected_commit_id(bs->blame.lines,
5776 bs->blame.nlines, bs->first_displayed_line,
5777 bs->selected_line);
5778 if (id == NULL)
5779 break;
5781 if (!got_object_id_cmp(prev_id, id))
5782 break;
5784 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5785 if (err)
5786 break;
5788 s->first_displayed_line = 1;
5789 s->last_displayed_line = view->nlines;
5790 s->matched_line = 0;
5791 view->x = 0;
5793 diff_view_indicate_progress(view);
5794 err = create_diff(s);
5795 break;
5796 default:
5797 view->count = 0;
5798 break;
5801 return err;
5804 static const struct got_error *
5805 cmd_diff(int argc, char *argv[])
5807 const struct got_error *io_err, *error;
5808 struct got_repository *repo = NULL;
5809 struct got_worktree *worktree = NULL;
5810 struct got_object_id *id1 = NULL, *id2 = NULL;
5811 char *repo_path = NULL, *cwd = NULL;
5812 char *id_str1 = NULL, *id_str2 = NULL;
5813 char *label1 = NULL, *label2 = NULL;
5814 int diff_context = 3, ignore_whitespace = 0;
5815 int ch, force_text_diff = 0;
5816 const char *errstr;
5817 struct tog_view *view;
5818 struct tog_io *tog_io = NULL;
5819 int *pack_fds = NULL;
5821 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5822 switch (ch) {
5823 case 'a':
5824 force_text_diff = 1;
5825 break;
5826 case 'C':
5827 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5828 &errstr);
5829 if (errstr != NULL)
5830 errx(1, "number of context lines is %s: %s",
5831 errstr, errstr);
5832 break;
5833 case 'r':
5834 repo_path = realpath(optarg, NULL);
5835 if (repo_path == NULL)
5836 return got_error_from_errno2("realpath",
5837 optarg);
5838 got_path_strip_trailing_slashes(repo_path);
5839 break;
5840 case 'w':
5841 ignore_whitespace = 1;
5842 break;
5843 default:
5844 usage_diff();
5845 /* NOTREACHED */
5849 argc -= optind;
5850 argv += optind;
5852 if (argc == 0) {
5853 usage_diff(); /* TODO show local worktree changes */
5854 } else if (argc == 2) {
5855 id_str1 = argv[0];
5856 id_str2 = argv[1];
5857 } else
5858 usage_diff();
5860 error = got_repo_pack_fds_open(&pack_fds);
5861 if (error)
5862 goto done;
5864 if (repo_path == NULL) {
5865 cwd = getcwd(NULL, 0);
5866 if (cwd == NULL)
5867 return got_error_from_errno("getcwd");
5868 error = got_worktree_open(&worktree, cwd);
5869 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5870 goto done;
5871 if (worktree)
5872 repo_path =
5873 strdup(got_worktree_get_repo_path(worktree));
5874 else
5875 repo_path = strdup(cwd);
5876 if (repo_path == NULL) {
5877 error = got_error_from_errno("strdup");
5878 goto done;
5882 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5883 if (error)
5884 goto done;
5886 error = init_curses(&tog_io);
5887 if (error)
5888 goto done;
5890 error = apply_unveil(got_repo_get_path(repo), NULL);
5891 if (error)
5892 goto done;
5894 error = tog_load_refs(repo, 0);
5895 if (error)
5896 goto done;
5898 error = got_repo_match_object_id(&id1, &label1, id_str1,
5899 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5900 if (error)
5901 goto done;
5903 error = got_repo_match_object_id(&id2, &label2, id_str2,
5904 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5905 if (error)
5906 goto done;
5908 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5909 if (view == NULL) {
5910 error = got_error_from_errno("view_open");
5911 goto done;
5913 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5914 ignore_whitespace, force_text_diff, NULL, repo);
5915 if (error)
5916 goto done;
5917 error = view_loop(view, tog_io);
5918 done:
5919 free(label1);
5920 free(label2);
5921 free(repo_path);
5922 free(cwd);
5923 if (repo) {
5924 const struct got_error *close_err = got_repo_close(repo);
5925 if (error == NULL)
5926 error = close_err;
5928 if (worktree)
5929 got_worktree_close(worktree);
5930 if (pack_fds) {
5931 const struct got_error *pack_err =
5932 got_repo_pack_fds_close(pack_fds);
5933 if (error == NULL)
5934 error = pack_err;
5936 if (tog_io != NULL) {
5937 io_err = tog_io_close(tog_io);
5938 if (error == NULL)
5939 error = io_err;
5941 tog_free_refs();
5942 return error;
5945 __dead static void
5946 usage_blame(void)
5948 endwin();
5949 fprintf(stderr,
5950 "usage: %s blame [-c commit] [-r repository-path] path\n",
5951 getprogname());
5952 exit(1);
5955 struct tog_blame_line {
5956 int annotated;
5957 struct got_object_id *id;
5960 static const struct got_error *
5961 draw_blame(struct tog_view *view)
5963 struct tog_blame_view_state *s = &view->state.blame;
5964 struct tog_blame *blame = &s->blame;
5965 regmatch_t *regmatch = &view->regmatch;
5966 const struct got_error *err;
5967 int lineno = 0, nprinted = 0;
5968 char *line = NULL;
5969 size_t linesize = 0;
5970 ssize_t linelen;
5971 wchar_t *wline;
5972 int width;
5973 struct tog_blame_line *blame_line;
5974 struct got_object_id *prev_id = NULL;
5975 char *id_str;
5976 struct tog_color *tc;
5978 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5979 if (err)
5980 return err;
5982 rewind(blame->f);
5983 werase(view->window);
5985 if (asprintf(&line, "commit %s", id_str) == -1) {
5986 err = got_error_from_errno("asprintf");
5987 free(id_str);
5988 return err;
5991 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5992 free(line);
5993 line = NULL;
5994 if (err)
5995 return err;
5996 if (view_needs_focus_indication(view))
5997 wstandout(view->window);
5998 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5999 if (tc)
6000 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6001 waddwstr(view->window, wline);
6002 while (width++ < view->ncols)
6003 waddch(view->window, ' ');
6004 if (tc)
6005 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6006 if (view_needs_focus_indication(view))
6007 wstandend(view->window);
6008 free(wline);
6009 wline = NULL;
6011 if (view->gline > blame->nlines)
6012 view->gline = blame->nlines;
6014 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6015 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6016 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6017 free(id_str);
6018 return got_error_from_errno("asprintf");
6020 free(id_str);
6021 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6022 free(line);
6023 line = NULL;
6024 if (err)
6025 return err;
6026 waddwstr(view->window, wline);
6027 free(wline);
6028 wline = NULL;
6029 if (width < view->ncols - 1)
6030 waddch(view->window, '\n');
6032 s->eof = 0;
6033 view->maxx = 0;
6034 while (nprinted < view->nlines - 2) {
6035 linelen = getline(&line, &linesize, blame->f);
6036 if (linelen == -1) {
6037 if (feof(blame->f)) {
6038 s->eof = 1;
6039 break;
6041 free(line);
6042 return got_ferror(blame->f, GOT_ERR_IO);
6044 if (++lineno < s->first_displayed_line)
6045 continue;
6046 if (view->gline && !gotoline(view, &lineno, &nprinted))
6047 continue;
6049 /* Set view->maxx based on full line length. */
6050 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6051 if (err) {
6052 free(line);
6053 return err;
6055 free(wline);
6056 wline = NULL;
6057 view->maxx = MAX(view->maxx, width);
6059 if (nprinted == s->selected_line - 1)
6060 wstandout(view->window);
6062 if (blame->nlines > 0) {
6063 blame_line = &blame->lines[lineno - 1];
6064 if (blame_line->annotated && prev_id &&
6065 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6066 !(nprinted == s->selected_line - 1)) {
6067 waddstr(view->window, " ");
6068 } else if (blame_line->annotated) {
6069 char *id_str;
6070 err = got_object_id_str(&id_str,
6071 blame_line->id);
6072 if (err) {
6073 free(line);
6074 return err;
6076 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6077 if (tc)
6078 wattr_on(view->window,
6079 COLOR_PAIR(tc->colorpair), NULL);
6080 wprintw(view->window, "%.8s", id_str);
6081 if (tc)
6082 wattr_off(view->window,
6083 COLOR_PAIR(tc->colorpair), NULL);
6084 free(id_str);
6085 prev_id = blame_line->id;
6086 } else {
6087 waddstr(view->window, "........");
6088 prev_id = NULL;
6090 } else {
6091 waddstr(view->window, "........");
6092 prev_id = NULL;
6095 if (nprinted == s->selected_line - 1)
6096 wstandend(view->window);
6097 waddstr(view->window, " ");
6099 if (view->ncols <= 9) {
6100 width = 9;
6101 } else if (s->first_displayed_line + nprinted ==
6102 s->matched_line &&
6103 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6104 err = add_matched_line(&width, line, view->ncols - 9, 9,
6105 view->window, view->x, regmatch);
6106 if (err) {
6107 free(line);
6108 return err;
6110 width += 9;
6111 } else {
6112 int skip;
6113 err = format_line(&wline, &width, &skip, line,
6114 view->x, view->ncols - 9, 9, 1);
6115 if (err) {
6116 free(line);
6117 return err;
6119 waddwstr(view->window, &wline[skip]);
6120 width += 9;
6121 free(wline);
6122 wline = NULL;
6125 if (width <= view->ncols - 1)
6126 waddch(view->window, '\n');
6127 if (++nprinted == 1)
6128 s->first_displayed_line = lineno;
6130 free(line);
6131 s->last_displayed_line = lineno;
6133 view_border(view);
6135 return NULL;
6138 static const struct got_error *
6139 blame_cb(void *arg, int nlines, int lineno,
6140 struct got_commit_object *commit, struct got_object_id *id)
6142 const struct got_error *err = NULL;
6143 struct tog_blame_cb_args *a = arg;
6144 struct tog_blame_line *line;
6145 int errcode;
6147 if (nlines != a->nlines ||
6148 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6149 return got_error(GOT_ERR_RANGE);
6151 errcode = pthread_mutex_lock(&tog_mutex);
6152 if (errcode)
6153 return got_error_set_errno(errcode, "pthread_mutex_lock");
6155 if (*a->quit) { /* user has quit the blame view */
6156 err = got_error(GOT_ERR_ITER_COMPLETED);
6157 goto done;
6160 if (lineno == -1)
6161 goto done; /* no change in this commit */
6163 line = &a->lines[lineno - 1];
6164 if (line->annotated)
6165 goto done;
6167 line->id = got_object_id_dup(id);
6168 if (line->id == NULL) {
6169 err = got_error_from_errno("got_object_id_dup");
6170 goto done;
6172 line->annotated = 1;
6173 done:
6174 errcode = pthread_mutex_unlock(&tog_mutex);
6175 if (errcode)
6176 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6177 return err;
6180 static void *
6181 blame_thread(void *arg)
6183 const struct got_error *err, *close_err;
6184 struct tog_blame_thread_args *ta = arg;
6185 struct tog_blame_cb_args *a = ta->cb_args;
6186 int errcode, fd1 = -1, fd2 = -1;
6187 FILE *f1 = NULL, *f2 = NULL;
6189 fd1 = got_opentempfd();
6190 if (fd1 == -1)
6191 return (void *)got_error_from_errno("got_opentempfd");
6193 fd2 = got_opentempfd();
6194 if (fd2 == -1) {
6195 err = got_error_from_errno("got_opentempfd");
6196 goto done;
6199 f1 = got_opentemp();
6200 if (f1 == NULL) {
6201 err = (void *)got_error_from_errno("got_opentemp");
6202 goto done;
6204 f2 = got_opentemp();
6205 if (f2 == NULL) {
6206 err = (void *)got_error_from_errno("got_opentemp");
6207 goto done;
6210 err = block_signals_used_by_main_thread();
6211 if (err)
6212 goto done;
6214 err = got_blame(ta->path, a->commit_id, ta->repo,
6215 tog_diff_algo, blame_cb, ta->cb_args,
6216 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6217 if (err && err->code == GOT_ERR_CANCELLED)
6218 err = NULL;
6220 errcode = pthread_mutex_lock(&tog_mutex);
6221 if (errcode) {
6222 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6223 goto done;
6226 close_err = got_repo_close(ta->repo);
6227 if (err == NULL)
6228 err = close_err;
6229 ta->repo = NULL;
6230 *ta->complete = 1;
6232 errcode = pthread_mutex_unlock(&tog_mutex);
6233 if (errcode && err == NULL)
6234 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6236 done:
6237 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6238 err = got_error_from_errno("close");
6239 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6240 err = got_error_from_errno("close");
6241 if (f1 && fclose(f1) == EOF && err == NULL)
6242 err = got_error_from_errno("fclose");
6243 if (f2 && fclose(f2) == EOF && err == NULL)
6244 err = got_error_from_errno("fclose");
6246 return (void *)err;
6249 static struct got_object_id *
6250 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6251 int first_displayed_line, int selected_line)
6253 struct tog_blame_line *line;
6255 if (nlines <= 0)
6256 return NULL;
6258 line = &lines[first_displayed_line - 1 + selected_line - 1];
6259 if (!line->annotated)
6260 return NULL;
6262 return line->id;
6265 static struct got_object_id *
6266 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6267 int lineno)
6269 struct tog_blame_line *line;
6271 if (nlines <= 0 || lineno >= nlines)
6272 return NULL;
6274 line = &lines[lineno - 1];
6275 if (!line->annotated)
6276 return NULL;
6278 return line->id;
6281 static const struct got_error *
6282 stop_blame(struct tog_blame *blame)
6284 const struct got_error *err = NULL;
6285 int i;
6287 if (blame->thread) {
6288 int errcode;
6289 errcode = pthread_mutex_unlock(&tog_mutex);
6290 if (errcode)
6291 return got_error_set_errno(errcode,
6292 "pthread_mutex_unlock");
6293 errcode = pthread_join(blame->thread, (void **)&err);
6294 if (errcode)
6295 return got_error_set_errno(errcode, "pthread_join");
6296 errcode = pthread_mutex_lock(&tog_mutex);
6297 if (errcode)
6298 return got_error_set_errno(errcode,
6299 "pthread_mutex_lock");
6300 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6301 err = NULL;
6302 blame->thread = NULL;
6304 if (blame->thread_args.repo) {
6305 const struct got_error *close_err;
6306 close_err = got_repo_close(blame->thread_args.repo);
6307 if (err == NULL)
6308 err = close_err;
6309 blame->thread_args.repo = NULL;
6311 if (blame->f) {
6312 if (fclose(blame->f) == EOF && err == NULL)
6313 err = got_error_from_errno("fclose");
6314 blame->f = NULL;
6316 if (blame->lines) {
6317 for (i = 0; i < blame->nlines; i++)
6318 free(blame->lines[i].id);
6319 free(blame->lines);
6320 blame->lines = NULL;
6322 free(blame->cb_args.commit_id);
6323 blame->cb_args.commit_id = NULL;
6324 if (blame->pack_fds) {
6325 const struct got_error *pack_err =
6326 got_repo_pack_fds_close(blame->pack_fds);
6327 if (err == NULL)
6328 err = pack_err;
6329 blame->pack_fds = NULL;
6331 return err;
6334 static const struct got_error *
6335 cancel_blame_view(void *arg)
6337 const struct got_error *err = NULL;
6338 int *done = arg;
6339 int errcode;
6341 errcode = pthread_mutex_lock(&tog_mutex);
6342 if (errcode)
6343 return got_error_set_errno(errcode,
6344 "pthread_mutex_unlock");
6346 if (*done)
6347 err = got_error(GOT_ERR_CANCELLED);
6349 errcode = pthread_mutex_unlock(&tog_mutex);
6350 if (errcode)
6351 return got_error_set_errno(errcode,
6352 "pthread_mutex_lock");
6354 return err;
6357 static const struct got_error *
6358 run_blame(struct tog_view *view)
6360 struct tog_blame_view_state *s = &view->state.blame;
6361 struct tog_blame *blame = &s->blame;
6362 const struct got_error *err = NULL;
6363 struct got_commit_object *commit = NULL;
6364 struct got_blob_object *blob = NULL;
6365 struct got_repository *thread_repo = NULL;
6366 struct got_object_id *obj_id = NULL;
6367 int obj_type, fd = -1;
6368 int *pack_fds = NULL;
6370 err = got_object_open_as_commit(&commit, s->repo,
6371 &s->blamed_commit->id);
6372 if (err)
6373 return err;
6375 fd = got_opentempfd();
6376 if (fd == -1) {
6377 err = got_error_from_errno("got_opentempfd");
6378 goto done;
6381 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6382 if (err)
6383 goto done;
6385 err = got_object_get_type(&obj_type, s->repo, obj_id);
6386 if (err)
6387 goto done;
6389 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6390 err = got_error(GOT_ERR_OBJ_TYPE);
6391 goto done;
6394 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6395 if (err)
6396 goto done;
6397 blame->f = got_opentemp();
6398 if (blame->f == NULL) {
6399 err = got_error_from_errno("got_opentemp");
6400 goto done;
6402 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6403 &blame->line_offsets, blame->f, blob);
6404 if (err)
6405 goto done;
6406 if (blame->nlines == 0) {
6407 s->blame_complete = 1;
6408 goto done;
6411 /* Don't include \n at EOF in the blame line count. */
6412 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6413 blame->nlines--;
6415 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6416 if (blame->lines == NULL) {
6417 err = got_error_from_errno("calloc");
6418 goto done;
6421 err = got_repo_pack_fds_open(&pack_fds);
6422 if (err)
6423 goto done;
6424 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6425 pack_fds);
6426 if (err)
6427 goto done;
6429 blame->pack_fds = pack_fds;
6430 blame->cb_args.view = view;
6431 blame->cb_args.lines = blame->lines;
6432 blame->cb_args.nlines = blame->nlines;
6433 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6434 if (blame->cb_args.commit_id == NULL) {
6435 err = got_error_from_errno("got_object_id_dup");
6436 goto done;
6438 blame->cb_args.quit = &s->done;
6440 blame->thread_args.path = s->path;
6441 blame->thread_args.repo = thread_repo;
6442 blame->thread_args.cb_args = &blame->cb_args;
6443 blame->thread_args.complete = &s->blame_complete;
6444 blame->thread_args.cancel_cb = cancel_blame_view;
6445 blame->thread_args.cancel_arg = &s->done;
6446 s->blame_complete = 0;
6448 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6449 s->first_displayed_line = 1;
6450 s->last_displayed_line = view->nlines;
6451 s->selected_line = 1;
6453 s->matched_line = 0;
6455 done:
6456 if (commit)
6457 got_object_commit_close(commit);
6458 if (fd != -1 && close(fd) == -1 && err == NULL)
6459 err = got_error_from_errno("close");
6460 if (blob)
6461 got_object_blob_close(blob);
6462 free(obj_id);
6463 if (err)
6464 stop_blame(blame);
6465 return err;
6468 static const struct got_error *
6469 open_blame_view(struct tog_view *view, char *path,
6470 struct got_object_id *commit_id, struct got_repository *repo)
6472 const struct got_error *err = NULL;
6473 struct tog_blame_view_state *s = &view->state.blame;
6475 STAILQ_INIT(&s->blamed_commits);
6477 s->path = strdup(path);
6478 if (s->path == NULL)
6479 return got_error_from_errno("strdup");
6481 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6482 if (err) {
6483 free(s->path);
6484 return err;
6487 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6488 s->first_displayed_line = 1;
6489 s->last_displayed_line = view->nlines;
6490 s->selected_line = 1;
6491 s->blame_complete = 0;
6492 s->repo = repo;
6493 s->commit_id = commit_id;
6494 memset(&s->blame, 0, sizeof(s->blame));
6496 STAILQ_INIT(&s->colors);
6497 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6498 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6499 get_color_value("TOG_COLOR_COMMIT"));
6500 if (err)
6501 return err;
6504 view->show = show_blame_view;
6505 view->input = input_blame_view;
6506 view->reset = reset_blame_view;
6507 view->close = close_blame_view;
6508 view->search_start = search_start_blame_view;
6509 view->search_setup = search_setup_blame_view;
6510 view->search_next = search_next_view_match;
6512 return run_blame(view);
6515 static const struct got_error *
6516 close_blame_view(struct tog_view *view)
6518 const struct got_error *err = NULL;
6519 struct tog_blame_view_state *s = &view->state.blame;
6521 if (s->blame.thread)
6522 err = stop_blame(&s->blame);
6524 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6525 struct got_object_qid *blamed_commit;
6526 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6527 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6528 got_object_qid_free(blamed_commit);
6531 free(s->path);
6532 free_colors(&s->colors);
6533 return err;
6536 static const struct got_error *
6537 search_start_blame_view(struct tog_view *view)
6539 struct tog_blame_view_state *s = &view->state.blame;
6541 s->matched_line = 0;
6542 return NULL;
6545 static void
6546 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6547 size_t *nlines, int **first, int **last, int **match, int **selected)
6549 struct tog_blame_view_state *s = &view->state.blame;
6551 *f = s->blame.f;
6552 *nlines = s->blame.nlines;
6553 *line_offsets = s->blame.line_offsets;
6554 *match = &s->matched_line;
6555 *first = &s->first_displayed_line;
6556 *last = &s->last_displayed_line;
6557 *selected = &s->selected_line;
6560 static const struct got_error *
6561 show_blame_view(struct tog_view *view)
6563 const struct got_error *err = NULL;
6564 struct tog_blame_view_state *s = &view->state.blame;
6565 int errcode;
6567 if (s->blame.thread == NULL && !s->blame_complete) {
6568 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6569 &s->blame.thread_args);
6570 if (errcode)
6571 return got_error_set_errno(errcode, "pthread_create");
6573 halfdelay(1); /* fast refresh while annotating */
6576 if (s->blame_complete)
6577 halfdelay(10); /* disable fast refresh */
6579 err = draw_blame(view);
6581 view_border(view);
6582 return err;
6585 static const struct got_error *
6586 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6587 struct got_repository *repo, struct got_object_id *id)
6589 struct tog_view *log_view;
6590 const struct got_error *err = NULL;
6592 *new_view = NULL;
6594 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6595 if (log_view == NULL)
6596 return got_error_from_errno("view_open");
6598 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6599 if (err)
6600 view_close(log_view);
6601 else
6602 *new_view = log_view;
6604 return err;
6607 static const struct got_error *
6608 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6610 const struct got_error *err = NULL, *thread_err = NULL;
6611 struct tog_view *diff_view;
6612 struct tog_blame_view_state *s = &view->state.blame;
6613 int eos, nscroll, begin_y = 0, begin_x = 0;
6615 eos = nscroll = view->nlines - 2;
6616 if (view_is_hsplit_top(view))
6617 --eos; /* border */
6619 switch (ch) {
6620 case '0':
6621 case '$':
6622 case KEY_RIGHT:
6623 case 'l':
6624 case KEY_LEFT:
6625 case 'h':
6626 horizontal_scroll_input(view, ch);
6627 break;
6628 case 'q':
6629 s->done = 1;
6630 break;
6631 case 'g':
6632 case KEY_HOME:
6633 s->selected_line = 1;
6634 s->first_displayed_line = 1;
6635 view->count = 0;
6636 break;
6637 case 'G':
6638 case KEY_END:
6639 if (s->blame.nlines < eos) {
6640 s->selected_line = s->blame.nlines;
6641 s->first_displayed_line = 1;
6642 } else {
6643 s->selected_line = eos;
6644 s->first_displayed_line = s->blame.nlines - (eos - 1);
6646 view->count = 0;
6647 break;
6648 case 'k':
6649 case KEY_UP:
6650 case CTRL('p'):
6651 if (s->selected_line > 1)
6652 s->selected_line--;
6653 else if (s->selected_line == 1 &&
6654 s->first_displayed_line > 1)
6655 s->first_displayed_line--;
6656 else
6657 view->count = 0;
6658 break;
6659 case CTRL('u'):
6660 case 'u':
6661 nscroll /= 2;
6662 /* FALL THROUGH */
6663 case KEY_PPAGE:
6664 case CTRL('b'):
6665 case 'b':
6666 if (s->first_displayed_line == 1) {
6667 if (view->count > 1)
6668 nscroll += nscroll;
6669 s->selected_line = MAX(1, s->selected_line - nscroll);
6670 view->count = 0;
6671 break;
6673 if (s->first_displayed_line > nscroll)
6674 s->first_displayed_line -= nscroll;
6675 else
6676 s->first_displayed_line = 1;
6677 break;
6678 case 'j':
6679 case KEY_DOWN:
6680 case CTRL('n'):
6681 if (s->selected_line < eos && s->first_displayed_line +
6682 s->selected_line <= s->blame.nlines)
6683 s->selected_line++;
6684 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6685 s->first_displayed_line++;
6686 else
6687 view->count = 0;
6688 break;
6689 case 'c':
6690 case 'p': {
6691 struct got_object_id *id = NULL;
6693 view->count = 0;
6694 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6695 s->first_displayed_line, s->selected_line);
6696 if (id == NULL)
6697 break;
6698 if (ch == 'p') {
6699 struct got_commit_object *commit, *pcommit;
6700 struct got_object_qid *pid;
6701 struct got_object_id *blob_id = NULL;
6702 int obj_type;
6703 err = got_object_open_as_commit(&commit,
6704 s->repo, id);
6705 if (err)
6706 break;
6707 pid = STAILQ_FIRST(
6708 got_object_commit_get_parent_ids(commit));
6709 if (pid == NULL) {
6710 got_object_commit_close(commit);
6711 break;
6713 /* Check if path history ends here. */
6714 err = got_object_open_as_commit(&pcommit,
6715 s->repo, &pid->id);
6716 if (err)
6717 break;
6718 err = got_object_id_by_path(&blob_id, s->repo,
6719 pcommit, s->path);
6720 got_object_commit_close(pcommit);
6721 if (err) {
6722 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6723 err = NULL;
6724 got_object_commit_close(commit);
6725 break;
6727 err = got_object_get_type(&obj_type, s->repo,
6728 blob_id);
6729 free(blob_id);
6730 /* Can't blame non-blob type objects. */
6731 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6732 got_object_commit_close(commit);
6733 break;
6735 err = got_object_qid_alloc(&s->blamed_commit,
6736 &pid->id);
6737 got_object_commit_close(commit);
6738 } else {
6739 if (got_object_id_cmp(id,
6740 &s->blamed_commit->id) == 0)
6741 break;
6742 err = got_object_qid_alloc(&s->blamed_commit,
6743 id);
6745 if (err)
6746 break;
6747 s->done = 1;
6748 thread_err = stop_blame(&s->blame);
6749 s->done = 0;
6750 if (thread_err)
6751 break;
6752 STAILQ_INSERT_HEAD(&s->blamed_commits,
6753 s->blamed_commit, entry);
6754 err = run_blame(view);
6755 if (err)
6756 break;
6757 break;
6759 case 'C': {
6760 struct got_object_qid *first;
6762 view->count = 0;
6763 first = STAILQ_FIRST(&s->blamed_commits);
6764 if (!got_object_id_cmp(&first->id, s->commit_id))
6765 break;
6766 s->done = 1;
6767 thread_err = stop_blame(&s->blame);
6768 s->done = 0;
6769 if (thread_err)
6770 break;
6771 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6772 got_object_qid_free(s->blamed_commit);
6773 s->blamed_commit =
6774 STAILQ_FIRST(&s->blamed_commits);
6775 err = run_blame(view);
6776 if (err)
6777 break;
6778 break;
6780 case 'L':
6781 view->count = 0;
6782 s->id_to_log = get_selected_commit_id(s->blame.lines,
6783 s->blame.nlines, s->first_displayed_line, s->selected_line);
6784 if (s->id_to_log)
6785 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6786 break;
6787 case KEY_ENTER:
6788 case '\r': {
6789 struct got_object_id *id = NULL;
6790 struct got_object_qid *pid;
6791 struct got_commit_object *commit = NULL;
6793 view->count = 0;
6794 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6795 s->first_displayed_line, s->selected_line);
6796 if (id == NULL)
6797 break;
6798 err = got_object_open_as_commit(&commit, s->repo, id);
6799 if (err)
6800 break;
6801 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6802 if (*new_view) {
6803 /* traversed from diff view, release diff resources */
6804 err = close_diff_view(*new_view);
6805 if (err)
6806 break;
6807 diff_view = *new_view;
6808 } else {
6809 if (view_is_parent_view(view))
6810 view_get_split(view, &begin_y, &begin_x);
6812 diff_view = view_open(0, 0, begin_y, begin_x,
6813 TOG_VIEW_DIFF);
6814 if (diff_view == NULL) {
6815 got_object_commit_close(commit);
6816 err = got_error_from_errno("view_open");
6817 break;
6820 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6821 id, NULL, NULL, 3, 0, 0, view, s->repo);
6822 got_object_commit_close(commit);
6823 if (err) {
6824 view_close(diff_view);
6825 break;
6827 s->last_diffed_line = s->first_displayed_line - 1 +
6828 s->selected_line;
6829 if (*new_view)
6830 break; /* still open from active diff view */
6831 if (view_is_parent_view(view) &&
6832 view->mode == TOG_VIEW_SPLIT_HRZN) {
6833 err = view_init_hsplit(view, begin_y);
6834 if (err)
6835 break;
6838 view->focussed = 0;
6839 diff_view->focussed = 1;
6840 diff_view->mode = view->mode;
6841 diff_view->nlines = view->lines - begin_y;
6842 if (view_is_parent_view(view)) {
6843 view_transfer_size(diff_view, view);
6844 err = view_close_child(view);
6845 if (err)
6846 break;
6847 err = view_set_child(view, diff_view);
6848 if (err)
6849 break;
6850 view->focus_child = 1;
6851 } else
6852 *new_view = diff_view;
6853 if (err)
6854 break;
6855 break;
6857 case CTRL('d'):
6858 case 'd':
6859 nscroll /= 2;
6860 /* FALL THROUGH */
6861 case KEY_NPAGE:
6862 case CTRL('f'):
6863 case 'f':
6864 case ' ':
6865 if (s->last_displayed_line >= s->blame.nlines &&
6866 s->selected_line >= MIN(s->blame.nlines,
6867 view->nlines - 2)) {
6868 view->count = 0;
6869 break;
6871 if (s->last_displayed_line >= s->blame.nlines &&
6872 s->selected_line < view->nlines - 2) {
6873 s->selected_line +=
6874 MIN(nscroll, s->last_displayed_line -
6875 s->first_displayed_line - s->selected_line + 1);
6877 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6878 s->first_displayed_line += nscroll;
6879 else
6880 s->first_displayed_line =
6881 s->blame.nlines - (view->nlines - 3);
6882 break;
6883 case KEY_RESIZE:
6884 if (s->selected_line > view->nlines - 2) {
6885 s->selected_line = MIN(s->blame.nlines,
6886 view->nlines - 2);
6888 break;
6889 default:
6890 view->count = 0;
6891 break;
6893 return thread_err ? thread_err : err;
6896 static const struct got_error *
6897 reset_blame_view(struct tog_view *view)
6899 const struct got_error *err;
6900 struct tog_blame_view_state *s = &view->state.blame;
6902 view->count = 0;
6903 s->done = 1;
6904 err = stop_blame(&s->blame);
6905 s->done = 0;
6906 if (err)
6907 return err;
6908 return run_blame(view);
6911 static const struct got_error *
6912 cmd_blame(int argc, char *argv[])
6914 const struct got_error *io_err, *error;
6915 struct got_repository *repo = NULL;
6916 struct got_worktree *worktree = NULL;
6917 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6918 char *link_target = NULL;
6919 struct got_object_id *commit_id = NULL;
6920 struct got_commit_object *commit = NULL;
6921 char *commit_id_str = NULL;
6922 int ch;
6923 struct tog_view *view;
6924 struct tog_io *tog_io = NULL;
6925 int *pack_fds = NULL;
6927 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6928 switch (ch) {
6929 case 'c':
6930 commit_id_str = optarg;
6931 break;
6932 case 'r':
6933 repo_path = realpath(optarg, NULL);
6934 if (repo_path == NULL)
6935 return got_error_from_errno2("realpath",
6936 optarg);
6937 break;
6938 default:
6939 usage_blame();
6940 /* NOTREACHED */
6944 argc -= optind;
6945 argv += optind;
6947 if (argc != 1)
6948 usage_blame();
6950 error = got_repo_pack_fds_open(&pack_fds);
6951 if (error != NULL)
6952 goto done;
6954 if (repo_path == NULL) {
6955 cwd = getcwd(NULL, 0);
6956 if (cwd == NULL)
6957 return got_error_from_errno("getcwd");
6958 error = got_worktree_open(&worktree, cwd);
6959 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6960 goto done;
6961 if (worktree)
6962 repo_path =
6963 strdup(got_worktree_get_repo_path(worktree));
6964 else
6965 repo_path = strdup(cwd);
6966 if (repo_path == NULL) {
6967 error = got_error_from_errno("strdup");
6968 goto done;
6972 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6973 if (error != NULL)
6974 goto done;
6976 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6977 worktree);
6978 if (error)
6979 goto done;
6981 error = init_curses(&tog_io);
6982 if (error)
6983 goto done;
6985 error = apply_unveil(got_repo_get_path(repo), NULL);
6986 if (error)
6987 goto done;
6989 error = tog_load_refs(repo, 0);
6990 if (error)
6991 goto done;
6993 if (commit_id_str == NULL) {
6994 struct got_reference *head_ref;
6995 error = got_ref_open(&head_ref, repo, worktree ?
6996 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6997 if (error != NULL)
6998 goto done;
6999 error = got_ref_resolve(&commit_id, repo, head_ref);
7000 got_ref_close(head_ref);
7001 } else {
7002 error = got_repo_match_object_id(&commit_id, NULL,
7003 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7005 if (error != NULL)
7006 goto done;
7008 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7009 if (view == NULL) {
7010 error = got_error_from_errno("view_open");
7011 goto done;
7014 error = got_object_open_as_commit(&commit, repo, commit_id);
7015 if (error)
7016 goto done;
7018 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7019 commit, repo);
7020 if (error)
7021 goto done;
7023 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7024 commit_id, repo);
7025 if (error)
7026 goto done;
7027 if (worktree) {
7028 /* Release work tree lock. */
7029 got_worktree_close(worktree);
7030 worktree = NULL;
7032 error = view_loop(view, tog_io);
7033 done:
7034 free(repo_path);
7035 free(in_repo_path);
7036 free(link_target);
7037 free(cwd);
7038 free(commit_id);
7039 if (commit)
7040 got_object_commit_close(commit);
7041 if (worktree)
7042 got_worktree_close(worktree);
7043 if (repo) {
7044 const struct got_error *close_err = got_repo_close(repo);
7045 if (error == NULL)
7046 error = close_err;
7048 if (pack_fds) {
7049 const struct got_error *pack_err =
7050 got_repo_pack_fds_close(pack_fds);
7051 if (error == NULL)
7052 error = pack_err;
7054 if (tog_io != NULL) {
7055 io_err = tog_io_close(tog_io);
7056 if (error == NULL)
7057 error = io_err;
7059 tog_free_refs();
7060 return error;
7063 static const struct got_error *
7064 draw_tree_entries(struct tog_view *view, const char *parent_path)
7066 struct tog_tree_view_state *s = &view->state.tree;
7067 const struct got_error *err = NULL;
7068 struct got_tree_entry *te;
7069 wchar_t *wline;
7070 char *index = NULL;
7071 struct tog_color *tc;
7072 int width, n, nentries, scrollx, i = 1;
7073 int limit = view->nlines;
7075 s->ndisplayed = 0;
7076 if (view_is_hsplit_top(view))
7077 --limit; /* border */
7079 werase(view->window);
7081 if (limit == 0)
7082 return NULL;
7084 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7085 0, 0);
7086 if (err)
7087 return err;
7088 if (view_needs_focus_indication(view))
7089 wstandout(view->window);
7090 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7091 if (tc)
7092 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7093 waddwstr(view->window, wline);
7094 free(wline);
7095 wline = NULL;
7096 while (width++ < view->ncols)
7097 waddch(view->window, ' ');
7098 if (tc)
7099 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7100 if (view_needs_focus_indication(view))
7101 wstandend(view->window);
7102 if (--limit <= 0)
7103 return NULL;
7105 i += s->selected;
7106 if (s->first_displayed_entry) {
7107 i += got_tree_entry_get_index(s->first_displayed_entry);
7108 if (s->tree != s->root)
7109 ++i; /* account for ".." entry */
7111 nentries = got_object_tree_get_nentries(s->tree);
7112 if (asprintf(&index, "[%d/%d] %s",
7113 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7114 return got_error_from_errno("asprintf");
7115 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7116 free(index);
7117 if (err)
7118 return err;
7119 waddwstr(view->window, wline);
7120 free(wline);
7121 wline = NULL;
7122 if (width < view->ncols - 1)
7123 waddch(view->window, '\n');
7124 if (--limit <= 0)
7125 return NULL;
7126 waddch(view->window, '\n');
7127 if (--limit <= 0)
7128 return NULL;
7130 if (s->first_displayed_entry == NULL) {
7131 te = got_object_tree_get_first_entry(s->tree);
7132 if (s->selected == 0) {
7133 if (view->focussed)
7134 wstandout(view->window);
7135 s->selected_entry = NULL;
7137 waddstr(view->window, " ..\n"); /* parent directory */
7138 if (s->selected == 0 && view->focussed)
7139 wstandend(view->window);
7140 s->ndisplayed++;
7141 if (--limit <= 0)
7142 return NULL;
7143 n = 1;
7144 } else {
7145 n = 0;
7146 te = s->first_displayed_entry;
7149 view->maxx = 0;
7150 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7151 char *line = NULL, *id_str = NULL, *link_target = NULL;
7152 const char *modestr = "";
7153 mode_t mode;
7155 te = got_object_tree_get_entry(s->tree, i);
7156 mode = got_tree_entry_get_mode(te);
7158 if (s->show_ids) {
7159 err = got_object_id_str(&id_str,
7160 got_tree_entry_get_id(te));
7161 if (err)
7162 return got_error_from_errno(
7163 "got_object_id_str");
7165 if (got_object_tree_entry_is_submodule(te))
7166 modestr = "$";
7167 else if (S_ISLNK(mode)) {
7168 int i;
7170 err = got_tree_entry_get_symlink_target(&link_target,
7171 te, s->repo);
7172 if (err) {
7173 free(id_str);
7174 return err;
7176 for (i = 0; i < strlen(link_target); i++) {
7177 if (!isprint((unsigned char)link_target[i]))
7178 link_target[i] = '?';
7180 modestr = "@";
7182 else if (S_ISDIR(mode))
7183 modestr = "/";
7184 else if (mode & S_IXUSR)
7185 modestr = "*";
7186 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7187 got_tree_entry_get_name(te), modestr,
7188 link_target ? " -> ": "",
7189 link_target ? link_target : "") == -1) {
7190 free(id_str);
7191 free(link_target);
7192 return got_error_from_errno("asprintf");
7194 free(id_str);
7195 free(link_target);
7197 /* use full line width to determine view->maxx */
7198 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7199 if (err) {
7200 free(line);
7201 break;
7203 view->maxx = MAX(view->maxx, width);
7204 free(wline);
7205 wline = NULL;
7207 err = format_line(&wline, &width, &scrollx, line, view->x,
7208 view->ncols, 0, 0);
7209 if (err) {
7210 free(line);
7211 break;
7213 if (n == s->selected) {
7214 if (view->focussed)
7215 wstandout(view->window);
7216 s->selected_entry = te;
7218 tc = match_color(&s->colors, line);
7219 if (tc)
7220 wattr_on(view->window,
7221 COLOR_PAIR(tc->colorpair), NULL);
7222 waddwstr(view->window, &wline[scrollx]);
7223 if (tc)
7224 wattr_off(view->window,
7225 COLOR_PAIR(tc->colorpair), NULL);
7226 if (width < view->ncols)
7227 waddch(view->window, '\n');
7228 if (n == s->selected && view->focussed)
7229 wstandend(view->window);
7230 free(line);
7231 free(wline);
7232 wline = NULL;
7233 n++;
7234 s->ndisplayed++;
7235 s->last_displayed_entry = te;
7236 if (--limit <= 0)
7237 break;
7240 return err;
7243 static void
7244 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7246 struct got_tree_entry *te;
7247 int isroot = s->tree == s->root;
7248 int i = 0;
7250 if (s->first_displayed_entry == NULL)
7251 return;
7253 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7254 while (i++ < maxscroll) {
7255 if (te == NULL) {
7256 if (!isroot)
7257 s->first_displayed_entry = NULL;
7258 break;
7260 s->first_displayed_entry = te;
7261 te = got_tree_entry_get_prev(s->tree, te);
7265 static const struct got_error *
7266 tree_scroll_down(struct tog_view *view, int maxscroll)
7268 struct tog_tree_view_state *s = &view->state.tree;
7269 struct got_tree_entry *next, *last;
7270 int n = 0;
7272 if (s->first_displayed_entry)
7273 next = got_tree_entry_get_next(s->tree,
7274 s->first_displayed_entry);
7275 else
7276 next = got_object_tree_get_first_entry(s->tree);
7278 last = s->last_displayed_entry;
7279 while (next && n++ < maxscroll) {
7280 if (last) {
7281 s->last_displayed_entry = last;
7282 last = got_tree_entry_get_next(s->tree, last);
7284 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7285 s->first_displayed_entry = next;
7286 next = got_tree_entry_get_next(s->tree, next);
7290 return NULL;
7293 static const struct got_error *
7294 tree_entry_path(char **path, struct tog_parent_trees *parents,
7295 struct got_tree_entry *te)
7297 const struct got_error *err = NULL;
7298 struct tog_parent_tree *pt;
7299 size_t len = 2; /* for leading slash and NUL */
7301 TAILQ_FOREACH(pt, parents, entry)
7302 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7303 + 1 /* slash */;
7304 if (te)
7305 len += strlen(got_tree_entry_get_name(te));
7307 *path = calloc(1, len);
7308 if (path == NULL)
7309 return got_error_from_errno("calloc");
7311 (*path)[0] = '/';
7312 pt = TAILQ_LAST(parents, tog_parent_trees);
7313 while (pt) {
7314 const char *name = got_tree_entry_get_name(pt->selected_entry);
7315 if (strlcat(*path, name, len) >= len) {
7316 err = got_error(GOT_ERR_NO_SPACE);
7317 goto done;
7319 if (strlcat(*path, "/", len) >= len) {
7320 err = got_error(GOT_ERR_NO_SPACE);
7321 goto done;
7323 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7325 if (te) {
7326 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7327 err = got_error(GOT_ERR_NO_SPACE);
7328 goto done;
7331 done:
7332 if (err) {
7333 free(*path);
7334 *path = NULL;
7336 return err;
7339 static const struct got_error *
7340 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7341 struct got_tree_entry *te, struct tog_parent_trees *parents,
7342 struct got_object_id *commit_id, struct got_repository *repo)
7344 const struct got_error *err = NULL;
7345 char *path;
7346 struct tog_view *blame_view;
7348 *new_view = NULL;
7350 err = tree_entry_path(&path, parents, te);
7351 if (err)
7352 return err;
7354 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7355 if (blame_view == NULL) {
7356 err = got_error_from_errno("view_open");
7357 goto done;
7360 err = open_blame_view(blame_view, path, commit_id, repo);
7361 if (err) {
7362 if (err->code == GOT_ERR_CANCELLED)
7363 err = NULL;
7364 view_close(blame_view);
7365 } else
7366 *new_view = blame_view;
7367 done:
7368 free(path);
7369 return err;
7372 static const struct got_error *
7373 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7374 struct tog_tree_view_state *s)
7376 struct tog_view *log_view;
7377 const struct got_error *err = NULL;
7378 char *path;
7380 *new_view = NULL;
7382 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7383 if (log_view == NULL)
7384 return got_error_from_errno("view_open");
7386 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7387 if (err)
7388 return err;
7390 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7391 path, 0);
7392 if (err)
7393 view_close(log_view);
7394 else
7395 *new_view = log_view;
7396 free(path);
7397 return err;
7400 static const struct got_error *
7401 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7402 const char *head_ref_name, struct got_repository *repo)
7404 const struct got_error *err = NULL;
7405 char *commit_id_str = NULL;
7406 struct tog_tree_view_state *s = &view->state.tree;
7407 struct got_commit_object *commit = NULL;
7409 TAILQ_INIT(&s->parents);
7410 STAILQ_INIT(&s->colors);
7412 s->commit_id = got_object_id_dup(commit_id);
7413 if (s->commit_id == NULL)
7414 return got_error_from_errno("got_object_id_dup");
7416 err = got_object_open_as_commit(&commit, repo, commit_id);
7417 if (err)
7418 goto done;
7421 * The root is opened here and will be closed when the view is closed.
7422 * Any visited subtrees and their path-wise parents are opened and
7423 * closed on demand.
7425 err = got_object_open_as_tree(&s->root, repo,
7426 got_object_commit_get_tree_id(commit));
7427 if (err)
7428 goto done;
7429 s->tree = s->root;
7431 err = got_object_id_str(&commit_id_str, commit_id);
7432 if (err != NULL)
7433 goto done;
7435 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7436 err = got_error_from_errno("asprintf");
7437 goto done;
7440 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7441 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7442 if (head_ref_name) {
7443 s->head_ref_name = strdup(head_ref_name);
7444 if (s->head_ref_name == NULL) {
7445 err = got_error_from_errno("strdup");
7446 goto done;
7449 s->repo = repo;
7451 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7452 err = add_color(&s->colors, "\\$$",
7453 TOG_COLOR_TREE_SUBMODULE,
7454 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7455 if (err)
7456 goto done;
7457 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7458 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7459 if (err)
7460 goto done;
7461 err = add_color(&s->colors, "/$",
7462 TOG_COLOR_TREE_DIRECTORY,
7463 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7464 if (err)
7465 goto done;
7467 err = add_color(&s->colors, "\\*$",
7468 TOG_COLOR_TREE_EXECUTABLE,
7469 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7470 if (err)
7471 goto done;
7473 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7474 get_color_value("TOG_COLOR_COMMIT"));
7475 if (err)
7476 goto done;
7479 view->show = show_tree_view;
7480 view->input = input_tree_view;
7481 view->close = close_tree_view;
7482 view->search_start = search_start_tree_view;
7483 view->search_next = search_next_tree_view;
7484 done:
7485 free(commit_id_str);
7486 if (commit)
7487 got_object_commit_close(commit);
7488 if (err)
7489 close_tree_view(view);
7490 return err;
7493 static const struct got_error *
7494 close_tree_view(struct tog_view *view)
7496 struct tog_tree_view_state *s = &view->state.tree;
7498 free_colors(&s->colors);
7499 free(s->tree_label);
7500 s->tree_label = NULL;
7501 free(s->commit_id);
7502 s->commit_id = NULL;
7503 free(s->head_ref_name);
7504 s->head_ref_name = NULL;
7505 while (!TAILQ_EMPTY(&s->parents)) {
7506 struct tog_parent_tree *parent;
7507 parent = TAILQ_FIRST(&s->parents);
7508 TAILQ_REMOVE(&s->parents, parent, entry);
7509 if (parent->tree != s->root)
7510 got_object_tree_close(parent->tree);
7511 free(parent);
7514 if (s->tree != NULL && s->tree != s->root)
7515 got_object_tree_close(s->tree);
7516 if (s->root)
7517 got_object_tree_close(s->root);
7518 return NULL;
7521 static const struct got_error *
7522 search_start_tree_view(struct tog_view *view)
7524 struct tog_tree_view_state *s = &view->state.tree;
7526 s->matched_entry = NULL;
7527 return NULL;
7530 static int
7531 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7533 regmatch_t regmatch;
7535 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7536 0) == 0;
7539 static const struct got_error *
7540 search_next_tree_view(struct tog_view *view)
7542 struct tog_tree_view_state *s = &view->state.tree;
7543 struct got_tree_entry *te = NULL;
7545 if (!view->searching) {
7546 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7547 return NULL;
7550 if (s->matched_entry) {
7551 if (view->searching == TOG_SEARCH_FORWARD) {
7552 if (s->selected_entry)
7553 te = got_tree_entry_get_next(s->tree,
7554 s->selected_entry);
7555 else
7556 te = got_object_tree_get_first_entry(s->tree);
7557 } else {
7558 if (s->selected_entry == NULL)
7559 te = got_object_tree_get_last_entry(s->tree);
7560 else
7561 te = got_tree_entry_get_prev(s->tree,
7562 s->selected_entry);
7564 } else {
7565 if (s->selected_entry)
7566 te = s->selected_entry;
7567 else if (view->searching == TOG_SEARCH_FORWARD)
7568 te = got_object_tree_get_first_entry(s->tree);
7569 else
7570 te = got_object_tree_get_last_entry(s->tree);
7573 while (1) {
7574 if (te == NULL) {
7575 if (s->matched_entry == NULL) {
7576 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7577 return NULL;
7579 if (view->searching == TOG_SEARCH_FORWARD)
7580 te = got_object_tree_get_first_entry(s->tree);
7581 else
7582 te = got_object_tree_get_last_entry(s->tree);
7585 if (match_tree_entry(te, &view->regex)) {
7586 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7587 s->matched_entry = te;
7588 break;
7591 if (view->searching == TOG_SEARCH_FORWARD)
7592 te = got_tree_entry_get_next(s->tree, te);
7593 else
7594 te = got_tree_entry_get_prev(s->tree, te);
7597 if (s->matched_entry) {
7598 s->first_displayed_entry = s->matched_entry;
7599 s->selected = 0;
7602 return NULL;
7605 static const struct got_error *
7606 show_tree_view(struct tog_view *view)
7608 const struct got_error *err = NULL;
7609 struct tog_tree_view_state *s = &view->state.tree;
7610 char *parent_path;
7612 err = tree_entry_path(&parent_path, &s->parents, NULL);
7613 if (err)
7614 return err;
7616 err = draw_tree_entries(view, parent_path);
7617 free(parent_path);
7619 view_border(view);
7620 return err;
7623 static const struct got_error *
7624 tree_goto_line(struct tog_view *view, int nlines)
7626 const struct got_error *err = NULL;
7627 struct tog_tree_view_state *s = &view->state.tree;
7628 struct got_tree_entry **fte, **lte, **ste;
7629 int g, last, first = 1, i = 1;
7630 int root = s->tree == s->root;
7631 int off = root ? 1 : 2;
7633 g = view->gline;
7634 view->gline = 0;
7636 if (g == 0)
7637 g = 1;
7638 else if (g > got_object_tree_get_nentries(s->tree))
7639 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7641 fte = &s->first_displayed_entry;
7642 lte = &s->last_displayed_entry;
7643 ste = &s->selected_entry;
7645 if (*fte != NULL) {
7646 first = got_tree_entry_get_index(*fte);
7647 first += off; /* account for ".." */
7649 last = got_tree_entry_get_index(*lte);
7650 last += off;
7652 if (g >= first && g <= last && g - first < nlines) {
7653 s->selected = g - first;
7654 return NULL; /* gline is on the current page */
7657 if (*ste != NULL) {
7658 i = got_tree_entry_get_index(*ste);
7659 i += off;
7662 if (i < g) {
7663 err = tree_scroll_down(view, g - i);
7664 if (err)
7665 return err;
7666 if (got_tree_entry_get_index(*lte) >=
7667 got_object_tree_get_nentries(s->tree) - 1 &&
7668 first + s->selected < g &&
7669 s->selected < s->ndisplayed - 1) {
7670 first = got_tree_entry_get_index(*fte);
7671 first += off;
7672 s->selected = g - first;
7674 } else if (i > g)
7675 tree_scroll_up(s, i - g);
7677 if (g < nlines &&
7678 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7679 s->selected = g - 1;
7681 return NULL;
7684 static const struct got_error *
7685 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7687 const struct got_error *err = NULL;
7688 struct tog_tree_view_state *s = &view->state.tree;
7689 struct got_tree_entry *te;
7690 int n, nscroll = view->nlines - 3;
7692 if (view->gline)
7693 return tree_goto_line(view, nscroll);
7695 switch (ch) {
7696 case '0':
7697 case '$':
7698 case KEY_RIGHT:
7699 case 'l':
7700 case KEY_LEFT:
7701 case 'h':
7702 horizontal_scroll_input(view, ch);
7703 break;
7704 case 'i':
7705 s->show_ids = !s->show_ids;
7706 view->count = 0;
7707 break;
7708 case 'L':
7709 view->count = 0;
7710 if (!s->selected_entry)
7711 break;
7712 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7713 break;
7714 case 'R':
7715 view->count = 0;
7716 err = view_request_new(new_view, view, TOG_VIEW_REF);
7717 break;
7718 case 'g':
7719 case '=':
7720 case KEY_HOME:
7721 s->selected = 0;
7722 view->count = 0;
7723 if (s->tree == s->root)
7724 s->first_displayed_entry =
7725 got_object_tree_get_first_entry(s->tree);
7726 else
7727 s->first_displayed_entry = NULL;
7728 break;
7729 case 'G':
7730 case '*':
7731 case KEY_END: {
7732 int eos = view->nlines - 3;
7734 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7735 --eos; /* border */
7736 s->selected = 0;
7737 view->count = 0;
7738 te = got_object_tree_get_last_entry(s->tree);
7739 for (n = 0; n < eos; n++) {
7740 if (te == NULL) {
7741 if (s->tree != s->root) {
7742 s->first_displayed_entry = NULL;
7743 n++;
7745 break;
7747 s->first_displayed_entry = te;
7748 te = got_tree_entry_get_prev(s->tree, te);
7750 if (n > 0)
7751 s->selected = n - 1;
7752 break;
7754 case 'k':
7755 case KEY_UP:
7756 case CTRL('p'):
7757 if (s->selected > 0) {
7758 s->selected--;
7759 break;
7761 tree_scroll_up(s, 1);
7762 if (s->selected_entry == NULL ||
7763 (s->tree == s->root && s->selected_entry ==
7764 got_object_tree_get_first_entry(s->tree)))
7765 view->count = 0;
7766 break;
7767 case CTRL('u'):
7768 case 'u':
7769 nscroll /= 2;
7770 /* FALL THROUGH */
7771 case KEY_PPAGE:
7772 case CTRL('b'):
7773 case 'b':
7774 if (s->tree == s->root) {
7775 if (got_object_tree_get_first_entry(s->tree) ==
7776 s->first_displayed_entry)
7777 s->selected -= MIN(s->selected, nscroll);
7778 } else {
7779 if (s->first_displayed_entry == NULL)
7780 s->selected -= MIN(s->selected, nscroll);
7782 tree_scroll_up(s, MAX(0, nscroll));
7783 if (s->selected_entry == NULL ||
7784 (s->tree == s->root && s->selected_entry ==
7785 got_object_tree_get_first_entry(s->tree)))
7786 view->count = 0;
7787 break;
7788 case 'j':
7789 case KEY_DOWN:
7790 case CTRL('n'):
7791 if (s->selected < s->ndisplayed - 1) {
7792 s->selected++;
7793 break;
7795 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7796 == NULL) {
7797 /* can't scroll any further */
7798 view->count = 0;
7799 break;
7801 tree_scroll_down(view, 1);
7802 break;
7803 case CTRL('d'):
7804 case 'd':
7805 nscroll /= 2;
7806 /* FALL THROUGH */
7807 case KEY_NPAGE:
7808 case CTRL('f'):
7809 case 'f':
7810 case ' ':
7811 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7812 == NULL) {
7813 /* can't scroll any further; move cursor down */
7814 if (s->selected < s->ndisplayed - 1)
7815 s->selected += MIN(nscroll,
7816 s->ndisplayed - s->selected - 1);
7817 else
7818 view->count = 0;
7819 break;
7821 tree_scroll_down(view, nscroll);
7822 break;
7823 case KEY_ENTER:
7824 case '\r':
7825 case KEY_BACKSPACE:
7826 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7827 struct tog_parent_tree *parent;
7828 /* user selected '..' */
7829 if (s->tree == s->root) {
7830 view->count = 0;
7831 break;
7833 parent = TAILQ_FIRST(&s->parents);
7834 TAILQ_REMOVE(&s->parents, parent,
7835 entry);
7836 got_object_tree_close(s->tree);
7837 s->tree = parent->tree;
7838 s->first_displayed_entry =
7839 parent->first_displayed_entry;
7840 s->selected_entry =
7841 parent->selected_entry;
7842 s->selected = parent->selected;
7843 if (s->selected > view->nlines - 3) {
7844 err = offset_selection_down(view);
7845 if (err)
7846 break;
7848 free(parent);
7849 } else if (S_ISDIR(got_tree_entry_get_mode(
7850 s->selected_entry))) {
7851 struct got_tree_object *subtree;
7852 view->count = 0;
7853 err = got_object_open_as_tree(&subtree, s->repo,
7854 got_tree_entry_get_id(s->selected_entry));
7855 if (err)
7856 break;
7857 err = tree_view_visit_subtree(s, subtree);
7858 if (err) {
7859 got_object_tree_close(subtree);
7860 break;
7862 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7863 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7864 break;
7865 case KEY_RESIZE:
7866 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7867 s->selected = view->nlines - 4;
7868 view->count = 0;
7869 break;
7870 default:
7871 view->count = 0;
7872 break;
7875 return err;
7878 __dead static void
7879 usage_tree(void)
7881 endwin();
7882 fprintf(stderr,
7883 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7884 getprogname());
7885 exit(1);
7888 static const struct got_error *
7889 cmd_tree(int argc, char *argv[])
7891 const struct got_error *io_err, *error;
7892 struct got_repository *repo = NULL;
7893 struct got_worktree *worktree = NULL;
7894 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7895 struct got_object_id *commit_id = NULL;
7896 struct got_commit_object *commit = NULL;
7897 const char *commit_id_arg = NULL;
7898 char *label = NULL;
7899 struct got_reference *ref = NULL;
7900 const char *head_ref_name = NULL;
7901 int ch;
7902 struct tog_view *view;
7903 struct tog_io *tog_io = NULL;
7904 int *pack_fds = NULL;
7906 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7907 switch (ch) {
7908 case 'c':
7909 commit_id_arg = optarg;
7910 break;
7911 case 'r':
7912 repo_path = realpath(optarg, NULL);
7913 if (repo_path == NULL)
7914 return got_error_from_errno2("realpath",
7915 optarg);
7916 break;
7917 default:
7918 usage_tree();
7919 /* NOTREACHED */
7923 argc -= optind;
7924 argv += optind;
7926 if (argc > 1)
7927 usage_tree();
7929 error = got_repo_pack_fds_open(&pack_fds);
7930 if (error != NULL)
7931 goto done;
7933 if (repo_path == NULL) {
7934 cwd = getcwd(NULL, 0);
7935 if (cwd == NULL)
7936 return got_error_from_errno("getcwd");
7937 error = got_worktree_open(&worktree, cwd);
7938 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7939 goto done;
7940 if (worktree)
7941 repo_path =
7942 strdup(got_worktree_get_repo_path(worktree));
7943 else
7944 repo_path = strdup(cwd);
7945 if (repo_path == NULL) {
7946 error = got_error_from_errno("strdup");
7947 goto done;
7951 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7952 if (error != NULL)
7953 goto done;
7955 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7956 repo, worktree);
7957 if (error)
7958 goto done;
7960 error = init_curses(&tog_io);
7961 if (error)
7962 goto done;
7964 error = apply_unveil(got_repo_get_path(repo), NULL);
7965 if (error)
7966 goto done;
7968 error = tog_load_refs(repo, 0);
7969 if (error)
7970 goto done;
7972 if (commit_id_arg == NULL) {
7973 error = got_repo_match_object_id(&commit_id, &label,
7974 worktree ? got_worktree_get_head_ref_name(worktree) :
7975 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7976 if (error)
7977 goto done;
7978 head_ref_name = label;
7979 } else {
7980 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7981 if (error == NULL)
7982 head_ref_name = got_ref_get_name(ref);
7983 else if (error->code != GOT_ERR_NOT_REF)
7984 goto done;
7985 error = got_repo_match_object_id(&commit_id, NULL,
7986 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7987 if (error)
7988 goto done;
7991 error = got_object_open_as_commit(&commit, repo, commit_id);
7992 if (error)
7993 goto done;
7995 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7996 if (view == NULL) {
7997 error = got_error_from_errno("view_open");
7998 goto done;
8000 error = open_tree_view(view, commit_id, head_ref_name, repo);
8001 if (error)
8002 goto done;
8003 if (!got_path_is_root_dir(in_repo_path)) {
8004 error = tree_view_walk_path(&view->state.tree, commit,
8005 in_repo_path);
8006 if (error)
8007 goto done;
8010 if (worktree) {
8011 /* Release work tree lock. */
8012 got_worktree_close(worktree);
8013 worktree = NULL;
8015 error = view_loop(view, tog_io);
8016 done:
8017 free(repo_path);
8018 free(cwd);
8019 free(commit_id);
8020 free(label);
8021 if (ref)
8022 got_ref_close(ref);
8023 if (repo) {
8024 const struct got_error *close_err = got_repo_close(repo);
8025 if (error == NULL)
8026 error = close_err;
8028 if (pack_fds) {
8029 const struct got_error *pack_err =
8030 got_repo_pack_fds_close(pack_fds);
8031 if (error == NULL)
8032 error = pack_err;
8034 if (tog_io != NULL) {
8035 io_err = tog_io_close(tog_io);
8036 if (error == NULL)
8037 error = io_err;
8039 tog_free_refs();
8040 return error;
8043 static const struct got_error *
8044 ref_view_load_refs(struct tog_ref_view_state *s)
8046 struct got_reflist_entry *sre;
8047 struct tog_reflist_entry *re;
8049 s->nrefs = 0;
8050 TAILQ_FOREACH(sre, &tog_refs, entry) {
8051 if (strncmp(got_ref_get_name(sre->ref),
8052 "refs/got/", 9) == 0 &&
8053 strncmp(got_ref_get_name(sre->ref),
8054 "refs/got/backup/", 16) != 0)
8055 continue;
8057 re = malloc(sizeof(*re));
8058 if (re == NULL)
8059 return got_error_from_errno("malloc");
8061 re->ref = got_ref_dup(sre->ref);
8062 if (re->ref == NULL)
8063 return got_error_from_errno("got_ref_dup");
8064 re->idx = s->nrefs++;
8065 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8068 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8069 return NULL;
8072 static void
8073 ref_view_free_refs(struct tog_ref_view_state *s)
8075 struct tog_reflist_entry *re;
8077 while (!TAILQ_EMPTY(&s->refs)) {
8078 re = TAILQ_FIRST(&s->refs);
8079 TAILQ_REMOVE(&s->refs, re, entry);
8080 got_ref_close(re->ref);
8081 free(re);
8085 static const struct got_error *
8086 open_ref_view(struct tog_view *view, struct got_repository *repo)
8088 const struct got_error *err = NULL;
8089 struct tog_ref_view_state *s = &view->state.ref;
8091 s->selected_entry = 0;
8092 s->repo = repo;
8094 TAILQ_INIT(&s->refs);
8095 STAILQ_INIT(&s->colors);
8097 err = ref_view_load_refs(s);
8098 if (err)
8099 return err;
8101 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8102 err = add_color(&s->colors, "^refs/heads/",
8103 TOG_COLOR_REFS_HEADS,
8104 get_color_value("TOG_COLOR_REFS_HEADS"));
8105 if (err)
8106 goto done;
8108 err = add_color(&s->colors, "^refs/tags/",
8109 TOG_COLOR_REFS_TAGS,
8110 get_color_value("TOG_COLOR_REFS_TAGS"));
8111 if (err)
8112 goto done;
8114 err = add_color(&s->colors, "^refs/remotes/",
8115 TOG_COLOR_REFS_REMOTES,
8116 get_color_value("TOG_COLOR_REFS_REMOTES"));
8117 if (err)
8118 goto done;
8120 err = add_color(&s->colors, "^refs/got/backup/",
8121 TOG_COLOR_REFS_BACKUP,
8122 get_color_value("TOG_COLOR_REFS_BACKUP"));
8123 if (err)
8124 goto done;
8127 view->show = show_ref_view;
8128 view->input = input_ref_view;
8129 view->close = close_ref_view;
8130 view->search_start = search_start_ref_view;
8131 view->search_next = search_next_ref_view;
8132 done:
8133 if (err)
8134 free_colors(&s->colors);
8135 return err;
8138 static const struct got_error *
8139 close_ref_view(struct tog_view *view)
8141 struct tog_ref_view_state *s = &view->state.ref;
8143 ref_view_free_refs(s);
8144 free_colors(&s->colors);
8146 return NULL;
8149 static const struct got_error *
8150 resolve_reflist_entry(struct got_object_id **commit_id,
8151 struct tog_reflist_entry *re, struct got_repository *repo)
8153 const struct got_error *err = NULL;
8154 struct got_object_id *obj_id;
8155 struct got_tag_object *tag = NULL;
8156 int obj_type;
8158 *commit_id = NULL;
8160 err = got_ref_resolve(&obj_id, repo, re->ref);
8161 if (err)
8162 return err;
8164 err = got_object_get_type(&obj_type, repo, obj_id);
8165 if (err)
8166 goto done;
8168 switch (obj_type) {
8169 case GOT_OBJ_TYPE_COMMIT:
8170 *commit_id = obj_id;
8171 break;
8172 case GOT_OBJ_TYPE_TAG:
8173 err = got_object_open_as_tag(&tag, repo, obj_id);
8174 if (err)
8175 goto done;
8176 free(obj_id);
8177 err = got_object_get_type(&obj_type, repo,
8178 got_object_tag_get_object_id(tag));
8179 if (err)
8180 goto done;
8181 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8182 err = got_error(GOT_ERR_OBJ_TYPE);
8183 goto done;
8185 *commit_id = got_object_id_dup(
8186 got_object_tag_get_object_id(tag));
8187 if (*commit_id == NULL) {
8188 err = got_error_from_errno("got_object_id_dup");
8189 goto done;
8191 break;
8192 default:
8193 err = got_error(GOT_ERR_OBJ_TYPE);
8194 break;
8197 done:
8198 if (tag)
8199 got_object_tag_close(tag);
8200 if (err) {
8201 free(*commit_id);
8202 *commit_id = NULL;
8204 return err;
8207 static const struct got_error *
8208 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8209 struct tog_reflist_entry *re, struct got_repository *repo)
8211 struct tog_view *log_view;
8212 const struct got_error *err = NULL;
8213 struct got_object_id *commit_id = NULL;
8215 *new_view = NULL;
8217 err = resolve_reflist_entry(&commit_id, re, repo);
8218 if (err) {
8219 if (err->code != GOT_ERR_OBJ_TYPE)
8220 return err;
8221 else
8222 return NULL;
8225 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8226 if (log_view == NULL) {
8227 err = got_error_from_errno("view_open");
8228 goto done;
8231 err = open_log_view(log_view, commit_id, repo,
8232 got_ref_get_name(re->ref), "", 0);
8233 done:
8234 if (err)
8235 view_close(log_view);
8236 else
8237 *new_view = log_view;
8238 free(commit_id);
8239 return err;
8242 static void
8243 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8245 struct tog_reflist_entry *re;
8246 int i = 0;
8248 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8249 return;
8251 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8252 while (i++ < maxscroll) {
8253 if (re == NULL)
8254 break;
8255 s->first_displayed_entry = re;
8256 re = TAILQ_PREV(re, tog_reflist_head, entry);
8260 static const struct got_error *
8261 ref_scroll_down(struct tog_view *view, int maxscroll)
8263 struct tog_ref_view_state *s = &view->state.ref;
8264 struct tog_reflist_entry *next, *last;
8265 int n = 0;
8267 if (s->first_displayed_entry)
8268 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8269 else
8270 next = TAILQ_FIRST(&s->refs);
8272 last = s->last_displayed_entry;
8273 while (next && n++ < maxscroll) {
8274 if (last) {
8275 s->last_displayed_entry = last;
8276 last = TAILQ_NEXT(last, entry);
8278 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8279 s->first_displayed_entry = next;
8280 next = TAILQ_NEXT(next, entry);
8284 return NULL;
8287 static const struct got_error *
8288 search_start_ref_view(struct tog_view *view)
8290 struct tog_ref_view_state *s = &view->state.ref;
8292 s->matched_entry = NULL;
8293 return NULL;
8296 static int
8297 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8299 regmatch_t regmatch;
8301 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8302 0) == 0;
8305 static const struct got_error *
8306 search_next_ref_view(struct tog_view *view)
8308 struct tog_ref_view_state *s = &view->state.ref;
8309 struct tog_reflist_entry *re = NULL;
8311 if (!view->searching) {
8312 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8313 return NULL;
8316 if (s->matched_entry) {
8317 if (view->searching == TOG_SEARCH_FORWARD) {
8318 if (s->selected_entry)
8319 re = TAILQ_NEXT(s->selected_entry, entry);
8320 else
8321 re = TAILQ_PREV(s->selected_entry,
8322 tog_reflist_head, entry);
8323 } else {
8324 if (s->selected_entry == NULL)
8325 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8326 else
8327 re = TAILQ_PREV(s->selected_entry,
8328 tog_reflist_head, entry);
8330 } else {
8331 if (s->selected_entry)
8332 re = s->selected_entry;
8333 else if (view->searching == TOG_SEARCH_FORWARD)
8334 re = TAILQ_FIRST(&s->refs);
8335 else
8336 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8339 while (1) {
8340 if (re == NULL) {
8341 if (s->matched_entry == NULL) {
8342 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8343 return NULL;
8345 if (view->searching == TOG_SEARCH_FORWARD)
8346 re = TAILQ_FIRST(&s->refs);
8347 else
8348 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8351 if (match_reflist_entry(re, &view->regex)) {
8352 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8353 s->matched_entry = re;
8354 break;
8357 if (view->searching == TOG_SEARCH_FORWARD)
8358 re = TAILQ_NEXT(re, entry);
8359 else
8360 re = TAILQ_PREV(re, tog_reflist_head, entry);
8363 if (s->matched_entry) {
8364 s->first_displayed_entry = s->matched_entry;
8365 s->selected = 0;
8368 return NULL;
8371 static const struct got_error *
8372 show_ref_view(struct tog_view *view)
8374 const struct got_error *err = NULL;
8375 struct tog_ref_view_state *s = &view->state.ref;
8376 struct tog_reflist_entry *re;
8377 char *line = NULL;
8378 wchar_t *wline;
8379 struct tog_color *tc;
8380 int width, n, scrollx;
8381 int limit = view->nlines;
8383 werase(view->window);
8385 s->ndisplayed = 0;
8386 if (view_is_hsplit_top(view))
8387 --limit; /* border */
8389 if (limit == 0)
8390 return NULL;
8392 re = s->first_displayed_entry;
8394 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8395 s->nrefs) == -1)
8396 return got_error_from_errno("asprintf");
8398 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8399 if (err) {
8400 free(line);
8401 return err;
8403 if (view_needs_focus_indication(view))
8404 wstandout(view->window);
8405 waddwstr(view->window, wline);
8406 while (width++ < view->ncols)
8407 waddch(view->window, ' ');
8408 if (view_needs_focus_indication(view))
8409 wstandend(view->window);
8410 free(wline);
8411 wline = NULL;
8412 free(line);
8413 line = NULL;
8414 if (--limit <= 0)
8415 return NULL;
8417 n = 0;
8418 view->maxx = 0;
8419 while (re && limit > 0) {
8420 char *line = NULL;
8421 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8423 if (s->show_date) {
8424 struct got_commit_object *ci;
8425 struct got_tag_object *tag;
8426 struct got_object_id *id;
8427 struct tm tm;
8428 time_t t;
8430 err = got_ref_resolve(&id, s->repo, re->ref);
8431 if (err)
8432 return err;
8433 err = got_object_open_as_tag(&tag, s->repo, id);
8434 if (err) {
8435 if (err->code != GOT_ERR_OBJ_TYPE) {
8436 free(id);
8437 return err;
8439 err = got_object_open_as_commit(&ci, s->repo,
8440 id);
8441 if (err) {
8442 free(id);
8443 return err;
8445 t = got_object_commit_get_committer_time(ci);
8446 got_object_commit_close(ci);
8447 } else {
8448 t = got_object_tag_get_tagger_time(tag);
8449 got_object_tag_close(tag);
8451 free(id);
8452 if (gmtime_r(&t, &tm) == NULL)
8453 return got_error_from_errno("gmtime_r");
8454 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8455 return got_error(GOT_ERR_NO_SPACE);
8457 if (got_ref_is_symbolic(re->ref)) {
8458 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8459 ymd : "", got_ref_get_name(re->ref),
8460 got_ref_get_symref_target(re->ref)) == -1)
8461 return got_error_from_errno("asprintf");
8462 } else if (s->show_ids) {
8463 struct got_object_id *id;
8464 char *id_str;
8465 err = got_ref_resolve(&id, s->repo, re->ref);
8466 if (err)
8467 return err;
8468 err = got_object_id_str(&id_str, id);
8469 if (err) {
8470 free(id);
8471 return err;
8473 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8474 got_ref_get_name(re->ref), id_str) == -1) {
8475 err = got_error_from_errno("asprintf");
8476 free(id);
8477 free(id_str);
8478 return err;
8480 free(id);
8481 free(id_str);
8482 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8483 got_ref_get_name(re->ref)) == -1)
8484 return got_error_from_errno("asprintf");
8486 /* use full line width to determine view->maxx */
8487 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8488 if (err) {
8489 free(line);
8490 return err;
8492 view->maxx = MAX(view->maxx, width);
8493 free(wline);
8494 wline = NULL;
8496 err = format_line(&wline, &width, &scrollx, line, view->x,
8497 view->ncols, 0, 0);
8498 if (err) {
8499 free(line);
8500 return err;
8502 if (n == s->selected) {
8503 if (view->focussed)
8504 wstandout(view->window);
8505 s->selected_entry = re;
8507 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8508 if (tc)
8509 wattr_on(view->window,
8510 COLOR_PAIR(tc->colorpair), NULL);
8511 waddwstr(view->window, &wline[scrollx]);
8512 if (tc)
8513 wattr_off(view->window,
8514 COLOR_PAIR(tc->colorpair), NULL);
8515 if (width < view->ncols)
8516 waddch(view->window, '\n');
8517 if (n == s->selected && view->focussed)
8518 wstandend(view->window);
8519 free(line);
8520 free(wline);
8521 wline = NULL;
8522 n++;
8523 s->ndisplayed++;
8524 s->last_displayed_entry = re;
8526 limit--;
8527 re = TAILQ_NEXT(re, entry);
8530 view_border(view);
8531 return err;
8534 static const struct got_error *
8535 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8536 struct tog_reflist_entry *re, struct got_repository *repo)
8538 const struct got_error *err = NULL;
8539 struct got_object_id *commit_id = NULL;
8540 struct tog_view *tree_view;
8542 *new_view = NULL;
8544 err = resolve_reflist_entry(&commit_id, re, repo);
8545 if (err) {
8546 if (err->code != GOT_ERR_OBJ_TYPE)
8547 return err;
8548 else
8549 return NULL;
8553 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8554 if (tree_view == NULL) {
8555 err = got_error_from_errno("view_open");
8556 goto done;
8559 err = open_tree_view(tree_view, commit_id,
8560 got_ref_get_name(re->ref), repo);
8561 if (err)
8562 goto done;
8564 *new_view = tree_view;
8565 done:
8566 free(commit_id);
8567 return err;
8570 static const struct got_error *
8571 ref_goto_line(struct tog_view *view, int nlines)
8573 const struct got_error *err = NULL;
8574 struct tog_ref_view_state *s = &view->state.ref;
8575 int g, idx = s->selected_entry->idx;
8577 g = view->gline;
8578 view->gline = 0;
8580 if (g == 0)
8581 g = 1;
8582 else if (g > s->nrefs)
8583 g = s->nrefs;
8585 if (g >= s->first_displayed_entry->idx + 1 &&
8586 g <= s->last_displayed_entry->idx + 1 &&
8587 g - s->first_displayed_entry->idx - 1 < nlines) {
8588 s->selected = g - s->first_displayed_entry->idx - 1;
8589 return NULL;
8592 if (idx + 1 < g) {
8593 err = ref_scroll_down(view, g - idx - 1);
8594 if (err)
8595 return err;
8596 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8597 s->first_displayed_entry->idx + s->selected < g &&
8598 s->selected < s->ndisplayed - 1)
8599 s->selected = g - s->first_displayed_entry->idx - 1;
8600 } else if (idx + 1 > g)
8601 ref_scroll_up(s, idx - g + 1);
8603 if (g < nlines && s->first_displayed_entry->idx == 0)
8604 s->selected = g - 1;
8606 return NULL;
8610 static const struct got_error *
8611 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8613 const struct got_error *err = NULL;
8614 struct tog_ref_view_state *s = &view->state.ref;
8615 struct tog_reflist_entry *re;
8616 int n, nscroll = view->nlines - 1;
8618 if (view->gline)
8619 return ref_goto_line(view, nscroll);
8621 switch (ch) {
8622 case '0':
8623 case '$':
8624 case KEY_RIGHT:
8625 case 'l':
8626 case KEY_LEFT:
8627 case 'h':
8628 horizontal_scroll_input(view, ch);
8629 break;
8630 case 'i':
8631 s->show_ids = !s->show_ids;
8632 view->count = 0;
8633 break;
8634 case 'm':
8635 s->show_date = !s->show_date;
8636 view->count = 0;
8637 break;
8638 case 'o':
8639 s->sort_by_date = !s->sort_by_date;
8640 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8641 view->count = 0;
8642 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8643 got_ref_cmp_by_commit_timestamp_descending :
8644 tog_ref_cmp_by_name, s->repo);
8645 if (err)
8646 break;
8647 got_reflist_object_id_map_free(tog_refs_idmap);
8648 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8649 &tog_refs, s->repo);
8650 if (err)
8651 break;
8652 ref_view_free_refs(s);
8653 err = ref_view_load_refs(s);
8654 break;
8655 case KEY_ENTER:
8656 case '\r':
8657 view->count = 0;
8658 if (!s->selected_entry)
8659 break;
8660 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8661 break;
8662 case 'T':
8663 view->count = 0;
8664 if (!s->selected_entry)
8665 break;
8666 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8667 break;
8668 case 'g':
8669 case '=':
8670 case KEY_HOME:
8671 s->selected = 0;
8672 view->count = 0;
8673 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8674 break;
8675 case 'G':
8676 case '*':
8677 case KEY_END: {
8678 int eos = view->nlines - 1;
8680 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8681 --eos; /* border */
8682 s->selected = 0;
8683 view->count = 0;
8684 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8685 for (n = 0; n < eos; n++) {
8686 if (re == NULL)
8687 break;
8688 s->first_displayed_entry = re;
8689 re = TAILQ_PREV(re, tog_reflist_head, entry);
8691 if (n > 0)
8692 s->selected = n - 1;
8693 break;
8695 case 'k':
8696 case KEY_UP:
8697 case CTRL('p'):
8698 if (s->selected > 0) {
8699 s->selected--;
8700 break;
8702 ref_scroll_up(s, 1);
8703 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8704 view->count = 0;
8705 break;
8706 case CTRL('u'):
8707 case 'u':
8708 nscroll /= 2;
8709 /* FALL THROUGH */
8710 case KEY_PPAGE:
8711 case CTRL('b'):
8712 case 'b':
8713 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8714 s->selected -= MIN(nscroll, s->selected);
8715 ref_scroll_up(s, MAX(0, nscroll));
8716 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8717 view->count = 0;
8718 break;
8719 case 'j':
8720 case KEY_DOWN:
8721 case CTRL('n'):
8722 if (s->selected < s->ndisplayed - 1) {
8723 s->selected++;
8724 break;
8726 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8727 /* can't scroll any further */
8728 view->count = 0;
8729 break;
8731 ref_scroll_down(view, 1);
8732 break;
8733 case CTRL('d'):
8734 case 'd':
8735 nscroll /= 2;
8736 /* FALL THROUGH */
8737 case KEY_NPAGE:
8738 case CTRL('f'):
8739 case 'f':
8740 case ' ':
8741 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8742 /* can't scroll any further; move cursor down */
8743 if (s->selected < s->ndisplayed - 1)
8744 s->selected += MIN(nscroll,
8745 s->ndisplayed - s->selected - 1);
8746 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8747 s->selected += s->ndisplayed - s->selected - 1;
8748 view->count = 0;
8749 break;
8751 ref_scroll_down(view, nscroll);
8752 break;
8753 case CTRL('l'):
8754 view->count = 0;
8755 tog_free_refs();
8756 err = tog_load_refs(s->repo, s->sort_by_date);
8757 if (err)
8758 break;
8759 ref_view_free_refs(s);
8760 err = ref_view_load_refs(s);
8761 break;
8762 case KEY_RESIZE:
8763 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8764 s->selected = view->nlines - 2;
8765 break;
8766 default:
8767 view->count = 0;
8768 break;
8771 return err;
8774 __dead static void
8775 usage_ref(void)
8777 endwin();
8778 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8779 getprogname());
8780 exit(1);
8783 static const struct got_error *
8784 cmd_ref(int argc, char *argv[])
8786 const struct got_error *io_err, *error;
8787 struct got_repository *repo = NULL;
8788 struct got_worktree *worktree = NULL;
8789 char *cwd = NULL, *repo_path = NULL;
8790 int ch;
8791 struct tog_view *view;
8792 struct tog_io *tog_io = NULL;
8793 int *pack_fds = NULL;
8795 while ((ch = getopt(argc, argv, "r:")) != -1) {
8796 switch (ch) {
8797 case 'r':
8798 repo_path = realpath(optarg, NULL);
8799 if (repo_path == NULL)
8800 return got_error_from_errno2("realpath",
8801 optarg);
8802 break;
8803 default:
8804 usage_ref();
8805 /* NOTREACHED */
8809 argc -= optind;
8810 argv += optind;
8812 if (argc > 1)
8813 usage_ref();
8815 error = got_repo_pack_fds_open(&pack_fds);
8816 if (error != NULL)
8817 goto done;
8819 if (repo_path == NULL) {
8820 cwd = getcwd(NULL, 0);
8821 if (cwd == NULL)
8822 return got_error_from_errno("getcwd");
8823 error = got_worktree_open(&worktree, cwd);
8824 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8825 goto done;
8826 if (worktree)
8827 repo_path =
8828 strdup(got_worktree_get_repo_path(worktree));
8829 else
8830 repo_path = strdup(cwd);
8831 if (repo_path == NULL) {
8832 error = got_error_from_errno("strdup");
8833 goto done;
8837 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8838 if (error != NULL)
8839 goto done;
8841 error = init_curses(&tog_io);
8842 if (error)
8843 goto done;
8845 error = apply_unveil(got_repo_get_path(repo), NULL);
8846 if (error)
8847 goto done;
8849 error = tog_load_refs(repo, 0);
8850 if (error)
8851 goto done;
8853 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8854 if (view == NULL) {
8855 error = got_error_from_errno("view_open");
8856 goto done;
8859 error = open_ref_view(view, repo);
8860 if (error)
8861 goto done;
8863 if (worktree) {
8864 /* Release work tree lock. */
8865 got_worktree_close(worktree);
8866 worktree = NULL;
8868 error = view_loop(view, tog_io);
8869 done:
8870 free(repo_path);
8871 free(cwd);
8872 if (repo) {
8873 const struct got_error *close_err = got_repo_close(repo);
8874 if (close_err)
8875 error = close_err;
8877 if (pack_fds) {
8878 const struct got_error *pack_err =
8879 got_repo_pack_fds_close(pack_fds);
8880 if (error == NULL)
8881 error = pack_err;
8883 if (tog_io != NULL) {
8884 io_err = tog_io_close(tog_io);
8885 if (error == NULL)
8886 error = io_err;
8888 tog_free_refs();
8889 return error;
8892 static const struct got_error*
8893 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8894 const char *str)
8896 size_t len;
8898 if (win == NULL)
8899 win = stdscr;
8901 len = strlen(str);
8902 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8904 if (focus)
8905 wstandout(win);
8906 if (mvwprintw(win, y, x, "%s", str) == ERR)
8907 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8908 if (focus)
8909 wstandend(win);
8911 return NULL;
8914 static const struct got_error *
8915 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8917 off_t *p;
8919 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8920 if (p == NULL) {
8921 free(*line_offsets);
8922 *line_offsets = NULL;
8923 return got_error_from_errno("reallocarray");
8926 *line_offsets = p;
8927 (*line_offsets)[*nlines] = off;
8928 ++(*nlines);
8929 return NULL;
8932 static const struct got_error *
8933 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8935 *ret = 0;
8937 for (;n > 0; --n, ++km) {
8938 char *t0, *t, *k;
8939 size_t len = 1;
8941 if (km->keys == NULL)
8942 continue;
8944 t = t0 = strdup(km->keys);
8945 if (t0 == NULL)
8946 return got_error_from_errno("strdup");
8948 len += strlen(t);
8949 while ((k = strsep(&t, " ")) != NULL)
8950 len += strlen(k) > 1 ? 2 : 0;
8951 free(t0);
8952 *ret = MAX(*ret, len);
8955 return NULL;
8959 * Write keymap section headers, keys, and key info in km to f.
8960 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8961 * wrap control and symbolic keys in guillemets, else use <>.
8963 static const struct got_error *
8964 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8966 int n, len = width;
8968 if (km->keys) {
8969 static const char *u8_glyph[] = {
8970 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8971 "\xe2\x80\xba" /* U+203A (utf8 >) */
8973 char *t0, *t, *k;
8974 int cs, s, first = 1;
8976 cs = got_locale_is_utf8();
8978 t = t0 = strdup(km->keys);
8979 if (t0 == NULL)
8980 return got_error_from_errno("strdup");
8982 len = strlen(km->keys);
8983 while ((k = strsep(&t, " ")) != NULL) {
8984 s = strlen(k) > 1; /* control or symbolic key */
8985 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8986 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8987 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8988 if (n < 0) {
8989 free(t0);
8990 return got_error_from_errno("fprintf");
8992 first = 0;
8993 len += s ? 2 : 0;
8994 *off += n;
8996 free(t0);
8998 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8999 if (n < 0)
9000 return got_error_from_errno("fprintf");
9001 *off += n;
9003 return NULL;
9006 static const struct got_error *
9007 format_help(struct tog_help_view_state *s)
9009 const struct got_error *err = NULL;
9010 off_t off = 0;
9011 int i, max, n, show = s->all;
9012 static const struct tog_key_map km[] = {
9013 #define KEYMAP_(info, type) { NULL, (info), type }
9014 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9015 GENERATE_HELP
9016 #undef KEYMAP_
9017 #undef KEY_
9020 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9021 if (err)
9022 return err;
9024 n = nitems(km);
9025 err = max_key_str(&max, km, n);
9026 if (err)
9027 return err;
9029 for (i = 0; i < n; ++i) {
9030 if (km[i].keys == NULL) {
9031 show = s->all;
9032 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9033 km[i].type == s->type || s->all)
9034 show = 1;
9036 if (show) {
9037 err = format_help_line(&off, s->f, &km[i], max);
9038 if (err)
9039 return err;
9040 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9041 if (err)
9042 return err;
9045 fputc('\n', s->f);
9046 ++off;
9047 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9048 return err;
9051 static const struct got_error *
9052 create_help(struct tog_help_view_state *s)
9054 FILE *f;
9055 const struct got_error *err;
9057 free(s->line_offsets);
9058 s->line_offsets = NULL;
9059 s->nlines = 0;
9061 f = got_opentemp();
9062 if (f == NULL)
9063 return got_error_from_errno("got_opentemp");
9064 s->f = f;
9066 err = format_help(s);
9067 if (err)
9068 return err;
9070 if (s->f && fflush(s->f) != 0)
9071 return got_error_from_errno("fflush");
9073 return NULL;
9076 static const struct got_error *
9077 search_start_help_view(struct tog_view *view)
9079 view->state.help.matched_line = 0;
9080 return NULL;
9083 static void
9084 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9085 size_t *nlines, int **first, int **last, int **match, int **selected)
9087 struct tog_help_view_state *s = &view->state.help;
9089 *f = s->f;
9090 *nlines = s->nlines;
9091 *line_offsets = s->line_offsets;
9092 *match = &s->matched_line;
9093 *first = &s->first_displayed_line;
9094 *last = &s->last_displayed_line;
9095 *selected = &s->selected_line;
9098 static const struct got_error *
9099 show_help_view(struct tog_view *view)
9101 struct tog_help_view_state *s = &view->state.help;
9102 const struct got_error *err;
9103 regmatch_t *regmatch = &view->regmatch;
9104 wchar_t *wline;
9105 char *line;
9106 ssize_t linelen;
9107 size_t linesz = 0;
9108 int width, nprinted = 0, rc = 0;
9109 int eos = view->nlines;
9111 if (view_is_hsplit_top(view))
9112 --eos; /* account for border */
9114 s->lineno = 0;
9115 rewind(s->f);
9116 werase(view->window);
9118 if (view->gline > s->nlines - 1)
9119 view->gline = s->nlines - 1;
9121 err = win_draw_center(view->window, 0, 0, view->ncols,
9122 view_needs_focus_indication(view),
9123 "tog help (press q to return to tog)");
9124 if (err)
9125 return err;
9126 if (eos <= 1)
9127 return NULL;
9128 waddstr(view->window, "\n\n");
9129 eos -= 2;
9131 s->eof = 0;
9132 view->maxx = 0;
9133 line = NULL;
9134 while (eos > 0 && nprinted < eos) {
9135 attr_t attr = 0;
9137 linelen = getline(&line, &linesz, s->f);
9138 if (linelen == -1) {
9139 if (!feof(s->f)) {
9140 free(line);
9141 return got_ferror(s->f, GOT_ERR_IO);
9143 s->eof = 1;
9144 break;
9146 if (++s->lineno < s->first_displayed_line)
9147 continue;
9148 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9149 continue;
9150 if (s->lineno == view->hiline)
9151 attr = A_STANDOUT;
9153 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9154 view->x ? 1 : 0);
9155 if (err) {
9156 free(line);
9157 return err;
9159 view->maxx = MAX(view->maxx, width);
9160 free(wline);
9161 wline = NULL;
9163 if (attr)
9164 wattron(view->window, attr);
9165 if (s->first_displayed_line + nprinted == s->matched_line &&
9166 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9167 err = add_matched_line(&width, line, view->ncols - 1, 0,
9168 view->window, view->x, regmatch);
9169 if (err) {
9170 free(line);
9171 return err;
9173 } else {
9174 int skip;
9176 err = format_line(&wline, &width, &skip, line,
9177 view->x, view->ncols, 0, view->x ? 1 : 0);
9178 if (err) {
9179 free(line);
9180 return err;
9182 waddwstr(view->window, &wline[skip]);
9183 free(wline);
9184 wline = NULL;
9186 if (s->lineno == view->hiline) {
9187 while (width++ < view->ncols)
9188 waddch(view->window, ' ');
9189 } else {
9190 if (width < view->ncols)
9191 waddch(view->window, '\n');
9193 if (attr)
9194 wattroff(view->window, attr);
9195 if (++nprinted == 1)
9196 s->first_displayed_line = s->lineno;
9198 free(line);
9199 if (nprinted > 0)
9200 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9201 else
9202 s->last_displayed_line = s->first_displayed_line;
9204 view_border(view);
9206 if (s->eof) {
9207 rc = waddnstr(view->window,
9208 "See the tog(1) manual page for full documentation",
9209 view->ncols - 1);
9210 if (rc == ERR)
9211 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9212 } else {
9213 wmove(view->window, view->nlines - 1, 0);
9214 wclrtoeol(view->window);
9215 wstandout(view->window);
9216 rc = waddnstr(view->window, "scroll down for more...",
9217 view->ncols - 1);
9218 if (rc == ERR)
9219 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9220 if (getcurx(view->window) < view->ncols - 6) {
9221 rc = wprintw(view->window, "[%.0f%%]",
9222 100.00 * s->last_displayed_line / s->nlines);
9223 if (rc == ERR)
9224 return got_error_msg(GOT_ERR_IO, "wprintw");
9226 wstandend(view->window);
9229 return NULL;
9232 static const struct got_error *
9233 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9235 struct tog_help_view_state *s = &view->state.help;
9236 const struct got_error *err = NULL;
9237 char *line = NULL;
9238 ssize_t linelen;
9239 size_t linesz = 0;
9240 int eos, nscroll;
9242 eos = nscroll = view->nlines;
9243 if (view_is_hsplit_top(view))
9244 --eos; /* border */
9246 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9248 switch (ch) {
9249 case '0':
9250 case '$':
9251 case KEY_RIGHT:
9252 case 'l':
9253 case KEY_LEFT:
9254 case 'h':
9255 horizontal_scroll_input(view, ch);
9256 break;
9257 case 'g':
9258 case KEY_HOME:
9259 s->first_displayed_line = 1;
9260 view->count = 0;
9261 break;
9262 case 'G':
9263 case KEY_END:
9264 view->count = 0;
9265 if (s->eof)
9266 break;
9267 s->first_displayed_line = (s->nlines - eos) + 3;
9268 s->eof = 1;
9269 break;
9270 case 'k':
9271 case KEY_UP:
9272 if (s->first_displayed_line > 1)
9273 --s->first_displayed_line;
9274 else
9275 view->count = 0;
9276 break;
9277 case CTRL('u'):
9278 case 'u':
9279 nscroll /= 2;
9280 /* FALL THROUGH */
9281 case KEY_PPAGE:
9282 case CTRL('b'):
9283 case 'b':
9284 if (s->first_displayed_line == 1) {
9285 view->count = 0;
9286 break;
9288 while (--nscroll > 0 && s->first_displayed_line > 1)
9289 s->first_displayed_line--;
9290 break;
9291 case 'j':
9292 case KEY_DOWN:
9293 case CTRL('n'):
9294 if (!s->eof)
9295 ++s->first_displayed_line;
9296 else
9297 view->count = 0;
9298 break;
9299 case CTRL('d'):
9300 case 'd':
9301 nscroll /= 2;
9302 /* FALL THROUGH */
9303 case KEY_NPAGE:
9304 case CTRL('f'):
9305 case 'f':
9306 case ' ':
9307 if (s->eof) {
9308 view->count = 0;
9309 break;
9311 while (!s->eof && --nscroll > 0) {
9312 linelen = getline(&line, &linesz, s->f);
9313 s->first_displayed_line++;
9314 if (linelen == -1) {
9315 if (feof(s->f))
9316 s->eof = 1;
9317 else
9318 err = got_ferror(s->f, GOT_ERR_IO);
9319 break;
9322 free(line);
9323 break;
9324 default:
9325 view->count = 0;
9326 break;
9329 return err;
9332 static const struct got_error *
9333 close_help_view(struct tog_view *view)
9335 struct tog_help_view_state *s = &view->state.help;
9337 free(s->line_offsets);
9338 s->line_offsets = NULL;
9339 if (fclose(s->f) == EOF)
9340 return got_error_from_errno("fclose");
9342 return NULL;
9345 static const struct got_error *
9346 reset_help_view(struct tog_view *view)
9348 struct tog_help_view_state *s = &view->state.help;
9351 if (s->f && fclose(s->f) == EOF)
9352 return got_error_from_errno("fclose");
9354 wclear(view->window);
9355 view->count = 0;
9356 view->x = 0;
9357 s->all = !s->all;
9358 s->first_displayed_line = 1;
9359 s->last_displayed_line = view->nlines;
9360 s->matched_line = 0;
9362 return create_help(s);
9365 static const struct got_error *
9366 open_help_view(struct tog_view *view, struct tog_view *parent)
9368 const struct got_error *err = NULL;
9369 struct tog_help_view_state *s = &view->state.help;
9371 s->type = (enum tog_keymap_type)parent->type;
9372 s->first_displayed_line = 1;
9373 s->last_displayed_line = view->nlines;
9374 s->selected_line = 1;
9376 view->show = show_help_view;
9377 view->input = input_help_view;
9378 view->reset = reset_help_view;
9379 view->close = close_help_view;
9380 view->search_start = search_start_help_view;
9381 view->search_setup = search_setup_help_view;
9382 view->search_next = search_next_view_match;
9384 err = create_help(s);
9385 return err;
9388 static const struct got_error *
9389 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9390 enum tog_view_type request, int y, int x)
9392 const struct got_error *err = NULL;
9394 *new_view = NULL;
9396 switch (request) {
9397 case TOG_VIEW_DIFF:
9398 if (view->type == TOG_VIEW_LOG) {
9399 struct tog_log_view_state *s = &view->state.log;
9401 err = open_diff_view_for_commit(new_view, y, x,
9402 s->selected_entry->commit, s->selected_entry->id,
9403 view, s->repo);
9404 } else
9405 return got_error_msg(GOT_ERR_NOT_IMPL,
9406 "parent/child view pair not supported");
9407 break;
9408 case TOG_VIEW_BLAME:
9409 if (view->type == TOG_VIEW_TREE) {
9410 struct tog_tree_view_state *s = &view->state.tree;
9412 err = blame_tree_entry(new_view, y, x,
9413 s->selected_entry, &s->parents, s->commit_id,
9414 s->repo);
9415 } else
9416 return got_error_msg(GOT_ERR_NOT_IMPL,
9417 "parent/child view pair not supported");
9418 break;
9419 case TOG_VIEW_LOG:
9420 if (view->type == TOG_VIEW_BLAME)
9421 err = log_annotated_line(new_view, y, x,
9422 view->state.blame.repo, view->state.blame.id_to_log);
9423 else if (view->type == TOG_VIEW_TREE)
9424 err = log_selected_tree_entry(new_view, y, x,
9425 &view->state.tree);
9426 else if (view->type == TOG_VIEW_REF)
9427 err = log_ref_entry(new_view, y, x,
9428 view->state.ref.selected_entry,
9429 view->state.ref.repo);
9430 else
9431 return got_error_msg(GOT_ERR_NOT_IMPL,
9432 "parent/child view pair not supported");
9433 break;
9434 case TOG_VIEW_TREE:
9435 if (view->type == TOG_VIEW_LOG)
9436 err = browse_commit_tree(new_view, y, x,
9437 view->state.log.selected_entry,
9438 view->state.log.in_repo_path,
9439 view->state.log.head_ref_name,
9440 view->state.log.repo);
9441 else if (view->type == TOG_VIEW_REF)
9442 err = browse_ref_tree(new_view, y, x,
9443 view->state.ref.selected_entry,
9444 view->state.ref.repo);
9445 else
9446 return got_error_msg(GOT_ERR_NOT_IMPL,
9447 "parent/child view pair not supported");
9448 break;
9449 case TOG_VIEW_REF:
9450 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9451 if (*new_view == NULL)
9452 return got_error_from_errno("view_open");
9453 if (view->type == TOG_VIEW_LOG)
9454 err = open_ref_view(*new_view, view->state.log.repo);
9455 else if (view->type == TOG_VIEW_TREE)
9456 err = open_ref_view(*new_view, view->state.tree.repo);
9457 else
9458 err = got_error_msg(GOT_ERR_NOT_IMPL,
9459 "parent/child view pair not supported");
9460 if (err)
9461 view_close(*new_view);
9462 break;
9463 case TOG_VIEW_HELP:
9464 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9465 if (*new_view == NULL)
9466 return got_error_from_errno("view_open");
9467 err = open_help_view(*new_view, view);
9468 if (err)
9469 view_close(*new_view);
9470 break;
9471 default:
9472 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9475 return err;
9479 * If view was scrolled down to move the selected line into view when opening a
9480 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9482 static void
9483 offset_selection_up(struct tog_view *view)
9485 switch (view->type) {
9486 case TOG_VIEW_BLAME: {
9487 struct tog_blame_view_state *s = &view->state.blame;
9488 if (s->first_displayed_line == 1) {
9489 s->selected_line = MAX(s->selected_line - view->offset,
9490 1);
9491 break;
9493 if (s->first_displayed_line > view->offset)
9494 s->first_displayed_line -= view->offset;
9495 else
9496 s->first_displayed_line = 1;
9497 s->selected_line += view->offset;
9498 break;
9500 case TOG_VIEW_LOG:
9501 log_scroll_up(&view->state.log, view->offset);
9502 view->state.log.selected += view->offset;
9503 break;
9504 case TOG_VIEW_REF:
9505 ref_scroll_up(&view->state.ref, view->offset);
9506 view->state.ref.selected += view->offset;
9507 break;
9508 case TOG_VIEW_TREE:
9509 tree_scroll_up(&view->state.tree, view->offset);
9510 view->state.tree.selected += view->offset;
9511 break;
9512 default:
9513 break;
9516 view->offset = 0;
9520 * If the selected line is in the section of screen covered by the bottom split,
9521 * scroll down offset lines to move it into view and index its new position.
9523 static const struct got_error *
9524 offset_selection_down(struct tog_view *view)
9526 const struct got_error *err = NULL;
9527 const struct got_error *(*scrolld)(struct tog_view *, int);
9528 int *selected = NULL;
9529 int header, offset;
9531 switch (view->type) {
9532 case TOG_VIEW_BLAME: {
9533 struct tog_blame_view_state *s = &view->state.blame;
9534 header = 3;
9535 scrolld = NULL;
9536 if (s->selected_line > view->nlines - header) {
9537 offset = abs(view->nlines - s->selected_line - header);
9538 s->first_displayed_line += offset;
9539 s->selected_line -= offset;
9540 view->offset = offset;
9542 break;
9544 case TOG_VIEW_LOG: {
9545 struct tog_log_view_state *s = &view->state.log;
9546 scrolld = &log_scroll_down;
9547 header = view_is_parent_view(view) ? 3 : 2;
9548 selected = &s->selected;
9549 break;
9551 case TOG_VIEW_REF: {
9552 struct tog_ref_view_state *s = &view->state.ref;
9553 scrolld = &ref_scroll_down;
9554 header = 3;
9555 selected = &s->selected;
9556 break;
9558 case TOG_VIEW_TREE: {
9559 struct tog_tree_view_state *s = &view->state.tree;
9560 scrolld = &tree_scroll_down;
9561 header = 5;
9562 selected = &s->selected;
9563 break;
9565 default:
9566 selected = NULL;
9567 scrolld = NULL;
9568 header = 0;
9569 break;
9572 if (selected && *selected > view->nlines - header) {
9573 offset = abs(view->nlines - *selected - header);
9574 view->offset = offset;
9575 if (scrolld && offset) {
9576 err = scrolld(view, offset);
9577 *selected -= offset;
9581 return err;
9584 static void
9585 list_commands(FILE *fp)
9587 size_t i;
9589 fprintf(fp, "commands:");
9590 for (i = 0; i < nitems(tog_commands); i++) {
9591 const struct tog_cmd *cmd = &tog_commands[i];
9592 fprintf(fp, " %s", cmd->name);
9594 fputc('\n', fp);
9597 __dead static void
9598 usage(int hflag, int status)
9600 FILE *fp = (status == 0) ? stdout : stderr;
9602 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9603 getprogname());
9604 if (hflag) {
9605 fprintf(fp, "lazy usage: %s path\n", getprogname());
9606 list_commands(fp);
9608 exit(status);
9611 static char **
9612 make_argv(int argc, ...)
9614 va_list ap;
9615 char **argv;
9616 int i;
9618 va_start(ap, argc);
9620 argv = calloc(argc, sizeof(char *));
9621 if (argv == NULL)
9622 err(1, "calloc");
9623 for (i = 0; i < argc; i++) {
9624 argv[i] = strdup(va_arg(ap, char *));
9625 if (argv[i] == NULL)
9626 err(1, "strdup");
9629 va_end(ap);
9630 return argv;
9634 * Try to convert 'tog path' into a 'tog log path' command.
9635 * The user could simply have mistyped the command rather than knowingly
9636 * provided a path. So check whether argv[0] can in fact be resolved
9637 * to a path in the HEAD commit and print a special error if not.
9638 * This hack is for mpi@ <3
9640 static const struct got_error *
9641 tog_log_with_path(int argc, char *argv[])
9643 const struct got_error *error = NULL, *close_err;
9644 const struct tog_cmd *cmd = NULL;
9645 struct got_repository *repo = NULL;
9646 struct got_worktree *worktree = NULL;
9647 struct got_object_id *commit_id = NULL, *id = NULL;
9648 struct got_commit_object *commit = NULL;
9649 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9650 char *commit_id_str = NULL, **cmd_argv = NULL;
9651 int *pack_fds = NULL;
9653 cwd = getcwd(NULL, 0);
9654 if (cwd == NULL)
9655 return got_error_from_errno("getcwd");
9657 error = got_repo_pack_fds_open(&pack_fds);
9658 if (error != NULL)
9659 goto done;
9661 error = got_worktree_open(&worktree, cwd);
9662 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9663 goto done;
9665 if (worktree)
9666 repo_path = strdup(got_worktree_get_repo_path(worktree));
9667 else
9668 repo_path = strdup(cwd);
9669 if (repo_path == NULL) {
9670 error = got_error_from_errno("strdup");
9671 goto done;
9674 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9675 if (error != NULL)
9676 goto done;
9678 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9679 repo, worktree);
9680 if (error)
9681 goto done;
9683 error = tog_load_refs(repo, 0);
9684 if (error)
9685 goto done;
9686 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9687 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9688 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9689 if (error)
9690 goto done;
9692 if (worktree) {
9693 got_worktree_close(worktree);
9694 worktree = NULL;
9697 error = got_object_open_as_commit(&commit, repo, commit_id);
9698 if (error)
9699 goto done;
9701 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9702 if (error) {
9703 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9704 goto done;
9705 fprintf(stderr, "%s: '%s' is no known command or path\n",
9706 getprogname(), argv[0]);
9707 usage(1, 1);
9708 /* not reached */
9711 error = got_object_id_str(&commit_id_str, commit_id);
9712 if (error)
9713 goto done;
9715 cmd = &tog_commands[0]; /* log */
9716 argc = 4;
9717 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9718 error = cmd->cmd_main(argc, cmd_argv);
9719 done:
9720 if (repo) {
9721 close_err = got_repo_close(repo);
9722 if (error == NULL)
9723 error = close_err;
9725 if (commit)
9726 got_object_commit_close(commit);
9727 if (worktree)
9728 got_worktree_close(worktree);
9729 if (pack_fds) {
9730 const struct got_error *pack_err =
9731 got_repo_pack_fds_close(pack_fds);
9732 if (error == NULL)
9733 error = pack_err;
9735 free(id);
9736 free(commit_id_str);
9737 free(commit_id);
9738 free(cwd);
9739 free(repo_path);
9740 free(in_repo_path);
9741 if (cmd_argv) {
9742 int i;
9743 for (i = 0; i < argc; i++)
9744 free(cmd_argv[i]);
9745 free(cmd_argv);
9747 tog_free_refs();
9748 return error;
9751 int
9752 main(int argc, char *argv[])
9754 const struct got_error *error = NULL;
9755 const struct tog_cmd *cmd = NULL;
9756 int ch, hflag = 0, Vflag = 0;
9757 char **cmd_argv = NULL;
9758 static const struct option longopts[] = {
9759 { "version", no_argument, NULL, 'V' },
9760 { NULL, 0, NULL, 0}
9762 char *diff_algo_str = NULL;
9764 setlocale(LC_CTYPE, "");
9766 #if !defined(PROFILE) && !defined(TOG_REGRESS)
9767 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9768 NULL) == -1)
9769 err(1, "pledge");
9770 #endif
9772 if (!isatty(STDIN_FILENO))
9773 errx(1, "standard input is not a tty");
9775 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9776 switch (ch) {
9777 case 'h':
9778 hflag = 1;
9779 break;
9780 case 'V':
9781 Vflag = 1;
9782 break;
9783 default:
9784 usage(hflag, 1);
9785 /* NOTREACHED */
9789 argc -= optind;
9790 argv += optind;
9791 optind = 1;
9792 optreset = 1;
9794 if (Vflag) {
9795 got_version_print_str();
9796 return 0;
9799 if (argc == 0) {
9800 if (hflag)
9801 usage(hflag, 0);
9802 /* Build an argument vector which runs a default command. */
9803 cmd = &tog_commands[0];
9804 argc = 1;
9805 cmd_argv = make_argv(argc, cmd->name);
9806 } else {
9807 size_t i;
9809 /* Did the user specify a command? */
9810 for (i = 0; i < nitems(tog_commands); i++) {
9811 if (strncmp(tog_commands[i].name, argv[0],
9812 strlen(argv[0])) == 0) {
9813 cmd = &tog_commands[i];
9814 break;
9819 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9820 if (diff_algo_str) {
9821 if (strcasecmp(diff_algo_str, "patience") == 0)
9822 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9823 if (strcasecmp(diff_algo_str, "myers") == 0)
9824 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9827 if (cmd == NULL) {
9828 if (argc != 1)
9829 usage(0, 1);
9830 /* No command specified; try log with a path */
9831 error = tog_log_with_path(argc, argv);
9832 } else {
9833 if (hflag)
9834 cmd->cmd_usage();
9835 else
9836 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9839 endwin();
9840 if (cmd_argv) {
9841 int i;
9842 for (i = 0; i < argc; i++)
9843 free(cmd_argv[i]);
9844 free(cmd_argv);
9847 if (error && error->code != GOT_ERR_CANCELLED &&
9848 error->code != GOT_ERR_EOF &&
9849 error->code != GOT_ERR_PRIVSEP_EXIT &&
9850 error->code != GOT_ERR_PRIVSEP_PIPE &&
9851 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9852 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9853 return 0;