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, "SCREENDUMP", 10) == 0)
1653 *ch = TOG_KEY_SCRDUMP;
1654 else if (isdigit((unsigned char)*line)) {
1655 char *t = line;
1657 while (isdigit((unsigned char)*t))
1658 ++t;
1659 view->ch = *ch = *t;
1660 *t = '\0';
1661 /* ignore error, view->count is 0 if instruction is invalid */
1662 view->count = strtonum(line, 0, INT_MAX, NULL);
1663 } else
1664 *ch = *line;
1666 done:
1667 free(line);
1668 return err;
1671 static const struct got_error *
1672 view_input(struct tog_view **new, int *done, struct tog_view *view,
1673 struct tog_view_list_head *views, int fast_refresh)
1675 const struct got_error *err = NULL;
1676 struct tog_view *v;
1677 int ch, errcode;
1679 *new = NULL;
1681 if (view->action)
1682 action_report(view);
1684 /* Clear "no matches" indicator. */
1685 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1686 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1687 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1688 view->count = 0;
1691 if (view->searching && !view->search_next_done) {
1692 errcode = pthread_mutex_unlock(&tog_mutex);
1693 if (errcode)
1694 return got_error_set_errno(errcode,
1695 "pthread_mutex_unlock");
1696 sched_yield();
1697 errcode = pthread_mutex_lock(&tog_mutex);
1698 if (errcode)
1699 return got_error_set_errno(errcode,
1700 "pthread_mutex_lock");
1701 view->search_next(view);
1702 return NULL;
1705 /* Allow threads to make progress while we are waiting for input. */
1706 errcode = pthread_mutex_unlock(&tog_mutex);
1707 if (errcode)
1708 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1710 if (using_mock_io) {
1711 err = tog_read_script_key(tog_io.f, view, &ch, done);
1712 if (err) {
1713 errcode = pthread_mutex_lock(&tog_mutex);
1714 return err;
1716 } else if (view->count && --view->count) {
1717 cbreak();
1718 nodelay(view->window, TRUE);
1719 ch = wgetch(view->window);
1720 /* let C-g or backspace abort unfinished count */
1721 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1722 view->count = 0;
1723 else
1724 ch = view->ch;
1725 } else {
1726 ch = wgetch(view->window);
1727 if (ch >= '1' && ch <= '9')
1728 view->ch = ch = get_compound_key(view, ch);
1730 if (view->hiline && ch != ERR && ch != 0)
1731 view->hiline = 0; /* key pressed, clear line highlight */
1732 nodelay(view->window, TRUE);
1733 errcode = pthread_mutex_lock(&tog_mutex);
1734 if (errcode)
1735 return got_error_set_errno(errcode, "pthread_mutex_lock");
1737 if (tog_sigwinch_received || tog_sigcont_received) {
1738 tog_resizeterm();
1739 tog_sigwinch_received = 0;
1740 tog_sigcont_received = 0;
1741 TAILQ_FOREACH(v, views, entry) {
1742 err = view_resize(v);
1743 if (err)
1744 return err;
1745 err = v->input(new, v, KEY_RESIZE);
1746 if (err)
1747 return err;
1748 if (v->child) {
1749 err = view_resize(v->child);
1750 if (err)
1751 return err;
1752 err = v->child->input(new, v->child,
1753 KEY_RESIZE);
1754 if (err)
1755 return err;
1756 if (v->child->resized_x || v->child->resized_y) {
1757 err = view_resize_split(v, 0);
1758 if (err)
1759 return err;
1765 switch (ch) {
1766 case '?':
1767 case 'H':
1768 case KEY_F(1):
1769 if (view->type == TOG_VIEW_HELP)
1770 err = view->reset(view);
1771 else
1772 err = view_request_new(new, view, TOG_VIEW_HELP);
1773 break;
1774 case '\t':
1775 view->count = 0;
1776 if (view->child) {
1777 view->focussed = 0;
1778 view->child->focussed = 1;
1779 view->focus_child = 1;
1780 } else if (view->parent) {
1781 view->focussed = 0;
1782 view->parent->focussed = 1;
1783 view->parent->focus_child = 0;
1784 if (!view_is_splitscreen(view)) {
1785 if (view->parent->resize) {
1786 err = view->parent->resize(view->parent,
1787 0);
1788 if (err)
1789 return err;
1791 offset_selection_up(view->parent);
1792 err = view_fullscreen(view->parent);
1793 if (err)
1794 return err;
1797 break;
1798 case 'q':
1799 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1800 if (view->parent->resize) {
1801 /* might need more commits to fill fullscreen */
1802 err = view->parent->resize(view->parent, 0);
1803 if (err)
1804 break;
1806 offset_selection_up(view->parent);
1808 err = view->input(new, view, ch);
1809 view->dying = 1;
1810 break;
1811 case 'Q':
1812 *done = 1;
1813 break;
1814 case 'F':
1815 view->count = 0;
1816 if (view_is_parent_view(view)) {
1817 if (view->child == NULL)
1818 break;
1819 if (view_is_splitscreen(view->child)) {
1820 view->focussed = 0;
1821 view->child->focussed = 1;
1822 err = view_fullscreen(view->child);
1823 } else {
1824 err = view_splitscreen(view->child);
1825 if (!err)
1826 err = view_resize_split(view, 0);
1828 if (err)
1829 break;
1830 err = view->child->input(new, view->child,
1831 KEY_RESIZE);
1832 } else {
1833 if (view_is_splitscreen(view)) {
1834 view->parent->focussed = 0;
1835 view->focussed = 1;
1836 err = view_fullscreen(view);
1837 } else {
1838 err = view_splitscreen(view);
1839 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1840 err = view_resize(view->parent);
1841 if (!err)
1842 err = view_resize_split(view, 0);
1844 if (err)
1845 break;
1846 err = view->input(new, view, KEY_RESIZE);
1848 if (err)
1849 break;
1850 if (view->resize) {
1851 err = view->resize(view, 0);
1852 if (err)
1853 break;
1855 if (view->parent) {
1856 if (view->parent->resize) {
1857 err = view->parent->resize(view->parent, 0);
1858 if (err != NULL)
1859 break;
1861 err = offset_selection_down(view->parent);
1862 if (err != NULL)
1863 break;
1865 err = offset_selection_down(view);
1866 break;
1867 case 'S':
1868 view->count = 0;
1869 err = switch_split(view);
1870 break;
1871 case '-':
1872 err = view_resize_split(view, -1);
1873 break;
1874 case '+':
1875 err = view_resize_split(view, 1);
1876 break;
1877 case KEY_RESIZE:
1878 break;
1879 case '/':
1880 view->count = 0;
1881 if (view->search_start)
1882 view_search_start(view, fast_refresh);
1883 else
1884 err = view->input(new, view, ch);
1885 break;
1886 case 'N':
1887 case 'n':
1888 if (view->search_started && view->search_next) {
1889 view->searching = (ch == 'n' ?
1890 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1891 view->search_next_done = 0;
1892 view->search_next(view);
1893 } else
1894 err = view->input(new, view, ch);
1895 break;
1896 case 'A':
1897 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1898 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1899 view->action = "Patience diff algorithm";
1900 } else {
1901 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1902 view->action = "Myers diff algorithm";
1904 TAILQ_FOREACH(v, views, entry) {
1905 if (v->reset) {
1906 err = v->reset(v);
1907 if (err)
1908 return err;
1910 if (v->child && v->child->reset) {
1911 err = v->child->reset(v->child);
1912 if (err)
1913 return err;
1916 break;
1917 case TOG_KEY_SCRDUMP:
1918 err = screendump(view);
1919 break;
1920 default:
1921 err = view->input(new, view, ch);
1922 break;
1925 return err;
1928 static int
1929 view_needs_focus_indication(struct tog_view *view)
1931 if (view_is_parent_view(view)) {
1932 if (view->child == NULL || view->child->focussed)
1933 return 0;
1934 if (!view_is_splitscreen(view->child))
1935 return 0;
1936 } else if (!view_is_splitscreen(view))
1937 return 0;
1939 return view->focussed;
1942 static const struct got_error *
1943 tog_io_close(void)
1945 const struct got_error *err = NULL;
1947 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1948 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1949 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1950 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1951 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1952 err = got_ferror(tog_io.f, GOT_ERR_IO);
1953 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1954 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1956 return err;
1959 static const struct got_error *
1960 view_loop(struct tog_view *view)
1962 const struct got_error *err = NULL;
1963 struct tog_view_list_head views;
1964 struct tog_view *new_view;
1965 char *mode;
1966 int fast_refresh = 10;
1967 int done = 0, errcode;
1969 mode = getenv("TOG_VIEW_SPLIT_MODE");
1970 if (!mode || !(*mode == 'h' || *mode == 'H'))
1971 view->mode = TOG_VIEW_SPLIT_VERT;
1972 else
1973 view->mode = TOG_VIEW_SPLIT_HRZN;
1975 errcode = pthread_mutex_lock(&tog_mutex);
1976 if (errcode)
1977 return got_error_set_errno(errcode, "pthread_mutex_lock");
1979 TAILQ_INIT(&views);
1980 TAILQ_INSERT_HEAD(&views, view, entry);
1982 view->focussed = 1;
1983 err = view->show(view);
1984 if (err)
1985 return err;
1986 update_panels();
1987 doupdate();
1988 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1989 !tog_fatal_signal_received()) {
1990 /* Refresh fast during initialization, then become slower. */
1991 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1992 halfdelay(10); /* switch to once per second */
1994 err = view_input(&new_view, &done, view, &views, fast_refresh);
1995 if (err)
1996 break;
1998 if (view->dying && view == TAILQ_FIRST(&views) &&
1999 TAILQ_NEXT(view, entry) == NULL)
2000 done = 1;
2001 if (done) {
2002 struct tog_view *v;
2005 * When we quit, scroll the screen up a single line
2006 * so we don't lose any information.
2008 TAILQ_FOREACH(v, &views, entry) {
2009 wmove(v->window, 0, 0);
2010 wdeleteln(v->window);
2011 wnoutrefresh(v->window);
2012 if (v->child && !view_is_fullscreen(v)) {
2013 wmove(v->child->window, 0, 0);
2014 wdeleteln(v->child->window);
2015 wnoutrefresh(v->child->window);
2018 doupdate();
2021 if (view->dying) {
2022 struct tog_view *v, *prev = NULL;
2024 if (view_is_parent_view(view))
2025 prev = TAILQ_PREV(view, tog_view_list_head,
2026 entry);
2027 else if (view->parent)
2028 prev = view->parent;
2030 if (view->parent) {
2031 view->parent->child = NULL;
2032 view->parent->focus_child = 0;
2033 /* Restore fullscreen line height. */
2034 view->parent->nlines = view->parent->lines;
2035 err = view_resize(view->parent);
2036 if (err)
2037 break;
2038 /* Make resized splits persist. */
2039 view_transfer_size(view->parent, view);
2040 } else
2041 TAILQ_REMOVE(&views, view, entry);
2043 err = view_close(view);
2044 if (err)
2045 goto done;
2047 view = NULL;
2048 TAILQ_FOREACH(v, &views, entry) {
2049 if (v->focussed)
2050 break;
2052 if (view == NULL && new_view == NULL) {
2053 /* No view has focus. Try to pick one. */
2054 if (prev)
2055 view = prev;
2056 else if (!TAILQ_EMPTY(&views)) {
2057 view = TAILQ_LAST(&views,
2058 tog_view_list_head);
2060 if (view) {
2061 if (view->focus_child) {
2062 view->child->focussed = 1;
2063 view = view->child;
2064 } else
2065 view->focussed = 1;
2069 if (new_view) {
2070 struct tog_view *v, *t;
2071 /* Only allow one parent view per type. */
2072 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2073 if (v->type != new_view->type)
2074 continue;
2075 TAILQ_REMOVE(&views, v, entry);
2076 err = view_close(v);
2077 if (err)
2078 goto done;
2079 break;
2081 TAILQ_INSERT_TAIL(&views, new_view, entry);
2082 view = new_view;
2084 if (view && !done) {
2085 if (view_is_parent_view(view)) {
2086 if (view->child && view->child->focussed)
2087 view = view->child;
2088 } else {
2089 if (view->parent && view->parent->focussed)
2090 view = view->parent;
2092 show_panel(view->panel);
2093 if (view->child && view_is_splitscreen(view->child))
2094 show_panel(view->child->panel);
2095 if (view->parent && view_is_splitscreen(view)) {
2096 err = view->parent->show(view->parent);
2097 if (err)
2098 goto done;
2100 err = view->show(view);
2101 if (err)
2102 goto done;
2103 if (view->child) {
2104 err = view->child->show(view->child);
2105 if (err)
2106 goto done;
2108 update_panels();
2109 doupdate();
2112 done:
2113 while (!TAILQ_EMPTY(&views)) {
2114 const struct got_error *close_err;
2115 view = TAILQ_FIRST(&views);
2116 TAILQ_REMOVE(&views, view, entry);
2117 close_err = view_close(view);
2118 if (close_err && err == NULL)
2119 err = close_err;
2122 errcode = pthread_mutex_unlock(&tog_mutex);
2123 if (errcode && err == NULL)
2124 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2126 return err;
2129 __dead static void
2130 usage_log(void)
2132 endwin();
2133 fprintf(stderr,
2134 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2135 getprogname());
2136 exit(1);
2139 /* Create newly allocated wide-character string equivalent to a byte string. */
2140 static const struct got_error *
2141 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2143 char *vis = NULL;
2144 const struct got_error *err = NULL;
2146 *ws = NULL;
2147 *wlen = mbstowcs(NULL, s, 0);
2148 if (*wlen == (size_t)-1) {
2149 int vislen;
2150 if (errno != EILSEQ)
2151 return got_error_from_errno("mbstowcs");
2153 /* byte string invalid in current encoding; try to "fix" it */
2154 err = got_mbsavis(&vis, &vislen, s);
2155 if (err)
2156 return err;
2157 *wlen = mbstowcs(NULL, vis, 0);
2158 if (*wlen == (size_t)-1) {
2159 err = got_error_from_errno("mbstowcs"); /* give up */
2160 goto done;
2164 *ws = calloc(*wlen + 1, sizeof(**ws));
2165 if (*ws == NULL) {
2166 err = got_error_from_errno("calloc");
2167 goto done;
2170 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2171 err = got_error_from_errno("mbstowcs");
2172 done:
2173 free(vis);
2174 if (err) {
2175 free(*ws);
2176 *ws = NULL;
2177 *wlen = 0;
2179 return err;
2182 static const struct got_error *
2183 expand_tab(char **ptr, const char *src)
2185 char *dst;
2186 size_t len, n, idx = 0, sz = 0;
2188 *ptr = NULL;
2189 n = len = strlen(src);
2190 dst = malloc(n + 1);
2191 if (dst == NULL)
2192 return got_error_from_errno("malloc");
2194 while (idx < len && src[idx]) {
2195 const char c = src[idx];
2197 if (c == '\t') {
2198 size_t nb = TABSIZE - sz % TABSIZE;
2199 char *p;
2201 p = realloc(dst, n + nb);
2202 if (p == NULL) {
2203 free(dst);
2204 return got_error_from_errno("realloc");
2207 dst = p;
2208 n += nb;
2209 memset(dst + sz, ' ', nb);
2210 sz += nb;
2211 } else
2212 dst[sz++] = src[idx];
2213 ++idx;
2216 dst[sz] = '\0';
2217 *ptr = dst;
2218 return NULL;
2222 * Advance at most n columns from wline starting at offset off.
2223 * Return the index to the first character after the span operation.
2224 * Return the combined column width of all spanned wide character in
2225 * *rcol.
2227 static int
2228 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2230 int width, i, cols = 0;
2232 if (n == 0) {
2233 *rcol = cols;
2234 return off;
2237 for (i = off; wline[i] != L'\0'; ++i) {
2238 if (wline[i] == L'\t')
2239 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2240 else
2241 width = wcwidth(wline[i]);
2243 if (width == -1) {
2244 width = 1;
2245 wline[i] = L'.';
2248 if (cols + width > n)
2249 break;
2250 cols += width;
2253 *rcol = cols;
2254 return i;
2258 * Format a line for display, ensuring that it won't overflow a width limit.
2259 * With scrolling, the width returned refers to the scrolled version of the
2260 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2262 static const struct got_error *
2263 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2264 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2266 const struct got_error *err = NULL;
2267 int cols;
2268 wchar_t *wline = NULL;
2269 char *exstr = NULL;
2270 size_t wlen;
2271 int i, scrollx;
2273 *wlinep = NULL;
2274 *widthp = 0;
2276 if (expand) {
2277 err = expand_tab(&exstr, line);
2278 if (err)
2279 return err;
2282 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2283 free(exstr);
2284 if (err)
2285 return err;
2287 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2289 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2290 wline[wlen - 1] = L'\0';
2291 wlen--;
2293 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2294 wline[wlen - 1] = L'\0';
2295 wlen--;
2298 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2299 wline[i] = L'\0';
2301 if (widthp)
2302 *widthp = cols;
2303 if (scrollxp)
2304 *scrollxp = scrollx;
2305 if (err)
2306 free(wline);
2307 else
2308 *wlinep = wline;
2309 return err;
2312 static const struct got_error*
2313 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2314 struct got_object_id *id, struct got_repository *repo)
2316 static const struct got_error *err = NULL;
2317 struct got_reflist_entry *re;
2318 char *s;
2319 const char *name;
2321 *refs_str = NULL;
2323 TAILQ_FOREACH(re, refs, entry) {
2324 struct got_tag_object *tag = NULL;
2325 struct got_object_id *ref_id;
2326 int cmp;
2328 name = got_ref_get_name(re->ref);
2329 if (strcmp(name, GOT_REF_HEAD) == 0)
2330 continue;
2331 if (strncmp(name, "refs/", 5) == 0)
2332 name += 5;
2333 if (strncmp(name, "got/", 4) == 0 &&
2334 strncmp(name, "got/backup/", 11) != 0)
2335 continue;
2336 if (strncmp(name, "heads/", 6) == 0)
2337 name += 6;
2338 if (strncmp(name, "remotes/", 8) == 0) {
2339 name += 8;
2340 s = strstr(name, "/" GOT_REF_HEAD);
2341 if (s != NULL && s[strlen(s)] == '\0')
2342 continue;
2344 err = got_ref_resolve(&ref_id, repo, re->ref);
2345 if (err)
2346 break;
2347 if (strncmp(name, "tags/", 5) == 0) {
2348 err = got_object_open_as_tag(&tag, repo, ref_id);
2349 if (err) {
2350 if (err->code != GOT_ERR_OBJ_TYPE) {
2351 free(ref_id);
2352 break;
2354 /* Ref points at something other than a tag. */
2355 err = NULL;
2356 tag = NULL;
2359 cmp = got_object_id_cmp(tag ?
2360 got_object_tag_get_object_id(tag) : ref_id, id);
2361 free(ref_id);
2362 if (tag)
2363 got_object_tag_close(tag);
2364 if (cmp != 0)
2365 continue;
2366 s = *refs_str;
2367 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2368 s ? ", " : "", name) == -1) {
2369 err = got_error_from_errno("asprintf");
2370 free(s);
2371 *refs_str = NULL;
2372 break;
2374 free(s);
2377 return err;
2380 static const struct got_error *
2381 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2382 int col_tab_align)
2384 char *smallerthan;
2386 smallerthan = strchr(author, '<');
2387 if (smallerthan && smallerthan[1] != '\0')
2388 author = smallerthan + 1;
2389 author[strcspn(author, "@>")] = '\0';
2390 return format_line(wauthor, author_width, NULL, author, 0, limit,
2391 col_tab_align, 0);
2394 static const struct got_error *
2395 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2396 struct got_object_id *id, const size_t date_display_cols,
2397 int author_display_cols)
2399 struct tog_log_view_state *s = &view->state.log;
2400 const struct got_error *err = NULL;
2401 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2402 char *logmsg0 = NULL, *logmsg = NULL;
2403 char *author = NULL;
2404 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2405 int author_width, logmsg_width;
2406 char *newline, *line = NULL;
2407 int col, limit, scrollx;
2408 const int avail = view->ncols;
2409 struct tm tm;
2410 time_t committer_time;
2411 struct tog_color *tc;
2413 committer_time = got_object_commit_get_committer_time(commit);
2414 if (gmtime_r(&committer_time, &tm) == NULL)
2415 return got_error_from_errno("gmtime_r");
2416 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2417 return got_error(GOT_ERR_NO_SPACE);
2419 if (avail <= date_display_cols)
2420 limit = MIN(sizeof(datebuf) - 1, avail);
2421 else
2422 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2423 tc = get_color(&s->colors, TOG_COLOR_DATE);
2424 if (tc)
2425 wattr_on(view->window,
2426 COLOR_PAIR(tc->colorpair), NULL);
2427 waddnstr(view->window, datebuf, limit);
2428 if (tc)
2429 wattr_off(view->window,
2430 COLOR_PAIR(tc->colorpair), NULL);
2431 col = limit;
2432 if (col > avail)
2433 goto done;
2435 if (avail >= 120) {
2436 char *id_str;
2437 err = got_object_id_str(&id_str, id);
2438 if (err)
2439 goto done;
2440 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2441 if (tc)
2442 wattr_on(view->window,
2443 COLOR_PAIR(tc->colorpair), NULL);
2444 wprintw(view->window, "%.8s ", id_str);
2445 if (tc)
2446 wattr_off(view->window,
2447 COLOR_PAIR(tc->colorpair), NULL);
2448 free(id_str);
2449 col += 9;
2450 if (col > avail)
2451 goto done;
2454 if (s->use_committer)
2455 author = strdup(got_object_commit_get_committer(commit));
2456 else
2457 author = strdup(got_object_commit_get_author(commit));
2458 if (author == NULL) {
2459 err = got_error_from_errno("strdup");
2460 goto done;
2462 err = format_author(&wauthor, &author_width, author, avail - col, col);
2463 if (err)
2464 goto done;
2465 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2466 if (tc)
2467 wattr_on(view->window,
2468 COLOR_PAIR(tc->colorpair), NULL);
2469 waddwstr(view->window, wauthor);
2470 col += author_width;
2471 while (col < avail && author_width < author_display_cols + 2) {
2472 waddch(view->window, ' ');
2473 col++;
2474 author_width++;
2476 if (tc)
2477 wattr_off(view->window,
2478 COLOR_PAIR(tc->colorpair), NULL);
2479 if (col > avail)
2480 goto done;
2482 err = got_object_commit_get_logmsg(&logmsg0, commit);
2483 if (err)
2484 goto done;
2485 logmsg = logmsg0;
2486 while (*logmsg == '\n')
2487 logmsg++;
2488 newline = strchr(logmsg, '\n');
2489 if (newline)
2490 *newline = '\0';
2491 limit = avail - col;
2492 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2493 limit--; /* for the border */
2494 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2495 limit, col, 1);
2496 if (err)
2497 goto done;
2498 waddwstr(view->window, &wlogmsg[scrollx]);
2499 col += MAX(logmsg_width, 0);
2500 while (col < avail) {
2501 waddch(view->window, ' ');
2502 col++;
2504 done:
2505 free(logmsg0);
2506 free(wlogmsg);
2507 free(author);
2508 free(wauthor);
2509 free(line);
2510 return err;
2513 static struct commit_queue_entry *
2514 alloc_commit_queue_entry(struct got_commit_object *commit,
2515 struct got_object_id *id)
2517 struct commit_queue_entry *entry;
2518 struct got_object_id *dup;
2520 entry = calloc(1, sizeof(*entry));
2521 if (entry == NULL)
2522 return NULL;
2524 dup = got_object_id_dup(id);
2525 if (dup == NULL) {
2526 free(entry);
2527 return NULL;
2530 entry->id = dup;
2531 entry->commit = commit;
2532 return entry;
2535 static void
2536 pop_commit(struct commit_queue *commits)
2538 struct commit_queue_entry *entry;
2540 entry = TAILQ_FIRST(&commits->head);
2541 TAILQ_REMOVE(&commits->head, entry, entry);
2542 got_object_commit_close(entry->commit);
2543 commits->ncommits--;
2544 free(entry->id);
2545 free(entry);
2548 static void
2549 free_commits(struct commit_queue *commits)
2551 while (!TAILQ_EMPTY(&commits->head))
2552 pop_commit(commits);
2555 static const struct got_error *
2556 match_commit(int *have_match, struct got_object_id *id,
2557 struct got_commit_object *commit, regex_t *regex)
2559 const struct got_error *err = NULL;
2560 regmatch_t regmatch;
2561 char *id_str = NULL, *logmsg = NULL;
2563 *have_match = 0;
2565 err = got_object_id_str(&id_str, id);
2566 if (err)
2567 return err;
2569 err = got_object_commit_get_logmsg(&logmsg, commit);
2570 if (err)
2571 goto done;
2573 if (regexec(regex, got_object_commit_get_author(commit), 1,
2574 &regmatch, 0) == 0 ||
2575 regexec(regex, got_object_commit_get_committer(commit), 1,
2576 &regmatch, 0) == 0 ||
2577 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2578 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2579 *have_match = 1;
2580 done:
2581 free(id_str);
2582 free(logmsg);
2583 return err;
2586 static const struct got_error *
2587 queue_commits(struct tog_log_thread_args *a)
2589 const struct got_error *err = NULL;
2592 * We keep all commits open throughout the lifetime of the log
2593 * view in order to avoid having to re-fetch commits from disk
2594 * while updating the display.
2596 do {
2597 struct got_object_id id;
2598 struct got_commit_object *commit;
2599 struct commit_queue_entry *entry;
2600 int limit_match = 0;
2601 int errcode;
2603 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2604 NULL, NULL);
2605 if (err)
2606 break;
2608 err = got_object_open_as_commit(&commit, a->repo, &id);
2609 if (err)
2610 break;
2611 entry = alloc_commit_queue_entry(commit, &id);
2612 if (entry == NULL) {
2613 err = got_error_from_errno("alloc_commit_queue_entry");
2614 break;
2617 errcode = pthread_mutex_lock(&tog_mutex);
2618 if (errcode) {
2619 err = got_error_set_errno(errcode,
2620 "pthread_mutex_lock");
2621 break;
2624 entry->idx = a->real_commits->ncommits;
2625 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2626 a->real_commits->ncommits++;
2628 if (*a->limiting) {
2629 err = match_commit(&limit_match, &id, commit,
2630 a->limit_regex);
2631 if (err)
2632 break;
2634 if (limit_match) {
2635 struct commit_queue_entry *matched;
2637 matched = alloc_commit_queue_entry(
2638 entry->commit, entry->id);
2639 if (matched == NULL) {
2640 err = got_error_from_errno(
2641 "alloc_commit_queue_entry");
2642 break;
2644 matched->commit = entry->commit;
2645 got_object_commit_retain(entry->commit);
2647 matched->idx = a->limit_commits->ncommits;
2648 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2649 matched, entry);
2650 a->limit_commits->ncommits++;
2654 * This is how we signal log_thread() that we
2655 * have found a match, and that it should be
2656 * counted as a new entry for the view.
2658 a->limit_match = limit_match;
2661 if (*a->searching == TOG_SEARCH_FORWARD &&
2662 !*a->search_next_done) {
2663 int have_match;
2664 err = match_commit(&have_match, &id, commit, a->regex);
2665 if (err)
2666 break;
2668 if (*a->limiting) {
2669 if (limit_match && have_match)
2670 *a->search_next_done =
2671 TOG_SEARCH_HAVE_MORE;
2672 } else if (have_match)
2673 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2676 errcode = pthread_mutex_unlock(&tog_mutex);
2677 if (errcode && err == NULL)
2678 err = got_error_set_errno(errcode,
2679 "pthread_mutex_unlock");
2680 if (err)
2681 break;
2682 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2684 return err;
2687 static void
2688 select_commit(struct tog_log_view_state *s)
2690 struct commit_queue_entry *entry;
2691 int ncommits = 0;
2693 entry = s->first_displayed_entry;
2694 while (entry) {
2695 if (ncommits == s->selected) {
2696 s->selected_entry = entry;
2697 break;
2699 entry = TAILQ_NEXT(entry, entry);
2700 ncommits++;
2704 static const struct got_error *
2705 draw_commits(struct tog_view *view)
2707 const struct got_error *err = NULL;
2708 struct tog_log_view_state *s = &view->state.log;
2709 struct commit_queue_entry *entry = s->selected_entry;
2710 int limit = view->nlines;
2711 int width;
2712 int ncommits, author_cols = 4;
2713 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2714 char *refs_str = NULL;
2715 wchar_t *wline;
2716 struct tog_color *tc;
2717 static const size_t date_display_cols = 12;
2719 if (view_is_hsplit_top(view))
2720 --limit; /* account for border */
2722 if (s->selected_entry &&
2723 !(view->searching && view->search_next_done == 0)) {
2724 struct got_reflist_head *refs;
2725 err = got_object_id_str(&id_str, s->selected_entry->id);
2726 if (err)
2727 return err;
2728 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2729 s->selected_entry->id);
2730 if (refs) {
2731 err = build_refs_str(&refs_str, refs,
2732 s->selected_entry->id, s->repo);
2733 if (err)
2734 goto done;
2738 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2739 halfdelay(10); /* disable fast refresh */
2741 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2742 if (asprintf(&ncommits_str, " [%d/%d] %s",
2743 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2744 (view->searching && !view->search_next_done) ?
2745 "searching..." : "loading...") == -1) {
2746 err = got_error_from_errno("asprintf");
2747 goto done;
2749 } else {
2750 const char *search_str = NULL;
2751 const char *limit_str = NULL;
2753 if (view->searching) {
2754 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2755 search_str = "no more matches";
2756 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2757 search_str = "no matches found";
2758 else if (!view->search_next_done)
2759 search_str = "searching...";
2762 if (s->limit_view && s->commits->ncommits == 0)
2763 limit_str = "no matches found";
2765 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2766 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2767 search_str ? search_str : (refs_str ? refs_str : ""),
2768 limit_str ? limit_str : "") == -1) {
2769 err = got_error_from_errno("asprintf");
2770 goto done;
2774 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2775 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2776 "........................................",
2777 s->in_repo_path, ncommits_str) == -1) {
2778 err = got_error_from_errno("asprintf");
2779 header = NULL;
2780 goto done;
2782 } else if (asprintf(&header, "commit %s%s",
2783 id_str ? id_str : "........................................",
2784 ncommits_str) == -1) {
2785 err = got_error_from_errno("asprintf");
2786 header = NULL;
2787 goto done;
2789 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2790 if (err)
2791 goto done;
2793 werase(view->window);
2795 if (view_needs_focus_indication(view))
2796 wstandout(view->window);
2797 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2798 if (tc)
2799 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2800 waddwstr(view->window, wline);
2801 while (width < view->ncols) {
2802 waddch(view->window, ' ');
2803 width++;
2805 if (tc)
2806 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2807 if (view_needs_focus_indication(view))
2808 wstandend(view->window);
2809 free(wline);
2810 if (limit <= 1)
2811 goto done;
2813 /* Grow author column size if necessary, and set view->maxx. */
2814 entry = s->first_displayed_entry;
2815 ncommits = 0;
2816 view->maxx = 0;
2817 while (entry) {
2818 struct got_commit_object *c = entry->commit;
2819 char *author, *eol, *msg, *msg0;
2820 wchar_t *wauthor, *wmsg;
2821 int width;
2822 if (ncommits >= limit - 1)
2823 break;
2824 if (s->use_committer)
2825 author = strdup(got_object_commit_get_committer(c));
2826 else
2827 author = strdup(got_object_commit_get_author(c));
2828 if (author == NULL) {
2829 err = got_error_from_errno("strdup");
2830 goto done;
2832 err = format_author(&wauthor, &width, author, COLS,
2833 date_display_cols);
2834 if (author_cols < width)
2835 author_cols = width;
2836 free(wauthor);
2837 free(author);
2838 if (err)
2839 goto done;
2840 err = got_object_commit_get_logmsg(&msg0, c);
2841 if (err)
2842 goto done;
2843 msg = msg0;
2844 while (*msg == '\n')
2845 ++msg;
2846 if ((eol = strchr(msg, '\n')))
2847 *eol = '\0';
2848 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2849 date_display_cols + author_cols, 0);
2850 if (err)
2851 goto done;
2852 view->maxx = MAX(view->maxx, width);
2853 free(msg0);
2854 free(wmsg);
2855 ncommits++;
2856 entry = TAILQ_NEXT(entry, entry);
2859 entry = s->first_displayed_entry;
2860 s->last_displayed_entry = s->first_displayed_entry;
2861 ncommits = 0;
2862 while (entry) {
2863 if (ncommits >= limit - 1)
2864 break;
2865 if (ncommits == s->selected)
2866 wstandout(view->window);
2867 err = draw_commit(view, entry->commit, entry->id,
2868 date_display_cols, author_cols);
2869 if (ncommits == s->selected)
2870 wstandend(view->window);
2871 if (err)
2872 goto done;
2873 ncommits++;
2874 s->last_displayed_entry = entry;
2875 entry = TAILQ_NEXT(entry, entry);
2878 view_border(view);
2879 done:
2880 free(id_str);
2881 free(refs_str);
2882 free(ncommits_str);
2883 free(header);
2884 return err;
2887 static void
2888 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2890 struct commit_queue_entry *entry;
2891 int nscrolled = 0;
2893 entry = TAILQ_FIRST(&s->commits->head);
2894 if (s->first_displayed_entry == entry)
2895 return;
2897 entry = s->first_displayed_entry;
2898 while (entry && nscrolled < maxscroll) {
2899 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2900 if (entry) {
2901 s->first_displayed_entry = entry;
2902 nscrolled++;
2907 static const struct got_error *
2908 trigger_log_thread(struct tog_view *view, int wait)
2910 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2911 int errcode;
2913 if (!using_mock_io)
2914 halfdelay(1); /* fast refresh while loading commits */
2916 while (!ta->log_complete && !tog_thread_error &&
2917 (ta->commits_needed > 0 || ta->load_all)) {
2918 /* Wake the log thread. */
2919 errcode = pthread_cond_signal(&ta->need_commits);
2920 if (errcode)
2921 return got_error_set_errno(errcode,
2922 "pthread_cond_signal");
2925 * The mutex will be released while the view loop waits
2926 * in wgetch(), at which time the log thread will run.
2928 if (!wait)
2929 break;
2931 /* Display progress update in log view. */
2932 show_log_view(view);
2933 update_panels();
2934 doupdate();
2936 /* Wait right here while next commit is being loaded. */
2937 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2938 if (errcode)
2939 return got_error_set_errno(errcode,
2940 "pthread_cond_wait");
2942 /* Display progress update in log view. */
2943 show_log_view(view);
2944 update_panels();
2945 doupdate();
2948 return NULL;
2951 static const struct got_error *
2952 request_log_commits(struct tog_view *view)
2954 struct tog_log_view_state *state = &view->state.log;
2955 const struct got_error *err = NULL;
2957 if (state->thread_args.log_complete)
2958 return NULL;
2960 state->thread_args.commits_needed += view->nscrolled;
2961 err = trigger_log_thread(view, 1);
2962 view->nscrolled = 0;
2964 return err;
2967 static const struct got_error *
2968 log_scroll_down(struct tog_view *view, int maxscroll)
2970 struct tog_log_view_state *s = &view->state.log;
2971 const struct got_error *err = NULL;
2972 struct commit_queue_entry *pentry;
2973 int nscrolled = 0, ncommits_needed;
2975 if (s->last_displayed_entry == NULL)
2976 return NULL;
2978 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2979 if (s->commits->ncommits < ncommits_needed &&
2980 !s->thread_args.log_complete) {
2982 * Ask the log thread for required amount of commits.
2984 s->thread_args.commits_needed +=
2985 ncommits_needed - s->commits->ncommits;
2986 err = trigger_log_thread(view, 1);
2987 if (err)
2988 return err;
2991 do {
2992 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2993 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2994 break;
2996 s->last_displayed_entry = pentry ?
2997 pentry : s->last_displayed_entry;
2999 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3000 if (pentry == NULL)
3001 break;
3002 s->first_displayed_entry = pentry;
3003 } while (++nscrolled < maxscroll);
3005 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3006 view->nscrolled += nscrolled;
3007 else
3008 view->nscrolled = 0;
3010 return err;
3013 static const struct got_error *
3014 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3015 struct got_commit_object *commit, struct got_object_id *commit_id,
3016 struct tog_view *log_view, struct got_repository *repo)
3018 const struct got_error *err;
3019 struct got_object_qid *parent_id;
3020 struct tog_view *diff_view;
3022 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3023 if (diff_view == NULL)
3024 return got_error_from_errno("view_open");
3026 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3027 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3028 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3029 if (err == NULL)
3030 *new_view = diff_view;
3031 return err;
3034 static const struct got_error *
3035 tree_view_visit_subtree(struct tog_tree_view_state *s,
3036 struct got_tree_object *subtree)
3038 struct tog_parent_tree *parent;
3040 parent = calloc(1, sizeof(*parent));
3041 if (parent == NULL)
3042 return got_error_from_errno("calloc");
3044 parent->tree = s->tree;
3045 parent->first_displayed_entry = s->first_displayed_entry;
3046 parent->selected_entry = s->selected_entry;
3047 parent->selected = s->selected;
3048 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3049 s->tree = subtree;
3050 s->selected = 0;
3051 s->first_displayed_entry = NULL;
3052 return NULL;
3055 static const struct got_error *
3056 tree_view_walk_path(struct tog_tree_view_state *s,
3057 struct got_commit_object *commit, const char *path)
3059 const struct got_error *err = NULL;
3060 struct got_tree_object *tree = NULL;
3061 const char *p;
3062 char *slash, *subpath = NULL;
3064 /* Walk the path and open corresponding tree objects. */
3065 p = path;
3066 while (*p) {
3067 struct got_tree_entry *te;
3068 struct got_object_id *tree_id;
3069 char *te_name;
3071 while (p[0] == '/')
3072 p++;
3074 /* Ensure the correct subtree entry is selected. */
3075 slash = strchr(p, '/');
3076 if (slash == NULL)
3077 te_name = strdup(p);
3078 else
3079 te_name = strndup(p, slash - p);
3080 if (te_name == NULL) {
3081 err = got_error_from_errno("strndup");
3082 break;
3084 te = got_object_tree_find_entry(s->tree, te_name);
3085 if (te == NULL) {
3086 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3087 free(te_name);
3088 break;
3090 free(te_name);
3091 s->first_displayed_entry = s->selected_entry = te;
3093 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3094 break; /* jump to this file's entry */
3096 slash = strchr(p, '/');
3097 if (slash)
3098 subpath = strndup(path, slash - path);
3099 else
3100 subpath = strdup(path);
3101 if (subpath == NULL) {
3102 err = got_error_from_errno("strdup");
3103 break;
3106 err = got_object_id_by_path(&tree_id, s->repo, commit,
3107 subpath);
3108 if (err)
3109 break;
3111 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3112 free(tree_id);
3113 if (err)
3114 break;
3116 err = tree_view_visit_subtree(s, tree);
3117 if (err) {
3118 got_object_tree_close(tree);
3119 break;
3121 if (slash == NULL)
3122 break;
3123 free(subpath);
3124 subpath = NULL;
3125 p = slash;
3128 free(subpath);
3129 return err;
3132 static const struct got_error *
3133 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3134 struct commit_queue_entry *entry, const char *path,
3135 const char *head_ref_name, struct got_repository *repo)
3137 const struct got_error *err = NULL;
3138 struct tog_tree_view_state *s;
3139 struct tog_view *tree_view;
3141 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3142 if (tree_view == NULL)
3143 return got_error_from_errno("view_open");
3145 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3146 if (err)
3147 return err;
3148 s = &tree_view->state.tree;
3150 *new_view = tree_view;
3152 if (got_path_is_root_dir(path))
3153 return NULL;
3155 return tree_view_walk_path(s, entry->commit, path);
3158 static const struct got_error *
3159 block_signals_used_by_main_thread(void)
3161 sigset_t sigset;
3162 int errcode;
3164 if (sigemptyset(&sigset) == -1)
3165 return got_error_from_errno("sigemptyset");
3167 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3168 if (sigaddset(&sigset, SIGWINCH) == -1)
3169 return got_error_from_errno("sigaddset");
3170 if (sigaddset(&sigset, SIGCONT) == -1)
3171 return got_error_from_errno("sigaddset");
3172 if (sigaddset(&sigset, SIGINT) == -1)
3173 return got_error_from_errno("sigaddset");
3174 if (sigaddset(&sigset, SIGTERM) == -1)
3175 return got_error_from_errno("sigaddset");
3177 /* ncurses handles SIGTSTP */
3178 if (sigaddset(&sigset, SIGTSTP) == -1)
3179 return got_error_from_errno("sigaddset");
3181 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3182 if (errcode)
3183 return got_error_set_errno(errcode, "pthread_sigmask");
3185 return NULL;
3188 static void *
3189 log_thread(void *arg)
3191 const struct got_error *err = NULL;
3192 int errcode = 0;
3193 struct tog_log_thread_args *a = arg;
3194 int done = 0;
3197 * Sync startup with main thread such that we begin our
3198 * work once view_input() has released the mutex.
3200 errcode = pthread_mutex_lock(&tog_mutex);
3201 if (errcode) {
3202 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3203 return (void *)err;
3206 err = block_signals_used_by_main_thread();
3207 if (err) {
3208 pthread_mutex_unlock(&tog_mutex);
3209 goto done;
3212 while (!done && !err && !tog_fatal_signal_received()) {
3213 errcode = pthread_mutex_unlock(&tog_mutex);
3214 if (errcode) {
3215 err = got_error_set_errno(errcode,
3216 "pthread_mutex_unlock");
3217 goto done;
3219 err = queue_commits(a);
3220 if (err) {
3221 if (err->code != GOT_ERR_ITER_COMPLETED)
3222 goto done;
3223 err = NULL;
3224 done = 1;
3225 } else if (a->commits_needed > 0 && !a->load_all) {
3226 if (*a->limiting) {
3227 if (a->limit_match)
3228 a->commits_needed--;
3229 } else
3230 a->commits_needed--;
3233 errcode = pthread_mutex_lock(&tog_mutex);
3234 if (errcode) {
3235 err = got_error_set_errno(errcode,
3236 "pthread_mutex_lock");
3237 goto done;
3238 } else if (*a->quit)
3239 done = 1;
3240 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3241 *a->first_displayed_entry =
3242 TAILQ_FIRST(&a->limit_commits->head);
3243 *a->selected_entry = *a->first_displayed_entry;
3244 } else if (*a->first_displayed_entry == NULL) {
3245 *a->first_displayed_entry =
3246 TAILQ_FIRST(&a->real_commits->head);
3247 *a->selected_entry = *a->first_displayed_entry;
3250 errcode = pthread_cond_signal(&a->commit_loaded);
3251 if (errcode) {
3252 err = got_error_set_errno(errcode,
3253 "pthread_cond_signal");
3254 pthread_mutex_unlock(&tog_mutex);
3255 goto done;
3258 if (done)
3259 a->commits_needed = 0;
3260 else {
3261 if (a->commits_needed == 0 && !a->load_all) {
3262 errcode = pthread_cond_wait(&a->need_commits,
3263 &tog_mutex);
3264 if (errcode) {
3265 err = got_error_set_errno(errcode,
3266 "pthread_cond_wait");
3267 pthread_mutex_unlock(&tog_mutex);
3268 goto done;
3270 if (*a->quit)
3271 done = 1;
3275 a->log_complete = 1;
3276 errcode = pthread_mutex_unlock(&tog_mutex);
3277 if (errcode)
3278 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3279 done:
3280 if (err) {
3281 tog_thread_error = 1;
3282 pthread_cond_signal(&a->commit_loaded);
3284 return (void *)err;
3287 static const struct got_error *
3288 stop_log_thread(struct tog_log_view_state *s)
3290 const struct got_error *err = NULL, *thread_err = NULL;
3291 int errcode;
3293 if (s->thread) {
3294 s->quit = 1;
3295 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3296 if (errcode)
3297 return got_error_set_errno(errcode,
3298 "pthread_cond_signal");
3299 errcode = pthread_mutex_unlock(&tog_mutex);
3300 if (errcode)
3301 return got_error_set_errno(errcode,
3302 "pthread_mutex_unlock");
3303 errcode = pthread_join(s->thread, (void **)&thread_err);
3304 if (errcode)
3305 return got_error_set_errno(errcode, "pthread_join");
3306 errcode = pthread_mutex_lock(&tog_mutex);
3307 if (errcode)
3308 return got_error_set_errno(errcode,
3309 "pthread_mutex_lock");
3310 s->thread = NULL;
3313 if (s->thread_args.repo) {
3314 err = got_repo_close(s->thread_args.repo);
3315 s->thread_args.repo = NULL;
3318 if (s->thread_args.pack_fds) {
3319 const struct got_error *pack_err =
3320 got_repo_pack_fds_close(s->thread_args.pack_fds);
3321 if (err == NULL)
3322 err = pack_err;
3323 s->thread_args.pack_fds = NULL;
3326 if (s->thread_args.graph) {
3327 got_commit_graph_close(s->thread_args.graph);
3328 s->thread_args.graph = NULL;
3331 return err ? err : thread_err;
3334 static const struct got_error *
3335 close_log_view(struct tog_view *view)
3337 const struct got_error *err = NULL;
3338 struct tog_log_view_state *s = &view->state.log;
3339 int errcode;
3341 err = stop_log_thread(s);
3343 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3344 if (errcode && err == NULL)
3345 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3347 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3348 if (errcode && err == NULL)
3349 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3351 free_commits(&s->limit_commits);
3352 free_commits(&s->real_commits);
3353 free(s->in_repo_path);
3354 s->in_repo_path = NULL;
3355 free(s->start_id);
3356 s->start_id = NULL;
3357 free(s->head_ref_name);
3358 s->head_ref_name = NULL;
3359 return err;
3363 * We use two queues to implement the limit feature: first consists of
3364 * commits matching the current limit_regex; second is the real queue
3365 * of all known commits (real_commits). When the user starts limiting,
3366 * we swap queues such that all movement and displaying functionality
3367 * works with very slight change.
3369 static const struct got_error *
3370 limit_log_view(struct tog_view *view)
3372 struct tog_log_view_state *s = &view->state.log;
3373 struct commit_queue_entry *entry;
3374 struct tog_view *v = view;
3375 const struct got_error *err = NULL;
3376 char pattern[1024];
3377 int ret;
3379 if (view_is_hsplit_top(view))
3380 v = view->child;
3381 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3382 v = view->parent;
3384 /* Get the pattern */
3385 wmove(v->window, v->nlines - 1, 0);
3386 wclrtoeol(v->window);
3387 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3388 nodelay(v->window, FALSE);
3389 nocbreak();
3390 echo();
3391 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3392 cbreak();
3393 noecho();
3394 nodelay(v->window, TRUE);
3395 if (ret == ERR)
3396 return NULL;
3398 if (*pattern == '\0') {
3400 * Safety measure for the situation where the user
3401 * resets limit without previously limiting anything.
3403 if (!s->limit_view)
3404 return NULL;
3407 * User could have pressed Ctrl+L, which refreshed the
3408 * commit queues, it means we can't save previously
3409 * (before limit took place) displayed entries,
3410 * because they would point to already free'ed memory,
3411 * so we are forced to always select first entry of
3412 * the queue.
3414 s->commits = &s->real_commits;
3415 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3416 s->selected_entry = s->first_displayed_entry;
3417 s->selected = 0;
3418 s->limit_view = 0;
3420 return NULL;
3423 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3424 return NULL;
3426 s->limit_view = 1;
3428 /* Clear the screen while loading limit view */
3429 s->first_displayed_entry = NULL;
3430 s->last_displayed_entry = NULL;
3431 s->selected_entry = NULL;
3432 s->commits = &s->limit_commits;
3434 /* Prepare limit queue for new search */
3435 free_commits(&s->limit_commits);
3436 s->limit_commits.ncommits = 0;
3438 /* First process commits, which are in queue already */
3439 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3440 int have_match = 0;
3442 err = match_commit(&have_match, entry->id,
3443 entry->commit, &s->limit_regex);
3444 if (err)
3445 return err;
3447 if (have_match) {
3448 struct commit_queue_entry *matched;
3450 matched = alloc_commit_queue_entry(entry->commit,
3451 entry->id);
3452 if (matched == NULL) {
3453 err = got_error_from_errno(
3454 "alloc_commit_queue_entry");
3455 break;
3457 matched->commit = entry->commit;
3458 got_object_commit_retain(entry->commit);
3460 matched->idx = s->limit_commits.ncommits;
3461 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3462 matched, entry);
3463 s->limit_commits.ncommits++;
3467 /* Second process all the commits, until we fill the screen */
3468 if (s->limit_commits.ncommits < view->nlines - 1 &&
3469 !s->thread_args.log_complete) {
3470 s->thread_args.commits_needed +=
3471 view->nlines - s->limit_commits.ncommits - 1;
3472 err = trigger_log_thread(view, 1);
3473 if (err)
3474 return err;
3477 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3478 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3479 s->selected = 0;
3481 return NULL;
3484 static const struct got_error *
3485 search_start_log_view(struct tog_view *view)
3487 struct tog_log_view_state *s = &view->state.log;
3489 s->matched_entry = NULL;
3490 s->search_entry = NULL;
3491 return NULL;
3494 static const struct got_error *
3495 search_next_log_view(struct tog_view *view)
3497 const struct got_error *err = NULL;
3498 struct tog_log_view_state *s = &view->state.log;
3499 struct commit_queue_entry *entry;
3501 /* Display progress update in log view. */
3502 show_log_view(view);
3503 update_panels();
3504 doupdate();
3506 if (s->search_entry) {
3507 int errcode, ch;
3508 errcode = pthread_mutex_unlock(&tog_mutex);
3509 if (errcode)
3510 return got_error_set_errno(errcode,
3511 "pthread_mutex_unlock");
3512 ch = wgetch(view->window);
3513 errcode = pthread_mutex_lock(&tog_mutex);
3514 if (errcode)
3515 return got_error_set_errno(errcode,
3516 "pthread_mutex_lock");
3517 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3518 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3519 return NULL;
3521 if (view->searching == TOG_SEARCH_FORWARD)
3522 entry = TAILQ_NEXT(s->search_entry, entry);
3523 else
3524 entry = TAILQ_PREV(s->search_entry,
3525 commit_queue_head, entry);
3526 } else if (s->matched_entry) {
3528 * If the user has moved the cursor after we hit a match,
3529 * the position from where we should continue searching
3530 * might have changed.
3532 if (view->searching == TOG_SEARCH_FORWARD)
3533 entry = TAILQ_NEXT(s->selected_entry, entry);
3534 else
3535 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3536 entry);
3537 } else {
3538 entry = s->selected_entry;
3541 while (1) {
3542 int have_match = 0;
3544 if (entry == NULL) {
3545 if (s->thread_args.log_complete ||
3546 view->searching == TOG_SEARCH_BACKWARD) {
3547 view->search_next_done =
3548 (s->matched_entry == NULL ?
3549 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3550 s->search_entry = NULL;
3551 return NULL;
3554 * Poke the log thread for more commits and return,
3555 * allowing the main loop to make progress. Search
3556 * will resume at s->search_entry once we come back.
3558 s->thread_args.commits_needed++;
3559 return trigger_log_thread(view, 0);
3562 err = match_commit(&have_match, entry->id, entry->commit,
3563 &view->regex);
3564 if (err)
3565 break;
3566 if (have_match) {
3567 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3568 s->matched_entry = entry;
3569 break;
3572 s->search_entry = entry;
3573 if (view->searching == TOG_SEARCH_FORWARD)
3574 entry = TAILQ_NEXT(entry, entry);
3575 else
3576 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3579 if (s->matched_entry) {
3580 int cur = s->selected_entry->idx;
3581 while (cur < s->matched_entry->idx) {
3582 err = input_log_view(NULL, view, KEY_DOWN);
3583 if (err)
3584 return err;
3585 cur++;
3587 while (cur > s->matched_entry->idx) {
3588 err = input_log_view(NULL, view, KEY_UP);
3589 if (err)
3590 return err;
3591 cur--;
3595 s->search_entry = NULL;
3597 return NULL;
3600 static const struct got_error *
3601 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3602 struct got_repository *repo, const char *head_ref_name,
3603 const char *in_repo_path, int log_branches)
3605 const struct got_error *err = NULL;
3606 struct tog_log_view_state *s = &view->state.log;
3607 struct got_repository *thread_repo = NULL;
3608 struct got_commit_graph *thread_graph = NULL;
3609 int errcode;
3611 if (in_repo_path != s->in_repo_path) {
3612 free(s->in_repo_path);
3613 s->in_repo_path = strdup(in_repo_path);
3614 if (s->in_repo_path == NULL) {
3615 err = got_error_from_errno("strdup");
3616 goto done;
3620 /* The commit queue only contains commits being displayed. */
3621 TAILQ_INIT(&s->real_commits.head);
3622 s->real_commits.ncommits = 0;
3623 s->commits = &s->real_commits;
3625 TAILQ_INIT(&s->limit_commits.head);
3626 s->limit_view = 0;
3627 s->limit_commits.ncommits = 0;
3629 s->repo = repo;
3630 if (head_ref_name) {
3631 s->head_ref_name = strdup(head_ref_name);
3632 if (s->head_ref_name == NULL) {
3633 err = got_error_from_errno("strdup");
3634 goto done;
3637 s->start_id = got_object_id_dup(start_id);
3638 if (s->start_id == NULL) {
3639 err = got_error_from_errno("got_object_id_dup");
3640 goto done;
3642 s->log_branches = log_branches;
3643 s->use_committer = 1;
3645 STAILQ_INIT(&s->colors);
3646 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3647 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3648 get_color_value("TOG_COLOR_COMMIT"));
3649 if (err)
3650 goto done;
3651 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3652 get_color_value("TOG_COLOR_AUTHOR"));
3653 if (err) {
3654 free_colors(&s->colors);
3655 goto done;
3657 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3658 get_color_value("TOG_COLOR_DATE"));
3659 if (err) {
3660 free_colors(&s->colors);
3661 goto done;
3665 view->show = show_log_view;
3666 view->input = input_log_view;
3667 view->resize = resize_log_view;
3668 view->close = close_log_view;
3669 view->search_start = search_start_log_view;
3670 view->search_next = search_next_log_view;
3672 if (s->thread_args.pack_fds == NULL) {
3673 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3674 if (err)
3675 goto done;
3677 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3678 s->thread_args.pack_fds);
3679 if (err)
3680 goto done;
3681 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3682 !s->log_branches);
3683 if (err)
3684 goto done;
3685 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3686 s->repo, NULL, NULL);
3687 if (err)
3688 goto done;
3690 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3691 if (errcode) {
3692 err = got_error_set_errno(errcode, "pthread_cond_init");
3693 goto done;
3695 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3696 if (errcode) {
3697 err = got_error_set_errno(errcode, "pthread_cond_init");
3698 goto done;
3701 s->thread_args.commits_needed = view->nlines;
3702 s->thread_args.graph = thread_graph;
3703 s->thread_args.real_commits = &s->real_commits;
3704 s->thread_args.limit_commits = &s->limit_commits;
3705 s->thread_args.in_repo_path = s->in_repo_path;
3706 s->thread_args.start_id = s->start_id;
3707 s->thread_args.repo = thread_repo;
3708 s->thread_args.log_complete = 0;
3709 s->thread_args.quit = &s->quit;
3710 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3711 s->thread_args.selected_entry = &s->selected_entry;
3712 s->thread_args.searching = &view->searching;
3713 s->thread_args.search_next_done = &view->search_next_done;
3714 s->thread_args.regex = &view->regex;
3715 s->thread_args.limiting = &s->limit_view;
3716 s->thread_args.limit_regex = &s->limit_regex;
3717 s->thread_args.limit_commits = &s->limit_commits;
3718 done:
3719 if (err) {
3720 if (view->close == NULL)
3721 close_log_view(view);
3722 view_close(view);
3724 return err;
3727 static const struct got_error *
3728 show_log_view(struct tog_view *view)
3730 const struct got_error *err;
3731 struct tog_log_view_state *s = &view->state.log;
3733 if (s->thread == NULL) {
3734 int errcode = pthread_create(&s->thread, NULL, log_thread,
3735 &s->thread_args);
3736 if (errcode)
3737 return got_error_set_errno(errcode, "pthread_create");
3738 if (s->thread_args.commits_needed > 0) {
3739 err = trigger_log_thread(view, 1);
3740 if (err)
3741 return err;
3745 return draw_commits(view);
3748 static void
3749 log_move_cursor_up(struct tog_view *view, int page, int home)
3751 struct tog_log_view_state *s = &view->state.log;
3753 if (s->first_displayed_entry == NULL)
3754 return;
3755 if (s->selected_entry->idx == 0)
3756 view->count = 0;
3758 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3759 || home)
3760 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3762 if (!page && !home && s->selected > 0)
3763 --s->selected;
3764 else
3765 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3767 select_commit(s);
3768 return;
3771 static const struct got_error *
3772 log_move_cursor_down(struct tog_view *view, int page)
3774 struct tog_log_view_state *s = &view->state.log;
3775 const struct got_error *err = NULL;
3776 int eos = view->nlines - 2;
3778 if (s->first_displayed_entry == NULL)
3779 return NULL;
3781 if (s->thread_args.log_complete &&
3782 s->selected_entry->idx >= s->commits->ncommits - 1)
3783 return NULL;
3785 if (view_is_hsplit_top(view))
3786 --eos; /* border consumes the last line */
3788 if (!page) {
3789 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3790 ++s->selected;
3791 else
3792 err = log_scroll_down(view, 1);
3793 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3794 struct commit_queue_entry *entry;
3795 int n;
3797 s->selected = 0;
3798 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3799 s->last_displayed_entry = entry;
3800 for (n = 0; n <= eos; n++) {
3801 if (entry == NULL)
3802 break;
3803 s->first_displayed_entry = entry;
3804 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3806 if (n > 0)
3807 s->selected = n - 1;
3808 } else {
3809 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3810 s->thread_args.log_complete)
3811 s->selected += MIN(page,
3812 s->commits->ncommits - s->selected_entry->idx - 1);
3813 else
3814 err = log_scroll_down(view, page);
3816 if (err)
3817 return err;
3820 * We might necessarily overshoot in horizontal
3821 * splits; if so, select the last displayed commit.
3823 if (s->first_displayed_entry && s->last_displayed_entry) {
3824 s->selected = MIN(s->selected,
3825 s->last_displayed_entry->idx -
3826 s->first_displayed_entry->idx);
3829 select_commit(s);
3831 if (s->thread_args.log_complete &&
3832 s->selected_entry->idx == s->commits->ncommits - 1)
3833 view->count = 0;
3835 return NULL;
3838 static void
3839 view_get_split(struct tog_view *view, int *y, int *x)
3841 *x = 0;
3842 *y = 0;
3844 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3845 if (view->child && view->child->resized_y)
3846 *y = view->child->resized_y;
3847 else if (view->resized_y)
3848 *y = view->resized_y;
3849 else
3850 *y = view_split_begin_y(view->lines);
3851 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3852 if (view->child && view->child->resized_x)
3853 *x = view->child->resized_x;
3854 else if (view->resized_x)
3855 *x = view->resized_x;
3856 else
3857 *x = view_split_begin_x(view->begin_x);
3861 /* Split view horizontally at y and offset view->state->selected line. */
3862 static const struct got_error *
3863 view_init_hsplit(struct tog_view *view, int y)
3865 const struct got_error *err = NULL;
3867 view->nlines = y;
3868 view->ncols = COLS;
3869 err = view_resize(view);
3870 if (err)
3871 return err;
3873 err = offset_selection_down(view);
3875 return err;
3878 static const struct got_error *
3879 log_goto_line(struct tog_view *view, int nlines)
3881 const struct got_error *err = NULL;
3882 struct tog_log_view_state *s = &view->state.log;
3883 int g, idx = s->selected_entry->idx;
3885 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3886 return NULL;
3888 g = view->gline;
3889 view->gline = 0;
3891 if (g >= s->first_displayed_entry->idx + 1 &&
3892 g <= s->last_displayed_entry->idx + 1 &&
3893 g - s->first_displayed_entry->idx - 1 < nlines) {
3894 s->selected = g - s->first_displayed_entry->idx - 1;
3895 select_commit(s);
3896 return NULL;
3899 if (idx + 1 < g) {
3900 err = log_move_cursor_down(view, g - idx - 1);
3901 if (!err && g > s->selected_entry->idx + 1)
3902 err = log_move_cursor_down(view,
3903 g - s->first_displayed_entry->idx - 1);
3904 if (err)
3905 return err;
3906 } else if (idx + 1 > g)
3907 log_move_cursor_up(view, idx - g + 1, 0);
3909 if (g < nlines && s->first_displayed_entry->idx == 0)
3910 s->selected = g - 1;
3912 select_commit(s);
3913 return NULL;
3917 static void
3918 horizontal_scroll_input(struct tog_view *view, int ch)
3921 switch (ch) {
3922 case KEY_LEFT:
3923 case 'h':
3924 view->x -= MIN(view->x, 2);
3925 if (view->x <= 0)
3926 view->count = 0;
3927 break;
3928 case KEY_RIGHT:
3929 case 'l':
3930 if (view->x + view->ncols / 2 < view->maxx)
3931 view->x += 2;
3932 else
3933 view->count = 0;
3934 break;
3935 case '0':
3936 view->x = 0;
3937 break;
3938 case '$':
3939 view->x = MAX(view->maxx - view->ncols / 2, 0);
3940 view->count = 0;
3941 break;
3942 default:
3943 break;
3947 static const struct got_error *
3948 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3950 const struct got_error *err = NULL;
3951 struct tog_log_view_state *s = &view->state.log;
3952 int eos, nscroll;
3954 if (s->thread_args.load_all) {
3955 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3956 s->thread_args.load_all = 0;
3957 else if (s->thread_args.log_complete) {
3958 err = log_move_cursor_down(view, s->commits->ncommits);
3959 s->thread_args.load_all = 0;
3961 if (err)
3962 return err;
3965 eos = nscroll = view->nlines - 1;
3966 if (view_is_hsplit_top(view))
3967 --eos; /* border */
3969 if (view->gline)
3970 return log_goto_line(view, eos);
3972 switch (ch) {
3973 case '&':
3974 err = limit_log_view(view);
3975 break;
3976 case 'q':
3977 s->quit = 1;
3978 break;
3979 case '0':
3980 case '$':
3981 case KEY_RIGHT:
3982 case 'l':
3983 case KEY_LEFT:
3984 case 'h':
3985 horizontal_scroll_input(view, ch);
3986 break;
3987 case 'k':
3988 case KEY_UP:
3989 case '<':
3990 case ',':
3991 case CTRL('p'):
3992 log_move_cursor_up(view, 0, 0);
3993 break;
3994 case 'g':
3995 case '=':
3996 case KEY_HOME:
3997 log_move_cursor_up(view, 0, 1);
3998 view->count = 0;
3999 break;
4000 case CTRL('u'):
4001 case 'u':
4002 nscroll /= 2;
4003 /* FALL THROUGH */
4004 case KEY_PPAGE:
4005 case CTRL('b'):
4006 case 'b':
4007 log_move_cursor_up(view, nscroll, 0);
4008 break;
4009 case 'j':
4010 case KEY_DOWN:
4011 case '>':
4012 case '.':
4013 case CTRL('n'):
4014 err = log_move_cursor_down(view, 0);
4015 break;
4016 case '@':
4017 s->use_committer = !s->use_committer;
4018 view->action = s->use_committer ?
4019 "show committer" : "show commit author";
4020 break;
4021 case 'G':
4022 case '*':
4023 case KEY_END: {
4024 /* We don't know yet how many commits, so we're forced to
4025 * traverse them all. */
4026 view->count = 0;
4027 s->thread_args.load_all = 1;
4028 if (!s->thread_args.log_complete)
4029 return trigger_log_thread(view, 0);
4030 err = log_move_cursor_down(view, s->commits->ncommits);
4031 s->thread_args.load_all = 0;
4032 break;
4034 case CTRL('d'):
4035 case 'd':
4036 nscroll /= 2;
4037 /* FALL THROUGH */
4038 case KEY_NPAGE:
4039 case CTRL('f'):
4040 case 'f':
4041 case ' ':
4042 err = log_move_cursor_down(view, nscroll);
4043 break;
4044 case KEY_RESIZE:
4045 if (s->selected > view->nlines - 2)
4046 s->selected = view->nlines - 2;
4047 if (s->selected > s->commits->ncommits - 1)
4048 s->selected = s->commits->ncommits - 1;
4049 select_commit(s);
4050 if (s->commits->ncommits < view->nlines - 1 &&
4051 !s->thread_args.log_complete) {
4052 s->thread_args.commits_needed += (view->nlines - 1) -
4053 s->commits->ncommits;
4054 err = trigger_log_thread(view, 1);
4056 break;
4057 case KEY_ENTER:
4058 case '\r':
4059 view->count = 0;
4060 if (s->selected_entry == NULL)
4061 break;
4062 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4063 break;
4064 case 'T':
4065 view->count = 0;
4066 if (s->selected_entry == NULL)
4067 break;
4068 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4069 break;
4070 case KEY_BACKSPACE:
4071 case CTRL('l'):
4072 case 'B':
4073 view->count = 0;
4074 if (ch == KEY_BACKSPACE &&
4075 got_path_is_root_dir(s->in_repo_path))
4076 break;
4077 err = stop_log_thread(s);
4078 if (err)
4079 return err;
4080 if (ch == KEY_BACKSPACE) {
4081 char *parent_path;
4082 err = got_path_dirname(&parent_path, s->in_repo_path);
4083 if (err)
4084 return err;
4085 free(s->in_repo_path);
4086 s->in_repo_path = parent_path;
4087 s->thread_args.in_repo_path = s->in_repo_path;
4088 } else if (ch == CTRL('l')) {
4089 struct got_object_id *start_id;
4090 err = got_repo_match_object_id(&start_id, NULL,
4091 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4092 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4093 if (err) {
4094 if (s->head_ref_name == NULL ||
4095 err->code != GOT_ERR_NOT_REF)
4096 return err;
4097 /* Try to cope with deleted references. */
4098 free(s->head_ref_name);
4099 s->head_ref_name = NULL;
4100 err = got_repo_match_object_id(&start_id,
4101 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4102 &tog_refs, s->repo);
4103 if (err)
4104 return err;
4106 free(s->start_id);
4107 s->start_id = start_id;
4108 s->thread_args.start_id = s->start_id;
4109 } else /* 'B' */
4110 s->log_branches = !s->log_branches;
4112 if (s->thread_args.pack_fds == NULL) {
4113 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4114 if (err)
4115 return err;
4117 err = got_repo_open(&s->thread_args.repo,
4118 got_repo_get_path(s->repo), NULL,
4119 s->thread_args.pack_fds);
4120 if (err)
4121 return err;
4122 tog_free_refs();
4123 err = tog_load_refs(s->repo, 0);
4124 if (err)
4125 return err;
4126 err = got_commit_graph_open(&s->thread_args.graph,
4127 s->in_repo_path, !s->log_branches);
4128 if (err)
4129 return err;
4130 err = got_commit_graph_iter_start(s->thread_args.graph,
4131 s->start_id, s->repo, NULL, NULL);
4132 if (err)
4133 return err;
4134 free_commits(&s->real_commits);
4135 free_commits(&s->limit_commits);
4136 s->first_displayed_entry = NULL;
4137 s->last_displayed_entry = NULL;
4138 s->selected_entry = NULL;
4139 s->selected = 0;
4140 s->thread_args.log_complete = 0;
4141 s->quit = 0;
4142 s->thread_args.commits_needed = view->lines;
4143 s->matched_entry = NULL;
4144 s->search_entry = NULL;
4145 view->offset = 0;
4146 break;
4147 case 'R':
4148 view->count = 0;
4149 err = view_request_new(new_view, view, TOG_VIEW_REF);
4150 break;
4151 default:
4152 view->count = 0;
4153 break;
4156 return err;
4159 static const struct got_error *
4160 apply_unveil(const char *repo_path, const char *worktree_path)
4162 const struct got_error *error;
4164 #ifdef PROFILE
4165 if (unveil("gmon.out", "rwc") != 0)
4166 return got_error_from_errno2("unveil", "gmon.out");
4167 #endif
4168 if (repo_path && unveil(repo_path, "r") != 0)
4169 return got_error_from_errno2("unveil", repo_path);
4171 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4172 return got_error_from_errno2("unveil", worktree_path);
4174 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4175 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4177 error = got_privsep_unveil_exec_helpers();
4178 if (error != NULL)
4179 return error;
4181 if (unveil(NULL, NULL) != 0)
4182 return got_error_from_errno("unveil");
4184 return NULL;
4187 static const struct got_error *
4188 init_mock_term(const char *test_script_path)
4190 const struct got_error *err = NULL;
4191 const char *screen_dump_path;
4192 int in;
4194 if (test_script_path == NULL || *test_script_path == '\0')
4195 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4197 tog_io.f = fopen(test_script_path, "re");
4198 if (tog_io.f == NULL) {
4199 err = got_error_from_errno_fmt("fopen: %s",
4200 test_script_path);
4201 goto done;
4204 /* test mode, we don't want any output */
4205 tog_io.cout = fopen("/dev/null", "w+");
4206 if (tog_io.cout == NULL) {
4207 err = got_error_from_errno2("fopen", "/dev/null");
4208 goto done;
4211 in = dup(fileno(tog_io.cout));
4212 if (in == -1) {
4213 err = got_error_from_errno("dup");
4214 goto done;
4216 tog_io.cin = fdopen(in, "r");
4217 if (tog_io.cin == NULL) {
4218 err = got_error_from_errno("fdopen");
4219 close(in);
4220 goto done;
4223 screen_dump_path = getenv("TOG_SCR_DUMP");
4224 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4225 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4226 tog_io.sdump = fopen(screen_dump_path, "wex");
4227 if (tog_io.sdump == NULL) {
4228 err = got_error_from_errno2("fopen", screen_dump_path);
4229 goto done;
4232 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4233 err = got_error_from_errno("fseeko");
4234 goto done;
4237 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4238 err = got_error_msg(GOT_ERR_IO,
4239 "newterm: failed to initialise curses");
4241 using_mock_io = 1;
4243 done:
4244 if (err)
4245 tog_io_close();
4246 return err;
4249 static void
4250 init_curses(void)
4253 * Override default signal handlers before starting ncurses.
4254 * This should prevent ncurses from installing its own
4255 * broken cleanup() signal handler.
4257 signal(SIGWINCH, tog_sigwinch);
4258 signal(SIGPIPE, tog_sigpipe);
4259 signal(SIGCONT, tog_sigcont);
4260 signal(SIGINT, tog_sigint);
4261 signal(SIGTERM, tog_sigterm);
4263 if (using_mock_io) /* In test mode we use a fake terminal */
4264 return;
4266 initscr();
4268 cbreak();
4269 halfdelay(1); /* Fast refresh while initial view is loading. */
4270 noecho();
4271 nonl();
4272 intrflush(stdscr, FALSE);
4273 keypad(stdscr, TRUE);
4274 curs_set(0);
4275 if (getenv("TOG_COLORS") != NULL) {
4276 start_color();
4277 use_default_colors();
4280 return;
4283 static const struct got_error *
4284 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4285 struct got_repository *repo, struct got_worktree *worktree)
4287 const struct got_error *err = NULL;
4289 if (argc == 0) {
4290 *in_repo_path = strdup("/");
4291 if (*in_repo_path == NULL)
4292 return got_error_from_errno("strdup");
4293 return NULL;
4296 if (worktree) {
4297 const char *prefix = got_worktree_get_path_prefix(worktree);
4298 char *p;
4300 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4301 if (err)
4302 return err;
4303 if (asprintf(in_repo_path, "%s%s%s", prefix,
4304 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4305 p) == -1) {
4306 err = got_error_from_errno("asprintf");
4307 *in_repo_path = NULL;
4309 free(p);
4310 } else
4311 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4313 return err;
4316 static const struct got_error *
4317 cmd_log(int argc, char *argv[])
4319 const struct got_error *error;
4320 struct got_repository *repo = NULL;
4321 struct got_worktree *worktree = NULL;
4322 struct got_object_id *start_id = NULL;
4323 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4324 char *start_commit = NULL, *label = NULL;
4325 struct got_reference *ref = NULL;
4326 const char *head_ref_name = NULL;
4327 int ch, log_branches = 0;
4328 struct tog_view *view;
4329 int *pack_fds = NULL;
4331 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4332 switch (ch) {
4333 case 'b':
4334 log_branches = 1;
4335 break;
4336 case 'c':
4337 start_commit = optarg;
4338 break;
4339 case 'r':
4340 repo_path = realpath(optarg, NULL);
4341 if (repo_path == NULL)
4342 return got_error_from_errno2("realpath",
4343 optarg);
4344 break;
4345 default:
4346 usage_log();
4347 /* NOTREACHED */
4351 argc -= optind;
4352 argv += optind;
4354 if (argc > 1)
4355 usage_log();
4357 error = got_repo_pack_fds_open(&pack_fds);
4358 if (error != NULL)
4359 goto done;
4361 if (repo_path == NULL) {
4362 cwd = getcwd(NULL, 0);
4363 if (cwd == NULL)
4364 return got_error_from_errno("getcwd");
4365 error = got_worktree_open(&worktree, cwd);
4366 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4367 goto done;
4368 if (worktree)
4369 repo_path =
4370 strdup(got_worktree_get_repo_path(worktree));
4371 else
4372 repo_path = strdup(cwd);
4373 if (repo_path == NULL) {
4374 error = got_error_from_errno("strdup");
4375 goto done;
4379 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4380 if (error != NULL)
4381 goto done;
4383 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4384 repo, worktree);
4385 if (error)
4386 goto done;
4388 init_curses();
4390 error = apply_unveil(got_repo_get_path(repo),
4391 worktree ? got_worktree_get_root_path(worktree) : NULL);
4392 if (error)
4393 goto done;
4395 /* already loaded by tog_log_with_path()? */
4396 if (TAILQ_EMPTY(&tog_refs)) {
4397 error = tog_load_refs(repo, 0);
4398 if (error)
4399 goto done;
4402 if (start_commit == NULL) {
4403 error = got_repo_match_object_id(&start_id, &label,
4404 worktree ? got_worktree_get_head_ref_name(worktree) :
4405 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4406 if (error)
4407 goto done;
4408 head_ref_name = label;
4409 } else {
4410 error = got_ref_open(&ref, repo, start_commit, 0);
4411 if (error == NULL)
4412 head_ref_name = got_ref_get_name(ref);
4413 else if (error->code != GOT_ERR_NOT_REF)
4414 goto done;
4415 error = got_repo_match_object_id(&start_id, NULL,
4416 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4417 if (error)
4418 goto done;
4421 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4422 if (view == NULL) {
4423 error = got_error_from_errno("view_open");
4424 goto done;
4426 error = open_log_view(view, start_id, repo, head_ref_name,
4427 in_repo_path, log_branches);
4428 if (error)
4429 goto done;
4430 if (worktree) {
4431 /* Release work tree lock. */
4432 got_worktree_close(worktree);
4433 worktree = NULL;
4435 error = view_loop(view);
4436 done:
4437 free(in_repo_path);
4438 free(repo_path);
4439 free(cwd);
4440 free(start_id);
4441 free(label);
4442 if (ref)
4443 got_ref_close(ref);
4444 if (repo) {
4445 const struct got_error *close_err = got_repo_close(repo);
4446 if (error == NULL)
4447 error = close_err;
4449 if (worktree)
4450 got_worktree_close(worktree);
4451 if (pack_fds) {
4452 const struct got_error *pack_err =
4453 got_repo_pack_fds_close(pack_fds);
4454 if (error == NULL)
4455 error = pack_err;
4457 tog_free_refs();
4458 return error;
4461 __dead static void
4462 usage_diff(void)
4464 endwin();
4465 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4466 "object1 object2\n", getprogname());
4467 exit(1);
4470 static int
4471 match_line(const char *line, regex_t *regex, size_t nmatch,
4472 regmatch_t *regmatch)
4474 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4477 static struct tog_color *
4478 match_color(struct tog_colors *colors, const char *line)
4480 struct tog_color *tc = NULL;
4482 STAILQ_FOREACH(tc, colors, entry) {
4483 if (match_line(line, &tc->regex, 0, NULL))
4484 return tc;
4487 return NULL;
4490 static const struct got_error *
4491 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4492 WINDOW *window, int skipcol, regmatch_t *regmatch)
4494 const struct got_error *err = NULL;
4495 char *exstr = NULL;
4496 wchar_t *wline = NULL;
4497 int rme, rms, n, width, scrollx;
4498 int width0 = 0, width1 = 0, width2 = 0;
4499 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4501 *wtotal = 0;
4503 rms = regmatch->rm_so;
4504 rme = regmatch->rm_eo;
4506 err = expand_tab(&exstr, line);
4507 if (err)
4508 return err;
4510 /* Split the line into 3 segments, according to match offsets. */
4511 seg0 = strndup(exstr, rms);
4512 if (seg0 == NULL) {
4513 err = got_error_from_errno("strndup");
4514 goto done;
4516 seg1 = strndup(exstr + rms, rme - rms);
4517 if (seg1 == NULL) {
4518 err = got_error_from_errno("strndup");
4519 goto done;
4521 seg2 = strdup(exstr + rme);
4522 if (seg2 == NULL) {
4523 err = got_error_from_errno("strndup");
4524 goto done;
4527 /* draw up to matched token if we haven't scrolled past it */
4528 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4529 col_tab_align, 1);
4530 if (err)
4531 goto done;
4532 n = MAX(width0 - skipcol, 0);
4533 if (n) {
4534 free(wline);
4535 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4536 wlimit, col_tab_align, 1);
4537 if (err)
4538 goto done;
4539 waddwstr(window, &wline[scrollx]);
4540 wlimit -= width;
4541 *wtotal += width;
4544 if (wlimit > 0) {
4545 int i = 0, w = 0;
4546 size_t wlen;
4548 free(wline);
4549 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4550 col_tab_align, 1);
4551 if (err)
4552 goto done;
4553 wlen = wcslen(wline);
4554 while (i < wlen) {
4555 width = wcwidth(wline[i]);
4556 if (width == -1) {
4557 /* should not happen, tabs are expanded */
4558 err = got_error(GOT_ERR_RANGE);
4559 goto done;
4561 if (width0 + w + width > skipcol)
4562 break;
4563 w += width;
4564 i++;
4566 /* draw (visible part of) matched token (if scrolled into it) */
4567 if (width1 - w > 0) {
4568 wattron(window, A_STANDOUT);
4569 waddwstr(window, &wline[i]);
4570 wattroff(window, A_STANDOUT);
4571 wlimit -= (width1 - w);
4572 *wtotal += (width1 - w);
4576 if (wlimit > 0) { /* draw rest of line */
4577 free(wline);
4578 if (skipcol > width0 + width1) {
4579 err = format_line(&wline, &width2, &scrollx, seg2,
4580 skipcol - (width0 + width1), wlimit,
4581 col_tab_align, 1);
4582 if (err)
4583 goto done;
4584 waddwstr(window, &wline[scrollx]);
4585 } else {
4586 err = format_line(&wline, &width2, NULL, seg2, 0,
4587 wlimit, col_tab_align, 1);
4588 if (err)
4589 goto done;
4590 waddwstr(window, wline);
4592 *wtotal += width2;
4594 done:
4595 free(wline);
4596 free(exstr);
4597 free(seg0);
4598 free(seg1);
4599 free(seg2);
4600 return err;
4603 static int
4604 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4606 FILE *f = NULL;
4607 int *eof, *first, *selected;
4609 if (view->type == TOG_VIEW_DIFF) {
4610 struct tog_diff_view_state *s = &view->state.diff;
4612 first = &s->first_displayed_line;
4613 selected = first;
4614 eof = &s->eof;
4615 f = s->f;
4616 } else if (view->type == TOG_VIEW_HELP) {
4617 struct tog_help_view_state *s = &view->state.help;
4619 first = &s->first_displayed_line;
4620 selected = first;
4621 eof = &s->eof;
4622 f = s->f;
4623 } else if (view->type == TOG_VIEW_BLAME) {
4624 struct tog_blame_view_state *s = &view->state.blame;
4626 first = &s->first_displayed_line;
4627 selected = &s->selected_line;
4628 eof = &s->eof;
4629 f = s->blame.f;
4630 } else
4631 return 0;
4633 /* Center gline in the middle of the page like vi(1). */
4634 if (*lineno < view->gline - (view->nlines - 3) / 2)
4635 return 0;
4636 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4637 rewind(f);
4638 *eof = 0;
4639 *first = 1;
4640 *lineno = 0;
4641 *nprinted = 0;
4642 return 0;
4645 *selected = view->gline <= (view->nlines - 3) / 2 ?
4646 view->gline : (view->nlines - 3) / 2 + 1;
4647 view->gline = 0;
4649 return 1;
4652 static const struct got_error *
4653 draw_file(struct tog_view *view, const char *header)
4655 struct tog_diff_view_state *s = &view->state.diff;
4656 regmatch_t *regmatch = &view->regmatch;
4657 const struct got_error *err;
4658 int nprinted = 0;
4659 char *line;
4660 size_t linesize = 0;
4661 ssize_t linelen;
4662 wchar_t *wline;
4663 int width;
4664 int max_lines = view->nlines;
4665 int nlines = s->nlines;
4666 off_t line_offset;
4668 s->lineno = s->first_displayed_line - 1;
4669 line_offset = s->lines[s->first_displayed_line - 1].offset;
4670 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4671 return got_error_from_errno("fseek");
4673 werase(view->window);
4675 if (view->gline > s->nlines - 1)
4676 view->gline = s->nlines - 1;
4678 if (header) {
4679 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4680 1 : view->gline - (view->nlines - 3) / 2 :
4681 s->lineno + s->selected_line;
4683 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4684 return got_error_from_errno("asprintf");
4685 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4686 0, 0);
4687 free(line);
4688 if (err)
4689 return err;
4691 if (view_needs_focus_indication(view))
4692 wstandout(view->window);
4693 waddwstr(view->window, wline);
4694 free(wline);
4695 wline = NULL;
4696 while (width++ < view->ncols)
4697 waddch(view->window, ' ');
4698 if (view_needs_focus_indication(view))
4699 wstandend(view->window);
4701 if (max_lines <= 1)
4702 return NULL;
4703 max_lines--;
4706 s->eof = 0;
4707 view->maxx = 0;
4708 line = NULL;
4709 while (max_lines > 0 && nprinted < max_lines) {
4710 enum got_diff_line_type linetype;
4711 attr_t attr = 0;
4713 linelen = getline(&line, &linesize, s->f);
4714 if (linelen == -1) {
4715 if (feof(s->f)) {
4716 s->eof = 1;
4717 break;
4719 free(line);
4720 return got_ferror(s->f, GOT_ERR_IO);
4723 if (++s->lineno < s->first_displayed_line)
4724 continue;
4725 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4726 continue;
4727 if (s->lineno == view->hiline)
4728 attr = A_STANDOUT;
4730 /* Set view->maxx based on full line length. */
4731 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4732 view->x ? 1 : 0);
4733 if (err) {
4734 free(line);
4735 return err;
4737 view->maxx = MAX(view->maxx, width);
4738 free(wline);
4739 wline = NULL;
4741 linetype = s->lines[s->lineno].type;
4742 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4743 linetype < GOT_DIFF_LINE_CONTEXT)
4744 attr |= COLOR_PAIR(linetype);
4745 if (attr)
4746 wattron(view->window, attr);
4747 if (s->first_displayed_line + nprinted == s->matched_line &&
4748 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4749 err = add_matched_line(&width, line, view->ncols, 0,
4750 view->window, view->x, regmatch);
4751 if (err) {
4752 free(line);
4753 return err;
4755 } else {
4756 int skip;
4757 err = format_line(&wline, &width, &skip, line,
4758 view->x, view->ncols, 0, view->x ? 1 : 0);
4759 if (err) {
4760 free(line);
4761 return err;
4763 waddwstr(view->window, &wline[skip]);
4764 free(wline);
4765 wline = NULL;
4767 if (s->lineno == view->hiline) {
4768 /* highlight full gline length */
4769 while (width++ < view->ncols)
4770 waddch(view->window, ' ');
4771 } else {
4772 if (width <= view->ncols - 1)
4773 waddch(view->window, '\n');
4775 if (attr)
4776 wattroff(view->window, attr);
4777 if (++nprinted == 1)
4778 s->first_displayed_line = s->lineno;
4780 free(line);
4781 if (nprinted >= 1)
4782 s->last_displayed_line = s->first_displayed_line +
4783 (nprinted - 1);
4784 else
4785 s->last_displayed_line = s->first_displayed_line;
4787 view_border(view);
4789 if (s->eof) {
4790 while (nprinted < view->nlines) {
4791 waddch(view->window, '\n');
4792 nprinted++;
4795 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4796 view->ncols, 0, 0);
4797 if (err) {
4798 return err;
4801 wstandout(view->window);
4802 waddwstr(view->window, wline);
4803 free(wline);
4804 wline = NULL;
4805 wstandend(view->window);
4808 return NULL;
4811 static char *
4812 get_datestr(time_t *time, char *datebuf)
4814 struct tm mytm, *tm;
4815 char *p, *s;
4817 tm = gmtime_r(time, &mytm);
4818 if (tm == NULL)
4819 return NULL;
4820 s = asctime_r(tm, datebuf);
4821 if (s == NULL)
4822 return NULL;
4823 p = strchr(s, '\n');
4824 if (p)
4825 *p = '\0';
4826 return s;
4829 static const struct got_error *
4830 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4831 off_t off, uint8_t type)
4833 struct got_diff_line *p;
4835 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4836 if (p == NULL)
4837 return got_error_from_errno("reallocarray");
4838 *lines = p;
4839 (*lines)[*nlines].offset = off;
4840 (*lines)[*nlines].type = type;
4841 (*nlines)++;
4843 return NULL;
4846 static const struct got_error *
4847 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4848 struct got_diff_line *s_lines, size_t s_nlines)
4850 struct got_diff_line *p;
4851 char buf[BUFSIZ];
4852 size_t i, r;
4854 if (fseeko(src, 0L, SEEK_SET) == -1)
4855 return got_error_from_errno("fseeko");
4857 for (;;) {
4858 r = fread(buf, 1, sizeof(buf), src);
4859 if (r == 0) {
4860 if (ferror(src))
4861 return got_error_from_errno("fread");
4862 if (feof(src))
4863 break;
4865 if (fwrite(buf, 1, r, dst) != r)
4866 return got_ferror(dst, GOT_ERR_IO);
4869 if (s_nlines == 0 && *d_nlines == 0)
4870 return NULL;
4873 * If commit info was in dst, increment line offsets
4874 * of the appended diff content, but skip s_lines[0]
4875 * because offset zero is already in *d_lines.
4877 if (*d_nlines > 0) {
4878 for (i = 1; i < s_nlines; ++i)
4879 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4881 if (s_nlines > 0) {
4882 --s_nlines;
4883 ++s_lines;
4887 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4888 if (p == NULL) {
4889 /* d_lines is freed in close_diff_view() */
4890 return got_error_from_errno("reallocarray");
4893 *d_lines = p;
4895 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4896 *d_nlines += s_nlines;
4898 return NULL;
4901 static const struct got_error *
4902 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4903 struct got_object_id *commit_id, struct got_reflist_head *refs,
4904 struct got_repository *repo, int ignore_ws, int force_text_diff,
4905 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4907 const struct got_error *err = NULL;
4908 char datebuf[26], *datestr;
4909 struct got_commit_object *commit;
4910 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4911 time_t committer_time;
4912 const char *author, *committer;
4913 char *refs_str = NULL;
4914 struct got_pathlist_entry *pe;
4915 off_t outoff = 0;
4916 int n;
4918 if (refs) {
4919 err = build_refs_str(&refs_str, refs, commit_id, repo);
4920 if (err)
4921 return err;
4924 err = got_object_open_as_commit(&commit, repo, commit_id);
4925 if (err)
4926 return err;
4928 err = got_object_id_str(&id_str, commit_id);
4929 if (err) {
4930 err = got_error_from_errno("got_object_id_str");
4931 goto done;
4934 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4935 if (err)
4936 goto done;
4938 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4939 refs_str ? refs_str : "", refs_str ? ")" : "");
4940 if (n < 0) {
4941 err = got_error_from_errno("fprintf");
4942 goto done;
4944 outoff += n;
4945 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4946 if (err)
4947 goto done;
4949 n = fprintf(outfile, "from: %s\n",
4950 got_object_commit_get_author(commit));
4951 if (n < 0) {
4952 err = got_error_from_errno("fprintf");
4953 goto done;
4955 outoff += n;
4956 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4957 if (err)
4958 goto done;
4960 author = got_object_commit_get_author(commit);
4961 committer = got_object_commit_get_committer(commit);
4962 if (strcmp(author, committer) != 0) {
4963 n = fprintf(outfile, "via: %s\n", committer);
4964 if (n < 0) {
4965 err = got_error_from_errno("fprintf");
4966 goto done;
4968 outoff += n;
4969 err = add_line_metadata(lines, nlines, outoff,
4970 GOT_DIFF_LINE_AUTHOR);
4971 if (err)
4972 goto done;
4974 committer_time = got_object_commit_get_committer_time(commit);
4975 datestr = get_datestr(&committer_time, datebuf);
4976 if (datestr) {
4977 n = fprintf(outfile, "date: %s UTC\n", datestr);
4978 if (n < 0) {
4979 err = got_error_from_errno("fprintf");
4980 goto done;
4982 outoff += n;
4983 err = add_line_metadata(lines, nlines, outoff,
4984 GOT_DIFF_LINE_DATE);
4985 if (err)
4986 goto done;
4988 if (got_object_commit_get_nparents(commit) > 1) {
4989 const struct got_object_id_queue *parent_ids;
4990 struct got_object_qid *qid;
4991 int pn = 1;
4992 parent_ids = got_object_commit_get_parent_ids(commit);
4993 STAILQ_FOREACH(qid, parent_ids, entry) {
4994 err = got_object_id_str(&id_str, &qid->id);
4995 if (err)
4996 goto done;
4997 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4998 if (n < 0) {
4999 err = got_error_from_errno("fprintf");
5000 goto done;
5002 outoff += n;
5003 err = add_line_metadata(lines, nlines, outoff,
5004 GOT_DIFF_LINE_META);
5005 if (err)
5006 goto done;
5007 free(id_str);
5008 id_str = NULL;
5012 err = got_object_commit_get_logmsg(&logmsg, commit);
5013 if (err)
5014 goto done;
5015 s = logmsg;
5016 while ((line = strsep(&s, "\n")) != NULL) {
5017 n = fprintf(outfile, "%s\n", line);
5018 if (n < 0) {
5019 err = got_error_from_errno("fprintf");
5020 goto done;
5022 outoff += n;
5023 err = add_line_metadata(lines, nlines, outoff,
5024 GOT_DIFF_LINE_LOGMSG);
5025 if (err)
5026 goto done;
5029 TAILQ_FOREACH(pe, dsa->paths, entry) {
5030 struct got_diff_changed_path *cp = pe->data;
5031 int pad = dsa->max_path_len - pe->path_len + 1;
5033 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5034 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5035 dsa->rm_cols + 1, cp->rm);
5036 if (n < 0) {
5037 err = got_error_from_errno("fprintf");
5038 goto done;
5040 outoff += n;
5041 err = add_line_metadata(lines, nlines, outoff,
5042 GOT_DIFF_LINE_CHANGES);
5043 if (err)
5044 goto done;
5047 fputc('\n', outfile);
5048 outoff++;
5049 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5050 if (err)
5051 goto done;
5053 n = fprintf(outfile,
5054 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5055 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5056 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5057 if (n < 0) {
5058 err = got_error_from_errno("fprintf");
5059 goto done;
5061 outoff += n;
5062 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5063 if (err)
5064 goto done;
5066 fputc('\n', outfile);
5067 outoff++;
5068 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5069 done:
5070 free(id_str);
5071 free(logmsg);
5072 free(refs_str);
5073 got_object_commit_close(commit);
5074 if (err) {
5075 free(*lines);
5076 *lines = NULL;
5077 *nlines = 0;
5079 return err;
5082 static const struct got_error *
5083 create_diff(struct tog_diff_view_state *s)
5085 const struct got_error *err = NULL;
5086 FILE *f = NULL, *tmp_diff_file = NULL;
5087 int obj_type;
5088 struct got_diff_line *lines = NULL;
5089 struct got_pathlist_head changed_paths;
5091 TAILQ_INIT(&changed_paths);
5093 free(s->lines);
5094 s->lines = malloc(sizeof(*s->lines));
5095 if (s->lines == NULL)
5096 return got_error_from_errno("malloc");
5097 s->nlines = 0;
5099 f = got_opentemp();
5100 if (f == NULL) {
5101 err = got_error_from_errno("got_opentemp");
5102 goto done;
5104 tmp_diff_file = got_opentemp();
5105 if (tmp_diff_file == NULL) {
5106 err = got_error_from_errno("got_opentemp");
5107 goto done;
5109 if (s->f && fclose(s->f) == EOF) {
5110 err = got_error_from_errno("fclose");
5111 goto done;
5113 s->f = f;
5115 if (s->id1)
5116 err = got_object_get_type(&obj_type, s->repo, s->id1);
5117 else
5118 err = got_object_get_type(&obj_type, s->repo, s->id2);
5119 if (err)
5120 goto done;
5122 switch (obj_type) {
5123 case GOT_OBJ_TYPE_BLOB:
5124 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5125 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5126 s->label1, s->label2, tog_diff_algo, s->diff_context,
5127 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5128 s->f);
5129 break;
5130 case GOT_OBJ_TYPE_TREE:
5131 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5132 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5133 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5134 s->force_text_diff, NULL, s->repo, s->f);
5135 break;
5136 case GOT_OBJ_TYPE_COMMIT: {
5137 const struct got_object_id_queue *parent_ids;
5138 struct got_object_qid *pid;
5139 struct got_commit_object *commit2;
5140 struct got_reflist_head *refs;
5141 size_t nlines = 0;
5142 struct got_diffstat_cb_arg dsa = {
5143 0, 0, 0, 0, 0, 0,
5144 &changed_paths,
5145 s->ignore_whitespace,
5146 s->force_text_diff,
5147 tog_diff_algo
5150 lines = malloc(sizeof(*lines));
5151 if (lines == NULL) {
5152 err = got_error_from_errno("malloc");
5153 goto done;
5156 /* build diff first in tmp file then append to commit info */
5157 err = got_diff_objects_as_commits(&lines, &nlines,
5158 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5159 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5160 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5161 if (err)
5162 break;
5164 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5165 if (err)
5166 goto done;
5167 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5168 /* Show commit info if we're diffing to a parent/root commit. */
5169 if (s->id1 == NULL) {
5170 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5171 refs, s->repo, s->ignore_whitespace,
5172 s->force_text_diff, &dsa, s->f);
5173 if (err)
5174 goto done;
5175 } else {
5176 parent_ids = got_object_commit_get_parent_ids(commit2);
5177 STAILQ_FOREACH(pid, parent_ids, entry) {
5178 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5179 err = write_commit_info(&s->lines,
5180 &s->nlines, s->id2, refs, s->repo,
5181 s->ignore_whitespace,
5182 s->force_text_diff, &dsa, s->f);
5183 if (err)
5184 goto done;
5185 break;
5189 got_object_commit_close(commit2);
5191 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5192 lines, nlines);
5193 break;
5195 default:
5196 err = got_error(GOT_ERR_OBJ_TYPE);
5197 break;
5199 done:
5200 free(lines);
5201 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5202 if (s->f && fflush(s->f) != 0 && err == NULL)
5203 err = got_error_from_errno("fflush");
5204 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5205 err = got_error_from_errno("fclose");
5206 return err;
5209 static void
5210 diff_view_indicate_progress(struct tog_view *view)
5212 mvwaddstr(view->window, 0, 0, "diffing...");
5213 update_panels();
5214 doupdate();
5217 static const struct got_error *
5218 search_start_diff_view(struct tog_view *view)
5220 struct tog_diff_view_state *s = &view->state.diff;
5222 s->matched_line = 0;
5223 return NULL;
5226 static void
5227 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5228 size_t *nlines, int **first, int **last, int **match, int **selected)
5230 struct tog_diff_view_state *s = &view->state.diff;
5232 *f = s->f;
5233 *nlines = s->nlines;
5234 *line_offsets = NULL;
5235 *match = &s->matched_line;
5236 *first = &s->first_displayed_line;
5237 *last = &s->last_displayed_line;
5238 *selected = &s->selected_line;
5241 static const struct got_error *
5242 search_next_view_match(struct tog_view *view)
5244 const struct got_error *err = NULL;
5245 FILE *f;
5246 int lineno;
5247 char *line = NULL;
5248 size_t linesize = 0;
5249 ssize_t linelen;
5250 off_t *line_offsets;
5251 size_t nlines = 0;
5252 int *first, *last, *match, *selected;
5254 if (!view->search_setup)
5255 return got_error_msg(GOT_ERR_NOT_IMPL,
5256 "view search not supported");
5257 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5258 &match, &selected);
5260 if (!view->searching) {
5261 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5262 return NULL;
5265 if (*match) {
5266 if (view->searching == TOG_SEARCH_FORWARD)
5267 lineno = *first + 1;
5268 else
5269 lineno = *first - 1;
5270 } else
5271 lineno = *first - 1 + *selected;
5273 while (1) {
5274 off_t offset;
5276 if (lineno <= 0 || lineno > nlines) {
5277 if (*match == 0) {
5278 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5279 break;
5282 if (view->searching == TOG_SEARCH_FORWARD)
5283 lineno = 1;
5284 else
5285 lineno = nlines;
5288 offset = view->type == TOG_VIEW_DIFF ?
5289 view->state.diff.lines[lineno - 1].offset :
5290 line_offsets[lineno - 1];
5291 if (fseeko(f, offset, SEEK_SET) != 0) {
5292 free(line);
5293 return got_error_from_errno("fseeko");
5295 linelen = getline(&line, &linesize, f);
5296 if (linelen != -1) {
5297 char *exstr;
5298 err = expand_tab(&exstr, line);
5299 if (err)
5300 break;
5301 if (match_line(exstr, &view->regex, 1,
5302 &view->regmatch)) {
5303 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5304 *match = lineno;
5305 free(exstr);
5306 break;
5308 free(exstr);
5310 if (view->searching == TOG_SEARCH_FORWARD)
5311 lineno++;
5312 else
5313 lineno--;
5315 free(line);
5317 if (*match) {
5318 *first = *match;
5319 *selected = 1;
5322 return err;
5325 static const struct got_error *
5326 close_diff_view(struct tog_view *view)
5328 const struct got_error *err = NULL;
5329 struct tog_diff_view_state *s = &view->state.diff;
5331 free(s->id1);
5332 s->id1 = NULL;
5333 free(s->id2);
5334 s->id2 = NULL;
5335 if (s->f && fclose(s->f) == EOF)
5336 err = got_error_from_errno("fclose");
5337 s->f = NULL;
5338 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5339 err = got_error_from_errno("fclose");
5340 s->f1 = NULL;
5341 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5342 err = got_error_from_errno("fclose");
5343 s->f2 = NULL;
5344 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5345 err = got_error_from_errno("close");
5346 s->fd1 = -1;
5347 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5348 err = got_error_from_errno("close");
5349 s->fd2 = -1;
5350 free(s->lines);
5351 s->lines = NULL;
5352 s->nlines = 0;
5353 return err;
5356 static const struct got_error *
5357 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5358 struct got_object_id *id2, const char *label1, const char *label2,
5359 int diff_context, int ignore_whitespace, int force_text_diff,
5360 struct tog_view *parent_view, struct got_repository *repo)
5362 const struct got_error *err;
5363 struct tog_diff_view_state *s = &view->state.diff;
5365 memset(s, 0, sizeof(*s));
5366 s->fd1 = -1;
5367 s->fd2 = -1;
5369 if (id1 != NULL && id2 != NULL) {
5370 int type1, type2;
5372 err = got_object_get_type(&type1, repo, id1);
5373 if (err)
5374 goto done;
5375 err = got_object_get_type(&type2, repo, id2);
5376 if (err)
5377 goto done;
5379 if (type1 != type2) {
5380 err = got_error(GOT_ERR_OBJ_TYPE);
5381 goto done;
5384 s->first_displayed_line = 1;
5385 s->last_displayed_line = view->nlines;
5386 s->selected_line = 1;
5387 s->repo = repo;
5388 s->id1 = id1;
5389 s->id2 = id2;
5390 s->label1 = label1;
5391 s->label2 = label2;
5393 if (id1) {
5394 s->id1 = got_object_id_dup(id1);
5395 if (s->id1 == NULL) {
5396 err = got_error_from_errno("got_object_id_dup");
5397 goto done;
5399 } else
5400 s->id1 = NULL;
5402 s->id2 = got_object_id_dup(id2);
5403 if (s->id2 == NULL) {
5404 err = got_error_from_errno("got_object_id_dup");
5405 goto done;
5408 s->f1 = got_opentemp();
5409 if (s->f1 == NULL) {
5410 err = got_error_from_errno("got_opentemp");
5411 goto done;
5414 s->f2 = got_opentemp();
5415 if (s->f2 == NULL) {
5416 err = got_error_from_errno("got_opentemp");
5417 goto done;
5420 s->fd1 = got_opentempfd();
5421 if (s->fd1 == -1) {
5422 err = got_error_from_errno("got_opentempfd");
5423 goto done;
5426 s->fd2 = got_opentempfd();
5427 if (s->fd2 == -1) {
5428 err = got_error_from_errno("got_opentempfd");
5429 goto done;
5432 s->diff_context = diff_context;
5433 s->ignore_whitespace = ignore_whitespace;
5434 s->force_text_diff = force_text_diff;
5435 s->parent_view = parent_view;
5436 s->repo = repo;
5438 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5439 int rc;
5441 rc = init_pair(GOT_DIFF_LINE_MINUS,
5442 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5443 if (rc != ERR)
5444 rc = init_pair(GOT_DIFF_LINE_PLUS,
5445 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5446 if (rc != ERR)
5447 rc = init_pair(GOT_DIFF_LINE_HUNK,
5448 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5449 if (rc != ERR)
5450 rc = init_pair(GOT_DIFF_LINE_META,
5451 get_color_value("TOG_COLOR_DIFF_META"), -1);
5452 if (rc != ERR)
5453 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5454 get_color_value("TOG_COLOR_DIFF_META"), -1);
5455 if (rc != ERR)
5456 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5457 get_color_value("TOG_COLOR_DIFF_META"), -1);
5458 if (rc != ERR)
5459 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5460 get_color_value("TOG_COLOR_DIFF_META"), -1);
5461 if (rc != ERR)
5462 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5463 get_color_value("TOG_COLOR_AUTHOR"), -1);
5464 if (rc != ERR)
5465 rc = init_pair(GOT_DIFF_LINE_DATE,
5466 get_color_value("TOG_COLOR_DATE"), -1);
5467 if (rc == ERR) {
5468 err = got_error(GOT_ERR_RANGE);
5469 goto done;
5473 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5474 view_is_splitscreen(view))
5475 show_log_view(parent_view); /* draw border */
5476 diff_view_indicate_progress(view);
5478 err = create_diff(s);
5480 view->show = show_diff_view;
5481 view->input = input_diff_view;
5482 view->reset = reset_diff_view;
5483 view->close = close_diff_view;
5484 view->search_start = search_start_diff_view;
5485 view->search_setup = search_setup_diff_view;
5486 view->search_next = search_next_view_match;
5487 done:
5488 if (err) {
5489 if (view->close == NULL)
5490 close_diff_view(view);
5491 view_close(view);
5493 return err;
5496 static const struct got_error *
5497 show_diff_view(struct tog_view *view)
5499 const struct got_error *err;
5500 struct tog_diff_view_state *s = &view->state.diff;
5501 char *id_str1 = NULL, *id_str2, *header;
5502 const char *label1, *label2;
5504 if (s->id1) {
5505 err = got_object_id_str(&id_str1, s->id1);
5506 if (err)
5507 return err;
5508 label1 = s->label1 ? s->label1 : id_str1;
5509 } else
5510 label1 = "/dev/null";
5512 err = got_object_id_str(&id_str2, s->id2);
5513 if (err)
5514 return err;
5515 label2 = s->label2 ? s->label2 : id_str2;
5517 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5518 err = got_error_from_errno("asprintf");
5519 free(id_str1);
5520 free(id_str2);
5521 return err;
5523 free(id_str1);
5524 free(id_str2);
5526 err = draw_file(view, header);
5527 free(header);
5528 return err;
5531 static const struct got_error *
5532 set_selected_commit(struct tog_diff_view_state *s,
5533 struct commit_queue_entry *entry)
5535 const struct got_error *err;
5536 const struct got_object_id_queue *parent_ids;
5537 struct got_commit_object *selected_commit;
5538 struct got_object_qid *pid;
5540 free(s->id2);
5541 s->id2 = got_object_id_dup(entry->id);
5542 if (s->id2 == NULL)
5543 return got_error_from_errno("got_object_id_dup");
5545 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5546 if (err)
5547 return err;
5548 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5549 free(s->id1);
5550 pid = STAILQ_FIRST(parent_ids);
5551 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5552 got_object_commit_close(selected_commit);
5553 return NULL;
5556 static const struct got_error *
5557 reset_diff_view(struct tog_view *view)
5559 struct tog_diff_view_state *s = &view->state.diff;
5561 view->count = 0;
5562 wclear(view->window);
5563 s->first_displayed_line = 1;
5564 s->last_displayed_line = view->nlines;
5565 s->matched_line = 0;
5566 diff_view_indicate_progress(view);
5567 return create_diff(s);
5570 static void
5571 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5573 int start, i;
5575 i = start = s->first_displayed_line - 1;
5577 while (s->lines[i].type != type) {
5578 if (i == 0)
5579 i = s->nlines - 1;
5580 if (--i == start)
5581 return; /* do nothing, requested type not in file */
5584 s->selected_line = 1;
5585 s->first_displayed_line = i;
5588 static void
5589 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5591 int start, i;
5593 i = start = s->first_displayed_line + 1;
5595 while (s->lines[i].type != type) {
5596 if (i == s->nlines - 1)
5597 i = 0;
5598 if (++i == start)
5599 return; /* do nothing, requested type not in file */
5602 s->selected_line = 1;
5603 s->first_displayed_line = i;
5606 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5607 int, int, int);
5608 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5609 int, int);
5611 static const struct got_error *
5612 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5614 const struct got_error *err = NULL;
5615 struct tog_diff_view_state *s = &view->state.diff;
5616 struct tog_log_view_state *ls;
5617 struct commit_queue_entry *old_selected_entry;
5618 char *line = NULL;
5619 size_t linesize = 0;
5620 ssize_t linelen;
5621 int i, nscroll = view->nlines - 1, up = 0;
5623 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5625 switch (ch) {
5626 case '0':
5627 case '$':
5628 case KEY_RIGHT:
5629 case 'l':
5630 case KEY_LEFT:
5631 case 'h':
5632 horizontal_scroll_input(view, ch);
5633 break;
5634 case 'a':
5635 case 'w':
5636 if (ch == 'a') {
5637 s->force_text_diff = !s->force_text_diff;
5638 view->action = s->force_text_diff ?
5639 "force ASCII text enabled" :
5640 "force ASCII text disabled";
5642 else if (ch == 'w') {
5643 s->ignore_whitespace = !s->ignore_whitespace;
5644 view->action = s->ignore_whitespace ?
5645 "ignore whitespace enabled" :
5646 "ignore whitespace disabled";
5648 err = reset_diff_view(view);
5649 break;
5650 case 'g':
5651 case KEY_HOME:
5652 s->first_displayed_line = 1;
5653 view->count = 0;
5654 break;
5655 case 'G':
5656 case KEY_END:
5657 view->count = 0;
5658 if (s->eof)
5659 break;
5661 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5662 s->eof = 1;
5663 break;
5664 case 'k':
5665 case KEY_UP:
5666 case CTRL('p'):
5667 if (s->first_displayed_line > 1)
5668 s->first_displayed_line--;
5669 else
5670 view->count = 0;
5671 break;
5672 case CTRL('u'):
5673 case 'u':
5674 nscroll /= 2;
5675 /* FALL THROUGH */
5676 case KEY_PPAGE:
5677 case CTRL('b'):
5678 case 'b':
5679 if (s->first_displayed_line == 1) {
5680 view->count = 0;
5681 break;
5683 i = 0;
5684 while (i++ < nscroll && s->first_displayed_line > 1)
5685 s->first_displayed_line--;
5686 break;
5687 case 'j':
5688 case KEY_DOWN:
5689 case CTRL('n'):
5690 if (!s->eof)
5691 s->first_displayed_line++;
5692 else
5693 view->count = 0;
5694 break;
5695 case CTRL('d'):
5696 case 'd':
5697 nscroll /= 2;
5698 /* FALL THROUGH */
5699 case KEY_NPAGE:
5700 case CTRL('f'):
5701 case 'f':
5702 case ' ':
5703 if (s->eof) {
5704 view->count = 0;
5705 break;
5707 i = 0;
5708 while (!s->eof && i++ < nscroll) {
5709 linelen = getline(&line, &linesize, s->f);
5710 s->first_displayed_line++;
5711 if (linelen == -1) {
5712 if (feof(s->f)) {
5713 s->eof = 1;
5714 } else
5715 err = got_ferror(s->f, GOT_ERR_IO);
5716 break;
5719 free(line);
5720 break;
5721 case '(':
5722 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5723 break;
5724 case ')':
5725 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5726 break;
5727 case '{':
5728 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5729 break;
5730 case '}':
5731 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5732 break;
5733 case '[':
5734 if (s->diff_context > 0) {
5735 s->diff_context--;
5736 s->matched_line = 0;
5737 diff_view_indicate_progress(view);
5738 err = create_diff(s);
5739 if (s->first_displayed_line + view->nlines - 1 >
5740 s->nlines) {
5741 s->first_displayed_line = 1;
5742 s->last_displayed_line = view->nlines;
5744 } else
5745 view->count = 0;
5746 break;
5747 case ']':
5748 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5749 s->diff_context++;
5750 s->matched_line = 0;
5751 diff_view_indicate_progress(view);
5752 err = create_diff(s);
5753 } else
5754 view->count = 0;
5755 break;
5756 case '<':
5757 case ',':
5758 case 'K':
5759 up = 1;
5760 /* FALL THROUGH */
5761 case '>':
5762 case '.':
5763 case 'J':
5764 if (s->parent_view == NULL) {
5765 view->count = 0;
5766 break;
5768 s->parent_view->count = view->count;
5770 if (s->parent_view->type == TOG_VIEW_LOG) {
5771 ls = &s->parent_view->state.log;
5772 old_selected_entry = ls->selected_entry;
5774 err = input_log_view(NULL, s->parent_view,
5775 up ? KEY_UP : KEY_DOWN);
5776 if (err)
5777 break;
5778 view->count = s->parent_view->count;
5780 if (old_selected_entry == ls->selected_entry)
5781 break;
5783 err = set_selected_commit(s, ls->selected_entry);
5784 if (err)
5785 break;
5786 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5787 struct tog_blame_view_state *bs;
5788 struct got_object_id *id, *prev_id;
5790 bs = &s->parent_view->state.blame;
5791 prev_id = get_annotation_for_line(bs->blame.lines,
5792 bs->blame.nlines, bs->last_diffed_line);
5794 err = input_blame_view(&view, s->parent_view,
5795 up ? KEY_UP : KEY_DOWN);
5796 if (err)
5797 break;
5798 view->count = s->parent_view->count;
5800 if (prev_id == NULL)
5801 break;
5802 id = get_selected_commit_id(bs->blame.lines,
5803 bs->blame.nlines, bs->first_displayed_line,
5804 bs->selected_line);
5805 if (id == NULL)
5806 break;
5808 if (!got_object_id_cmp(prev_id, id))
5809 break;
5811 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5812 if (err)
5813 break;
5815 s->first_displayed_line = 1;
5816 s->last_displayed_line = view->nlines;
5817 s->matched_line = 0;
5818 view->x = 0;
5820 diff_view_indicate_progress(view);
5821 err = create_diff(s);
5822 break;
5823 default:
5824 view->count = 0;
5825 break;
5828 return err;
5831 static const struct got_error *
5832 cmd_diff(int argc, char *argv[])
5834 const struct got_error *error;
5835 struct got_repository *repo = NULL;
5836 struct got_worktree *worktree = NULL;
5837 struct got_object_id *id1 = NULL, *id2 = NULL;
5838 char *repo_path = NULL, *cwd = NULL;
5839 char *id_str1 = NULL, *id_str2 = NULL;
5840 char *label1 = NULL, *label2 = NULL;
5841 int diff_context = 3, ignore_whitespace = 0;
5842 int ch, force_text_diff = 0;
5843 const char *errstr;
5844 struct tog_view *view;
5845 int *pack_fds = NULL;
5847 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5848 switch (ch) {
5849 case 'a':
5850 force_text_diff = 1;
5851 break;
5852 case 'C':
5853 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5854 &errstr);
5855 if (errstr != NULL)
5856 errx(1, "number of context lines is %s: %s",
5857 errstr, errstr);
5858 break;
5859 case 'r':
5860 repo_path = realpath(optarg, NULL);
5861 if (repo_path == NULL)
5862 return got_error_from_errno2("realpath",
5863 optarg);
5864 got_path_strip_trailing_slashes(repo_path);
5865 break;
5866 case 'w':
5867 ignore_whitespace = 1;
5868 break;
5869 default:
5870 usage_diff();
5871 /* NOTREACHED */
5875 argc -= optind;
5876 argv += optind;
5878 if (argc == 0) {
5879 usage_diff(); /* TODO show local worktree changes */
5880 } else if (argc == 2) {
5881 id_str1 = argv[0];
5882 id_str2 = argv[1];
5883 } else
5884 usage_diff();
5886 error = got_repo_pack_fds_open(&pack_fds);
5887 if (error)
5888 goto done;
5890 if (repo_path == NULL) {
5891 cwd = getcwd(NULL, 0);
5892 if (cwd == NULL)
5893 return got_error_from_errno("getcwd");
5894 error = got_worktree_open(&worktree, cwd);
5895 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5896 goto done;
5897 if (worktree)
5898 repo_path =
5899 strdup(got_worktree_get_repo_path(worktree));
5900 else
5901 repo_path = strdup(cwd);
5902 if (repo_path == NULL) {
5903 error = got_error_from_errno("strdup");
5904 goto done;
5908 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5909 if (error)
5910 goto done;
5912 init_curses();
5914 error = apply_unveil(got_repo_get_path(repo), NULL);
5915 if (error)
5916 goto done;
5918 error = tog_load_refs(repo, 0);
5919 if (error)
5920 goto done;
5922 error = got_repo_match_object_id(&id1, &label1, id_str1,
5923 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5924 if (error)
5925 goto done;
5927 error = got_repo_match_object_id(&id2, &label2, id_str2,
5928 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5929 if (error)
5930 goto done;
5932 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5933 if (view == NULL) {
5934 error = got_error_from_errno("view_open");
5935 goto done;
5937 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5938 ignore_whitespace, force_text_diff, NULL, repo);
5939 if (error)
5940 goto done;
5941 error = view_loop(view);
5942 done:
5943 free(label1);
5944 free(label2);
5945 free(repo_path);
5946 free(cwd);
5947 if (repo) {
5948 const struct got_error *close_err = got_repo_close(repo);
5949 if (error == NULL)
5950 error = close_err;
5952 if (worktree)
5953 got_worktree_close(worktree);
5954 if (pack_fds) {
5955 const struct got_error *pack_err =
5956 got_repo_pack_fds_close(pack_fds);
5957 if (error == NULL)
5958 error = pack_err;
5960 tog_free_refs();
5961 return error;
5964 __dead static void
5965 usage_blame(void)
5967 endwin();
5968 fprintf(stderr,
5969 "usage: %s blame [-c commit] [-r repository-path] path\n",
5970 getprogname());
5971 exit(1);
5974 struct tog_blame_line {
5975 int annotated;
5976 struct got_object_id *id;
5979 static const struct got_error *
5980 draw_blame(struct tog_view *view)
5982 struct tog_blame_view_state *s = &view->state.blame;
5983 struct tog_blame *blame = &s->blame;
5984 regmatch_t *regmatch = &view->regmatch;
5985 const struct got_error *err;
5986 int lineno = 0, nprinted = 0;
5987 char *line = NULL;
5988 size_t linesize = 0;
5989 ssize_t linelen;
5990 wchar_t *wline;
5991 int width;
5992 struct tog_blame_line *blame_line;
5993 struct got_object_id *prev_id = NULL;
5994 char *id_str;
5995 struct tog_color *tc;
5997 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5998 if (err)
5999 return err;
6001 rewind(blame->f);
6002 werase(view->window);
6004 if (asprintf(&line, "commit %s", id_str) == -1) {
6005 err = got_error_from_errno("asprintf");
6006 free(id_str);
6007 return err;
6010 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6011 free(line);
6012 line = NULL;
6013 if (err)
6014 return err;
6015 if (view_needs_focus_indication(view))
6016 wstandout(view->window);
6017 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6018 if (tc)
6019 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6020 waddwstr(view->window, wline);
6021 while (width++ < view->ncols)
6022 waddch(view->window, ' ');
6023 if (tc)
6024 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6025 if (view_needs_focus_indication(view))
6026 wstandend(view->window);
6027 free(wline);
6028 wline = NULL;
6030 if (view->gline > blame->nlines)
6031 view->gline = blame->nlines;
6033 if (tog_io.wait_for_ui) {
6034 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6035 int rc;
6037 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6038 if (rc)
6039 return got_error_set_errno(rc, "pthread_cond_wait");
6040 tog_io.wait_for_ui = 0;
6043 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6044 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6045 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6046 free(id_str);
6047 return got_error_from_errno("asprintf");
6049 free(id_str);
6050 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6051 free(line);
6052 line = NULL;
6053 if (err)
6054 return err;
6055 waddwstr(view->window, wline);
6056 free(wline);
6057 wline = NULL;
6058 if (width < view->ncols - 1)
6059 waddch(view->window, '\n');
6061 s->eof = 0;
6062 view->maxx = 0;
6063 while (nprinted < view->nlines - 2) {
6064 linelen = getline(&line, &linesize, blame->f);
6065 if (linelen == -1) {
6066 if (feof(blame->f)) {
6067 s->eof = 1;
6068 break;
6070 free(line);
6071 return got_ferror(blame->f, GOT_ERR_IO);
6073 if (++lineno < s->first_displayed_line)
6074 continue;
6075 if (view->gline && !gotoline(view, &lineno, &nprinted))
6076 continue;
6078 /* Set view->maxx based on full line length. */
6079 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6080 if (err) {
6081 free(line);
6082 return err;
6084 free(wline);
6085 wline = NULL;
6086 view->maxx = MAX(view->maxx, width);
6088 if (nprinted == s->selected_line - 1)
6089 wstandout(view->window);
6091 if (blame->nlines > 0) {
6092 blame_line = &blame->lines[lineno - 1];
6093 if (blame_line->annotated && prev_id &&
6094 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6095 !(nprinted == s->selected_line - 1)) {
6096 waddstr(view->window, " ");
6097 } else if (blame_line->annotated) {
6098 char *id_str;
6099 err = got_object_id_str(&id_str,
6100 blame_line->id);
6101 if (err) {
6102 free(line);
6103 return err;
6105 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6106 if (tc)
6107 wattr_on(view->window,
6108 COLOR_PAIR(tc->colorpair), NULL);
6109 wprintw(view->window, "%.8s", id_str);
6110 if (tc)
6111 wattr_off(view->window,
6112 COLOR_PAIR(tc->colorpair), NULL);
6113 free(id_str);
6114 prev_id = blame_line->id;
6115 } else {
6116 waddstr(view->window, "........");
6117 prev_id = NULL;
6119 } else {
6120 waddstr(view->window, "........");
6121 prev_id = NULL;
6124 if (nprinted == s->selected_line - 1)
6125 wstandend(view->window);
6126 waddstr(view->window, " ");
6128 if (view->ncols <= 9) {
6129 width = 9;
6130 } else if (s->first_displayed_line + nprinted ==
6131 s->matched_line &&
6132 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6133 err = add_matched_line(&width, line, view->ncols - 9, 9,
6134 view->window, view->x, regmatch);
6135 if (err) {
6136 free(line);
6137 return err;
6139 width += 9;
6140 } else {
6141 int skip;
6142 err = format_line(&wline, &width, &skip, line,
6143 view->x, view->ncols - 9, 9, 1);
6144 if (err) {
6145 free(line);
6146 return err;
6148 waddwstr(view->window, &wline[skip]);
6149 width += 9;
6150 free(wline);
6151 wline = NULL;
6154 if (width <= view->ncols - 1)
6155 waddch(view->window, '\n');
6156 if (++nprinted == 1)
6157 s->first_displayed_line = lineno;
6159 free(line);
6160 s->last_displayed_line = lineno;
6162 view_border(view);
6164 return NULL;
6167 static const struct got_error *
6168 blame_cb(void *arg, int nlines, int lineno,
6169 struct got_commit_object *commit, struct got_object_id *id)
6171 const struct got_error *err = NULL;
6172 struct tog_blame_cb_args *a = arg;
6173 struct tog_blame_line *line;
6174 int errcode;
6176 if (nlines != a->nlines ||
6177 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6178 return got_error(GOT_ERR_RANGE);
6180 errcode = pthread_mutex_lock(&tog_mutex);
6181 if (errcode)
6182 return got_error_set_errno(errcode, "pthread_mutex_lock");
6184 if (*a->quit) { /* user has quit the blame view */
6185 err = got_error(GOT_ERR_ITER_COMPLETED);
6186 goto done;
6189 if (lineno == -1)
6190 goto done; /* no change in this commit */
6192 line = &a->lines[lineno - 1];
6193 if (line->annotated)
6194 goto done;
6196 line->id = got_object_id_dup(id);
6197 if (line->id == NULL) {
6198 err = got_error_from_errno("got_object_id_dup");
6199 goto done;
6201 line->annotated = 1;
6202 done:
6203 errcode = pthread_mutex_unlock(&tog_mutex);
6204 if (errcode)
6205 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6206 return err;
6209 static void *
6210 blame_thread(void *arg)
6212 const struct got_error *err, *close_err;
6213 struct tog_blame_thread_args *ta = arg;
6214 struct tog_blame_cb_args *a = ta->cb_args;
6215 int errcode, fd1 = -1, fd2 = -1;
6216 FILE *f1 = NULL, *f2 = NULL;
6218 fd1 = got_opentempfd();
6219 if (fd1 == -1)
6220 return (void *)got_error_from_errno("got_opentempfd");
6222 fd2 = got_opentempfd();
6223 if (fd2 == -1) {
6224 err = got_error_from_errno("got_opentempfd");
6225 goto done;
6228 f1 = got_opentemp();
6229 if (f1 == NULL) {
6230 err = (void *)got_error_from_errno("got_opentemp");
6231 goto done;
6233 f2 = got_opentemp();
6234 if (f2 == NULL) {
6235 err = (void *)got_error_from_errno("got_opentemp");
6236 goto done;
6239 err = block_signals_used_by_main_thread();
6240 if (err)
6241 goto done;
6243 err = got_blame(ta->path, a->commit_id, ta->repo,
6244 tog_diff_algo, blame_cb, ta->cb_args,
6245 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6246 if (err && err->code == GOT_ERR_CANCELLED)
6247 err = NULL;
6249 errcode = pthread_mutex_lock(&tog_mutex);
6250 if (errcode) {
6251 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6252 goto done;
6255 close_err = got_repo_close(ta->repo);
6256 if (err == NULL)
6257 err = close_err;
6258 ta->repo = NULL;
6259 *ta->complete = 1;
6261 if (tog_io.wait_for_ui) {
6262 errcode = pthread_cond_signal(&ta->blame_complete);
6263 if (errcode && err == NULL)
6264 err = got_error_set_errno(errcode,
6265 "pthread_cond_signal");
6268 errcode = pthread_mutex_unlock(&tog_mutex);
6269 if (errcode && err == NULL)
6270 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6272 done:
6273 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6274 err = got_error_from_errno("close");
6275 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6276 err = got_error_from_errno("close");
6277 if (f1 && fclose(f1) == EOF && err == NULL)
6278 err = got_error_from_errno("fclose");
6279 if (f2 && fclose(f2) == EOF && err == NULL)
6280 err = got_error_from_errno("fclose");
6282 return (void *)err;
6285 static struct got_object_id *
6286 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6287 int first_displayed_line, int selected_line)
6289 struct tog_blame_line *line;
6291 if (nlines <= 0)
6292 return NULL;
6294 line = &lines[first_displayed_line - 1 + selected_line - 1];
6295 if (!line->annotated)
6296 return NULL;
6298 return line->id;
6301 static struct got_object_id *
6302 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6303 int lineno)
6305 struct tog_blame_line *line;
6307 if (nlines <= 0 || lineno >= nlines)
6308 return NULL;
6310 line = &lines[lineno - 1];
6311 if (!line->annotated)
6312 return NULL;
6314 return line->id;
6317 static const struct got_error *
6318 stop_blame(struct tog_blame *blame)
6320 const struct got_error *err = NULL;
6321 int i;
6323 if (blame->thread) {
6324 int errcode;
6325 errcode = pthread_mutex_unlock(&tog_mutex);
6326 if (errcode)
6327 return got_error_set_errno(errcode,
6328 "pthread_mutex_unlock");
6329 errcode = pthread_join(blame->thread, (void **)&err);
6330 if (errcode)
6331 return got_error_set_errno(errcode, "pthread_join");
6332 errcode = pthread_mutex_lock(&tog_mutex);
6333 if (errcode)
6334 return got_error_set_errno(errcode,
6335 "pthread_mutex_lock");
6336 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6337 err = NULL;
6338 blame->thread = NULL;
6340 if (blame->thread_args.repo) {
6341 const struct got_error *close_err;
6342 close_err = got_repo_close(blame->thread_args.repo);
6343 if (err == NULL)
6344 err = close_err;
6345 blame->thread_args.repo = NULL;
6347 if (blame->f) {
6348 if (fclose(blame->f) == EOF && err == NULL)
6349 err = got_error_from_errno("fclose");
6350 blame->f = NULL;
6352 if (blame->lines) {
6353 for (i = 0; i < blame->nlines; i++)
6354 free(blame->lines[i].id);
6355 free(blame->lines);
6356 blame->lines = NULL;
6358 free(blame->cb_args.commit_id);
6359 blame->cb_args.commit_id = NULL;
6360 if (blame->pack_fds) {
6361 const struct got_error *pack_err =
6362 got_repo_pack_fds_close(blame->pack_fds);
6363 if (err == NULL)
6364 err = pack_err;
6365 blame->pack_fds = NULL;
6367 return err;
6370 static const struct got_error *
6371 cancel_blame_view(void *arg)
6373 const struct got_error *err = NULL;
6374 int *done = arg;
6375 int errcode;
6377 errcode = pthread_mutex_lock(&tog_mutex);
6378 if (errcode)
6379 return got_error_set_errno(errcode,
6380 "pthread_mutex_unlock");
6382 if (*done)
6383 err = got_error(GOT_ERR_CANCELLED);
6385 errcode = pthread_mutex_unlock(&tog_mutex);
6386 if (errcode)
6387 return got_error_set_errno(errcode,
6388 "pthread_mutex_lock");
6390 return err;
6393 static const struct got_error *
6394 run_blame(struct tog_view *view)
6396 struct tog_blame_view_state *s = &view->state.blame;
6397 struct tog_blame *blame = &s->blame;
6398 const struct got_error *err = NULL;
6399 struct got_commit_object *commit = NULL;
6400 struct got_blob_object *blob = NULL;
6401 struct got_repository *thread_repo = NULL;
6402 struct got_object_id *obj_id = NULL;
6403 int obj_type, fd = -1;
6404 int *pack_fds = NULL;
6406 err = got_object_open_as_commit(&commit, s->repo,
6407 &s->blamed_commit->id);
6408 if (err)
6409 return err;
6411 fd = got_opentempfd();
6412 if (fd == -1) {
6413 err = got_error_from_errno("got_opentempfd");
6414 goto done;
6417 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6418 if (err)
6419 goto done;
6421 err = got_object_get_type(&obj_type, s->repo, obj_id);
6422 if (err)
6423 goto done;
6425 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6426 err = got_error(GOT_ERR_OBJ_TYPE);
6427 goto done;
6430 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6431 if (err)
6432 goto done;
6433 blame->f = got_opentemp();
6434 if (blame->f == NULL) {
6435 err = got_error_from_errno("got_opentemp");
6436 goto done;
6438 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6439 &blame->line_offsets, blame->f, blob);
6440 if (err)
6441 goto done;
6442 if (blame->nlines == 0) {
6443 s->blame_complete = 1;
6444 goto done;
6447 /* Don't include \n at EOF in the blame line count. */
6448 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6449 blame->nlines--;
6451 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6452 if (blame->lines == NULL) {
6453 err = got_error_from_errno("calloc");
6454 goto done;
6457 err = got_repo_pack_fds_open(&pack_fds);
6458 if (err)
6459 goto done;
6460 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6461 pack_fds);
6462 if (err)
6463 goto done;
6465 blame->pack_fds = pack_fds;
6466 blame->cb_args.view = view;
6467 blame->cb_args.lines = blame->lines;
6468 blame->cb_args.nlines = blame->nlines;
6469 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6470 if (blame->cb_args.commit_id == NULL) {
6471 err = got_error_from_errno("got_object_id_dup");
6472 goto done;
6474 blame->cb_args.quit = &s->done;
6476 blame->thread_args.path = s->path;
6477 blame->thread_args.repo = thread_repo;
6478 blame->thread_args.cb_args = &blame->cb_args;
6479 blame->thread_args.complete = &s->blame_complete;
6480 blame->thread_args.cancel_cb = cancel_blame_view;
6481 blame->thread_args.cancel_arg = &s->done;
6482 s->blame_complete = 0;
6484 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6485 s->first_displayed_line = 1;
6486 s->last_displayed_line = view->nlines;
6487 s->selected_line = 1;
6489 s->matched_line = 0;
6491 done:
6492 if (commit)
6493 got_object_commit_close(commit);
6494 if (fd != -1 && close(fd) == -1 && err == NULL)
6495 err = got_error_from_errno("close");
6496 if (blob)
6497 got_object_blob_close(blob);
6498 free(obj_id);
6499 if (err)
6500 stop_blame(blame);
6501 return err;
6504 static const struct got_error *
6505 open_blame_view(struct tog_view *view, char *path,
6506 struct got_object_id *commit_id, struct got_repository *repo)
6508 const struct got_error *err = NULL;
6509 struct tog_blame_view_state *s = &view->state.blame;
6511 STAILQ_INIT(&s->blamed_commits);
6513 s->path = strdup(path);
6514 if (s->path == NULL)
6515 return got_error_from_errno("strdup");
6517 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6518 if (err) {
6519 free(s->path);
6520 return err;
6523 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6524 s->first_displayed_line = 1;
6525 s->last_displayed_line = view->nlines;
6526 s->selected_line = 1;
6527 s->blame_complete = 0;
6528 s->repo = repo;
6529 s->commit_id = commit_id;
6530 memset(&s->blame, 0, sizeof(s->blame));
6532 STAILQ_INIT(&s->colors);
6533 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6534 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6535 get_color_value("TOG_COLOR_COMMIT"));
6536 if (err)
6537 return err;
6540 view->show = show_blame_view;
6541 view->input = input_blame_view;
6542 view->reset = reset_blame_view;
6543 view->close = close_blame_view;
6544 view->search_start = search_start_blame_view;
6545 view->search_setup = search_setup_blame_view;
6546 view->search_next = search_next_view_match;
6548 if (using_mock_io) {
6549 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6550 int rc;
6552 rc = pthread_cond_init(&bta->blame_complete, NULL);
6553 if (rc)
6554 return got_error_set_errno(rc, "pthread_cond_init");
6557 return run_blame(view);
6560 static const struct got_error *
6561 close_blame_view(struct tog_view *view)
6563 const struct got_error *err = NULL;
6564 struct tog_blame_view_state *s = &view->state.blame;
6566 if (s->blame.thread)
6567 err = stop_blame(&s->blame);
6569 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6570 struct got_object_qid *blamed_commit;
6571 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6572 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6573 got_object_qid_free(blamed_commit);
6576 if (using_mock_io) {
6577 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6578 int rc;
6580 rc = pthread_cond_destroy(&bta->blame_complete);
6581 if (rc && err == NULL)
6582 err = got_error_set_errno(rc, "pthread_cond_destroy");
6585 free(s->path);
6586 free_colors(&s->colors);
6587 return err;
6590 static const struct got_error *
6591 search_start_blame_view(struct tog_view *view)
6593 struct tog_blame_view_state *s = &view->state.blame;
6595 s->matched_line = 0;
6596 return NULL;
6599 static void
6600 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6601 size_t *nlines, int **first, int **last, int **match, int **selected)
6603 struct tog_blame_view_state *s = &view->state.blame;
6605 *f = s->blame.f;
6606 *nlines = s->blame.nlines;
6607 *line_offsets = s->blame.line_offsets;
6608 *match = &s->matched_line;
6609 *first = &s->first_displayed_line;
6610 *last = &s->last_displayed_line;
6611 *selected = &s->selected_line;
6614 static const struct got_error *
6615 show_blame_view(struct tog_view *view)
6617 const struct got_error *err = NULL;
6618 struct tog_blame_view_state *s = &view->state.blame;
6619 int errcode;
6621 if (s->blame.thread == NULL && !s->blame_complete) {
6622 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6623 &s->blame.thread_args);
6624 if (errcode)
6625 return got_error_set_errno(errcode, "pthread_create");
6627 if (!using_mock_io)
6628 halfdelay(1); /* fast refresh while annotating */
6631 if (s->blame_complete && !using_mock_io)
6632 halfdelay(10); /* disable fast refresh */
6634 err = draw_blame(view);
6636 view_border(view);
6637 return err;
6640 static const struct got_error *
6641 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6642 struct got_repository *repo, struct got_object_id *id)
6644 struct tog_view *log_view;
6645 const struct got_error *err = NULL;
6647 *new_view = NULL;
6649 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6650 if (log_view == NULL)
6651 return got_error_from_errno("view_open");
6653 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6654 if (err)
6655 view_close(log_view);
6656 else
6657 *new_view = log_view;
6659 return err;
6662 static const struct got_error *
6663 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6665 const struct got_error *err = NULL, *thread_err = NULL;
6666 struct tog_view *diff_view;
6667 struct tog_blame_view_state *s = &view->state.blame;
6668 int eos, nscroll, begin_y = 0, begin_x = 0;
6670 eos = nscroll = view->nlines - 2;
6671 if (view_is_hsplit_top(view))
6672 --eos; /* border */
6674 switch (ch) {
6675 case '0':
6676 case '$':
6677 case KEY_RIGHT:
6678 case 'l':
6679 case KEY_LEFT:
6680 case 'h':
6681 horizontal_scroll_input(view, ch);
6682 break;
6683 case 'q':
6684 s->done = 1;
6685 break;
6686 case 'g':
6687 case KEY_HOME:
6688 s->selected_line = 1;
6689 s->first_displayed_line = 1;
6690 view->count = 0;
6691 break;
6692 case 'G':
6693 case KEY_END:
6694 if (s->blame.nlines < eos) {
6695 s->selected_line = s->blame.nlines;
6696 s->first_displayed_line = 1;
6697 } else {
6698 s->selected_line = eos;
6699 s->first_displayed_line = s->blame.nlines - (eos - 1);
6701 view->count = 0;
6702 break;
6703 case 'k':
6704 case KEY_UP:
6705 case CTRL('p'):
6706 if (s->selected_line > 1)
6707 s->selected_line--;
6708 else if (s->selected_line == 1 &&
6709 s->first_displayed_line > 1)
6710 s->first_displayed_line--;
6711 else
6712 view->count = 0;
6713 break;
6714 case CTRL('u'):
6715 case 'u':
6716 nscroll /= 2;
6717 /* FALL THROUGH */
6718 case KEY_PPAGE:
6719 case CTRL('b'):
6720 case 'b':
6721 if (s->first_displayed_line == 1) {
6722 if (view->count > 1)
6723 nscroll += nscroll;
6724 s->selected_line = MAX(1, s->selected_line - nscroll);
6725 view->count = 0;
6726 break;
6728 if (s->first_displayed_line > nscroll)
6729 s->first_displayed_line -= nscroll;
6730 else
6731 s->first_displayed_line = 1;
6732 break;
6733 case 'j':
6734 case KEY_DOWN:
6735 case CTRL('n'):
6736 if (s->selected_line < eos && s->first_displayed_line +
6737 s->selected_line <= s->blame.nlines)
6738 s->selected_line++;
6739 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6740 s->first_displayed_line++;
6741 else
6742 view->count = 0;
6743 break;
6744 case 'c':
6745 case 'p': {
6746 struct got_object_id *id = NULL;
6748 view->count = 0;
6749 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6750 s->first_displayed_line, s->selected_line);
6751 if (id == NULL)
6752 break;
6753 if (ch == 'p') {
6754 struct got_commit_object *commit, *pcommit;
6755 struct got_object_qid *pid;
6756 struct got_object_id *blob_id = NULL;
6757 int obj_type;
6758 err = got_object_open_as_commit(&commit,
6759 s->repo, id);
6760 if (err)
6761 break;
6762 pid = STAILQ_FIRST(
6763 got_object_commit_get_parent_ids(commit));
6764 if (pid == NULL) {
6765 got_object_commit_close(commit);
6766 break;
6768 /* Check if path history ends here. */
6769 err = got_object_open_as_commit(&pcommit,
6770 s->repo, &pid->id);
6771 if (err)
6772 break;
6773 err = got_object_id_by_path(&blob_id, s->repo,
6774 pcommit, s->path);
6775 got_object_commit_close(pcommit);
6776 if (err) {
6777 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6778 err = NULL;
6779 got_object_commit_close(commit);
6780 break;
6782 err = got_object_get_type(&obj_type, s->repo,
6783 blob_id);
6784 free(blob_id);
6785 /* Can't blame non-blob type objects. */
6786 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6787 got_object_commit_close(commit);
6788 break;
6790 err = got_object_qid_alloc(&s->blamed_commit,
6791 &pid->id);
6792 got_object_commit_close(commit);
6793 } else {
6794 if (got_object_id_cmp(id,
6795 &s->blamed_commit->id) == 0)
6796 break;
6797 err = got_object_qid_alloc(&s->blamed_commit,
6798 id);
6800 if (err)
6801 break;
6802 s->done = 1;
6803 thread_err = stop_blame(&s->blame);
6804 s->done = 0;
6805 if (thread_err)
6806 break;
6807 STAILQ_INSERT_HEAD(&s->blamed_commits,
6808 s->blamed_commit, entry);
6809 err = run_blame(view);
6810 if (err)
6811 break;
6812 break;
6814 case 'C': {
6815 struct got_object_qid *first;
6817 view->count = 0;
6818 first = STAILQ_FIRST(&s->blamed_commits);
6819 if (!got_object_id_cmp(&first->id, s->commit_id))
6820 break;
6821 s->done = 1;
6822 thread_err = stop_blame(&s->blame);
6823 s->done = 0;
6824 if (thread_err)
6825 break;
6826 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6827 got_object_qid_free(s->blamed_commit);
6828 s->blamed_commit =
6829 STAILQ_FIRST(&s->blamed_commits);
6830 err = run_blame(view);
6831 if (err)
6832 break;
6833 break;
6835 case 'L':
6836 view->count = 0;
6837 s->id_to_log = get_selected_commit_id(s->blame.lines,
6838 s->blame.nlines, s->first_displayed_line, s->selected_line);
6839 if (s->id_to_log)
6840 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6841 break;
6842 case KEY_ENTER:
6843 case '\r': {
6844 struct got_object_id *id = NULL;
6845 struct got_object_qid *pid;
6846 struct got_commit_object *commit = NULL;
6848 view->count = 0;
6849 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6850 s->first_displayed_line, s->selected_line);
6851 if (id == NULL)
6852 break;
6853 err = got_object_open_as_commit(&commit, s->repo, id);
6854 if (err)
6855 break;
6856 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6857 if (*new_view) {
6858 /* traversed from diff view, release diff resources */
6859 err = close_diff_view(*new_view);
6860 if (err)
6861 break;
6862 diff_view = *new_view;
6863 } else {
6864 if (view_is_parent_view(view))
6865 view_get_split(view, &begin_y, &begin_x);
6867 diff_view = view_open(0, 0, begin_y, begin_x,
6868 TOG_VIEW_DIFF);
6869 if (diff_view == NULL) {
6870 got_object_commit_close(commit);
6871 err = got_error_from_errno("view_open");
6872 break;
6875 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6876 id, NULL, NULL, 3, 0, 0, view, s->repo);
6877 got_object_commit_close(commit);
6878 if (err) {
6879 view_close(diff_view);
6880 break;
6882 s->last_diffed_line = s->first_displayed_line - 1 +
6883 s->selected_line;
6884 if (*new_view)
6885 break; /* still open from active diff view */
6886 if (view_is_parent_view(view) &&
6887 view->mode == TOG_VIEW_SPLIT_HRZN) {
6888 err = view_init_hsplit(view, begin_y);
6889 if (err)
6890 break;
6893 view->focussed = 0;
6894 diff_view->focussed = 1;
6895 diff_view->mode = view->mode;
6896 diff_view->nlines = view->lines - begin_y;
6897 if (view_is_parent_view(view)) {
6898 view_transfer_size(diff_view, view);
6899 err = view_close_child(view);
6900 if (err)
6901 break;
6902 err = view_set_child(view, diff_view);
6903 if (err)
6904 break;
6905 view->focus_child = 1;
6906 } else
6907 *new_view = diff_view;
6908 if (err)
6909 break;
6910 break;
6912 case CTRL('d'):
6913 case 'd':
6914 nscroll /= 2;
6915 /* FALL THROUGH */
6916 case KEY_NPAGE:
6917 case CTRL('f'):
6918 case 'f':
6919 case ' ':
6920 if (s->last_displayed_line >= s->blame.nlines &&
6921 s->selected_line >= MIN(s->blame.nlines,
6922 view->nlines - 2)) {
6923 view->count = 0;
6924 break;
6926 if (s->last_displayed_line >= s->blame.nlines &&
6927 s->selected_line < view->nlines - 2) {
6928 s->selected_line +=
6929 MIN(nscroll, s->last_displayed_line -
6930 s->first_displayed_line - s->selected_line + 1);
6932 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6933 s->first_displayed_line += nscroll;
6934 else
6935 s->first_displayed_line =
6936 s->blame.nlines - (view->nlines - 3);
6937 break;
6938 case KEY_RESIZE:
6939 if (s->selected_line > view->nlines - 2) {
6940 s->selected_line = MIN(s->blame.nlines,
6941 view->nlines - 2);
6943 break;
6944 default:
6945 view->count = 0;
6946 break;
6948 return thread_err ? thread_err : err;
6951 static const struct got_error *
6952 reset_blame_view(struct tog_view *view)
6954 const struct got_error *err;
6955 struct tog_blame_view_state *s = &view->state.blame;
6957 view->count = 0;
6958 s->done = 1;
6959 err = stop_blame(&s->blame);
6960 s->done = 0;
6961 if (err)
6962 return err;
6963 return run_blame(view);
6966 static const struct got_error *
6967 cmd_blame(int argc, char *argv[])
6969 const struct got_error *error;
6970 struct got_repository *repo = NULL;
6971 struct got_worktree *worktree = NULL;
6972 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6973 char *link_target = NULL;
6974 struct got_object_id *commit_id = NULL;
6975 struct got_commit_object *commit = NULL;
6976 char *commit_id_str = NULL;
6977 int ch;
6978 struct tog_view *view = NULL;
6979 int *pack_fds = NULL;
6981 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6982 switch (ch) {
6983 case 'c':
6984 commit_id_str = optarg;
6985 break;
6986 case 'r':
6987 repo_path = realpath(optarg, NULL);
6988 if (repo_path == NULL)
6989 return got_error_from_errno2("realpath",
6990 optarg);
6991 break;
6992 default:
6993 usage_blame();
6994 /* NOTREACHED */
6998 argc -= optind;
6999 argv += optind;
7001 if (argc != 1)
7002 usage_blame();
7004 error = got_repo_pack_fds_open(&pack_fds);
7005 if (error != NULL)
7006 goto done;
7008 if (repo_path == NULL) {
7009 cwd = getcwd(NULL, 0);
7010 if (cwd == NULL)
7011 return got_error_from_errno("getcwd");
7012 error = got_worktree_open(&worktree, cwd);
7013 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7014 goto done;
7015 if (worktree)
7016 repo_path =
7017 strdup(got_worktree_get_repo_path(worktree));
7018 else
7019 repo_path = strdup(cwd);
7020 if (repo_path == NULL) {
7021 error = got_error_from_errno("strdup");
7022 goto done;
7026 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7027 if (error != NULL)
7028 goto done;
7030 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7031 worktree);
7032 if (error)
7033 goto done;
7035 init_curses();
7037 error = apply_unveil(got_repo_get_path(repo), NULL);
7038 if (error)
7039 goto done;
7041 error = tog_load_refs(repo, 0);
7042 if (error)
7043 goto done;
7045 if (commit_id_str == NULL) {
7046 struct got_reference *head_ref;
7047 error = got_ref_open(&head_ref, repo, worktree ?
7048 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7049 if (error != NULL)
7050 goto done;
7051 error = got_ref_resolve(&commit_id, repo, head_ref);
7052 got_ref_close(head_ref);
7053 } else {
7054 error = got_repo_match_object_id(&commit_id, NULL,
7055 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7057 if (error != NULL)
7058 goto done;
7060 error = got_object_open_as_commit(&commit, repo, commit_id);
7061 if (error)
7062 goto done;
7064 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7065 commit, repo);
7066 if (error)
7067 goto done;
7069 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7070 if (view == NULL) {
7071 error = got_error_from_errno("view_open");
7072 goto done;
7074 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7075 commit_id, repo);
7076 if (error != NULL) {
7077 if (view->close == NULL)
7078 close_blame_view(view);
7079 view_close(view);
7080 goto done;
7082 if (worktree) {
7083 /* Release work tree lock. */
7084 got_worktree_close(worktree);
7085 worktree = NULL;
7087 error = view_loop(view);
7088 done:
7089 free(repo_path);
7090 free(in_repo_path);
7091 free(link_target);
7092 free(cwd);
7093 free(commit_id);
7094 if (commit)
7095 got_object_commit_close(commit);
7096 if (worktree)
7097 got_worktree_close(worktree);
7098 if (repo) {
7099 const struct got_error *close_err = got_repo_close(repo);
7100 if (error == NULL)
7101 error = close_err;
7103 if (pack_fds) {
7104 const struct got_error *pack_err =
7105 got_repo_pack_fds_close(pack_fds);
7106 if (error == NULL)
7107 error = pack_err;
7109 tog_free_refs();
7110 return error;
7113 static const struct got_error *
7114 draw_tree_entries(struct tog_view *view, const char *parent_path)
7116 struct tog_tree_view_state *s = &view->state.tree;
7117 const struct got_error *err = NULL;
7118 struct got_tree_entry *te;
7119 wchar_t *wline;
7120 char *index = NULL;
7121 struct tog_color *tc;
7122 int width, n, nentries, scrollx, i = 1;
7123 int limit = view->nlines;
7125 s->ndisplayed = 0;
7126 if (view_is_hsplit_top(view))
7127 --limit; /* border */
7129 werase(view->window);
7131 if (limit == 0)
7132 return NULL;
7134 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7135 0, 0);
7136 if (err)
7137 return err;
7138 if (view_needs_focus_indication(view))
7139 wstandout(view->window);
7140 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7141 if (tc)
7142 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7143 waddwstr(view->window, wline);
7144 free(wline);
7145 wline = NULL;
7146 while (width++ < view->ncols)
7147 waddch(view->window, ' ');
7148 if (tc)
7149 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7150 if (view_needs_focus_indication(view))
7151 wstandend(view->window);
7152 if (--limit <= 0)
7153 return NULL;
7155 i += s->selected;
7156 if (s->first_displayed_entry) {
7157 i += got_tree_entry_get_index(s->first_displayed_entry);
7158 if (s->tree != s->root)
7159 ++i; /* account for ".." entry */
7161 nentries = got_object_tree_get_nentries(s->tree);
7162 if (asprintf(&index, "[%d/%d] %s",
7163 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7164 return got_error_from_errno("asprintf");
7165 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7166 free(index);
7167 if (err)
7168 return err;
7169 waddwstr(view->window, wline);
7170 free(wline);
7171 wline = NULL;
7172 if (width < view->ncols - 1)
7173 waddch(view->window, '\n');
7174 if (--limit <= 0)
7175 return NULL;
7176 waddch(view->window, '\n');
7177 if (--limit <= 0)
7178 return NULL;
7180 if (s->first_displayed_entry == NULL) {
7181 te = got_object_tree_get_first_entry(s->tree);
7182 if (s->selected == 0) {
7183 if (view->focussed)
7184 wstandout(view->window);
7185 s->selected_entry = NULL;
7187 waddstr(view->window, " ..\n"); /* parent directory */
7188 if (s->selected == 0 && view->focussed)
7189 wstandend(view->window);
7190 s->ndisplayed++;
7191 if (--limit <= 0)
7192 return NULL;
7193 n = 1;
7194 } else {
7195 n = 0;
7196 te = s->first_displayed_entry;
7199 view->maxx = 0;
7200 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7201 char *line = NULL, *id_str = NULL, *link_target = NULL;
7202 const char *modestr = "";
7203 mode_t mode;
7205 te = got_object_tree_get_entry(s->tree, i);
7206 mode = got_tree_entry_get_mode(te);
7208 if (s->show_ids) {
7209 err = got_object_id_str(&id_str,
7210 got_tree_entry_get_id(te));
7211 if (err)
7212 return got_error_from_errno(
7213 "got_object_id_str");
7215 if (got_object_tree_entry_is_submodule(te))
7216 modestr = "$";
7217 else if (S_ISLNK(mode)) {
7218 int i;
7220 err = got_tree_entry_get_symlink_target(&link_target,
7221 te, s->repo);
7222 if (err) {
7223 free(id_str);
7224 return err;
7226 for (i = 0; i < strlen(link_target); i++) {
7227 if (!isprint((unsigned char)link_target[i]))
7228 link_target[i] = '?';
7230 modestr = "@";
7232 else if (S_ISDIR(mode))
7233 modestr = "/";
7234 else if (mode & S_IXUSR)
7235 modestr = "*";
7236 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7237 got_tree_entry_get_name(te), modestr,
7238 link_target ? " -> ": "",
7239 link_target ? link_target : "") == -1) {
7240 free(id_str);
7241 free(link_target);
7242 return got_error_from_errno("asprintf");
7244 free(id_str);
7245 free(link_target);
7247 /* use full line width to determine view->maxx */
7248 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7249 if (err) {
7250 free(line);
7251 break;
7253 view->maxx = MAX(view->maxx, width);
7254 free(wline);
7255 wline = NULL;
7257 err = format_line(&wline, &width, &scrollx, line, view->x,
7258 view->ncols, 0, 0);
7259 if (err) {
7260 free(line);
7261 break;
7263 if (n == s->selected) {
7264 if (view->focussed)
7265 wstandout(view->window);
7266 s->selected_entry = te;
7268 tc = match_color(&s->colors, line);
7269 if (tc)
7270 wattr_on(view->window,
7271 COLOR_PAIR(tc->colorpair), NULL);
7272 waddwstr(view->window, &wline[scrollx]);
7273 if (tc)
7274 wattr_off(view->window,
7275 COLOR_PAIR(tc->colorpair), NULL);
7276 if (width < view->ncols)
7277 waddch(view->window, '\n');
7278 if (n == s->selected && view->focussed)
7279 wstandend(view->window);
7280 free(line);
7281 free(wline);
7282 wline = NULL;
7283 n++;
7284 s->ndisplayed++;
7285 s->last_displayed_entry = te;
7286 if (--limit <= 0)
7287 break;
7290 return err;
7293 static void
7294 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7296 struct got_tree_entry *te;
7297 int isroot = s->tree == s->root;
7298 int i = 0;
7300 if (s->first_displayed_entry == NULL)
7301 return;
7303 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7304 while (i++ < maxscroll) {
7305 if (te == NULL) {
7306 if (!isroot)
7307 s->first_displayed_entry = NULL;
7308 break;
7310 s->first_displayed_entry = te;
7311 te = got_tree_entry_get_prev(s->tree, te);
7315 static const struct got_error *
7316 tree_scroll_down(struct tog_view *view, int maxscroll)
7318 struct tog_tree_view_state *s = &view->state.tree;
7319 struct got_tree_entry *next, *last;
7320 int n = 0;
7322 if (s->first_displayed_entry)
7323 next = got_tree_entry_get_next(s->tree,
7324 s->first_displayed_entry);
7325 else
7326 next = got_object_tree_get_first_entry(s->tree);
7328 last = s->last_displayed_entry;
7329 while (next && n++ < maxscroll) {
7330 if (last) {
7331 s->last_displayed_entry = last;
7332 last = got_tree_entry_get_next(s->tree, last);
7334 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7335 s->first_displayed_entry = next;
7336 next = got_tree_entry_get_next(s->tree, next);
7340 return NULL;
7343 static const struct got_error *
7344 tree_entry_path(char **path, struct tog_parent_trees *parents,
7345 struct got_tree_entry *te)
7347 const struct got_error *err = NULL;
7348 struct tog_parent_tree *pt;
7349 size_t len = 2; /* for leading slash and NUL */
7351 TAILQ_FOREACH(pt, parents, entry)
7352 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7353 + 1 /* slash */;
7354 if (te)
7355 len += strlen(got_tree_entry_get_name(te));
7357 *path = calloc(1, len);
7358 if (path == NULL)
7359 return got_error_from_errno("calloc");
7361 (*path)[0] = '/';
7362 pt = TAILQ_LAST(parents, tog_parent_trees);
7363 while (pt) {
7364 const char *name = got_tree_entry_get_name(pt->selected_entry);
7365 if (strlcat(*path, name, len) >= len) {
7366 err = got_error(GOT_ERR_NO_SPACE);
7367 goto done;
7369 if (strlcat(*path, "/", len) >= len) {
7370 err = got_error(GOT_ERR_NO_SPACE);
7371 goto done;
7373 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7375 if (te) {
7376 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7377 err = got_error(GOT_ERR_NO_SPACE);
7378 goto done;
7381 done:
7382 if (err) {
7383 free(*path);
7384 *path = NULL;
7386 return err;
7389 static const struct got_error *
7390 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7391 struct got_tree_entry *te, struct tog_parent_trees *parents,
7392 struct got_object_id *commit_id, struct got_repository *repo)
7394 const struct got_error *err = NULL;
7395 char *path;
7396 struct tog_view *blame_view;
7398 *new_view = NULL;
7400 err = tree_entry_path(&path, parents, te);
7401 if (err)
7402 return err;
7404 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7405 if (blame_view == NULL) {
7406 err = got_error_from_errno("view_open");
7407 goto done;
7410 err = open_blame_view(blame_view, path, commit_id, repo);
7411 if (err) {
7412 if (err->code == GOT_ERR_CANCELLED)
7413 err = NULL;
7414 view_close(blame_view);
7415 } else
7416 *new_view = blame_view;
7417 done:
7418 free(path);
7419 return err;
7422 static const struct got_error *
7423 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7424 struct tog_tree_view_state *s)
7426 struct tog_view *log_view;
7427 const struct got_error *err = NULL;
7428 char *path;
7430 *new_view = NULL;
7432 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7433 if (log_view == NULL)
7434 return got_error_from_errno("view_open");
7436 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7437 if (err)
7438 return err;
7440 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7441 path, 0);
7442 if (err)
7443 view_close(log_view);
7444 else
7445 *new_view = log_view;
7446 free(path);
7447 return err;
7450 static const struct got_error *
7451 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7452 const char *head_ref_name, struct got_repository *repo)
7454 const struct got_error *err = NULL;
7455 char *commit_id_str = NULL;
7456 struct tog_tree_view_state *s = &view->state.tree;
7457 struct got_commit_object *commit = NULL;
7459 TAILQ_INIT(&s->parents);
7460 STAILQ_INIT(&s->colors);
7462 s->commit_id = got_object_id_dup(commit_id);
7463 if (s->commit_id == NULL) {
7464 err = got_error_from_errno("got_object_id_dup");
7465 goto done;
7468 err = got_object_open_as_commit(&commit, repo, commit_id);
7469 if (err)
7470 goto done;
7473 * The root is opened here and will be closed when the view is closed.
7474 * Any visited subtrees and their path-wise parents are opened and
7475 * closed on demand.
7477 err = got_object_open_as_tree(&s->root, repo,
7478 got_object_commit_get_tree_id(commit));
7479 if (err)
7480 goto done;
7481 s->tree = s->root;
7483 err = got_object_id_str(&commit_id_str, commit_id);
7484 if (err != NULL)
7485 goto done;
7487 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7488 err = got_error_from_errno("asprintf");
7489 goto done;
7492 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7493 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7494 if (head_ref_name) {
7495 s->head_ref_name = strdup(head_ref_name);
7496 if (s->head_ref_name == NULL) {
7497 err = got_error_from_errno("strdup");
7498 goto done;
7501 s->repo = repo;
7503 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7504 err = add_color(&s->colors, "\\$$",
7505 TOG_COLOR_TREE_SUBMODULE,
7506 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7507 if (err)
7508 goto done;
7509 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7510 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7511 if (err)
7512 goto done;
7513 err = add_color(&s->colors, "/$",
7514 TOG_COLOR_TREE_DIRECTORY,
7515 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7516 if (err)
7517 goto done;
7519 err = add_color(&s->colors, "\\*$",
7520 TOG_COLOR_TREE_EXECUTABLE,
7521 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7522 if (err)
7523 goto done;
7525 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7526 get_color_value("TOG_COLOR_COMMIT"));
7527 if (err)
7528 goto done;
7531 view->show = show_tree_view;
7532 view->input = input_tree_view;
7533 view->close = close_tree_view;
7534 view->search_start = search_start_tree_view;
7535 view->search_next = search_next_tree_view;
7536 done:
7537 free(commit_id_str);
7538 if (commit)
7539 got_object_commit_close(commit);
7540 if (err) {
7541 if (view->close == NULL)
7542 close_tree_view(view);
7543 view_close(view);
7545 return err;
7548 static const struct got_error *
7549 close_tree_view(struct tog_view *view)
7551 struct tog_tree_view_state *s = &view->state.tree;
7553 free_colors(&s->colors);
7554 free(s->tree_label);
7555 s->tree_label = NULL;
7556 free(s->commit_id);
7557 s->commit_id = NULL;
7558 free(s->head_ref_name);
7559 s->head_ref_name = NULL;
7560 while (!TAILQ_EMPTY(&s->parents)) {
7561 struct tog_parent_tree *parent;
7562 parent = TAILQ_FIRST(&s->parents);
7563 TAILQ_REMOVE(&s->parents, parent, entry);
7564 if (parent->tree != s->root)
7565 got_object_tree_close(parent->tree);
7566 free(parent);
7569 if (s->tree != NULL && s->tree != s->root)
7570 got_object_tree_close(s->tree);
7571 if (s->root)
7572 got_object_tree_close(s->root);
7573 return NULL;
7576 static const struct got_error *
7577 search_start_tree_view(struct tog_view *view)
7579 struct tog_tree_view_state *s = &view->state.tree;
7581 s->matched_entry = NULL;
7582 return NULL;
7585 static int
7586 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7588 regmatch_t regmatch;
7590 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7591 0) == 0;
7594 static const struct got_error *
7595 search_next_tree_view(struct tog_view *view)
7597 struct tog_tree_view_state *s = &view->state.tree;
7598 struct got_tree_entry *te = NULL;
7600 if (!view->searching) {
7601 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7602 return NULL;
7605 if (s->matched_entry) {
7606 if (view->searching == TOG_SEARCH_FORWARD) {
7607 if (s->selected_entry)
7608 te = got_tree_entry_get_next(s->tree,
7609 s->selected_entry);
7610 else
7611 te = got_object_tree_get_first_entry(s->tree);
7612 } else {
7613 if (s->selected_entry == NULL)
7614 te = got_object_tree_get_last_entry(s->tree);
7615 else
7616 te = got_tree_entry_get_prev(s->tree,
7617 s->selected_entry);
7619 } else {
7620 if (s->selected_entry)
7621 te = s->selected_entry;
7622 else if (view->searching == TOG_SEARCH_FORWARD)
7623 te = got_object_tree_get_first_entry(s->tree);
7624 else
7625 te = got_object_tree_get_last_entry(s->tree);
7628 while (1) {
7629 if (te == NULL) {
7630 if (s->matched_entry == NULL) {
7631 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7632 return NULL;
7634 if (view->searching == TOG_SEARCH_FORWARD)
7635 te = got_object_tree_get_first_entry(s->tree);
7636 else
7637 te = got_object_tree_get_last_entry(s->tree);
7640 if (match_tree_entry(te, &view->regex)) {
7641 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7642 s->matched_entry = te;
7643 break;
7646 if (view->searching == TOG_SEARCH_FORWARD)
7647 te = got_tree_entry_get_next(s->tree, te);
7648 else
7649 te = got_tree_entry_get_prev(s->tree, te);
7652 if (s->matched_entry) {
7653 s->first_displayed_entry = s->matched_entry;
7654 s->selected = 0;
7657 return NULL;
7660 static const struct got_error *
7661 show_tree_view(struct tog_view *view)
7663 const struct got_error *err = NULL;
7664 struct tog_tree_view_state *s = &view->state.tree;
7665 char *parent_path;
7667 err = tree_entry_path(&parent_path, &s->parents, NULL);
7668 if (err)
7669 return err;
7671 err = draw_tree_entries(view, parent_path);
7672 free(parent_path);
7674 view_border(view);
7675 return err;
7678 static const struct got_error *
7679 tree_goto_line(struct tog_view *view, int nlines)
7681 const struct got_error *err = NULL;
7682 struct tog_tree_view_state *s = &view->state.tree;
7683 struct got_tree_entry **fte, **lte, **ste;
7684 int g, last, first = 1, i = 1;
7685 int root = s->tree == s->root;
7686 int off = root ? 1 : 2;
7688 g = view->gline;
7689 view->gline = 0;
7691 if (g == 0)
7692 g = 1;
7693 else if (g > got_object_tree_get_nentries(s->tree))
7694 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7696 fte = &s->first_displayed_entry;
7697 lte = &s->last_displayed_entry;
7698 ste = &s->selected_entry;
7700 if (*fte != NULL) {
7701 first = got_tree_entry_get_index(*fte);
7702 first += off; /* account for ".." */
7704 last = got_tree_entry_get_index(*lte);
7705 last += off;
7707 if (g >= first && g <= last && g - first < nlines) {
7708 s->selected = g - first;
7709 return NULL; /* gline is on the current page */
7712 if (*ste != NULL) {
7713 i = got_tree_entry_get_index(*ste);
7714 i += off;
7717 if (i < g) {
7718 err = tree_scroll_down(view, g - i);
7719 if (err)
7720 return err;
7721 if (got_tree_entry_get_index(*lte) >=
7722 got_object_tree_get_nentries(s->tree) - 1 &&
7723 first + s->selected < g &&
7724 s->selected < s->ndisplayed - 1) {
7725 first = got_tree_entry_get_index(*fte);
7726 first += off;
7727 s->selected = g - first;
7729 } else if (i > g)
7730 tree_scroll_up(s, i - g);
7732 if (g < nlines &&
7733 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7734 s->selected = g - 1;
7736 return NULL;
7739 static const struct got_error *
7740 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7742 const struct got_error *err = NULL;
7743 struct tog_tree_view_state *s = &view->state.tree;
7744 struct got_tree_entry *te;
7745 int n, nscroll = view->nlines - 3;
7747 if (view->gline)
7748 return tree_goto_line(view, nscroll);
7750 switch (ch) {
7751 case '0':
7752 case '$':
7753 case KEY_RIGHT:
7754 case 'l':
7755 case KEY_LEFT:
7756 case 'h':
7757 horizontal_scroll_input(view, ch);
7758 break;
7759 case 'i':
7760 s->show_ids = !s->show_ids;
7761 view->count = 0;
7762 break;
7763 case 'L':
7764 view->count = 0;
7765 if (!s->selected_entry)
7766 break;
7767 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7768 break;
7769 case 'R':
7770 view->count = 0;
7771 err = view_request_new(new_view, view, TOG_VIEW_REF);
7772 break;
7773 case 'g':
7774 case '=':
7775 case KEY_HOME:
7776 s->selected = 0;
7777 view->count = 0;
7778 if (s->tree == s->root)
7779 s->first_displayed_entry =
7780 got_object_tree_get_first_entry(s->tree);
7781 else
7782 s->first_displayed_entry = NULL;
7783 break;
7784 case 'G':
7785 case '*':
7786 case KEY_END: {
7787 int eos = view->nlines - 3;
7789 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7790 --eos; /* border */
7791 s->selected = 0;
7792 view->count = 0;
7793 te = got_object_tree_get_last_entry(s->tree);
7794 for (n = 0; n < eos; n++) {
7795 if (te == NULL) {
7796 if (s->tree != s->root) {
7797 s->first_displayed_entry = NULL;
7798 n++;
7800 break;
7802 s->first_displayed_entry = te;
7803 te = got_tree_entry_get_prev(s->tree, te);
7805 if (n > 0)
7806 s->selected = n - 1;
7807 break;
7809 case 'k':
7810 case KEY_UP:
7811 case CTRL('p'):
7812 if (s->selected > 0) {
7813 s->selected--;
7814 break;
7816 tree_scroll_up(s, 1);
7817 if (s->selected_entry == NULL ||
7818 (s->tree == s->root && s->selected_entry ==
7819 got_object_tree_get_first_entry(s->tree)))
7820 view->count = 0;
7821 break;
7822 case CTRL('u'):
7823 case 'u':
7824 nscroll /= 2;
7825 /* FALL THROUGH */
7826 case KEY_PPAGE:
7827 case CTRL('b'):
7828 case 'b':
7829 if (s->tree == s->root) {
7830 if (got_object_tree_get_first_entry(s->tree) ==
7831 s->first_displayed_entry)
7832 s->selected -= MIN(s->selected, nscroll);
7833 } else {
7834 if (s->first_displayed_entry == NULL)
7835 s->selected -= MIN(s->selected, nscroll);
7837 tree_scroll_up(s, MAX(0, nscroll));
7838 if (s->selected_entry == NULL ||
7839 (s->tree == s->root && s->selected_entry ==
7840 got_object_tree_get_first_entry(s->tree)))
7841 view->count = 0;
7842 break;
7843 case 'j':
7844 case KEY_DOWN:
7845 case CTRL('n'):
7846 if (s->selected < s->ndisplayed - 1) {
7847 s->selected++;
7848 break;
7850 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7851 == NULL) {
7852 /* can't scroll any further */
7853 view->count = 0;
7854 break;
7856 tree_scroll_down(view, 1);
7857 break;
7858 case CTRL('d'):
7859 case 'd':
7860 nscroll /= 2;
7861 /* FALL THROUGH */
7862 case KEY_NPAGE:
7863 case CTRL('f'):
7864 case 'f':
7865 case ' ':
7866 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7867 == NULL) {
7868 /* can't scroll any further; move cursor down */
7869 if (s->selected < s->ndisplayed - 1)
7870 s->selected += MIN(nscroll,
7871 s->ndisplayed - s->selected - 1);
7872 else
7873 view->count = 0;
7874 break;
7876 tree_scroll_down(view, nscroll);
7877 break;
7878 case KEY_ENTER:
7879 case '\r':
7880 case KEY_BACKSPACE:
7881 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7882 struct tog_parent_tree *parent;
7883 /* user selected '..' */
7884 if (s->tree == s->root) {
7885 view->count = 0;
7886 break;
7888 parent = TAILQ_FIRST(&s->parents);
7889 TAILQ_REMOVE(&s->parents, parent,
7890 entry);
7891 got_object_tree_close(s->tree);
7892 s->tree = parent->tree;
7893 s->first_displayed_entry =
7894 parent->first_displayed_entry;
7895 s->selected_entry =
7896 parent->selected_entry;
7897 s->selected = parent->selected;
7898 if (s->selected > view->nlines - 3) {
7899 err = offset_selection_down(view);
7900 if (err)
7901 break;
7903 free(parent);
7904 } else if (S_ISDIR(got_tree_entry_get_mode(
7905 s->selected_entry))) {
7906 struct got_tree_object *subtree;
7907 view->count = 0;
7908 err = got_object_open_as_tree(&subtree, s->repo,
7909 got_tree_entry_get_id(s->selected_entry));
7910 if (err)
7911 break;
7912 err = tree_view_visit_subtree(s, subtree);
7913 if (err) {
7914 got_object_tree_close(subtree);
7915 break;
7917 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7918 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7919 break;
7920 case KEY_RESIZE:
7921 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7922 s->selected = view->nlines - 4;
7923 view->count = 0;
7924 break;
7925 default:
7926 view->count = 0;
7927 break;
7930 return err;
7933 __dead static void
7934 usage_tree(void)
7936 endwin();
7937 fprintf(stderr,
7938 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7939 getprogname());
7940 exit(1);
7943 static const struct got_error *
7944 cmd_tree(int argc, char *argv[])
7946 const struct got_error *error;
7947 struct got_repository *repo = NULL;
7948 struct got_worktree *worktree = NULL;
7949 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7950 struct got_object_id *commit_id = NULL;
7951 struct got_commit_object *commit = NULL;
7952 const char *commit_id_arg = NULL;
7953 char *label = NULL;
7954 struct got_reference *ref = NULL;
7955 const char *head_ref_name = NULL;
7956 int ch;
7957 struct tog_view *view;
7958 int *pack_fds = NULL;
7960 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7961 switch (ch) {
7962 case 'c':
7963 commit_id_arg = optarg;
7964 break;
7965 case 'r':
7966 repo_path = realpath(optarg, NULL);
7967 if (repo_path == NULL)
7968 return got_error_from_errno2("realpath",
7969 optarg);
7970 break;
7971 default:
7972 usage_tree();
7973 /* NOTREACHED */
7977 argc -= optind;
7978 argv += optind;
7980 if (argc > 1)
7981 usage_tree();
7983 error = got_repo_pack_fds_open(&pack_fds);
7984 if (error != NULL)
7985 goto done;
7987 if (repo_path == NULL) {
7988 cwd = getcwd(NULL, 0);
7989 if (cwd == NULL)
7990 return got_error_from_errno("getcwd");
7991 error = got_worktree_open(&worktree, cwd);
7992 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7993 goto done;
7994 if (worktree)
7995 repo_path =
7996 strdup(got_worktree_get_repo_path(worktree));
7997 else
7998 repo_path = strdup(cwd);
7999 if (repo_path == NULL) {
8000 error = got_error_from_errno("strdup");
8001 goto done;
8005 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8006 if (error != NULL)
8007 goto done;
8009 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8010 repo, worktree);
8011 if (error)
8012 goto done;
8014 init_curses();
8016 error = apply_unveil(got_repo_get_path(repo), NULL);
8017 if (error)
8018 goto done;
8020 error = tog_load_refs(repo, 0);
8021 if (error)
8022 goto done;
8024 if (commit_id_arg == NULL) {
8025 error = got_repo_match_object_id(&commit_id, &label,
8026 worktree ? got_worktree_get_head_ref_name(worktree) :
8027 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8028 if (error)
8029 goto done;
8030 head_ref_name = label;
8031 } else {
8032 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8033 if (error == NULL)
8034 head_ref_name = got_ref_get_name(ref);
8035 else if (error->code != GOT_ERR_NOT_REF)
8036 goto done;
8037 error = got_repo_match_object_id(&commit_id, NULL,
8038 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8039 if (error)
8040 goto done;
8043 error = got_object_open_as_commit(&commit, repo, commit_id);
8044 if (error)
8045 goto done;
8047 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8048 if (view == NULL) {
8049 error = got_error_from_errno("view_open");
8050 goto done;
8052 error = open_tree_view(view, commit_id, head_ref_name, repo);
8053 if (error)
8054 goto done;
8055 if (!got_path_is_root_dir(in_repo_path)) {
8056 error = tree_view_walk_path(&view->state.tree, commit,
8057 in_repo_path);
8058 if (error)
8059 goto done;
8062 if (worktree) {
8063 /* Release work tree lock. */
8064 got_worktree_close(worktree);
8065 worktree = NULL;
8067 error = view_loop(view);
8068 done:
8069 free(repo_path);
8070 free(cwd);
8071 free(commit_id);
8072 free(label);
8073 if (ref)
8074 got_ref_close(ref);
8075 if (repo) {
8076 const struct got_error *close_err = got_repo_close(repo);
8077 if (error == NULL)
8078 error = close_err;
8080 if (pack_fds) {
8081 const struct got_error *pack_err =
8082 got_repo_pack_fds_close(pack_fds);
8083 if (error == NULL)
8084 error = pack_err;
8086 tog_free_refs();
8087 return error;
8090 static const struct got_error *
8091 ref_view_load_refs(struct tog_ref_view_state *s)
8093 struct got_reflist_entry *sre;
8094 struct tog_reflist_entry *re;
8096 s->nrefs = 0;
8097 TAILQ_FOREACH(sre, &tog_refs, entry) {
8098 if (strncmp(got_ref_get_name(sre->ref),
8099 "refs/got/", 9) == 0 &&
8100 strncmp(got_ref_get_name(sre->ref),
8101 "refs/got/backup/", 16) != 0)
8102 continue;
8104 re = malloc(sizeof(*re));
8105 if (re == NULL)
8106 return got_error_from_errno("malloc");
8108 re->ref = got_ref_dup(sre->ref);
8109 if (re->ref == NULL)
8110 return got_error_from_errno("got_ref_dup");
8111 re->idx = s->nrefs++;
8112 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8115 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8116 return NULL;
8119 static void
8120 ref_view_free_refs(struct tog_ref_view_state *s)
8122 struct tog_reflist_entry *re;
8124 while (!TAILQ_EMPTY(&s->refs)) {
8125 re = TAILQ_FIRST(&s->refs);
8126 TAILQ_REMOVE(&s->refs, re, entry);
8127 got_ref_close(re->ref);
8128 free(re);
8132 static const struct got_error *
8133 open_ref_view(struct tog_view *view, struct got_repository *repo)
8135 const struct got_error *err = NULL;
8136 struct tog_ref_view_state *s = &view->state.ref;
8138 s->selected_entry = 0;
8139 s->repo = repo;
8141 TAILQ_INIT(&s->refs);
8142 STAILQ_INIT(&s->colors);
8144 err = ref_view_load_refs(s);
8145 if (err)
8146 goto done;
8148 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8149 err = add_color(&s->colors, "^refs/heads/",
8150 TOG_COLOR_REFS_HEADS,
8151 get_color_value("TOG_COLOR_REFS_HEADS"));
8152 if (err)
8153 goto done;
8155 err = add_color(&s->colors, "^refs/tags/",
8156 TOG_COLOR_REFS_TAGS,
8157 get_color_value("TOG_COLOR_REFS_TAGS"));
8158 if (err)
8159 goto done;
8161 err = add_color(&s->colors, "^refs/remotes/",
8162 TOG_COLOR_REFS_REMOTES,
8163 get_color_value("TOG_COLOR_REFS_REMOTES"));
8164 if (err)
8165 goto done;
8167 err = add_color(&s->colors, "^refs/got/backup/",
8168 TOG_COLOR_REFS_BACKUP,
8169 get_color_value("TOG_COLOR_REFS_BACKUP"));
8170 if (err)
8171 goto done;
8174 view->show = show_ref_view;
8175 view->input = input_ref_view;
8176 view->close = close_ref_view;
8177 view->search_start = search_start_ref_view;
8178 view->search_next = search_next_ref_view;
8179 done:
8180 if (err) {
8181 if (view->close == NULL)
8182 close_ref_view(view);
8183 view_close(view);
8185 return err;
8188 static const struct got_error *
8189 close_ref_view(struct tog_view *view)
8191 struct tog_ref_view_state *s = &view->state.ref;
8193 ref_view_free_refs(s);
8194 free_colors(&s->colors);
8196 return NULL;
8199 static const struct got_error *
8200 resolve_reflist_entry(struct got_object_id **commit_id,
8201 struct tog_reflist_entry *re, struct got_repository *repo)
8203 const struct got_error *err = NULL;
8204 struct got_object_id *obj_id;
8205 struct got_tag_object *tag = NULL;
8206 int obj_type;
8208 *commit_id = NULL;
8210 err = got_ref_resolve(&obj_id, repo, re->ref);
8211 if (err)
8212 return err;
8214 err = got_object_get_type(&obj_type, repo, obj_id);
8215 if (err)
8216 goto done;
8218 switch (obj_type) {
8219 case GOT_OBJ_TYPE_COMMIT:
8220 *commit_id = obj_id;
8221 break;
8222 case GOT_OBJ_TYPE_TAG:
8223 err = got_object_open_as_tag(&tag, repo, obj_id);
8224 if (err)
8225 goto done;
8226 free(obj_id);
8227 err = got_object_get_type(&obj_type, repo,
8228 got_object_tag_get_object_id(tag));
8229 if (err)
8230 goto done;
8231 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8232 err = got_error(GOT_ERR_OBJ_TYPE);
8233 goto done;
8235 *commit_id = got_object_id_dup(
8236 got_object_tag_get_object_id(tag));
8237 if (*commit_id == NULL) {
8238 err = got_error_from_errno("got_object_id_dup");
8239 goto done;
8241 break;
8242 default:
8243 err = got_error(GOT_ERR_OBJ_TYPE);
8244 break;
8247 done:
8248 if (tag)
8249 got_object_tag_close(tag);
8250 if (err) {
8251 free(*commit_id);
8252 *commit_id = NULL;
8254 return err;
8257 static const struct got_error *
8258 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8259 struct tog_reflist_entry *re, struct got_repository *repo)
8261 struct tog_view *log_view;
8262 const struct got_error *err = NULL;
8263 struct got_object_id *commit_id = NULL;
8265 *new_view = NULL;
8267 err = resolve_reflist_entry(&commit_id, re, repo);
8268 if (err) {
8269 if (err->code != GOT_ERR_OBJ_TYPE)
8270 return err;
8271 else
8272 return NULL;
8275 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8276 if (log_view == NULL) {
8277 err = got_error_from_errno("view_open");
8278 goto done;
8281 err = open_log_view(log_view, commit_id, repo,
8282 got_ref_get_name(re->ref), "", 0);
8283 done:
8284 if (err)
8285 view_close(log_view);
8286 else
8287 *new_view = log_view;
8288 free(commit_id);
8289 return err;
8292 static void
8293 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8295 struct tog_reflist_entry *re;
8296 int i = 0;
8298 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8299 return;
8301 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8302 while (i++ < maxscroll) {
8303 if (re == NULL)
8304 break;
8305 s->first_displayed_entry = re;
8306 re = TAILQ_PREV(re, tog_reflist_head, entry);
8310 static const struct got_error *
8311 ref_scroll_down(struct tog_view *view, int maxscroll)
8313 struct tog_ref_view_state *s = &view->state.ref;
8314 struct tog_reflist_entry *next, *last;
8315 int n = 0;
8317 if (s->first_displayed_entry)
8318 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8319 else
8320 next = TAILQ_FIRST(&s->refs);
8322 last = s->last_displayed_entry;
8323 while (next && n++ < maxscroll) {
8324 if (last) {
8325 s->last_displayed_entry = last;
8326 last = TAILQ_NEXT(last, entry);
8328 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8329 s->first_displayed_entry = next;
8330 next = TAILQ_NEXT(next, entry);
8334 return NULL;
8337 static const struct got_error *
8338 search_start_ref_view(struct tog_view *view)
8340 struct tog_ref_view_state *s = &view->state.ref;
8342 s->matched_entry = NULL;
8343 return NULL;
8346 static int
8347 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8349 regmatch_t regmatch;
8351 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8352 0) == 0;
8355 static const struct got_error *
8356 search_next_ref_view(struct tog_view *view)
8358 struct tog_ref_view_state *s = &view->state.ref;
8359 struct tog_reflist_entry *re = NULL;
8361 if (!view->searching) {
8362 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8363 return NULL;
8366 if (s->matched_entry) {
8367 if (view->searching == TOG_SEARCH_FORWARD) {
8368 if (s->selected_entry)
8369 re = TAILQ_NEXT(s->selected_entry, entry);
8370 else
8371 re = TAILQ_PREV(s->selected_entry,
8372 tog_reflist_head, entry);
8373 } else {
8374 if (s->selected_entry == NULL)
8375 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8376 else
8377 re = TAILQ_PREV(s->selected_entry,
8378 tog_reflist_head, entry);
8380 } else {
8381 if (s->selected_entry)
8382 re = s->selected_entry;
8383 else if (view->searching == TOG_SEARCH_FORWARD)
8384 re = TAILQ_FIRST(&s->refs);
8385 else
8386 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8389 while (1) {
8390 if (re == NULL) {
8391 if (s->matched_entry == NULL) {
8392 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8393 return NULL;
8395 if (view->searching == TOG_SEARCH_FORWARD)
8396 re = TAILQ_FIRST(&s->refs);
8397 else
8398 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8401 if (match_reflist_entry(re, &view->regex)) {
8402 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8403 s->matched_entry = re;
8404 break;
8407 if (view->searching == TOG_SEARCH_FORWARD)
8408 re = TAILQ_NEXT(re, entry);
8409 else
8410 re = TAILQ_PREV(re, tog_reflist_head, entry);
8413 if (s->matched_entry) {
8414 s->first_displayed_entry = s->matched_entry;
8415 s->selected = 0;
8418 return NULL;
8421 static const struct got_error *
8422 show_ref_view(struct tog_view *view)
8424 const struct got_error *err = NULL;
8425 struct tog_ref_view_state *s = &view->state.ref;
8426 struct tog_reflist_entry *re;
8427 char *line = NULL;
8428 wchar_t *wline;
8429 struct tog_color *tc;
8430 int width, n, scrollx;
8431 int limit = view->nlines;
8433 werase(view->window);
8435 s->ndisplayed = 0;
8436 if (view_is_hsplit_top(view))
8437 --limit; /* border */
8439 if (limit == 0)
8440 return NULL;
8442 re = s->first_displayed_entry;
8444 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8445 s->nrefs) == -1)
8446 return got_error_from_errno("asprintf");
8448 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8449 if (err) {
8450 free(line);
8451 return err;
8453 if (view_needs_focus_indication(view))
8454 wstandout(view->window);
8455 waddwstr(view->window, wline);
8456 while (width++ < view->ncols)
8457 waddch(view->window, ' ');
8458 if (view_needs_focus_indication(view))
8459 wstandend(view->window);
8460 free(wline);
8461 wline = NULL;
8462 free(line);
8463 line = NULL;
8464 if (--limit <= 0)
8465 return NULL;
8467 n = 0;
8468 view->maxx = 0;
8469 while (re && limit > 0) {
8470 char *line = NULL;
8471 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8473 if (s->show_date) {
8474 struct got_commit_object *ci;
8475 struct got_tag_object *tag;
8476 struct got_object_id *id;
8477 struct tm tm;
8478 time_t t;
8480 err = got_ref_resolve(&id, s->repo, re->ref);
8481 if (err)
8482 return err;
8483 err = got_object_open_as_tag(&tag, s->repo, id);
8484 if (err) {
8485 if (err->code != GOT_ERR_OBJ_TYPE) {
8486 free(id);
8487 return err;
8489 err = got_object_open_as_commit(&ci, s->repo,
8490 id);
8491 if (err) {
8492 free(id);
8493 return err;
8495 t = got_object_commit_get_committer_time(ci);
8496 got_object_commit_close(ci);
8497 } else {
8498 t = got_object_tag_get_tagger_time(tag);
8499 got_object_tag_close(tag);
8501 free(id);
8502 if (gmtime_r(&t, &tm) == NULL)
8503 return got_error_from_errno("gmtime_r");
8504 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8505 return got_error(GOT_ERR_NO_SPACE);
8507 if (got_ref_is_symbolic(re->ref)) {
8508 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8509 ymd : "", got_ref_get_name(re->ref),
8510 got_ref_get_symref_target(re->ref)) == -1)
8511 return got_error_from_errno("asprintf");
8512 } else if (s->show_ids) {
8513 struct got_object_id *id;
8514 char *id_str;
8515 err = got_ref_resolve(&id, s->repo, re->ref);
8516 if (err)
8517 return err;
8518 err = got_object_id_str(&id_str, id);
8519 if (err) {
8520 free(id);
8521 return err;
8523 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8524 got_ref_get_name(re->ref), id_str) == -1) {
8525 err = got_error_from_errno("asprintf");
8526 free(id);
8527 free(id_str);
8528 return err;
8530 free(id);
8531 free(id_str);
8532 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8533 got_ref_get_name(re->ref)) == -1)
8534 return got_error_from_errno("asprintf");
8536 /* use full line width to determine view->maxx */
8537 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8538 if (err) {
8539 free(line);
8540 return err;
8542 view->maxx = MAX(view->maxx, width);
8543 free(wline);
8544 wline = NULL;
8546 err = format_line(&wline, &width, &scrollx, line, view->x,
8547 view->ncols, 0, 0);
8548 if (err) {
8549 free(line);
8550 return err;
8552 if (n == s->selected) {
8553 if (view->focussed)
8554 wstandout(view->window);
8555 s->selected_entry = re;
8557 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8558 if (tc)
8559 wattr_on(view->window,
8560 COLOR_PAIR(tc->colorpair), NULL);
8561 waddwstr(view->window, &wline[scrollx]);
8562 if (tc)
8563 wattr_off(view->window,
8564 COLOR_PAIR(tc->colorpair), NULL);
8565 if (width < view->ncols)
8566 waddch(view->window, '\n');
8567 if (n == s->selected && view->focussed)
8568 wstandend(view->window);
8569 free(line);
8570 free(wline);
8571 wline = NULL;
8572 n++;
8573 s->ndisplayed++;
8574 s->last_displayed_entry = re;
8576 limit--;
8577 re = TAILQ_NEXT(re, entry);
8580 view_border(view);
8581 return err;
8584 static const struct got_error *
8585 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8586 struct tog_reflist_entry *re, struct got_repository *repo)
8588 const struct got_error *err = NULL;
8589 struct got_object_id *commit_id = NULL;
8590 struct tog_view *tree_view;
8592 *new_view = NULL;
8594 err = resolve_reflist_entry(&commit_id, re, repo);
8595 if (err) {
8596 if (err->code != GOT_ERR_OBJ_TYPE)
8597 return err;
8598 else
8599 return NULL;
8603 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8604 if (tree_view == NULL) {
8605 err = got_error_from_errno("view_open");
8606 goto done;
8609 err = open_tree_view(tree_view, commit_id,
8610 got_ref_get_name(re->ref), repo);
8611 if (err)
8612 goto done;
8614 *new_view = tree_view;
8615 done:
8616 free(commit_id);
8617 return err;
8620 static const struct got_error *
8621 ref_goto_line(struct tog_view *view, int nlines)
8623 const struct got_error *err = NULL;
8624 struct tog_ref_view_state *s = &view->state.ref;
8625 int g, idx = s->selected_entry->idx;
8627 g = view->gline;
8628 view->gline = 0;
8630 if (g == 0)
8631 g = 1;
8632 else if (g > s->nrefs)
8633 g = s->nrefs;
8635 if (g >= s->first_displayed_entry->idx + 1 &&
8636 g <= s->last_displayed_entry->idx + 1 &&
8637 g - s->first_displayed_entry->idx - 1 < nlines) {
8638 s->selected = g - s->first_displayed_entry->idx - 1;
8639 return NULL;
8642 if (idx + 1 < g) {
8643 err = ref_scroll_down(view, g - idx - 1);
8644 if (err)
8645 return err;
8646 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8647 s->first_displayed_entry->idx + s->selected < g &&
8648 s->selected < s->ndisplayed - 1)
8649 s->selected = g - s->first_displayed_entry->idx - 1;
8650 } else if (idx + 1 > g)
8651 ref_scroll_up(s, idx - g + 1);
8653 if (g < nlines && s->first_displayed_entry->idx == 0)
8654 s->selected = g - 1;
8656 return NULL;
8660 static const struct got_error *
8661 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8663 const struct got_error *err = NULL;
8664 struct tog_ref_view_state *s = &view->state.ref;
8665 struct tog_reflist_entry *re;
8666 int n, nscroll = view->nlines - 1;
8668 if (view->gline)
8669 return ref_goto_line(view, nscroll);
8671 switch (ch) {
8672 case '0':
8673 case '$':
8674 case KEY_RIGHT:
8675 case 'l':
8676 case KEY_LEFT:
8677 case 'h':
8678 horizontal_scroll_input(view, ch);
8679 break;
8680 case 'i':
8681 s->show_ids = !s->show_ids;
8682 view->count = 0;
8683 break;
8684 case 'm':
8685 s->show_date = !s->show_date;
8686 view->count = 0;
8687 break;
8688 case 'o':
8689 s->sort_by_date = !s->sort_by_date;
8690 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8691 view->count = 0;
8692 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8693 got_ref_cmp_by_commit_timestamp_descending :
8694 tog_ref_cmp_by_name, s->repo);
8695 if (err)
8696 break;
8697 got_reflist_object_id_map_free(tog_refs_idmap);
8698 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8699 &tog_refs, s->repo);
8700 if (err)
8701 break;
8702 ref_view_free_refs(s);
8703 err = ref_view_load_refs(s);
8704 break;
8705 case KEY_ENTER:
8706 case '\r':
8707 view->count = 0;
8708 if (!s->selected_entry)
8709 break;
8710 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8711 break;
8712 case 'T':
8713 view->count = 0;
8714 if (!s->selected_entry)
8715 break;
8716 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8717 break;
8718 case 'g':
8719 case '=':
8720 case KEY_HOME:
8721 s->selected = 0;
8722 view->count = 0;
8723 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8724 break;
8725 case 'G':
8726 case '*':
8727 case KEY_END: {
8728 int eos = view->nlines - 1;
8730 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8731 --eos; /* border */
8732 s->selected = 0;
8733 view->count = 0;
8734 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8735 for (n = 0; n < eos; n++) {
8736 if (re == NULL)
8737 break;
8738 s->first_displayed_entry = re;
8739 re = TAILQ_PREV(re, tog_reflist_head, entry);
8741 if (n > 0)
8742 s->selected = n - 1;
8743 break;
8745 case 'k':
8746 case KEY_UP:
8747 case CTRL('p'):
8748 if (s->selected > 0) {
8749 s->selected--;
8750 break;
8752 ref_scroll_up(s, 1);
8753 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8754 view->count = 0;
8755 break;
8756 case CTRL('u'):
8757 case 'u':
8758 nscroll /= 2;
8759 /* FALL THROUGH */
8760 case KEY_PPAGE:
8761 case CTRL('b'):
8762 case 'b':
8763 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8764 s->selected -= MIN(nscroll, s->selected);
8765 ref_scroll_up(s, MAX(0, nscroll));
8766 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8767 view->count = 0;
8768 break;
8769 case 'j':
8770 case KEY_DOWN:
8771 case CTRL('n'):
8772 if (s->selected < s->ndisplayed - 1) {
8773 s->selected++;
8774 break;
8776 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8777 /* can't scroll any further */
8778 view->count = 0;
8779 break;
8781 ref_scroll_down(view, 1);
8782 break;
8783 case CTRL('d'):
8784 case 'd':
8785 nscroll /= 2;
8786 /* FALL THROUGH */
8787 case KEY_NPAGE:
8788 case CTRL('f'):
8789 case 'f':
8790 case ' ':
8791 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8792 /* can't scroll any further; move cursor down */
8793 if (s->selected < s->ndisplayed - 1)
8794 s->selected += MIN(nscroll,
8795 s->ndisplayed - s->selected - 1);
8796 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8797 s->selected += s->ndisplayed - s->selected - 1;
8798 view->count = 0;
8799 break;
8801 ref_scroll_down(view, nscroll);
8802 break;
8803 case CTRL('l'):
8804 view->count = 0;
8805 tog_free_refs();
8806 err = tog_load_refs(s->repo, s->sort_by_date);
8807 if (err)
8808 break;
8809 ref_view_free_refs(s);
8810 err = ref_view_load_refs(s);
8811 break;
8812 case KEY_RESIZE:
8813 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8814 s->selected = view->nlines - 2;
8815 break;
8816 default:
8817 view->count = 0;
8818 break;
8821 return err;
8824 __dead static void
8825 usage_ref(void)
8827 endwin();
8828 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8829 getprogname());
8830 exit(1);
8833 static const struct got_error *
8834 cmd_ref(int argc, char *argv[])
8836 const struct got_error *error;
8837 struct got_repository *repo = NULL;
8838 struct got_worktree *worktree = NULL;
8839 char *cwd = NULL, *repo_path = NULL;
8840 int ch;
8841 struct tog_view *view;
8842 int *pack_fds = NULL;
8844 while ((ch = getopt(argc, argv, "r:")) != -1) {
8845 switch (ch) {
8846 case 'r':
8847 repo_path = realpath(optarg, NULL);
8848 if (repo_path == NULL)
8849 return got_error_from_errno2("realpath",
8850 optarg);
8851 break;
8852 default:
8853 usage_ref();
8854 /* NOTREACHED */
8858 argc -= optind;
8859 argv += optind;
8861 if (argc > 1)
8862 usage_ref();
8864 error = got_repo_pack_fds_open(&pack_fds);
8865 if (error != NULL)
8866 goto done;
8868 if (repo_path == NULL) {
8869 cwd = getcwd(NULL, 0);
8870 if (cwd == NULL)
8871 return got_error_from_errno("getcwd");
8872 error = got_worktree_open(&worktree, cwd);
8873 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8874 goto done;
8875 if (worktree)
8876 repo_path =
8877 strdup(got_worktree_get_repo_path(worktree));
8878 else
8879 repo_path = strdup(cwd);
8880 if (repo_path == NULL) {
8881 error = got_error_from_errno("strdup");
8882 goto done;
8886 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8887 if (error != NULL)
8888 goto done;
8890 init_curses();
8892 error = apply_unveil(got_repo_get_path(repo), NULL);
8893 if (error)
8894 goto done;
8896 error = tog_load_refs(repo, 0);
8897 if (error)
8898 goto done;
8900 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8901 if (view == NULL) {
8902 error = got_error_from_errno("view_open");
8903 goto done;
8906 error = open_ref_view(view, repo);
8907 if (error)
8908 goto done;
8910 if (worktree) {
8911 /* Release work tree lock. */
8912 got_worktree_close(worktree);
8913 worktree = NULL;
8915 error = view_loop(view);
8916 done:
8917 free(repo_path);
8918 free(cwd);
8919 if (repo) {
8920 const struct got_error *close_err = got_repo_close(repo);
8921 if (close_err)
8922 error = close_err;
8924 if (pack_fds) {
8925 const struct got_error *pack_err =
8926 got_repo_pack_fds_close(pack_fds);
8927 if (error == NULL)
8928 error = pack_err;
8930 tog_free_refs();
8931 return error;
8934 static const struct got_error*
8935 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8936 const char *str)
8938 size_t len;
8940 if (win == NULL)
8941 win = stdscr;
8943 len = strlen(str);
8944 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8946 if (focus)
8947 wstandout(win);
8948 if (mvwprintw(win, y, x, "%s", str) == ERR)
8949 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8950 if (focus)
8951 wstandend(win);
8953 return NULL;
8956 static const struct got_error *
8957 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8959 off_t *p;
8961 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8962 if (p == NULL) {
8963 free(*line_offsets);
8964 *line_offsets = NULL;
8965 return got_error_from_errno("reallocarray");
8968 *line_offsets = p;
8969 (*line_offsets)[*nlines] = off;
8970 ++(*nlines);
8971 return NULL;
8974 static const struct got_error *
8975 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8977 *ret = 0;
8979 for (;n > 0; --n, ++km) {
8980 char *t0, *t, *k;
8981 size_t len = 1;
8983 if (km->keys == NULL)
8984 continue;
8986 t = t0 = strdup(km->keys);
8987 if (t0 == NULL)
8988 return got_error_from_errno("strdup");
8990 len += strlen(t);
8991 while ((k = strsep(&t, " ")) != NULL)
8992 len += strlen(k) > 1 ? 2 : 0;
8993 free(t0);
8994 *ret = MAX(*ret, len);
8997 return NULL;
9001 * Write keymap section headers, keys, and key info in km to f.
9002 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9003 * wrap control and symbolic keys in guillemets, else use <>.
9005 static const struct got_error *
9006 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9008 int n, len = width;
9010 if (km->keys) {
9011 static const char *u8_glyph[] = {
9012 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9013 "\xe2\x80\xba" /* U+203A (utf8 >) */
9015 char *t0, *t, *k;
9016 int cs, s, first = 1;
9018 cs = got_locale_is_utf8();
9020 t = t0 = strdup(km->keys);
9021 if (t0 == NULL)
9022 return got_error_from_errno("strdup");
9024 len = strlen(km->keys);
9025 while ((k = strsep(&t, " ")) != NULL) {
9026 s = strlen(k) > 1; /* control or symbolic key */
9027 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9028 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9029 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9030 if (n < 0) {
9031 free(t0);
9032 return got_error_from_errno("fprintf");
9034 first = 0;
9035 len += s ? 2 : 0;
9036 *off += n;
9038 free(t0);
9040 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9041 if (n < 0)
9042 return got_error_from_errno("fprintf");
9043 *off += n;
9045 return NULL;
9048 static const struct got_error *
9049 format_help(struct tog_help_view_state *s)
9051 const struct got_error *err = NULL;
9052 off_t off = 0;
9053 int i, max, n, show = s->all;
9054 static const struct tog_key_map km[] = {
9055 #define KEYMAP_(info, type) { NULL, (info), type }
9056 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9057 GENERATE_HELP
9058 #undef KEYMAP_
9059 #undef KEY_
9062 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9063 if (err)
9064 return err;
9066 n = nitems(km);
9067 err = max_key_str(&max, km, n);
9068 if (err)
9069 return err;
9071 for (i = 0; i < n; ++i) {
9072 if (km[i].keys == NULL) {
9073 show = s->all;
9074 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9075 km[i].type == s->type || s->all)
9076 show = 1;
9078 if (show) {
9079 err = format_help_line(&off, s->f, &km[i], max);
9080 if (err)
9081 return err;
9082 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9083 if (err)
9084 return err;
9087 fputc('\n', s->f);
9088 ++off;
9089 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9090 return err;
9093 static const struct got_error *
9094 create_help(struct tog_help_view_state *s)
9096 FILE *f;
9097 const struct got_error *err;
9099 free(s->line_offsets);
9100 s->line_offsets = NULL;
9101 s->nlines = 0;
9103 f = got_opentemp();
9104 if (f == NULL)
9105 return got_error_from_errno("got_opentemp");
9106 s->f = f;
9108 err = format_help(s);
9109 if (err)
9110 return err;
9112 if (s->f && fflush(s->f) != 0)
9113 return got_error_from_errno("fflush");
9115 return NULL;
9118 static const struct got_error *
9119 search_start_help_view(struct tog_view *view)
9121 view->state.help.matched_line = 0;
9122 return NULL;
9125 static void
9126 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9127 size_t *nlines, int **first, int **last, int **match, int **selected)
9129 struct tog_help_view_state *s = &view->state.help;
9131 *f = s->f;
9132 *nlines = s->nlines;
9133 *line_offsets = s->line_offsets;
9134 *match = &s->matched_line;
9135 *first = &s->first_displayed_line;
9136 *last = &s->last_displayed_line;
9137 *selected = &s->selected_line;
9140 static const struct got_error *
9141 show_help_view(struct tog_view *view)
9143 struct tog_help_view_state *s = &view->state.help;
9144 const struct got_error *err;
9145 regmatch_t *regmatch = &view->regmatch;
9146 wchar_t *wline;
9147 char *line;
9148 ssize_t linelen;
9149 size_t linesz = 0;
9150 int width, nprinted = 0, rc = 0;
9151 int eos = view->nlines;
9153 if (view_is_hsplit_top(view))
9154 --eos; /* account for border */
9156 s->lineno = 0;
9157 rewind(s->f);
9158 werase(view->window);
9160 if (view->gline > s->nlines - 1)
9161 view->gline = s->nlines - 1;
9163 err = win_draw_center(view->window, 0, 0, view->ncols,
9164 view_needs_focus_indication(view),
9165 "tog help (press q to return to tog)");
9166 if (err)
9167 return err;
9168 if (eos <= 1)
9169 return NULL;
9170 waddstr(view->window, "\n\n");
9171 eos -= 2;
9173 s->eof = 0;
9174 view->maxx = 0;
9175 line = NULL;
9176 while (eos > 0 && nprinted < eos) {
9177 attr_t attr = 0;
9179 linelen = getline(&line, &linesz, s->f);
9180 if (linelen == -1) {
9181 if (!feof(s->f)) {
9182 free(line);
9183 return got_ferror(s->f, GOT_ERR_IO);
9185 s->eof = 1;
9186 break;
9188 if (++s->lineno < s->first_displayed_line)
9189 continue;
9190 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9191 continue;
9192 if (s->lineno == view->hiline)
9193 attr = A_STANDOUT;
9195 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9196 view->x ? 1 : 0);
9197 if (err) {
9198 free(line);
9199 return err;
9201 view->maxx = MAX(view->maxx, width);
9202 free(wline);
9203 wline = NULL;
9205 if (attr)
9206 wattron(view->window, attr);
9207 if (s->first_displayed_line + nprinted == s->matched_line &&
9208 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9209 err = add_matched_line(&width, line, view->ncols - 1, 0,
9210 view->window, view->x, regmatch);
9211 if (err) {
9212 free(line);
9213 return err;
9215 } else {
9216 int skip;
9218 err = format_line(&wline, &width, &skip, line,
9219 view->x, view->ncols, 0, view->x ? 1 : 0);
9220 if (err) {
9221 free(line);
9222 return err;
9224 waddwstr(view->window, &wline[skip]);
9225 free(wline);
9226 wline = NULL;
9228 if (s->lineno == view->hiline) {
9229 while (width++ < view->ncols)
9230 waddch(view->window, ' ');
9231 } else {
9232 if (width < view->ncols)
9233 waddch(view->window, '\n');
9235 if (attr)
9236 wattroff(view->window, attr);
9237 if (++nprinted == 1)
9238 s->first_displayed_line = s->lineno;
9240 free(line);
9241 if (nprinted > 0)
9242 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9243 else
9244 s->last_displayed_line = s->first_displayed_line;
9246 view_border(view);
9248 if (s->eof) {
9249 rc = waddnstr(view->window,
9250 "See the tog(1) manual page for full documentation",
9251 view->ncols - 1);
9252 if (rc == ERR)
9253 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9254 } else {
9255 wmove(view->window, view->nlines - 1, 0);
9256 wclrtoeol(view->window);
9257 wstandout(view->window);
9258 rc = waddnstr(view->window, "scroll down for more...",
9259 view->ncols - 1);
9260 if (rc == ERR)
9261 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9262 if (getcurx(view->window) < view->ncols - 6) {
9263 rc = wprintw(view->window, "[%.0f%%]",
9264 100.00 * s->last_displayed_line / s->nlines);
9265 if (rc == ERR)
9266 return got_error_msg(GOT_ERR_IO, "wprintw");
9268 wstandend(view->window);
9271 return NULL;
9274 static const struct got_error *
9275 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9277 struct tog_help_view_state *s = &view->state.help;
9278 const struct got_error *err = NULL;
9279 char *line = NULL;
9280 ssize_t linelen;
9281 size_t linesz = 0;
9282 int eos, nscroll;
9284 eos = nscroll = view->nlines;
9285 if (view_is_hsplit_top(view))
9286 --eos; /* border */
9288 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9290 switch (ch) {
9291 case '0':
9292 case '$':
9293 case KEY_RIGHT:
9294 case 'l':
9295 case KEY_LEFT:
9296 case 'h':
9297 horizontal_scroll_input(view, ch);
9298 break;
9299 case 'g':
9300 case KEY_HOME:
9301 s->first_displayed_line = 1;
9302 view->count = 0;
9303 break;
9304 case 'G':
9305 case KEY_END:
9306 view->count = 0;
9307 if (s->eof)
9308 break;
9309 s->first_displayed_line = (s->nlines - eos) + 3;
9310 s->eof = 1;
9311 break;
9312 case 'k':
9313 case KEY_UP:
9314 if (s->first_displayed_line > 1)
9315 --s->first_displayed_line;
9316 else
9317 view->count = 0;
9318 break;
9319 case CTRL('u'):
9320 case 'u':
9321 nscroll /= 2;
9322 /* FALL THROUGH */
9323 case KEY_PPAGE:
9324 case CTRL('b'):
9325 case 'b':
9326 if (s->first_displayed_line == 1) {
9327 view->count = 0;
9328 break;
9330 while (--nscroll > 0 && s->first_displayed_line > 1)
9331 s->first_displayed_line--;
9332 break;
9333 case 'j':
9334 case KEY_DOWN:
9335 case CTRL('n'):
9336 if (!s->eof)
9337 ++s->first_displayed_line;
9338 else
9339 view->count = 0;
9340 break;
9341 case CTRL('d'):
9342 case 'd':
9343 nscroll /= 2;
9344 /* FALL THROUGH */
9345 case KEY_NPAGE:
9346 case CTRL('f'):
9347 case 'f':
9348 case ' ':
9349 if (s->eof) {
9350 view->count = 0;
9351 break;
9353 while (!s->eof && --nscroll > 0) {
9354 linelen = getline(&line, &linesz, s->f);
9355 s->first_displayed_line++;
9356 if (linelen == -1) {
9357 if (feof(s->f))
9358 s->eof = 1;
9359 else
9360 err = got_ferror(s->f, GOT_ERR_IO);
9361 break;
9364 free(line);
9365 break;
9366 default:
9367 view->count = 0;
9368 break;
9371 return err;
9374 static const struct got_error *
9375 close_help_view(struct tog_view *view)
9377 struct tog_help_view_state *s = &view->state.help;
9379 free(s->line_offsets);
9380 s->line_offsets = NULL;
9381 if (fclose(s->f) == EOF)
9382 return got_error_from_errno("fclose");
9384 return NULL;
9387 static const struct got_error *
9388 reset_help_view(struct tog_view *view)
9390 struct tog_help_view_state *s = &view->state.help;
9393 if (s->f && fclose(s->f) == EOF)
9394 return got_error_from_errno("fclose");
9396 wclear(view->window);
9397 view->count = 0;
9398 view->x = 0;
9399 s->all = !s->all;
9400 s->first_displayed_line = 1;
9401 s->last_displayed_line = view->nlines;
9402 s->matched_line = 0;
9404 return create_help(s);
9407 static const struct got_error *
9408 open_help_view(struct tog_view *view, struct tog_view *parent)
9410 const struct got_error *err = NULL;
9411 struct tog_help_view_state *s = &view->state.help;
9413 s->type = (enum tog_keymap_type)parent->type;
9414 s->first_displayed_line = 1;
9415 s->last_displayed_line = view->nlines;
9416 s->selected_line = 1;
9418 view->show = show_help_view;
9419 view->input = input_help_view;
9420 view->reset = reset_help_view;
9421 view->close = close_help_view;
9422 view->search_start = search_start_help_view;
9423 view->search_setup = search_setup_help_view;
9424 view->search_next = search_next_view_match;
9426 err = create_help(s);
9427 return err;
9430 static const struct got_error *
9431 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9432 enum tog_view_type request, int y, int x)
9434 const struct got_error *err = NULL;
9436 *new_view = NULL;
9438 switch (request) {
9439 case TOG_VIEW_DIFF:
9440 if (view->type == TOG_VIEW_LOG) {
9441 struct tog_log_view_state *s = &view->state.log;
9443 err = open_diff_view_for_commit(new_view, y, x,
9444 s->selected_entry->commit, s->selected_entry->id,
9445 view, s->repo);
9446 } else
9447 return got_error_msg(GOT_ERR_NOT_IMPL,
9448 "parent/child view pair not supported");
9449 break;
9450 case TOG_VIEW_BLAME:
9451 if (view->type == TOG_VIEW_TREE) {
9452 struct tog_tree_view_state *s = &view->state.tree;
9454 err = blame_tree_entry(new_view, y, x,
9455 s->selected_entry, &s->parents, s->commit_id,
9456 s->repo);
9457 } else
9458 return got_error_msg(GOT_ERR_NOT_IMPL,
9459 "parent/child view pair not supported");
9460 break;
9461 case TOG_VIEW_LOG:
9462 if (view->type == TOG_VIEW_BLAME)
9463 err = log_annotated_line(new_view, y, x,
9464 view->state.blame.repo, view->state.blame.id_to_log);
9465 else if (view->type == TOG_VIEW_TREE)
9466 err = log_selected_tree_entry(new_view, y, x,
9467 &view->state.tree);
9468 else if (view->type == TOG_VIEW_REF)
9469 err = log_ref_entry(new_view, y, x,
9470 view->state.ref.selected_entry,
9471 view->state.ref.repo);
9472 else
9473 return got_error_msg(GOT_ERR_NOT_IMPL,
9474 "parent/child view pair not supported");
9475 break;
9476 case TOG_VIEW_TREE:
9477 if (view->type == TOG_VIEW_LOG)
9478 err = browse_commit_tree(new_view, y, x,
9479 view->state.log.selected_entry,
9480 view->state.log.in_repo_path,
9481 view->state.log.head_ref_name,
9482 view->state.log.repo);
9483 else if (view->type == TOG_VIEW_REF)
9484 err = browse_ref_tree(new_view, y, x,
9485 view->state.ref.selected_entry,
9486 view->state.ref.repo);
9487 else
9488 return got_error_msg(GOT_ERR_NOT_IMPL,
9489 "parent/child view pair not supported");
9490 break;
9491 case TOG_VIEW_REF:
9492 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9493 if (*new_view == NULL)
9494 return got_error_from_errno("view_open");
9495 if (view->type == TOG_VIEW_LOG)
9496 err = open_ref_view(*new_view, view->state.log.repo);
9497 else if (view->type == TOG_VIEW_TREE)
9498 err = open_ref_view(*new_view, view->state.tree.repo);
9499 else
9500 err = got_error_msg(GOT_ERR_NOT_IMPL,
9501 "parent/child view pair not supported");
9502 if (err)
9503 view_close(*new_view);
9504 break;
9505 case TOG_VIEW_HELP:
9506 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9507 if (*new_view == NULL)
9508 return got_error_from_errno("view_open");
9509 err = open_help_view(*new_view, view);
9510 if (err)
9511 view_close(*new_view);
9512 break;
9513 default:
9514 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9517 return err;
9521 * If view was scrolled down to move the selected line into view when opening a
9522 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9524 static void
9525 offset_selection_up(struct tog_view *view)
9527 switch (view->type) {
9528 case TOG_VIEW_BLAME: {
9529 struct tog_blame_view_state *s = &view->state.blame;
9530 if (s->first_displayed_line == 1) {
9531 s->selected_line = MAX(s->selected_line - view->offset,
9532 1);
9533 break;
9535 if (s->first_displayed_line > view->offset)
9536 s->first_displayed_line -= view->offset;
9537 else
9538 s->first_displayed_line = 1;
9539 s->selected_line += view->offset;
9540 break;
9542 case TOG_VIEW_LOG:
9543 log_scroll_up(&view->state.log, view->offset);
9544 view->state.log.selected += view->offset;
9545 break;
9546 case TOG_VIEW_REF:
9547 ref_scroll_up(&view->state.ref, view->offset);
9548 view->state.ref.selected += view->offset;
9549 break;
9550 case TOG_VIEW_TREE:
9551 tree_scroll_up(&view->state.tree, view->offset);
9552 view->state.tree.selected += view->offset;
9553 break;
9554 default:
9555 break;
9558 view->offset = 0;
9562 * If the selected line is in the section of screen covered by the bottom split,
9563 * scroll down offset lines to move it into view and index its new position.
9565 static const struct got_error *
9566 offset_selection_down(struct tog_view *view)
9568 const struct got_error *err = NULL;
9569 const struct got_error *(*scrolld)(struct tog_view *, int);
9570 int *selected = NULL;
9571 int header, offset;
9573 switch (view->type) {
9574 case TOG_VIEW_BLAME: {
9575 struct tog_blame_view_state *s = &view->state.blame;
9576 header = 3;
9577 scrolld = NULL;
9578 if (s->selected_line > view->nlines - header) {
9579 offset = abs(view->nlines - s->selected_line - header);
9580 s->first_displayed_line += offset;
9581 s->selected_line -= offset;
9582 view->offset = offset;
9584 break;
9586 case TOG_VIEW_LOG: {
9587 struct tog_log_view_state *s = &view->state.log;
9588 scrolld = &log_scroll_down;
9589 header = view_is_parent_view(view) ? 3 : 2;
9590 selected = &s->selected;
9591 break;
9593 case TOG_VIEW_REF: {
9594 struct tog_ref_view_state *s = &view->state.ref;
9595 scrolld = &ref_scroll_down;
9596 header = 3;
9597 selected = &s->selected;
9598 break;
9600 case TOG_VIEW_TREE: {
9601 struct tog_tree_view_state *s = &view->state.tree;
9602 scrolld = &tree_scroll_down;
9603 header = 5;
9604 selected = &s->selected;
9605 break;
9607 default:
9608 selected = NULL;
9609 scrolld = NULL;
9610 header = 0;
9611 break;
9614 if (selected && *selected > view->nlines - header) {
9615 offset = abs(view->nlines - *selected - header);
9616 view->offset = offset;
9617 if (scrolld && offset) {
9618 err = scrolld(view, offset);
9619 *selected -= offset;
9623 return err;
9626 static void
9627 list_commands(FILE *fp)
9629 size_t i;
9631 fprintf(fp, "commands:");
9632 for (i = 0; i < nitems(tog_commands); i++) {
9633 const struct tog_cmd *cmd = &tog_commands[i];
9634 fprintf(fp, " %s", cmd->name);
9636 fputc('\n', fp);
9639 __dead static void
9640 usage(int hflag, int status)
9642 FILE *fp = (status == 0) ? stdout : stderr;
9644 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9645 getprogname());
9646 if (hflag) {
9647 fprintf(fp, "lazy usage: %s path\n", getprogname());
9648 list_commands(fp);
9650 exit(status);
9653 static char **
9654 make_argv(int argc, ...)
9656 va_list ap;
9657 char **argv;
9658 int i;
9660 va_start(ap, argc);
9662 argv = calloc(argc, sizeof(char *));
9663 if (argv == NULL)
9664 err(1, "calloc");
9665 for (i = 0; i < argc; i++) {
9666 argv[i] = strdup(va_arg(ap, char *));
9667 if (argv[i] == NULL)
9668 err(1, "strdup");
9671 va_end(ap);
9672 return argv;
9676 * Try to convert 'tog path' into a 'tog log path' command.
9677 * The user could simply have mistyped the command rather than knowingly
9678 * provided a path. So check whether argv[0] can in fact be resolved
9679 * to a path in the HEAD commit and print a special error if not.
9680 * This hack is for mpi@ <3
9682 static const struct got_error *
9683 tog_log_with_path(int argc, char *argv[])
9685 const struct got_error *error = NULL, *close_err;
9686 const struct tog_cmd *cmd = NULL;
9687 struct got_repository *repo = NULL;
9688 struct got_worktree *worktree = NULL;
9689 struct got_object_id *commit_id = NULL, *id = NULL;
9690 struct got_commit_object *commit = NULL;
9691 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9692 char *commit_id_str = NULL, **cmd_argv = NULL;
9693 int *pack_fds = NULL;
9695 cwd = getcwd(NULL, 0);
9696 if (cwd == NULL)
9697 return got_error_from_errno("getcwd");
9699 error = got_repo_pack_fds_open(&pack_fds);
9700 if (error != NULL)
9701 goto done;
9703 error = got_worktree_open(&worktree, cwd);
9704 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9705 goto done;
9707 if (worktree)
9708 repo_path = strdup(got_worktree_get_repo_path(worktree));
9709 else
9710 repo_path = strdup(cwd);
9711 if (repo_path == NULL) {
9712 error = got_error_from_errno("strdup");
9713 goto done;
9716 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9717 if (error != NULL)
9718 goto done;
9720 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9721 repo, worktree);
9722 if (error)
9723 goto done;
9725 error = tog_load_refs(repo, 0);
9726 if (error)
9727 goto done;
9728 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9729 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9730 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9731 if (error)
9732 goto done;
9734 if (worktree) {
9735 got_worktree_close(worktree);
9736 worktree = NULL;
9739 error = got_object_open_as_commit(&commit, repo, commit_id);
9740 if (error)
9741 goto done;
9743 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9744 if (error) {
9745 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9746 goto done;
9747 fprintf(stderr, "%s: '%s' is no known command or path\n",
9748 getprogname(), argv[0]);
9749 usage(1, 1);
9750 /* not reached */
9753 error = got_object_id_str(&commit_id_str, commit_id);
9754 if (error)
9755 goto done;
9757 cmd = &tog_commands[0]; /* log */
9758 argc = 4;
9759 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9760 error = cmd->cmd_main(argc, cmd_argv);
9761 done:
9762 if (repo) {
9763 close_err = got_repo_close(repo);
9764 if (error == NULL)
9765 error = close_err;
9767 if (commit)
9768 got_object_commit_close(commit);
9769 if (worktree)
9770 got_worktree_close(worktree);
9771 if (pack_fds) {
9772 const struct got_error *pack_err =
9773 got_repo_pack_fds_close(pack_fds);
9774 if (error == NULL)
9775 error = pack_err;
9777 free(id);
9778 free(commit_id_str);
9779 free(commit_id);
9780 free(cwd);
9781 free(repo_path);
9782 free(in_repo_path);
9783 if (cmd_argv) {
9784 int i;
9785 for (i = 0; i < argc; i++)
9786 free(cmd_argv[i]);
9787 free(cmd_argv);
9789 tog_free_refs();
9790 return error;
9793 int
9794 main(int argc, char *argv[])
9796 const struct got_error *io_err, *error = NULL;
9797 const struct tog_cmd *cmd = NULL;
9798 int ch, hflag = 0, Vflag = 0;
9799 char **cmd_argv = NULL;
9800 static const struct option longopts[] = {
9801 { "version", no_argument, NULL, 'V' },
9802 { NULL, 0, NULL, 0}
9804 char *diff_algo_str = NULL;
9805 const char *test_script_path;
9807 setlocale(LC_CTYPE, "");
9810 * Test mode init must happen before pledge() because "tty" will
9811 * not allow TTY-related ioctls to occur via regular files.
9813 test_script_path = getenv("TOG_TEST_SCRIPT");
9814 if (test_script_path != NULL) {
9815 error = init_mock_term(test_script_path);
9816 if (error) {
9817 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9818 return 1;
9820 } else if (!isatty(STDIN_FILENO))
9821 errx(1, "standard input is not a tty");
9823 #if !defined(PROFILE)
9824 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9825 NULL) == -1)
9826 err(1, "pledge");
9827 #endif
9829 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9830 switch (ch) {
9831 case 'h':
9832 hflag = 1;
9833 break;
9834 case 'V':
9835 Vflag = 1;
9836 break;
9837 default:
9838 usage(hflag, 1);
9839 /* NOTREACHED */
9843 argc -= optind;
9844 argv += optind;
9845 optind = 1;
9846 optreset = 1;
9848 if (Vflag) {
9849 got_version_print_str();
9850 return 0;
9853 if (argc == 0) {
9854 if (hflag)
9855 usage(hflag, 0);
9856 /* Build an argument vector which runs a default command. */
9857 cmd = &tog_commands[0];
9858 argc = 1;
9859 cmd_argv = make_argv(argc, cmd->name);
9860 } else {
9861 size_t i;
9863 /* Did the user specify a command? */
9864 for (i = 0; i < nitems(tog_commands); i++) {
9865 if (strncmp(tog_commands[i].name, argv[0],
9866 strlen(argv[0])) == 0) {
9867 cmd = &tog_commands[i];
9868 break;
9873 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9874 if (diff_algo_str) {
9875 if (strcasecmp(diff_algo_str, "patience") == 0)
9876 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9877 if (strcasecmp(diff_algo_str, "myers") == 0)
9878 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9881 if (cmd == NULL) {
9882 if (argc != 1)
9883 usage(0, 1);
9884 /* No command specified; try log with a path */
9885 error = tog_log_with_path(argc, argv);
9886 } else {
9887 if (hflag)
9888 cmd->cmd_usage();
9889 else
9890 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9893 if (using_mock_io) {
9894 io_err = tog_io_close();
9895 if (error == NULL)
9896 error = io_err;
9898 endwin();
9899 if (cmd_argv) {
9900 int i;
9901 for (i = 0; i < argc; i++)
9902 free(cmd_argv[i]);
9903 free(cmd_argv);
9906 if (error && error->code != GOT_ERR_CANCELLED &&
9907 error->code != GOT_ERR_EOF &&
9908 error->code != GOT_ERR_PRIVSEP_EXIT &&
9909 error->code != GOT_ERR_PRIVSEP_PIPE &&
9910 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9911 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9912 return 0;