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.3f /* 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 pthread_cond_t blame_complete;
436 };
438 struct tog_blame {
439 FILE *f;
440 off_t filesize;
441 struct tog_blame_line *lines;
442 int nlines;
443 off_t *line_offsets;
444 pthread_t thread;
445 struct tog_blame_thread_args thread_args;
446 struct tog_blame_cb_args cb_args;
447 const char *path;
448 int *pack_fds;
449 };
451 struct tog_blame_view_state {
452 int first_displayed_line;
453 int last_displayed_line;
454 int selected_line;
455 int last_diffed_line;
456 int blame_complete;
457 int eof;
458 int done;
459 struct got_object_id_queue blamed_commits;
460 struct got_object_qid *blamed_commit;
461 char *path;
462 struct got_repository *repo;
463 struct got_object_id *commit_id;
464 struct got_object_id *id_to_log;
465 struct tog_blame blame;
466 int matched_line;
467 struct tog_colors colors;
468 };
470 struct tog_parent_tree {
471 TAILQ_ENTRY(tog_parent_tree) entry;
472 struct got_tree_object *tree;
473 struct got_tree_entry *first_displayed_entry;
474 struct got_tree_entry *selected_entry;
475 int selected;
476 };
478 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
480 struct tog_tree_view_state {
481 char *tree_label;
482 struct got_object_id *commit_id;/* commit which this tree belongs to */
483 struct got_tree_object *root; /* the commit's root tree entry */
484 struct got_tree_object *tree; /* currently displayed (sub-)tree */
485 struct got_tree_entry *first_displayed_entry;
486 struct got_tree_entry *last_displayed_entry;
487 struct got_tree_entry *selected_entry;
488 int ndisplayed, selected, show_ids;
489 struct tog_parent_trees parents; /* parent trees of current sub-tree */
490 char *head_ref_name;
491 struct got_repository *repo;
492 struct got_tree_entry *matched_entry;
493 struct tog_colors colors;
494 };
496 struct tog_reflist_entry {
497 TAILQ_ENTRY(tog_reflist_entry) entry;
498 struct got_reference *ref;
499 int idx;
500 };
502 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
504 struct tog_ref_view_state {
505 struct tog_reflist_head refs;
506 struct tog_reflist_entry *first_displayed_entry;
507 struct tog_reflist_entry *last_displayed_entry;
508 struct tog_reflist_entry *selected_entry;
509 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
510 struct got_repository *repo;
511 struct tog_reflist_entry *matched_entry;
512 struct tog_colors colors;
513 };
515 struct tog_help_view_state {
516 FILE *f;
517 off_t *line_offsets;
518 size_t nlines;
519 int lineno;
520 int first_displayed_line;
521 int last_displayed_line;
522 int eof;
523 int matched_line;
524 int selected_line;
525 int all;
526 enum tog_keymap_type type;
527 };
529 #define GENERATE_HELP \
530 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
531 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
532 KEY_("k C-p Up", "Move cursor or page up one line"), \
533 KEY_("j C-n Down", "Move cursor or page down one line"), \
534 KEY_("C-b b PgUp", "Scroll the view up one page"), \
535 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
536 KEY_("C-u u", "Scroll the view up one half page"), \
537 KEY_("C-d d", "Scroll the view down one half page"), \
538 KEY_("g", "Go to line N (default: first line)"), \
539 KEY_("Home =", "Go to the first line"), \
540 KEY_("G", "Go to line N (default: last line)"), \
541 KEY_("End *", "Go to the last line"), \
542 KEY_("l Right", "Scroll the view right"), \
543 KEY_("h Left", "Scroll the view left"), \
544 KEY_("$", "Scroll view to the rightmost position"), \
545 KEY_("0", "Scroll view to the leftmost position"), \
546 KEY_("-", "Decrease size of the focussed split"), \
547 KEY_("+", "Increase size of the focussed split"), \
548 KEY_("Tab", "Switch focus between views"), \
549 KEY_("F", "Toggle fullscreen mode"), \
550 KEY_("S", "Switch split-screen layout"), \
551 KEY_("/", "Open prompt to enter search term"), \
552 KEY_("n", "Find next line/token matching the current search term"), \
553 KEY_("N", "Find previous line/token matching the current search term"),\
554 KEY_("q", "Quit the focussed view; Quit help screen"), \
555 KEY_("Q", "Quit tog"), \
557 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
558 KEY_("< ,", "Move cursor up one commit"), \
559 KEY_("> .", "Move cursor down one commit"), \
560 KEY_("Enter", "Open diff view of the selected commit"), \
561 KEY_("B", "Reload the log view and toggle display of merged commits"), \
562 KEY_("R", "Open ref view of all repository references"), \
563 KEY_("T", "Display tree view of the repository from the selected" \
564 " commit"), \
565 KEY_("@", "Toggle between displaying author and committer name"), \
566 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
567 KEY_("C-g Backspace", "Cancel current search or log operation"), \
568 KEY_("C-l", "Reload the log view with new commits in the repository"), \
570 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
571 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
572 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
573 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
574 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
575 " data"), \
576 KEY_("(", "Go to the previous file in the diff"), \
577 KEY_(")", "Go to the next file in the diff"), \
578 KEY_("{", "Go to the previous hunk in the diff"), \
579 KEY_("}", "Go to the next hunk in the diff"), \
580 KEY_("[", "Decrease the number of context lines"), \
581 KEY_("]", "Increase the number of context lines"), \
582 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
584 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
585 KEY_("Enter", "Display diff view of the selected line's commit"), \
586 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
587 KEY_("L", "Open log view for the currently selected annotated line"), \
588 KEY_("C", "Reload view with the previously blamed commit"), \
589 KEY_("c", "Reload view with the version of the file found in the" \
590 " selected line's commit"), \
591 KEY_("p", "Reload view with the version of the file found in the" \
592 " selected line's parent commit"), \
594 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
595 KEY_("Enter", "Enter selected directory or open blame view of the" \
596 " selected file"), \
597 KEY_("L", "Open log view for the selected entry"), \
598 KEY_("R", "Open ref view of all repository references"), \
599 KEY_("i", "Show object IDs for all tree entries"), \
600 KEY_("Backspace", "Return to the parent directory"), \
602 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
603 KEY_("Enter", "Display log view of the selected reference"), \
604 KEY_("T", "Display tree view of the selected reference"), \
605 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
606 KEY_("m", "Toggle display of last modified date for each reference"), \
607 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
608 KEY_("C-l", "Reload view with all repository references")
610 struct tog_key_map {
611 const char *keys;
612 const char *info;
613 enum tog_keymap_type type;
614 };
616 /* curses io for tog regress */
617 struct tog_io {
618 FILE *cin;
619 FILE *cout;
620 FILE *f;
621 FILE *sdump;
622 int wait_for_ui;
623 } tog_io;
624 static int using_mock_io;
626 #define TOG_KEY_SCRDUMP SHRT_MIN
628 /*
629 * We implement two types of views: parent views and child views.
631 * The 'Tab' key switches focus between a parent view and its child view.
632 * Child views are shown side-by-side to their parent view, provided
633 * there is enough screen estate.
635 * When a new view is opened from within a parent view, this new view
636 * becomes a child view of the parent view, replacing any existing child.
638 * When a new view is opened from within a child view, this new view
639 * becomes a parent view which will obscure the views below until the
640 * user quits the new parent view by typing 'q'.
642 * This list of views contains parent views only.
643 * Child views are only pointed to by their parent view.
644 */
645 TAILQ_HEAD(tog_view_list_head, tog_view);
647 struct tog_view {
648 TAILQ_ENTRY(tog_view) entry;
649 WINDOW *window;
650 PANEL *panel;
651 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
652 int resized_y, resized_x; /* begin_y/x based on user resizing */
653 int maxx, x; /* max column and current start column */
654 int lines, cols; /* copies of LINES and COLS */
655 int nscrolled, offset; /* lines scrolled and hsplit line offset */
656 int gline, hiline; /* navigate to and highlight this nG line */
657 int ch, count; /* current keymap and count prefix */
658 int resized; /* set when in a resize event */
659 int focussed; /* Only set on one parent or child view at a time. */
660 int dying;
661 struct tog_view *parent;
662 struct tog_view *child;
664 /*
665 * This flag is initially set on parent views when a new child view
666 * is created. It gets toggled when the 'Tab' key switches focus
667 * between parent and child.
668 * The flag indicates whether focus should be passed on to our child
669 * view if this parent view gets picked for focus after another parent
670 * view was closed. This prevents child views from losing focus in such
671 * situations.
672 */
673 int focus_child;
675 enum tog_view_mode mode;
676 /* type-specific state */
677 enum tog_view_type type;
678 union {
679 struct tog_diff_view_state diff;
680 struct tog_log_view_state log;
681 struct tog_blame_view_state blame;
682 struct tog_tree_view_state tree;
683 struct tog_ref_view_state ref;
684 struct tog_help_view_state help;
685 } state;
687 const struct got_error *(*show)(struct tog_view *);
688 const struct got_error *(*input)(struct tog_view **,
689 struct tog_view *, int);
690 const struct got_error *(*reset)(struct tog_view *);
691 const struct got_error *(*resize)(struct tog_view *, int);
692 const struct got_error *(*close)(struct tog_view *);
694 const struct got_error *(*search_start)(struct tog_view *);
695 const struct got_error *(*search_next)(struct tog_view *);
696 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
697 int **, int **, int **, int **);
698 int search_started;
699 int searching;
700 #define TOG_SEARCH_FORWARD 1
701 #define TOG_SEARCH_BACKWARD 2
702 int search_next_done;
703 #define TOG_SEARCH_HAVE_MORE 1
704 #define TOG_SEARCH_NO_MORE 2
705 #define TOG_SEARCH_HAVE_NONE 3
706 regex_t regex;
707 regmatch_t regmatch;
708 const char *action;
709 };
711 static const struct got_error *open_diff_view(struct tog_view *,
712 struct got_object_id *, struct got_object_id *,
713 const char *, const char *, int, int, int, struct tog_view *,
714 struct got_repository *);
715 static const struct got_error *show_diff_view(struct tog_view *);
716 static const struct got_error *input_diff_view(struct tog_view **,
717 struct tog_view *, int);
718 static const struct got_error *reset_diff_view(struct tog_view *);
719 static const struct got_error* close_diff_view(struct tog_view *);
720 static const struct got_error *search_start_diff_view(struct tog_view *);
721 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
722 size_t *, int **, int **, int **, int **);
723 static const struct got_error *search_next_view_match(struct tog_view *);
725 static const struct got_error *open_log_view(struct tog_view *,
726 struct got_object_id *, struct got_repository *,
727 const char *, const char *, int);
728 static const struct got_error * show_log_view(struct tog_view *);
729 static const struct got_error *input_log_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *resize_log_view(struct tog_view *, int);
732 static const struct got_error *close_log_view(struct tog_view *);
733 static const struct got_error *search_start_log_view(struct tog_view *);
734 static const struct got_error *search_next_log_view(struct tog_view *);
736 static const struct got_error *open_blame_view(struct tog_view *, char *,
737 struct got_object_id *, struct got_repository *);
738 static const struct got_error *show_blame_view(struct tog_view *);
739 static const struct got_error *input_blame_view(struct tog_view **,
740 struct tog_view *, int);
741 static const struct got_error *reset_blame_view(struct tog_view *);
742 static const struct got_error *close_blame_view(struct tog_view *);
743 static const struct got_error *search_start_blame_view(struct tog_view *);
744 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
745 size_t *, int **, int **, int **, int **);
747 static const struct got_error *open_tree_view(struct tog_view *,
748 struct got_object_id *, const char *, struct got_repository *);
749 static const struct got_error *show_tree_view(struct tog_view *);
750 static const struct got_error *input_tree_view(struct tog_view **,
751 struct tog_view *, int);
752 static const struct got_error *close_tree_view(struct tog_view *);
753 static const struct got_error *search_start_tree_view(struct tog_view *);
754 static const struct got_error *search_next_tree_view(struct tog_view *);
756 static const struct got_error *open_ref_view(struct tog_view *,
757 struct got_repository *);
758 static const struct got_error *show_ref_view(struct tog_view *);
759 static const struct got_error *input_ref_view(struct tog_view **,
760 struct tog_view *, int);
761 static const struct got_error *close_ref_view(struct tog_view *);
762 static const struct got_error *search_start_ref_view(struct tog_view *);
763 static const struct got_error *search_next_ref_view(struct tog_view *);
765 static const struct got_error *open_help_view(struct tog_view *,
766 struct tog_view *);
767 static const struct got_error *show_help_view(struct tog_view *);
768 static const struct got_error *input_help_view(struct tog_view **,
769 struct tog_view *, int);
770 static const struct got_error *reset_help_view(struct tog_view *);
771 static const struct got_error* close_help_view(struct tog_view *);
772 static const struct got_error *search_start_help_view(struct tog_view *);
773 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
774 size_t *, int **, int **, int **, int **);
776 static volatile sig_atomic_t tog_sigwinch_received;
777 static volatile sig_atomic_t tog_sigpipe_received;
778 static volatile sig_atomic_t tog_sigcont_received;
779 static volatile sig_atomic_t tog_sigint_received;
780 static volatile sig_atomic_t tog_sigterm_received;
782 static void
783 tog_sigwinch(int signo)
785 tog_sigwinch_received = 1;
788 static void
789 tog_sigpipe(int signo)
791 tog_sigpipe_received = 1;
794 static void
795 tog_sigcont(int signo)
797 tog_sigcont_received = 1;
800 static void
801 tog_sigint(int signo)
803 tog_sigint_received = 1;
806 static void
807 tog_sigterm(int signo)
809 tog_sigterm_received = 1;
812 static int
813 tog_fatal_signal_received(void)
815 return (tog_sigpipe_received ||
816 tog_sigint_received || tog_sigterm_received);
819 static const struct got_error *
820 view_close(struct tog_view *view)
822 const struct got_error *err = NULL, *child_err = NULL;
824 if (view->child) {
825 child_err = view_close(view->child);
826 view->child = NULL;
828 if (view->close)
829 err = view->close(view);
830 if (view->panel)
831 del_panel(view->panel);
832 if (view->window)
833 delwin(view->window);
834 free(view);
835 return err ? err : child_err;
838 static struct tog_view *
839 view_open(int nlines, int ncols, int begin_y, int begin_x,
840 enum tog_view_type type)
842 struct tog_view *view = calloc(1, sizeof(*view));
844 if (view == NULL)
845 return NULL;
847 view->type = type;
848 view->lines = LINES;
849 view->cols = COLS;
850 view->nlines = nlines ? nlines : LINES - begin_y;
851 view->ncols = ncols ? ncols : COLS - begin_x;
852 view->begin_y = begin_y;
853 view->begin_x = begin_x;
854 view->window = newwin(nlines, ncols, begin_y, begin_x);
855 if (view->window == NULL) {
856 view_close(view);
857 return NULL;
859 view->panel = new_panel(view->window);
860 if (view->panel == NULL ||
861 set_panel_userptr(view->panel, view) != OK) {
862 view_close(view);
863 return NULL;
866 keypad(view->window, TRUE);
867 return view;
870 static int
871 view_split_begin_x(int begin_x)
873 if (begin_x > 0 || COLS < 120)
874 return 0;
875 return (COLS - MAX(COLS / 2, 80));
878 /* XXX Stub till we decide what to do. */
879 static int
880 view_split_begin_y(int lines)
882 return lines * HSPLIT_SCALE;
885 static const struct got_error *view_resize(struct tog_view *);
887 static const struct got_error *
888 view_splitscreen(struct tog_view *view)
890 const struct got_error *err = NULL;
892 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
893 if (view->resized_y && view->resized_y < view->lines)
894 view->begin_y = view->resized_y;
895 else
896 view->begin_y = view_split_begin_y(view->nlines);
897 view->begin_x = 0;
898 } else if (!view->resized) {
899 if (view->resized_x && view->resized_x < view->cols - 1 &&
900 view->cols > 119)
901 view->begin_x = view->resized_x;
902 else
903 view->begin_x = view_split_begin_x(0);
904 view->begin_y = 0;
906 view->nlines = LINES - view->begin_y;
907 view->ncols = COLS - view->begin_x;
908 view->lines = LINES;
909 view->cols = COLS;
910 err = view_resize(view);
911 if (err)
912 return err;
914 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
915 view->parent->nlines = view->begin_y;
917 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
918 return got_error_from_errno("mvwin");
920 return NULL;
923 static const struct got_error *
924 view_fullscreen(struct tog_view *view)
926 const struct got_error *err = NULL;
928 view->begin_x = 0;
929 view->begin_y = view->resized ? view->begin_y : 0;
930 view->nlines = view->resized ? view->nlines : LINES;
931 view->ncols = COLS;
932 view->lines = LINES;
933 view->cols = COLS;
934 err = view_resize(view);
935 if (err)
936 return err;
938 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
939 return got_error_from_errno("mvwin");
941 return NULL;
944 static int
945 view_is_parent_view(struct tog_view *view)
947 return view->parent == NULL;
950 static int
951 view_is_splitscreen(struct tog_view *view)
953 return view->begin_x > 0 || view->begin_y > 0;
956 static int
957 view_is_fullscreen(struct tog_view *view)
959 return view->nlines == LINES && view->ncols == COLS;
962 static int
963 view_is_hsplit_top(struct tog_view *view)
965 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
966 view_is_splitscreen(view->child);
969 static void
970 view_border(struct tog_view *view)
972 PANEL *panel;
973 const struct tog_view *view_above;
975 if (view->parent)
976 return view_border(view->parent);
978 panel = panel_above(view->panel);
979 if (panel == NULL)
980 return;
982 view_above = panel_userptr(panel);
983 if (view->mode == TOG_VIEW_SPLIT_HRZN)
984 mvwhline(view->window, view_above->begin_y - 1,
985 view->begin_x, ACS_HLINE, view->ncols);
986 else
987 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
988 ACS_VLINE, view->nlines);
991 static const struct got_error *view_init_hsplit(struct tog_view *, int);
992 static const struct got_error *request_log_commits(struct tog_view *);
993 static const struct got_error *offset_selection_down(struct tog_view *);
994 static void offset_selection_up(struct tog_view *);
995 static void view_get_split(struct tog_view *, int *, int *);
997 static const struct got_error *
998 view_resize(struct tog_view *view)
1000 const struct got_error *err = NULL;
1001 int dif, nlines, ncols;
1003 dif = LINES - view->lines; /* line difference */
1005 if (view->lines > LINES)
1006 nlines = view->nlines - (view->lines - LINES);
1007 else
1008 nlines = view->nlines + (LINES - view->lines);
1009 if (view->cols > COLS)
1010 ncols = view->ncols - (view->cols - COLS);
1011 else
1012 ncols = view->ncols + (COLS - view->cols);
1014 if (view->child) {
1015 int hs = view->child->begin_y;
1017 if (!view_is_fullscreen(view))
1018 view->child->begin_x = view_split_begin_x(view->begin_x);
1019 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1020 view->child->begin_x == 0) {
1021 ncols = COLS;
1023 view_fullscreen(view->child);
1024 if (view->child->focussed)
1025 show_panel(view->child->panel);
1026 else
1027 show_panel(view->panel);
1028 } else {
1029 ncols = view->child->begin_x;
1031 view_splitscreen(view->child);
1032 show_panel(view->child->panel);
1035 * XXX This is ugly and needs to be moved into the above
1036 * logic but "works" for now and my attempts at moving it
1037 * break either 'tab' or 'F' key maps in horizontal splits.
1039 if (hs) {
1040 err = view_splitscreen(view->child);
1041 if (err)
1042 return err;
1043 if (dif < 0) { /* top split decreased */
1044 err = offset_selection_down(view);
1045 if (err)
1046 return err;
1048 view_border(view);
1049 update_panels();
1050 doupdate();
1051 show_panel(view->child->panel);
1052 nlines = view->nlines;
1054 } else if (view->parent == NULL)
1055 ncols = COLS;
1057 if (view->resize && dif > 0) {
1058 err = view->resize(view, dif);
1059 if (err)
1060 return err;
1063 if (wresize(view->window, nlines, ncols) == ERR)
1064 return got_error_from_errno("wresize");
1065 if (replace_panel(view->panel, view->window) == ERR)
1066 return got_error_from_errno("replace_panel");
1067 wclear(view->window);
1069 view->nlines = nlines;
1070 view->ncols = ncols;
1071 view->lines = LINES;
1072 view->cols = COLS;
1074 return NULL;
1077 static const struct got_error *
1078 resize_log_view(struct tog_view *view, int increase)
1080 struct tog_log_view_state *s = &view->state.log;
1081 const struct got_error *err = NULL;
1082 int n = 0;
1084 if (s->selected_entry)
1085 n = s->selected_entry->idx + view->lines - s->selected;
1088 * Request commits to account for the increased
1089 * height so we have enough to populate the view.
1091 if (s->commits->ncommits < n) {
1092 view->nscrolled = n - s->commits->ncommits + increase + 1;
1093 err = request_log_commits(view);
1096 return err;
1099 static void
1100 view_adjust_offset(struct tog_view *view, int n)
1102 if (n == 0)
1103 return;
1105 if (view->parent && view->parent->offset) {
1106 if (view->parent->offset + n >= 0)
1107 view->parent->offset += n;
1108 else
1109 view->parent->offset = 0;
1110 } else if (view->offset) {
1111 if (view->offset - n >= 0)
1112 view->offset -= n;
1113 else
1114 view->offset = 0;
1118 static const struct got_error *
1119 view_resize_split(struct tog_view *view, int resize)
1121 const struct got_error *err = NULL;
1122 struct tog_view *v = NULL;
1124 if (view->parent)
1125 v = view->parent;
1126 else
1127 v = view;
1129 if (!v->child || !view_is_splitscreen(v->child))
1130 return NULL;
1132 v->resized = v->child->resized = resize; /* lock for resize event */
1134 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1135 if (v->child->resized_y)
1136 v->child->begin_y = v->child->resized_y;
1137 if (view->parent)
1138 v->child->begin_y -= resize;
1139 else
1140 v->child->begin_y += resize;
1141 if (v->child->begin_y < 3) {
1142 view->count = 0;
1143 v->child->begin_y = 3;
1144 } else if (v->child->begin_y > LINES - 1) {
1145 view->count = 0;
1146 v->child->begin_y = LINES - 1;
1148 v->ncols = COLS;
1149 v->child->ncols = COLS;
1150 view_adjust_offset(view, resize);
1151 err = view_init_hsplit(v, v->child->begin_y);
1152 if (err)
1153 return err;
1154 v->child->resized_y = v->child->begin_y;
1155 } else {
1156 if (v->child->resized_x)
1157 v->child->begin_x = v->child->resized_x;
1158 if (view->parent)
1159 v->child->begin_x -= resize;
1160 else
1161 v->child->begin_x += resize;
1162 if (v->child->begin_x < 11) {
1163 view->count = 0;
1164 v->child->begin_x = 11;
1165 } else if (v->child->begin_x > COLS - 1) {
1166 view->count = 0;
1167 v->child->begin_x = COLS - 1;
1169 v->child->resized_x = v->child->begin_x;
1172 v->child->mode = v->mode;
1173 v->child->nlines = v->lines - v->child->begin_y;
1174 v->child->ncols = v->cols - v->child->begin_x;
1175 v->focus_child = 1;
1177 err = view_fullscreen(v);
1178 if (err)
1179 return err;
1180 err = view_splitscreen(v->child);
1181 if (err)
1182 return err;
1184 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1185 err = offset_selection_down(v->child);
1186 if (err)
1187 return err;
1190 if (v->resize)
1191 err = v->resize(v, 0);
1192 else if (v->child->resize)
1193 err = v->child->resize(v->child, 0);
1195 v->resized = v->child->resized = 0;
1197 return err;
1200 static void
1201 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1203 struct tog_view *v = src->child ? src->child : src;
1205 dst->resized_x = v->resized_x;
1206 dst->resized_y = v->resized_y;
1209 static const struct got_error *
1210 view_close_child(struct tog_view *view)
1212 const struct got_error *err = NULL;
1214 if (view->child == NULL)
1215 return NULL;
1217 err = view_close(view->child);
1218 view->child = NULL;
1219 return err;
1222 static const struct got_error *
1223 view_set_child(struct tog_view *view, struct tog_view *child)
1225 const struct got_error *err = NULL;
1227 view->child = child;
1228 child->parent = view;
1230 err = view_resize(view);
1231 if (err)
1232 return err;
1234 if (view->child->resized_x || view->child->resized_y)
1235 err = view_resize_split(view, 0);
1237 return err;
1240 static const struct got_error *view_dispatch_request(struct tog_view **,
1241 struct tog_view *, enum tog_view_type, int, int);
1243 static const struct got_error *
1244 view_request_new(struct tog_view **requested, struct tog_view *view,
1245 enum tog_view_type request)
1247 struct tog_view *new_view = NULL;
1248 const struct got_error *err;
1249 int y = 0, x = 0;
1251 *requested = NULL;
1253 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1254 view_get_split(view, &y, &x);
1256 err = view_dispatch_request(&new_view, view, request, y, x);
1257 if (err)
1258 return err;
1260 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1261 request != TOG_VIEW_HELP) {
1262 err = view_init_hsplit(view, y);
1263 if (err)
1264 return err;
1267 view->focussed = 0;
1268 new_view->focussed = 1;
1269 new_view->mode = view->mode;
1270 new_view->nlines = request == TOG_VIEW_HELP ?
1271 view->lines : view->lines - y;
1273 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1274 view_transfer_size(new_view, view);
1275 err = view_close_child(view);
1276 if (err)
1277 return err;
1278 err = view_set_child(view, new_view);
1279 if (err)
1280 return err;
1281 view->focus_child = 1;
1282 } else
1283 *requested = new_view;
1285 return NULL;
1288 static void
1289 tog_resizeterm(void)
1291 int cols, lines;
1292 struct winsize size;
1294 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1295 cols = 80; /* Default */
1296 lines = 24;
1297 } else {
1298 cols = size.ws_col;
1299 lines = size.ws_row;
1301 resize_term(lines, cols);
1304 static const struct got_error *
1305 view_search_start(struct tog_view *view, int fast_refresh)
1307 const struct got_error *err = NULL;
1308 struct tog_view *v = view;
1309 char pattern[1024];
1310 int ret;
1312 if (view->search_started) {
1313 regfree(&view->regex);
1314 view->searching = 0;
1315 memset(&view->regmatch, 0, sizeof(view->regmatch));
1317 view->search_started = 0;
1319 if (view->nlines < 1)
1320 return NULL;
1322 if (view_is_hsplit_top(view))
1323 v = view->child;
1324 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1325 v = view->parent;
1327 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1328 wclrtoeol(v->window);
1330 nodelay(v->window, FALSE); /* block for search term input */
1331 nocbreak();
1332 echo();
1333 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1334 wrefresh(v->window);
1335 cbreak();
1336 noecho();
1337 nodelay(v->window, TRUE);
1338 if (!fast_refresh && !using_mock_io)
1339 halfdelay(10);
1340 if (ret == ERR)
1341 return NULL;
1343 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1344 err = view->search_start(view);
1345 if (err) {
1346 regfree(&view->regex);
1347 return err;
1349 view->search_started = 1;
1350 view->searching = TOG_SEARCH_FORWARD;
1351 view->search_next_done = 0;
1352 view->search_next(view);
1355 return NULL;
1358 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1359 static const struct got_error *
1360 switch_split(struct tog_view *view)
1362 const struct got_error *err = NULL;
1363 struct tog_view *v = NULL;
1365 if (view->parent)
1366 v = view->parent;
1367 else
1368 v = view;
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1371 v->mode = TOG_VIEW_SPLIT_VERT;
1372 else
1373 v->mode = TOG_VIEW_SPLIT_HRZN;
1375 if (!v->child)
1376 return NULL;
1377 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1378 v->mode = TOG_VIEW_SPLIT_NONE;
1380 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1381 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1382 v->child->begin_y = v->child->resized_y;
1383 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1384 v->child->begin_x = v->child->resized_x;
1387 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1388 v->ncols = COLS;
1389 v->child->ncols = COLS;
1390 v->child->nscrolled = LINES - v->child->nlines;
1392 err = view_init_hsplit(v, v->child->begin_y);
1393 if (err)
1394 return err;
1396 v->child->mode = v->mode;
1397 v->child->nlines = v->lines - v->child->begin_y;
1398 v->focus_child = 1;
1400 err = view_fullscreen(v);
1401 if (err)
1402 return err;
1403 err = view_splitscreen(v->child);
1404 if (err)
1405 return err;
1407 if (v->mode == TOG_VIEW_SPLIT_NONE)
1408 v->mode = TOG_VIEW_SPLIT_VERT;
1409 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1410 err = offset_selection_down(v);
1411 if (err)
1412 return err;
1413 err = offset_selection_down(v->child);
1414 if (err)
1415 return err;
1416 } else {
1417 offset_selection_up(v);
1418 offset_selection_up(v->child);
1420 if (v->resize)
1421 err = v->resize(v, 0);
1422 else if (v->child->resize)
1423 err = v->child->resize(v->child, 0);
1425 return err;
1429 * Strip trailing whitespace from str starting at byte *n;
1430 * if *n < 0, use strlen(str). Return new str length in *n.
1432 static void
1433 strip_trailing_ws(char *str, int *n)
1435 size_t x = *n;
1437 if (str == NULL || *str == '\0')
1438 return;
1440 if (x < 0)
1441 x = strlen(str);
1443 while (x-- > 0 && isspace((unsigned char)str[x]))
1444 str[x] = '\0';
1446 *n = x + 1;
1450 * Extract visible substring of line y from the curses screen
1451 * and strip trailing whitespace. If vline is set, overwrite
1452 * line[vline] with '|' because the ACS_VLINE character is
1453 * written out as 'x'. Write the line to file f.
1455 static const struct got_error *
1456 view_write_line(FILE *f, int y, int vline)
1458 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1459 int r, w;
1461 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1462 if (r == ERR)
1463 return got_error_fmt(GOT_ERR_RANGE,
1464 "failed to extract line %d", y);
1467 * In some views, lines are padded with blanks to COLS width.
1468 * Strip them so we can diff without the -b flag when testing.
1470 strip_trailing_ws(line, &r);
1472 if (vline > 0)
1473 line[vline] = '|';
1475 w = fprintf(f, "%s\n", line);
1476 if (w != r + 1) /* \n */
1477 return got_ferror(f, GOT_ERR_IO);
1479 return NULL;
1483 * Capture the visible curses screen by writing each line to the
1484 * file at the path set via the TOG_SCR_DUMP environment variable.
1486 static const struct got_error *
1487 screendump(struct tog_view *view)
1489 const struct got_error *err;
1490 int i;
1492 err = got_opentemp_truncate(tog_io.sdump);
1493 if (err)
1494 return err;
1496 if ((view->child && view->child->begin_x) ||
1497 (view->parent && view->begin_x)) {
1498 int ncols = view->child ? view->ncols : view->parent->ncols;
1500 /* vertical splitscreen */
1501 for (i = 0; i < view->nlines; ++i) {
1502 err = view_write_line(tog_io.sdump, i, ncols - 1);
1503 if (err)
1504 goto done;
1506 } else {
1507 int hline = 0;
1509 /* fullscreen or horizontal splitscreen */
1510 if ((view->child && view->child->begin_y) ||
1511 (view->parent && view->begin_y)) /* hsplit */
1512 hline = view->child ?
1513 view->child->begin_y : view->begin_y;
1515 for (i = 0; i < view->lines; i++) {
1516 if (hline && i == hline - 1) {
1517 int c;
1519 /* ACS_HLINE writes out as 'q', overwrite it */
1520 for (c = 0; c < view->cols; ++c)
1521 fputc('-', tog_io.sdump);
1522 fputc('\n', tog_io.sdump);
1523 continue;
1526 err = view_write_line(tog_io.sdump, i, 0);
1527 if (err)
1528 goto done;
1532 done:
1533 return err;
1537 * Compute view->count from numeric input. Assign total to view->count and
1538 * return first non-numeric key entered.
1540 static int
1541 get_compound_key(struct tog_view *view, int c)
1543 struct tog_view *v = view;
1544 int x, n = 0;
1546 if (view_is_hsplit_top(view))
1547 v = view->child;
1548 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1549 v = view->parent;
1551 view->count = 0;
1552 cbreak(); /* block for input */
1553 nodelay(view->window, FALSE);
1554 wmove(v->window, v->nlines - 1, 0);
1555 wclrtoeol(v->window);
1556 waddch(v->window, ':');
1558 do {
1559 x = getcurx(v->window);
1560 if (x != ERR && x < view->ncols) {
1561 waddch(v->window, c);
1562 wrefresh(v->window);
1566 * Don't overflow. Max valid request should be the greatest
1567 * between the longest and total lines; cap at 10 million.
1569 if (n >= 9999999)
1570 n = 9999999;
1571 else
1572 n = n * 10 + (c - '0');
1573 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1575 if (c == 'G' || c == 'g') { /* nG key map */
1576 view->gline = view->hiline = n;
1577 n = 0;
1578 c = 0;
1581 /* Massage excessive or inapplicable values at the input handler. */
1582 view->count = n;
1584 return c;
1587 static void
1588 action_report(struct tog_view *view)
1590 struct tog_view *v = view;
1592 if (view_is_hsplit_top(view))
1593 v = view->child;
1594 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1595 v = view->parent;
1597 wmove(v->window, v->nlines - 1, 0);
1598 wclrtoeol(v->window);
1599 wprintw(v->window, ":%s", view->action);
1600 wrefresh(v->window);
1603 * Clear action status report. Only clear in blame view
1604 * once annotating is complete, otherwise it's too fast.
1606 if (view->type == TOG_VIEW_BLAME) {
1607 if (view->state.blame.blame_complete)
1608 view->action = NULL;
1609 } else
1610 view->action = NULL;
1614 * Read the next line from the test script and assign
1615 * key instruction to *ch. If at EOF, set the *done flag.
1617 static const struct got_error *
1618 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1620 const struct got_error *err = NULL;
1621 char *line = NULL;
1622 size_t linesz = 0;
1624 if (view->count && --view->count) {
1625 *ch = view->ch;
1626 return NULL;
1627 } else
1628 *ch = -1;
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;
1640 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1641 tog_io.wait_for_ui = 1;
1642 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1643 *ch = KEY_ENTER;
1644 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1645 *ch = KEY_RIGHT;
1646 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1647 *ch = KEY_LEFT;
1648 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1649 *ch = KEY_DOWN;
1650 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1651 *ch = KEY_UP;
1652 else if (strncasecmp(line, "TAB", 3) == 0)
1653 *ch = '\t';
1654 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1655 *ch = TOG_KEY_SCRDUMP;
1656 else if (isdigit((unsigned char)*line)) {
1657 char *t = line;
1659 while (isdigit((unsigned char)*t))
1660 ++t;
1661 view->ch = *ch = *t;
1662 *t = '\0';
1663 /* ignore error, view->count is 0 if instruction is invalid */
1664 view->count = strtonum(line, 0, INT_MAX, NULL);
1665 } else
1666 *ch = *line;
1668 done:
1669 free(line);
1670 return err;
1673 static const struct got_error *
1674 view_input(struct tog_view **new, int *done, struct tog_view *view,
1675 struct tog_view_list_head *views, int fast_refresh)
1677 const struct got_error *err = NULL;
1678 struct tog_view *v;
1679 int ch, errcode;
1681 *new = NULL;
1683 if (view->action)
1684 action_report(view);
1686 /* Clear "no matches" indicator. */
1687 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1688 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1689 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1690 view->count = 0;
1693 if (view->searching && !view->search_next_done) {
1694 errcode = pthread_mutex_unlock(&tog_mutex);
1695 if (errcode)
1696 return got_error_set_errno(errcode,
1697 "pthread_mutex_unlock");
1698 sched_yield();
1699 errcode = pthread_mutex_lock(&tog_mutex);
1700 if (errcode)
1701 return got_error_set_errno(errcode,
1702 "pthread_mutex_lock");
1703 view->search_next(view);
1704 return NULL;
1707 /* Allow threads to make progress while we are waiting for input. */
1708 errcode = pthread_mutex_unlock(&tog_mutex);
1709 if (errcode)
1710 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1712 if (using_mock_io) {
1713 err = tog_read_script_key(tog_io.f, view, &ch, done);
1714 if (err) {
1715 errcode = pthread_mutex_lock(&tog_mutex);
1716 return err;
1718 } else if (view->count && --view->count) {
1719 cbreak();
1720 nodelay(view->window, TRUE);
1721 ch = wgetch(view->window);
1722 /* let C-g or backspace abort unfinished count */
1723 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1724 view->count = 0;
1725 else
1726 ch = view->ch;
1727 } else {
1728 ch = wgetch(view->window);
1729 if (ch >= '1' && ch <= '9')
1730 view->ch = ch = get_compound_key(view, ch);
1732 if (view->hiline && ch != ERR && ch != 0)
1733 view->hiline = 0; /* key pressed, clear line highlight */
1734 nodelay(view->window, TRUE);
1735 errcode = pthread_mutex_lock(&tog_mutex);
1736 if (errcode)
1737 return got_error_set_errno(errcode, "pthread_mutex_lock");
1739 if (tog_sigwinch_received || tog_sigcont_received) {
1740 tog_resizeterm();
1741 tog_sigwinch_received = 0;
1742 tog_sigcont_received = 0;
1743 TAILQ_FOREACH(v, views, entry) {
1744 err = view_resize(v);
1745 if (err)
1746 return err;
1747 err = v->input(new, v, KEY_RESIZE);
1748 if (err)
1749 return err;
1750 if (v->child) {
1751 err = view_resize(v->child);
1752 if (err)
1753 return err;
1754 err = v->child->input(new, v->child,
1755 KEY_RESIZE);
1756 if (err)
1757 return err;
1758 if (v->child->resized_x || v->child->resized_y) {
1759 err = view_resize_split(v, 0);
1760 if (err)
1761 return err;
1767 switch (ch) {
1768 case '?':
1769 case 'H':
1770 case KEY_F(1):
1771 if (view->type == TOG_VIEW_HELP)
1772 err = view->reset(view);
1773 else
1774 err = view_request_new(new, view, TOG_VIEW_HELP);
1775 break;
1776 case '\t':
1777 view->count = 0;
1778 if (view->child) {
1779 view->focussed = 0;
1780 view->child->focussed = 1;
1781 view->focus_child = 1;
1782 } else if (view->parent) {
1783 view->focussed = 0;
1784 view->parent->focussed = 1;
1785 view->parent->focus_child = 0;
1786 if (!view_is_splitscreen(view)) {
1787 if (view->parent->resize) {
1788 err = view->parent->resize(view->parent,
1789 0);
1790 if (err)
1791 return err;
1793 offset_selection_up(view->parent);
1794 err = view_fullscreen(view->parent);
1795 if (err)
1796 return err;
1799 break;
1800 case 'q':
1801 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1802 if (view->parent->resize) {
1803 /* might need more commits to fill fullscreen */
1804 err = view->parent->resize(view->parent, 0);
1805 if (err)
1806 break;
1808 offset_selection_up(view->parent);
1810 err = view->input(new, view, ch);
1811 view->dying = 1;
1812 break;
1813 case 'Q':
1814 *done = 1;
1815 break;
1816 case 'F':
1817 view->count = 0;
1818 if (view_is_parent_view(view)) {
1819 if (view->child == NULL)
1820 break;
1821 if (view_is_splitscreen(view->child)) {
1822 view->focussed = 0;
1823 view->child->focussed = 1;
1824 err = view_fullscreen(view->child);
1825 } else {
1826 err = view_splitscreen(view->child);
1827 if (!err)
1828 err = view_resize_split(view, 0);
1830 if (err)
1831 break;
1832 err = view->child->input(new, view->child,
1833 KEY_RESIZE);
1834 } else {
1835 if (view_is_splitscreen(view)) {
1836 view->parent->focussed = 0;
1837 view->focussed = 1;
1838 err = view_fullscreen(view);
1839 } else {
1840 err = view_splitscreen(view);
1841 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1842 err = view_resize(view->parent);
1843 if (!err)
1844 err = view_resize_split(view, 0);
1846 if (err)
1847 break;
1848 err = view->input(new, view, KEY_RESIZE);
1850 if (err)
1851 break;
1852 if (view->resize) {
1853 err = view->resize(view, 0);
1854 if (err)
1855 break;
1857 if (view->parent) {
1858 if (view->parent->resize) {
1859 err = view->parent->resize(view->parent, 0);
1860 if (err != NULL)
1861 break;
1863 err = offset_selection_down(view->parent);
1864 if (err != NULL)
1865 break;
1867 err = offset_selection_down(view);
1868 break;
1869 case 'S':
1870 view->count = 0;
1871 err = switch_split(view);
1872 break;
1873 case '-':
1874 err = view_resize_split(view, -1);
1875 break;
1876 case '+':
1877 err = view_resize_split(view, 1);
1878 break;
1879 case KEY_RESIZE:
1880 break;
1881 case '/':
1882 view->count = 0;
1883 if (view->search_start)
1884 view_search_start(view, fast_refresh);
1885 else
1886 err = view->input(new, view, ch);
1887 break;
1888 case 'N':
1889 case 'n':
1890 if (view->search_started && view->search_next) {
1891 view->searching = (ch == 'n' ?
1892 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1893 view->search_next_done = 0;
1894 view->search_next(view);
1895 } else
1896 err = view->input(new, view, ch);
1897 break;
1898 case 'A':
1899 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1900 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1901 view->action = "Patience diff algorithm";
1902 } else {
1903 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1904 view->action = "Myers diff algorithm";
1906 TAILQ_FOREACH(v, views, entry) {
1907 if (v->reset) {
1908 err = v->reset(v);
1909 if (err)
1910 return err;
1912 if (v->child && v->child->reset) {
1913 err = v->child->reset(v->child);
1914 if (err)
1915 return err;
1918 break;
1919 case TOG_KEY_SCRDUMP:
1920 err = screendump(view);
1921 break;
1922 default:
1923 err = view->input(new, view, ch);
1924 break;
1927 return err;
1930 static int
1931 view_needs_focus_indication(struct tog_view *view)
1933 if (view_is_parent_view(view)) {
1934 if (view->child == NULL || view->child->focussed)
1935 return 0;
1936 if (!view_is_splitscreen(view->child))
1937 return 0;
1938 } else if (!view_is_splitscreen(view))
1939 return 0;
1941 return view->focussed;
1944 static const struct got_error *
1945 tog_io_close(void)
1947 const struct got_error *err = NULL;
1949 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1950 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1951 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1952 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1953 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1954 err = got_ferror(tog_io.f, GOT_ERR_IO);
1955 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1956 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1958 return err;
1961 static const struct got_error *
1962 view_loop(struct tog_view *view)
1964 const struct got_error *err = NULL;
1965 struct tog_view_list_head views;
1966 struct tog_view *new_view;
1967 char *mode;
1968 int fast_refresh = 10;
1969 int done = 0, errcode;
1971 mode = getenv("TOG_VIEW_SPLIT_MODE");
1972 if (!mode || !(*mode == 'h' || *mode == 'H'))
1973 view->mode = TOG_VIEW_SPLIT_VERT;
1974 else
1975 view->mode = TOG_VIEW_SPLIT_HRZN;
1977 errcode = pthread_mutex_lock(&tog_mutex);
1978 if (errcode)
1979 return got_error_set_errno(errcode, "pthread_mutex_lock");
1981 TAILQ_INIT(&views);
1982 TAILQ_INSERT_HEAD(&views, view, entry);
1984 view->focussed = 1;
1985 err = view->show(view);
1986 if (err)
1987 return err;
1988 update_panels();
1989 doupdate();
1990 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1991 !tog_fatal_signal_received()) {
1992 /* Refresh fast during initialization, then become slower. */
1993 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1994 halfdelay(10); /* switch to once per second */
1996 err = view_input(&new_view, &done, view, &views, fast_refresh);
1997 if (err)
1998 break;
2000 if (view->dying && view == TAILQ_FIRST(&views) &&
2001 TAILQ_NEXT(view, entry) == NULL)
2002 done = 1;
2003 if (done) {
2004 struct tog_view *v;
2007 * When we quit, scroll the screen up a single line
2008 * so we don't lose any information.
2010 TAILQ_FOREACH(v, &views, entry) {
2011 wmove(v->window, 0, 0);
2012 wdeleteln(v->window);
2013 wnoutrefresh(v->window);
2014 if (v->child && !view_is_fullscreen(v)) {
2015 wmove(v->child->window, 0, 0);
2016 wdeleteln(v->child->window);
2017 wnoutrefresh(v->child->window);
2020 doupdate();
2023 if (view->dying) {
2024 struct tog_view *v, *prev = NULL;
2026 if (view_is_parent_view(view))
2027 prev = TAILQ_PREV(view, tog_view_list_head,
2028 entry);
2029 else if (view->parent)
2030 prev = view->parent;
2032 if (view->parent) {
2033 view->parent->child = NULL;
2034 view->parent->focus_child = 0;
2035 /* Restore fullscreen line height. */
2036 view->parent->nlines = view->parent->lines;
2037 err = view_resize(view->parent);
2038 if (err)
2039 break;
2040 /* Make resized splits persist. */
2041 view_transfer_size(view->parent, view);
2042 } else
2043 TAILQ_REMOVE(&views, view, entry);
2045 err = view_close(view);
2046 if (err)
2047 goto done;
2049 view = NULL;
2050 TAILQ_FOREACH(v, &views, entry) {
2051 if (v->focussed)
2052 break;
2054 if (view == NULL && new_view == NULL) {
2055 /* No view has focus. Try to pick one. */
2056 if (prev)
2057 view = prev;
2058 else if (!TAILQ_EMPTY(&views)) {
2059 view = TAILQ_LAST(&views,
2060 tog_view_list_head);
2062 if (view) {
2063 if (view->focus_child) {
2064 view->child->focussed = 1;
2065 view = view->child;
2066 } else
2067 view->focussed = 1;
2071 if (new_view) {
2072 struct tog_view *v, *t;
2073 /* Only allow one parent view per type. */
2074 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2075 if (v->type != new_view->type)
2076 continue;
2077 TAILQ_REMOVE(&views, v, entry);
2078 err = view_close(v);
2079 if (err)
2080 goto done;
2081 break;
2083 TAILQ_INSERT_TAIL(&views, new_view, entry);
2084 view = new_view;
2086 if (view && !done) {
2087 if (view_is_parent_view(view)) {
2088 if (view->child && view->child->focussed)
2089 view = view->child;
2090 } else {
2091 if (view->parent && view->parent->focussed)
2092 view = view->parent;
2094 show_panel(view->panel);
2095 if (view->child && view_is_splitscreen(view->child))
2096 show_panel(view->child->panel);
2097 if (view->parent && view_is_splitscreen(view)) {
2098 err = view->parent->show(view->parent);
2099 if (err)
2100 goto done;
2102 err = view->show(view);
2103 if (err)
2104 goto done;
2105 if (view->child) {
2106 err = view->child->show(view->child);
2107 if (err)
2108 goto done;
2110 update_panels();
2111 doupdate();
2114 done:
2115 while (!TAILQ_EMPTY(&views)) {
2116 const struct got_error *close_err;
2117 view = TAILQ_FIRST(&views);
2118 TAILQ_REMOVE(&views, view, entry);
2119 close_err = view_close(view);
2120 if (close_err && err == NULL)
2121 err = close_err;
2124 errcode = pthread_mutex_unlock(&tog_mutex);
2125 if (errcode && err == NULL)
2126 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2128 return err;
2131 __dead static void
2132 usage_log(void)
2134 endwin();
2135 fprintf(stderr,
2136 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2137 getprogname());
2138 exit(1);
2141 /* Create newly allocated wide-character string equivalent to a byte string. */
2142 static const struct got_error *
2143 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2145 char *vis = NULL;
2146 const struct got_error *err = NULL;
2148 *ws = NULL;
2149 *wlen = mbstowcs(NULL, s, 0);
2150 if (*wlen == (size_t)-1) {
2151 int vislen;
2152 if (errno != EILSEQ)
2153 return got_error_from_errno("mbstowcs");
2155 /* byte string invalid in current encoding; try to "fix" it */
2156 err = got_mbsavis(&vis, &vislen, s);
2157 if (err)
2158 return err;
2159 *wlen = mbstowcs(NULL, vis, 0);
2160 if (*wlen == (size_t)-1) {
2161 err = got_error_from_errno("mbstowcs"); /* give up */
2162 goto done;
2166 *ws = calloc(*wlen + 1, sizeof(**ws));
2167 if (*ws == NULL) {
2168 err = got_error_from_errno("calloc");
2169 goto done;
2172 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2173 err = got_error_from_errno("mbstowcs");
2174 done:
2175 free(vis);
2176 if (err) {
2177 free(*ws);
2178 *ws = NULL;
2179 *wlen = 0;
2181 return err;
2184 static const struct got_error *
2185 expand_tab(char **ptr, const char *src)
2187 char *dst;
2188 size_t len, n, idx = 0, sz = 0;
2190 *ptr = NULL;
2191 n = len = strlen(src);
2192 dst = malloc(n + 1);
2193 if (dst == NULL)
2194 return got_error_from_errno("malloc");
2196 while (idx < len && src[idx]) {
2197 const char c = src[idx];
2199 if (c == '\t') {
2200 size_t nb = TABSIZE - sz % TABSIZE;
2201 char *p;
2203 p = realloc(dst, n + nb);
2204 if (p == NULL) {
2205 free(dst);
2206 return got_error_from_errno("realloc");
2209 dst = p;
2210 n += nb;
2211 memset(dst + sz, ' ', nb);
2212 sz += nb;
2213 } else
2214 dst[sz++] = src[idx];
2215 ++idx;
2218 dst[sz] = '\0';
2219 *ptr = dst;
2220 return NULL;
2224 * Advance at most n columns from wline starting at offset off.
2225 * Return the index to the first character after the span operation.
2226 * Return the combined column width of all spanned wide character in
2227 * *rcol.
2229 static int
2230 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2232 int width, i, cols = 0;
2234 if (n == 0) {
2235 *rcol = cols;
2236 return off;
2239 for (i = off; wline[i] != L'\0'; ++i) {
2240 if (wline[i] == L'\t')
2241 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2242 else
2243 width = wcwidth(wline[i]);
2245 if (width == -1) {
2246 width = 1;
2247 wline[i] = L'.';
2250 if (cols + width > n)
2251 break;
2252 cols += width;
2255 *rcol = cols;
2256 return i;
2260 * Format a line for display, ensuring that it won't overflow a width limit.
2261 * With scrolling, the width returned refers to the scrolled version of the
2262 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2264 static const struct got_error *
2265 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2266 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2268 const struct got_error *err = NULL;
2269 int cols;
2270 wchar_t *wline = NULL;
2271 char *exstr = NULL;
2272 size_t wlen;
2273 int i, scrollx;
2275 *wlinep = NULL;
2276 *widthp = 0;
2278 if (expand) {
2279 err = expand_tab(&exstr, line);
2280 if (err)
2281 return err;
2284 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2285 free(exstr);
2286 if (err)
2287 return err;
2289 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2291 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2292 wline[wlen - 1] = L'\0';
2293 wlen--;
2295 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2296 wline[wlen - 1] = L'\0';
2297 wlen--;
2300 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2301 wline[i] = L'\0';
2303 if (widthp)
2304 *widthp = cols;
2305 if (scrollxp)
2306 *scrollxp = scrollx;
2307 if (err)
2308 free(wline);
2309 else
2310 *wlinep = wline;
2311 return err;
2314 static const struct got_error*
2315 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2316 struct got_object_id *id, struct got_repository *repo)
2318 static const struct got_error *err = NULL;
2319 struct got_reflist_entry *re;
2320 char *s;
2321 const char *name;
2323 *refs_str = NULL;
2325 TAILQ_FOREACH(re, refs, entry) {
2326 struct got_tag_object *tag = NULL;
2327 struct got_object_id *ref_id;
2328 int cmp;
2330 name = got_ref_get_name(re->ref);
2331 if (strcmp(name, GOT_REF_HEAD) == 0)
2332 continue;
2333 if (strncmp(name, "refs/", 5) == 0)
2334 name += 5;
2335 if (strncmp(name, "got/", 4) == 0 &&
2336 strncmp(name, "got/backup/", 11) != 0)
2337 continue;
2338 if (strncmp(name, "heads/", 6) == 0)
2339 name += 6;
2340 if (strncmp(name, "remotes/", 8) == 0) {
2341 name += 8;
2342 s = strstr(name, "/" GOT_REF_HEAD);
2343 if (s != NULL && s[strlen(s)] == '\0')
2344 continue;
2346 err = got_ref_resolve(&ref_id, repo, re->ref);
2347 if (err)
2348 break;
2349 if (strncmp(name, "tags/", 5) == 0) {
2350 err = got_object_open_as_tag(&tag, repo, ref_id);
2351 if (err) {
2352 if (err->code != GOT_ERR_OBJ_TYPE) {
2353 free(ref_id);
2354 break;
2356 /* Ref points at something other than a tag. */
2357 err = NULL;
2358 tag = NULL;
2361 cmp = got_object_id_cmp(tag ?
2362 got_object_tag_get_object_id(tag) : ref_id, id);
2363 free(ref_id);
2364 if (tag)
2365 got_object_tag_close(tag);
2366 if (cmp != 0)
2367 continue;
2368 s = *refs_str;
2369 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2370 s ? ", " : "", name) == -1) {
2371 err = got_error_from_errno("asprintf");
2372 free(s);
2373 *refs_str = NULL;
2374 break;
2376 free(s);
2379 return err;
2382 static const struct got_error *
2383 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2384 int col_tab_align)
2386 char *smallerthan;
2388 smallerthan = strchr(author, '<');
2389 if (smallerthan && smallerthan[1] != '\0')
2390 author = smallerthan + 1;
2391 author[strcspn(author, "@>")] = '\0';
2392 return format_line(wauthor, author_width, NULL, author, 0, limit,
2393 col_tab_align, 0);
2396 static const struct got_error *
2397 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2398 struct got_object_id *id, const size_t date_display_cols,
2399 int author_display_cols)
2401 struct tog_log_view_state *s = &view->state.log;
2402 const struct got_error *err = NULL;
2403 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2404 char *logmsg0 = NULL, *logmsg = NULL;
2405 char *author = NULL;
2406 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2407 int author_width, logmsg_width;
2408 char *newline, *line = NULL;
2409 int col, limit, scrollx;
2410 const int avail = view->ncols;
2411 struct tm tm;
2412 time_t committer_time;
2413 struct tog_color *tc;
2415 committer_time = got_object_commit_get_committer_time(commit);
2416 if (gmtime_r(&committer_time, &tm) == NULL)
2417 return got_error_from_errno("gmtime_r");
2418 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2419 return got_error(GOT_ERR_NO_SPACE);
2421 if (avail <= date_display_cols)
2422 limit = MIN(sizeof(datebuf) - 1, avail);
2423 else
2424 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2425 tc = get_color(&s->colors, TOG_COLOR_DATE);
2426 if (tc)
2427 wattr_on(view->window,
2428 COLOR_PAIR(tc->colorpair), NULL);
2429 waddnstr(view->window, datebuf, limit);
2430 if (tc)
2431 wattr_off(view->window,
2432 COLOR_PAIR(tc->colorpair), NULL);
2433 col = limit;
2434 if (col > avail)
2435 goto done;
2437 if (avail >= 120) {
2438 char *id_str;
2439 err = got_object_id_str(&id_str, id);
2440 if (err)
2441 goto done;
2442 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2443 if (tc)
2444 wattr_on(view->window,
2445 COLOR_PAIR(tc->colorpair), NULL);
2446 wprintw(view->window, "%.8s ", id_str);
2447 if (tc)
2448 wattr_off(view->window,
2449 COLOR_PAIR(tc->colorpair), NULL);
2450 free(id_str);
2451 col += 9;
2452 if (col > avail)
2453 goto done;
2456 if (s->use_committer)
2457 author = strdup(got_object_commit_get_committer(commit));
2458 else
2459 author = strdup(got_object_commit_get_author(commit));
2460 if (author == NULL) {
2461 err = got_error_from_errno("strdup");
2462 goto done;
2464 err = format_author(&wauthor, &author_width, author, avail - col, col);
2465 if (err)
2466 goto done;
2467 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2468 if (tc)
2469 wattr_on(view->window,
2470 COLOR_PAIR(tc->colorpair), NULL);
2471 waddwstr(view->window, wauthor);
2472 col += author_width;
2473 while (col < avail && author_width < author_display_cols + 2) {
2474 waddch(view->window, ' ');
2475 col++;
2476 author_width++;
2478 if (tc)
2479 wattr_off(view->window,
2480 COLOR_PAIR(tc->colorpair), NULL);
2481 if (col > avail)
2482 goto done;
2484 err = got_object_commit_get_logmsg(&logmsg0, commit);
2485 if (err)
2486 goto done;
2487 logmsg = logmsg0;
2488 while (*logmsg == '\n')
2489 logmsg++;
2490 newline = strchr(logmsg, '\n');
2491 if (newline)
2492 *newline = '\0';
2493 limit = avail - col;
2494 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2495 limit--; /* for the border */
2496 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2497 limit, col, 1);
2498 if (err)
2499 goto done;
2500 waddwstr(view->window, &wlogmsg[scrollx]);
2501 col += MAX(logmsg_width, 0);
2502 while (col < avail) {
2503 waddch(view->window, ' ');
2504 col++;
2506 done:
2507 free(logmsg0);
2508 free(wlogmsg);
2509 free(author);
2510 free(wauthor);
2511 free(line);
2512 return err;
2515 static struct commit_queue_entry *
2516 alloc_commit_queue_entry(struct got_commit_object *commit,
2517 struct got_object_id *id)
2519 struct commit_queue_entry *entry;
2520 struct got_object_id *dup;
2522 entry = calloc(1, sizeof(*entry));
2523 if (entry == NULL)
2524 return NULL;
2526 dup = got_object_id_dup(id);
2527 if (dup == NULL) {
2528 free(entry);
2529 return NULL;
2532 entry->id = dup;
2533 entry->commit = commit;
2534 return entry;
2537 static void
2538 pop_commit(struct commit_queue *commits)
2540 struct commit_queue_entry *entry;
2542 entry = TAILQ_FIRST(&commits->head);
2543 TAILQ_REMOVE(&commits->head, entry, entry);
2544 got_object_commit_close(entry->commit);
2545 commits->ncommits--;
2546 free(entry->id);
2547 free(entry);
2550 static void
2551 free_commits(struct commit_queue *commits)
2553 while (!TAILQ_EMPTY(&commits->head))
2554 pop_commit(commits);
2557 static const struct got_error *
2558 match_commit(int *have_match, struct got_object_id *id,
2559 struct got_commit_object *commit, regex_t *regex)
2561 const struct got_error *err = NULL;
2562 regmatch_t regmatch;
2563 char *id_str = NULL, *logmsg = NULL;
2565 *have_match = 0;
2567 err = got_object_id_str(&id_str, id);
2568 if (err)
2569 return err;
2571 err = got_object_commit_get_logmsg(&logmsg, commit);
2572 if (err)
2573 goto done;
2575 if (regexec(regex, got_object_commit_get_author(commit), 1,
2576 &regmatch, 0) == 0 ||
2577 regexec(regex, got_object_commit_get_committer(commit), 1,
2578 &regmatch, 0) == 0 ||
2579 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2580 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2581 *have_match = 1;
2582 done:
2583 free(id_str);
2584 free(logmsg);
2585 return err;
2588 static const struct got_error *
2589 queue_commits(struct tog_log_thread_args *a)
2591 const struct got_error *err = NULL;
2594 * We keep all commits open throughout the lifetime of the log
2595 * view in order to avoid having to re-fetch commits from disk
2596 * while updating the display.
2598 do {
2599 struct got_object_id id;
2600 struct got_commit_object *commit;
2601 struct commit_queue_entry *entry;
2602 int limit_match = 0;
2603 int errcode;
2605 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2606 NULL, NULL);
2607 if (err)
2608 break;
2610 err = got_object_open_as_commit(&commit, a->repo, &id);
2611 if (err)
2612 break;
2613 entry = alloc_commit_queue_entry(commit, &id);
2614 if (entry == NULL) {
2615 err = got_error_from_errno("alloc_commit_queue_entry");
2616 break;
2619 errcode = pthread_mutex_lock(&tog_mutex);
2620 if (errcode) {
2621 err = got_error_set_errno(errcode,
2622 "pthread_mutex_lock");
2623 break;
2626 entry->idx = a->real_commits->ncommits;
2627 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2628 a->real_commits->ncommits++;
2630 if (*a->limiting) {
2631 err = match_commit(&limit_match, &id, commit,
2632 a->limit_regex);
2633 if (err)
2634 break;
2636 if (limit_match) {
2637 struct commit_queue_entry *matched;
2639 matched = alloc_commit_queue_entry(
2640 entry->commit, entry->id);
2641 if (matched == NULL) {
2642 err = got_error_from_errno(
2643 "alloc_commit_queue_entry");
2644 break;
2646 matched->commit = entry->commit;
2647 got_object_commit_retain(entry->commit);
2649 matched->idx = a->limit_commits->ncommits;
2650 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2651 matched, entry);
2652 a->limit_commits->ncommits++;
2656 * This is how we signal log_thread() that we
2657 * have found a match, and that it should be
2658 * counted as a new entry for the view.
2660 a->limit_match = limit_match;
2663 if (*a->searching == TOG_SEARCH_FORWARD &&
2664 !*a->search_next_done) {
2665 int have_match;
2666 err = match_commit(&have_match, &id, commit, a->regex);
2667 if (err)
2668 break;
2670 if (*a->limiting) {
2671 if (limit_match && have_match)
2672 *a->search_next_done =
2673 TOG_SEARCH_HAVE_MORE;
2674 } else if (have_match)
2675 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2678 errcode = pthread_mutex_unlock(&tog_mutex);
2679 if (errcode && err == NULL)
2680 err = got_error_set_errno(errcode,
2681 "pthread_mutex_unlock");
2682 if (err)
2683 break;
2684 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2686 return err;
2689 static void
2690 select_commit(struct tog_log_view_state *s)
2692 struct commit_queue_entry *entry;
2693 int ncommits = 0;
2695 entry = s->first_displayed_entry;
2696 while (entry) {
2697 if (ncommits == s->selected) {
2698 s->selected_entry = entry;
2699 break;
2701 entry = TAILQ_NEXT(entry, entry);
2702 ncommits++;
2706 static const struct got_error *
2707 draw_commits(struct tog_view *view)
2709 const struct got_error *err = NULL;
2710 struct tog_log_view_state *s = &view->state.log;
2711 struct commit_queue_entry *entry = s->selected_entry;
2712 int limit = view->nlines;
2713 int width;
2714 int ncommits, author_cols = 4;
2715 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2716 char *refs_str = NULL;
2717 wchar_t *wline;
2718 struct tog_color *tc;
2719 static const size_t date_display_cols = 12;
2721 if (view_is_hsplit_top(view))
2722 --limit; /* account for border */
2724 if (s->selected_entry &&
2725 !(view->searching && view->search_next_done == 0)) {
2726 struct got_reflist_head *refs;
2727 err = got_object_id_str(&id_str, s->selected_entry->id);
2728 if (err)
2729 return err;
2730 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2731 s->selected_entry->id);
2732 if (refs) {
2733 err = build_refs_str(&refs_str, refs,
2734 s->selected_entry->id, s->repo);
2735 if (err)
2736 goto done;
2740 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2741 halfdelay(10); /* disable fast refresh */
2743 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2744 if (asprintf(&ncommits_str, " [%d/%d] %s",
2745 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2746 (view->searching && !view->search_next_done) ?
2747 "searching..." : "loading...") == -1) {
2748 err = got_error_from_errno("asprintf");
2749 goto done;
2751 } else {
2752 const char *search_str = NULL;
2753 const char *limit_str = NULL;
2755 if (view->searching) {
2756 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2757 search_str = "no more matches";
2758 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2759 search_str = "no matches found";
2760 else if (!view->search_next_done)
2761 search_str = "searching...";
2764 if (s->limit_view && s->commits->ncommits == 0)
2765 limit_str = "no matches found";
2767 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2768 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2769 search_str ? search_str : (refs_str ? refs_str : ""),
2770 limit_str ? limit_str : "") == -1) {
2771 err = got_error_from_errno("asprintf");
2772 goto done;
2776 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2777 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2778 "........................................",
2779 s->in_repo_path, ncommits_str) == -1) {
2780 err = got_error_from_errno("asprintf");
2781 header = NULL;
2782 goto done;
2784 } else if (asprintf(&header, "commit %s%s",
2785 id_str ? id_str : "........................................",
2786 ncommits_str) == -1) {
2787 err = got_error_from_errno("asprintf");
2788 header = NULL;
2789 goto done;
2791 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2792 if (err)
2793 goto done;
2795 werase(view->window);
2797 if (view_needs_focus_indication(view))
2798 wstandout(view->window);
2799 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2800 if (tc)
2801 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2802 waddwstr(view->window, wline);
2803 while (width < view->ncols) {
2804 waddch(view->window, ' ');
2805 width++;
2807 if (tc)
2808 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2809 if (view_needs_focus_indication(view))
2810 wstandend(view->window);
2811 free(wline);
2812 if (limit <= 1)
2813 goto done;
2815 /* Grow author column size if necessary, and set view->maxx. */
2816 entry = s->first_displayed_entry;
2817 ncommits = 0;
2818 view->maxx = 0;
2819 while (entry) {
2820 struct got_commit_object *c = entry->commit;
2821 char *author, *eol, *msg, *msg0;
2822 wchar_t *wauthor, *wmsg;
2823 int width;
2824 if (ncommits >= limit - 1)
2825 break;
2826 if (s->use_committer)
2827 author = strdup(got_object_commit_get_committer(c));
2828 else
2829 author = strdup(got_object_commit_get_author(c));
2830 if (author == NULL) {
2831 err = got_error_from_errno("strdup");
2832 goto done;
2834 err = format_author(&wauthor, &width, author, COLS,
2835 date_display_cols);
2836 if (author_cols < width)
2837 author_cols = width;
2838 free(wauthor);
2839 free(author);
2840 if (err)
2841 goto done;
2842 err = got_object_commit_get_logmsg(&msg0, c);
2843 if (err)
2844 goto done;
2845 msg = msg0;
2846 while (*msg == '\n')
2847 ++msg;
2848 if ((eol = strchr(msg, '\n')))
2849 *eol = '\0';
2850 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2851 date_display_cols + author_cols, 0);
2852 if (err)
2853 goto done;
2854 view->maxx = MAX(view->maxx, width);
2855 free(msg0);
2856 free(wmsg);
2857 ncommits++;
2858 entry = TAILQ_NEXT(entry, entry);
2861 entry = s->first_displayed_entry;
2862 s->last_displayed_entry = s->first_displayed_entry;
2863 ncommits = 0;
2864 while (entry) {
2865 if (ncommits >= limit - 1)
2866 break;
2867 if (ncommits == s->selected)
2868 wstandout(view->window);
2869 err = draw_commit(view, entry->commit, entry->id,
2870 date_display_cols, author_cols);
2871 if (ncommits == s->selected)
2872 wstandend(view->window);
2873 if (err)
2874 goto done;
2875 ncommits++;
2876 s->last_displayed_entry = entry;
2877 entry = TAILQ_NEXT(entry, entry);
2880 view_border(view);
2881 done:
2882 free(id_str);
2883 free(refs_str);
2884 free(ncommits_str);
2885 free(header);
2886 return err;
2889 static void
2890 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2892 struct commit_queue_entry *entry;
2893 int nscrolled = 0;
2895 entry = TAILQ_FIRST(&s->commits->head);
2896 if (s->first_displayed_entry == entry)
2897 return;
2899 entry = s->first_displayed_entry;
2900 while (entry && nscrolled < maxscroll) {
2901 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2902 if (entry) {
2903 s->first_displayed_entry = entry;
2904 nscrolled++;
2909 static const struct got_error *
2910 trigger_log_thread(struct tog_view *view, int wait)
2912 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2913 int errcode;
2915 if (!using_mock_io)
2916 halfdelay(1); /* fast refresh while loading commits */
2918 while (!ta->log_complete && !tog_thread_error &&
2919 (ta->commits_needed > 0 || ta->load_all)) {
2920 /* Wake the log thread. */
2921 errcode = pthread_cond_signal(&ta->need_commits);
2922 if (errcode)
2923 return got_error_set_errno(errcode,
2924 "pthread_cond_signal");
2927 * The mutex will be released while the view loop waits
2928 * in wgetch(), at which time the log thread will run.
2930 if (!wait)
2931 break;
2933 /* Display progress update in log view. */
2934 show_log_view(view);
2935 update_panels();
2936 doupdate();
2938 /* Wait right here while next commit is being loaded. */
2939 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2940 if (errcode)
2941 return got_error_set_errno(errcode,
2942 "pthread_cond_wait");
2944 /* Display progress update in log view. */
2945 show_log_view(view);
2946 update_panels();
2947 doupdate();
2950 return NULL;
2953 static const struct got_error *
2954 request_log_commits(struct tog_view *view)
2956 struct tog_log_view_state *state = &view->state.log;
2957 const struct got_error *err = NULL;
2959 if (state->thread_args.log_complete)
2960 return NULL;
2962 state->thread_args.commits_needed += view->nscrolled;
2963 err = trigger_log_thread(view, 1);
2964 view->nscrolled = 0;
2966 return err;
2969 static const struct got_error *
2970 log_scroll_down(struct tog_view *view, int maxscroll)
2972 struct tog_log_view_state *s = &view->state.log;
2973 const struct got_error *err = NULL;
2974 struct commit_queue_entry *pentry;
2975 int nscrolled = 0, ncommits_needed;
2977 if (s->last_displayed_entry == NULL)
2978 return NULL;
2980 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2981 if (s->commits->ncommits < ncommits_needed &&
2982 !s->thread_args.log_complete) {
2984 * Ask the log thread for required amount of commits.
2986 s->thread_args.commits_needed +=
2987 ncommits_needed - s->commits->ncommits;
2988 err = trigger_log_thread(view, 1);
2989 if (err)
2990 return err;
2993 do {
2994 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2995 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2996 break;
2998 s->last_displayed_entry = pentry ?
2999 pentry : s->last_displayed_entry;
3001 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3002 if (pentry == NULL)
3003 break;
3004 s->first_displayed_entry = pentry;
3005 } while (++nscrolled < maxscroll);
3007 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3008 view->nscrolled += nscrolled;
3009 else
3010 view->nscrolled = 0;
3012 return err;
3015 static const struct got_error *
3016 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3017 struct got_commit_object *commit, struct got_object_id *commit_id,
3018 struct tog_view *log_view, struct got_repository *repo)
3020 const struct got_error *err;
3021 struct got_object_qid *parent_id;
3022 struct tog_view *diff_view;
3024 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3025 if (diff_view == NULL)
3026 return got_error_from_errno("view_open");
3028 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3029 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3030 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3031 if (err == NULL)
3032 *new_view = diff_view;
3033 return err;
3036 static const struct got_error *
3037 tree_view_visit_subtree(struct tog_tree_view_state *s,
3038 struct got_tree_object *subtree)
3040 struct tog_parent_tree *parent;
3042 parent = calloc(1, sizeof(*parent));
3043 if (parent == NULL)
3044 return got_error_from_errno("calloc");
3046 parent->tree = s->tree;
3047 parent->first_displayed_entry = s->first_displayed_entry;
3048 parent->selected_entry = s->selected_entry;
3049 parent->selected = s->selected;
3050 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3051 s->tree = subtree;
3052 s->selected = 0;
3053 s->first_displayed_entry = NULL;
3054 return NULL;
3057 static const struct got_error *
3058 tree_view_walk_path(struct tog_tree_view_state *s,
3059 struct got_commit_object *commit, const char *path)
3061 const struct got_error *err = NULL;
3062 struct got_tree_object *tree = NULL;
3063 const char *p;
3064 char *slash, *subpath = NULL;
3066 /* Walk the path and open corresponding tree objects. */
3067 p = path;
3068 while (*p) {
3069 struct got_tree_entry *te;
3070 struct got_object_id *tree_id;
3071 char *te_name;
3073 while (p[0] == '/')
3074 p++;
3076 /* Ensure the correct subtree entry is selected. */
3077 slash = strchr(p, '/');
3078 if (slash == NULL)
3079 te_name = strdup(p);
3080 else
3081 te_name = strndup(p, slash - p);
3082 if (te_name == NULL) {
3083 err = got_error_from_errno("strndup");
3084 break;
3086 te = got_object_tree_find_entry(s->tree, te_name);
3087 if (te == NULL) {
3088 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3089 free(te_name);
3090 break;
3092 free(te_name);
3093 s->first_displayed_entry = s->selected_entry = te;
3095 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3096 break; /* jump to this file's entry */
3098 slash = strchr(p, '/');
3099 if (slash)
3100 subpath = strndup(path, slash - path);
3101 else
3102 subpath = strdup(path);
3103 if (subpath == NULL) {
3104 err = got_error_from_errno("strdup");
3105 break;
3108 err = got_object_id_by_path(&tree_id, s->repo, commit,
3109 subpath);
3110 if (err)
3111 break;
3113 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3114 free(tree_id);
3115 if (err)
3116 break;
3118 err = tree_view_visit_subtree(s, tree);
3119 if (err) {
3120 got_object_tree_close(tree);
3121 break;
3123 if (slash == NULL)
3124 break;
3125 free(subpath);
3126 subpath = NULL;
3127 p = slash;
3130 free(subpath);
3131 return err;
3134 static const struct got_error *
3135 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3136 struct commit_queue_entry *entry, const char *path,
3137 const char *head_ref_name, struct got_repository *repo)
3139 const struct got_error *err = NULL;
3140 struct tog_tree_view_state *s;
3141 struct tog_view *tree_view;
3143 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3144 if (tree_view == NULL)
3145 return got_error_from_errno("view_open");
3147 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3148 if (err)
3149 return err;
3150 s = &tree_view->state.tree;
3152 *new_view = tree_view;
3154 if (got_path_is_root_dir(path))
3155 return NULL;
3157 return tree_view_walk_path(s, entry->commit, path);
3160 static const struct got_error *
3161 block_signals_used_by_main_thread(void)
3163 sigset_t sigset;
3164 int errcode;
3166 if (sigemptyset(&sigset) == -1)
3167 return got_error_from_errno("sigemptyset");
3169 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3170 if (sigaddset(&sigset, SIGWINCH) == -1)
3171 return got_error_from_errno("sigaddset");
3172 if (sigaddset(&sigset, SIGCONT) == -1)
3173 return got_error_from_errno("sigaddset");
3174 if (sigaddset(&sigset, SIGINT) == -1)
3175 return got_error_from_errno("sigaddset");
3176 if (sigaddset(&sigset, SIGTERM) == -1)
3177 return got_error_from_errno("sigaddset");
3179 /* ncurses handles SIGTSTP */
3180 if (sigaddset(&sigset, SIGTSTP) == -1)
3181 return got_error_from_errno("sigaddset");
3183 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3184 if (errcode)
3185 return got_error_set_errno(errcode, "pthread_sigmask");
3187 return NULL;
3190 static void *
3191 log_thread(void *arg)
3193 const struct got_error *err = NULL;
3194 int errcode = 0;
3195 struct tog_log_thread_args *a = arg;
3196 int done = 0;
3199 * Sync startup with main thread such that we begin our
3200 * work once view_input() has released the mutex.
3202 errcode = pthread_mutex_lock(&tog_mutex);
3203 if (errcode) {
3204 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3205 return (void *)err;
3208 err = block_signals_used_by_main_thread();
3209 if (err) {
3210 pthread_mutex_unlock(&tog_mutex);
3211 goto done;
3214 while (!done && !err && !tog_fatal_signal_received()) {
3215 errcode = pthread_mutex_unlock(&tog_mutex);
3216 if (errcode) {
3217 err = got_error_set_errno(errcode,
3218 "pthread_mutex_unlock");
3219 goto done;
3221 err = queue_commits(a);
3222 if (err) {
3223 if (err->code != GOT_ERR_ITER_COMPLETED)
3224 goto done;
3225 err = NULL;
3226 done = 1;
3227 } else if (a->commits_needed > 0 && !a->load_all) {
3228 if (*a->limiting) {
3229 if (a->limit_match)
3230 a->commits_needed--;
3231 } else
3232 a->commits_needed--;
3235 errcode = pthread_mutex_lock(&tog_mutex);
3236 if (errcode) {
3237 err = got_error_set_errno(errcode,
3238 "pthread_mutex_lock");
3239 goto done;
3240 } else if (*a->quit)
3241 done = 1;
3242 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3243 *a->first_displayed_entry =
3244 TAILQ_FIRST(&a->limit_commits->head);
3245 *a->selected_entry = *a->first_displayed_entry;
3246 } else if (*a->first_displayed_entry == NULL) {
3247 *a->first_displayed_entry =
3248 TAILQ_FIRST(&a->real_commits->head);
3249 *a->selected_entry = *a->first_displayed_entry;
3252 errcode = pthread_cond_signal(&a->commit_loaded);
3253 if (errcode) {
3254 err = got_error_set_errno(errcode,
3255 "pthread_cond_signal");
3256 pthread_mutex_unlock(&tog_mutex);
3257 goto done;
3260 if (done)
3261 a->commits_needed = 0;
3262 else {
3263 if (a->commits_needed == 0 && !a->load_all) {
3264 errcode = pthread_cond_wait(&a->need_commits,
3265 &tog_mutex);
3266 if (errcode) {
3267 err = got_error_set_errno(errcode,
3268 "pthread_cond_wait");
3269 pthread_mutex_unlock(&tog_mutex);
3270 goto done;
3272 if (*a->quit)
3273 done = 1;
3277 a->log_complete = 1;
3278 errcode = pthread_mutex_unlock(&tog_mutex);
3279 if (errcode)
3280 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3281 done:
3282 if (err) {
3283 tog_thread_error = 1;
3284 pthread_cond_signal(&a->commit_loaded);
3286 return (void *)err;
3289 static const struct got_error *
3290 stop_log_thread(struct tog_log_view_state *s)
3292 const struct got_error *err = NULL, *thread_err = NULL;
3293 int errcode;
3295 if (s->thread) {
3296 s->quit = 1;
3297 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3298 if (errcode)
3299 return got_error_set_errno(errcode,
3300 "pthread_cond_signal");
3301 errcode = pthread_mutex_unlock(&tog_mutex);
3302 if (errcode)
3303 return got_error_set_errno(errcode,
3304 "pthread_mutex_unlock");
3305 errcode = pthread_join(s->thread, (void **)&thread_err);
3306 if (errcode)
3307 return got_error_set_errno(errcode, "pthread_join");
3308 errcode = pthread_mutex_lock(&tog_mutex);
3309 if (errcode)
3310 return got_error_set_errno(errcode,
3311 "pthread_mutex_lock");
3312 s->thread = NULL;
3315 if (s->thread_args.repo) {
3316 err = got_repo_close(s->thread_args.repo);
3317 s->thread_args.repo = NULL;
3320 if (s->thread_args.pack_fds) {
3321 const struct got_error *pack_err =
3322 got_repo_pack_fds_close(s->thread_args.pack_fds);
3323 if (err == NULL)
3324 err = pack_err;
3325 s->thread_args.pack_fds = NULL;
3328 if (s->thread_args.graph) {
3329 got_commit_graph_close(s->thread_args.graph);
3330 s->thread_args.graph = NULL;
3333 return err ? err : thread_err;
3336 static const struct got_error *
3337 close_log_view(struct tog_view *view)
3339 const struct got_error *err = NULL;
3340 struct tog_log_view_state *s = &view->state.log;
3341 int errcode;
3343 err = stop_log_thread(s);
3345 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3346 if (errcode && err == NULL)
3347 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3349 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3350 if (errcode && err == NULL)
3351 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3353 free_commits(&s->limit_commits);
3354 free_commits(&s->real_commits);
3355 free(s->in_repo_path);
3356 s->in_repo_path = NULL;
3357 free(s->start_id);
3358 s->start_id = NULL;
3359 free(s->head_ref_name);
3360 s->head_ref_name = NULL;
3361 return err;
3365 * We use two queues to implement the limit feature: first consists of
3366 * commits matching the current limit_regex; second is the real queue
3367 * of all known commits (real_commits). When the user starts limiting,
3368 * we swap queues such that all movement and displaying functionality
3369 * works with very slight change.
3371 static const struct got_error *
3372 limit_log_view(struct tog_view *view)
3374 struct tog_log_view_state *s = &view->state.log;
3375 struct commit_queue_entry *entry;
3376 struct tog_view *v = view;
3377 const struct got_error *err = NULL;
3378 char pattern[1024];
3379 int ret;
3381 if (view_is_hsplit_top(view))
3382 v = view->child;
3383 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3384 v = view->parent;
3386 /* Get the pattern */
3387 wmove(v->window, v->nlines - 1, 0);
3388 wclrtoeol(v->window);
3389 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3390 nodelay(v->window, FALSE);
3391 nocbreak();
3392 echo();
3393 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3394 cbreak();
3395 noecho();
3396 nodelay(v->window, TRUE);
3397 if (ret == ERR)
3398 return NULL;
3400 if (*pattern == '\0') {
3402 * Safety measure for the situation where the user
3403 * resets limit without previously limiting anything.
3405 if (!s->limit_view)
3406 return NULL;
3409 * User could have pressed Ctrl+L, which refreshed the
3410 * commit queues, it means we can't save previously
3411 * (before limit took place) displayed entries,
3412 * because they would point to already free'ed memory,
3413 * so we are forced to always select first entry of
3414 * the queue.
3416 s->commits = &s->real_commits;
3417 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3418 s->selected_entry = s->first_displayed_entry;
3419 s->selected = 0;
3420 s->limit_view = 0;
3422 return NULL;
3425 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3426 return NULL;
3428 s->limit_view = 1;
3430 /* Clear the screen while loading limit view */
3431 s->first_displayed_entry = NULL;
3432 s->last_displayed_entry = NULL;
3433 s->selected_entry = NULL;
3434 s->commits = &s->limit_commits;
3436 /* Prepare limit queue for new search */
3437 free_commits(&s->limit_commits);
3438 s->limit_commits.ncommits = 0;
3440 /* First process commits, which are in queue already */
3441 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3442 int have_match = 0;
3444 err = match_commit(&have_match, entry->id,
3445 entry->commit, &s->limit_regex);
3446 if (err)
3447 return err;
3449 if (have_match) {
3450 struct commit_queue_entry *matched;
3452 matched = alloc_commit_queue_entry(entry->commit,
3453 entry->id);
3454 if (matched == NULL) {
3455 err = got_error_from_errno(
3456 "alloc_commit_queue_entry");
3457 break;
3459 matched->commit = entry->commit;
3460 got_object_commit_retain(entry->commit);
3462 matched->idx = s->limit_commits.ncommits;
3463 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3464 matched, entry);
3465 s->limit_commits.ncommits++;
3469 /* Second process all the commits, until we fill the screen */
3470 if (s->limit_commits.ncommits < view->nlines - 1 &&
3471 !s->thread_args.log_complete) {
3472 s->thread_args.commits_needed +=
3473 view->nlines - s->limit_commits.ncommits - 1;
3474 err = trigger_log_thread(view, 1);
3475 if (err)
3476 return err;
3479 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3480 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3481 s->selected = 0;
3483 return NULL;
3486 static const struct got_error *
3487 search_start_log_view(struct tog_view *view)
3489 struct tog_log_view_state *s = &view->state.log;
3491 s->matched_entry = NULL;
3492 s->search_entry = NULL;
3493 return NULL;
3496 static const struct got_error *
3497 search_next_log_view(struct tog_view *view)
3499 const struct got_error *err = NULL;
3500 struct tog_log_view_state *s = &view->state.log;
3501 struct commit_queue_entry *entry;
3503 /* Display progress update in log view. */
3504 show_log_view(view);
3505 update_panels();
3506 doupdate();
3508 if (s->search_entry) {
3509 int errcode, ch;
3510 errcode = pthread_mutex_unlock(&tog_mutex);
3511 if (errcode)
3512 return got_error_set_errno(errcode,
3513 "pthread_mutex_unlock");
3514 ch = wgetch(view->window);
3515 errcode = pthread_mutex_lock(&tog_mutex);
3516 if (errcode)
3517 return got_error_set_errno(errcode,
3518 "pthread_mutex_lock");
3519 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3520 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3521 return NULL;
3523 if (view->searching == TOG_SEARCH_FORWARD)
3524 entry = TAILQ_NEXT(s->search_entry, entry);
3525 else
3526 entry = TAILQ_PREV(s->search_entry,
3527 commit_queue_head, entry);
3528 } else if (s->matched_entry) {
3530 * If the user has moved the cursor after we hit a match,
3531 * the position from where we should continue searching
3532 * might have changed.
3534 if (view->searching == TOG_SEARCH_FORWARD)
3535 entry = TAILQ_NEXT(s->selected_entry, entry);
3536 else
3537 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3538 entry);
3539 } else {
3540 entry = s->selected_entry;
3543 while (1) {
3544 int have_match = 0;
3546 if (entry == NULL) {
3547 if (s->thread_args.log_complete ||
3548 view->searching == TOG_SEARCH_BACKWARD) {
3549 view->search_next_done =
3550 (s->matched_entry == NULL ?
3551 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3552 s->search_entry = NULL;
3553 return NULL;
3556 * Poke the log thread for more commits and return,
3557 * allowing the main loop to make progress. Search
3558 * will resume at s->search_entry once we come back.
3560 s->thread_args.commits_needed++;
3561 return trigger_log_thread(view, 0);
3564 err = match_commit(&have_match, entry->id, entry->commit,
3565 &view->regex);
3566 if (err)
3567 break;
3568 if (have_match) {
3569 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3570 s->matched_entry = entry;
3571 break;
3574 s->search_entry = entry;
3575 if (view->searching == TOG_SEARCH_FORWARD)
3576 entry = TAILQ_NEXT(entry, entry);
3577 else
3578 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3581 if (s->matched_entry) {
3582 int cur = s->selected_entry->idx;
3583 while (cur < s->matched_entry->idx) {
3584 err = input_log_view(NULL, view, KEY_DOWN);
3585 if (err)
3586 return err;
3587 cur++;
3589 while (cur > s->matched_entry->idx) {
3590 err = input_log_view(NULL, view, KEY_UP);
3591 if (err)
3592 return err;
3593 cur--;
3597 s->search_entry = NULL;
3599 return NULL;
3602 static const struct got_error *
3603 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3604 struct got_repository *repo, const char *head_ref_name,
3605 const char *in_repo_path, int log_branches)
3607 const struct got_error *err = NULL;
3608 struct tog_log_view_state *s = &view->state.log;
3609 struct got_repository *thread_repo = NULL;
3610 struct got_commit_graph *thread_graph = NULL;
3611 int errcode;
3613 if (in_repo_path != s->in_repo_path) {
3614 free(s->in_repo_path);
3615 s->in_repo_path = strdup(in_repo_path);
3616 if (s->in_repo_path == NULL) {
3617 err = got_error_from_errno("strdup");
3618 goto done;
3622 /* The commit queue only contains commits being displayed. */
3623 TAILQ_INIT(&s->real_commits.head);
3624 s->real_commits.ncommits = 0;
3625 s->commits = &s->real_commits;
3627 TAILQ_INIT(&s->limit_commits.head);
3628 s->limit_view = 0;
3629 s->limit_commits.ncommits = 0;
3631 s->repo = repo;
3632 if (head_ref_name) {
3633 s->head_ref_name = strdup(head_ref_name);
3634 if (s->head_ref_name == NULL) {
3635 err = got_error_from_errno("strdup");
3636 goto done;
3639 s->start_id = got_object_id_dup(start_id);
3640 if (s->start_id == NULL) {
3641 err = got_error_from_errno("got_object_id_dup");
3642 goto done;
3644 s->log_branches = log_branches;
3645 s->use_committer = 1;
3647 STAILQ_INIT(&s->colors);
3648 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3649 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3650 get_color_value("TOG_COLOR_COMMIT"));
3651 if (err)
3652 goto done;
3653 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3654 get_color_value("TOG_COLOR_AUTHOR"));
3655 if (err) {
3656 free_colors(&s->colors);
3657 goto done;
3659 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3660 get_color_value("TOG_COLOR_DATE"));
3661 if (err) {
3662 free_colors(&s->colors);
3663 goto done;
3667 view->show = show_log_view;
3668 view->input = input_log_view;
3669 view->resize = resize_log_view;
3670 view->close = close_log_view;
3671 view->search_start = search_start_log_view;
3672 view->search_next = search_next_log_view;
3674 if (s->thread_args.pack_fds == NULL) {
3675 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3676 if (err)
3677 goto done;
3679 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3680 s->thread_args.pack_fds);
3681 if (err)
3682 goto done;
3683 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3684 !s->log_branches);
3685 if (err)
3686 goto done;
3687 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3688 s->repo, NULL, NULL);
3689 if (err)
3690 goto done;
3692 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3693 if (errcode) {
3694 err = got_error_set_errno(errcode, "pthread_cond_init");
3695 goto done;
3697 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3698 if (errcode) {
3699 err = got_error_set_errno(errcode, "pthread_cond_init");
3700 goto done;
3703 s->thread_args.commits_needed = view->nlines;
3704 s->thread_args.graph = thread_graph;
3705 s->thread_args.real_commits = &s->real_commits;
3706 s->thread_args.limit_commits = &s->limit_commits;
3707 s->thread_args.in_repo_path = s->in_repo_path;
3708 s->thread_args.start_id = s->start_id;
3709 s->thread_args.repo = thread_repo;
3710 s->thread_args.log_complete = 0;
3711 s->thread_args.quit = &s->quit;
3712 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3713 s->thread_args.selected_entry = &s->selected_entry;
3714 s->thread_args.searching = &view->searching;
3715 s->thread_args.search_next_done = &view->search_next_done;
3716 s->thread_args.regex = &view->regex;
3717 s->thread_args.limiting = &s->limit_view;
3718 s->thread_args.limit_regex = &s->limit_regex;
3719 s->thread_args.limit_commits = &s->limit_commits;
3720 done:
3721 if (err) {
3722 if (view->close == NULL)
3723 close_log_view(view);
3724 view_close(view);
3726 return err;
3729 static const struct got_error *
3730 show_log_view(struct tog_view *view)
3732 const struct got_error *err;
3733 struct tog_log_view_state *s = &view->state.log;
3735 if (s->thread == NULL) {
3736 int errcode = pthread_create(&s->thread, NULL, log_thread,
3737 &s->thread_args);
3738 if (errcode)
3739 return got_error_set_errno(errcode, "pthread_create");
3740 if (s->thread_args.commits_needed > 0) {
3741 err = trigger_log_thread(view, 1);
3742 if (err)
3743 return err;
3747 return draw_commits(view);
3750 static void
3751 log_move_cursor_up(struct tog_view *view, int page, int home)
3753 struct tog_log_view_state *s = &view->state.log;
3755 if (s->first_displayed_entry == NULL)
3756 return;
3757 if (s->selected_entry->idx == 0)
3758 view->count = 0;
3760 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3761 || home)
3762 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3764 if (!page && !home && s->selected > 0)
3765 --s->selected;
3766 else
3767 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3769 select_commit(s);
3770 return;
3773 static const struct got_error *
3774 log_move_cursor_down(struct tog_view *view, int page)
3776 struct tog_log_view_state *s = &view->state.log;
3777 const struct got_error *err = NULL;
3778 int eos = view->nlines - 2;
3780 if (s->first_displayed_entry == NULL)
3781 return NULL;
3783 if (s->thread_args.log_complete &&
3784 s->selected_entry->idx >= s->commits->ncommits - 1)
3785 return NULL;
3787 if (view_is_hsplit_top(view))
3788 --eos; /* border consumes the last line */
3790 if (!page) {
3791 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3792 ++s->selected;
3793 else
3794 err = log_scroll_down(view, 1);
3795 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3796 struct commit_queue_entry *entry;
3797 int n;
3799 s->selected = 0;
3800 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3801 s->last_displayed_entry = entry;
3802 for (n = 0; n <= eos; n++) {
3803 if (entry == NULL)
3804 break;
3805 s->first_displayed_entry = entry;
3806 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3808 if (n > 0)
3809 s->selected = n - 1;
3810 } else {
3811 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3812 s->thread_args.log_complete)
3813 s->selected += MIN(page,
3814 s->commits->ncommits - s->selected_entry->idx - 1);
3815 else
3816 err = log_scroll_down(view, page);
3818 if (err)
3819 return err;
3822 * We might necessarily overshoot in horizontal
3823 * splits; if so, select the last displayed commit.
3825 if (s->first_displayed_entry && s->last_displayed_entry) {
3826 s->selected = MIN(s->selected,
3827 s->last_displayed_entry->idx -
3828 s->first_displayed_entry->idx);
3831 select_commit(s);
3833 if (s->thread_args.log_complete &&
3834 s->selected_entry->idx == s->commits->ncommits - 1)
3835 view->count = 0;
3837 return NULL;
3840 static void
3841 view_get_split(struct tog_view *view, int *y, int *x)
3843 *x = 0;
3844 *y = 0;
3846 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3847 if (view->child && view->child->resized_y)
3848 *y = view->child->resized_y;
3849 else if (view->resized_y)
3850 *y = view->resized_y;
3851 else
3852 *y = view_split_begin_y(view->lines);
3853 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3854 if (view->child && view->child->resized_x)
3855 *x = view->child->resized_x;
3856 else if (view->resized_x)
3857 *x = view->resized_x;
3858 else
3859 *x = view_split_begin_x(view->begin_x);
3863 /* Split view horizontally at y and offset view->state->selected line. */
3864 static const struct got_error *
3865 view_init_hsplit(struct tog_view *view, int y)
3867 const struct got_error *err = NULL;
3869 view->nlines = y;
3870 view->ncols = COLS;
3871 err = view_resize(view);
3872 if (err)
3873 return err;
3875 err = offset_selection_down(view);
3877 return err;
3880 static const struct got_error *
3881 log_goto_line(struct tog_view *view, int nlines)
3883 const struct got_error *err = NULL;
3884 struct tog_log_view_state *s = &view->state.log;
3885 int g, idx = s->selected_entry->idx;
3887 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3888 return NULL;
3890 g = view->gline;
3891 view->gline = 0;
3893 if (g >= s->first_displayed_entry->idx + 1 &&
3894 g <= s->last_displayed_entry->idx + 1 &&
3895 g - s->first_displayed_entry->idx - 1 < nlines) {
3896 s->selected = g - s->first_displayed_entry->idx - 1;
3897 select_commit(s);
3898 return NULL;
3901 if (idx + 1 < g) {
3902 err = log_move_cursor_down(view, g - idx - 1);
3903 if (!err && g > s->selected_entry->idx + 1)
3904 err = log_move_cursor_down(view,
3905 g - s->first_displayed_entry->idx - 1);
3906 if (err)
3907 return err;
3908 } else if (idx + 1 > g)
3909 log_move_cursor_up(view, idx - g + 1, 0);
3911 if (g < nlines && s->first_displayed_entry->idx == 0)
3912 s->selected = g - 1;
3914 select_commit(s);
3915 return NULL;
3919 static void
3920 horizontal_scroll_input(struct tog_view *view, int ch)
3923 switch (ch) {
3924 case KEY_LEFT:
3925 case 'h':
3926 view->x -= MIN(view->x, 2);
3927 if (view->x <= 0)
3928 view->count = 0;
3929 break;
3930 case KEY_RIGHT:
3931 case 'l':
3932 if (view->x + view->ncols / 2 < view->maxx)
3933 view->x += 2;
3934 else
3935 view->count = 0;
3936 break;
3937 case '0':
3938 view->x = 0;
3939 break;
3940 case '$':
3941 view->x = MAX(view->maxx - view->ncols / 2, 0);
3942 view->count = 0;
3943 break;
3944 default:
3945 break;
3949 static const struct got_error *
3950 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3952 const struct got_error *err = NULL;
3953 struct tog_log_view_state *s = &view->state.log;
3954 int eos, nscroll;
3956 if (s->thread_args.load_all) {
3957 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3958 s->thread_args.load_all = 0;
3959 else if (s->thread_args.log_complete) {
3960 err = log_move_cursor_down(view, s->commits->ncommits);
3961 s->thread_args.load_all = 0;
3963 if (err)
3964 return err;
3967 eos = nscroll = view->nlines - 1;
3968 if (view_is_hsplit_top(view))
3969 --eos; /* border */
3971 if (view->gline)
3972 return log_goto_line(view, eos);
3974 switch (ch) {
3975 case '&':
3976 err = limit_log_view(view);
3977 break;
3978 case 'q':
3979 s->quit = 1;
3980 break;
3981 case '0':
3982 case '$':
3983 case KEY_RIGHT:
3984 case 'l':
3985 case KEY_LEFT:
3986 case 'h':
3987 horizontal_scroll_input(view, ch);
3988 break;
3989 case 'k':
3990 case KEY_UP:
3991 case '<':
3992 case ',':
3993 case CTRL('p'):
3994 log_move_cursor_up(view, 0, 0);
3995 break;
3996 case 'g':
3997 case '=':
3998 case KEY_HOME:
3999 log_move_cursor_up(view, 0, 1);
4000 view->count = 0;
4001 break;
4002 case CTRL('u'):
4003 case 'u':
4004 nscroll /= 2;
4005 /* FALL THROUGH */
4006 case KEY_PPAGE:
4007 case CTRL('b'):
4008 case 'b':
4009 log_move_cursor_up(view, nscroll, 0);
4010 break;
4011 case 'j':
4012 case KEY_DOWN:
4013 case '>':
4014 case '.':
4015 case CTRL('n'):
4016 err = log_move_cursor_down(view, 0);
4017 break;
4018 case '@':
4019 s->use_committer = !s->use_committer;
4020 view->action = s->use_committer ?
4021 "show committer" : "show commit author";
4022 break;
4023 case 'G':
4024 case '*':
4025 case KEY_END: {
4026 /* We don't know yet how many commits, so we're forced to
4027 * traverse them all. */
4028 view->count = 0;
4029 s->thread_args.load_all = 1;
4030 if (!s->thread_args.log_complete)
4031 return trigger_log_thread(view, 0);
4032 err = log_move_cursor_down(view, s->commits->ncommits);
4033 s->thread_args.load_all = 0;
4034 break;
4036 case CTRL('d'):
4037 case 'd':
4038 nscroll /= 2;
4039 /* FALL THROUGH */
4040 case KEY_NPAGE:
4041 case CTRL('f'):
4042 case 'f':
4043 case ' ':
4044 err = log_move_cursor_down(view, nscroll);
4045 break;
4046 case KEY_RESIZE:
4047 if (s->selected > view->nlines - 2)
4048 s->selected = view->nlines - 2;
4049 if (s->selected > s->commits->ncommits - 1)
4050 s->selected = s->commits->ncommits - 1;
4051 select_commit(s);
4052 if (s->commits->ncommits < view->nlines - 1 &&
4053 !s->thread_args.log_complete) {
4054 s->thread_args.commits_needed += (view->nlines - 1) -
4055 s->commits->ncommits;
4056 err = trigger_log_thread(view, 1);
4058 break;
4059 case KEY_ENTER:
4060 case '\r':
4061 view->count = 0;
4062 if (s->selected_entry == NULL)
4063 break;
4064 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4065 break;
4066 case 'T':
4067 view->count = 0;
4068 if (s->selected_entry == NULL)
4069 break;
4070 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4071 break;
4072 case KEY_BACKSPACE:
4073 case CTRL('l'):
4074 case 'B':
4075 view->count = 0;
4076 if (ch == KEY_BACKSPACE &&
4077 got_path_is_root_dir(s->in_repo_path))
4078 break;
4079 err = stop_log_thread(s);
4080 if (err)
4081 return err;
4082 if (ch == KEY_BACKSPACE) {
4083 char *parent_path;
4084 err = got_path_dirname(&parent_path, s->in_repo_path);
4085 if (err)
4086 return err;
4087 free(s->in_repo_path);
4088 s->in_repo_path = parent_path;
4089 s->thread_args.in_repo_path = s->in_repo_path;
4090 } else if (ch == CTRL('l')) {
4091 struct got_object_id *start_id;
4092 err = got_repo_match_object_id(&start_id, NULL,
4093 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4094 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4095 if (err) {
4096 if (s->head_ref_name == NULL ||
4097 err->code != GOT_ERR_NOT_REF)
4098 return err;
4099 /* Try to cope with deleted references. */
4100 free(s->head_ref_name);
4101 s->head_ref_name = NULL;
4102 err = got_repo_match_object_id(&start_id,
4103 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4104 &tog_refs, s->repo);
4105 if (err)
4106 return err;
4108 free(s->start_id);
4109 s->start_id = start_id;
4110 s->thread_args.start_id = s->start_id;
4111 } else /* 'B' */
4112 s->log_branches = !s->log_branches;
4114 if (s->thread_args.pack_fds == NULL) {
4115 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4116 if (err)
4117 return err;
4119 err = got_repo_open(&s->thread_args.repo,
4120 got_repo_get_path(s->repo), NULL,
4121 s->thread_args.pack_fds);
4122 if (err)
4123 return err;
4124 tog_free_refs();
4125 err = tog_load_refs(s->repo, 0);
4126 if (err)
4127 return err;
4128 err = got_commit_graph_open(&s->thread_args.graph,
4129 s->in_repo_path, !s->log_branches);
4130 if (err)
4131 return err;
4132 err = got_commit_graph_iter_start(s->thread_args.graph,
4133 s->start_id, s->repo, NULL, NULL);
4134 if (err)
4135 return err;
4136 free_commits(&s->real_commits);
4137 free_commits(&s->limit_commits);
4138 s->first_displayed_entry = NULL;
4139 s->last_displayed_entry = NULL;
4140 s->selected_entry = NULL;
4141 s->selected = 0;
4142 s->thread_args.log_complete = 0;
4143 s->quit = 0;
4144 s->thread_args.commits_needed = view->lines;
4145 s->matched_entry = NULL;
4146 s->search_entry = NULL;
4147 view->offset = 0;
4148 break;
4149 case 'R':
4150 view->count = 0;
4151 err = view_request_new(new_view, view, TOG_VIEW_REF);
4152 break;
4153 default:
4154 view->count = 0;
4155 break;
4158 return err;
4161 static const struct got_error *
4162 apply_unveil(const char *repo_path, const char *worktree_path)
4164 const struct got_error *error;
4166 #ifdef PROFILE
4167 if (unveil("gmon.out", "rwc") != 0)
4168 return got_error_from_errno2("unveil", "gmon.out");
4169 #endif
4170 if (repo_path && unveil(repo_path, "r") != 0)
4171 return got_error_from_errno2("unveil", repo_path);
4173 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4174 return got_error_from_errno2("unveil", worktree_path);
4176 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4177 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4179 error = got_privsep_unveil_exec_helpers();
4180 if (error != NULL)
4181 return error;
4183 if (unveil(NULL, NULL) != 0)
4184 return got_error_from_errno("unveil");
4186 return NULL;
4189 static const struct got_error *
4190 init_mock_term(const char *test_script_path)
4192 const struct got_error *err = NULL;
4193 const char *screen_dump_path;
4194 int in;
4196 if (test_script_path == NULL || *test_script_path == '\0')
4197 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4199 tog_io.f = fopen(test_script_path, "re");
4200 if (tog_io.f == NULL) {
4201 err = got_error_from_errno_fmt("fopen: %s",
4202 test_script_path);
4203 goto done;
4206 /* test mode, we don't want any output */
4207 tog_io.cout = fopen("/dev/null", "w+");
4208 if (tog_io.cout == NULL) {
4209 err = got_error_from_errno2("fopen", "/dev/null");
4210 goto done;
4213 in = dup(fileno(tog_io.cout));
4214 if (in == -1) {
4215 err = got_error_from_errno("dup");
4216 goto done;
4218 tog_io.cin = fdopen(in, "r");
4219 if (tog_io.cin == NULL) {
4220 err = got_error_from_errno("fdopen");
4221 close(in);
4222 goto done;
4225 screen_dump_path = getenv("TOG_SCR_DUMP");
4226 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4227 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4228 tog_io.sdump = fopen(screen_dump_path, "wex");
4229 if (tog_io.sdump == NULL) {
4230 err = got_error_from_errno2("fopen", screen_dump_path);
4231 goto done;
4234 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4235 err = got_error_from_errno("fseeko");
4236 goto done;
4239 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4240 err = got_error_msg(GOT_ERR_IO,
4241 "newterm: failed to initialise curses");
4243 using_mock_io = 1;
4245 done:
4246 if (err)
4247 tog_io_close();
4248 return err;
4251 static void
4252 init_curses(void)
4255 * Override default signal handlers before starting ncurses.
4256 * This should prevent ncurses from installing its own
4257 * broken cleanup() signal handler.
4259 signal(SIGWINCH, tog_sigwinch);
4260 signal(SIGPIPE, tog_sigpipe);
4261 signal(SIGCONT, tog_sigcont);
4262 signal(SIGINT, tog_sigint);
4263 signal(SIGTERM, tog_sigterm);
4265 if (using_mock_io) /* In test mode we use a fake terminal */
4266 return;
4268 initscr();
4270 cbreak();
4271 halfdelay(1); /* Fast refresh while initial view is loading. */
4272 noecho();
4273 nonl();
4274 intrflush(stdscr, FALSE);
4275 keypad(stdscr, TRUE);
4276 curs_set(0);
4277 if (getenv("TOG_COLORS") != NULL) {
4278 start_color();
4279 use_default_colors();
4282 return;
4285 static const struct got_error *
4286 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4287 struct got_repository *repo, struct got_worktree *worktree)
4289 const struct got_error *err = NULL;
4291 if (argc == 0) {
4292 *in_repo_path = strdup("/");
4293 if (*in_repo_path == NULL)
4294 return got_error_from_errno("strdup");
4295 return NULL;
4298 if (worktree) {
4299 const char *prefix = got_worktree_get_path_prefix(worktree);
4300 char *p;
4302 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4303 if (err)
4304 return err;
4305 if (asprintf(in_repo_path, "%s%s%s", prefix,
4306 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4307 p) == -1) {
4308 err = got_error_from_errno("asprintf");
4309 *in_repo_path = NULL;
4311 free(p);
4312 } else
4313 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4315 return err;
4318 static const struct got_error *
4319 cmd_log(int argc, char *argv[])
4321 const struct got_error *error;
4322 struct got_repository *repo = NULL;
4323 struct got_worktree *worktree = NULL;
4324 struct got_object_id *start_id = NULL;
4325 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4326 char *start_commit = NULL, *label = NULL;
4327 struct got_reference *ref = NULL;
4328 const char *head_ref_name = NULL;
4329 int ch, log_branches = 0;
4330 struct tog_view *view;
4331 int *pack_fds = NULL;
4333 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4334 switch (ch) {
4335 case 'b':
4336 log_branches = 1;
4337 break;
4338 case 'c':
4339 start_commit = optarg;
4340 break;
4341 case 'r':
4342 repo_path = realpath(optarg, NULL);
4343 if (repo_path == NULL)
4344 return got_error_from_errno2("realpath",
4345 optarg);
4346 break;
4347 default:
4348 usage_log();
4349 /* NOTREACHED */
4353 argc -= optind;
4354 argv += optind;
4356 if (argc > 1)
4357 usage_log();
4359 error = got_repo_pack_fds_open(&pack_fds);
4360 if (error != NULL)
4361 goto done;
4363 if (repo_path == NULL) {
4364 cwd = getcwd(NULL, 0);
4365 if (cwd == NULL)
4366 return got_error_from_errno("getcwd");
4367 error = got_worktree_open(&worktree, cwd);
4368 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4369 goto done;
4370 if (worktree)
4371 repo_path =
4372 strdup(got_worktree_get_repo_path(worktree));
4373 else
4374 repo_path = strdup(cwd);
4375 if (repo_path == NULL) {
4376 error = got_error_from_errno("strdup");
4377 goto done;
4381 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4382 if (error != NULL)
4383 goto done;
4385 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4386 repo, worktree);
4387 if (error)
4388 goto done;
4390 init_curses();
4392 error = apply_unveil(got_repo_get_path(repo),
4393 worktree ? got_worktree_get_root_path(worktree) : NULL);
4394 if (error)
4395 goto done;
4397 /* already loaded by tog_log_with_path()? */
4398 if (TAILQ_EMPTY(&tog_refs)) {
4399 error = tog_load_refs(repo, 0);
4400 if (error)
4401 goto done;
4404 if (start_commit == NULL) {
4405 error = got_repo_match_object_id(&start_id, &label,
4406 worktree ? got_worktree_get_head_ref_name(worktree) :
4407 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4408 if (error)
4409 goto done;
4410 head_ref_name = label;
4411 } else {
4412 error = got_ref_open(&ref, repo, start_commit, 0);
4413 if (error == NULL)
4414 head_ref_name = got_ref_get_name(ref);
4415 else if (error->code != GOT_ERR_NOT_REF)
4416 goto done;
4417 error = got_repo_match_object_id(&start_id, NULL,
4418 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4419 if (error)
4420 goto done;
4423 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4424 if (view == NULL) {
4425 error = got_error_from_errno("view_open");
4426 goto done;
4428 error = open_log_view(view, start_id, repo, head_ref_name,
4429 in_repo_path, log_branches);
4430 if (error)
4431 goto done;
4432 if (worktree) {
4433 /* Release work tree lock. */
4434 got_worktree_close(worktree);
4435 worktree = NULL;
4437 error = view_loop(view);
4438 done:
4439 free(in_repo_path);
4440 free(repo_path);
4441 free(cwd);
4442 free(start_id);
4443 free(label);
4444 if (ref)
4445 got_ref_close(ref);
4446 if (repo) {
4447 const struct got_error *close_err = got_repo_close(repo);
4448 if (error == NULL)
4449 error = close_err;
4451 if (worktree)
4452 got_worktree_close(worktree);
4453 if (pack_fds) {
4454 const struct got_error *pack_err =
4455 got_repo_pack_fds_close(pack_fds);
4456 if (error == NULL)
4457 error = pack_err;
4459 tog_free_refs();
4460 return error;
4463 __dead static void
4464 usage_diff(void)
4466 endwin();
4467 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4468 "object1 object2\n", getprogname());
4469 exit(1);
4472 static int
4473 match_line(const char *line, regex_t *regex, size_t nmatch,
4474 regmatch_t *regmatch)
4476 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4479 static struct tog_color *
4480 match_color(struct tog_colors *colors, const char *line)
4482 struct tog_color *tc = NULL;
4484 STAILQ_FOREACH(tc, colors, entry) {
4485 if (match_line(line, &tc->regex, 0, NULL))
4486 return tc;
4489 return NULL;
4492 static const struct got_error *
4493 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4494 WINDOW *window, int skipcol, regmatch_t *regmatch)
4496 const struct got_error *err = NULL;
4497 char *exstr = NULL;
4498 wchar_t *wline = NULL;
4499 int rme, rms, n, width, scrollx;
4500 int width0 = 0, width1 = 0, width2 = 0;
4501 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4503 *wtotal = 0;
4505 rms = regmatch->rm_so;
4506 rme = regmatch->rm_eo;
4508 err = expand_tab(&exstr, line);
4509 if (err)
4510 return err;
4512 /* Split the line into 3 segments, according to match offsets. */
4513 seg0 = strndup(exstr, rms);
4514 if (seg0 == NULL) {
4515 err = got_error_from_errno("strndup");
4516 goto done;
4518 seg1 = strndup(exstr + rms, rme - rms);
4519 if (seg1 == NULL) {
4520 err = got_error_from_errno("strndup");
4521 goto done;
4523 seg2 = strdup(exstr + rme);
4524 if (seg2 == NULL) {
4525 err = got_error_from_errno("strndup");
4526 goto done;
4529 /* draw up to matched token if we haven't scrolled past it */
4530 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4531 col_tab_align, 1);
4532 if (err)
4533 goto done;
4534 n = MAX(width0 - skipcol, 0);
4535 if (n) {
4536 free(wline);
4537 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4538 wlimit, col_tab_align, 1);
4539 if (err)
4540 goto done;
4541 waddwstr(window, &wline[scrollx]);
4542 wlimit -= width;
4543 *wtotal += width;
4546 if (wlimit > 0) {
4547 int i = 0, w = 0;
4548 size_t wlen;
4550 free(wline);
4551 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4552 col_tab_align, 1);
4553 if (err)
4554 goto done;
4555 wlen = wcslen(wline);
4556 while (i < wlen) {
4557 width = wcwidth(wline[i]);
4558 if (width == -1) {
4559 /* should not happen, tabs are expanded */
4560 err = got_error(GOT_ERR_RANGE);
4561 goto done;
4563 if (width0 + w + width > skipcol)
4564 break;
4565 w += width;
4566 i++;
4568 /* draw (visible part of) matched token (if scrolled into it) */
4569 if (width1 - w > 0) {
4570 wattron(window, A_STANDOUT);
4571 waddwstr(window, &wline[i]);
4572 wattroff(window, A_STANDOUT);
4573 wlimit -= (width1 - w);
4574 *wtotal += (width1 - w);
4578 if (wlimit > 0) { /* draw rest of line */
4579 free(wline);
4580 if (skipcol > width0 + width1) {
4581 err = format_line(&wline, &width2, &scrollx, seg2,
4582 skipcol - (width0 + width1), wlimit,
4583 col_tab_align, 1);
4584 if (err)
4585 goto done;
4586 waddwstr(window, &wline[scrollx]);
4587 } else {
4588 err = format_line(&wline, &width2, NULL, seg2, 0,
4589 wlimit, col_tab_align, 1);
4590 if (err)
4591 goto done;
4592 waddwstr(window, wline);
4594 *wtotal += width2;
4596 done:
4597 free(wline);
4598 free(exstr);
4599 free(seg0);
4600 free(seg1);
4601 free(seg2);
4602 return err;
4605 static int
4606 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4608 FILE *f = NULL;
4609 int *eof, *first, *selected;
4611 if (view->type == TOG_VIEW_DIFF) {
4612 struct tog_diff_view_state *s = &view->state.diff;
4614 first = &s->first_displayed_line;
4615 selected = first;
4616 eof = &s->eof;
4617 f = s->f;
4618 } else if (view->type == TOG_VIEW_HELP) {
4619 struct tog_help_view_state *s = &view->state.help;
4621 first = &s->first_displayed_line;
4622 selected = first;
4623 eof = &s->eof;
4624 f = s->f;
4625 } else if (view->type == TOG_VIEW_BLAME) {
4626 struct tog_blame_view_state *s = &view->state.blame;
4628 first = &s->first_displayed_line;
4629 selected = &s->selected_line;
4630 eof = &s->eof;
4631 f = s->blame.f;
4632 } else
4633 return 0;
4635 /* Center gline in the middle of the page like vi(1). */
4636 if (*lineno < view->gline - (view->nlines - 3) / 2)
4637 return 0;
4638 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4639 rewind(f);
4640 *eof = 0;
4641 *first = 1;
4642 *lineno = 0;
4643 *nprinted = 0;
4644 return 0;
4647 *selected = view->gline <= (view->nlines - 3) / 2 ?
4648 view->gline : (view->nlines - 3) / 2 + 1;
4649 view->gline = 0;
4651 return 1;
4654 static const struct got_error *
4655 draw_file(struct tog_view *view, const char *header)
4657 struct tog_diff_view_state *s = &view->state.diff;
4658 regmatch_t *regmatch = &view->regmatch;
4659 const struct got_error *err;
4660 int nprinted = 0;
4661 char *line;
4662 size_t linesize = 0;
4663 ssize_t linelen;
4664 wchar_t *wline;
4665 int width;
4666 int max_lines = view->nlines;
4667 int nlines = s->nlines;
4668 off_t line_offset;
4670 s->lineno = s->first_displayed_line - 1;
4671 line_offset = s->lines[s->first_displayed_line - 1].offset;
4672 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4673 return got_error_from_errno("fseek");
4675 werase(view->window);
4677 if (view->gline > s->nlines - 1)
4678 view->gline = s->nlines - 1;
4680 if (header) {
4681 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4682 1 : view->gline - (view->nlines - 3) / 2 :
4683 s->lineno + s->selected_line;
4685 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4686 return got_error_from_errno("asprintf");
4687 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4688 0, 0);
4689 free(line);
4690 if (err)
4691 return err;
4693 if (view_needs_focus_indication(view))
4694 wstandout(view->window);
4695 waddwstr(view->window, wline);
4696 free(wline);
4697 wline = NULL;
4698 while (width++ < view->ncols)
4699 waddch(view->window, ' ');
4700 if (view_needs_focus_indication(view))
4701 wstandend(view->window);
4703 if (max_lines <= 1)
4704 return NULL;
4705 max_lines--;
4708 s->eof = 0;
4709 view->maxx = 0;
4710 line = NULL;
4711 while (max_lines > 0 && nprinted < max_lines) {
4712 enum got_diff_line_type linetype;
4713 attr_t attr = 0;
4715 linelen = getline(&line, &linesize, s->f);
4716 if (linelen == -1) {
4717 if (feof(s->f)) {
4718 s->eof = 1;
4719 break;
4721 free(line);
4722 return got_ferror(s->f, GOT_ERR_IO);
4725 if (++s->lineno < s->first_displayed_line)
4726 continue;
4727 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4728 continue;
4729 if (s->lineno == view->hiline)
4730 attr = A_STANDOUT;
4732 /* Set view->maxx based on full line length. */
4733 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4734 view->x ? 1 : 0);
4735 if (err) {
4736 free(line);
4737 return err;
4739 view->maxx = MAX(view->maxx, width);
4740 free(wline);
4741 wline = NULL;
4743 linetype = s->lines[s->lineno].type;
4744 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4745 linetype < GOT_DIFF_LINE_CONTEXT)
4746 attr |= COLOR_PAIR(linetype);
4747 if (attr)
4748 wattron(view->window, attr);
4749 if (s->first_displayed_line + nprinted == s->matched_line &&
4750 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4751 err = add_matched_line(&width, line, view->ncols, 0,
4752 view->window, view->x, regmatch);
4753 if (err) {
4754 free(line);
4755 return err;
4757 } else {
4758 int skip;
4759 err = format_line(&wline, &width, &skip, line,
4760 view->x, view->ncols, 0, view->x ? 1 : 0);
4761 if (err) {
4762 free(line);
4763 return err;
4765 waddwstr(view->window, &wline[skip]);
4766 free(wline);
4767 wline = NULL;
4769 if (s->lineno == view->hiline) {
4770 /* highlight full gline length */
4771 while (width++ < view->ncols)
4772 waddch(view->window, ' ');
4773 } else {
4774 if (width <= view->ncols - 1)
4775 waddch(view->window, '\n');
4777 if (attr)
4778 wattroff(view->window, attr);
4779 if (++nprinted == 1)
4780 s->first_displayed_line = s->lineno;
4782 free(line);
4783 if (nprinted >= 1)
4784 s->last_displayed_line = s->first_displayed_line +
4785 (nprinted - 1);
4786 else
4787 s->last_displayed_line = s->first_displayed_line;
4789 view_border(view);
4791 if (s->eof) {
4792 while (nprinted < view->nlines) {
4793 waddch(view->window, '\n');
4794 nprinted++;
4797 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4798 view->ncols, 0, 0);
4799 if (err) {
4800 return err;
4803 wstandout(view->window);
4804 waddwstr(view->window, wline);
4805 free(wline);
4806 wline = NULL;
4807 wstandend(view->window);
4810 return NULL;
4813 static char *
4814 get_datestr(time_t *time, char *datebuf)
4816 struct tm mytm, *tm;
4817 char *p, *s;
4819 tm = gmtime_r(time, &mytm);
4820 if (tm == NULL)
4821 return NULL;
4822 s = asctime_r(tm, datebuf);
4823 if (s == NULL)
4824 return NULL;
4825 p = strchr(s, '\n');
4826 if (p)
4827 *p = '\0';
4828 return s;
4831 static const struct got_error *
4832 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4833 off_t off, uint8_t type)
4835 struct got_diff_line *p;
4837 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4838 if (p == NULL)
4839 return got_error_from_errno("reallocarray");
4840 *lines = p;
4841 (*lines)[*nlines].offset = off;
4842 (*lines)[*nlines].type = type;
4843 (*nlines)++;
4845 return NULL;
4848 static const struct got_error *
4849 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4850 struct got_diff_line *s_lines, size_t s_nlines)
4852 struct got_diff_line *p;
4853 char buf[BUFSIZ];
4854 size_t i, r;
4856 if (fseeko(src, 0L, SEEK_SET) == -1)
4857 return got_error_from_errno("fseeko");
4859 for (;;) {
4860 r = fread(buf, 1, sizeof(buf), src);
4861 if (r == 0) {
4862 if (ferror(src))
4863 return got_error_from_errno("fread");
4864 if (feof(src))
4865 break;
4867 if (fwrite(buf, 1, r, dst) != r)
4868 return got_ferror(dst, GOT_ERR_IO);
4871 if (s_nlines == 0 && *d_nlines == 0)
4872 return NULL;
4875 * If commit info was in dst, increment line offsets
4876 * of the appended diff content, but skip s_lines[0]
4877 * because offset zero is already in *d_lines.
4879 if (*d_nlines > 0) {
4880 for (i = 1; i < s_nlines; ++i)
4881 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4883 if (s_nlines > 0) {
4884 --s_nlines;
4885 ++s_lines;
4889 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4890 if (p == NULL) {
4891 /* d_lines is freed in close_diff_view() */
4892 return got_error_from_errno("reallocarray");
4895 *d_lines = p;
4897 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4898 *d_nlines += s_nlines;
4900 return NULL;
4903 static const struct got_error *
4904 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4905 struct got_object_id *commit_id, struct got_reflist_head *refs,
4906 struct got_repository *repo, int ignore_ws, int force_text_diff,
4907 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4909 const struct got_error *err = NULL;
4910 char datebuf[26], *datestr;
4911 struct got_commit_object *commit;
4912 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4913 time_t committer_time;
4914 const char *author, *committer;
4915 char *refs_str = NULL;
4916 struct got_pathlist_entry *pe;
4917 off_t outoff = 0;
4918 int n;
4920 if (refs) {
4921 err = build_refs_str(&refs_str, refs, commit_id, repo);
4922 if (err)
4923 return err;
4926 err = got_object_open_as_commit(&commit, repo, commit_id);
4927 if (err)
4928 return err;
4930 err = got_object_id_str(&id_str, commit_id);
4931 if (err) {
4932 err = got_error_from_errno("got_object_id_str");
4933 goto done;
4936 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4937 if (err)
4938 goto done;
4940 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4941 refs_str ? refs_str : "", refs_str ? ")" : "");
4942 if (n < 0) {
4943 err = got_error_from_errno("fprintf");
4944 goto done;
4946 outoff += n;
4947 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4948 if (err)
4949 goto done;
4951 n = fprintf(outfile, "from: %s\n",
4952 got_object_commit_get_author(commit));
4953 if (n < 0) {
4954 err = got_error_from_errno("fprintf");
4955 goto done;
4957 outoff += n;
4958 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4959 if (err)
4960 goto done;
4962 author = got_object_commit_get_author(commit);
4963 committer = got_object_commit_get_committer(commit);
4964 if (strcmp(author, committer) != 0) {
4965 n = fprintf(outfile, "via: %s\n", committer);
4966 if (n < 0) {
4967 err = got_error_from_errno("fprintf");
4968 goto done;
4970 outoff += n;
4971 err = add_line_metadata(lines, nlines, outoff,
4972 GOT_DIFF_LINE_AUTHOR);
4973 if (err)
4974 goto done;
4976 committer_time = got_object_commit_get_committer_time(commit);
4977 datestr = get_datestr(&committer_time, datebuf);
4978 if (datestr) {
4979 n = fprintf(outfile, "date: %s UTC\n", datestr);
4980 if (n < 0) {
4981 err = got_error_from_errno("fprintf");
4982 goto done;
4984 outoff += n;
4985 err = add_line_metadata(lines, nlines, outoff,
4986 GOT_DIFF_LINE_DATE);
4987 if (err)
4988 goto done;
4990 if (got_object_commit_get_nparents(commit) > 1) {
4991 const struct got_object_id_queue *parent_ids;
4992 struct got_object_qid *qid;
4993 int pn = 1;
4994 parent_ids = got_object_commit_get_parent_ids(commit);
4995 STAILQ_FOREACH(qid, parent_ids, entry) {
4996 err = got_object_id_str(&id_str, &qid->id);
4997 if (err)
4998 goto done;
4999 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5000 if (n < 0) {
5001 err = got_error_from_errno("fprintf");
5002 goto done;
5004 outoff += n;
5005 err = add_line_metadata(lines, nlines, outoff,
5006 GOT_DIFF_LINE_META);
5007 if (err)
5008 goto done;
5009 free(id_str);
5010 id_str = NULL;
5014 err = got_object_commit_get_logmsg(&logmsg, commit);
5015 if (err)
5016 goto done;
5017 s = logmsg;
5018 while ((line = strsep(&s, "\n")) != NULL) {
5019 n = fprintf(outfile, "%s\n", line);
5020 if (n < 0) {
5021 err = got_error_from_errno("fprintf");
5022 goto done;
5024 outoff += n;
5025 err = add_line_metadata(lines, nlines, outoff,
5026 GOT_DIFF_LINE_LOGMSG);
5027 if (err)
5028 goto done;
5031 TAILQ_FOREACH(pe, dsa->paths, entry) {
5032 struct got_diff_changed_path *cp = pe->data;
5033 int pad = dsa->max_path_len - pe->path_len + 1;
5035 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5036 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5037 dsa->rm_cols + 1, cp->rm);
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,
5044 GOT_DIFF_LINE_CHANGES);
5045 if (err)
5046 goto done;
5049 fputc('\n', outfile);
5050 outoff++;
5051 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5052 if (err)
5053 goto done;
5055 n = fprintf(outfile,
5056 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5057 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5058 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5059 if (n < 0) {
5060 err = got_error_from_errno("fprintf");
5061 goto done;
5063 outoff += n;
5064 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5065 if (err)
5066 goto done;
5068 fputc('\n', outfile);
5069 outoff++;
5070 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5071 done:
5072 free(id_str);
5073 free(logmsg);
5074 free(refs_str);
5075 got_object_commit_close(commit);
5076 if (err) {
5077 free(*lines);
5078 *lines = NULL;
5079 *nlines = 0;
5081 return err;
5084 static const struct got_error *
5085 create_diff(struct tog_diff_view_state *s)
5087 const struct got_error *err = NULL;
5088 FILE *f = NULL, *tmp_diff_file = NULL;
5089 int obj_type;
5090 struct got_diff_line *lines = NULL;
5091 struct got_pathlist_head changed_paths;
5093 TAILQ_INIT(&changed_paths);
5095 free(s->lines);
5096 s->lines = malloc(sizeof(*s->lines));
5097 if (s->lines == NULL)
5098 return got_error_from_errno("malloc");
5099 s->nlines = 0;
5101 f = got_opentemp();
5102 if (f == NULL) {
5103 err = got_error_from_errno("got_opentemp");
5104 goto done;
5106 tmp_diff_file = got_opentemp();
5107 if (tmp_diff_file == NULL) {
5108 err = got_error_from_errno("got_opentemp");
5109 goto done;
5111 if (s->f && fclose(s->f) == EOF) {
5112 err = got_error_from_errno("fclose");
5113 goto done;
5115 s->f = f;
5117 if (s->id1)
5118 err = got_object_get_type(&obj_type, s->repo, s->id1);
5119 else
5120 err = got_object_get_type(&obj_type, s->repo, s->id2);
5121 if (err)
5122 goto done;
5124 switch (obj_type) {
5125 case GOT_OBJ_TYPE_BLOB:
5126 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5127 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5128 s->label1, s->label2, tog_diff_algo, s->diff_context,
5129 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5130 s->f);
5131 break;
5132 case GOT_OBJ_TYPE_TREE:
5133 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5134 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5135 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5136 s->force_text_diff, NULL, s->repo, s->f);
5137 break;
5138 case GOT_OBJ_TYPE_COMMIT: {
5139 const struct got_object_id_queue *parent_ids;
5140 struct got_object_qid *pid;
5141 struct got_commit_object *commit2;
5142 struct got_reflist_head *refs;
5143 size_t nlines = 0;
5144 struct got_diffstat_cb_arg dsa = {
5145 0, 0, 0, 0, 0, 0,
5146 &changed_paths,
5147 s->ignore_whitespace,
5148 s->force_text_diff,
5149 tog_diff_algo
5152 lines = malloc(sizeof(*lines));
5153 if (lines == NULL) {
5154 err = got_error_from_errno("malloc");
5155 goto done;
5158 /* build diff first in tmp file then append to commit info */
5159 err = got_diff_objects_as_commits(&lines, &nlines,
5160 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5161 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5162 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5163 if (err)
5164 break;
5166 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5167 if (err)
5168 goto done;
5169 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5170 /* Show commit info if we're diffing to a parent/root commit. */
5171 if (s->id1 == NULL) {
5172 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5173 refs, s->repo, s->ignore_whitespace,
5174 s->force_text_diff, &dsa, s->f);
5175 if (err)
5176 goto done;
5177 } else {
5178 parent_ids = got_object_commit_get_parent_ids(commit2);
5179 STAILQ_FOREACH(pid, parent_ids, entry) {
5180 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5181 err = write_commit_info(&s->lines,
5182 &s->nlines, s->id2, refs, s->repo,
5183 s->ignore_whitespace,
5184 s->force_text_diff, &dsa, s->f);
5185 if (err)
5186 goto done;
5187 break;
5191 got_object_commit_close(commit2);
5193 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5194 lines, nlines);
5195 break;
5197 default:
5198 err = got_error(GOT_ERR_OBJ_TYPE);
5199 break;
5201 done:
5202 free(lines);
5203 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5204 if (s->f && fflush(s->f) != 0 && err == NULL)
5205 err = got_error_from_errno("fflush");
5206 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5207 err = got_error_from_errno("fclose");
5208 return err;
5211 static void
5212 diff_view_indicate_progress(struct tog_view *view)
5214 mvwaddstr(view->window, 0, 0, "diffing...");
5215 update_panels();
5216 doupdate();
5219 static const struct got_error *
5220 search_start_diff_view(struct tog_view *view)
5222 struct tog_diff_view_state *s = &view->state.diff;
5224 s->matched_line = 0;
5225 return NULL;
5228 static void
5229 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5230 size_t *nlines, int **first, int **last, int **match, int **selected)
5232 struct tog_diff_view_state *s = &view->state.diff;
5234 *f = s->f;
5235 *nlines = s->nlines;
5236 *line_offsets = NULL;
5237 *match = &s->matched_line;
5238 *first = &s->first_displayed_line;
5239 *last = &s->last_displayed_line;
5240 *selected = &s->selected_line;
5243 static const struct got_error *
5244 search_next_view_match(struct tog_view *view)
5246 const struct got_error *err = NULL;
5247 FILE *f;
5248 int lineno;
5249 char *line = NULL;
5250 size_t linesize = 0;
5251 ssize_t linelen;
5252 off_t *line_offsets;
5253 size_t nlines = 0;
5254 int *first, *last, *match, *selected;
5256 if (!view->search_setup)
5257 return got_error_msg(GOT_ERR_NOT_IMPL,
5258 "view search not supported");
5259 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5260 &match, &selected);
5262 if (!view->searching) {
5263 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5264 return NULL;
5267 if (*match) {
5268 if (view->searching == TOG_SEARCH_FORWARD)
5269 lineno = *first + 1;
5270 else
5271 lineno = *first - 1;
5272 } else
5273 lineno = *first - 1 + *selected;
5275 while (1) {
5276 off_t offset;
5278 if (lineno <= 0 || lineno > nlines) {
5279 if (*match == 0) {
5280 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5281 break;
5284 if (view->searching == TOG_SEARCH_FORWARD)
5285 lineno = 1;
5286 else
5287 lineno = nlines;
5290 offset = view->type == TOG_VIEW_DIFF ?
5291 view->state.diff.lines[lineno - 1].offset :
5292 line_offsets[lineno - 1];
5293 if (fseeko(f, offset, SEEK_SET) != 0) {
5294 free(line);
5295 return got_error_from_errno("fseeko");
5297 linelen = getline(&line, &linesize, f);
5298 if (linelen != -1) {
5299 char *exstr;
5300 err = expand_tab(&exstr, line);
5301 if (err)
5302 break;
5303 if (match_line(exstr, &view->regex, 1,
5304 &view->regmatch)) {
5305 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5306 *match = lineno;
5307 free(exstr);
5308 break;
5310 free(exstr);
5312 if (view->searching == TOG_SEARCH_FORWARD)
5313 lineno++;
5314 else
5315 lineno--;
5317 free(line);
5319 if (*match) {
5320 *first = *match;
5321 *selected = 1;
5324 return err;
5327 static const struct got_error *
5328 close_diff_view(struct tog_view *view)
5330 const struct got_error *err = NULL;
5331 struct tog_diff_view_state *s = &view->state.diff;
5333 free(s->id1);
5334 s->id1 = NULL;
5335 free(s->id2);
5336 s->id2 = NULL;
5337 if (s->f && fclose(s->f) == EOF)
5338 err = got_error_from_errno("fclose");
5339 s->f = NULL;
5340 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5341 err = got_error_from_errno("fclose");
5342 s->f1 = NULL;
5343 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5344 err = got_error_from_errno("fclose");
5345 s->f2 = NULL;
5346 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5347 err = got_error_from_errno("close");
5348 s->fd1 = -1;
5349 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5350 err = got_error_from_errno("close");
5351 s->fd2 = -1;
5352 free(s->lines);
5353 s->lines = NULL;
5354 s->nlines = 0;
5355 return err;
5358 static const struct got_error *
5359 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5360 struct got_object_id *id2, const char *label1, const char *label2,
5361 int diff_context, int ignore_whitespace, int force_text_diff,
5362 struct tog_view *parent_view, struct got_repository *repo)
5364 const struct got_error *err;
5365 struct tog_diff_view_state *s = &view->state.diff;
5367 memset(s, 0, sizeof(*s));
5368 s->fd1 = -1;
5369 s->fd2 = -1;
5371 if (id1 != NULL && id2 != NULL) {
5372 int type1, type2;
5374 err = got_object_get_type(&type1, repo, id1);
5375 if (err)
5376 goto done;
5377 err = got_object_get_type(&type2, repo, id2);
5378 if (err)
5379 goto done;
5381 if (type1 != type2) {
5382 err = got_error(GOT_ERR_OBJ_TYPE);
5383 goto done;
5386 s->first_displayed_line = 1;
5387 s->last_displayed_line = view->nlines;
5388 s->selected_line = 1;
5389 s->repo = repo;
5390 s->id1 = id1;
5391 s->id2 = id2;
5392 s->label1 = label1;
5393 s->label2 = label2;
5395 if (id1) {
5396 s->id1 = got_object_id_dup(id1);
5397 if (s->id1 == NULL) {
5398 err = got_error_from_errno("got_object_id_dup");
5399 goto done;
5401 } else
5402 s->id1 = NULL;
5404 s->id2 = got_object_id_dup(id2);
5405 if (s->id2 == NULL) {
5406 err = got_error_from_errno("got_object_id_dup");
5407 goto done;
5410 s->f1 = got_opentemp();
5411 if (s->f1 == NULL) {
5412 err = got_error_from_errno("got_opentemp");
5413 goto done;
5416 s->f2 = got_opentemp();
5417 if (s->f2 == NULL) {
5418 err = got_error_from_errno("got_opentemp");
5419 goto done;
5422 s->fd1 = got_opentempfd();
5423 if (s->fd1 == -1) {
5424 err = got_error_from_errno("got_opentempfd");
5425 goto done;
5428 s->fd2 = got_opentempfd();
5429 if (s->fd2 == -1) {
5430 err = got_error_from_errno("got_opentempfd");
5431 goto done;
5434 s->diff_context = diff_context;
5435 s->ignore_whitespace = ignore_whitespace;
5436 s->force_text_diff = force_text_diff;
5437 s->parent_view = parent_view;
5438 s->repo = repo;
5440 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5441 int rc;
5443 rc = init_pair(GOT_DIFF_LINE_MINUS,
5444 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5445 if (rc != ERR)
5446 rc = init_pair(GOT_DIFF_LINE_PLUS,
5447 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5448 if (rc != ERR)
5449 rc = init_pair(GOT_DIFF_LINE_HUNK,
5450 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5451 if (rc != ERR)
5452 rc = init_pair(GOT_DIFF_LINE_META,
5453 get_color_value("TOG_COLOR_DIFF_META"), -1);
5454 if (rc != ERR)
5455 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5456 get_color_value("TOG_COLOR_DIFF_META"), -1);
5457 if (rc != ERR)
5458 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5459 get_color_value("TOG_COLOR_DIFF_META"), -1);
5460 if (rc != ERR)
5461 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5462 get_color_value("TOG_COLOR_DIFF_META"), -1);
5463 if (rc != ERR)
5464 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5465 get_color_value("TOG_COLOR_AUTHOR"), -1);
5466 if (rc != ERR)
5467 rc = init_pair(GOT_DIFF_LINE_DATE,
5468 get_color_value("TOG_COLOR_DATE"), -1);
5469 if (rc == ERR) {
5470 err = got_error(GOT_ERR_RANGE);
5471 goto done;
5475 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5476 view_is_splitscreen(view))
5477 show_log_view(parent_view); /* draw border */
5478 diff_view_indicate_progress(view);
5480 err = create_diff(s);
5482 view->show = show_diff_view;
5483 view->input = input_diff_view;
5484 view->reset = reset_diff_view;
5485 view->close = close_diff_view;
5486 view->search_start = search_start_diff_view;
5487 view->search_setup = search_setup_diff_view;
5488 view->search_next = search_next_view_match;
5489 done:
5490 if (err) {
5491 if (view->close == NULL)
5492 close_diff_view(view);
5493 view_close(view);
5495 return err;
5498 static const struct got_error *
5499 show_diff_view(struct tog_view *view)
5501 const struct got_error *err;
5502 struct tog_diff_view_state *s = &view->state.diff;
5503 char *id_str1 = NULL, *id_str2, *header;
5504 const char *label1, *label2;
5506 if (s->id1) {
5507 err = got_object_id_str(&id_str1, s->id1);
5508 if (err)
5509 return err;
5510 label1 = s->label1 ? s->label1 : id_str1;
5511 } else
5512 label1 = "/dev/null";
5514 err = got_object_id_str(&id_str2, s->id2);
5515 if (err)
5516 return err;
5517 label2 = s->label2 ? s->label2 : id_str2;
5519 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5520 err = got_error_from_errno("asprintf");
5521 free(id_str1);
5522 free(id_str2);
5523 return err;
5525 free(id_str1);
5526 free(id_str2);
5528 err = draw_file(view, header);
5529 free(header);
5530 return err;
5533 static const struct got_error *
5534 set_selected_commit(struct tog_diff_view_state *s,
5535 struct commit_queue_entry *entry)
5537 const struct got_error *err;
5538 const struct got_object_id_queue *parent_ids;
5539 struct got_commit_object *selected_commit;
5540 struct got_object_qid *pid;
5542 free(s->id2);
5543 s->id2 = got_object_id_dup(entry->id);
5544 if (s->id2 == NULL)
5545 return got_error_from_errno("got_object_id_dup");
5547 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5548 if (err)
5549 return err;
5550 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5551 free(s->id1);
5552 pid = STAILQ_FIRST(parent_ids);
5553 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5554 got_object_commit_close(selected_commit);
5555 return NULL;
5558 static const struct got_error *
5559 reset_diff_view(struct tog_view *view)
5561 struct tog_diff_view_state *s = &view->state.diff;
5563 view->count = 0;
5564 wclear(view->window);
5565 s->first_displayed_line = 1;
5566 s->last_displayed_line = view->nlines;
5567 s->matched_line = 0;
5568 diff_view_indicate_progress(view);
5569 return create_diff(s);
5572 static void
5573 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5575 int start, i;
5577 i = start = s->first_displayed_line - 1;
5579 while (s->lines[i].type != type) {
5580 if (i == 0)
5581 i = s->nlines - 1;
5582 if (--i == start)
5583 return; /* do nothing, requested type not in file */
5586 s->selected_line = 1;
5587 s->first_displayed_line = i;
5590 static void
5591 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5593 int start, i;
5595 i = start = s->first_displayed_line + 1;
5597 while (s->lines[i].type != type) {
5598 if (i == s->nlines - 1)
5599 i = 0;
5600 if (++i == start)
5601 return; /* do nothing, requested type not in file */
5604 s->selected_line = 1;
5605 s->first_displayed_line = i;
5608 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5609 int, int, int);
5610 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5611 int, int);
5613 static const struct got_error *
5614 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5616 const struct got_error *err = NULL;
5617 struct tog_diff_view_state *s = &view->state.diff;
5618 struct tog_log_view_state *ls;
5619 struct commit_queue_entry *old_selected_entry;
5620 char *line = NULL;
5621 size_t linesize = 0;
5622 ssize_t linelen;
5623 int i, nscroll = view->nlines - 1, up = 0;
5625 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5627 switch (ch) {
5628 case '0':
5629 case '$':
5630 case KEY_RIGHT:
5631 case 'l':
5632 case KEY_LEFT:
5633 case 'h':
5634 horizontal_scroll_input(view, ch);
5635 break;
5636 case 'a':
5637 case 'w':
5638 if (ch == 'a') {
5639 s->force_text_diff = !s->force_text_diff;
5640 view->action = s->force_text_diff ?
5641 "force ASCII text enabled" :
5642 "force ASCII text disabled";
5644 else if (ch == 'w') {
5645 s->ignore_whitespace = !s->ignore_whitespace;
5646 view->action = s->ignore_whitespace ?
5647 "ignore whitespace enabled" :
5648 "ignore whitespace disabled";
5650 err = reset_diff_view(view);
5651 break;
5652 case 'g':
5653 case KEY_HOME:
5654 s->first_displayed_line = 1;
5655 view->count = 0;
5656 break;
5657 case 'G':
5658 case KEY_END:
5659 view->count = 0;
5660 if (s->eof)
5661 break;
5663 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5664 s->eof = 1;
5665 break;
5666 case 'k':
5667 case KEY_UP:
5668 case CTRL('p'):
5669 if (s->first_displayed_line > 1)
5670 s->first_displayed_line--;
5671 else
5672 view->count = 0;
5673 break;
5674 case CTRL('u'):
5675 case 'u':
5676 nscroll /= 2;
5677 /* FALL THROUGH */
5678 case KEY_PPAGE:
5679 case CTRL('b'):
5680 case 'b':
5681 if (s->first_displayed_line == 1) {
5682 view->count = 0;
5683 break;
5685 i = 0;
5686 while (i++ < nscroll && s->first_displayed_line > 1)
5687 s->first_displayed_line--;
5688 break;
5689 case 'j':
5690 case KEY_DOWN:
5691 case CTRL('n'):
5692 if (!s->eof)
5693 s->first_displayed_line++;
5694 else
5695 view->count = 0;
5696 break;
5697 case CTRL('d'):
5698 case 'd':
5699 nscroll /= 2;
5700 /* FALL THROUGH */
5701 case KEY_NPAGE:
5702 case CTRL('f'):
5703 case 'f':
5704 case ' ':
5705 if (s->eof) {
5706 view->count = 0;
5707 break;
5709 i = 0;
5710 while (!s->eof && i++ < nscroll) {
5711 linelen = getline(&line, &linesize, s->f);
5712 s->first_displayed_line++;
5713 if (linelen == -1) {
5714 if (feof(s->f)) {
5715 s->eof = 1;
5716 } else
5717 err = got_ferror(s->f, GOT_ERR_IO);
5718 break;
5721 free(line);
5722 break;
5723 case '(':
5724 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5725 break;
5726 case ')':
5727 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5728 break;
5729 case '{':
5730 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5731 break;
5732 case '}':
5733 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5734 break;
5735 case '[':
5736 if (s->diff_context > 0) {
5737 s->diff_context--;
5738 s->matched_line = 0;
5739 diff_view_indicate_progress(view);
5740 err = create_diff(s);
5741 if (s->first_displayed_line + view->nlines - 1 >
5742 s->nlines) {
5743 s->first_displayed_line = 1;
5744 s->last_displayed_line = view->nlines;
5746 } else
5747 view->count = 0;
5748 break;
5749 case ']':
5750 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5751 s->diff_context++;
5752 s->matched_line = 0;
5753 diff_view_indicate_progress(view);
5754 err = create_diff(s);
5755 } else
5756 view->count = 0;
5757 break;
5758 case '<':
5759 case ',':
5760 case 'K':
5761 up = 1;
5762 /* FALL THROUGH */
5763 case '>':
5764 case '.':
5765 case 'J':
5766 if (s->parent_view == NULL) {
5767 view->count = 0;
5768 break;
5770 s->parent_view->count = view->count;
5772 if (s->parent_view->type == TOG_VIEW_LOG) {
5773 ls = &s->parent_view->state.log;
5774 old_selected_entry = ls->selected_entry;
5776 err = input_log_view(NULL, s->parent_view,
5777 up ? KEY_UP : KEY_DOWN);
5778 if (err)
5779 break;
5780 view->count = s->parent_view->count;
5782 if (old_selected_entry == ls->selected_entry)
5783 break;
5785 err = set_selected_commit(s, ls->selected_entry);
5786 if (err)
5787 break;
5788 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5789 struct tog_blame_view_state *bs;
5790 struct got_object_id *id, *prev_id;
5792 bs = &s->parent_view->state.blame;
5793 prev_id = get_annotation_for_line(bs->blame.lines,
5794 bs->blame.nlines, bs->last_diffed_line);
5796 err = input_blame_view(&view, s->parent_view,
5797 up ? KEY_UP : KEY_DOWN);
5798 if (err)
5799 break;
5800 view->count = s->parent_view->count;
5802 if (prev_id == NULL)
5803 break;
5804 id = get_selected_commit_id(bs->blame.lines,
5805 bs->blame.nlines, bs->first_displayed_line,
5806 bs->selected_line);
5807 if (id == NULL)
5808 break;
5810 if (!got_object_id_cmp(prev_id, id))
5811 break;
5813 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5814 if (err)
5815 break;
5817 s->first_displayed_line = 1;
5818 s->last_displayed_line = view->nlines;
5819 s->matched_line = 0;
5820 view->x = 0;
5822 diff_view_indicate_progress(view);
5823 err = create_diff(s);
5824 break;
5825 default:
5826 view->count = 0;
5827 break;
5830 return err;
5833 static const struct got_error *
5834 cmd_diff(int argc, char *argv[])
5836 const struct got_error *error;
5837 struct got_repository *repo = NULL;
5838 struct got_worktree *worktree = NULL;
5839 struct got_object_id *id1 = NULL, *id2 = NULL;
5840 char *repo_path = NULL, *cwd = NULL;
5841 char *id_str1 = NULL, *id_str2 = NULL;
5842 char *label1 = NULL, *label2 = NULL;
5843 int diff_context = 3, ignore_whitespace = 0;
5844 int ch, force_text_diff = 0;
5845 const char *errstr;
5846 struct tog_view *view;
5847 int *pack_fds = NULL;
5849 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5850 switch (ch) {
5851 case 'a':
5852 force_text_diff = 1;
5853 break;
5854 case 'C':
5855 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5856 &errstr);
5857 if (errstr != NULL)
5858 errx(1, "number of context lines is %s: %s",
5859 errstr, errstr);
5860 break;
5861 case 'r':
5862 repo_path = realpath(optarg, NULL);
5863 if (repo_path == NULL)
5864 return got_error_from_errno2("realpath",
5865 optarg);
5866 got_path_strip_trailing_slashes(repo_path);
5867 break;
5868 case 'w':
5869 ignore_whitespace = 1;
5870 break;
5871 default:
5872 usage_diff();
5873 /* NOTREACHED */
5877 argc -= optind;
5878 argv += optind;
5880 if (argc == 0) {
5881 usage_diff(); /* TODO show local worktree changes */
5882 } else if (argc == 2) {
5883 id_str1 = argv[0];
5884 id_str2 = argv[1];
5885 } else
5886 usage_diff();
5888 error = got_repo_pack_fds_open(&pack_fds);
5889 if (error)
5890 goto done;
5892 if (repo_path == NULL) {
5893 cwd = getcwd(NULL, 0);
5894 if (cwd == NULL)
5895 return got_error_from_errno("getcwd");
5896 error = got_worktree_open(&worktree, cwd);
5897 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5898 goto done;
5899 if (worktree)
5900 repo_path =
5901 strdup(got_worktree_get_repo_path(worktree));
5902 else
5903 repo_path = strdup(cwd);
5904 if (repo_path == NULL) {
5905 error = got_error_from_errno("strdup");
5906 goto done;
5910 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5911 if (error)
5912 goto done;
5914 init_curses();
5916 error = apply_unveil(got_repo_get_path(repo), NULL);
5917 if (error)
5918 goto done;
5920 error = tog_load_refs(repo, 0);
5921 if (error)
5922 goto done;
5924 error = got_repo_match_object_id(&id1, &label1, id_str1,
5925 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5926 if (error)
5927 goto done;
5929 error = got_repo_match_object_id(&id2, &label2, id_str2,
5930 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5931 if (error)
5932 goto done;
5934 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5935 if (view == NULL) {
5936 error = got_error_from_errno("view_open");
5937 goto done;
5939 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5940 ignore_whitespace, force_text_diff, NULL, repo);
5941 if (error)
5942 goto done;
5943 error = view_loop(view);
5944 done:
5945 free(label1);
5946 free(label2);
5947 free(repo_path);
5948 free(cwd);
5949 if (repo) {
5950 const struct got_error *close_err = got_repo_close(repo);
5951 if (error == NULL)
5952 error = close_err;
5954 if (worktree)
5955 got_worktree_close(worktree);
5956 if (pack_fds) {
5957 const struct got_error *pack_err =
5958 got_repo_pack_fds_close(pack_fds);
5959 if (error == NULL)
5960 error = pack_err;
5962 tog_free_refs();
5963 return error;
5966 __dead static void
5967 usage_blame(void)
5969 endwin();
5970 fprintf(stderr,
5971 "usage: %s blame [-c commit] [-r repository-path] path\n",
5972 getprogname());
5973 exit(1);
5976 struct tog_blame_line {
5977 int annotated;
5978 struct got_object_id *id;
5981 static const struct got_error *
5982 draw_blame(struct tog_view *view)
5984 struct tog_blame_view_state *s = &view->state.blame;
5985 struct tog_blame *blame = &s->blame;
5986 regmatch_t *regmatch = &view->regmatch;
5987 const struct got_error *err;
5988 int lineno = 0, nprinted = 0;
5989 char *line = NULL;
5990 size_t linesize = 0;
5991 ssize_t linelen;
5992 wchar_t *wline;
5993 int width;
5994 struct tog_blame_line *blame_line;
5995 struct got_object_id *prev_id = NULL;
5996 char *id_str;
5997 struct tog_color *tc;
5999 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6000 if (err)
6001 return err;
6003 rewind(blame->f);
6004 werase(view->window);
6006 if (asprintf(&line, "commit %s", id_str) == -1) {
6007 err = got_error_from_errno("asprintf");
6008 free(id_str);
6009 return err;
6012 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6013 free(line);
6014 line = NULL;
6015 if (err)
6016 return err;
6017 if (view_needs_focus_indication(view))
6018 wstandout(view->window);
6019 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6020 if (tc)
6021 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6022 waddwstr(view->window, wline);
6023 while (width++ < view->ncols)
6024 waddch(view->window, ' ');
6025 if (tc)
6026 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6027 if (view_needs_focus_indication(view))
6028 wstandend(view->window);
6029 free(wline);
6030 wline = NULL;
6032 if (view->gline > blame->nlines)
6033 view->gline = blame->nlines;
6035 if (tog_io.wait_for_ui) {
6036 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6037 int rc;
6039 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6040 if (rc)
6041 return got_error_set_errno(rc, "pthread_cond_wait");
6042 tog_io.wait_for_ui = 0;
6045 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6046 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6047 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6048 free(id_str);
6049 return got_error_from_errno("asprintf");
6051 free(id_str);
6052 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6053 free(line);
6054 line = NULL;
6055 if (err)
6056 return err;
6057 waddwstr(view->window, wline);
6058 free(wline);
6059 wline = NULL;
6060 if (width < view->ncols - 1)
6061 waddch(view->window, '\n');
6063 s->eof = 0;
6064 view->maxx = 0;
6065 while (nprinted < view->nlines - 2) {
6066 linelen = getline(&line, &linesize, blame->f);
6067 if (linelen == -1) {
6068 if (feof(blame->f)) {
6069 s->eof = 1;
6070 break;
6072 free(line);
6073 return got_ferror(blame->f, GOT_ERR_IO);
6075 if (++lineno < s->first_displayed_line)
6076 continue;
6077 if (view->gline && !gotoline(view, &lineno, &nprinted))
6078 continue;
6080 /* Set view->maxx based on full line length. */
6081 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6082 if (err) {
6083 free(line);
6084 return err;
6086 free(wline);
6087 wline = NULL;
6088 view->maxx = MAX(view->maxx, width);
6090 if (nprinted == s->selected_line - 1)
6091 wstandout(view->window);
6093 if (blame->nlines > 0) {
6094 blame_line = &blame->lines[lineno - 1];
6095 if (blame_line->annotated && prev_id &&
6096 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6097 !(nprinted == s->selected_line - 1)) {
6098 waddstr(view->window, " ");
6099 } else if (blame_line->annotated) {
6100 char *id_str;
6101 err = got_object_id_str(&id_str,
6102 blame_line->id);
6103 if (err) {
6104 free(line);
6105 return err;
6107 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6108 if (tc)
6109 wattr_on(view->window,
6110 COLOR_PAIR(tc->colorpair), NULL);
6111 wprintw(view->window, "%.8s", id_str);
6112 if (tc)
6113 wattr_off(view->window,
6114 COLOR_PAIR(tc->colorpair), NULL);
6115 free(id_str);
6116 prev_id = blame_line->id;
6117 } else {
6118 waddstr(view->window, "........");
6119 prev_id = NULL;
6121 } else {
6122 waddstr(view->window, "........");
6123 prev_id = NULL;
6126 if (nprinted == s->selected_line - 1)
6127 wstandend(view->window);
6128 waddstr(view->window, " ");
6130 if (view->ncols <= 9) {
6131 width = 9;
6132 } else if (s->first_displayed_line + nprinted ==
6133 s->matched_line &&
6134 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6135 err = add_matched_line(&width, line, view->ncols - 9, 9,
6136 view->window, view->x, regmatch);
6137 if (err) {
6138 free(line);
6139 return err;
6141 width += 9;
6142 } else {
6143 int skip;
6144 err = format_line(&wline, &width, &skip, line,
6145 view->x, view->ncols - 9, 9, 1);
6146 if (err) {
6147 free(line);
6148 return err;
6150 waddwstr(view->window, &wline[skip]);
6151 width += 9;
6152 free(wline);
6153 wline = NULL;
6156 if (width <= view->ncols - 1)
6157 waddch(view->window, '\n');
6158 if (++nprinted == 1)
6159 s->first_displayed_line = lineno;
6161 free(line);
6162 s->last_displayed_line = lineno;
6164 view_border(view);
6166 return NULL;
6169 static const struct got_error *
6170 blame_cb(void *arg, int nlines, int lineno,
6171 struct got_commit_object *commit, struct got_object_id *id)
6173 const struct got_error *err = NULL;
6174 struct tog_blame_cb_args *a = arg;
6175 struct tog_blame_line *line;
6176 int errcode;
6178 if (nlines != a->nlines ||
6179 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6180 return got_error(GOT_ERR_RANGE);
6182 errcode = pthread_mutex_lock(&tog_mutex);
6183 if (errcode)
6184 return got_error_set_errno(errcode, "pthread_mutex_lock");
6186 if (*a->quit) { /* user has quit the blame view */
6187 err = got_error(GOT_ERR_ITER_COMPLETED);
6188 goto done;
6191 if (lineno == -1)
6192 goto done; /* no change in this commit */
6194 line = &a->lines[lineno - 1];
6195 if (line->annotated)
6196 goto done;
6198 line->id = got_object_id_dup(id);
6199 if (line->id == NULL) {
6200 err = got_error_from_errno("got_object_id_dup");
6201 goto done;
6203 line->annotated = 1;
6204 done:
6205 errcode = pthread_mutex_unlock(&tog_mutex);
6206 if (errcode)
6207 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6208 return err;
6211 static void *
6212 blame_thread(void *arg)
6214 const struct got_error *err, *close_err;
6215 struct tog_blame_thread_args *ta = arg;
6216 struct tog_blame_cb_args *a = ta->cb_args;
6217 int errcode, fd1 = -1, fd2 = -1;
6218 FILE *f1 = NULL, *f2 = NULL;
6220 fd1 = got_opentempfd();
6221 if (fd1 == -1)
6222 return (void *)got_error_from_errno("got_opentempfd");
6224 fd2 = got_opentempfd();
6225 if (fd2 == -1) {
6226 err = got_error_from_errno("got_opentempfd");
6227 goto done;
6230 f1 = got_opentemp();
6231 if (f1 == NULL) {
6232 err = (void *)got_error_from_errno("got_opentemp");
6233 goto done;
6235 f2 = got_opentemp();
6236 if (f2 == NULL) {
6237 err = (void *)got_error_from_errno("got_opentemp");
6238 goto done;
6241 err = block_signals_used_by_main_thread();
6242 if (err)
6243 goto done;
6245 err = got_blame(ta->path, a->commit_id, ta->repo,
6246 tog_diff_algo, blame_cb, ta->cb_args,
6247 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6248 if (err && err->code == GOT_ERR_CANCELLED)
6249 err = NULL;
6251 errcode = pthread_mutex_lock(&tog_mutex);
6252 if (errcode) {
6253 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6254 goto done;
6257 close_err = got_repo_close(ta->repo);
6258 if (err == NULL)
6259 err = close_err;
6260 ta->repo = NULL;
6261 *ta->complete = 1;
6263 if (tog_io.wait_for_ui) {
6264 errcode = pthread_cond_signal(&ta->blame_complete);
6265 if (errcode && err == NULL)
6266 err = got_error_set_errno(errcode,
6267 "pthread_cond_signal");
6270 errcode = pthread_mutex_unlock(&tog_mutex);
6271 if (errcode && err == NULL)
6272 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6274 done:
6275 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6276 err = got_error_from_errno("close");
6277 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6278 err = got_error_from_errno("close");
6279 if (f1 && fclose(f1) == EOF && err == NULL)
6280 err = got_error_from_errno("fclose");
6281 if (f2 && fclose(f2) == EOF && err == NULL)
6282 err = got_error_from_errno("fclose");
6284 return (void *)err;
6287 static struct got_object_id *
6288 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6289 int first_displayed_line, int selected_line)
6291 struct tog_blame_line *line;
6293 if (nlines <= 0)
6294 return NULL;
6296 line = &lines[first_displayed_line - 1 + selected_line - 1];
6297 if (!line->annotated)
6298 return NULL;
6300 return line->id;
6303 static struct got_object_id *
6304 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6305 int lineno)
6307 struct tog_blame_line *line;
6309 if (nlines <= 0 || lineno >= nlines)
6310 return NULL;
6312 line = &lines[lineno - 1];
6313 if (!line->annotated)
6314 return NULL;
6316 return line->id;
6319 static const struct got_error *
6320 stop_blame(struct tog_blame *blame)
6322 const struct got_error *err = NULL;
6323 int i;
6325 if (blame->thread) {
6326 int errcode;
6327 errcode = pthread_mutex_unlock(&tog_mutex);
6328 if (errcode)
6329 return got_error_set_errno(errcode,
6330 "pthread_mutex_unlock");
6331 errcode = pthread_join(blame->thread, (void **)&err);
6332 if (errcode)
6333 return got_error_set_errno(errcode, "pthread_join");
6334 errcode = pthread_mutex_lock(&tog_mutex);
6335 if (errcode)
6336 return got_error_set_errno(errcode,
6337 "pthread_mutex_lock");
6338 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6339 err = NULL;
6340 blame->thread = NULL;
6342 if (blame->thread_args.repo) {
6343 const struct got_error *close_err;
6344 close_err = got_repo_close(blame->thread_args.repo);
6345 if (err == NULL)
6346 err = close_err;
6347 blame->thread_args.repo = NULL;
6349 if (blame->f) {
6350 if (fclose(blame->f) == EOF && err == NULL)
6351 err = got_error_from_errno("fclose");
6352 blame->f = NULL;
6354 if (blame->lines) {
6355 for (i = 0; i < blame->nlines; i++)
6356 free(blame->lines[i].id);
6357 free(blame->lines);
6358 blame->lines = NULL;
6360 free(blame->cb_args.commit_id);
6361 blame->cb_args.commit_id = NULL;
6362 if (blame->pack_fds) {
6363 const struct got_error *pack_err =
6364 got_repo_pack_fds_close(blame->pack_fds);
6365 if (err == NULL)
6366 err = pack_err;
6367 blame->pack_fds = NULL;
6369 return err;
6372 static const struct got_error *
6373 cancel_blame_view(void *arg)
6375 const struct got_error *err = NULL;
6376 int *done = arg;
6377 int errcode;
6379 errcode = pthread_mutex_lock(&tog_mutex);
6380 if (errcode)
6381 return got_error_set_errno(errcode,
6382 "pthread_mutex_unlock");
6384 if (*done)
6385 err = got_error(GOT_ERR_CANCELLED);
6387 errcode = pthread_mutex_unlock(&tog_mutex);
6388 if (errcode)
6389 return got_error_set_errno(errcode,
6390 "pthread_mutex_lock");
6392 return err;
6395 static const struct got_error *
6396 run_blame(struct tog_view *view)
6398 struct tog_blame_view_state *s = &view->state.blame;
6399 struct tog_blame *blame = &s->blame;
6400 const struct got_error *err = NULL;
6401 struct got_commit_object *commit = NULL;
6402 struct got_blob_object *blob = NULL;
6403 struct got_repository *thread_repo = NULL;
6404 struct got_object_id *obj_id = NULL;
6405 int obj_type, fd = -1;
6406 int *pack_fds = NULL;
6408 err = got_object_open_as_commit(&commit, s->repo,
6409 &s->blamed_commit->id);
6410 if (err)
6411 return err;
6413 fd = got_opentempfd();
6414 if (fd == -1) {
6415 err = got_error_from_errno("got_opentempfd");
6416 goto done;
6419 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6420 if (err)
6421 goto done;
6423 err = got_object_get_type(&obj_type, s->repo, obj_id);
6424 if (err)
6425 goto done;
6427 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6428 err = got_error(GOT_ERR_OBJ_TYPE);
6429 goto done;
6432 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6433 if (err)
6434 goto done;
6435 blame->f = got_opentemp();
6436 if (blame->f == NULL) {
6437 err = got_error_from_errno("got_opentemp");
6438 goto done;
6440 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6441 &blame->line_offsets, blame->f, blob);
6442 if (err)
6443 goto done;
6444 if (blame->nlines == 0) {
6445 s->blame_complete = 1;
6446 goto done;
6449 /* Don't include \n at EOF in the blame line count. */
6450 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6451 blame->nlines--;
6453 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6454 if (blame->lines == NULL) {
6455 err = got_error_from_errno("calloc");
6456 goto done;
6459 err = got_repo_pack_fds_open(&pack_fds);
6460 if (err)
6461 goto done;
6462 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6463 pack_fds);
6464 if (err)
6465 goto done;
6467 blame->pack_fds = pack_fds;
6468 blame->cb_args.view = view;
6469 blame->cb_args.lines = blame->lines;
6470 blame->cb_args.nlines = blame->nlines;
6471 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6472 if (blame->cb_args.commit_id == NULL) {
6473 err = got_error_from_errno("got_object_id_dup");
6474 goto done;
6476 blame->cb_args.quit = &s->done;
6478 blame->thread_args.path = s->path;
6479 blame->thread_args.repo = thread_repo;
6480 blame->thread_args.cb_args = &blame->cb_args;
6481 blame->thread_args.complete = &s->blame_complete;
6482 blame->thread_args.cancel_cb = cancel_blame_view;
6483 blame->thread_args.cancel_arg = &s->done;
6484 s->blame_complete = 0;
6486 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6487 s->first_displayed_line = 1;
6488 s->last_displayed_line = view->nlines;
6489 s->selected_line = 1;
6491 s->matched_line = 0;
6493 done:
6494 if (commit)
6495 got_object_commit_close(commit);
6496 if (fd != -1 && close(fd) == -1 && err == NULL)
6497 err = got_error_from_errno("close");
6498 if (blob)
6499 got_object_blob_close(blob);
6500 free(obj_id);
6501 if (err)
6502 stop_blame(blame);
6503 return err;
6506 static const struct got_error *
6507 open_blame_view(struct tog_view *view, char *path,
6508 struct got_object_id *commit_id, struct got_repository *repo)
6510 const struct got_error *err = NULL;
6511 struct tog_blame_view_state *s = &view->state.blame;
6513 STAILQ_INIT(&s->blamed_commits);
6515 s->path = strdup(path);
6516 if (s->path == NULL)
6517 return got_error_from_errno("strdup");
6519 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6520 if (err) {
6521 free(s->path);
6522 return err;
6525 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6526 s->first_displayed_line = 1;
6527 s->last_displayed_line = view->nlines;
6528 s->selected_line = 1;
6529 s->blame_complete = 0;
6530 s->repo = repo;
6531 s->commit_id = commit_id;
6532 memset(&s->blame, 0, sizeof(s->blame));
6534 STAILQ_INIT(&s->colors);
6535 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6536 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6537 get_color_value("TOG_COLOR_COMMIT"));
6538 if (err)
6539 return err;
6542 view->show = show_blame_view;
6543 view->input = input_blame_view;
6544 view->reset = reset_blame_view;
6545 view->close = close_blame_view;
6546 view->search_start = search_start_blame_view;
6547 view->search_setup = search_setup_blame_view;
6548 view->search_next = search_next_view_match;
6550 if (using_mock_io) {
6551 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6552 int rc;
6554 rc = pthread_cond_init(&bta->blame_complete, NULL);
6555 if (rc)
6556 return got_error_set_errno(rc, "pthread_cond_init");
6559 return run_blame(view);
6562 static const struct got_error *
6563 close_blame_view(struct tog_view *view)
6565 const struct got_error *err = NULL;
6566 struct tog_blame_view_state *s = &view->state.blame;
6568 if (s->blame.thread)
6569 err = stop_blame(&s->blame);
6571 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6572 struct got_object_qid *blamed_commit;
6573 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6574 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6575 got_object_qid_free(blamed_commit);
6578 if (using_mock_io) {
6579 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6580 int rc;
6582 rc = pthread_cond_destroy(&bta->blame_complete);
6583 if (rc && err == NULL)
6584 err = got_error_set_errno(rc, "pthread_cond_destroy");
6587 free(s->path);
6588 free_colors(&s->colors);
6589 return err;
6592 static const struct got_error *
6593 search_start_blame_view(struct tog_view *view)
6595 struct tog_blame_view_state *s = &view->state.blame;
6597 s->matched_line = 0;
6598 return NULL;
6601 static void
6602 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6603 size_t *nlines, int **first, int **last, int **match, int **selected)
6605 struct tog_blame_view_state *s = &view->state.blame;
6607 *f = s->blame.f;
6608 *nlines = s->blame.nlines;
6609 *line_offsets = s->blame.line_offsets;
6610 *match = &s->matched_line;
6611 *first = &s->first_displayed_line;
6612 *last = &s->last_displayed_line;
6613 *selected = &s->selected_line;
6616 static const struct got_error *
6617 show_blame_view(struct tog_view *view)
6619 const struct got_error *err = NULL;
6620 struct tog_blame_view_state *s = &view->state.blame;
6621 int errcode;
6623 if (s->blame.thread == NULL && !s->blame_complete) {
6624 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6625 &s->blame.thread_args);
6626 if (errcode)
6627 return got_error_set_errno(errcode, "pthread_create");
6629 if (!using_mock_io)
6630 halfdelay(1); /* fast refresh while annotating */
6633 if (s->blame_complete && !using_mock_io)
6634 halfdelay(10); /* disable fast refresh */
6636 err = draw_blame(view);
6638 view_border(view);
6639 return err;
6642 static const struct got_error *
6643 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6644 struct got_repository *repo, struct got_object_id *id)
6646 struct tog_view *log_view;
6647 const struct got_error *err = NULL;
6649 *new_view = NULL;
6651 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6652 if (log_view == NULL)
6653 return got_error_from_errno("view_open");
6655 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6656 if (err)
6657 view_close(log_view);
6658 else
6659 *new_view = log_view;
6661 return err;
6664 static const struct got_error *
6665 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6667 const struct got_error *err = NULL, *thread_err = NULL;
6668 struct tog_view *diff_view;
6669 struct tog_blame_view_state *s = &view->state.blame;
6670 int eos, nscroll, begin_y = 0, begin_x = 0;
6672 eos = nscroll = view->nlines - 2;
6673 if (view_is_hsplit_top(view))
6674 --eos; /* border */
6676 switch (ch) {
6677 case '0':
6678 case '$':
6679 case KEY_RIGHT:
6680 case 'l':
6681 case KEY_LEFT:
6682 case 'h':
6683 horizontal_scroll_input(view, ch);
6684 break;
6685 case 'q':
6686 s->done = 1;
6687 break;
6688 case 'g':
6689 case KEY_HOME:
6690 s->selected_line = 1;
6691 s->first_displayed_line = 1;
6692 view->count = 0;
6693 break;
6694 case 'G':
6695 case KEY_END:
6696 if (s->blame.nlines < eos) {
6697 s->selected_line = s->blame.nlines;
6698 s->first_displayed_line = 1;
6699 } else {
6700 s->selected_line = eos;
6701 s->first_displayed_line = s->blame.nlines - (eos - 1);
6703 view->count = 0;
6704 break;
6705 case 'k':
6706 case KEY_UP:
6707 case CTRL('p'):
6708 if (s->selected_line > 1)
6709 s->selected_line--;
6710 else if (s->selected_line == 1 &&
6711 s->first_displayed_line > 1)
6712 s->first_displayed_line--;
6713 else
6714 view->count = 0;
6715 break;
6716 case CTRL('u'):
6717 case 'u':
6718 nscroll /= 2;
6719 /* FALL THROUGH */
6720 case KEY_PPAGE:
6721 case CTRL('b'):
6722 case 'b':
6723 if (s->first_displayed_line == 1) {
6724 if (view->count > 1)
6725 nscroll += nscroll;
6726 s->selected_line = MAX(1, s->selected_line - nscroll);
6727 view->count = 0;
6728 break;
6730 if (s->first_displayed_line > nscroll)
6731 s->first_displayed_line -= nscroll;
6732 else
6733 s->first_displayed_line = 1;
6734 break;
6735 case 'j':
6736 case KEY_DOWN:
6737 case CTRL('n'):
6738 if (s->selected_line < eos && s->first_displayed_line +
6739 s->selected_line <= s->blame.nlines)
6740 s->selected_line++;
6741 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6742 s->first_displayed_line++;
6743 else
6744 view->count = 0;
6745 break;
6746 case 'c':
6747 case 'p': {
6748 struct got_object_id *id = NULL;
6750 view->count = 0;
6751 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6752 s->first_displayed_line, s->selected_line);
6753 if (id == NULL)
6754 break;
6755 if (ch == 'p') {
6756 struct got_commit_object *commit, *pcommit;
6757 struct got_object_qid *pid;
6758 struct got_object_id *blob_id = NULL;
6759 int obj_type;
6760 err = got_object_open_as_commit(&commit,
6761 s->repo, id);
6762 if (err)
6763 break;
6764 pid = STAILQ_FIRST(
6765 got_object_commit_get_parent_ids(commit));
6766 if (pid == NULL) {
6767 got_object_commit_close(commit);
6768 break;
6770 /* Check if path history ends here. */
6771 err = got_object_open_as_commit(&pcommit,
6772 s->repo, &pid->id);
6773 if (err)
6774 break;
6775 err = got_object_id_by_path(&blob_id, s->repo,
6776 pcommit, s->path);
6777 got_object_commit_close(pcommit);
6778 if (err) {
6779 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6780 err = NULL;
6781 got_object_commit_close(commit);
6782 break;
6784 err = got_object_get_type(&obj_type, s->repo,
6785 blob_id);
6786 free(blob_id);
6787 /* Can't blame non-blob type objects. */
6788 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6789 got_object_commit_close(commit);
6790 break;
6792 err = got_object_qid_alloc(&s->blamed_commit,
6793 &pid->id);
6794 got_object_commit_close(commit);
6795 } else {
6796 if (got_object_id_cmp(id,
6797 &s->blamed_commit->id) == 0)
6798 break;
6799 err = got_object_qid_alloc(&s->blamed_commit,
6800 id);
6802 if (err)
6803 break;
6804 s->done = 1;
6805 thread_err = stop_blame(&s->blame);
6806 s->done = 0;
6807 if (thread_err)
6808 break;
6809 STAILQ_INSERT_HEAD(&s->blamed_commits,
6810 s->blamed_commit, entry);
6811 err = run_blame(view);
6812 if (err)
6813 break;
6814 break;
6816 case 'C': {
6817 struct got_object_qid *first;
6819 view->count = 0;
6820 first = STAILQ_FIRST(&s->blamed_commits);
6821 if (!got_object_id_cmp(&first->id, s->commit_id))
6822 break;
6823 s->done = 1;
6824 thread_err = stop_blame(&s->blame);
6825 s->done = 0;
6826 if (thread_err)
6827 break;
6828 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6829 got_object_qid_free(s->blamed_commit);
6830 s->blamed_commit =
6831 STAILQ_FIRST(&s->blamed_commits);
6832 err = run_blame(view);
6833 if (err)
6834 break;
6835 break;
6837 case 'L':
6838 view->count = 0;
6839 s->id_to_log = get_selected_commit_id(s->blame.lines,
6840 s->blame.nlines, s->first_displayed_line, s->selected_line);
6841 if (s->id_to_log)
6842 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6843 break;
6844 case KEY_ENTER:
6845 case '\r': {
6846 struct got_object_id *id = NULL;
6847 struct got_object_qid *pid;
6848 struct got_commit_object *commit = NULL;
6850 view->count = 0;
6851 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6852 s->first_displayed_line, s->selected_line);
6853 if (id == NULL)
6854 break;
6855 err = got_object_open_as_commit(&commit, s->repo, id);
6856 if (err)
6857 break;
6858 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6859 if (*new_view) {
6860 /* traversed from diff view, release diff resources */
6861 err = close_diff_view(*new_view);
6862 if (err)
6863 break;
6864 diff_view = *new_view;
6865 } else {
6866 if (view_is_parent_view(view))
6867 view_get_split(view, &begin_y, &begin_x);
6869 diff_view = view_open(0, 0, begin_y, begin_x,
6870 TOG_VIEW_DIFF);
6871 if (diff_view == NULL) {
6872 got_object_commit_close(commit);
6873 err = got_error_from_errno("view_open");
6874 break;
6877 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6878 id, NULL, NULL, 3, 0, 0, view, s->repo);
6879 got_object_commit_close(commit);
6880 if (err) {
6881 view_close(diff_view);
6882 break;
6884 s->last_diffed_line = s->first_displayed_line - 1 +
6885 s->selected_line;
6886 if (*new_view)
6887 break; /* still open from active diff view */
6888 if (view_is_parent_view(view) &&
6889 view->mode == TOG_VIEW_SPLIT_HRZN) {
6890 err = view_init_hsplit(view, begin_y);
6891 if (err)
6892 break;
6895 view->focussed = 0;
6896 diff_view->focussed = 1;
6897 diff_view->mode = view->mode;
6898 diff_view->nlines = view->lines - begin_y;
6899 if (view_is_parent_view(view)) {
6900 view_transfer_size(diff_view, view);
6901 err = view_close_child(view);
6902 if (err)
6903 break;
6904 err = view_set_child(view, diff_view);
6905 if (err)
6906 break;
6907 view->focus_child = 1;
6908 } else
6909 *new_view = diff_view;
6910 if (err)
6911 break;
6912 break;
6914 case CTRL('d'):
6915 case 'd':
6916 nscroll /= 2;
6917 /* FALL THROUGH */
6918 case KEY_NPAGE:
6919 case CTRL('f'):
6920 case 'f':
6921 case ' ':
6922 if (s->last_displayed_line >= s->blame.nlines &&
6923 s->selected_line >= MIN(s->blame.nlines,
6924 view->nlines - 2)) {
6925 view->count = 0;
6926 break;
6928 if (s->last_displayed_line >= s->blame.nlines &&
6929 s->selected_line < view->nlines - 2) {
6930 s->selected_line +=
6931 MIN(nscroll, s->last_displayed_line -
6932 s->first_displayed_line - s->selected_line + 1);
6934 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6935 s->first_displayed_line += nscroll;
6936 else
6937 s->first_displayed_line =
6938 s->blame.nlines - (view->nlines - 3);
6939 break;
6940 case KEY_RESIZE:
6941 if (s->selected_line > view->nlines - 2) {
6942 s->selected_line = MIN(s->blame.nlines,
6943 view->nlines - 2);
6945 break;
6946 default:
6947 view->count = 0;
6948 break;
6950 return thread_err ? thread_err : err;
6953 static const struct got_error *
6954 reset_blame_view(struct tog_view *view)
6956 const struct got_error *err;
6957 struct tog_blame_view_state *s = &view->state.blame;
6959 view->count = 0;
6960 s->done = 1;
6961 err = stop_blame(&s->blame);
6962 s->done = 0;
6963 if (err)
6964 return err;
6965 return run_blame(view);
6968 static const struct got_error *
6969 cmd_blame(int argc, char *argv[])
6971 const struct got_error *error;
6972 struct got_repository *repo = NULL;
6973 struct got_worktree *worktree = NULL;
6974 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6975 char *link_target = NULL;
6976 struct got_object_id *commit_id = NULL;
6977 struct got_commit_object *commit = NULL;
6978 char *commit_id_str = NULL;
6979 int ch;
6980 struct tog_view *view = NULL;
6981 int *pack_fds = NULL;
6983 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6984 switch (ch) {
6985 case 'c':
6986 commit_id_str = optarg;
6987 break;
6988 case 'r':
6989 repo_path = realpath(optarg, NULL);
6990 if (repo_path == NULL)
6991 return got_error_from_errno2("realpath",
6992 optarg);
6993 break;
6994 default:
6995 usage_blame();
6996 /* NOTREACHED */
7000 argc -= optind;
7001 argv += optind;
7003 if (argc != 1)
7004 usage_blame();
7006 error = got_repo_pack_fds_open(&pack_fds);
7007 if (error != NULL)
7008 goto done;
7010 if (repo_path == NULL) {
7011 cwd = getcwd(NULL, 0);
7012 if (cwd == NULL)
7013 return got_error_from_errno("getcwd");
7014 error = got_worktree_open(&worktree, cwd);
7015 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7016 goto done;
7017 if (worktree)
7018 repo_path =
7019 strdup(got_worktree_get_repo_path(worktree));
7020 else
7021 repo_path = strdup(cwd);
7022 if (repo_path == NULL) {
7023 error = got_error_from_errno("strdup");
7024 goto done;
7028 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7029 if (error != NULL)
7030 goto done;
7032 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7033 worktree);
7034 if (error)
7035 goto done;
7037 init_curses();
7039 error = apply_unveil(got_repo_get_path(repo), NULL);
7040 if (error)
7041 goto done;
7043 error = tog_load_refs(repo, 0);
7044 if (error)
7045 goto done;
7047 if (commit_id_str == NULL) {
7048 struct got_reference *head_ref;
7049 error = got_ref_open(&head_ref, repo, worktree ?
7050 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7051 if (error != NULL)
7052 goto done;
7053 error = got_ref_resolve(&commit_id, repo, head_ref);
7054 got_ref_close(head_ref);
7055 } else {
7056 error = got_repo_match_object_id(&commit_id, NULL,
7057 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7059 if (error != NULL)
7060 goto done;
7062 error = got_object_open_as_commit(&commit, repo, commit_id);
7063 if (error)
7064 goto done;
7066 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7067 commit, repo);
7068 if (error)
7069 goto done;
7071 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7072 if (view == NULL) {
7073 error = got_error_from_errno("view_open");
7074 goto done;
7076 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7077 commit_id, repo);
7078 if (error != NULL) {
7079 if (view->close == NULL)
7080 close_blame_view(view);
7081 view_close(view);
7082 goto done;
7084 if (worktree) {
7085 /* Release work tree lock. */
7086 got_worktree_close(worktree);
7087 worktree = NULL;
7089 error = view_loop(view);
7090 done:
7091 free(repo_path);
7092 free(in_repo_path);
7093 free(link_target);
7094 free(cwd);
7095 free(commit_id);
7096 if (commit)
7097 got_object_commit_close(commit);
7098 if (worktree)
7099 got_worktree_close(worktree);
7100 if (repo) {
7101 const struct got_error *close_err = got_repo_close(repo);
7102 if (error == NULL)
7103 error = close_err;
7105 if (pack_fds) {
7106 const struct got_error *pack_err =
7107 got_repo_pack_fds_close(pack_fds);
7108 if (error == NULL)
7109 error = pack_err;
7111 tog_free_refs();
7112 return error;
7115 static const struct got_error *
7116 draw_tree_entries(struct tog_view *view, const char *parent_path)
7118 struct tog_tree_view_state *s = &view->state.tree;
7119 const struct got_error *err = NULL;
7120 struct got_tree_entry *te;
7121 wchar_t *wline;
7122 char *index = NULL;
7123 struct tog_color *tc;
7124 int width, n, nentries, scrollx, i = 1;
7125 int limit = view->nlines;
7127 s->ndisplayed = 0;
7128 if (view_is_hsplit_top(view))
7129 --limit; /* border */
7131 werase(view->window);
7133 if (limit == 0)
7134 return NULL;
7136 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7137 0, 0);
7138 if (err)
7139 return err;
7140 if (view_needs_focus_indication(view))
7141 wstandout(view->window);
7142 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7143 if (tc)
7144 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7145 waddwstr(view->window, wline);
7146 free(wline);
7147 wline = NULL;
7148 while (width++ < view->ncols)
7149 waddch(view->window, ' ');
7150 if (tc)
7151 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7152 if (view_needs_focus_indication(view))
7153 wstandend(view->window);
7154 if (--limit <= 0)
7155 return NULL;
7157 i += s->selected;
7158 if (s->first_displayed_entry) {
7159 i += got_tree_entry_get_index(s->first_displayed_entry);
7160 if (s->tree != s->root)
7161 ++i; /* account for ".." entry */
7163 nentries = got_object_tree_get_nentries(s->tree);
7164 if (asprintf(&index, "[%d/%d] %s",
7165 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7166 return got_error_from_errno("asprintf");
7167 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7168 free(index);
7169 if (err)
7170 return err;
7171 waddwstr(view->window, wline);
7172 free(wline);
7173 wline = NULL;
7174 if (width < view->ncols - 1)
7175 waddch(view->window, '\n');
7176 if (--limit <= 0)
7177 return NULL;
7178 waddch(view->window, '\n');
7179 if (--limit <= 0)
7180 return NULL;
7182 if (s->first_displayed_entry == NULL) {
7183 te = got_object_tree_get_first_entry(s->tree);
7184 if (s->selected == 0) {
7185 if (view->focussed)
7186 wstandout(view->window);
7187 s->selected_entry = NULL;
7189 waddstr(view->window, " ..\n"); /* parent directory */
7190 if (s->selected == 0 && view->focussed)
7191 wstandend(view->window);
7192 s->ndisplayed++;
7193 if (--limit <= 0)
7194 return NULL;
7195 n = 1;
7196 } else {
7197 n = 0;
7198 te = s->first_displayed_entry;
7201 view->maxx = 0;
7202 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7203 char *line = NULL, *id_str = NULL, *link_target = NULL;
7204 const char *modestr = "";
7205 mode_t mode;
7207 te = got_object_tree_get_entry(s->tree, i);
7208 mode = got_tree_entry_get_mode(te);
7210 if (s->show_ids) {
7211 err = got_object_id_str(&id_str,
7212 got_tree_entry_get_id(te));
7213 if (err)
7214 return got_error_from_errno(
7215 "got_object_id_str");
7217 if (got_object_tree_entry_is_submodule(te))
7218 modestr = "$";
7219 else if (S_ISLNK(mode)) {
7220 int i;
7222 err = got_tree_entry_get_symlink_target(&link_target,
7223 te, s->repo);
7224 if (err) {
7225 free(id_str);
7226 return err;
7228 for (i = 0; i < strlen(link_target); i++) {
7229 if (!isprint((unsigned char)link_target[i]))
7230 link_target[i] = '?';
7232 modestr = "@";
7234 else if (S_ISDIR(mode))
7235 modestr = "/";
7236 else if (mode & S_IXUSR)
7237 modestr = "*";
7238 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7239 got_tree_entry_get_name(te), modestr,
7240 link_target ? " -> ": "",
7241 link_target ? link_target : "") == -1) {
7242 free(id_str);
7243 free(link_target);
7244 return got_error_from_errno("asprintf");
7246 free(id_str);
7247 free(link_target);
7249 /* use full line width to determine view->maxx */
7250 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7251 if (err) {
7252 free(line);
7253 break;
7255 view->maxx = MAX(view->maxx, width);
7256 free(wline);
7257 wline = NULL;
7259 err = format_line(&wline, &width, &scrollx, line, view->x,
7260 view->ncols, 0, 0);
7261 if (err) {
7262 free(line);
7263 break;
7265 if (n == s->selected) {
7266 if (view->focussed)
7267 wstandout(view->window);
7268 s->selected_entry = te;
7270 tc = match_color(&s->colors, line);
7271 if (tc)
7272 wattr_on(view->window,
7273 COLOR_PAIR(tc->colorpair), NULL);
7274 waddwstr(view->window, &wline[scrollx]);
7275 if (tc)
7276 wattr_off(view->window,
7277 COLOR_PAIR(tc->colorpair), NULL);
7278 if (width < view->ncols)
7279 waddch(view->window, '\n');
7280 if (n == s->selected && view->focussed)
7281 wstandend(view->window);
7282 free(line);
7283 free(wline);
7284 wline = NULL;
7285 n++;
7286 s->ndisplayed++;
7287 s->last_displayed_entry = te;
7288 if (--limit <= 0)
7289 break;
7292 return err;
7295 static void
7296 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7298 struct got_tree_entry *te;
7299 int isroot = s->tree == s->root;
7300 int i = 0;
7302 if (s->first_displayed_entry == NULL)
7303 return;
7305 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7306 while (i++ < maxscroll) {
7307 if (te == NULL) {
7308 if (!isroot)
7309 s->first_displayed_entry = NULL;
7310 break;
7312 s->first_displayed_entry = te;
7313 te = got_tree_entry_get_prev(s->tree, te);
7317 static const struct got_error *
7318 tree_scroll_down(struct tog_view *view, int maxscroll)
7320 struct tog_tree_view_state *s = &view->state.tree;
7321 struct got_tree_entry *next, *last;
7322 int n = 0;
7324 if (s->first_displayed_entry)
7325 next = got_tree_entry_get_next(s->tree,
7326 s->first_displayed_entry);
7327 else
7328 next = got_object_tree_get_first_entry(s->tree);
7330 last = s->last_displayed_entry;
7331 while (next && n++ < maxscroll) {
7332 if (last) {
7333 s->last_displayed_entry = last;
7334 last = got_tree_entry_get_next(s->tree, last);
7336 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7337 s->first_displayed_entry = next;
7338 next = got_tree_entry_get_next(s->tree, next);
7342 return NULL;
7345 static const struct got_error *
7346 tree_entry_path(char **path, struct tog_parent_trees *parents,
7347 struct got_tree_entry *te)
7349 const struct got_error *err = NULL;
7350 struct tog_parent_tree *pt;
7351 size_t len = 2; /* for leading slash and NUL */
7353 TAILQ_FOREACH(pt, parents, entry)
7354 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7355 + 1 /* slash */;
7356 if (te)
7357 len += strlen(got_tree_entry_get_name(te));
7359 *path = calloc(1, len);
7360 if (path == NULL)
7361 return got_error_from_errno("calloc");
7363 (*path)[0] = '/';
7364 pt = TAILQ_LAST(parents, tog_parent_trees);
7365 while (pt) {
7366 const char *name = got_tree_entry_get_name(pt->selected_entry);
7367 if (strlcat(*path, name, len) >= len) {
7368 err = got_error(GOT_ERR_NO_SPACE);
7369 goto done;
7371 if (strlcat(*path, "/", len) >= len) {
7372 err = got_error(GOT_ERR_NO_SPACE);
7373 goto done;
7375 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7377 if (te) {
7378 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7379 err = got_error(GOT_ERR_NO_SPACE);
7380 goto done;
7383 done:
7384 if (err) {
7385 free(*path);
7386 *path = NULL;
7388 return err;
7391 static const struct got_error *
7392 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7393 struct got_tree_entry *te, struct tog_parent_trees *parents,
7394 struct got_object_id *commit_id, struct got_repository *repo)
7396 const struct got_error *err = NULL;
7397 char *path;
7398 struct tog_view *blame_view;
7400 *new_view = NULL;
7402 err = tree_entry_path(&path, parents, te);
7403 if (err)
7404 return err;
7406 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7407 if (blame_view == NULL) {
7408 err = got_error_from_errno("view_open");
7409 goto done;
7412 err = open_blame_view(blame_view, path, commit_id, repo);
7413 if (err) {
7414 if (err->code == GOT_ERR_CANCELLED)
7415 err = NULL;
7416 view_close(blame_view);
7417 } else
7418 *new_view = blame_view;
7419 done:
7420 free(path);
7421 return err;
7424 static const struct got_error *
7425 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7426 struct tog_tree_view_state *s)
7428 struct tog_view *log_view;
7429 const struct got_error *err = NULL;
7430 char *path;
7432 *new_view = NULL;
7434 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7435 if (log_view == NULL)
7436 return got_error_from_errno("view_open");
7438 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7439 if (err)
7440 return err;
7442 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7443 path, 0);
7444 if (err)
7445 view_close(log_view);
7446 else
7447 *new_view = log_view;
7448 free(path);
7449 return err;
7452 static const struct got_error *
7453 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7454 const char *head_ref_name, struct got_repository *repo)
7456 const struct got_error *err = NULL;
7457 char *commit_id_str = NULL;
7458 struct tog_tree_view_state *s = &view->state.tree;
7459 struct got_commit_object *commit = NULL;
7461 TAILQ_INIT(&s->parents);
7462 STAILQ_INIT(&s->colors);
7464 s->commit_id = got_object_id_dup(commit_id);
7465 if (s->commit_id == NULL) {
7466 err = got_error_from_errno("got_object_id_dup");
7467 goto done;
7470 err = got_object_open_as_commit(&commit, repo, commit_id);
7471 if (err)
7472 goto done;
7475 * The root is opened here and will be closed when the view is closed.
7476 * Any visited subtrees and their path-wise parents are opened and
7477 * closed on demand.
7479 err = got_object_open_as_tree(&s->root, repo,
7480 got_object_commit_get_tree_id(commit));
7481 if (err)
7482 goto done;
7483 s->tree = s->root;
7485 err = got_object_id_str(&commit_id_str, commit_id);
7486 if (err != NULL)
7487 goto done;
7489 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7490 err = got_error_from_errno("asprintf");
7491 goto done;
7494 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7495 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7496 if (head_ref_name) {
7497 s->head_ref_name = strdup(head_ref_name);
7498 if (s->head_ref_name == NULL) {
7499 err = got_error_from_errno("strdup");
7500 goto done;
7503 s->repo = repo;
7505 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7506 err = add_color(&s->colors, "\\$$",
7507 TOG_COLOR_TREE_SUBMODULE,
7508 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7509 if (err)
7510 goto done;
7511 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7512 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7513 if (err)
7514 goto done;
7515 err = add_color(&s->colors, "/$",
7516 TOG_COLOR_TREE_DIRECTORY,
7517 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7518 if (err)
7519 goto done;
7521 err = add_color(&s->colors, "\\*$",
7522 TOG_COLOR_TREE_EXECUTABLE,
7523 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7524 if (err)
7525 goto done;
7527 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7528 get_color_value("TOG_COLOR_COMMIT"));
7529 if (err)
7530 goto done;
7533 view->show = show_tree_view;
7534 view->input = input_tree_view;
7535 view->close = close_tree_view;
7536 view->search_start = search_start_tree_view;
7537 view->search_next = search_next_tree_view;
7538 done:
7539 free(commit_id_str);
7540 if (commit)
7541 got_object_commit_close(commit);
7542 if (err) {
7543 if (view->close == NULL)
7544 close_tree_view(view);
7545 view_close(view);
7547 return err;
7550 static const struct got_error *
7551 close_tree_view(struct tog_view *view)
7553 struct tog_tree_view_state *s = &view->state.tree;
7555 free_colors(&s->colors);
7556 free(s->tree_label);
7557 s->tree_label = NULL;
7558 free(s->commit_id);
7559 s->commit_id = NULL;
7560 free(s->head_ref_name);
7561 s->head_ref_name = NULL;
7562 while (!TAILQ_EMPTY(&s->parents)) {
7563 struct tog_parent_tree *parent;
7564 parent = TAILQ_FIRST(&s->parents);
7565 TAILQ_REMOVE(&s->parents, parent, entry);
7566 if (parent->tree != s->root)
7567 got_object_tree_close(parent->tree);
7568 free(parent);
7571 if (s->tree != NULL && s->tree != s->root)
7572 got_object_tree_close(s->tree);
7573 if (s->root)
7574 got_object_tree_close(s->root);
7575 return NULL;
7578 static const struct got_error *
7579 search_start_tree_view(struct tog_view *view)
7581 struct tog_tree_view_state *s = &view->state.tree;
7583 s->matched_entry = NULL;
7584 return NULL;
7587 static int
7588 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7590 regmatch_t regmatch;
7592 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7593 0) == 0;
7596 static const struct got_error *
7597 search_next_tree_view(struct tog_view *view)
7599 struct tog_tree_view_state *s = &view->state.tree;
7600 struct got_tree_entry *te = NULL;
7602 if (!view->searching) {
7603 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7604 return NULL;
7607 if (s->matched_entry) {
7608 if (view->searching == TOG_SEARCH_FORWARD) {
7609 if (s->selected_entry)
7610 te = got_tree_entry_get_next(s->tree,
7611 s->selected_entry);
7612 else
7613 te = got_object_tree_get_first_entry(s->tree);
7614 } else {
7615 if (s->selected_entry == NULL)
7616 te = got_object_tree_get_last_entry(s->tree);
7617 else
7618 te = got_tree_entry_get_prev(s->tree,
7619 s->selected_entry);
7621 } else {
7622 if (s->selected_entry)
7623 te = s->selected_entry;
7624 else if (view->searching == TOG_SEARCH_FORWARD)
7625 te = got_object_tree_get_first_entry(s->tree);
7626 else
7627 te = got_object_tree_get_last_entry(s->tree);
7630 while (1) {
7631 if (te == NULL) {
7632 if (s->matched_entry == NULL) {
7633 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7634 return NULL;
7636 if (view->searching == TOG_SEARCH_FORWARD)
7637 te = got_object_tree_get_first_entry(s->tree);
7638 else
7639 te = got_object_tree_get_last_entry(s->tree);
7642 if (match_tree_entry(te, &view->regex)) {
7643 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7644 s->matched_entry = te;
7645 break;
7648 if (view->searching == TOG_SEARCH_FORWARD)
7649 te = got_tree_entry_get_next(s->tree, te);
7650 else
7651 te = got_tree_entry_get_prev(s->tree, te);
7654 if (s->matched_entry) {
7655 s->first_displayed_entry = s->matched_entry;
7656 s->selected = 0;
7659 return NULL;
7662 static const struct got_error *
7663 show_tree_view(struct tog_view *view)
7665 const struct got_error *err = NULL;
7666 struct tog_tree_view_state *s = &view->state.tree;
7667 char *parent_path;
7669 err = tree_entry_path(&parent_path, &s->parents, NULL);
7670 if (err)
7671 return err;
7673 err = draw_tree_entries(view, parent_path);
7674 free(parent_path);
7676 view_border(view);
7677 return err;
7680 static const struct got_error *
7681 tree_goto_line(struct tog_view *view, int nlines)
7683 const struct got_error *err = NULL;
7684 struct tog_tree_view_state *s = &view->state.tree;
7685 struct got_tree_entry **fte, **lte, **ste;
7686 int g, last, first = 1, i = 1;
7687 int root = s->tree == s->root;
7688 int off = root ? 1 : 2;
7690 g = view->gline;
7691 view->gline = 0;
7693 if (g == 0)
7694 g = 1;
7695 else if (g > got_object_tree_get_nentries(s->tree))
7696 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7698 fte = &s->first_displayed_entry;
7699 lte = &s->last_displayed_entry;
7700 ste = &s->selected_entry;
7702 if (*fte != NULL) {
7703 first = got_tree_entry_get_index(*fte);
7704 first += off; /* account for ".." */
7706 last = got_tree_entry_get_index(*lte);
7707 last += off;
7709 if (g >= first && g <= last && g - first < nlines) {
7710 s->selected = g - first;
7711 return NULL; /* gline is on the current page */
7714 if (*ste != NULL) {
7715 i = got_tree_entry_get_index(*ste);
7716 i += off;
7719 if (i < g) {
7720 err = tree_scroll_down(view, g - i);
7721 if (err)
7722 return err;
7723 if (got_tree_entry_get_index(*lte) >=
7724 got_object_tree_get_nentries(s->tree) - 1 &&
7725 first + s->selected < g &&
7726 s->selected < s->ndisplayed - 1) {
7727 first = got_tree_entry_get_index(*fte);
7728 first += off;
7729 s->selected = g - first;
7731 } else if (i > g)
7732 tree_scroll_up(s, i - g);
7734 if (g < nlines &&
7735 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7736 s->selected = g - 1;
7738 return NULL;
7741 static const struct got_error *
7742 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7744 const struct got_error *err = NULL;
7745 struct tog_tree_view_state *s = &view->state.tree;
7746 struct got_tree_entry *te;
7747 int n, nscroll = view->nlines - 3;
7749 if (view->gline)
7750 return tree_goto_line(view, nscroll);
7752 switch (ch) {
7753 case '0':
7754 case '$':
7755 case KEY_RIGHT:
7756 case 'l':
7757 case KEY_LEFT:
7758 case 'h':
7759 horizontal_scroll_input(view, ch);
7760 break;
7761 case 'i':
7762 s->show_ids = !s->show_ids;
7763 view->count = 0;
7764 break;
7765 case 'L':
7766 view->count = 0;
7767 if (!s->selected_entry)
7768 break;
7769 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7770 break;
7771 case 'R':
7772 view->count = 0;
7773 err = view_request_new(new_view, view, TOG_VIEW_REF);
7774 break;
7775 case 'g':
7776 case '=':
7777 case KEY_HOME:
7778 s->selected = 0;
7779 view->count = 0;
7780 if (s->tree == s->root)
7781 s->first_displayed_entry =
7782 got_object_tree_get_first_entry(s->tree);
7783 else
7784 s->first_displayed_entry = NULL;
7785 break;
7786 case 'G':
7787 case '*':
7788 case KEY_END: {
7789 int eos = view->nlines - 3;
7791 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7792 --eos; /* border */
7793 s->selected = 0;
7794 view->count = 0;
7795 te = got_object_tree_get_last_entry(s->tree);
7796 for (n = 0; n < eos; n++) {
7797 if (te == NULL) {
7798 if (s->tree != s->root) {
7799 s->first_displayed_entry = NULL;
7800 n++;
7802 break;
7804 s->first_displayed_entry = te;
7805 te = got_tree_entry_get_prev(s->tree, te);
7807 if (n > 0)
7808 s->selected = n - 1;
7809 break;
7811 case 'k':
7812 case KEY_UP:
7813 case CTRL('p'):
7814 if (s->selected > 0) {
7815 s->selected--;
7816 break;
7818 tree_scroll_up(s, 1);
7819 if (s->selected_entry == NULL ||
7820 (s->tree == s->root && s->selected_entry ==
7821 got_object_tree_get_first_entry(s->tree)))
7822 view->count = 0;
7823 break;
7824 case CTRL('u'):
7825 case 'u':
7826 nscroll /= 2;
7827 /* FALL THROUGH */
7828 case KEY_PPAGE:
7829 case CTRL('b'):
7830 case 'b':
7831 if (s->tree == s->root) {
7832 if (got_object_tree_get_first_entry(s->tree) ==
7833 s->first_displayed_entry)
7834 s->selected -= MIN(s->selected, nscroll);
7835 } else {
7836 if (s->first_displayed_entry == NULL)
7837 s->selected -= MIN(s->selected, nscroll);
7839 tree_scroll_up(s, MAX(0, nscroll));
7840 if (s->selected_entry == NULL ||
7841 (s->tree == s->root && s->selected_entry ==
7842 got_object_tree_get_first_entry(s->tree)))
7843 view->count = 0;
7844 break;
7845 case 'j':
7846 case KEY_DOWN:
7847 case CTRL('n'):
7848 if (s->selected < s->ndisplayed - 1) {
7849 s->selected++;
7850 break;
7852 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7853 == NULL) {
7854 /* can't scroll any further */
7855 view->count = 0;
7856 break;
7858 tree_scroll_down(view, 1);
7859 break;
7860 case CTRL('d'):
7861 case 'd':
7862 nscroll /= 2;
7863 /* FALL THROUGH */
7864 case KEY_NPAGE:
7865 case CTRL('f'):
7866 case 'f':
7867 case ' ':
7868 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7869 == NULL) {
7870 /* can't scroll any further; move cursor down */
7871 if (s->selected < s->ndisplayed - 1)
7872 s->selected += MIN(nscroll,
7873 s->ndisplayed - s->selected - 1);
7874 else
7875 view->count = 0;
7876 break;
7878 tree_scroll_down(view, nscroll);
7879 break;
7880 case KEY_ENTER:
7881 case '\r':
7882 case KEY_BACKSPACE:
7883 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7884 struct tog_parent_tree *parent;
7885 /* user selected '..' */
7886 if (s->tree == s->root) {
7887 view->count = 0;
7888 break;
7890 parent = TAILQ_FIRST(&s->parents);
7891 TAILQ_REMOVE(&s->parents, parent,
7892 entry);
7893 got_object_tree_close(s->tree);
7894 s->tree = parent->tree;
7895 s->first_displayed_entry =
7896 parent->first_displayed_entry;
7897 s->selected_entry =
7898 parent->selected_entry;
7899 s->selected = parent->selected;
7900 if (s->selected > view->nlines - 3) {
7901 err = offset_selection_down(view);
7902 if (err)
7903 break;
7905 free(parent);
7906 } else if (S_ISDIR(got_tree_entry_get_mode(
7907 s->selected_entry))) {
7908 struct got_tree_object *subtree;
7909 view->count = 0;
7910 err = got_object_open_as_tree(&subtree, s->repo,
7911 got_tree_entry_get_id(s->selected_entry));
7912 if (err)
7913 break;
7914 err = tree_view_visit_subtree(s, subtree);
7915 if (err) {
7916 got_object_tree_close(subtree);
7917 break;
7919 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7920 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7921 break;
7922 case KEY_RESIZE:
7923 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7924 s->selected = view->nlines - 4;
7925 view->count = 0;
7926 break;
7927 default:
7928 view->count = 0;
7929 break;
7932 return err;
7935 __dead static void
7936 usage_tree(void)
7938 endwin();
7939 fprintf(stderr,
7940 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7941 getprogname());
7942 exit(1);
7945 static const struct got_error *
7946 cmd_tree(int argc, char *argv[])
7948 const struct got_error *error;
7949 struct got_repository *repo = NULL;
7950 struct got_worktree *worktree = NULL;
7951 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7952 struct got_object_id *commit_id = NULL;
7953 struct got_commit_object *commit = NULL;
7954 const char *commit_id_arg = NULL;
7955 char *label = NULL;
7956 struct got_reference *ref = NULL;
7957 const char *head_ref_name = NULL;
7958 int ch;
7959 struct tog_view *view;
7960 int *pack_fds = NULL;
7962 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7963 switch (ch) {
7964 case 'c':
7965 commit_id_arg = optarg;
7966 break;
7967 case 'r':
7968 repo_path = realpath(optarg, NULL);
7969 if (repo_path == NULL)
7970 return got_error_from_errno2("realpath",
7971 optarg);
7972 break;
7973 default:
7974 usage_tree();
7975 /* NOTREACHED */
7979 argc -= optind;
7980 argv += optind;
7982 if (argc > 1)
7983 usage_tree();
7985 error = got_repo_pack_fds_open(&pack_fds);
7986 if (error != NULL)
7987 goto done;
7989 if (repo_path == NULL) {
7990 cwd = getcwd(NULL, 0);
7991 if (cwd == NULL)
7992 return got_error_from_errno("getcwd");
7993 error = got_worktree_open(&worktree, cwd);
7994 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7995 goto done;
7996 if (worktree)
7997 repo_path =
7998 strdup(got_worktree_get_repo_path(worktree));
7999 else
8000 repo_path = strdup(cwd);
8001 if (repo_path == NULL) {
8002 error = got_error_from_errno("strdup");
8003 goto done;
8007 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8008 if (error != NULL)
8009 goto done;
8011 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8012 repo, worktree);
8013 if (error)
8014 goto done;
8016 init_curses();
8018 error = apply_unveil(got_repo_get_path(repo), NULL);
8019 if (error)
8020 goto done;
8022 error = tog_load_refs(repo, 0);
8023 if (error)
8024 goto done;
8026 if (commit_id_arg == NULL) {
8027 error = got_repo_match_object_id(&commit_id, &label,
8028 worktree ? got_worktree_get_head_ref_name(worktree) :
8029 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8030 if (error)
8031 goto done;
8032 head_ref_name = label;
8033 } else {
8034 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8035 if (error == NULL)
8036 head_ref_name = got_ref_get_name(ref);
8037 else if (error->code != GOT_ERR_NOT_REF)
8038 goto done;
8039 error = got_repo_match_object_id(&commit_id, NULL,
8040 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8041 if (error)
8042 goto done;
8045 error = got_object_open_as_commit(&commit, repo, commit_id);
8046 if (error)
8047 goto done;
8049 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8050 if (view == NULL) {
8051 error = got_error_from_errno("view_open");
8052 goto done;
8054 error = open_tree_view(view, commit_id, head_ref_name, repo);
8055 if (error)
8056 goto done;
8057 if (!got_path_is_root_dir(in_repo_path)) {
8058 error = tree_view_walk_path(&view->state.tree, commit,
8059 in_repo_path);
8060 if (error)
8061 goto done;
8064 if (worktree) {
8065 /* Release work tree lock. */
8066 got_worktree_close(worktree);
8067 worktree = NULL;
8069 error = view_loop(view);
8070 done:
8071 free(repo_path);
8072 free(cwd);
8073 free(commit_id);
8074 free(label);
8075 if (ref)
8076 got_ref_close(ref);
8077 if (repo) {
8078 const struct got_error *close_err = got_repo_close(repo);
8079 if (error == NULL)
8080 error = close_err;
8082 if (pack_fds) {
8083 const struct got_error *pack_err =
8084 got_repo_pack_fds_close(pack_fds);
8085 if (error == NULL)
8086 error = pack_err;
8088 tog_free_refs();
8089 return error;
8092 static const struct got_error *
8093 ref_view_load_refs(struct tog_ref_view_state *s)
8095 struct got_reflist_entry *sre;
8096 struct tog_reflist_entry *re;
8098 s->nrefs = 0;
8099 TAILQ_FOREACH(sre, &tog_refs, entry) {
8100 if (strncmp(got_ref_get_name(sre->ref),
8101 "refs/got/", 9) == 0 &&
8102 strncmp(got_ref_get_name(sre->ref),
8103 "refs/got/backup/", 16) != 0)
8104 continue;
8106 re = malloc(sizeof(*re));
8107 if (re == NULL)
8108 return got_error_from_errno("malloc");
8110 re->ref = got_ref_dup(sre->ref);
8111 if (re->ref == NULL)
8112 return got_error_from_errno("got_ref_dup");
8113 re->idx = s->nrefs++;
8114 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8117 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8118 return NULL;
8121 static void
8122 ref_view_free_refs(struct tog_ref_view_state *s)
8124 struct tog_reflist_entry *re;
8126 while (!TAILQ_EMPTY(&s->refs)) {
8127 re = TAILQ_FIRST(&s->refs);
8128 TAILQ_REMOVE(&s->refs, re, entry);
8129 got_ref_close(re->ref);
8130 free(re);
8134 static const struct got_error *
8135 open_ref_view(struct tog_view *view, struct got_repository *repo)
8137 const struct got_error *err = NULL;
8138 struct tog_ref_view_state *s = &view->state.ref;
8140 s->selected_entry = 0;
8141 s->repo = repo;
8143 TAILQ_INIT(&s->refs);
8144 STAILQ_INIT(&s->colors);
8146 err = ref_view_load_refs(s);
8147 if (err)
8148 goto done;
8150 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8151 err = add_color(&s->colors, "^refs/heads/",
8152 TOG_COLOR_REFS_HEADS,
8153 get_color_value("TOG_COLOR_REFS_HEADS"));
8154 if (err)
8155 goto done;
8157 err = add_color(&s->colors, "^refs/tags/",
8158 TOG_COLOR_REFS_TAGS,
8159 get_color_value("TOG_COLOR_REFS_TAGS"));
8160 if (err)
8161 goto done;
8163 err = add_color(&s->colors, "^refs/remotes/",
8164 TOG_COLOR_REFS_REMOTES,
8165 get_color_value("TOG_COLOR_REFS_REMOTES"));
8166 if (err)
8167 goto done;
8169 err = add_color(&s->colors, "^refs/got/backup/",
8170 TOG_COLOR_REFS_BACKUP,
8171 get_color_value("TOG_COLOR_REFS_BACKUP"));
8172 if (err)
8173 goto done;
8176 view->show = show_ref_view;
8177 view->input = input_ref_view;
8178 view->close = close_ref_view;
8179 view->search_start = search_start_ref_view;
8180 view->search_next = search_next_ref_view;
8181 done:
8182 if (err) {
8183 if (view->close == NULL)
8184 close_ref_view(view);
8185 view_close(view);
8187 return err;
8190 static const struct got_error *
8191 close_ref_view(struct tog_view *view)
8193 struct tog_ref_view_state *s = &view->state.ref;
8195 ref_view_free_refs(s);
8196 free_colors(&s->colors);
8198 return NULL;
8201 static const struct got_error *
8202 resolve_reflist_entry(struct got_object_id **commit_id,
8203 struct tog_reflist_entry *re, struct got_repository *repo)
8205 const struct got_error *err = NULL;
8206 struct got_object_id *obj_id;
8207 struct got_tag_object *tag = NULL;
8208 int obj_type;
8210 *commit_id = NULL;
8212 err = got_ref_resolve(&obj_id, repo, re->ref);
8213 if (err)
8214 return err;
8216 err = got_object_get_type(&obj_type, repo, obj_id);
8217 if (err)
8218 goto done;
8220 switch (obj_type) {
8221 case GOT_OBJ_TYPE_COMMIT:
8222 *commit_id = obj_id;
8223 break;
8224 case GOT_OBJ_TYPE_TAG:
8225 err = got_object_open_as_tag(&tag, repo, obj_id);
8226 if (err)
8227 goto done;
8228 free(obj_id);
8229 err = got_object_get_type(&obj_type, repo,
8230 got_object_tag_get_object_id(tag));
8231 if (err)
8232 goto done;
8233 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8234 err = got_error(GOT_ERR_OBJ_TYPE);
8235 goto done;
8237 *commit_id = got_object_id_dup(
8238 got_object_tag_get_object_id(tag));
8239 if (*commit_id == NULL) {
8240 err = got_error_from_errno("got_object_id_dup");
8241 goto done;
8243 break;
8244 default:
8245 err = got_error(GOT_ERR_OBJ_TYPE);
8246 break;
8249 done:
8250 if (tag)
8251 got_object_tag_close(tag);
8252 if (err) {
8253 free(*commit_id);
8254 *commit_id = NULL;
8256 return err;
8259 static const struct got_error *
8260 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8261 struct tog_reflist_entry *re, struct got_repository *repo)
8263 struct tog_view *log_view;
8264 const struct got_error *err = NULL;
8265 struct got_object_id *commit_id = NULL;
8267 *new_view = NULL;
8269 err = resolve_reflist_entry(&commit_id, re, repo);
8270 if (err) {
8271 if (err->code != GOT_ERR_OBJ_TYPE)
8272 return err;
8273 else
8274 return NULL;
8277 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8278 if (log_view == NULL) {
8279 err = got_error_from_errno("view_open");
8280 goto done;
8283 err = open_log_view(log_view, commit_id, repo,
8284 got_ref_get_name(re->ref), "", 0);
8285 done:
8286 if (err)
8287 view_close(log_view);
8288 else
8289 *new_view = log_view;
8290 free(commit_id);
8291 return err;
8294 static void
8295 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8297 struct tog_reflist_entry *re;
8298 int i = 0;
8300 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8301 return;
8303 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8304 while (i++ < maxscroll) {
8305 if (re == NULL)
8306 break;
8307 s->first_displayed_entry = re;
8308 re = TAILQ_PREV(re, tog_reflist_head, entry);
8312 static const struct got_error *
8313 ref_scroll_down(struct tog_view *view, int maxscroll)
8315 struct tog_ref_view_state *s = &view->state.ref;
8316 struct tog_reflist_entry *next, *last;
8317 int n = 0;
8319 if (s->first_displayed_entry)
8320 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8321 else
8322 next = TAILQ_FIRST(&s->refs);
8324 last = s->last_displayed_entry;
8325 while (next && n++ < maxscroll) {
8326 if (last) {
8327 s->last_displayed_entry = last;
8328 last = TAILQ_NEXT(last, entry);
8330 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8331 s->first_displayed_entry = next;
8332 next = TAILQ_NEXT(next, entry);
8336 return NULL;
8339 static const struct got_error *
8340 search_start_ref_view(struct tog_view *view)
8342 struct tog_ref_view_state *s = &view->state.ref;
8344 s->matched_entry = NULL;
8345 return NULL;
8348 static int
8349 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8351 regmatch_t regmatch;
8353 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8354 0) == 0;
8357 static const struct got_error *
8358 search_next_ref_view(struct tog_view *view)
8360 struct tog_ref_view_state *s = &view->state.ref;
8361 struct tog_reflist_entry *re = NULL;
8363 if (!view->searching) {
8364 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8365 return NULL;
8368 if (s->matched_entry) {
8369 if (view->searching == TOG_SEARCH_FORWARD) {
8370 if (s->selected_entry)
8371 re = TAILQ_NEXT(s->selected_entry, entry);
8372 else
8373 re = TAILQ_PREV(s->selected_entry,
8374 tog_reflist_head, entry);
8375 } else {
8376 if (s->selected_entry == NULL)
8377 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8378 else
8379 re = TAILQ_PREV(s->selected_entry,
8380 tog_reflist_head, entry);
8382 } else {
8383 if (s->selected_entry)
8384 re = s->selected_entry;
8385 else if (view->searching == TOG_SEARCH_FORWARD)
8386 re = TAILQ_FIRST(&s->refs);
8387 else
8388 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8391 while (1) {
8392 if (re == NULL) {
8393 if (s->matched_entry == NULL) {
8394 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8395 return NULL;
8397 if (view->searching == TOG_SEARCH_FORWARD)
8398 re = TAILQ_FIRST(&s->refs);
8399 else
8400 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8403 if (match_reflist_entry(re, &view->regex)) {
8404 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8405 s->matched_entry = re;
8406 break;
8409 if (view->searching == TOG_SEARCH_FORWARD)
8410 re = TAILQ_NEXT(re, entry);
8411 else
8412 re = TAILQ_PREV(re, tog_reflist_head, entry);
8415 if (s->matched_entry) {
8416 s->first_displayed_entry = s->matched_entry;
8417 s->selected = 0;
8420 return NULL;
8423 static const struct got_error *
8424 show_ref_view(struct tog_view *view)
8426 const struct got_error *err = NULL;
8427 struct tog_ref_view_state *s = &view->state.ref;
8428 struct tog_reflist_entry *re;
8429 char *line = NULL;
8430 wchar_t *wline;
8431 struct tog_color *tc;
8432 int width, n, scrollx;
8433 int limit = view->nlines;
8435 werase(view->window);
8437 s->ndisplayed = 0;
8438 if (view_is_hsplit_top(view))
8439 --limit; /* border */
8441 if (limit == 0)
8442 return NULL;
8444 re = s->first_displayed_entry;
8446 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8447 s->nrefs) == -1)
8448 return got_error_from_errno("asprintf");
8450 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8451 if (err) {
8452 free(line);
8453 return err;
8455 if (view_needs_focus_indication(view))
8456 wstandout(view->window);
8457 waddwstr(view->window, wline);
8458 while (width++ < view->ncols)
8459 waddch(view->window, ' ');
8460 if (view_needs_focus_indication(view))
8461 wstandend(view->window);
8462 free(wline);
8463 wline = NULL;
8464 free(line);
8465 line = NULL;
8466 if (--limit <= 0)
8467 return NULL;
8469 n = 0;
8470 view->maxx = 0;
8471 while (re && limit > 0) {
8472 char *line = NULL;
8473 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8475 if (s->show_date) {
8476 struct got_commit_object *ci;
8477 struct got_tag_object *tag;
8478 struct got_object_id *id;
8479 struct tm tm;
8480 time_t t;
8482 err = got_ref_resolve(&id, s->repo, re->ref);
8483 if (err)
8484 return err;
8485 err = got_object_open_as_tag(&tag, s->repo, id);
8486 if (err) {
8487 if (err->code != GOT_ERR_OBJ_TYPE) {
8488 free(id);
8489 return err;
8491 err = got_object_open_as_commit(&ci, s->repo,
8492 id);
8493 if (err) {
8494 free(id);
8495 return err;
8497 t = got_object_commit_get_committer_time(ci);
8498 got_object_commit_close(ci);
8499 } else {
8500 t = got_object_tag_get_tagger_time(tag);
8501 got_object_tag_close(tag);
8503 free(id);
8504 if (gmtime_r(&t, &tm) == NULL)
8505 return got_error_from_errno("gmtime_r");
8506 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8507 return got_error(GOT_ERR_NO_SPACE);
8509 if (got_ref_is_symbolic(re->ref)) {
8510 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8511 ymd : "", got_ref_get_name(re->ref),
8512 got_ref_get_symref_target(re->ref)) == -1)
8513 return got_error_from_errno("asprintf");
8514 } else if (s->show_ids) {
8515 struct got_object_id *id;
8516 char *id_str;
8517 err = got_ref_resolve(&id, s->repo, re->ref);
8518 if (err)
8519 return err;
8520 err = got_object_id_str(&id_str, id);
8521 if (err) {
8522 free(id);
8523 return err;
8525 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8526 got_ref_get_name(re->ref), id_str) == -1) {
8527 err = got_error_from_errno("asprintf");
8528 free(id);
8529 free(id_str);
8530 return err;
8532 free(id);
8533 free(id_str);
8534 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8535 got_ref_get_name(re->ref)) == -1)
8536 return got_error_from_errno("asprintf");
8538 /* use full line width to determine view->maxx */
8539 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8540 if (err) {
8541 free(line);
8542 return err;
8544 view->maxx = MAX(view->maxx, width);
8545 free(wline);
8546 wline = NULL;
8548 err = format_line(&wline, &width, &scrollx, line, view->x,
8549 view->ncols, 0, 0);
8550 if (err) {
8551 free(line);
8552 return err;
8554 if (n == s->selected) {
8555 if (view->focussed)
8556 wstandout(view->window);
8557 s->selected_entry = re;
8559 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8560 if (tc)
8561 wattr_on(view->window,
8562 COLOR_PAIR(tc->colorpair), NULL);
8563 waddwstr(view->window, &wline[scrollx]);
8564 if (tc)
8565 wattr_off(view->window,
8566 COLOR_PAIR(tc->colorpair), NULL);
8567 if (width < view->ncols)
8568 waddch(view->window, '\n');
8569 if (n == s->selected && view->focussed)
8570 wstandend(view->window);
8571 free(line);
8572 free(wline);
8573 wline = NULL;
8574 n++;
8575 s->ndisplayed++;
8576 s->last_displayed_entry = re;
8578 limit--;
8579 re = TAILQ_NEXT(re, entry);
8582 view_border(view);
8583 return err;
8586 static const struct got_error *
8587 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8588 struct tog_reflist_entry *re, struct got_repository *repo)
8590 const struct got_error *err = NULL;
8591 struct got_object_id *commit_id = NULL;
8592 struct tog_view *tree_view;
8594 *new_view = NULL;
8596 err = resolve_reflist_entry(&commit_id, re, repo);
8597 if (err) {
8598 if (err->code != GOT_ERR_OBJ_TYPE)
8599 return err;
8600 else
8601 return NULL;
8605 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8606 if (tree_view == NULL) {
8607 err = got_error_from_errno("view_open");
8608 goto done;
8611 err = open_tree_view(tree_view, commit_id,
8612 got_ref_get_name(re->ref), repo);
8613 if (err)
8614 goto done;
8616 *new_view = tree_view;
8617 done:
8618 free(commit_id);
8619 return err;
8622 static const struct got_error *
8623 ref_goto_line(struct tog_view *view, int nlines)
8625 const struct got_error *err = NULL;
8626 struct tog_ref_view_state *s = &view->state.ref;
8627 int g, idx = s->selected_entry->idx;
8629 g = view->gline;
8630 view->gline = 0;
8632 if (g == 0)
8633 g = 1;
8634 else if (g > s->nrefs)
8635 g = s->nrefs;
8637 if (g >= s->first_displayed_entry->idx + 1 &&
8638 g <= s->last_displayed_entry->idx + 1 &&
8639 g - s->first_displayed_entry->idx - 1 < nlines) {
8640 s->selected = g - s->first_displayed_entry->idx - 1;
8641 return NULL;
8644 if (idx + 1 < g) {
8645 err = ref_scroll_down(view, g - idx - 1);
8646 if (err)
8647 return err;
8648 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8649 s->first_displayed_entry->idx + s->selected < g &&
8650 s->selected < s->ndisplayed - 1)
8651 s->selected = g - s->first_displayed_entry->idx - 1;
8652 } else if (idx + 1 > g)
8653 ref_scroll_up(s, idx - g + 1);
8655 if (g < nlines && s->first_displayed_entry->idx == 0)
8656 s->selected = g - 1;
8658 return NULL;
8662 static const struct got_error *
8663 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8665 const struct got_error *err = NULL;
8666 struct tog_ref_view_state *s = &view->state.ref;
8667 struct tog_reflist_entry *re;
8668 int n, nscroll = view->nlines - 1;
8670 if (view->gline)
8671 return ref_goto_line(view, nscroll);
8673 switch (ch) {
8674 case '0':
8675 case '$':
8676 case KEY_RIGHT:
8677 case 'l':
8678 case KEY_LEFT:
8679 case 'h':
8680 horizontal_scroll_input(view, ch);
8681 break;
8682 case 'i':
8683 s->show_ids = !s->show_ids;
8684 view->count = 0;
8685 break;
8686 case 'm':
8687 s->show_date = !s->show_date;
8688 view->count = 0;
8689 break;
8690 case 'o':
8691 s->sort_by_date = !s->sort_by_date;
8692 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8693 view->count = 0;
8694 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8695 got_ref_cmp_by_commit_timestamp_descending :
8696 tog_ref_cmp_by_name, s->repo);
8697 if (err)
8698 break;
8699 got_reflist_object_id_map_free(tog_refs_idmap);
8700 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8701 &tog_refs, s->repo);
8702 if (err)
8703 break;
8704 ref_view_free_refs(s);
8705 err = ref_view_load_refs(s);
8706 break;
8707 case KEY_ENTER:
8708 case '\r':
8709 view->count = 0;
8710 if (!s->selected_entry)
8711 break;
8712 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8713 break;
8714 case 'T':
8715 view->count = 0;
8716 if (!s->selected_entry)
8717 break;
8718 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8719 break;
8720 case 'g':
8721 case '=':
8722 case KEY_HOME:
8723 s->selected = 0;
8724 view->count = 0;
8725 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8726 break;
8727 case 'G':
8728 case '*':
8729 case KEY_END: {
8730 int eos = view->nlines - 1;
8732 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8733 --eos; /* border */
8734 s->selected = 0;
8735 view->count = 0;
8736 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8737 for (n = 0; n < eos; n++) {
8738 if (re == NULL)
8739 break;
8740 s->first_displayed_entry = re;
8741 re = TAILQ_PREV(re, tog_reflist_head, entry);
8743 if (n > 0)
8744 s->selected = n - 1;
8745 break;
8747 case 'k':
8748 case KEY_UP:
8749 case CTRL('p'):
8750 if (s->selected > 0) {
8751 s->selected--;
8752 break;
8754 ref_scroll_up(s, 1);
8755 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8756 view->count = 0;
8757 break;
8758 case CTRL('u'):
8759 case 'u':
8760 nscroll /= 2;
8761 /* FALL THROUGH */
8762 case KEY_PPAGE:
8763 case CTRL('b'):
8764 case 'b':
8765 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8766 s->selected -= MIN(nscroll, s->selected);
8767 ref_scroll_up(s, MAX(0, nscroll));
8768 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8769 view->count = 0;
8770 break;
8771 case 'j':
8772 case KEY_DOWN:
8773 case CTRL('n'):
8774 if (s->selected < s->ndisplayed - 1) {
8775 s->selected++;
8776 break;
8778 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8779 /* can't scroll any further */
8780 view->count = 0;
8781 break;
8783 ref_scroll_down(view, 1);
8784 break;
8785 case CTRL('d'):
8786 case 'd':
8787 nscroll /= 2;
8788 /* FALL THROUGH */
8789 case KEY_NPAGE:
8790 case CTRL('f'):
8791 case 'f':
8792 case ' ':
8793 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8794 /* can't scroll any further; move cursor down */
8795 if (s->selected < s->ndisplayed - 1)
8796 s->selected += MIN(nscroll,
8797 s->ndisplayed - s->selected - 1);
8798 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8799 s->selected += s->ndisplayed - s->selected - 1;
8800 view->count = 0;
8801 break;
8803 ref_scroll_down(view, nscroll);
8804 break;
8805 case CTRL('l'):
8806 view->count = 0;
8807 tog_free_refs();
8808 err = tog_load_refs(s->repo, s->sort_by_date);
8809 if (err)
8810 break;
8811 ref_view_free_refs(s);
8812 err = ref_view_load_refs(s);
8813 break;
8814 case KEY_RESIZE:
8815 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8816 s->selected = view->nlines - 2;
8817 break;
8818 default:
8819 view->count = 0;
8820 break;
8823 return err;
8826 __dead static void
8827 usage_ref(void)
8829 endwin();
8830 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8831 getprogname());
8832 exit(1);
8835 static const struct got_error *
8836 cmd_ref(int argc, char *argv[])
8838 const struct got_error *error;
8839 struct got_repository *repo = NULL;
8840 struct got_worktree *worktree = NULL;
8841 char *cwd = NULL, *repo_path = NULL;
8842 int ch;
8843 struct tog_view *view;
8844 int *pack_fds = NULL;
8846 while ((ch = getopt(argc, argv, "r:")) != -1) {
8847 switch (ch) {
8848 case 'r':
8849 repo_path = realpath(optarg, NULL);
8850 if (repo_path == NULL)
8851 return got_error_from_errno2("realpath",
8852 optarg);
8853 break;
8854 default:
8855 usage_ref();
8856 /* NOTREACHED */
8860 argc -= optind;
8861 argv += optind;
8863 if (argc > 1)
8864 usage_ref();
8866 error = got_repo_pack_fds_open(&pack_fds);
8867 if (error != NULL)
8868 goto done;
8870 if (repo_path == NULL) {
8871 cwd = getcwd(NULL, 0);
8872 if (cwd == NULL)
8873 return got_error_from_errno("getcwd");
8874 error = got_worktree_open(&worktree, cwd);
8875 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8876 goto done;
8877 if (worktree)
8878 repo_path =
8879 strdup(got_worktree_get_repo_path(worktree));
8880 else
8881 repo_path = strdup(cwd);
8882 if (repo_path == NULL) {
8883 error = got_error_from_errno("strdup");
8884 goto done;
8888 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8889 if (error != NULL)
8890 goto done;
8892 init_curses();
8894 error = apply_unveil(got_repo_get_path(repo), NULL);
8895 if (error)
8896 goto done;
8898 error = tog_load_refs(repo, 0);
8899 if (error)
8900 goto done;
8902 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8903 if (view == NULL) {
8904 error = got_error_from_errno("view_open");
8905 goto done;
8908 error = open_ref_view(view, repo);
8909 if (error)
8910 goto done;
8912 if (worktree) {
8913 /* Release work tree lock. */
8914 got_worktree_close(worktree);
8915 worktree = NULL;
8917 error = view_loop(view);
8918 done:
8919 free(repo_path);
8920 free(cwd);
8921 if (repo) {
8922 const struct got_error *close_err = got_repo_close(repo);
8923 if (close_err)
8924 error = close_err;
8926 if (pack_fds) {
8927 const struct got_error *pack_err =
8928 got_repo_pack_fds_close(pack_fds);
8929 if (error == NULL)
8930 error = pack_err;
8932 tog_free_refs();
8933 return error;
8936 static const struct got_error*
8937 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8938 const char *str)
8940 size_t len;
8942 if (win == NULL)
8943 win = stdscr;
8945 len = strlen(str);
8946 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8948 if (focus)
8949 wstandout(win);
8950 if (mvwprintw(win, y, x, "%s", str) == ERR)
8951 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8952 if (focus)
8953 wstandend(win);
8955 return NULL;
8958 static const struct got_error *
8959 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8961 off_t *p;
8963 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8964 if (p == NULL) {
8965 free(*line_offsets);
8966 *line_offsets = NULL;
8967 return got_error_from_errno("reallocarray");
8970 *line_offsets = p;
8971 (*line_offsets)[*nlines] = off;
8972 ++(*nlines);
8973 return NULL;
8976 static const struct got_error *
8977 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8979 *ret = 0;
8981 for (;n > 0; --n, ++km) {
8982 char *t0, *t, *k;
8983 size_t len = 1;
8985 if (km->keys == NULL)
8986 continue;
8988 t = t0 = strdup(km->keys);
8989 if (t0 == NULL)
8990 return got_error_from_errno("strdup");
8992 len += strlen(t);
8993 while ((k = strsep(&t, " ")) != NULL)
8994 len += strlen(k) > 1 ? 2 : 0;
8995 free(t0);
8996 *ret = MAX(*ret, len);
8999 return NULL;
9003 * Write keymap section headers, keys, and key info in km to f.
9004 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9005 * wrap control and symbolic keys in guillemets, else use <>.
9007 static const struct got_error *
9008 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9010 int n, len = width;
9012 if (km->keys) {
9013 static const char *u8_glyph[] = {
9014 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9015 "\xe2\x80\xba" /* U+203A (utf8 >) */
9017 char *t0, *t, *k;
9018 int cs, s, first = 1;
9020 cs = got_locale_is_utf8();
9022 t = t0 = strdup(km->keys);
9023 if (t0 == NULL)
9024 return got_error_from_errno("strdup");
9026 len = strlen(km->keys);
9027 while ((k = strsep(&t, " ")) != NULL) {
9028 s = strlen(k) > 1; /* control or symbolic key */
9029 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9030 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9031 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9032 if (n < 0) {
9033 free(t0);
9034 return got_error_from_errno("fprintf");
9036 first = 0;
9037 len += s ? 2 : 0;
9038 *off += n;
9040 free(t0);
9042 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9043 if (n < 0)
9044 return got_error_from_errno("fprintf");
9045 *off += n;
9047 return NULL;
9050 static const struct got_error *
9051 format_help(struct tog_help_view_state *s)
9053 const struct got_error *err = NULL;
9054 off_t off = 0;
9055 int i, max, n, show = s->all;
9056 static const struct tog_key_map km[] = {
9057 #define KEYMAP_(info, type) { NULL, (info), type }
9058 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9059 GENERATE_HELP
9060 #undef KEYMAP_
9061 #undef KEY_
9064 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9065 if (err)
9066 return err;
9068 n = nitems(km);
9069 err = max_key_str(&max, km, n);
9070 if (err)
9071 return err;
9073 for (i = 0; i < n; ++i) {
9074 if (km[i].keys == NULL) {
9075 show = s->all;
9076 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9077 km[i].type == s->type || s->all)
9078 show = 1;
9080 if (show) {
9081 err = format_help_line(&off, s->f, &km[i], max);
9082 if (err)
9083 return err;
9084 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9085 if (err)
9086 return err;
9089 fputc('\n', s->f);
9090 ++off;
9091 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9092 return err;
9095 static const struct got_error *
9096 create_help(struct tog_help_view_state *s)
9098 FILE *f;
9099 const struct got_error *err;
9101 free(s->line_offsets);
9102 s->line_offsets = NULL;
9103 s->nlines = 0;
9105 f = got_opentemp();
9106 if (f == NULL)
9107 return got_error_from_errno("got_opentemp");
9108 s->f = f;
9110 err = format_help(s);
9111 if (err)
9112 return err;
9114 if (s->f && fflush(s->f) != 0)
9115 return got_error_from_errno("fflush");
9117 return NULL;
9120 static const struct got_error *
9121 search_start_help_view(struct tog_view *view)
9123 view->state.help.matched_line = 0;
9124 return NULL;
9127 static void
9128 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9129 size_t *nlines, int **first, int **last, int **match, int **selected)
9131 struct tog_help_view_state *s = &view->state.help;
9133 *f = s->f;
9134 *nlines = s->nlines;
9135 *line_offsets = s->line_offsets;
9136 *match = &s->matched_line;
9137 *first = &s->first_displayed_line;
9138 *last = &s->last_displayed_line;
9139 *selected = &s->selected_line;
9142 static const struct got_error *
9143 show_help_view(struct tog_view *view)
9145 struct tog_help_view_state *s = &view->state.help;
9146 const struct got_error *err;
9147 regmatch_t *regmatch = &view->regmatch;
9148 wchar_t *wline;
9149 char *line;
9150 ssize_t linelen;
9151 size_t linesz = 0;
9152 int width, nprinted = 0, rc = 0;
9153 int eos = view->nlines;
9155 if (view_is_hsplit_top(view))
9156 --eos; /* account for border */
9158 s->lineno = 0;
9159 rewind(s->f);
9160 werase(view->window);
9162 if (view->gline > s->nlines - 1)
9163 view->gline = s->nlines - 1;
9165 err = win_draw_center(view->window, 0, 0, view->ncols,
9166 view_needs_focus_indication(view),
9167 "tog help (press q to return to tog)");
9168 if (err)
9169 return err;
9170 if (eos <= 1)
9171 return NULL;
9172 waddstr(view->window, "\n\n");
9173 eos -= 2;
9175 s->eof = 0;
9176 view->maxx = 0;
9177 line = NULL;
9178 while (eos > 0 && nprinted < eos) {
9179 attr_t attr = 0;
9181 linelen = getline(&line, &linesz, s->f);
9182 if (linelen == -1) {
9183 if (!feof(s->f)) {
9184 free(line);
9185 return got_ferror(s->f, GOT_ERR_IO);
9187 s->eof = 1;
9188 break;
9190 if (++s->lineno < s->first_displayed_line)
9191 continue;
9192 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9193 continue;
9194 if (s->lineno == view->hiline)
9195 attr = A_STANDOUT;
9197 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9198 view->x ? 1 : 0);
9199 if (err) {
9200 free(line);
9201 return err;
9203 view->maxx = MAX(view->maxx, width);
9204 free(wline);
9205 wline = NULL;
9207 if (attr)
9208 wattron(view->window, attr);
9209 if (s->first_displayed_line + nprinted == s->matched_line &&
9210 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9211 err = add_matched_line(&width, line, view->ncols - 1, 0,
9212 view->window, view->x, regmatch);
9213 if (err) {
9214 free(line);
9215 return err;
9217 } else {
9218 int skip;
9220 err = format_line(&wline, &width, &skip, line,
9221 view->x, view->ncols, 0, view->x ? 1 : 0);
9222 if (err) {
9223 free(line);
9224 return err;
9226 waddwstr(view->window, &wline[skip]);
9227 free(wline);
9228 wline = NULL;
9230 if (s->lineno == view->hiline) {
9231 while (width++ < view->ncols)
9232 waddch(view->window, ' ');
9233 } else {
9234 if (width < view->ncols)
9235 waddch(view->window, '\n');
9237 if (attr)
9238 wattroff(view->window, attr);
9239 if (++nprinted == 1)
9240 s->first_displayed_line = s->lineno;
9242 free(line);
9243 if (nprinted > 0)
9244 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9245 else
9246 s->last_displayed_line = s->first_displayed_line;
9248 view_border(view);
9250 if (s->eof) {
9251 rc = waddnstr(view->window,
9252 "See the tog(1) manual page for full documentation",
9253 view->ncols - 1);
9254 if (rc == ERR)
9255 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9256 } else {
9257 wmove(view->window, view->nlines - 1, 0);
9258 wclrtoeol(view->window);
9259 wstandout(view->window);
9260 rc = waddnstr(view->window, "scroll down for more...",
9261 view->ncols - 1);
9262 if (rc == ERR)
9263 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9264 if (getcurx(view->window) < view->ncols - 6) {
9265 rc = wprintw(view->window, "[%.0f%%]",
9266 100.00 * s->last_displayed_line / s->nlines);
9267 if (rc == ERR)
9268 return got_error_msg(GOT_ERR_IO, "wprintw");
9270 wstandend(view->window);
9273 return NULL;
9276 static const struct got_error *
9277 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9279 struct tog_help_view_state *s = &view->state.help;
9280 const struct got_error *err = NULL;
9281 char *line = NULL;
9282 ssize_t linelen;
9283 size_t linesz = 0;
9284 int eos, nscroll;
9286 eos = nscroll = view->nlines;
9287 if (view_is_hsplit_top(view))
9288 --eos; /* border */
9290 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9292 switch (ch) {
9293 case '0':
9294 case '$':
9295 case KEY_RIGHT:
9296 case 'l':
9297 case KEY_LEFT:
9298 case 'h':
9299 horizontal_scroll_input(view, ch);
9300 break;
9301 case 'g':
9302 case KEY_HOME:
9303 s->first_displayed_line = 1;
9304 view->count = 0;
9305 break;
9306 case 'G':
9307 case KEY_END:
9308 view->count = 0;
9309 if (s->eof)
9310 break;
9311 s->first_displayed_line = (s->nlines - eos) + 3;
9312 s->eof = 1;
9313 break;
9314 case 'k':
9315 case KEY_UP:
9316 if (s->first_displayed_line > 1)
9317 --s->first_displayed_line;
9318 else
9319 view->count = 0;
9320 break;
9321 case CTRL('u'):
9322 case 'u':
9323 nscroll /= 2;
9324 /* FALL THROUGH */
9325 case KEY_PPAGE:
9326 case CTRL('b'):
9327 case 'b':
9328 if (s->first_displayed_line == 1) {
9329 view->count = 0;
9330 break;
9332 while (--nscroll > 0 && s->first_displayed_line > 1)
9333 s->first_displayed_line--;
9334 break;
9335 case 'j':
9336 case KEY_DOWN:
9337 case CTRL('n'):
9338 if (!s->eof)
9339 ++s->first_displayed_line;
9340 else
9341 view->count = 0;
9342 break;
9343 case CTRL('d'):
9344 case 'd':
9345 nscroll /= 2;
9346 /* FALL THROUGH */
9347 case KEY_NPAGE:
9348 case CTRL('f'):
9349 case 'f':
9350 case ' ':
9351 if (s->eof) {
9352 view->count = 0;
9353 break;
9355 while (!s->eof && --nscroll > 0) {
9356 linelen = getline(&line, &linesz, s->f);
9357 s->first_displayed_line++;
9358 if (linelen == -1) {
9359 if (feof(s->f))
9360 s->eof = 1;
9361 else
9362 err = got_ferror(s->f, GOT_ERR_IO);
9363 break;
9366 free(line);
9367 break;
9368 default:
9369 view->count = 0;
9370 break;
9373 return err;
9376 static const struct got_error *
9377 close_help_view(struct tog_view *view)
9379 struct tog_help_view_state *s = &view->state.help;
9381 free(s->line_offsets);
9382 s->line_offsets = NULL;
9383 if (fclose(s->f) == EOF)
9384 return got_error_from_errno("fclose");
9386 return NULL;
9389 static const struct got_error *
9390 reset_help_view(struct tog_view *view)
9392 struct tog_help_view_state *s = &view->state.help;
9395 if (s->f && fclose(s->f) == EOF)
9396 return got_error_from_errno("fclose");
9398 wclear(view->window);
9399 view->count = 0;
9400 view->x = 0;
9401 s->all = !s->all;
9402 s->first_displayed_line = 1;
9403 s->last_displayed_line = view->nlines;
9404 s->matched_line = 0;
9406 return create_help(s);
9409 static const struct got_error *
9410 open_help_view(struct tog_view *view, struct tog_view *parent)
9412 const struct got_error *err = NULL;
9413 struct tog_help_view_state *s = &view->state.help;
9415 s->type = (enum tog_keymap_type)parent->type;
9416 s->first_displayed_line = 1;
9417 s->last_displayed_line = view->nlines;
9418 s->selected_line = 1;
9420 view->show = show_help_view;
9421 view->input = input_help_view;
9422 view->reset = reset_help_view;
9423 view->close = close_help_view;
9424 view->search_start = search_start_help_view;
9425 view->search_setup = search_setup_help_view;
9426 view->search_next = search_next_view_match;
9428 err = create_help(s);
9429 return err;
9432 static const struct got_error *
9433 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9434 enum tog_view_type request, int y, int x)
9436 const struct got_error *err = NULL;
9438 *new_view = NULL;
9440 switch (request) {
9441 case TOG_VIEW_DIFF:
9442 if (view->type == TOG_VIEW_LOG) {
9443 struct tog_log_view_state *s = &view->state.log;
9445 err = open_diff_view_for_commit(new_view, y, x,
9446 s->selected_entry->commit, s->selected_entry->id,
9447 view, s->repo);
9448 } else
9449 return got_error_msg(GOT_ERR_NOT_IMPL,
9450 "parent/child view pair not supported");
9451 break;
9452 case TOG_VIEW_BLAME:
9453 if (view->type == TOG_VIEW_TREE) {
9454 struct tog_tree_view_state *s = &view->state.tree;
9456 err = blame_tree_entry(new_view, y, x,
9457 s->selected_entry, &s->parents, s->commit_id,
9458 s->repo);
9459 } else
9460 return got_error_msg(GOT_ERR_NOT_IMPL,
9461 "parent/child view pair not supported");
9462 break;
9463 case TOG_VIEW_LOG:
9464 if (view->type == TOG_VIEW_BLAME)
9465 err = log_annotated_line(new_view, y, x,
9466 view->state.blame.repo, view->state.blame.id_to_log);
9467 else if (view->type == TOG_VIEW_TREE)
9468 err = log_selected_tree_entry(new_view, y, x,
9469 &view->state.tree);
9470 else if (view->type == TOG_VIEW_REF)
9471 err = log_ref_entry(new_view, y, x,
9472 view->state.ref.selected_entry,
9473 view->state.ref.repo);
9474 else
9475 return got_error_msg(GOT_ERR_NOT_IMPL,
9476 "parent/child view pair not supported");
9477 break;
9478 case TOG_VIEW_TREE:
9479 if (view->type == TOG_VIEW_LOG)
9480 err = browse_commit_tree(new_view, y, x,
9481 view->state.log.selected_entry,
9482 view->state.log.in_repo_path,
9483 view->state.log.head_ref_name,
9484 view->state.log.repo);
9485 else if (view->type == TOG_VIEW_REF)
9486 err = browse_ref_tree(new_view, y, x,
9487 view->state.ref.selected_entry,
9488 view->state.ref.repo);
9489 else
9490 return got_error_msg(GOT_ERR_NOT_IMPL,
9491 "parent/child view pair not supported");
9492 break;
9493 case TOG_VIEW_REF:
9494 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9495 if (*new_view == NULL)
9496 return got_error_from_errno("view_open");
9497 if (view->type == TOG_VIEW_LOG)
9498 err = open_ref_view(*new_view, view->state.log.repo);
9499 else if (view->type == TOG_VIEW_TREE)
9500 err = open_ref_view(*new_view, view->state.tree.repo);
9501 else
9502 err = got_error_msg(GOT_ERR_NOT_IMPL,
9503 "parent/child view pair not supported");
9504 if (err)
9505 view_close(*new_view);
9506 break;
9507 case TOG_VIEW_HELP:
9508 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9509 if (*new_view == NULL)
9510 return got_error_from_errno("view_open");
9511 err = open_help_view(*new_view, view);
9512 if (err)
9513 view_close(*new_view);
9514 break;
9515 default:
9516 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9519 return err;
9523 * If view was scrolled down to move the selected line into view when opening a
9524 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9526 static void
9527 offset_selection_up(struct tog_view *view)
9529 switch (view->type) {
9530 case TOG_VIEW_BLAME: {
9531 struct tog_blame_view_state *s = &view->state.blame;
9532 if (s->first_displayed_line == 1) {
9533 s->selected_line = MAX(s->selected_line - view->offset,
9534 1);
9535 break;
9537 if (s->first_displayed_line > view->offset)
9538 s->first_displayed_line -= view->offset;
9539 else
9540 s->first_displayed_line = 1;
9541 s->selected_line += view->offset;
9542 break;
9544 case TOG_VIEW_LOG:
9545 log_scroll_up(&view->state.log, view->offset);
9546 view->state.log.selected += view->offset;
9547 break;
9548 case TOG_VIEW_REF:
9549 ref_scroll_up(&view->state.ref, view->offset);
9550 view->state.ref.selected += view->offset;
9551 break;
9552 case TOG_VIEW_TREE:
9553 tree_scroll_up(&view->state.tree, view->offset);
9554 view->state.tree.selected += view->offset;
9555 break;
9556 default:
9557 break;
9560 view->offset = 0;
9564 * If the selected line is in the section of screen covered by the bottom split,
9565 * scroll down offset lines to move it into view and index its new position.
9567 static const struct got_error *
9568 offset_selection_down(struct tog_view *view)
9570 const struct got_error *err = NULL;
9571 const struct got_error *(*scrolld)(struct tog_view *, int);
9572 int *selected = NULL;
9573 int header, offset;
9575 switch (view->type) {
9576 case TOG_VIEW_BLAME: {
9577 struct tog_blame_view_state *s = &view->state.blame;
9578 header = 3;
9579 scrolld = NULL;
9580 if (s->selected_line > view->nlines - header) {
9581 offset = abs(view->nlines - s->selected_line - header);
9582 s->first_displayed_line += offset;
9583 s->selected_line -= offset;
9584 view->offset = offset;
9586 break;
9588 case TOG_VIEW_LOG: {
9589 struct tog_log_view_state *s = &view->state.log;
9590 scrolld = &log_scroll_down;
9591 header = view_is_parent_view(view) ? 3 : 2;
9592 selected = &s->selected;
9593 break;
9595 case TOG_VIEW_REF: {
9596 struct tog_ref_view_state *s = &view->state.ref;
9597 scrolld = &ref_scroll_down;
9598 header = 3;
9599 selected = &s->selected;
9600 break;
9602 case TOG_VIEW_TREE: {
9603 struct tog_tree_view_state *s = &view->state.tree;
9604 scrolld = &tree_scroll_down;
9605 header = 5;
9606 selected = &s->selected;
9607 break;
9609 default:
9610 selected = NULL;
9611 scrolld = NULL;
9612 header = 0;
9613 break;
9616 if (selected && *selected > view->nlines - header) {
9617 offset = abs(view->nlines - *selected - header);
9618 view->offset = offset;
9619 if (scrolld && offset) {
9620 err = scrolld(view, offset);
9621 *selected -= offset;
9625 return err;
9628 static void
9629 list_commands(FILE *fp)
9631 size_t i;
9633 fprintf(fp, "commands:");
9634 for (i = 0; i < nitems(tog_commands); i++) {
9635 const struct tog_cmd *cmd = &tog_commands[i];
9636 fprintf(fp, " %s", cmd->name);
9638 fputc('\n', fp);
9641 __dead static void
9642 usage(int hflag, int status)
9644 FILE *fp = (status == 0) ? stdout : stderr;
9646 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9647 getprogname());
9648 if (hflag) {
9649 fprintf(fp, "lazy usage: %s path\n", getprogname());
9650 list_commands(fp);
9652 exit(status);
9655 static char **
9656 make_argv(int argc, ...)
9658 va_list ap;
9659 char **argv;
9660 int i;
9662 va_start(ap, argc);
9664 argv = calloc(argc, sizeof(char *));
9665 if (argv == NULL)
9666 err(1, "calloc");
9667 for (i = 0; i < argc; i++) {
9668 argv[i] = strdup(va_arg(ap, char *));
9669 if (argv[i] == NULL)
9670 err(1, "strdup");
9673 va_end(ap);
9674 return argv;
9678 * Try to convert 'tog path' into a 'tog log path' command.
9679 * The user could simply have mistyped the command rather than knowingly
9680 * provided a path. So check whether argv[0] can in fact be resolved
9681 * to a path in the HEAD commit and print a special error if not.
9682 * This hack is for mpi@ <3
9684 static const struct got_error *
9685 tog_log_with_path(int argc, char *argv[])
9687 const struct got_error *error = NULL, *close_err;
9688 const struct tog_cmd *cmd = NULL;
9689 struct got_repository *repo = NULL;
9690 struct got_worktree *worktree = NULL;
9691 struct got_object_id *commit_id = NULL, *id = NULL;
9692 struct got_commit_object *commit = NULL;
9693 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9694 char *commit_id_str = NULL, **cmd_argv = NULL;
9695 int *pack_fds = NULL;
9697 cwd = getcwd(NULL, 0);
9698 if (cwd == NULL)
9699 return got_error_from_errno("getcwd");
9701 error = got_repo_pack_fds_open(&pack_fds);
9702 if (error != NULL)
9703 goto done;
9705 error = got_worktree_open(&worktree, cwd);
9706 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9707 goto done;
9709 if (worktree)
9710 repo_path = strdup(got_worktree_get_repo_path(worktree));
9711 else
9712 repo_path = strdup(cwd);
9713 if (repo_path == NULL) {
9714 error = got_error_from_errno("strdup");
9715 goto done;
9718 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9719 if (error != NULL)
9720 goto done;
9722 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9723 repo, worktree);
9724 if (error)
9725 goto done;
9727 error = tog_load_refs(repo, 0);
9728 if (error)
9729 goto done;
9730 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9731 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9732 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9733 if (error)
9734 goto done;
9736 if (worktree) {
9737 got_worktree_close(worktree);
9738 worktree = NULL;
9741 error = got_object_open_as_commit(&commit, repo, commit_id);
9742 if (error)
9743 goto done;
9745 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9746 if (error) {
9747 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9748 goto done;
9749 fprintf(stderr, "%s: '%s' is no known command or path\n",
9750 getprogname(), argv[0]);
9751 usage(1, 1);
9752 /* not reached */
9755 error = got_object_id_str(&commit_id_str, commit_id);
9756 if (error)
9757 goto done;
9759 cmd = &tog_commands[0]; /* log */
9760 argc = 4;
9761 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9762 error = cmd->cmd_main(argc, cmd_argv);
9763 done:
9764 if (repo) {
9765 close_err = got_repo_close(repo);
9766 if (error == NULL)
9767 error = close_err;
9769 if (commit)
9770 got_object_commit_close(commit);
9771 if (worktree)
9772 got_worktree_close(worktree);
9773 if (pack_fds) {
9774 const struct got_error *pack_err =
9775 got_repo_pack_fds_close(pack_fds);
9776 if (error == NULL)
9777 error = pack_err;
9779 free(id);
9780 free(commit_id_str);
9781 free(commit_id);
9782 free(cwd);
9783 free(repo_path);
9784 free(in_repo_path);
9785 if (cmd_argv) {
9786 int i;
9787 for (i = 0; i < argc; i++)
9788 free(cmd_argv[i]);
9789 free(cmd_argv);
9791 tog_free_refs();
9792 return error;
9795 int
9796 main(int argc, char *argv[])
9798 const struct got_error *io_err, *error = NULL;
9799 const struct tog_cmd *cmd = NULL;
9800 int ch, hflag = 0, Vflag = 0;
9801 char **cmd_argv = NULL;
9802 static const struct option longopts[] = {
9803 { "version", no_argument, NULL, 'V' },
9804 { NULL, 0, NULL, 0}
9806 char *diff_algo_str = NULL;
9807 const char *test_script_path;
9809 setlocale(LC_CTYPE, "");
9812 * Test mode init must happen before pledge() because "tty" will
9813 * not allow TTY-related ioctls to occur via regular files.
9815 test_script_path = getenv("TOG_TEST_SCRIPT");
9816 if (test_script_path != NULL) {
9817 error = init_mock_term(test_script_path);
9818 if (error) {
9819 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9820 return 1;
9822 } else if (!isatty(STDIN_FILENO))
9823 errx(1, "standard input is not a tty");
9825 #if !defined(PROFILE)
9826 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9827 NULL) == -1)
9828 err(1, "pledge");
9829 #endif
9831 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9832 switch (ch) {
9833 case 'h':
9834 hflag = 1;
9835 break;
9836 case 'V':
9837 Vflag = 1;
9838 break;
9839 default:
9840 usage(hflag, 1);
9841 /* NOTREACHED */
9845 argc -= optind;
9846 argv += optind;
9847 optind = 1;
9848 optreset = 1;
9850 if (Vflag) {
9851 got_version_print_str();
9852 return 0;
9855 if (argc == 0) {
9856 if (hflag)
9857 usage(hflag, 0);
9858 /* Build an argument vector which runs a default command. */
9859 cmd = &tog_commands[0];
9860 argc = 1;
9861 cmd_argv = make_argv(argc, cmd->name);
9862 } else {
9863 size_t i;
9865 /* Did the user specify a command? */
9866 for (i = 0; i < nitems(tog_commands); i++) {
9867 if (strncmp(tog_commands[i].name, argv[0],
9868 strlen(argv[0])) == 0) {
9869 cmd = &tog_commands[i];
9870 break;
9875 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9876 if (diff_algo_str) {
9877 if (strcasecmp(diff_algo_str, "patience") == 0)
9878 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9879 if (strcasecmp(diff_algo_str, "myers") == 0)
9880 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9883 if (cmd == NULL) {
9884 if (argc != 1)
9885 usage(0, 1);
9886 /* No command specified; try log with a path */
9887 error = tog_log_with_path(argc, argv);
9888 } else {
9889 if (hflag)
9890 cmd->cmd_usage();
9891 else
9892 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9895 if (using_mock_io) {
9896 io_err = tog_io_close();
9897 if (error == NULL)
9898 error = io_err;
9900 endwin();
9901 if (cmd_argv) {
9902 int i;
9903 for (i = 0; i < argc; i++)
9904 free(cmd_argv[i]);
9905 free(cmd_argv);
9908 if (error && error->code != GOT_ERR_CANCELLED &&
9909 error->code != GOT_ERR_EOF &&
9910 error->code != GOT_ERR_PRIVSEP_EXIT &&
9911 error->code != GOT_ERR_PRIVSEP_PIPE &&
9912 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9913 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9914 return 0;