Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
60 #ifndef MIN
61 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
62 #endif
64 #ifndef MAX
65 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
66 #endif
68 #define CTRL(x) ((x) & 0x1f)
70 #ifndef nitems
71 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
72 #endif
74 struct tog_cmd {
75 const char *name;
76 const struct got_error *(*cmd_main)(int, char *[]);
77 void (*cmd_usage)(void);
78 };
80 __dead static void usage(int, int);
81 __dead static void usage_log(void);
82 __dead static void usage_diff(void);
83 __dead static void usage_blame(void);
84 __dead static void usage_tree(void);
85 __dead static void usage_ref(void);
87 static const struct got_error* cmd_log(int, char *[]);
88 static const struct got_error* cmd_diff(int, char *[]);
89 static const struct got_error* cmd_blame(int, char *[]);
90 static const struct got_error* cmd_tree(int, char *[]);
91 static const struct got_error* cmd_ref(int, char *[]);
93 static const struct tog_cmd tog_commands[] = {
94 { "log", cmd_log, usage_log },
95 { "diff", cmd_diff, usage_diff },
96 { "blame", cmd_blame, usage_blame },
97 { "tree", cmd_tree, usage_tree },
98 { "ref", cmd_ref, usage_ref },
99 };
101 enum tog_view_type {
102 TOG_VIEW_DIFF,
103 TOG_VIEW_LOG,
104 TOG_VIEW_BLAME,
105 TOG_VIEW_TREE,
106 TOG_VIEW_REF,
107 TOG_VIEW_HELP
108 };
110 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
111 enum tog_keymap_type {
112 TOG_KEYMAP_KEYS = -2,
113 TOG_KEYMAP_GLOBAL,
114 TOG_KEYMAP_DIFF,
115 TOG_KEYMAP_LOG,
116 TOG_KEYMAP_BLAME,
117 TOG_KEYMAP_TREE,
118 TOG_KEYMAP_REF,
119 TOG_KEYMAP_HELP
120 };
122 enum tog_view_mode {
123 TOG_VIEW_SPLIT_NONE,
124 TOG_VIEW_SPLIT_VERT,
125 TOG_VIEW_SPLIT_HRZN
126 };
128 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
130 #define TOG_EOF_STRING "(END)"
132 struct commit_queue_entry {
133 TAILQ_ENTRY(commit_queue_entry) entry;
134 struct got_object_id *id;
135 struct got_commit_object *commit;
136 int idx;
137 };
138 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
139 struct commit_queue {
140 int ncommits;
141 struct commit_queue_head head;
142 };
144 struct tog_color {
145 STAILQ_ENTRY(tog_color) entry;
146 regex_t regex;
147 short colorpair;
148 };
149 STAILQ_HEAD(tog_colors, tog_color);
151 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
152 static struct got_reflist_object_id_map *tog_refs_idmap;
153 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
155 static const struct got_error *
156 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
157 struct got_reference* re2)
159 const char *name1 = got_ref_get_name(re1);
160 const char *name2 = got_ref_get_name(re2);
161 int isbackup1, isbackup2;
163 /* Sort backup refs towards the bottom of the list. */
164 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
165 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
166 if (!isbackup1 && isbackup2) {
167 *cmp = -1;
168 return NULL;
169 } else if (isbackup1 && !isbackup2) {
170 *cmp = 1;
171 return NULL;
174 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
175 return NULL;
178 static const struct got_error *
179 tog_load_refs(struct got_repository *repo, int sort_by_date)
181 const struct got_error *err;
183 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
184 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
185 repo);
186 if (err)
187 return err;
189 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
190 repo);
193 static void
194 tog_free_refs(void)
196 if (tog_refs_idmap) {
197 got_reflist_object_id_map_free(tog_refs_idmap);
198 tog_refs_idmap = NULL;
200 got_ref_list_free(&tog_refs);
203 static const struct got_error *
204 add_color(struct tog_colors *colors, const char *pattern,
205 int idx, short color)
207 const struct got_error *err = NULL;
208 struct tog_color *tc;
209 int regerr = 0;
211 if (idx < 1 || idx > COLOR_PAIRS - 1)
212 return NULL;
214 init_pair(idx, color, -1);
216 tc = calloc(1, sizeof(*tc));
217 if (tc == NULL)
218 return got_error_from_errno("calloc");
219 regerr = regcomp(&tc->regex, pattern,
220 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
221 if (regerr) {
222 static char regerr_msg[512];
223 static char err_msg[512];
224 regerror(regerr, &tc->regex, regerr_msg,
225 sizeof(regerr_msg));
226 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
227 regerr_msg);
228 err = got_error_msg(GOT_ERR_REGEX, err_msg);
229 free(tc);
230 return err;
232 tc->colorpair = idx;
233 STAILQ_INSERT_HEAD(colors, tc, entry);
234 return NULL;
237 static void
238 free_colors(struct tog_colors *colors)
240 struct tog_color *tc;
242 while (!STAILQ_EMPTY(colors)) {
243 tc = STAILQ_FIRST(colors);
244 STAILQ_REMOVE_HEAD(colors, entry);
245 regfree(&tc->regex);
246 free(tc);
250 static struct tog_color *
251 get_color(struct tog_colors *colors, int colorpair)
253 struct tog_color *tc = NULL;
255 STAILQ_FOREACH(tc, colors, entry) {
256 if (tc->colorpair == colorpair)
257 return tc;
260 return NULL;
263 static int
264 default_color_value(const char *envvar)
266 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
281 return COLOR_GREEN;
282 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
287 return COLOR_YELLOW;
288 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
291 return COLOR_MAGENTA;
292 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
295 return COLOR_CYAN;
297 return -1;
300 static int
301 get_color_value(const char *envvar)
303 const char *val = getenv(envvar);
305 if (val == NULL)
306 return default_color_value(envvar);
308 if (strcasecmp(val, "black") == 0)
309 return COLOR_BLACK;
310 if (strcasecmp(val, "red") == 0)
311 return COLOR_RED;
312 if (strcasecmp(val, "green") == 0)
313 return COLOR_GREEN;
314 if (strcasecmp(val, "yellow") == 0)
315 return COLOR_YELLOW;
316 if (strcasecmp(val, "blue") == 0)
317 return COLOR_BLUE;
318 if (strcasecmp(val, "magenta") == 0)
319 return COLOR_MAGENTA;
320 if (strcasecmp(val, "cyan") == 0)
321 return COLOR_CYAN;
322 if (strcasecmp(val, "white") == 0)
323 return COLOR_WHITE;
324 if (strcasecmp(val, "default") == 0)
325 return -1;
327 return default_color_value(envvar);
330 struct tog_diff_view_state {
331 struct got_object_id *id1, *id2;
332 const char *label1, *label2;
333 FILE *f, *f1, *f2;
334 int fd1, fd2;
335 int lineno;
336 int first_displayed_line;
337 int last_displayed_line;
338 int eof;
339 int diff_context;
340 int ignore_whitespace;
341 int force_text_diff;
342 struct got_repository *repo;
343 struct got_diff_line *lines;
344 size_t nlines;
345 int matched_line;
346 int selected_line;
348 /* passed from log or blame view; may be NULL */
349 struct tog_view *parent_view;
350 };
352 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
353 static volatile sig_atomic_t tog_thread_error;
355 struct tog_log_thread_args {
356 pthread_cond_t need_commits;
357 pthread_cond_t commit_loaded;
358 int commits_needed;
359 int load_all;
360 struct got_commit_graph *graph;
361 struct commit_queue *real_commits;
362 const char *in_repo_path;
363 struct got_object_id *start_id;
364 struct got_repository *repo;
365 int *pack_fds;
366 int log_complete;
367 sig_atomic_t *quit;
368 struct commit_queue_entry **first_displayed_entry;
369 struct commit_queue_entry **selected_entry;
370 int *searching;
371 int *search_next_done;
372 regex_t *regex;
373 int *limiting;
374 int limit_match;
375 regex_t *limit_regex;
376 struct commit_queue *limit_commits;
377 };
379 struct tog_log_view_state {
380 struct commit_queue *commits;
381 struct commit_queue_entry *first_displayed_entry;
382 struct commit_queue_entry *last_displayed_entry;
383 struct commit_queue_entry *selected_entry;
384 struct commit_queue real_commits;
385 int selected;
386 char *in_repo_path;
387 char *head_ref_name;
388 int log_branches;
389 struct got_repository *repo;
390 struct got_object_id *start_id;
391 sig_atomic_t quit;
392 pthread_t thread;
393 struct tog_log_thread_args thread_args;
394 struct commit_queue_entry *matched_entry;
395 struct commit_queue_entry *search_entry;
396 struct tog_colors colors;
397 int use_committer;
398 int limit_view;
399 regex_t limit_regex;
400 struct commit_queue limit_commits;
401 };
403 #define TOG_COLOR_DIFF_MINUS 1
404 #define TOG_COLOR_DIFF_PLUS 2
405 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
406 #define TOG_COLOR_DIFF_META 4
407 #define TOG_COLOR_TREE_SUBMODULE 5
408 #define TOG_COLOR_TREE_SYMLINK 6
409 #define TOG_COLOR_TREE_DIRECTORY 7
410 #define TOG_COLOR_TREE_EXECUTABLE 8
411 #define TOG_COLOR_COMMIT 9
412 #define TOG_COLOR_AUTHOR 10
413 #define TOG_COLOR_DATE 11
414 #define TOG_COLOR_REFS_HEADS 12
415 #define TOG_COLOR_REFS_TAGS 13
416 #define TOG_COLOR_REFS_REMOTES 14
417 #define TOG_COLOR_REFS_BACKUP 15
419 struct tog_blame_cb_args {
420 struct tog_blame_line *lines; /* one per line */
421 int nlines;
423 struct tog_view *view;
424 struct got_object_id *commit_id;
425 int *quit;
426 };
428 struct tog_blame_thread_args {
429 const char *path;
430 struct got_repository *repo;
431 struct tog_blame_cb_args *cb_args;
432 int *complete;
433 got_cancel_cb cancel_cb;
434 void *cancel_arg;
435 pthread_cond_t blame_complete;
436 };
438 struct tog_blame {
439 FILE *f;
440 off_t filesize;
441 struct tog_blame_line *lines;
442 int nlines;
443 off_t *line_offsets;
444 pthread_t thread;
445 struct tog_blame_thread_args thread_args;
446 struct tog_blame_cb_args cb_args;
447 const char *path;
448 int *pack_fds;
449 };
451 struct tog_blame_view_state {
452 int first_displayed_line;
453 int last_displayed_line;
454 int selected_line;
455 int last_diffed_line;
456 int blame_complete;
457 int eof;
458 int done;
459 struct got_object_id_queue blamed_commits;
460 struct got_object_qid *blamed_commit;
461 char *path;
462 struct got_repository *repo;
463 struct got_object_id *commit_id;
464 struct got_object_id *id_to_log;
465 struct tog_blame blame;
466 int matched_line;
467 struct tog_colors colors;
468 };
470 struct tog_parent_tree {
471 TAILQ_ENTRY(tog_parent_tree) entry;
472 struct got_tree_object *tree;
473 struct got_tree_entry *first_displayed_entry;
474 struct got_tree_entry *selected_entry;
475 int selected;
476 };
478 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
480 struct tog_tree_view_state {
481 char *tree_label;
482 struct got_object_id *commit_id;/* commit which this tree belongs to */
483 struct got_tree_object *root; /* the commit's root tree entry */
484 struct got_tree_object *tree; /* currently displayed (sub-)tree */
485 struct got_tree_entry *first_displayed_entry;
486 struct got_tree_entry *last_displayed_entry;
487 struct got_tree_entry *selected_entry;
488 int ndisplayed, selected, show_ids;
489 struct tog_parent_trees parents; /* parent trees of current sub-tree */
490 char *head_ref_name;
491 struct got_repository *repo;
492 struct got_tree_entry *matched_entry;
493 struct tog_colors colors;
494 };
496 struct tog_reflist_entry {
497 TAILQ_ENTRY(tog_reflist_entry) entry;
498 struct got_reference *ref;
499 int idx;
500 };
502 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
504 struct tog_ref_view_state {
505 struct tog_reflist_head refs;
506 struct tog_reflist_entry *first_displayed_entry;
507 struct tog_reflist_entry *last_displayed_entry;
508 struct tog_reflist_entry *selected_entry;
509 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
510 struct got_repository *repo;
511 struct tog_reflist_entry *matched_entry;
512 struct tog_colors colors;
513 };
515 struct tog_help_view_state {
516 FILE *f;
517 off_t *line_offsets;
518 size_t nlines;
519 int lineno;
520 int first_displayed_line;
521 int last_displayed_line;
522 int eof;
523 int matched_line;
524 int selected_line;
525 int all;
526 enum tog_keymap_type type;
527 };
529 #define GENERATE_HELP \
530 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
531 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
532 KEY_("k C-p Up", "Move cursor or page up one line"), \
533 KEY_("j C-n Down", "Move cursor or page down one line"), \
534 KEY_("C-b b PgUp", "Scroll the view up one page"), \
535 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
536 KEY_("C-u u", "Scroll the view up one half page"), \
537 KEY_("C-d d", "Scroll the view down one half page"), \
538 KEY_("g", "Go to line N (default: first line)"), \
539 KEY_("Home =", "Go to the first line"), \
540 KEY_("G", "Go to line N (default: last line)"), \
541 KEY_("End *", "Go to the last line"), \
542 KEY_("l Right", "Scroll the view right"), \
543 KEY_("h Left", "Scroll the view left"), \
544 KEY_("$", "Scroll view to the rightmost position"), \
545 KEY_("0", "Scroll view to the leftmost position"), \
546 KEY_("-", "Decrease size of the focussed split"), \
547 KEY_("+", "Increase size of the focussed split"), \
548 KEY_("Tab", "Switch focus between views"), \
549 KEY_("F", "Toggle fullscreen mode"), \
550 KEY_("S", "Switch split-screen layout"), \
551 KEY_("/", "Open prompt to enter search term"), \
552 KEY_("n", "Find next line/token matching the current search term"), \
553 KEY_("N", "Find previous line/token matching the current search term"),\
554 KEY_("q", "Quit the focussed view; Quit help screen"), \
555 KEY_("Q", "Quit tog"), \
557 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
558 KEY_("< ,", "Move cursor up one commit"), \
559 KEY_("> .", "Move cursor down one commit"), \
560 KEY_("Enter", "Open diff view of the selected commit"), \
561 KEY_("B", "Reload the log view and toggle display of merged commits"), \
562 KEY_("R", "Open ref view of all repository references"), \
563 KEY_("T", "Display tree view of the repository from the selected" \
564 " commit"), \
565 KEY_("@", "Toggle between displaying author and committer name"), \
566 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
567 KEY_("C-g Backspace", "Cancel current search or log operation"), \
568 KEY_("C-l", "Reload the log view with new commits in the repository"), \
570 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
571 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
572 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
573 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
574 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
575 " data"), \
576 KEY_("(", "Go to the previous file in the diff"), \
577 KEY_(")", "Go to the next file in the diff"), \
578 KEY_("{", "Go to the previous hunk in the diff"), \
579 KEY_("}", "Go to the next hunk in the diff"), \
580 KEY_("[", "Decrease the number of context lines"), \
581 KEY_("]", "Increase the number of context lines"), \
582 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
584 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
585 KEY_("Enter", "Display diff view of the selected line's commit"), \
586 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
587 KEY_("L", "Open log view for the currently selected annotated line"), \
588 KEY_("C", "Reload view with the previously blamed commit"), \
589 KEY_("c", "Reload view with the version of the file found in the" \
590 " selected line's commit"), \
591 KEY_("p", "Reload view with the version of the file found in the" \
592 " selected line's parent commit"), \
594 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
595 KEY_("Enter", "Enter selected directory or open blame view of the" \
596 " selected file"), \
597 KEY_("L", "Open log view for the selected entry"), \
598 KEY_("R", "Open ref view of all repository references"), \
599 KEY_("i", "Show object IDs for all tree entries"), \
600 KEY_("Backspace", "Return to the parent directory"), \
602 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
603 KEY_("Enter", "Display log view of the selected reference"), \
604 KEY_("T", "Display tree view of the selected reference"), \
605 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
606 KEY_("m", "Toggle display of last modified date for each reference"), \
607 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
608 KEY_("C-l", "Reload view with all repository references")
610 struct tog_key_map {
611 const char *keys;
612 const char *info;
613 enum tog_keymap_type type;
614 };
616 /* curses io for tog regress */
617 struct tog_io {
618 FILE *cin;
619 FILE *cout;
620 FILE *f;
621 FILE *sdump;
622 int wait_for_ui;
623 } tog_io;
624 static int using_mock_io;
626 #define TOG_KEY_SCRDUMP SHRT_MIN
628 /*
629 * We implement two types of views: parent views and child views.
631 * The 'Tab' key switches focus between a parent view and its child view.
632 * Child views are shown side-by-side to their parent view, provided
633 * there is enough screen estate.
635 * When a new view is opened from within a parent view, this new view
636 * becomes a child view of the parent view, replacing any existing child.
638 * When a new view is opened from within a child view, this new view
639 * becomes a parent view which will obscure the views below until the
640 * user quits the new parent view by typing 'q'.
642 * This list of views contains parent views only.
643 * Child views are only pointed to by their parent view.
644 */
645 TAILQ_HEAD(tog_view_list_head, tog_view);
647 struct tog_view {
648 TAILQ_ENTRY(tog_view) entry;
649 WINDOW *window;
650 PANEL *panel;
651 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
652 int resized_y, resized_x; /* begin_y/x based on user resizing */
653 int maxx, x; /* max column and current start column */
654 int lines, cols; /* copies of LINES and COLS */
655 int nscrolled, offset; /* lines scrolled and hsplit line offset */
656 int gline, hiline; /* navigate to and highlight this nG line */
657 int ch, count; /* current keymap and count prefix */
658 int resized; /* set when in a resize event */
659 int focussed; /* Only set on one parent or child view at a time. */
660 int dying;
661 struct tog_view *parent;
662 struct tog_view *child;
664 /*
665 * This flag is initially set on parent views when a new child view
666 * is created. It gets toggled when the 'Tab' key switches focus
667 * between parent and child.
668 * The flag indicates whether focus should be passed on to our child
669 * view if this parent view gets picked for focus after another parent
670 * view was closed. This prevents child views from losing focus in such
671 * situations.
672 */
673 int focus_child;
675 enum tog_view_mode mode;
676 /* type-specific state */
677 enum tog_view_type type;
678 union {
679 struct tog_diff_view_state diff;
680 struct tog_log_view_state log;
681 struct tog_blame_view_state blame;
682 struct tog_tree_view_state tree;
683 struct tog_ref_view_state ref;
684 struct tog_help_view_state help;
685 } state;
687 const struct got_error *(*show)(struct tog_view *);
688 const struct got_error *(*input)(struct tog_view **,
689 struct tog_view *, int);
690 const struct got_error *(*reset)(struct tog_view *);
691 const struct got_error *(*resize)(struct tog_view *, int);
692 const struct got_error *(*close)(struct tog_view *);
694 const struct got_error *(*search_start)(struct tog_view *);
695 const struct got_error *(*search_next)(struct tog_view *);
696 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
697 int **, int **, int **, int **);
698 int search_started;
699 int searching;
700 #define TOG_SEARCH_FORWARD 1
701 #define TOG_SEARCH_BACKWARD 2
702 int search_next_done;
703 #define TOG_SEARCH_HAVE_MORE 1
704 #define TOG_SEARCH_NO_MORE 2
705 #define TOG_SEARCH_HAVE_NONE 3
706 regex_t regex;
707 regmatch_t regmatch;
708 const char *action;
709 };
711 static const struct got_error *open_diff_view(struct tog_view *,
712 struct got_object_id *, struct got_object_id *,
713 const char *, const char *, int, int, int, struct tog_view *,
714 struct got_repository *);
715 static const struct got_error *show_diff_view(struct tog_view *);
716 static const struct got_error *input_diff_view(struct tog_view **,
717 struct tog_view *, int);
718 static const struct got_error *reset_diff_view(struct tog_view *);
719 static const struct got_error* close_diff_view(struct tog_view *);
720 static const struct got_error *search_start_diff_view(struct tog_view *);
721 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
722 size_t *, int **, int **, int **, int **);
723 static const struct got_error *search_next_view_match(struct tog_view *);
725 static const struct got_error *open_log_view(struct tog_view *,
726 struct got_object_id *, struct got_repository *,
727 const char *, const char *, int);
728 static const struct got_error * show_log_view(struct tog_view *);
729 static const struct got_error *input_log_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *resize_log_view(struct tog_view *, int);
732 static const struct got_error *close_log_view(struct tog_view *);
733 static const struct got_error *search_start_log_view(struct tog_view *);
734 static const struct got_error *search_next_log_view(struct tog_view *);
736 static const struct got_error *open_blame_view(struct tog_view *, char *,
737 struct got_object_id *, struct got_repository *);
738 static const struct got_error *show_blame_view(struct tog_view *);
739 static const struct got_error *input_blame_view(struct tog_view **,
740 struct tog_view *, int);
741 static const struct got_error *reset_blame_view(struct tog_view *);
742 static const struct got_error *close_blame_view(struct tog_view *);
743 static const struct got_error *search_start_blame_view(struct tog_view *);
744 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
745 size_t *, int **, int **, int **, int **);
747 static const struct got_error *open_tree_view(struct tog_view *,
748 struct got_object_id *, const char *, struct got_repository *);
749 static const struct got_error *show_tree_view(struct tog_view *);
750 static const struct got_error *input_tree_view(struct tog_view **,
751 struct tog_view *, int);
752 static const struct got_error *close_tree_view(struct tog_view *);
753 static const struct got_error *search_start_tree_view(struct tog_view *);
754 static const struct got_error *search_next_tree_view(struct tog_view *);
756 static const struct got_error *open_ref_view(struct tog_view *,
757 struct got_repository *);
758 static const struct got_error *show_ref_view(struct tog_view *);
759 static const struct got_error *input_ref_view(struct tog_view **,
760 struct tog_view *, int);
761 static const struct got_error *close_ref_view(struct tog_view *);
762 static const struct got_error *search_start_ref_view(struct tog_view *);
763 static const struct got_error *search_next_ref_view(struct tog_view *);
765 static const struct got_error *open_help_view(struct tog_view *,
766 struct tog_view *);
767 static const struct got_error *show_help_view(struct tog_view *);
768 static const struct got_error *input_help_view(struct tog_view **,
769 struct tog_view *, int);
770 static const struct got_error *reset_help_view(struct tog_view *);
771 static const struct got_error* close_help_view(struct tog_view *);
772 static const struct got_error *search_start_help_view(struct tog_view *);
773 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
774 size_t *, int **, int **, int **, int **);
776 static volatile sig_atomic_t tog_sigwinch_received;
777 static volatile sig_atomic_t tog_sigpipe_received;
778 static volatile sig_atomic_t tog_sigcont_received;
779 static volatile sig_atomic_t tog_sigint_received;
780 static volatile sig_atomic_t tog_sigterm_received;
782 static void
783 tog_sigwinch(int signo)
785 tog_sigwinch_received = 1;
788 static void
789 tog_sigpipe(int signo)
791 tog_sigpipe_received = 1;
794 static void
795 tog_sigcont(int signo)
797 tog_sigcont_received = 1;
800 static void
801 tog_sigint(int signo)
803 tog_sigint_received = 1;
806 static void
807 tog_sigterm(int signo)
809 tog_sigterm_received = 1;
812 static int
813 tog_fatal_signal_received(void)
815 return (tog_sigpipe_received ||
816 tog_sigint_received || tog_sigterm_received);
819 static const struct got_error *
820 view_close(struct tog_view *view)
822 const struct got_error *err = NULL, *child_err = NULL;
824 if (view->child) {
825 child_err = view_close(view->child);
826 view->child = NULL;
828 if (view->close)
829 err = view->close(view);
830 if (view->panel)
831 del_panel(view->panel);
832 if (view->window)
833 delwin(view->window);
834 free(view);
835 return err ? err : child_err;
838 static struct tog_view *
839 view_open(int nlines, int ncols, int begin_y, int begin_x,
840 enum tog_view_type type)
842 struct tog_view *view = calloc(1, sizeof(*view));
844 if (view == NULL)
845 return NULL;
847 view->type = type;
848 view->lines = LINES;
849 view->cols = COLS;
850 view->nlines = nlines ? nlines : LINES - begin_y;
851 view->ncols = ncols ? ncols : COLS - begin_x;
852 view->begin_y = begin_y;
853 view->begin_x = begin_x;
854 view->window = newwin(nlines, ncols, begin_y, begin_x);
855 if (view->window == NULL) {
856 view_close(view);
857 return NULL;
859 view->panel = new_panel(view->window);
860 if (view->panel == NULL ||
861 set_panel_userptr(view->panel, view) != OK) {
862 view_close(view);
863 return NULL;
866 keypad(view->window, TRUE);
867 return view;
870 static int
871 view_split_begin_x(int begin_x)
873 if (begin_x > 0 || COLS < 120)
874 return 0;
875 return (COLS - MAX(COLS / 2, 80));
878 /* XXX Stub till we decide what to do. */
879 static int
880 view_split_begin_y(int lines)
882 return lines * HSPLIT_SCALE;
885 static const struct got_error *view_resize(struct tog_view *);
887 static const struct got_error *
888 view_splitscreen(struct tog_view *view)
890 const struct got_error *err = NULL;
892 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
893 if (view->resized_y && view->resized_y < view->lines)
894 view->begin_y = view->resized_y;
895 else
896 view->begin_y = view_split_begin_y(view->nlines);
897 view->begin_x = 0;
898 } else if (!view->resized) {
899 if (view->resized_x && view->resized_x < view->cols - 1 &&
900 view->cols > 119)
901 view->begin_x = view->resized_x;
902 else
903 view->begin_x = view_split_begin_x(0);
904 view->begin_y = 0;
906 view->nlines = LINES - view->begin_y;
907 view->ncols = COLS - view->begin_x;
908 view->lines = LINES;
909 view->cols = COLS;
910 err = view_resize(view);
911 if (err)
912 return err;
914 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
915 view->parent->nlines = view->begin_y;
917 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
918 return got_error_from_errno("mvwin");
920 return NULL;
923 static const struct got_error *
924 view_fullscreen(struct tog_view *view)
926 const struct got_error *err = NULL;
928 view->begin_x = 0;
929 view->begin_y = view->resized ? view->begin_y : 0;
930 view->nlines = view->resized ? view->nlines : LINES;
931 view->ncols = COLS;
932 view->lines = LINES;
933 view->cols = COLS;
934 err = view_resize(view);
935 if (err)
936 return err;
938 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
939 return got_error_from_errno("mvwin");
941 return NULL;
944 static int
945 view_is_parent_view(struct tog_view *view)
947 return view->parent == NULL;
950 static int
951 view_is_splitscreen(struct tog_view *view)
953 return view->begin_x > 0 || view->begin_y > 0;
956 static int
957 view_is_fullscreen(struct tog_view *view)
959 return view->nlines == LINES && view->ncols == COLS;
962 static int
963 view_is_hsplit_top(struct tog_view *view)
965 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
966 view_is_splitscreen(view->child);
969 static void
970 view_border(struct tog_view *view)
972 PANEL *panel;
973 const struct tog_view *view_above;
975 if (view->parent)
976 return view_border(view->parent);
978 panel = panel_above(view->panel);
979 if (panel == NULL)
980 return;
982 view_above = panel_userptr(panel);
983 if (view->mode == TOG_VIEW_SPLIT_HRZN)
984 mvwhline(view->window, view_above->begin_y - 1,
985 view->begin_x, ACS_HLINE, view->ncols);
986 else
987 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
988 ACS_VLINE, view->nlines);
991 static const struct got_error *view_init_hsplit(struct tog_view *, int);
992 static const struct got_error *request_log_commits(struct tog_view *);
993 static const struct got_error *offset_selection_down(struct tog_view *);
994 static void offset_selection_up(struct tog_view *);
995 static void view_get_split(struct tog_view *, int *, int *);
997 static const struct got_error *
998 view_resize(struct tog_view *view)
1000 const struct got_error *err = NULL;
1001 int dif, nlines, ncols;
1003 dif = LINES - view->lines; /* line difference */
1005 if (view->lines > LINES)
1006 nlines = view->nlines - (view->lines - LINES);
1007 else
1008 nlines = view->nlines + (LINES - view->lines);
1009 if (view->cols > COLS)
1010 ncols = view->ncols - (view->cols - COLS);
1011 else
1012 ncols = view->ncols + (COLS - view->cols);
1014 if (view->child) {
1015 int hs = view->child->begin_y;
1017 if (!view_is_fullscreen(view))
1018 view->child->begin_x = view_split_begin_x(view->begin_x);
1019 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1020 view->child->begin_x == 0) {
1021 ncols = COLS;
1023 view_fullscreen(view->child);
1024 if (view->child->focussed)
1025 show_panel(view->child->panel);
1026 else
1027 show_panel(view->panel);
1028 } else {
1029 ncols = view->child->begin_x;
1031 view_splitscreen(view->child);
1032 show_panel(view->child->panel);
1035 * XXX This is ugly and needs to be moved into the above
1036 * logic but "works" for now and my attempts at moving it
1037 * break either 'tab' or 'F' key maps in horizontal splits.
1039 if (hs) {
1040 err = view_splitscreen(view->child);
1041 if (err)
1042 return err;
1043 if (dif < 0) { /* top split decreased */
1044 err = offset_selection_down(view);
1045 if (err)
1046 return err;
1048 view_border(view);
1049 update_panels();
1050 doupdate();
1051 show_panel(view->child->panel);
1052 nlines = view->nlines;
1054 } else if (view->parent == NULL)
1055 ncols = COLS;
1057 if (view->resize && dif > 0) {
1058 err = view->resize(view, dif);
1059 if (err)
1060 return err;
1063 if (wresize(view->window, nlines, ncols) == ERR)
1064 return got_error_from_errno("wresize");
1065 if (replace_panel(view->panel, view->window) == ERR)
1066 return got_error_from_errno("replace_panel");
1067 wclear(view->window);
1069 view->nlines = nlines;
1070 view->ncols = ncols;
1071 view->lines = LINES;
1072 view->cols = COLS;
1074 return NULL;
1077 static const struct got_error *
1078 resize_log_view(struct tog_view *view, int increase)
1080 struct tog_log_view_state *s = &view->state.log;
1081 const struct got_error *err = NULL;
1082 int n = 0;
1084 if (s->selected_entry)
1085 n = s->selected_entry->idx + view->lines - s->selected;
1088 * Request commits to account for the increased
1089 * height so we have enough to populate the view.
1091 if (s->commits->ncommits < n) {
1092 view->nscrolled = n - s->commits->ncommits + increase + 1;
1093 err = request_log_commits(view);
1096 return err;
1099 static void
1100 view_adjust_offset(struct tog_view *view, int n)
1102 if (n == 0)
1103 return;
1105 if (view->parent && view->parent->offset) {
1106 if (view->parent->offset + n >= 0)
1107 view->parent->offset += n;
1108 else
1109 view->parent->offset = 0;
1110 } else if (view->offset) {
1111 if (view->offset - n >= 0)
1112 view->offset -= n;
1113 else
1114 view->offset = 0;
1118 static const struct got_error *
1119 view_resize_split(struct tog_view *view, int resize)
1121 const struct got_error *err = NULL;
1122 struct tog_view *v = NULL;
1124 if (view->parent)
1125 v = view->parent;
1126 else
1127 v = view;
1129 if (!v->child || !view_is_splitscreen(v->child))
1130 return NULL;
1132 v->resized = v->child->resized = resize; /* lock for resize event */
1134 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1135 if (v->child->resized_y)
1136 v->child->begin_y = v->child->resized_y;
1137 if (view->parent)
1138 v->child->begin_y -= resize;
1139 else
1140 v->child->begin_y += resize;
1141 if (v->child->begin_y < 3) {
1142 view->count = 0;
1143 v->child->begin_y = 3;
1144 } else if (v->child->begin_y > LINES - 1) {
1145 view->count = 0;
1146 v->child->begin_y = LINES - 1;
1148 v->ncols = COLS;
1149 v->child->ncols = COLS;
1150 view_adjust_offset(view, resize);
1151 err = view_init_hsplit(v, v->child->begin_y);
1152 if (err)
1153 return err;
1154 v->child->resized_y = v->child->begin_y;
1155 } else {
1156 if (v->child->resized_x)
1157 v->child->begin_x = v->child->resized_x;
1158 if (view->parent)
1159 v->child->begin_x -= resize;
1160 else
1161 v->child->begin_x += resize;
1162 if (v->child->begin_x < 11) {
1163 view->count = 0;
1164 v->child->begin_x = 11;
1165 } else if (v->child->begin_x > COLS - 1) {
1166 view->count = 0;
1167 v->child->begin_x = COLS - 1;
1169 v->child->resized_x = v->child->begin_x;
1172 v->child->mode = v->mode;
1173 v->child->nlines = v->lines - v->child->begin_y;
1174 v->child->ncols = v->cols - v->child->begin_x;
1175 v->focus_child = 1;
1177 err = view_fullscreen(v);
1178 if (err)
1179 return err;
1180 err = view_splitscreen(v->child);
1181 if (err)
1182 return err;
1184 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1185 err = offset_selection_down(v->child);
1186 if (err)
1187 return err;
1190 if (v->resize)
1191 err = v->resize(v, 0);
1192 else if (v->child->resize)
1193 err = v->child->resize(v->child, 0);
1195 v->resized = v->child->resized = 0;
1197 return err;
1200 static void
1201 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1203 struct tog_view *v = src->child ? src->child : src;
1205 dst->resized_x = v->resized_x;
1206 dst->resized_y = v->resized_y;
1209 static const struct got_error *
1210 view_close_child(struct tog_view *view)
1212 const struct got_error *err = NULL;
1214 if (view->child == NULL)
1215 return NULL;
1217 err = view_close(view->child);
1218 view->child = NULL;
1219 return err;
1222 static const struct got_error *
1223 view_set_child(struct tog_view *view, struct tog_view *child)
1225 const struct got_error *err = NULL;
1227 view->child = child;
1228 child->parent = view;
1230 err = view_resize(view);
1231 if (err)
1232 return err;
1234 if (view->child->resized_x || view->child->resized_y)
1235 err = view_resize_split(view, 0);
1237 return err;
1240 static const struct got_error *view_dispatch_request(struct tog_view **,
1241 struct tog_view *, enum tog_view_type, int, int);
1243 static const struct got_error *
1244 view_request_new(struct tog_view **requested, struct tog_view *view,
1245 enum tog_view_type request)
1247 struct tog_view *new_view = NULL;
1248 const struct got_error *err;
1249 int y = 0, x = 0;
1251 *requested = NULL;
1253 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1254 view_get_split(view, &y, &x);
1256 err = view_dispatch_request(&new_view, view, request, y, x);
1257 if (err)
1258 return err;
1260 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1261 request != TOG_VIEW_HELP) {
1262 err = view_init_hsplit(view, y);
1263 if (err)
1264 return err;
1267 view->focussed = 0;
1268 new_view->focussed = 1;
1269 new_view->mode = view->mode;
1270 new_view->nlines = request == TOG_VIEW_HELP ?
1271 view->lines : view->lines - y;
1273 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1274 view_transfer_size(new_view, view);
1275 err = view_close_child(view);
1276 if (err)
1277 return err;
1278 err = view_set_child(view, new_view);
1279 if (err)
1280 return err;
1281 view->focus_child = 1;
1282 } else
1283 *requested = new_view;
1285 return NULL;
1288 static void
1289 tog_resizeterm(void)
1291 int cols, lines;
1292 struct winsize size;
1294 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1295 cols = 80; /* Default */
1296 lines = 24;
1297 } else {
1298 cols = size.ws_col;
1299 lines = size.ws_row;
1301 resize_term(lines, cols);
1304 static const struct got_error *
1305 view_search_start(struct tog_view *view, int fast_refresh)
1307 const struct got_error *err = NULL;
1308 struct tog_view *v = view;
1309 char pattern[1024];
1310 int ret;
1312 if (view->search_started) {
1313 regfree(&view->regex);
1314 view->searching = 0;
1315 memset(&view->regmatch, 0, sizeof(view->regmatch));
1317 view->search_started = 0;
1319 if (view->nlines < 1)
1320 return NULL;
1322 if (view_is_hsplit_top(view))
1323 v = view->child;
1324 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1325 v = view->parent;
1327 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1328 wclrtoeol(v->window);
1330 nodelay(v->window, FALSE); /* block for search term input */
1331 nocbreak();
1332 echo();
1333 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1334 wrefresh(v->window);
1335 cbreak();
1336 noecho();
1337 nodelay(v->window, TRUE);
1338 if (!fast_refresh && !using_mock_io)
1339 halfdelay(10);
1340 if (ret == ERR)
1341 return NULL;
1343 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1344 err = view->search_start(view);
1345 if (err) {
1346 regfree(&view->regex);
1347 return err;
1349 view->search_started = 1;
1350 view->searching = TOG_SEARCH_FORWARD;
1351 view->search_next_done = 0;
1352 view->search_next(view);
1355 return NULL;
1358 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1359 static const struct got_error *
1360 switch_split(struct tog_view *view)
1362 const struct got_error *err = NULL;
1363 struct tog_view *v = NULL;
1365 if (view->parent)
1366 v = view->parent;
1367 else
1368 v = view;
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1371 v->mode = TOG_VIEW_SPLIT_VERT;
1372 else
1373 v->mode = TOG_VIEW_SPLIT_HRZN;
1375 if (!v->child)
1376 return NULL;
1377 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1378 v->mode = TOG_VIEW_SPLIT_NONE;
1380 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1381 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1382 v->child->begin_y = v->child->resized_y;
1383 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1384 v->child->begin_x = v->child->resized_x;
1387 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1388 v->ncols = COLS;
1389 v->child->ncols = COLS;
1390 v->child->nscrolled = LINES - v->child->nlines;
1392 err = view_init_hsplit(v, v->child->begin_y);
1393 if (err)
1394 return err;
1396 v->child->mode = v->mode;
1397 v->child->nlines = v->lines - v->child->begin_y;
1398 v->focus_child = 1;
1400 err = view_fullscreen(v);
1401 if (err)
1402 return err;
1403 err = view_splitscreen(v->child);
1404 if (err)
1405 return err;
1407 if (v->mode == TOG_VIEW_SPLIT_NONE)
1408 v->mode = TOG_VIEW_SPLIT_VERT;
1409 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1410 err = offset_selection_down(v);
1411 if (err)
1412 return err;
1413 err = offset_selection_down(v->child);
1414 if (err)
1415 return err;
1416 } else {
1417 offset_selection_up(v);
1418 offset_selection_up(v->child);
1420 if (v->resize)
1421 err = v->resize(v, 0);
1422 else if (v->child->resize)
1423 err = v->child->resize(v->child, 0);
1425 return err;
1429 * Strip trailing whitespace from str starting at byte *n;
1430 * if *n < 0, use strlen(str). Return new str length in *n.
1432 static void
1433 strip_trailing_ws(char *str, int *n)
1435 size_t x = *n;
1437 if (str == NULL || *str == '\0')
1438 return;
1440 if (x < 0)
1441 x = strlen(str);
1443 while (x-- > 0 && isspace((unsigned char)str[x]))
1444 str[x] = '\0';
1446 *n = x + 1;
1450 * Extract visible substring of line y from the curses screen
1451 * and strip trailing whitespace. If vline is set, overwrite
1452 * line[vline] with '|' because the ACS_VLINE character is
1453 * written out as 'x'. Write the line to file f.
1455 static const struct got_error *
1456 view_write_line(FILE *f, int y, int vline)
1458 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1459 int r, w;
1461 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1462 if (r == ERR)
1463 return got_error_fmt(GOT_ERR_RANGE,
1464 "failed to extract line %d", y);
1467 * In some views, lines are padded with blanks to COLS width.
1468 * Strip them so we can diff without the -b flag when testing.
1470 strip_trailing_ws(line, &r);
1472 if (vline > 0)
1473 line[vline] = '|';
1475 w = fprintf(f, "%s\n", line);
1476 if (w != r + 1) /* \n */
1477 return got_ferror(f, GOT_ERR_IO);
1479 return NULL;
1483 * Capture the visible curses screen by writing each line to the
1484 * file at the path set via the TOG_SCR_DUMP environment variable.
1486 static const struct got_error *
1487 screendump(struct tog_view *view)
1489 const struct got_error *err;
1490 int i;
1492 err = got_opentemp_truncate(tog_io.sdump);
1493 if (err)
1494 return err;
1496 if ((view->child && view->child->begin_x) ||
1497 (view->parent && view->begin_x)) {
1498 int ncols = view->child ? view->ncols : view->parent->ncols;
1500 /* vertical splitscreen */
1501 for (i = 0; i < view->nlines; ++i) {
1502 err = view_write_line(tog_io.sdump, i, ncols - 1);
1503 if (err)
1504 goto done;
1506 } else {
1507 int hline = 0;
1509 /* fullscreen or horizontal splitscreen */
1510 if ((view->child && view->child->begin_y) ||
1511 (view->parent && view->begin_y)) /* hsplit */
1512 hline = view->child ?
1513 view->child->begin_y : view->begin_y;
1515 for (i = 0; i < view->lines; i++) {
1516 if (hline && i == hline - 1) {
1517 int c;
1519 /* ACS_HLINE writes out as 'q', overwrite it */
1520 for (c = 0; c < view->cols; ++c)
1521 fputc('-', tog_io.sdump);
1522 fputc('\n', tog_io.sdump);
1523 continue;
1526 err = view_write_line(tog_io.sdump, i, 0);
1527 if (err)
1528 goto done;
1532 done:
1533 return err;
1537 * Compute view->count from numeric input. Assign total to view->count and
1538 * return first non-numeric key entered.
1540 static int
1541 get_compound_key(struct tog_view *view, int c)
1543 struct tog_view *v = view;
1544 int x, n = 0;
1546 if (view_is_hsplit_top(view))
1547 v = view->child;
1548 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1549 v = view->parent;
1551 view->count = 0;
1552 cbreak(); /* block for input */
1553 nodelay(view->window, FALSE);
1554 wmove(v->window, v->nlines - 1, 0);
1555 wclrtoeol(v->window);
1556 waddch(v->window, ':');
1558 do {
1559 x = getcurx(v->window);
1560 if (x != ERR && x < view->ncols) {
1561 waddch(v->window, c);
1562 wrefresh(v->window);
1566 * Don't overflow. Max valid request should be the greatest
1567 * between the longest and total lines; cap at 10 million.
1569 if (n >= 9999999)
1570 n = 9999999;
1571 else
1572 n = n * 10 + (c - '0');
1573 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1575 if (c == 'G' || c == 'g') { /* nG key map */
1576 view->gline = view->hiline = n;
1577 n = 0;
1578 c = 0;
1581 /* Massage excessive or inapplicable values at the input handler. */
1582 view->count = n;
1584 return c;
1587 static void
1588 action_report(struct tog_view *view)
1590 struct tog_view *v = view;
1592 if (view_is_hsplit_top(view))
1593 v = view->child;
1594 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1595 v = view->parent;
1597 wmove(v->window, v->nlines - 1, 0);
1598 wclrtoeol(v->window);
1599 wprintw(v->window, ":%s", view->action);
1600 wrefresh(v->window);
1603 * Clear action status report. Only clear in blame view
1604 * once annotating is complete, otherwise it's too fast.
1606 if (view->type == TOG_VIEW_BLAME) {
1607 if (view->state.blame.blame_complete)
1608 view->action = NULL;
1609 } else
1610 view->action = NULL;
1614 * Read the next line from the test script and assign
1615 * key instruction to *ch. If at EOF, set the *done flag.
1617 static const struct got_error *
1618 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1620 const struct got_error *err = NULL;
1621 char *line = NULL;
1622 size_t linesz = 0;
1624 if (view->count && --view->count) {
1625 *ch = view->ch;
1626 return NULL;
1627 } else
1628 *ch = -1;
1630 if (getline(&line, &linesz, script) == -1) {
1631 if (feof(script)) {
1632 *done = 1;
1633 goto done;
1634 } else {
1635 err = got_ferror(script, GOT_ERR_IO);
1636 goto done;
1640 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1641 tog_io.wait_for_ui = 1;
1642 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1643 *ch = KEY_ENTER;
1644 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1645 *ch = KEY_RIGHT;
1646 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1647 *ch = KEY_LEFT;
1648 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1649 *ch = KEY_DOWN;
1650 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1651 *ch = KEY_UP;
1652 else if (strncasecmp(line, "TAB", 3) == 0)
1653 *ch = '\t';
1654 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1655 *ch = TOG_KEY_SCRDUMP;
1656 else if (isdigit((unsigned char)*line)) {
1657 char *t = line;
1659 while (isdigit((unsigned char)*t))
1660 ++t;
1661 view->ch = *ch = *t;
1662 *t = '\0';
1663 /* ignore error, view->count is 0 if instruction is invalid */
1664 view->count = strtonum(line, 0, INT_MAX, NULL);
1665 } else
1666 *ch = *line;
1668 done:
1669 free(line);
1670 return err;
1673 static const struct got_error *
1674 view_input(struct tog_view **new, int *done, struct tog_view *view,
1675 struct tog_view_list_head *views, int fast_refresh)
1677 const struct got_error *err = NULL;
1678 struct tog_view *v;
1679 int ch, errcode;
1681 *new = NULL;
1683 if (view->action)
1684 action_report(view);
1686 /* Clear "no matches" indicator. */
1687 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1688 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1689 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1690 view->count = 0;
1693 if (view->searching && !view->search_next_done) {
1694 errcode = pthread_mutex_unlock(&tog_mutex);
1695 if (errcode)
1696 return got_error_set_errno(errcode,
1697 "pthread_mutex_unlock");
1698 sched_yield();
1699 errcode = pthread_mutex_lock(&tog_mutex);
1700 if (errcode)
1701 return got_error_set_errno(errcode,
1702 "pthread_mutex_lock");
1703 view->search_next(view);
1704 return NULL;
1707 /* Allow threads to make progress while we are waiting for input. */
1708 errcode = pthread_mutex_unlock(&tog_mutex);
1709 if (errcode)
1710 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1712 if (using_mock_io) {
1713 err = tog_read_script_key(tog_io.f, view, &ch, done);
1714 if (err) {
1715 errcode = pthread_mutex_lock(&tog_mutex);
1716 return err;
1718 } else if (view->count && --view->count) {
1719 cbreak();
1720 nodelay(view->window, TRUE);
1721 ch = wgetch(view->window);
1722 /* let C-g or backspace abort unfinished count */
1723 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1724 view->count = 0;
1725 else
1726 ch = view->ch;
1727 } else {
1728 ch = wgetch(view->window);
1729 if (ch >= '1' && ch <= '9')
1730 view->ch = ch = get_compound_key(view, ch);
1732 if (view->hiline && ch != ERR && ch != 0)
1733 view->hiline = 0; /* key pressed, clear line highlight */
1734 nodelay(view->window, TRUE);
1735 errcode = pthread_mutex_lock(&tog_mutex);
1736 if (errcode)
1737 return got_error_set_errno(errcode, "pthread_mutex_lock");
1739 if (tog_sigwinch_received || tog_sigcont_received) {
1740 tog_resizeterm();
1741 tog_sigwinch_received = 0;
1742 tog_sigcont_received = 0;
1743 TAILQ_FOREACH(v, views, entry) {
1744 err = view_resize(v);
1745 if (err)
1746 return err;
1747 err = v->input(new, v, KEY_RESIZE);
1748 if (err)
1749 return err;
1750 if (v->child) {
1751 err = view_resize(v->child);
1752 if (err)
1753 return err;
1754 err = v->child->input(new, v->child,
1755 KEY_RESIZE);
1756 if (err)
1757 return err;
1758 if (v->child->resized_x || v->child->resized_y) {
1759 err = view_resize_split(v, 0);
1760 if (err)
1761 return err;
1767 switch (ch) {
1768 case '?':
1769 case 'H':
1770 case KEY_F(1):
1771 if (view->type == TOG_VIEW_HELP)
1772 err = view->reset(view);
1773 else
1774 err = view_request_new(new, view, TOG_VIEW_HELP);
1775 break;
1776 case '\t':
1777 view->count = 0;
1778 if (view->child) {
1779 view->focussed = 0;
1780 view->child->focussed = 1;
1781 view->focus_child = 1;
1782 } else if (view->parent) {
1783 view->focussed = 0;
1784 view->parent->focussed = 1;
1785 view->parent->focus_child = 0;
1786 if (!view_is_splitscreen(view)) {
1787 if (view->parent->resize) {
1788 err = view->parent->resize(view->parent,
1789 0);
1790 if (err)
1791 return err;
1793 offset_selection_up(view->parent);
1794 err = view_fullscreen(view->parent);
1795 if (err)
1796 return err;
1799 break;
1800 case 'q':
1801 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1802 if (view->parent->resize) {
1803 /* might need more commits to fill fullscreen */
1804 err = view->parent->resize(view->parent, 0);
1805 if (err)
1806 break;
1808 offset_selection_up(view->parent);
1810 err = view->input(new, view, ch);
1811 view->dying = 1;
1812 break;
1813 case 'Q':
1814 *done = 1;
1815 break;
1816 case 'F':
1817 view->count = 0;
1818 if (view_is_parent_view(view)) {
1819 if (view->child == NULL)
1820 break;
1821 if (view_is_splitscreen(view->child)) {
1822 view->focussed = 0;
1823 view->child->focussed = 1;
1824 err = view_fullscreen(view->child);
1825 } else {
1826 err = view_splitscreen(view->child);
1827 if (!err)
1828 err = view_resize_split(view, 0);
1830 if (err)
1831 break;
1832 err = view->child->input(new, view->child,
1833 KEY_RESIZE);
1834 } else {
1835 if (view_is_splitscreen(view)) {
1836 view->parent->focussed = 0;
1837 view->focussed = 1;
1838 err = view_fullscreen(view);
1839 } else {
1840 err = view_splitscreen(view);
1841 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1842 err = view_resize(view->parent);
1843 if (!err)
1844 err = view_resize_split(view, 0);
1846 if (err)
1847 break;
1848 err = view->input(new, view, KEY_RESIZE);
1850 if (err)
1851 break;
1852 if (view->resize) {
1853 err = view->resize(view, 0);
1854 if (err)
1855 break;
1857 if (view->parent) {
1858 if (view->parent->resize) {
1859 err = view->parent->resize(view->parent, 0);
1860 if (err != NULL)
1861 break;
1863 err = offset_selection_down(view->parent);
1864 if (err != NULL)
1865 break;
1867 err = offset_selection_down(view);
1868 break;
1869 case 'S':
1870 view->count = 0;
1871 err = switch_split(view);
1872 break;
1873 case '-':
1874 err = view_resize_split(view, -1);
1875 break;
1876 case '+':
1877 err = view_resize_split(view, 1);
1878 break;
1879 case KEY_RESIZE:
1880 break;
1881 case '/':
1882 view->count = 0;
1883 if (view->search_start)
1884 view_search_start(view, fast_refresh);
1885 else
1886 err = view->input(new, view, ch);
1887 break;
1888 case 'N':
1889 case 'n':
1890 if (view->search_started && view->search_next) {
1891 view->searching = (ch == 'n' ?
1892 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1893 view->search_next_done = 0;
1894 view->search_next(view);
1895 } else
1896 err = view->input(new, view, ch);
1897 break;
1898 case 'A':
1899 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1900 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1901 view->action = "Patience diff algorithm";
1902 } else {
1903 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1904 view->action = "Myers diff algorithm";
1906 TAILQ_FOREACH(v, views, entry) {
1907 if (v->reset) {
1908 err = v->reset(v);
1909 if (err)
1910 return err;
1912 if (v->child && v->child->reset) {
1913 err = v->child->reset(v->child);
1914 if (err)
1915 return err;
1918 break;
1919 case TOG_KEY_SCRDUMP:
1920 err = screendump(view);
1921 break;
1922 default:
1923 err = view->input(new, view, ch);
1924 break;
1927 return err;
1930 static int
1931 view_needs_focus_indication(struct tog_view *view)
1933 if (view_is_parent_view(view)) {
1934 if (view->child == NULL || view->child->focussed)
1935 return 0;
1936 if (!view_is_splitscreen(view->child))
1937 return 0;
1938 } else if (!view_is_splitscreen(view))
1939 return 0;
1941 return view->focussed;
1944 static const struct got_error *
1945 tog_io_close(void)
1947 const struct got_error *err = NULL;
1949 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1950 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1951 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1952 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1953 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1954 err = got_ferror(tog_io.f, GOT_ERR_IO);
1955 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1956 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1958 return err;
1961 static const struct got_error *
1962 view_loop(struct tog_view *view)
1964 const struct got_error *err = NULL;
1965 struct tog_view_list_head views;
1966 struct tog_view *new_view;
1967 char *mode;
1968 int fast_refresh = 10;
1969 int done = 0, errcode;
1971 mode = getenv("TOG_VIEW_SPLIT_MODE");
1972 if (!mode || !(*mode == 'h' || *mode == 'H'))
1973 view->mode = TOG_VIEW_SPLIT_VERT;
1974 else
1975 view->mode = TOG_VIEW_SPLIT_HRZN;
1977 errcode = pthread_mutex_lock(&tog_mutex);
1978 if (errcode)
1979 return got_error_set_errno(errcode, "pthread_mutex_lock");
1981 TAILQ_INIT(&views);
1982 TAILQ_INSERT_HEAD(&views, view, entry);
1984 view->focussed = 1;
1985 err = view->show(view);
1986 if (err)
1987 return err;
1988 update_panels();
1989 doupdate();
1990 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1991 !tog_fatal_signal_received()) {
1992 /* Refresh fast during initialization, then become slower. */
1993 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1994 halfdelay(10); /* switch to once per second */
1996 err = view_input(&new_view, &done, view, &views, fast_refresh);
1997 if (err)
1998 break;
2000 if (view->dying && view == TAILQ_FIRST(&views) &&
2001 TAILQ_NEXT(view, entry) == NULL)
2002 done = 1;
2003 if (done) {
2004 struct tog_view *v;
2007 * When we quit, scroll the screen up a single line
2008 * so we don't lose any information.
2010 TAILQ_FOREACH(v, &views, entry) {
2011 wmove(v->window, 0, 0);
2012 wdeleteln(v->window);
2013 wnoutrefresh(v->window);
2014 if (v->child && !view_is_fullscreen(v)) {
2015 wmove(v->child->window, 0, 0);
2016 wdeleteln(v->child->window);
2017 wnoutrefresh(v->child->window);
2020 doupdate();
2023 if (view->dying) {
2024 struct tog_view *v, *prev = NULL;
2026 if (view_is_parent_view(view))
2027 prev = TAILQ_PREV(view, tog_view_list_head,
2028 entry);
2029 else if (view->parent)
2030 prev = view->parent;
2032 if (view->parent) {
2033 view->parent->child = NULL;
2034 view->parent->focus_child = 0;
2035 /* Restore fullscreen line height. */
2036 view->parent->nlines = view->parent->lines;
2037 err = view_resize(view->parent);
2038 if (err)
2039 break;
2040 /* Make resized splits persist. */
2041 view_transfer_size(view->parent, view);
2042 } else
2043 TAILQ_REMOVE(&views, view, entry);
2045 err = view_close(view);
2046 if (err)
2047 goto done;
2049 view = NULL;
2050 TAILQ_FOREACH(v, &views, entry) {
2051 if (v->focussed)
2052 break;
2054 if (view == NULL && new_view == NULL) {
2055 /* No view has focus. Try to pick one. */
2056 if (prev)
2057 view = prev;
2058 else if (!TAILQ_EMPTY(&views)) {
2059 view = TAILQ_LAST(&views,
2060 tog_view_list_head);
2062 if (view) {
2063 if (view->focus_child) {
2064 view->child->focussed = 1;
2065 view = view->child;
2066 } else
2067 view->focussed = 1;
2071 if (new_view) {
2072 struct tog_view *v, *t;
2073 /* Only allow one parent view per type. */
2074 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2075 if (v->type != new_view->type)
2076 continue;
2077 TAILQ_REMOVE(&views, v, entry);
2078 err = view_close(v);
2079 if (err)
2080 goto done;
2081 break;
2083 TAILQ_INSERT_TAIL(&views, new_view, entry);
2084 view = new_view;
2086 if (view && !done) {
2087 if (view_is_parent_view(view)) {
2088 if (view->child && view->child->focussed)
2089 view = view->child;
2090 } else {
2091 if (view->parent && view->parent->focussed)
2092 view = view->parent;
2094 show_panel(view->panel);
2095 if (view->child && view_is_splitscreen(view->child))
2096 show_panel(view->child->panel);
2097 if (view->parent && view_is_splitscreen(view)) {
2098 err = view->parent->show(view->parent);
2099 if (err)
2100 goto done;
2102 err = view->show(view);
2103 if (err)
2104 goto done;
2105 if (view->child) {
2106 err = view->child->show(view->child);
2107 if (err)
2108 goto done;
2110 update_panels();
2111 doupdate();
2114 done:
2115 while (!TAILQ_EMPTY(&views)) {
2116 const struct got_error *close_err;
2117 view = TAILQ_FIRST(&views);
2118 TAILQ_REMOVE(&views, view, entry);
2119 close_err = view_close(view);
2120 if (close_err && err == NULL)
2121 err = close_err;
2124 errcode = pthread_mutex_unlock(&tog_mutex);
2125 if (errcode && err == NULL)
2126 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2128 return err;
2131 __dead static void
2132 usage_log(void)
2134 endwin();
2135 fprintf(stderr,
2136 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2137 getprogname());
2138 exit(1);
2141 /* Create newly allocated wide-character string equivalent to a byte string. */
2142 static const struct got_error *
2143 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2145 char *vis = NULL;
2146 const struct got_error *err = NULL;
2148 *ws = NULL;
2149 *wlen = mbstowcs(NULL, s, 0);
2150 if (*wlen == (size_t)-1) {
2151 int vislen;
2152 if (errno != EILSEQ)
2153 return got_error_from_errno("mbstowcs");
2155 /* byte string invalid in current encoding; try to "fix" it */
2156 err = got_mbsavis(&vis, &vislen, s);
2157 if (err)
2158 return err;
2159 *wlen = mbstowcs(NULL, vis, 0);
2160 if (*wlen == (size_t)-1) {
2161 err = got_error_from_errno("mbstowcs"); /* give up */
2162 goto done;
2166 *ws = calloc(*wlen + 1, sizeof(**ws));
2167 if (*ws == NULL) {
2168 err = got_error_from_errno("calloc");
2169 goto done;
2172 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2173 err = got_error_from_errno("mbstowcs");
2174 done:
2175 free(vis);
2176 if (err) {
2177 free(*ws);
2178 *ws = NULL;
2179 *wlen = 0;
2181 return err;
2184 static const struct got_error *
2185 expand_tab(char **ptr, const char *src)
2187 char *dst;
2188 size_t len, n, idx = 0, sz = 0;
2190 *ptr = NULL;
2191 n = len = strlen(src);
2192 dst = malloc(n + 1);
2193 if (dst == NULL)
2194 return got_error_from_errno("malloc");
2196 while (idx < len && src[idx]) {
2197 const char c = src[idx];
2199 if (c == '\t') {
2200 size_t nb = TABSIZE - sz % TABSIZE;
2201 char *p;
2203 p = realloc(dst, n + nb);
2204 if (p == NULL) {
2205 free(dst);
2206 return got_error_from_errno("realloc");
2209 dst = p;
2210 n += nb;
2211 memset(dst + sz, ' ', nb);
2212 sz += nb;
2213 } else
2214 dst[sz++] = src[idx];
2215 ++idx;
2218 dst[sz] = '\0';
2219 *ptr = dst;
2220 return NULL;
2224 * Advance at most n columns from wline starting at offset off.
2225 * Return the index to the first character after the span operation.
2226 * Return the combined column width of all spanned wide character in
2227 * *rcol.
2229 static int
2230 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2232 int width, i, cols = 0;
2234 if (n == 0) {
2235 *rcol = cols;
2236 return off;
2239 for (i = off; wline[i] != L'\0'; ++i) {
2240 if (wline[i] == L'\t')
2241 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2242 else
2243 width = wcwidth(wline[i]);
2245 if (width == -1) {
2246 width = 1;
2247 wline[i] = L'.';
2250 if (cols + width > n)
2251 break;
2252 cols += width;
2255 *rcol = cols;
2256 return i;
2260 * Format a line for display, ensuring that it won't overflow a width limit.
2261 * With scrolling, the width returned refers to the scrolled version of the
2262 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2264 static const struct got_error *
2265 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2266 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2268 const struct got_error *err = NULL;
2269 int cols;
2270 wchar_t *wline = NULL;
2271 char *exstr = NULL;
2272 size_t wlen;
2273 int i, scrollx;
2275 *wlinep = NULL;
2276 *widthp = 0;
2278 if (expand) {
2279 err = expand_tab(&exstr, line);
2280 if (err)
2281 return err;
2284 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2285 free(exstr);
2286 if (err)
2287 return err;
2289 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2291 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2292 wline[wlen - 1] = L'\0';
2293 wlen--;
2295 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2296 wline[wlen - 1] = L'\0';
2297 wlen--;
2300 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2301 wline[i] = L'\0';
2303 if (widthp)
2304 *widthp = cols;
2305 if (scrollxp)
2306 *scrollxp = scrollx;
2307 if (err)
2308 free(wline);
2309 else
2310 *wlinep = wline;
2311 return err;
2314 static const struct got_error*
2315 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2316 struct got_object_id *id, struct got_repository *repo)
2318 static const struct got_error *err = NULL;
2319 struct got_reflist_entry *re;
2320 char *s;
2321 const char *name;
2323 *refs_str = NULL;
2325 if (refs == NULL)
2326 return NULL;
2328 TAILQ_FOREACH(re, refs, entry) {
2329 struct got_tag_object *tag = NULL;
2330 struct got_object_id *ref_id;
2331 int cmp;
2333 name = got_ref_get_name(re->ref);
2334 if (strcmp(name, GOT_REF_HEAD) == 0)
2335 continue;
2336 if (strncmp(name, "refs/", 5) == 0)
2337 name += 5;
2338 if (strncmp(name, "got/", 4) == 0 &&
2339 strncmp(name, "got/backup/", 11) != 0)
2340 continue;
2341 if (strncmp(name, "heads/", 6) == 0)
2342 name += 6;
2343 if (strncmp(name, "remotes/", 8) == 0) {
2344 name += 8;
2345 s = strstr(name, "/" GOT_REF_HEAD);
2346 if (s != NULL && s[strlen(s)] == '\0')
2347 continue;
2349 err = got_ref_resolve(&ref_id, repo, re->ref);
2350 if (err)
2351 break;
2352 if (strncmp(name, "tags/", 5) == 0) {
2353 err = got_object_open_as_tag(&tag, repo, ref_id);
2354 if (err) {
2355 if (err->code != GOT_ERR_OBJ_TYPE) {
2356 free(ref_id);
2357 break;
2359 /* Ref points at something other than a tag. */
2360 err = NULL;
2361 tag = NULL;
2364 cmp = got_object_id_cmp(tag ?
2365 got_object_tag_get_object_id(tag) : ref_id, id);
2366 free(ref_id);
2367 if (tag)
2368 got_object_tag_close(tag);
2369 if (cmp != 0)
2370 continue;
2371 s = *refs_str;
2372 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2373 s ? ", " : "", name) == -1) {
2374 err = got_error_from_errno("asprintf");
2375 free(s);
2376 *refs_str = NULL;
2377 break;
2379 free(s);
2382 return err;
2385 static const struct got_error *
2386 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2387 int col_tab_align)
2389 char *smallerthan;
2391 smallerthan = strchr(author, '<');
2392 if (smallerthan && smallerthan[1] != '\0')
2393 author = smallerthan + 1;
2394 author[strcspn(author, "@>")] = '\0';
2395 return format_line(wauthor, author_width, NULL, author, 0, limit,
2396 col_tab_align, 0);
2399 static const struct got_error *
2400 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2401 struct got_object_id *id, const size_t date_display_cols,
2402 int author_display_cols)
2404 struct tog_log_view_state *s = &view->state.log;
2405 const struct got_error *err = NULL;
2406 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2407 char *refs_str = NULL;
2408 char *logmsg0 = NULL, *logmsg = NULL;
2409 char *author = NULL;
2410 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2411 int author_width, logmsg_width;
2412 size_t wrefstr_len = 0;
2413 char *newline, *line = NULL;
2414 int col, limit, scrollx;
2415 const int avail = view->ncols;
2416 struct tm tm;
2417 time_t committer_time;
2418 struct tog_color *tc;
2419 struct got_reflist_head *refs;
2421 committer_time = got_object_commit_get_committer_time(commit);
2422 if (gmtime_r(&committer_time, &tm) == NULL)
2423 return got_error_from_errno("gmtime_r");
2424 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2425 return got_error(GOT_ERR_NO_SPACE);
2427 if (avail <= date_display_cols)
2428 limit = MIN(sizeof(datebuf) - 1, avail);
2429 else
2430 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2431 tc = get_color(&s->colors, TOG_COLOR_DATE);
2432 if (tc)
2433 wattr_on(view->window,
2434 COLOR_PAIR(tc->colorpair), NULL);
2435 waddnstr(view->window, datebuf, limit);
2436 if (tc)
2437 wattr_off(view->window,
2438 COLOR_PAIR(tc->colorpair), NULL);
2439 col = limit;
2440 if (col > avail)
2441 goto done;
2443 if (avail >= 120) {
2444 char *id_str;
2445 err = got_object_id_str(&id_str, id);
2446 if (err)
2447 goto done;
2448 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2449 if (tc)
2450 wattr_on(view->window,
2451 COLOR_PAIR(tc->colorpair), NULL);
2452 wprintw(view->window, "%.8s ", id_str);
2453 if (tc)
2454 wattr_off(view->window,
2455 COLOR_PAIR(tc->colorpair), NULL);
2456 free(id_str);
2457 col += 9;
2458 if (col > avail)
2459 goto done;
2462 if (s->use_committer)
2463 author = strdup(got_object_commit_get_committer(commit));
2464 else
2465 author = strdup(got_object_commit_get_author(commit));
2466 if (author == NULL) {
2467 err = got_error_from_errno("strdup");
2468 goto done;
2470 err = format_author(&wauthor, &author_width, author, avail - col, col);
2471 if (err)
2472 goto done;
2473 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2474 if (tc)
2475 wattr_on(view->window,
2476 COLOR_PAIR(tc->colorpair), NULL);
2477 waddwstr(view->window, wauthor);
2478 col += author_width;
2479 while (col < avail && author_width < author_display_cols + 2) {
2480 waddch(view->window, ' ');
2481 col++;
2482 author_width++;
2484 if (tc)
2485 wattr_off(view->window,
2486 COLOR_PAIR(tc->colorpair), NULL);
2487 if (col > avail)
2488 goto done;
2490 err = got_object_commit_get_logmsg(&logmsg0, commit);
2491 if (err)
2492 goto done;
2493 logmsg = logmsg0;
2494 while (*logmsg == '\n')
2495 logmsg++;
2496 newline = strchr(logmsg, '\n');
2497 if (newline)
2498 *newline = '\0';
2500 /* Prepend reference labels to log message if possible .*/
2501 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2502 err = build_refs_str(&refs_str, refs, id, s->repo);
2503 if (err)
2504 goto done;
2505 if (refs_str) {
2506 char *newlogmsg;
2507 wchar_t *ws;
2510 * The length of this wide-char sub-string will be
2511 * needed later for colorization.
2513 err = mbs2ws(&ws, &wrefstr_len, refs_str);
2514 if (err)
2515 goto done;
2516 free(ws);
2518 wrefstr_len += 2; /* account for '[' and ']' */
2520 if (asprintf(&newlogmsg, "[%s] %s", refs_str, logmsg) == -1) {
2521 err = got_error_from_errno("asprintf");
2522 goto done;
2525 free(logmsg0);
2526 logmsg0 = newlogmsg;
2527 logmsg = logmsg0;
2530 limit = avail - col;
2531 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2532 limit--; /* for the border */
2533 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2534 limit, col, 1);
2535 if (err)
2536 goto done;
2537 if (wrefstr_len > 0 && scrollx < wrefstr_len) {
2538 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2539 if (tc)
2540 wattr_on(view->window,
2541 COLOR_PAIR(tc->colorpair), NULL);
2542 waddnwstr(view->window, &wlogmsg[scrollx],
2543 MIN(logmsg_width, wrefstr_len - scrollx));
2544 if (tc)
2545 wattr_off(view->window,
2546 COLOR_PAIR(tc->colorpair), NULL);
2547 if (col + MIN(logmsg_width, wrefstr_len - scrollx) < avail)
2548 waddwstr(view->window, &wlogmsg[wrefstr_len]);
2549 } else
2550 waddwstr(view->window, &wlogmsg[scrollx]);
2551 col += MAX(logmsg_width, 0);
2552 while (col < avail) {
2553 waddch(view->window, ' ');
2554 col++;
2556 done:
2557 free(logmsg0);
2558 free(wlogmsg);
2559 free(refs_str);
2560 free(author);
2561 free(wauthor);
2562 free(line);
2563 return err;
2566 static struct commit_queue_entry *
2567 alloc_commit_queue_entry(struct got_commit_object *commit,
2568 struct got_object_id *id)
2570 struct commit_queue_entry *entry;
2571 struct got_object_id *dup;
2573 entry = calloc(1, sizeof(*entry));
2574 if (entry == NULL)
2575 return NULL;
2577 dup = got_object_id_dup(id);
2578 if (dup == NULL) {
2579 free(entry);
2580 return NULL;
2583 entry->id = dup;
2584 entry->commit = commit;
2585 return entry;
2588 static void
2589 pop_commit(struct commit_queue *commits)
2591 struct commit_queue_entry *entry;
2593 entry = TAILQ_FIRST(&commits->head);
2594 TAILQ_REMOVE(&commits->head, entry, entry);
2595 got_object_commit_close(entry->commit);
2596 commits->ncommits--;
2597 free(entry->id);
2598 free(entry);
2601 static void
2602 free_commits(struct commit_queue *commits)
2604 while (!TAILQ_EMPTY(&commits->head))
2605 pop_commit(commits);
2608 static const struct got_error *
2609 match_commit(int *have_match, struct got_object_id *id,
2610 struct got_commit_object *commit, regex_t *regex)
2612 const struct got_error *err = NULL;
2613 regmatch_t regmatch;
2614 char *id_str = NULL, *logmsg = NULL;
2616 *have_match = 0;
2618 err = got_object_id_str(&id_str, id);
2619 if (err)
2620 return err;
2622 err = got_object_commit_get_logmsg(&logmsg, commit);
2623 if (err)
2624 goto done;
2626 if (regexec(regex, got_object_commit_get_author(commit), 1,
2627 &regmatch, 0) == 0 ||
2628 regexec(regex, got_object_commit_get_committer(commit), 1,
2629 &regmatch, 0) == 0 ||
2630 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2631 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2632 *have_match = 1;
2633 done:
2634 free(id_str);
2635 free(logmsg);
2636 return err;
2639 static const struct got_error *
2640 queue_commits(struct tog_log_thread_args *a)
2642 const struct got_error *err = NULL;
2645 * We keep all commits open throughout the lifetime of the log
2646 * view in order to avoid having to re-fetch commits from disk
2647 * while updating the display.
2649 do {
2650 struct got_object_id id;
2651 struct got_commit_object *commit;
2652 struct commit_queue_entry *entry;
2653 int limit_match = 0;
2654 int errcode;
2656 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2657 NULL, NULL);
2658 if (err)
2659 break;
2661 err = got_object_open_as_commit(&commit, a->repo, &id);
2662 if (err)
2663 break;
2664 entry = alloc_commit_queue_entry(commit, &id);
2665 if (entry == NULL) {
2666 err = got_error_from_errno("alloc_commit_queue_entry");
2667 break;
2670 errcode = pthread_mutex_lock(&tog_mutex);
2671 if (errcode) {
2672 err = got_error_set_errno(errcode,
2673 "pthread_mutex_lock");
2674 break;
2677 entry->idx = a->real_commits->ncommits;
2678 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2679 a->real_commits->ncommits++;
2681 if (*a->limiting) {
2682 err = match_commit(&limit_match, &id, commit,
2683 a->limit_regex);
2684 if (err)
2685 break;
2687 if (limit_match) {
2688 struct commit_queue_entry *matched;
2690 matched = alloc_commit_queue_entry(
2691 entry->commit, entry->id);
2692 if (matched == NULL) {
2693 err = got_error_from_errno(
2694 "alloc_commit_queue_entry");
2695 break;
2697 matched->commit = entry->commit;
2698 got_object_commit_retain(entry->commit);
2700 matched->idx = a->limit_commits->ncommits;
2701 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2702 matched, entry);
2703 a->limit_commits->ncommits++;
2707 * This is how we signal log_thread() that we
2708 * have found a match, and that it should be
2709 * counted as a new entry for the view.
2711 a->limit_match = limit_match;
2714 if (*a->searching == TOG_SEARCH_FORWARD &&
2715 !*a->search_next_done) {
2716 int have_match;
2717 err = match_commit(&have_match, &id, commit, a->regex);
2718 if (err)
2719 break;
2721 if (*a->limiting) {
2722 if (limit_match && have_match)
2723 *a->search_next_done =
2724 TOG_SEARCH_HAVE_MORE;
2725 } else if (have_match)
2726 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2729 errcode = pthread_mutex_unlock(&tog_mutex);
2730 if (errcode && err == NULL)
2731 err = got_error_set_errno(errcode,
2732 "pthread_mutex_unlock");
2733 if (err)
2734 break;
2735 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2737 return err;
2740 static void
2741 select_commit(struct tog_log_view_state *s)
2743 struct commit_queue_entry *entry;
2744 int ncommits = 0;
2746 entry = s->first_displayed_entry;
2747 while (entry) {
2748 if (ncommits == s->selected) {
2749 s->selected_entry = entry;
2750 break;
2752 entry = TAILQ_NEXT(entry, entry);
2753 ncommits++;
2757 static const struct got_error *
2758 draw_commits(struct tog_view *view)
2760 const struct got_error *err = NULL;
2761 struct tog_log_view_state *s = &view->state.log;
2762 struct commit_queue_entry *entry = s->selected_entry;
2763 int limit = view->nlines;
2764 int width;
2765 int ncommits, author_cols = 4;
2766 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2767 char *refs_str = NULL;
2768 wchar_t *wline;
2769 struct tog_color *tc;
2770 static const size_t date_display_cols = 12;
2772 if (view_is_hsplit_top(view))
2773 --limit; /* account for border */
2775 if (s->selected_entry &&
2776 !(view->searching && view->search_next_done == 0)) {
2777 struct got_reflist_head *refs;
2778 err = got_object_id_str(&id_str, s->selected_entry->id);
2779 if (err)
2780 return err;
2781 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2782 s->selected_entry->id);
2783 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2784 s->repo);
2785 if (err)
2786 goto done;
2789 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2790 halfdelay(10); /* disable fast refresh */
2792 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2793 if (asprintf(&ncommits_str, " [%d/%d] %s",
2794 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2795 (view->searching && !view->search_next_done) ?
2796 "searching..." : "loading...") == -1) {
2797 err = got_error_from_errno("asprintf");
2798 goto done;
2800 } else {
2801 const char *search_str = NULL;
2802 const char *limit_str = NULL;
2804 if (view->searching) {
2805 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2806 search_str = "no more matches";
2807 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2808 search_str = "no matches found";
2809 else if (!view->search_next_done)
2810 search_str = "searching...";
2813 if (s->limit_view && s->commits->ncommits == 0)
2814 limit_str = "no matches found";
2816 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2817 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2818 search_str ? search_str : (refs_str ? refs_str : ""),
2819 limit_str ? limit_str : "") == -1) {
2820 err = got_error_from_errno("asprintf");
2821 goto done;
2825 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2826 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2827 "........................................",
2828 s->in_repo_path, ncommits_str) == -1) {
2829 err = got_error_from_errno("asprintf");
2830 header = NULL;
2831 goto done;
2833 } else if (asprintf(&header, "commit %s%s",
2834 id_str ? id_str : "........................................",
2835 ncommits_str) == -1) {
2836 err = got_error_from_errno("asprintf");
2837 header = NULL;
2838 goto done;
2840 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2841 if (err)
2842 goto done;
2844 werase(view->window);
2846 if (view_needs_focus_indication(view))
2847 wstandout(view->window);
2848 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2849 if (tc)
2850 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2851 waddwstr(view->window, wline);
2852 while (width < view->ncols) {
2853 waddch(view->window, ' ');
2854 width++;
2856 if (tc)
2857 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2858 if (view_needs_focus_indication(view))
2859 wstandend(view->window);
2860 free(wline);
2861 if (limit <= 1)
2862 goto done;
2864 /* Grow author column size if necessary, and set view->maxx. */
2865 entry = s->first_displayed_entry;
2866 ncommits = 0;
2867 view->maxx = 0;
2868 while (entry) {
2869 struct got_commit_object *c = entry->commit;
2870 char *author, *eol, *msg, *msg0;
2871 wchar_t *wauthor, *wmsg;
2872 int width;
2873 if (ncommits >= limit - 1)
2874 break;
2875 if (s->use_committer)
2876 author = strdup(got_object_commit_get_committer(c));
2877 else
2878 author = strdup(got_object_commit_get_author(c));
2879 if (author == NULL) {
2880 err = got_error_from_errno("strdup");
2881 goto done;
2883 err = format_author(&wauthor, &width, author, COLS,
2884 date_display_cols);
2885 if (author_cols < width)
2886 author_cols = width;
2887 free(wauthor);
2888 free(author);
2889 if (err)
2890 goto done;
2891 err = got_object_commit_get_logmsg(&msg0, c);
2892 if (err)
2893 goto done;
2894 msg = msg0;
2895 while (*msg == '\n')
2896 ++msg;
2897 if ((eol = strchr(msg, '\n')))
2898 *eol = '\0';
2899 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2900 date_display_cols + author_cols, 0);
2901 if (err)
2902 goto done;
2903 view->maxx = MAX(view->maxx, width);
2904 free(msg0);
2905 free(wmsg);
2906 ncommits++;
2907 entry = TAILQ_NEXT(entry, entry);
2910 entry = s->first_displayed_entry;
2911 s->last_displayed_entry = s->first_displayed_entry;
2912 ncommits = 0;
2913 while (entry) {
2914 if (ncommits >= limit - 1)
2915 break;
2916 if (ncommits == s->selected)
2917 wstandout(view->window);
2918 err = draw_commit(view, entry->commit, entry->id,
2919 date_display_cols, author_cols);
2920 if (ncommits == s->selected)
2921 wstandend(view->window);
2922 if (err)
2923 goto done;
2924 ncommits++;
2925 s->last_displayed_entry = entry;
2926 entry = TAILQ_NEXT(entry, entry);
2929 view_border(view);
2930 done:
2931 free(id_str);
2932 free(refs_str);
2933 free(ncommits_str);
2934 free(header);
2935 return err;
2938 static void
2939 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2941 struct commit_queue_entry *entry;
2942 int nscrolled = 0;
2944 entry = TAILQ_FIRST(&s->commits->head);
2945 if (s->first_displayed_entry == entry)
2946 return;
2948 entry = s->first_displayed_entry;
2949 while (entry && nscrolled < maxscroll) {
2950 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2951 if (entry) {
2952 s->first_displayed_entry = entry;
2953 nscrolled++;
2958 static const struct got_error *
2959 trigger_log_thread(struct tog_view *view, int wait)
2961 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2962 int errcode;
2964 if (!using_mock_io)
2965 halfdelay(1); /* fast refresh while loading commits */
2967 while (!ta->log_complete && !tog_thread_error &&
2968 (ta->commits_needed > 0 || ta->load_all)) {
2969 /* Wake the log thread. */
2970 errcode = pthread_cond_signal(&ta->need_commits);
2971 if (errcode)
2972 return got_error_set_errno(errcode,
2973 "pthread_cond_signal");
2976 * The mutex will be released while the view loop waits
2977 * in wgetch(), at which time the log thread will run.
2979 if (!wait)
2980 break;
2982 /* Display progress update in log view. */
2983 show_log_view(view);
2984 update_panels();
2985 doupdate();
2987 /* Wait right here while next commit is being loaded. */
2988 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2989 if (errcode)
2990 return got_error_set_errno(errcode,
2991 "pthread_cond_wait");
2993 /* Display progress update in log view. */
2994 show_log_view(view);
2995 update_panels();
2996 doupdate();
2999 return NULL;
3002 static const struct got_error *
3003 request_log_commits(struct tog_view *view)
3005 struct tog_log_view_state *state = &view->state.log;
3006 const struct got_error *err = NULL;
3008 if (state->thread_args.log_complete)
3009 return NULL;
3011 state->thread_args.commits_needed += view->nscrolled;
3012 err = trigger_log_thread(view, 1);
3013 view->nscrolled = 0;
3015 return err;
3018 static const struct got_error *
3019 log_scroll_down(struct tog_view *view, int maxscroll)
3021 struct tog_log_view_state *s = &view->state.log;
3022 const struct got_error *err = NULL;
3023 struct commit_queue_entry *pentry;
3024 int nscrolled = 0, ncommits_needed;
3026 if (s->last_displayed_entry == NULL)
3027 return NULL;
3029 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3030 if (s->commits->ncommits < ncommits_needed &&
3031 !s->thread_args.log_complete) {
3033 * Ask the log thread for required amount of commits.
3035 s->thread_args.commits_needed +=
3036 ncommits_needed - s->commits->ncommits;
3037 err = trigger_log_thread(view, 1);
3038 if (err)
3039 return err;
3042 do {
3043 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3044 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3045 break;
3047 s->last_displayed_entry = pentry ?
3048 pentry : s->last_displayed_entry;
3050 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3051 if (pentry == NULL)
3052 break;
3053 s->first_displayed_entry = pentry;
3054 } while (++nscrolled < maxscroll);
3056 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3057 view->nscrolled += nscrolled;
3058 else
3059 view->nscrolled = 0;
3061 return err;
3064 static const struct got_error *
3065 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3066 struct got_commit_object *commit, struct got_object_id *commit_id,
3067 struct tog_view *log_view, struct got_repository *repo)
3069 const struct got_error *err;
3070 struct got_object_qid *parent_id;
3071 struct tog_view *diff_view;
3073 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3074 if (diff_view == NULL)
3075 return got_error_from_errno("view_open");
3077 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3078 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3079 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3080 if (err == NULL)
3081 *new_view = diff_view;
3082 return err;
3085 static const struct got_error *
3086 tree_view_visit_subtree(struct tog_tree_view_state *s,
3087 struct got_tree_object *subtree)
3089 struct tog_parent_tree *parent;
3091 parent = calloc(1, sizeof(*parent));
3092 if (parent == NULL)
3093 return got_error_from_errno("calloc");
3095 parent->tree = s->tree;
3096 parent->first_displayed_entry = s->first_displayed_entry;
3097 parent->selected_entry = s->selected_entry;
3098 parent->selected = s->selected;
3099 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3100 s->tree = subtree;
3101 s->selected = 0;
3102 s->first_displayed_entry = NULL;
3103 return NULL;
3106 static const struct got_error *
3107 tree_view_walk_path(struct tog_tree_view_state *s,
3108 struct got_commit_object *commit, const char *path)
3110 const struct got_error *err = NULL;
3111 struct got_tree_object *tree = NULL;
3112 const char *p;
3113 char *slash, *subpath = NULL;
3115 /* Walk the path and open corresponding tree objects. */
3116 p = path;
3117 while (*p) {
3118 struct got_tree_entry *te;
3119 struct got_object_id *tree_id;
3120 char *te_name;
3122 while (p[0] == '/')
3123 p++;
3125 /* Ensure the correct subtree entry is selected. */
3126 slash = strchr(p, '/');
3127 if (slash == NULL)
3128 te_name = strdup(p);
3129 else
3130 te_name = strndup(p, slash - p);
3131 if (te_name == NULL) {
3132 err = got_error_from_errno("strndup");
3133 break;
3135 te = got_object_tree_find_entry(s->tree, te_name);
3136 if (te == NULL) {
3137 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3138 free(te_name);
3139 break;
3141 free(te_name);
3142 s->first_displayed_entry = s->selected_entry = te;
3144 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3145 break; /* jump to this file's entry */
3147 slash = strchr(p, '/');
3148 if (slash)
3149 subpath = strndup(path, slash - path);
3150 else
3151 subpath = strdup(path);
3152 if (subpath == NULL) {
3153 err = got_error_from_errno("strdup");
3154 break;
3157 err = got_object_id_by_path(&tree_id, s->repo, commit,
3158 subpath);
3159 if (err)
3160 break;
3162 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3163 free(tree_id);
3164 if (err)
3165 break;
3167 err = tree_view_visit_subtree(s, tree);
3168 if (err) {
3169 got_object_tree_close(tree);
3170 break;
3172 if (slash == NULL)
3173 break;
3174 free(subpath);
3175 subpath = NULL;
3176 p = slash;
3179 free(subpath);
3180 return err;
3183 static const struct got_error *
3184 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3185 struct commit_queue_entry *entry, const char *path,
3186 const char *head_ref_name, struct got_repository *repo)
3188 const struct got_error *err = NULL;
3189 struct tog_tree_view_state *s;
3190 struct tog_view *tree_view;
3192 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3193 if (tree_view == NULL)
3194 return got_error_from_errno("view_open");
3196 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3197 if (err)
3198 return err;
3199 s = &tree_view->state.tree;
3201 *new_view = tree_view;
3203 if (got_path_is_root_dir(path))
3204 return NULL;
3206 return tree_view_walk_path(s, entry->commit, path);
3209 static const struct got_error *
3210 block_signals_used_by_main_thread(void)
3212 sigset_t sigset;
3213 int errcode;
3215 if (sigemptyset(&sigset) == -1)
3216 return got_error_from_errno("sigemptyset");
3218 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3219 if (sigaddset(&sigset, SIGWINCH) == -1)
3220 return got_error_from_errno("sigaddset");
3221 if (sigaddset(&sigset, SIGCONT) == -1)
3222 return got_error_from_errno("sigaddset");
3223 if (sigaddset(&sigset, SIGINT) == -1)
3224 return got_error_from_errno("sigaddset");
3225 if (sigaddset(&sigset, SIGTERM) == -1)
3226 return got_error_from_errno("sigaddset");
3228 /* ncurses handles SIGTSTP */
3229 if (sigaddset(&sigset, SIGTSTP) == -1)
3230 return got_error_from_errno("sigaddset");
3232 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3233 if (errcode)
3234 return got_error_set_errno(errcode, "pthread_sigmask");
3236 return NULL;
3239 static void *
3240 log_thread(void *arg)
3242 const struct got_error *err = NULL;
3243 int errcode = 0;
3244 struct tog_log_thread_args *a = arg;
3245 int done = 0;
3248 * Sync startup with main thread such that we begin our
3249 * work once view_input() has released the mutex.
3251 errcode = pthread_mutex_lock(&tog_mutex);
3252 if (errcode) {
3253 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3254 return (void *)err;
3257 err = block_signals_used_by_main_thread();
3258 if (err) {
3259 pthread_mutex_unlock(&tog_mutex);
3260 goto done;
3263 while (!done && !err && !tog_fatal_signal_received()) {
3264 errcode = pthread_mutex_unlock(&tog_mutex);
3265 if (errcode) {
3266 err = got_error_set_errno(errcode,
3267 "pthread_mutex_unlock");
3268 goto done;
3270 err = queue_commits(a);
3271 if (err) {
3272 if (err->code != GOT_ERR_ITER_COMPLETED)
3273 goto done;
3274 err = NULL;
3275 done = 1;
3276 } else if (a->commits_needed > 0 && !a->load_all) {
3277 if (*a->limiting) {
3278 if (a->limit_match)
3279 a->commits_needed--;
3280 } else
3281 a->commits_needed--;
3284 errcode = pthread_mutex_lock(&tog_mutex);
3285 if (errcode) {
3286 err = got_error_set_errno(errcode,
3287 "pthread_mutex_lock");
3288 goto done;
3289 } else if (*a->quit)
3290 done = 1;
3291 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3292 *a->first_displayed_entry =
3293 TAILQ_FIRST(&a->limit_commits->head);
3294 *a->selected_entry = *a->first_displayed_entry;
3295 } else if (*a->first_displayed_entry == NULL) {
3296 *a->first_displayed_entry =
3297 TAILQ_FIRST(&a->real_commits->head);
3298 *a->selected_entry = *a->first_displayed_entry;
3301 errcode = pthread_cond_signal(&a->commit_loaded);
3302 if (errcode) {
3303 err = got_error_set_errno(errcode,
3304 "pthread_cond_signal");
3305 pthread_mutex_unlock(&tog_mutex);
3306 goto done;
3309 if (done)
3310 a->commits_needed = 0;
3311 else {
3312 if (a->commits_needed == 0 && !a->load_all) {
3313 errcode = pthread_cond_wait(&a->need_commits,
3314 &tog_mutex);
3315 if (errcode) {
3316 err = got_error_set_errno(errcode,
3317 "pthread_cond_wait");
3318 pthread_mutex_unlock(&tog_mutex);
3319 goto done;
3321 if (*a->quit)
3322 done = 1;
3326 a->log_complete = 1;
3327 errcode = pthread_mutex_unlock(&tog_mutex);
3328 if (errcode)
3329 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3330 done:
3331 if (err) {
3332 tog_thread_error = 1;
3333 pthread_cond_signal(&a->commit_loaded);
3335 return (void *)err;
3338 static const struct got_error *
3339 stop_log_thread(struct tog_log_view_state *s)
3341 const struct got_error *err = NULL, *thread_err = NULL;
3342 int errcode;
3344 if (s->thread) {
3345 s->quit = 1;
3346 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3347 if (errcode)
3348 return got_error_set_errno(errcode,
3349 "pthread_cond_signal");
3350 errcode = pthread_mutex_unlock(&tog_mutex);
3351 if (errcode)
3352 return got_error_set_errno(errcode,
3353 "pthread_mutex_unlock");
3354 errcode = pthread_join(s->thread, (void **)&thread_err);
3355 if (errcode)
3356 return got_error_set_errno(errcode, "pthread_join");
3357 errcode = pthread_mutex_lock(&tog_mutex);
3358 if (errcode)
3359 return got_error_set_errno(errcode,
3360 "pthread_mutex_lock");
3361 s->thread = NULL;
3364 if (s->thread_args.repo) {
3365 err = got_repo_close(s->thread_args.repo);
3366 s->thread_args.repo = NULL;
3369 if (s->thread_args.pack_fds) {
3370 const struct got_error *pack_err =
3371 got_repo_pack_fds_close(s->thread_args.pack_fds);
3372 if (err == NULL)
3373 err = pack_err;
3374 s->thread_args.pack_fds = NULL;
3377 if (s->thread_args.graph) {
3378 got_commit_graph_close(s->thread_args.graph);
3379 s->thread_args.graph = NULL;
3382 return err ? err : thread_err;
3385 static const struct got_error *
3386 close_log_view(struct tog_view *view)
3388 const struct got_error *err = NULL;
3389 struct tog_log_view_state *s = &view->state.log;
3390 int errcode;
3392 err = stop_log_thread(s);
3394 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3395 if (errcode && err == NULL)
3396 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3398 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3399 if (errcode && err == NULL)
3400 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3402 free_commits(&s->limit_commits);
3403 free_commits(&s->real_commits);
3404 free(s->in_repo_path);
3405 s->in_repo_path = NULL;
3406 free(s->start_id);
3407 s->start_id = NULL;
3408 free(s->head_ref_name);
3409 s->head_ref_name = NULL;
3410 return err;
3414 * We use two queues to implement the limit feature: first consists of
3415 * commits matching the current limit_regex; second is the real queue
3416 * of all known commits (real_commits). When the user starts limiting,
3417 * we swap queues such that all movement and displaying functionality
3418 * works with very slight change.
3420 static const struct got_error *
3421 limit_log_view(struct tog_view *view)
3423 struct tog_log_view_state *s = &view->state.log;
3424 struct commit_queue_entry *entry;
3425 struct tog_view *v = view;
3426 const struct got_error *err = NULL;
3427 char pattern[1024];
3428 int ret;
3430 if (view_is_hsplit_top(view))
3431 v = view->child;
3432 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3433 v = view->parent;
3435 /* Get the pattern */
3436 wmove(v->window, v->nlines - 1, 0);
3437 wclrtoeol(v->window);
3438 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3439 nodelay(v->window, FALSE);
3440 nocbreak();
3441 echo();
3442 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3443 cbreak();
3444 noecho();
3445 nodelay(v->window, TRUE);
3446 if (ret == ERR)
3447 return NULL;
3449 if (*pattern == '\0') {
3451 * Safety measure for the situation where the user
3452 * resets limit without previously limiting anything.
3454 if (!s->limit_view)
3455 return NULL;
3458 * User could have pressed Ctrl+L, which refreshed the
3459 * commit queues, it means we can't save previously
3460 * (before limit took place) displayed entries,
3461 * because they would point to already free'ed memory,
3462 * so we are forced to always select first entry of
3463 * the queue.
3465 s->commits = &s->real_commits;
3466 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3467 s->selected_entry = s->first_displayed_entry;
3468 s->selected = 0;
3469 s->limit_view = 0;
3471 return NULL;
3474 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3475 return NULL;
3477 s->limit_view = 1;
3479 /* Clear the screen while loading limit view */
3480 s->first_displayed_entry = NULL;
3481 s->last_displayed_entry = NULL;
3482 s->selected_entry = NULL;
3483 s->commits = &s->limit_commits;
3485 /* Prepare limit queue for new search */
3486 free_commits(&s->limit_commits);
3487 s->limit_commits.ncommits = 0;
3489 /* First process commits, which are in queue already */
3490 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3491 int have_match = 0;
3493 err = match_commit(&have_match, entry->id,
3494 entry->commit, &s->limit_regex);
3495 if (err)
3496 return err;
3498 if (have_match) {
3499 struct commit_queue_entry *matched;
3501 matched = alloc_commit_queue_entry(entry->commit,
3502 entry->id);
3503 if (matched == NULL) {
3504 err = got_error_from_errno(
3505 "alloc_commit_queue_entry");
3506 break;
3508 matched->commit = entry->commit;
3509 got_object_commit_retain(entry->commit);
3511 matched->idx = s->limit_commits.ncommits;
3512 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3513 matched, entry);
3514 s->limit_commits.ncommits++;
3518 /* Second process all the commits, until we fill the screen */
3519 if (s->limit_commits.ncommits < view->nlines - 1 &&
3520 !s->thread_args.log_complete) {
3521 s->thread_args.commits_needed +=
3522 view->nlines - s->limit_commits.ncommits - 1;
3523 err = trigger_log_thread(view, 1);
3524 if (err)
3525 return err;
3528 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3529 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3530 s->selected = 0;
3532 return NULL;
3535 static const struct got_error *
3536 search_start_log_view(struct tog_view *view)
3538 struct tog_log_view_state *s = &view->state.log;
3540 s->matched_entry = NULL;
3541 s->search_entry = NULL;
3542 return NULL;
3545 static const struct got_error *
3546 search_next_log_view(struct tog_view *view)
3548 const struct got_error *err = NULL;
3549 struct tog_log_view_state *s = &view->state.log;
3550 struct commit_queue_entry *entry;
3552 /* Display progress update in log view. */
3553 show_log_view(view);
3554 update_panels();
3555 doupdate();
3557 if (s->search_entry) {
3558 int errcode, ch;
3559 errcode = pthread_mutex_unlock(&tog_mutex);
3560 if (errcode)
3561 return got_error_set_errno(errcode,
3562 "pthread_mutex_unlock");
3563 ch = wgetch(view->window);
3564 errcode = pthread_mutex_lock(&tog_mutex);
3565 if (errcode)
3566 return got_error_set_errno(errcode,
3567 "pthread_mutex_lock");
3568 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3569 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3570 return NULL;
3572 if (view->searching == TOG_SEARCH_FORWARD)
3573 entry = TAILQ_NEXT(s->search_entry, entry);
3574 else
3575 entry = TAILQ_PREV(s->search_entry,
3576 commit_queue_head, entry);
3577 } else if (s->matched_entry) {
3579 * If the user has moved the cursor after we hit a match,
3580 * the position from where we should continue searching
3581 * might have changed.
3583 if (view->searching == TOG_SEARCH_FORWARD)
3584 entry = TAILQ_NEXT(s->selected_entry, entry);
3585 else
3586 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3587 entry);
3588 } else {
3589 entry = s->selected_entry;
3592 while (1) {
3593 int have_match = 0;
3595 if (entry == NULL) {
3596 if (s->thread_args.log_complete ||
3597 view->searching == TOG_SEARCH_BACKWARD) {
3598 view->search_next_done =
3599 (s->matched_entry == NULL ?
3600 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3601 s->search_entry = NULL;
3602 return NULL;
3605 * Poke the log thread for more commits and return,
3606 * allowing the main loop to make progress. Search
3607 * will resume at s->search_entry once we come back.
3609 s->thread_args.commits_needed++;
3610 return trigger_log_thread(view, 0);
3613 err = match_commit(&have_match, entry->id, entry->commit,
3614 &view->regex);
3615 if (err)
3616 break;
3617 if (have_match) {
3618 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3619 s->matched_entry = entry;
3620 break;
3623 s->search_entry = entry;
3624 if (view->searching == TOG_SEARCH_FORWARD)
3625 entry = TAILQ_NEXT(entry, entry);
3626 else
3627 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3630 if (s->matched_entry) {
3631 int cur = s->selected_entry->idx;
3632 while (cur < s->matched_entry->idx) {
3633 err = input_log_view(NULL, view, KEY_DOWN);
3634 if (err)
3635 return err;
3636 cur++;
3638 while (cur > s->matched_entry->idx) {
3639 err = input_log_view(NULL, view, KEY_UP);
3640 if (err)
3641 return err;
3642 cur--;
3646 s->search_entry = NULL;
3648 return NULL;
3651 static const struct got_error *
3652 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3653 struct got_repository *repo, const char *head_ref_name,
3654 const char *in_repo_path, int log_branches)
3656 const struct got_error *err = NULL;
3657 struct tog_log_view_state *s = &view->state.log;
3658 struct got_repository *thread_repo = NULL;
3659 struct got_commit_graph *thread_graph = NULL;
3660 int errcode;
3662 if (in_repo_path != s->in_repo_path) {
3663 free(s->in_repo_path);
3664 s->in_repo_path = strdup(in_repo_path);
3665 if (s->in_repo_path == NULL) {
3666 err = got_error_from_errno("strdup");
3667 goto done;
3671 /* The commit queue only contains commits being displayed. */
3672 TAILQ_INIT(&s->real_commits.head);
3673 s->real_commits.ncommits = 0;
3674 s->commits = &s->real_commits;
3676 TAILQ_INIT(&s->limit_commits.head);
3677 s->limit_view = 0;
3678 s->limit_commits.ncommits = 0;
3680 s->repo = repo;
3681 if (head_ref_name) {
3682 s->head_ref_name = strdup(head_ref_name);
3683 if (s->head_ref_name == NULL) {
3684 err = got_error_from_errno("strdup");
3685 goto done;
3688 s->start_id = got_object_id_dup(start_id);
3689 if (s->start_id == NULL) {
3690 err = got_error_from_errno("got_object_id_dup");
3691 goto done;
3693 s->log_branches = log_branches;
3694 s->use_committer = 1;
3696 STAILQ_INIT(&s->colors);
3697 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3698 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3699 get_color_value("TOG_COLOR_COMMIT"));
3700 if (err)
3701 goto done;
3702 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3703 get_color_value("TOG_COLOR_AUTHOR"));
3704 if (err) {
3705 free_colors(&s->colors);
3706 goto done;
3708 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3709 get_color_value("TOG_COLOR_DATE"));
3710 if (err) {
3711 free_colors(&s->colors);
3712 goto done;
3716 view->show = show_log_view;
3717 view->input = input_log_view;
3718 view->resize = resize_log_view;
3719 view->close = close_log_view;
3720 view->search_start = search_start_log_view;
3721 view->search_next = search_next_log_view;
3723 if (s->thread_args.pack_fds == NULL) {
3724 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3725 if (err)
3726 goto done;
3728 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3729 s->thread_args.pack_fds);
3730 if (err)
3731 goto done;
3732 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3733 !s->log_branches);
3734 if (err)
3735 goto done;
3736 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3737 s->repo, NULL, NULL);
3738 if (err)
3739 goto done;
3741 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3742 if (errcode) {
3743 err = got_error_set_errno(errcode, "pthread_cond_init");
3744 goto done;
3746 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3747 if (errcode) {
3748 err = got_error_set_errno(errcode, "pthread_cond_init");
3749 goto done;
3752 s->thread_args.commits_needed = view->nlines;
3753 s->thread_args.graph = thread_graph;
3754 s->thread_args.real_commits = &s->real_commits;
3755 s->thread_args.limit_commits = &s->limit_commits;
3756 s->thread_args.in_repo_path = s->in_repo_path;
3757 s->thread_args.start_id = s->start_id;
3758 s->thread_args.repo = thread_repo;
3759 s->thread_args.log_complete = 0;
3760 s->thread_args.quit = &s->quit;
3761 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3762 s->thread_args.selected_entry = &s->selected_entry;
3763 s->thread_args.searching = &view->searching;
3764 s->thread_args.search_next_done = &view->search_next_done;
3765 s->thread_args.regex = &view->regex;
3766 s->thread_args.limiting = &s->limit_view;
3767 s->thread_args.limit_regex = &s->limit_regex;
3768 s->thread_args.limit_commits = &s->limit_commits;
3769 done:
3770 if (err) {
3771 if (view->close == NULL)
3772 close_log_view(view);
3773 view_close(view);
3775 return err;
3778 static const struct got_error *
3779 show_log_view(struct tog_view *view)
3781 const struct got_error *err;
3782 struct tog_log_view_state *s = &view->state.log;
3784 if (s->thread == NULL) {
3785 int errcode = pthread_create(&s->thread, NULL, log_thread,
3786 &s->thread_args);
3787 if (errcode)
3788 return got_error_set_errno(errcode, "pthread_create");
3789 if (s->thread_args.commits_needed > 0) {
3790 err = trigger_log_thread(view, 1);
3791 if (err)
3792 return err;
3796 return draw_commits(view);
3799 static void
3800 log_move_cursor_up(struct tog_view *view, int page, int home)
3802 struct tog_log_view_state *s = &view->state.log;
3804 if (s->first_displayed_entry == NULL)
3805 return;
3806 if (s->selected_entry->idx == 0)
3807 view->count = 0;
3809 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3810 || home)
3811 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3813 if (!page && !home && s->selected > 0)
3814 --s->selected;
3815 else
3816 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3818 select_commit(s);
3819 return;
3822 static const struct got_error *
3823 log_move_cursor_down(struct tog_view *view, int page)
3825 struct tog_log_view_state *s = &view->state.log;
3826 const struct got_error *err = NULL;
3827 int eos = view->nlines - 2;
3829 if (s->first_displayed_entry == NULL)
3830 return NULL;
3832 if (s->thread_args.log_complete &&
3833 s->selected_entry->idx >= s->commits->ncommits - 1)
3834 return NULL;
3836 if (view_is_hsplit_top(view))
3837 --eos; /* border consumes the last line */
3839 if (!page) {
3840 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3841 ++s->selected;
3842 else
3843 err = log_scroll_down(view, 1);
3844 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3845 struct commit_queue_entry *entry;
3846 int n;
3848 s->selected = 0;
3849 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3850 s->last_displayed_entry = entry;
3851 for (n = 0; n <= eos; n++) {
3852 if (entry == NULL)
3853 break;
3854 s->first_displayed_entry = entry;
3855 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3857 if (n > 0)
3858 s->selected = n - 1;
3859 } else {
3860 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3861 s->thread_args.log_complete)
3862 s->selected += MIN(page,
3863 s->commits->ncommits - s->selected_entry->idx - 1);
3864 else
3865 err = log_scroll_down(view, page);
3867 if (err)
3868 return err;
3871 * We might necessarily overshoot in horizontal
3872 * splits; if so, select the last displayed commit.
3874 if (s->first_displayed_entry && s->last_displayed_entry) {
3875 s->selected = MIN(s->selected,
3876 s->last_displayed_entry->idx -
3877 s->first_displayed_entry->idx);
3880 select_commit(s);
3882 if (s->thread_args.log_complete &&
3883 s->selected_entry->idx == s->commits->ncommits - 1)
3884 view->count = 0;
3886 return NULL;
3889 static void
3890 view_get_split(struct tog_view *view, int *y, int *x)
3892 *x = 0;
3893 *y = 0;
3895 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3896 if (view->child && view->child->resized_y)
3897 *y = view->child->resized_y;
3898 else if (view->resized_y)
3899 *y = view->resized_y;
3900 else
3901 *y = view_split_begin_y(view->lines);
3902 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3903 if (view->child && view->child->resized_x)
3904 *x = view->child->resized_x;
3905 else if (view->resized_x)
3906 *x = view->resized_x;
3907 else
3908 *x = view_split_begin_x(view->begin_x);
3912 /* Split view horizontally at y and offset view->state->selected line. */
3913 static const struct got_error *
3914 view_init_hsplit(struct tog_view *view, int y)
3916 const struct got_error *err = NULL;
3918 view->nlines = y;
3919 view->ncols = COLS;
3920 err = view_resize(view);
3921 if (err)
3922 return err;
3924 err = offset_selection_down(view);
3926 return err;
3929 static const struct got_error *
3930 log_goto_line(struct tog_view *view, int nlines)
3932 const struct got_error *err = NULL;
3933 struct tog_log_view_state *s = &view->state.log;
3934 int g, idx = s->selected_entry->idx;
3936 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3937 return NULL;
3939 g = view->gline;
3940 view->gline = 0;
3942 if (g >= s->first_displayed_entry->idx + 1 &&
3943 g <= s->last_displayed_entry->idx + 1 &&
3944 g - s->first_displayed_entry->idx - 1 < nlines) {
3945 s->selected = g - s->first_displayed_entry->idx - 1;
3946 select_commit(s);
3947 return NULL;
3950 if (idx + 1 < g) {
3951 err = log_move_cursor_down(view, g - idx - 1);
3952 if (!err && g > s->selected_entry->idx + 1)
3953 err = log_move_cursor_down(view,
3954 g - s->first_displayed_entry->idx - 1);
3955 if (err)
3956 return err;
3957 } else if (idx + 1 > g)
3958 log_move_cursor_up(view, idx - g + 1, 0);
3960 if (g < nlines && s->first_displayed_entry->idx == 0)
3961 s->selected = g - 1;
3963 select_commit(s);
3964 return NULL;
3968 static void
3969 horizontal_scroll_input(struct tog_view *view, int ch)
3972 switch (ch) {
3973 case KEY_LEFT:
3974 case 'h':
3975 view->x -= MIN(view->x, 2);
3976 if (view->x <= 0)
3977 view->count = 0;
3978 break;
3979 case KEY_RIGHT:
3980 case 'l':
3981 if (view->x + view->ncols / 2 < view->maxx)
3982 view->x += 2;
3983 else
3984 view->count = 0;
3985 break;
3986 case '0':
3987 view->x = 0;
3988 break;
3989 case '$':
3990 view->x = MAX(view->maxx - view->ncols / 2, 0);
3991 view->count = 0;
3992 break;
3993 default:
3994 break;
3998 static const struct got_error *
3999 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4001 const struct got_error *err = NULL;
4002 struct tog_log_view_state *s = &view->state.log;
4003 int eos, nscroll;
4005 if (s->thread_args.load_all) {
4006 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4007 s->thread_args.load_all = 0;
4008 else if (s->thread_args.log_complete) {
4009 err = log_move_cursor_down(view, s->commits->ncommits);
4010 s->thread_args.load_all = 0;
4012 if (err)
4013 return err;
4016 eos = nscroll = view->nlines - 1;
4017 if (view_is_hsplit_top(view))
4018 --eos; /* border */
4020 if (view->gline)
4021 return log_goto_line(view, eos);
4023 switch (ch) {
4024 case '&':
4025 err = limit_log_view(view);
4026 break;
4027 case 'q':
4028 s->quit = 1;
4029 break;
4030 case '0':
4031 case '$':
4032 case KEY_RIGHT:
4033 case 'l':
4034 case KEY_LEFT:
4035 case 'h':
4036 horizontal_scroll_input(view, ch);
4037 break;
4038 case 'k':
4039 case KEY_UP:
4040 case '<':
4041 case ',':
4042 case CTRL('p'):
4043 log_move_cursor_up(view, 0, 0);
4044 break;
4045 case 'g':
4046 case '=':
4047 case KEY_HOME:
4048 log_move_cursor_up(view, 0, 1);
4049 view->count = 0;
4050 break;
4051 case CTRL('u'):
4052 case 'u':
4053 nscroll /= 2;
4054 /* FALL THROUGH */
4055 case KEY_PPAGE:
4056 case CTRL('b'):
4057 case 'b':
4058 log_move_cursor_up(view, nscroll, 0);
4059 break;
4060 case 'j':
4061 case KEY_DOWN:
4062 case '>':
4063 case '.':
4064 case CTRL('n'):
4065 err = log_move_cursor_down(view, 0);
4066 break;
4067 case '@':
4068 s->use_committer = !s->use_committer;
4069 view->action = s->use_committer ?
4070 "show committer" : "show commit author";
4071 break;
4072 case 'G':
4073 case '*':
4074 case KEY_END: {
4075 /* We don't know yet how many commits, so we're forced to
4076 * traverse them all. */
4077 view->count = 0;
4078 s->thread_args.load_all = 1;
4079 if (!s->thread_args.log_complete)
4080 return trigger_log_thread(view, 0);
4081 err = log_move_cursor_down(view, s->commits->ncommits);
4082 s->thread_args.load_all = 0;
4083 break;
4085 case CTRL('d'):
4086 case 'd':
4087 nscroll /= 2;
4088 /* FALL THROUGH */
4089 case KEY_NPAGE:
4090 case CTRL('f'):
4091 case 'f':
4092 case ' ':
4093 err = log_move_cursor_down(view, nscroll);
4094 break;
4095 case KEY_RESIZE:
4096 if (s->selected > view->nlines - 2)
4097 s->selected = view->nlines - 2;
4098 if (s->selected > s->commits->ncommits - 1)
4099 s->selected = s->commits->ncommits - 1;
4100 select_commit(s);
4101 if (s->commits->ncommits < view->nlines - 1 &&
4102 !s->thread_args.log_complete) {
4103 s->thread_args.commits_needed += (view->nlines - 1) -
4104 s->commits->ncommits;
4105 err = trigger_log_thread(view, 1);
4107 break;
4108 case KEY_ENTER:
4109 case '\r':
4110 view->count = 0;
4111 if (s->selected_entry == NULL)
4112 break;
4113 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4114 break;
4115 case 'T':
4116 view->count = 0;
4117 if (s->selected_entry == NULL)
4118 break;
4119 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4120 break;
4121 case KEY_BACKSPACE:
4122 case CTRL('l'):
4123 case 'B':
4124 view->count = 0;
4125 if (ch == KEY_BACKSPACE &&
4126 got_path_is_root_dir(s->in_repo_path))
4127 break;
4128 err = stop_log_thread(s);
4129 if (err)
4130 return err;
4131 if (ch == KEY_BACKSPACE) {
4132 char *parent_path;
4133 err = got_path_dirname(&parent_path, s->in_repo_path);
4134 if (err)
4135 return err;
4136 free(s->in_repo_path);
4137 s->in_repo_path = parent_path;
4138 s->thread_args.in_repo_path = s->in_repo_path;
4139 } else if (ch == CTRL('l')) {
4140 struct got_object_id *start_id;
4141 err = got_repo_match_object_id(&start_id, NULL,
4142 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4143 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4144 if (err) {
4145 if (s->head_ref_name == NULL ||
4146 err->code != GOT_ERR_NOT_REF)
4147 return err;
4148 /* Try to cope with deleted references. */
4149 free(s->head_ref_name);
4150 s->head_ref_name = NULL;
4151 err = got_repo_match_object_id(&start_id,
4152 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4153 &tog_refs, s->repo);
4154 if (err)
4155 return err;
4157 free(s->start_id);
4158 s->start_id = start_id;
4159 s->thread_args.start_id = s->start_id;
4160 } else /* 'B' */
4161 s->log_branches = !s->log_branches;
4163 if (s->thread_args.pack_fds == NULL) {
4164 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4165 if (err)
4166 return err;
4168 err = got_repo_open(&s->thread_args.repo,
4169 got_repo_get_path(s->repo), NULL,
4170 s->thread_args.pack_fds);
4171 if (err)
4172 return err;
4173 tog_free_refs();
4174 err = tog_load_refs(s->repo, 0);
4175 if (err)
4176 return err;
4177 err = got_commit_graph_open(&s->thread_args.graph,
4178 s->in_repo_path, !s->log_branches);
4179 if (err)
4180 return err;
4181 err = got_commit_graph_iter_start(s->thread_args.graph,
4182 s->start_id, s->repo, NULL, NULL);
4183 if (err)
4184 return err;
4185 free_commits(&s->real_commits);
4186 free_commits(&s->limit_commits);
4187 s->first_displayed_entry = NULL;
4188 s->last_displayed_entry = NULL;
4189 s->selected_entry = NULL;
4190 s->selected = 0;
4191 s->thread_args.log_complete = 0;
4192 s->quit = 0;
4193 s->thread_args.commits_needed = view->lines;
4194 s->matched_entry = NULL;
4195 s->search_entry = NULL;
4196 view->offset = 0;
4197 break;
4198 case 'R':
4199 view->count = 0;
4200 err = view_request_new(new_view, view, TOG_VIEW_REF);
4201 break;
4202 default:
4203 view->count = 0;
4204 break;
4207 return err;
4210 static const struct got_error *
4211 apply_unveil(const char *repo_path, const char *worktree_path)
4213 const struct got_error *error;
4215 #ifdef PROFILE
4216 if (unveil("gmon.out", "rwc") != 0)
4217 return got_error_from_errno2("unveil", "gmon.out");
4218 #endif
4219 if (repo_path && unveil(repo_path, "r") != 0)
4220 return got_error_from_errno2("unveil", repo_path);
4222 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4223 return got_error_from_errno2("unveil", worktree_path);
4225 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4226 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4228 error = got_privsep_unveil_exec_helpers();
4229 if (error != NULL)
4230 return error;
4232 if (unveil(NULL, NULL) != 0)
4233 return got_error_from_errno("unveil");
4235 return NULL;
4238 static const struct got_error *
4239 init_mock_term(const char *test_script_path)
4241 const struct got_error *err = NULL;
4242 const char *screen_dump_path;
4243 int in;
4245 if (test_script_path == NULL || *test_script_path == '\0')
4246 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4248 tog_io.f = fopen(test_script_path, "re");
4249 if (tog_io.f == NULL) {
4250 err = got_error_from_errno_fmt("fopen: %s",
4251 test_script_path);
4252 goto done;
4255 /* test mode, we don't want any output */
4256 tog_io.cout = fopen("/dev/null", "w+");
4257 if (tog_io.cout == NULL) {
4258 err = got_error_from_errno2("fopen", "/dev/null");
4259 goto done;
4262 in = dup(fileno(tog_io.cout));
4263 if (in == -1) {
4264 err = got_error_from_errno("dup");
4265 goto done;
4267 tog_io.cin = fdopen(in, "r");
4268 if (tog_io.cin == NULL) {
4269 err = got_error_from_errno("fdopen");
4270 close(in);
4271 goto done;
4274 screen_dump_path = getenv("TOG_SCR_DUMP");
4275 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4276 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4277 tog_io.sdump = fopen(screen_dump_path, "wex");
4278 if (tog_io.sdump == NULL) {
4279 err = got_error_from_errno2("fopen", screen_dump_path);
4280 goto done;
4283 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4284 err = got_error_from_errno("fseeko");
4285 goto done;
4288 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4289 err = got_error_msg(GOT_ERR_IO,
4290 "newterm: failed to initialise curses");
4292 using_mock_io = 1;
4294 done:
4295 if (err)
4296 tog_io_close();
4297 return err;
4300 static void
4301 init_curses(void)
4304 * Override default signal handlers before starting ncurses.
4305 * This should prevent ncurses from installing its own
4306 * broken cleanup() signal handler.
4308 signal(SIGWINCH, tog_sigwinch);
4309 signal(SIGPIPE, tog_sigpipe);
4310 signal(SIGCONT, tog_sigcont);
4311 signal(SIGINT, tog_sigint);
4312 signal(SIGTERM, tog_sigterm);
4314 if (using_mock_io) /* In test mode we use a fake terminal */
4315 return;
4317 initscr();
4319 cbreak();
4320 halfdelay(1); /* Fast refresh while initial view is loading. */
4321 noecho();
4322 nonl();
4323 intrflush(stdscr, FALSE);
4324 keypad(stdscr, TRUE);
4325 curs_set(0);
4326 if (getenv("TOG_COLORS") != NULL) {
4327 start_color();
4328 use_default_colors();
4331 return;
4334 static const struct got_error *
4335 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4336 struct got_repository *repo, struct got_worktree *worktree)
4338 const struct got_error *err = NULL;
4340 if (argc == 0) {
4341 *in_repo_path = strdup("/");
4342 if (*in_repo_path == NULL)
4343 return got_error_from_errno("strdup");
4344 return NULL;
4347 if (worktree) {
4348 const char *prefix = got_worktree_get_path_prefix(worktree);
4349 char *p;
4351 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4352 if (err)
4353 return err;
4354 if (asprintf(in_repo_path, "%s%s%s", prefix,
4355 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4356 p) == -1) {
4357 err = got_error_from_errno("asprintf");
4358 *in_repo_path = NULL;
4360 free(p);
4361 } else
4362 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4364 return err;
4367 static const struct got_error *
4368 cmd_log(int argc, char *argv[])
4370 const struct got_error *error;
4371 struct got_repository *repo = NULL;
4372 struct got_worktree *worktree = NULL;
4373 struct got_object_id *start_id = NULL;
4374 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4375 char *start_commit = NULL, *label = NULL;
4376 struct got_reference *ref = NULL;
4377 const char *head_ref_name = NULL;
4378 int ch, log_branches = 0;
4379 struct tog_view *view;
4380 int *pack_fds = NULL;
4382 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4383 switch (ch) {
4384 case 'b':
4385 log_branches = 1;
4386 break;
4387 case 'c':
4388 start_commit = optarg;
4389 break;
4390 case 'r':
4391 repo_path = realpath(optarg, NULL);
4392 if (repo_path == NULL)
4393 return got_error_from_errno2("realpath",
4394 optarg);
4395 break;
4396 default:
4397 usage_log();
4398 /* NOTREACHED */
4402 argc -= optind;
4403 argv += optind;
4405 if (argc > 1)
4406 usage_log();
4408 error = got_repo_pack_fds_open(&pack_fds);
4409 if (error != NULL)
4410 goto done;
4412 if (repo_path == NULL) {
4413 cwd = getcwd(NULL, 0);
4414 if (cwd == NULL)
4415 return got_error_from_errno("getcwd");
4416 error = got_worktree_open(&worktree, cwd);
4417 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4418 goto done;
4419 if (worktree)
4420 repo_path =
4421 strdup(got_worktree_get_repo_path(worktree));
4422 else
4423 repo_path = strdup(cwd);
4424 if (repo_path == NULL) {
4425 error = got_error_from_errno("strdup");
4426 goto done;
4430 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4431 if (error != NULL)
4432 goto done;
4434 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4435 repo, worktree);
4436 if (error)
4437 goto done;
4439 init_curses();
4441 error = apply_unveil(got_repo_get_path(repo),
4442 worktree ? got_worktree_get_root_path(worktree) : NULL);
4443 if (error)
4444 goto done;
4446 /* already loaded by tog_log_with_path()? */
4447 if (TAILQ_EMPTY(&tog_refs)) {
4448 error = tog_load_refs(repo, 0);
4449 if (error)
4450 goto done;
4453 if (start_commit == NULL) {
4454 error = got_repo_match_object_id(&start_id, &label,
4455 worktree ? got_worktree_get_head_ref_name(worktree) :
4456 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4457 if (error)
4458 goto done;
4459 head_ref_name = label;
4460 } else {
4461 error = got_ref_open(&ref, repo, start_commit, 0);
4462 if (error == NULL)
4463 head_ref_name = got_ref_get_name(ref);
4464 else if (error->code != GOT_ERR_NOT_REF)
4465 goto done;
4466 error = got_repo_match_object_id(&start_id, NULL,
4467 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4468 if (error)
4469 goto done;
4472 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4473 if (view == NULL) {
4474 error = got_error_from_errno("view_open");
4475 goto done;
4477 error = open_log_view(view, start_id, repo, head_ref_name,
4478 in_repo_path, log_branches);
4479 if (error)
4480 goto done;
4481 if (worktree) {
4482 /* Release work tree lock. */
4483 got_worktree_close(worktree);
4484 worktree = NULL;
4486 error = view_loop(view);
4487 done:
4488 free(in_repo_path);
4489 free(repo_path);
4490 free(cwd);
4491 free(start_id);
4492 free(label);
4493 if (ref)
4494 got_ref_close(ref);
4495 if (repo) {
4496 const struct got_error *close_err = got_repo_close(repo);
4497 if (error == NULL)
4498 error = close_err;
4500 if (worktree)
4501 got_worktree_close(worktree);
4502 if (pack_fds) {
4503 const struct got_error *pack_err =
4504 got_repo_pack_fds_close(pack_fds);
4505 if (error == NULL)
4506 error = pack_err;
4508 tog_free_refs();
4509 return error;
4512 __dead static void
4513 usage_diff(void)
4515 endwin();
4516 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4517 "object1 object2\n", getprogname());
4518 exit(1);
4521 static int
4522 match_line(const char *line, regex_t *regex, size_t nmatch,
4523 regmatch_t *regmatch)
4525 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4528 static struct tog_color *
4529 match_color(struct tog_colors *colors, const char *line)
4531 struct tog_color *tc = NULL;
4533 STAILQ_FOREACH(tc, colors, entry) {
4534 if (match_line(line, &tc->regex, 0, NULL))
4535 return tc;
4538 return NULL;
4541 static const struct got_error *
4542 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4543 WINDOW *window, int skipcol, regmatch_t *regmatch)
4545 const struct got_error *err = NULL;
4546 char *exstr = NULL;
4547 wchar_t *wline = NULL;
4548 int rme, rms, n, width, scrollx;
4549 int width0 = 0, width1 = 0, width2 = 0;
4550 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4552 *wtotal = 0;
4554 rms = regmatch->rm_so;
4555 rme = regmatch->rm_eo;
4557 err = expand_tab(&exstr, line);
4558 if (err)
4559 return err;
4561 /* Split the line into 3 segments, according to match offsets. */
4562 seg0 = strndup(exstr, rms);
4563 if (seg0 == NULL) {
4564 err = got_error_from_errno("strndup");
4565 goto done;
4567 seg1 = strndup(exstr + rms, rme - rms);
4568 if (seg1 == NULL) {
4569 err = got_error_from_errno("strndup");
4570 goto done;
4572 seg2 = strdup(exstr + rme);
4573 if (seg2 == NULL) {
4574 err = got_error_from_errno("strndup");
4575 goto done;
4578 /* draw up to matched token if we haven't scrolled past it */
4579 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4580 col_tab_align, 1);
4581 if (err)
4582 goto done;
4583 n = MAX(width0 - skipcol, 0);
4584 if (n) {
4585 free(wline);
4586 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4587 wlimit, col_tab_align, 1);
4588 if (err)
4589 goto done;
4590 waddwstr(window, &wline[scrollx]);
4591 wlimit -= width;
4592 *wtotal += width;
4595 if (wlimit > 0) {
4596 int i = 0, w = 0;
4597 size_t wlen;
4599 free(wline);
4600 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4601 col_tab_align, 1);
4602 if (err)
4603 goto done;
4604 wlen = wcslen(wline);
4605 while (i < wlen) {
4606 width = wcwidth(wline[i]);
4607 if (width == -1) {
4608 /* should not happen, tabs are expanded */
4609 err = got_error(GOT_ERR_RANGE);
4610 goto done;
4612 if (width0 + w + width > skipcol)
4613 break;
4614 w += width;
4615 i++;
4617 /* draw (visible part of) matched token (if scrolled into it) */
4618 if (width1 - w > 0) {
4619 wattron(window, A_STANDOUT);
4620 waddwstr(window, &wline[i]);
4621 wattroff(window, A_STANDOUT);
4622 wlimit -= (width1 - w);
4623 *wtotal += (width1 - w);
4627 if (wlimit > 0) { /* draw rest of line */
4628 free(wline);
4629 if (skipcol > width0 + width1) {
4630 err = format_line(&wline, &width2, &scrollx, seg2,
4631 skipcol - (width0 + width1), wlimit,
4632 col_tab_align, 1);
4633 if (err)
4634 goto done;
4635 waddwstr(window, &wline[scrollx]);
4636 } else {
4637 err = format_line(&wline, &width2, NULL, seg2, 0,
4638 wlimit, col_tab_align, 1);
4639 if (err)
4640 goto done;
4641 waddwstr(window, wline);
4643 *wtotal += width2;
4645 done:
4646 free(wline);
4647 free(exstr);
4648 free(seg0);
4649 free(seg1);
4650 free(seg2);
4651 return err;
4654 static int
4655 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4657 FILE *f = NULL;
4658 int *eof, *first, *selected;
4660 if (view->type == TOG_VIEW_DIFF) {
4661 struct tog_diff_view_state *s = &view->state.diff;
4663 first = &s->first_displayed_line;
4664 selected = first;
4665 eof = &s->eof;
4666 f = s->f;
4667 } else if (view->type == TOG_VIEW_HELP) {
4668 struct tog_help_view_state *s = &view->state.help;
4670 first = &s->first_displayed_line;
4671 selected = first;
4672 eof = &s->eof;
4673 f = s->f;
4674 } else if (view->type == TOG_VIEW_BLAME) {
4675 struct tog_blame_view_state *s = &view->state.blame;
4677 first = &s->first_displayed_line;
4678 selected = &s->selected_line;
4679 eof = &s->eof;
4680 f = s->blame.f;
4681 } else
4682 return 0;
4684 /* Center gline in the middle of the page like vi(1). */
4685 if (*lineno < view->gline - (view->nlines - 3) / 2)
4686 return 0;
4687 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4688 rewind(f);
4689 *eof = 0;
4690 *first = 1;
4691 *lineno = 0;
4692 *nprinted = 0;
4693 return 0;
4696 *selected = view->gline <= (view->nlines - 3) / 2 ?
4697 view->gline : (view->nlines - 3) / 2 + 1;
4698 view->gline = 0;
4700 return 1;
4703 static const struct got_error *
4704 draw_file(struct tog_view *view, const char *header)
4706 struct tog_diff_view_state *s = &view->state.diff;
4707 regmatch_t *regmatch = &view->regmatch;
4708 const struct got_error *err;
4709 int nprinted = 0;
4710 char *line;
4711 size_t linesize = 0;
4712 ssize_t linelen;
4713 wchar_t *wline;
4714 int width;
4715 int max_lines = view->nlines;
4716 int nlines = s->nlines;
4717 off_t line_offset;
4719 s->lineno = s->first_displayed_line - 1;
4720 line_offset = s->lines[s->first_displayed_line - 1].offset;
4721 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4722 return got_error_from_errno("fseek");
4724 werase(view->window);
4726 if (view->gline > s->nlines - 1)
4727 view->gline = s->nlines - 1;
4729 if (header) {
4730 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4731 1 : view->gline - (view->nlines - 3) / 2 :
4732 s->lineno + s->selected_line;
4734 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4735 return got_error_from_errno("asprintf");
4736 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4737 0, 0);
4738 free(line);
4739 if (err)
4740 return err;
4742 if (view_needs_focus_indication(view))
4743 wstandout(view->window);
4744 waddwstr(view->window, wline);
4745 free(wline);
4746 wline = NULL;
4747 while (width++ < view->ncols)
4748 waddch(view->window, ' ');
4749 if (view_needs_focus_indication(view))
4750 wstandend(view->window);
4752 if (max_lines <= 1)
4753 return NULL;
4754 max_lines--;
4757 s->eof = 0;
4758 view->maxx = 0;
4759 line = NULL;
4760 while (max_lines > 0 && nprinted < max_lines) {
4761 enum got_diff_line_type linetype;
4762 attr_t attr = 0;
4764 linelen = getline(&line, &linesize, s->f);
4765 if (linelen == -1) {
4766 if (feof(s->f)) {
4767 s->eof = 1;
4768 break;
4770 free(line);
4771 return got_ferror(s->f, GOT_ERR_IO);
4774 if (++s->lineno < s->first_displayed_line)
4775 continue;
4776 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4777 continue;
4778 if (s->lineno == view->hiline)
4779 attr = A_STANDOUT;
4781 /* Set view->maxx based on full line length. */
4782 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4783 view->x ? 1 : 0);
4784 if (err) {
4785 free(line);
4786 return err;
4788 view->maxx = MAX(view->maxx, width);
4789 free(wline);
4790 wline = NULL;
4792 linetype = s->lines[s->lineno].type;
4793 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4794 linetype < GOT_DIFF_LINE_CONTEXT)
4795 attr |= COLOR_PAIR(linetype);
4796 if (attr)
4797 wattron(view->window, attr);
4798 if (s->first_displayed_line + nprinted == s->matched_line &&
4799 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4800 err = add_matched_line(&width, line, view->ncols, 0,
4801 view->window, view->x, regmatch);
4802 if (err) {
4803 free(line);
4804 return err;
4806 } else {
4807 int skip;
4808 err = format_line(&wline, &width, &skip, line,
4809 view->x, view->ncols, 0, view->x ? 1 : 0);
4810 if (err) {
4811 free(line);
4812 return err;
4814 waddwstr(view->window, &wline[skip]);
4815 free(wline);
4816 wline = NULL;
4818 if (s->lineno == view->hiline) {
4819 /* highlight full gline length */
4820 while (width++ < view->ncols)
4821 waddch(view->window, ' ');
4822 } else {
4823 if (width <= view->ncols - 1)
4824 waddch(view->window, '\n');
4826 if (attr)
4827 wattroff(view->window, attr);
4828 if (++nprinted == 1)
4829 s->first_displayed_line = s->lineno;
4831 free(line);
4832 if (nprinted >= 1)
4833 s->last_displayed_line = s->first_displayed_line +
4834 (nprinted - 1);
4835 else
4836 s->last_displayed_line = s->first_displayed_line;
4838 view_border(view);
4840 if (s->eof) {
4841 while (nprinted < view->nlines) {
4842 waddch(view->window, '\n');
4843 nprinted++;
4846 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4847 view->ncols, 0, 0);
4848 if (err) {
4849 return err;
4852 wstandout(view->window);
4853 waddwstr(view->window, wline);
4854 free(wline);
4855 wline = NULL;
4856 wstandend(view->window);
4859 return NULL;
4862 static char *
4863 get_datestr(time_t *time, char *datebuf)
4865 struct tm mytm, *tm;
4866 char *p, *s;
4868 tm = gmtime_r(time, &mytm);
4869 if (tm == NULL)
4870 return NULL;
4871 s = asctime_r(tm, datebuf);
4872 if (s == NULL)
4873 return NULL;
4874 p = strchr(s, '\n');
4875 if (p)
4876 *p = '\0';
4877 return s;
4880 static const struct got_error *
4881 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4882 off_t off, uint8_t type)
4884 struct got_diff_line *p;
4886 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4887 if (p == NULL)
4888 return got_error_from_errno("reallocarray");
4889 *lines = p;
4890 (*lines)[*nlines].offset = off;
4891 (*lines)[*nlines].type = type;
4892 (*nlines)++;
4894 return NULL;
4897 static const struct got_error *
4898 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4899 struct got_diff_line *s_lines, size_t s_nlines)
4901 struct got_diff_line *p;
4902 char buf[BUFSIZ];
4903 size_t i, r;
4905 if (fseeko(src, 0L, SEEK_SET) == -1)
4906 return got_error_from_errno("fseeko");
4908 for (;;) {
4909 r = fread(buf, 1, sizeof(buf), src);
4910 if (r == 0) {
4911 if (ferror(src))
4912 return got_error_from_errno("fread");
4913 if (feof(src))
4914 break;
4916 if (fwrite(buf, 1, r, dst) != r)
4917 return got_ferror(dst, GOT_ERR_IO);
4920 if (s_nlines == 0 && *d_nlines == 0)
4921 return NULL;
4924 * If commit info was in dst, increment line offsets
4925 * of the appended diff content, but skip s_lines[0]
4926 * because offset zero is already in *d_lines.
4928 if (*d_nlines > 0) {
4929 for (i = 1; i < s_nlines; ++i)
4930 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4932 if (s_nlines > 0) {
4933 --s_nlines;
4934 ++s_lines;
4938 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4939 if (p == NULL) {
4940 /* d_lines is freed in close_diff_view() */
4941 return got_error_from_errno("reallocarray");
4944 *d_lines = p;
4946 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4947 *d_nlines += s_nlines;
4949 return NULL;
4952 static const struct got_error *
4953 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4954 struct got_object_id *commit_id, struct got_reflist_head *refs,
4955 struct got_repository *repo, int ignore_ws, int force_text_diff,
4956 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4958 const struct got_error *err = NULL;
4959 char datebuf[26], *datestr;
4960 struct got_commit_object *commit;
4961 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4962 time_t committer_time;
4963 const char *author, *committer;
4964 char *refs_str = NULL;
4965 struct got_pathlist_entry *pe;
4966 off_t outoff = 0;
4967 int n;
4969 err = build_refs_str(&refs_str, refs, commit_id, repo);
4970 if (err)
4971 return err;
4973 err = got_object_open_as_commit(&commit, repo, commit_id);
4974 if (err)
4975 return err;
4977 err = got_object_id_str(&id_str, commit_id);
4978 if (err) {
4979 err = got_error_from_errno("got_object_id_str");
4980 goto done;
4983 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4984 if (err)
4985 goto done;
4987 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4988 refs_str ? refs_str : "", refs_str ? ")" : "");
4989 if (n < 0) {
4990 err = got_error_from_errno("fprintf");
4991 goto done;
4993 outoff += n;
4994 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4995 if (err)
4996 goto done;
4998 n = fprintf(outfile, "from: %s\n",
4999 got_object_commit_get_author(commit));
5000 if (n < 0) {
5001 err = got_error_from_errno("fprintf");
5002 goto done;
5004 outoff += n;
5005 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5006 if (err)
5007 goto done;
5009 author = got_object_commit_get_author(commit);
5010 committer = got_object_commit_get_committer(commit);
5011 if (strcmp(author, committer) != 0) {
5012 n = fprintf(outfile, "via: %s\n", committer);
5013 if (n < 0) {
5014 err = got_error_from_errno("fprintf");
5015 goto done;
5017 outoff += n;
5018 err = add_line_metadata(lines, nlines, outoff,
5019 GOT_DIFF_LINE_AUTHOR);
5020 if (err)
5021 goto done;
5023 committer_time = got_object_commit_get_committer_time(commit);
5024 datestr = get_datestr(&committer_time, datebuf);
5025 if (datestr) {
5026 n = fprintf(outfile, "date: %s UTC\n", datestr);
5027 if (n < 0) {
5028 err = got_error_from_errno("fprintf");
5029 goto done;
5031 outoff += n;
5032 err = add_line_metadata(lines, nlines, outoff,
5033 GOT_DIFF_LINE_DATE);
5034 if (err)
5035 goto done;
5037 if (got_object_commit_get_nparents(commit) > 1) {
5038 const struct got_object_id_queue *parent_ids;
5039 struct got_object_qid *qid;
5040 int pn = 1;
5041 parent_ids = got_object_commit_get_parent_ids(commit);
5042 STAILQ_FOREACH(qid, parent_ids, entry) {
5043 err = got_object_id_str(&id_str, &qid->id);
5044 if (err)
5045 goto done;
5046 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5047 if (n < 0) {
5048 err = got_error_from_errno("fprintf");
5049 goto done;
5051 outoff += n;
5052 err = add_line_metadata(lines, nlines, outoff,
5053 GOT_DIFF_LINE_META);
5054 if (err)
5055 goto done;
5056 free(id_str);
5057 id_str = NULL;
5061 err = got_object_commit_get_logmsg(&logmsg, commit);
5062 if (err)
5063 goto done;
5064 s = logmsg;
5065 while ((line = strsep(&s, "\n")) != NULL) {
5066 n = fprintf(outfile, "%s\n", line);
5067 if (n < 0) {
5068 err = got_error_from_errno("fprintf");
5069 goto done;
5071 outoff += n;
5072 err = add_line_metadata(lines, nlines, outoff,
5073 GOT_DIFF_LINE_LOGMSG);
5074 if (err)
5075 goto done;
5078 TAILQ_FOREACH(pe, dsa->paths, entry) {
5079 struct got_diff_changed_path *cp = pe->data;
5080 int pad = dsa->max_path_len - pe->path_len + 1;
5082 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5083 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5084 dsa->rm_cols + 1, cp->rm);
5085 if (n < 0) {
5086 err = got_error_from_errno("fprintf");
5087 goto done;
5089 outoff += n;
5090 err = add_line_metadata(lines, nlines, outoff,
5091 GOT_DIFF_LINE_CHANGES);
5092 if (err)
5093 goto done;
5096 fputc('\n', outfile);
5097 outoff++;
5098 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5099 if (err)
5100 goto done;
5102 n = fprintf(outfile,
5103 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5104 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5105 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5106 if (n < 0) {
5107 err = got_error_from_errno("fprintf");
5108 goto done;
5110 outoff += n;
5111 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5112 if (err)
5113 goto done;
5115 fputc('\n', outfile);
5116 outoff++;
5117 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5118 done:
5119 free(id_str);
5120 free(logmsg);
5121 free(refs_str);
5122 got_object_commit_close(commit);
5123 if (err) {
5124 free(*lines);
5125 *lines = NULL;
5126 *nlines = 0;
5128 return err;
5131 static const struct got_error *
5132 create_diff(struct tog_diff_view_state *s)
5134 const struct got_error *err = NULL;
5135 FILE *f = NULL, *tmp_diff_file = NULL;
5136 int obj_type;
5137 struct got_diff_line *lines = NULL;
5138 struct got_pathlist_head changed_paths;
5140 TAILQ_INIT(&changed_paths);
5142 free(s->lines);
5143 s->lines = malloc(sizeof(*s->lines));
5144 if (s->lines == NULL)
5145 return got_error_from_errno("malloc");
5146 s->nlines = 0;
5148 f = got_opentemp();
5149 if (f == NULL) {
5150 err = got_error_from_errno("got_opentemp");
5151 goto done;
5153 tmp_diff_file = got_opentemp();
5154 if (tmp_diff_file == NULL) {
5155 err = got_error_from_errno("got_opentemp");
5156 goto done;
5158 if (s->f && fclose(s->f) == EOF) {
5159 err = got_error_from_errno("fclose");
5160 goto done;
5162 s->f = f;
5164 if (s->id1)
5165 err = got_object_get_type(&obj_type, s->repo, s->id1);
5166 else
5167 err = got_object_get_type(&obj_type, s->repo, s->id2);
5168 if (err)
5169 goto done;
5171 switch (obj_type) {
5172 case GOT_OBJ_TYPE_BLOB:
5173 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5174 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5175 s->label1, s->label2, tog_diff_algo, s->diff_context,
5176 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5177 s->f);
5178 break;
5179 case GOT_OBJ_TYPE_TREE:
5180 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5181 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5182 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5183 s->force_text_diff, NULL, s->repo, s->f);
5184 break;
5185 case GOT_OBJ_TYPE_COMMIT: {
5186 const struct got_object_id_queue *parent_ids;
5187 struct got_object_qid *pid;
5188 struct got_commit_object *commit2;
5189 struct got_reflist_head *refs;
5190 size_t nlines = 0;
5191 struct got_diffstat_cb_arg dsa = {
5192 0, 0, 0, 0, 0, 0,
5193 &changed_paths,
5194 s->ignore_whitespace,
5195 s->force_text_diff,
5196 tog_diff_algo
5199 lines = malloc(sizeof(*lines));
5200 if (lines == NULL) {
5201 err = got_error_from_errno("malloc");
5202 goto done;
5205 /* build diff first in tmp file then append to commit info */
5206 err = got_diff_objects_as_commits(&lines, &nlines,
5207 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5208 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5209 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5210 if (err)
5211 break;
5213 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5214 if (err)
5215 goto done;
5216 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5217 /* Show commit info if we're diffing to a parent/root commit. */
5218 if (s->id1 == NULL) {
5219 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5220 refs, s->repo, s->ignore_whitespace,
5221 s->force_text_diff, &dsa, s->f);
5222 if (err)
5223 goto done;
5224 } else {
5225 parent_ids = got_object_commit_get_parent_ids(commit2);
5226 STAILQ_FOREACH(pid, parent_ids, entry) {
5227 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5228 err = write_commit_info(&s->lines,
5229 &s->nlines, s->id2, refs, s->repo,
5230 s->ignore_whitespace,
5231 s->force_text_diff, &dsa, s->f);
5232 if (err)
5233 goto done;
5234 break;
5238 got_object_commit_close(commit2);
5240 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5241 lines, nlines);
5242 break;
5244 default:
5245 err = got_error(GOT_ERR_OBJ_TYPE);
5246 break;
5248 done:
5249 free(lines);
5250 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5251 if (s->f && fflush(s->f) != 0 && err == NULL)
5252 err = got_error_from_errno("fflush");
5253 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5254 err = got_error_from_errno("fclose");
5255 return err;
5258 static void
5259 diff_view_indicate_progress(struct tog_view *view)
5261 mvwaddstr(view->window, 0, 0, "diffing...");
5262 update_panels();
5263 doupdate();
5266 static const struct got_error *
5267 search_start_diff_view(struct tog_view *view)
5269 struct tog_diff_view_state *s = &view->state.diff;
5271 s->matched_line = 0;
5272 return NULL;
5275 static void
5276 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5277 size_t *nlines, int **first, int **last, int **match, int **selected)
5279 struct tog_diff_view_state *s = &view->state.diff;
5281 *f = s->f;
5282 *nlines = s->nlines;
5283 *line_offsets = NULL;
5284 *match = &s->matched_line;
5285 *first = &s->first_displayed_line;
5286 *last = &s->last_displayed_line;
5287 *selected = &s->selected_line;
5290 static const struct got_error *
5291 search_next_view_match(struct tog_view *view)
5293 const struct got_error *err = NULL;
5294 FILE *f;
5295 int lineno;
5296 char *line = NULL;
5297 size_t linesize = 0;
5298 ssize_t linelen;
5299 off_t *line_offsets;
5300 size_t nlines = 0;
5301 int *first, *last, *match, *selected;
5303 if (!view->search_setup)
5304 return got_error_msg(GOT_ERR_NOT_IMPL,
5305 "view search not supported");
5306 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5307 &match, &selected);
5309 if (!view->searching) {
5310 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5311 return NULL;
5314 if (*match) {
5315 if (view->searching == TOG_SEARCH_FORWARD)
5316 lineno = *first + 1;
5317 else
5318 lineno = *first - 1;
5319 } else
5320 lineno = *first - 1 + *selected;
5322 while (1) {
5323 off_t offset;
5325 if (lineno <= 0 || lineno > nlines) {
5326 if (*match == 0) {
5327 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5328 break;
5331 if (view->searching == TOG_SEARCH_FORWARD)
5332 lineno = 1;
5333 else
5334 lineno = nlines;
5337 offset = view->type == TOG_VIEW_DIFF ?
5338 view->state.diff.lines[lineno - 1].offset :
5339 line_offsets[lineno - 1];
5340 if (fseeko(f, offset, SEEK_SET) != 0) {
5341 free(line);
5342 return got_error_from_errno("fseeko");
5344 linelen = getline(&line, &linesize, f);
5345 if (linelen != -1) {
5346 char *exstr;
5347 err = expand_tab(&exstr, line);
5348 if (err)
5349 break;
5350 if (match_line(exstr, &view->regex, 1,
5351 &view->regmatch)) {
5352 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5353 *match = lineno;
5354 free(exstr);
5355 break;
5357 free(exstr);
5359 if (view->searching == TOG_SEARCH_FORWARD)
5360 lineno++;
5361 else
5362 lineno--;
5364 free(line);
5366 if (*match) {
5367 *first = *match;
5368 *selected = 1;
5371 return err;
5374 static const struct got_error *
5375 close_diff_view(struct tog_view *view)
5377 const struct got_error *err = NULL;
5378 struct tog_diff_view_state *s = &view->state.diff;
5380 free(s->id1);
5381 s->id1 = NULL;
5382 free(s->id2);
5383 s->id2 = NULL;
5384 if (s->f && fclose(s->f) == EOF)
5385 err = got_error_from_errno("fclose");
5386 s->f = NULL;
5387 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5388 err = got_error_from_errno("fclose");
5389 s->f1 = NULL;
5390 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5391 err = got_error_from_errno("fclose");
5392 s->f2 = NULL;
5393 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5394 err = got_error_from_errno("close");
5395 s->fd1 = -1;
5396 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5397 err = got_error_from_errno("close");
5398 s->fd2 = -1;
5399 free(s->lines);
5400 s->lines = NULL;
5401 s->nlines = 0;
5402 return err;
5405 static const struct got_error *
5406 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5407 struct got_object_id *id2, const char *label1, const char *label2,
5408 int diff_context, int ignore_whitespace, int force_text_diff,
5409 struct tog_view *parent_view, struct got_repository *repo)
5411 const struct got_error *err;
5412 struct tog_diff_view_state *s = &view->state.diff;
5414 memset(s, 0, sizeof(*s));
5415 s->fd1 = -1;
5416 s->fd2 = -1;
5418 if (id1 != NULL && id2 != NULL) {
5419 int type1, type2;
5421 err = got_object_get_type(&type1, repo, id1);
5422 if (err)
5423 goto done;
5424 err = got_object_get_type(&type2, repo, id2);
5425 if (err)
5426 goto done;
5428 if (type1 != type2) {
5429 err = got_error(GOT_ERR_OBJ_TYPE);
5430 goto done;
5433 s->first_displayed_line = 1;
5434 s->last_displayed_line = view->nlines;
5435 s->selected_line = 1;
5436 s->repo = repo;
5437 s->id1 = id1;
5438 s->id2 = id2;
5439 s->label1 = label1;
5440 s->label2 = label2;
5442 if (id1) {
5443 s->id1 = got_object_id_dup(id1);
5444 if (s->id1 == NULL) {
5445 err = got_error_from_errno("got_object_id_dup");
5446 goto done;
5448 } else
5449 s->id1 = NULL;
5451 s->id2 = got_object_id_dup(id2);
5452 if (s->id2 == NULL) {
5453 err = got_error_from_errno("got_object_id_dup");
5454 goto done;
5457 s->f1 = got_opentemp();
5458 if (s->f1 == NULL) {
5459 err = got_error_from_errno("got_opentemp");
5460 goto done;
5463 s->f2 = got_opentemp();
5464 if (s->f2 == NULL) {
5465 err = got_error_from_errno("got_opentemp");
5466 goto done;
5469 s->fd1 = got_opentempfd();
5470 if (s->fd1 == -1) {
5471 err = got_error_from_errno("got_opentempfd");
5472 goto done;
5475 s->fd2 = got_opentempfd();
5476 if (s->fd2 == -1) {
5477 err = got_error_from_errno("got_opentempfd");
5478 goto done;
5481 s->diff_context = diff_context;
5482 s->ignore_whitespace = ignore_whitespace;
5483 s->force_text_diff = force_text_diff;
5484 s->parent_view = parent_view;
5485 s->repo = repo;
5487 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5488 int rc;
5490 rc = init_pair(GOT_DIFF_LINE_MINUS,
5491 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5492 if (rc != ERR)
5493 rc = init_pair(GOT_DIFF_LINE_PLUS,
5494 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5495 if (rc != ERR)
5496 rc = init_pair(GOT_DIFF_LINE_HUNK,
5497 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5498 if (rc != ERR)
5499 rc = init_pair(GOT_DIFF_LINE_META,
5500 get_color_value("TOG_COLOR_DIFF_META"), -1);
5501 if (rc != ERR)
5502 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5503 get_color_value("TOG_COLOR_DIFF_META"), -1);
5504 if (rc != ERR)
5505 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5506 get_color_value("TOG_COLOR_DIFF_META"), -1);
5507 if (rc != ERR)
5508 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5509 get_color_value("TOG_COLOR_DIFF_META"), -1);
5510 if (rc != ERR)
5511 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5512 get_color_value("TOG_COLOR_AUTHOR"), -1);
5513 if (rc != ERR)
5514 rc = init_pair(GOT_DIFF_LINE_DATE,
5515 get_color_value("TOG_COLOR_DATE"), -1);
5516 if (rc == ERR) {
5517 err = got_error(GOT_ERR_RANGE);
5518 goto done;
5522 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5523 view_is_splitscreen(view))
5524 show_log_view(parent_view); /* draw border */
5525 diff_view_indicate_progress(view);
5527 err = create_diff(s);
5529 view->show = show_diff_view;
5530 view->input = input_diff_view;
5531 view->reset = reset_diff_view;
5532 view->close = close_diff_view;
5533 view->search_start = search_start_diff_view;
5534 view->search_setup = search_setup_diff_view;
5535 view->search_next = search_next_view_match;
5536 done:
5537 if (err) {
5538 if (view->close == NULL)
5539 close_diff_view(view);
5540 view_close(view);
5542 return err;
5545 static const struct got_error *
5546 show_diff_view(struct tog_view *view)
5548 const struct got_error *err;
5549 struct tog_diff_view_state *s = &view->state.diff;
5550 char *id_str1 = NULL, *id_str2, *header;
5551 const char *label1, *label2;
5553 if (s->id1) {
5554 err = got_object_id_str(&id_str1, s->id1);
5555 if (err)
5556 return err;
5557 label1 = s->label1 ? s->label1 : id_str1;
5558 } else
5559 label1 = "/dev/null";
5561 err = got_object_id_str(&id_str2, s->id2);
5562 if (err)
5563 return err;
5564 label2 = s->label2 ? s->label2 : id_str2;
5566 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5567 err = got_error_from_errno("asprintf");
5568 free(id_str1);
5569 free(id_str2);
5570 return err;
5572 free(id_str1);
5573 free(id_str2);
5575 err = draw_file(view, header);
5576 free(header);
5577 return err;
5580 static const struct got_error *
5581 set_selected_commit(struct tog_diff_view_state *s,
5582 struct commit_queue_entry *entry)
5584 const struct got_error *err;
5585 const struct got_object_id_queue *parent_ids;
5586 struct got_commit_object *selected_commit;
5587 struct got_object_qid *pid;
5589 free(s->id2);
5590 s->id2 = got_object_id_dup(entry->id);
5591 if (s->id2 == NULL)
5592 return got_error_from_errno("got_object_id_dup");
5594 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5595 if (err)
5596 return err;
5597 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5598 free(s->id1);
5599 pid = STAILQ_FIRST(parent_ids);
5600 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5601 got_object_commit_close(selected_commit);
5602 return NULL;
5605 static const struct got_error *
5606 reset_diff_view(struct tog_view *view)
5608 struct tog_diff_view_state *s = &view->state.diff;
5610 view->count = 0;
5611 wclear(view->window);
5612 s->first_displayed_line = 1;
5613 s->last_displayed_line = view->nlines;
5614 s->matched_line = 0;
5615 diff_view_indicate_progress(view);
5616 return create_diff(s);
5619 static void
5620 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5622 int start, i;
5624 i = start = s->first_displayed_line - 1;
5626 while (s->lines[i].type != type) {
5627 if (i == 0)
5628 i = s->nlines - 1;
5629 if (--i == start)
5630 return; /* do nothing, requested type not in file */
5633 s->selected_line = 1;
5634 s->first_displayed_line = i;
5637 static void
5638 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5640 int start, i;
5642 i = start = s->first_displayed_line + 1;
5644 while (s->lines[i].type != type) {
5645 if (i == s->nlines - 1)
5646 i = 0;
5647 if (++i == start)
5648 return; /* do nothing, requested type not in file */
5651 s->selected_line = 1;
5652 s->first_displayed_line = i;
5655 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5656 int, int, int);
5657 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5658 int, int);
5660 static const struct got_error *
5661 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5663 const struct got_error *err = NULL;
5664 struct tog_diff_view_state *s = &view->state.diff;
5665 struct tog_log_view_state *ls;
5666 struct commit_queue_entry *old_selected_entry;
5667 char *line = NULL;
5668 size_t linesize = 0;
5669 ssize_t linelen;
5670 int i, nscroll = view->nlines - 1, up = 0;
5672 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5674 switch (ch) {
5675 case '0':
5676 case '$':
5677 case KEY_RIGHT:
5678 case 'l':
5679 case KEY_LEFT:
5680 case 'h':
5681 horizontal_scroll_input(view, ch);
5682 break;
5683 case 'a':
5684 case 'w':
5685 if (ch == 'a') {
5686 s->force_text_diff = !s->force_text_diff;
5687 view->action = s->force_text_diff ?
5688 "force ASCII text enabled" :
5689 "force ASCII text disabled";
5691 else if (ch == 'w') {
5692 s->ignore_whitespace = !s->ignore_whitespace;
5693 view->action = s->ignore_whitespace ?
5694 "ignore whitespace enabled" :
5695 "ignore whitespace disabled";
5697 err = reset_diff_view(view);
5698 break;
5699 case 'g':
5700 case KEY_HOME:
5701 s->first_displayed_line = 1;
5702 view->count = 0;
5703 break;
5704 case 'G':
5705 case KEY_END:
5706 view->count = 0;
5707 if (s->eof)
5708 break;
5710 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5711 s->eof = 1;
5712 break;
5713 case 'k':
5714 case KEY_UP:
5715 case CTRL('p'):
5716 if (s->first_displayed_line > 1)
5717 s->first_displayed_line--;
5718 else
5719 view->count = 0;
5720 break;
5721 case CTRL('u'):
5722 case 'u':
5723 nscroll /= 2;
5724 /* FALL THROUGH */
5725 case KEY_PPAGE:
5726 case CTRL('b'):
5727 case 'b':
5728 if (s->first_displayed_line == 1) {
5729 view->count = 0;
5730 break;
5732 i = 0;
5733 while (i++ < nscroll && s->first_displayed_line > 1)
5734 s->first_displayed_line--;
5735 break;
5736 case 'j':
5737 case KEY_DOWN:
5738 case CTRL('n'):
5739 if (!s->eof)
5740 s->first_displayed_line++;
5741 else
5742 view->count = 0;
5743 break;
5744 case CTRL('d'):
5745 case 'd':
5746 nscroll /= 2;
5747 /* FALL THROUGH */
5748 case KEY_NPAGE:
5749 case CTRL('f'):
5750 case 'f':
5751 case ' ':
5752 if (s->eof) {
5753 view->count = 0;
5754 break;
5756 i = 0;
5757 while (!s->eof && i++ < nscroll) {
5758 linelen = getline(&line, &linesize, s->f);
5759 s->first_displayed_line++;
5760 if (linelen == -1) {
5761 if (feof(s->f)) {
5762 s->eof = 1;
5763 } else
5764 err = got_ferror(s->f, GOT_ERR_IO);
5765 break;
5768 free(line);
5769 break;
5770 case '(':
5771 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5772 break;
5773 case ')':
5774 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5775 break;
5776 case '{':
5777 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5778 break;
5779 case '}':
5780 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5781 break;
5782 case '[':
5783 if (s->diff_context > 0) {
5784 s->diff_context--;
5785 s->matched_line = 0;
5786 diff_view_indicate_progress(view);
5787 err = create_diff(s);
5788 if (s->first_displayed_line + view->nlines - 1 >
5789 s->nlines) {
5790 s->first_displayed_line = 1;
5791 s->last_displayed_line = view->nlines;
5793 } else
5794 view->count = 0;
5795 break;
5796 case ']':
5797 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5798 s->diff_context++;
5799 s->matched_line = 0;
5800 diff_view_indicate_progress(view);
5801 err = create_diff(s);
5802 } else
5803 view->count = 0;
5804 break;
5805 case '<':
5806 case ',':
5807 case 'K':
5808 up = 1;
5809 /* FALL THROUGH */
5810 case '>':
5811 case '.':
5812 case 'J':
5813 if (s->parent_view == NULL) {
5814 view->count = 0;
5815 break;
5817 s->parent_view->count = view->count;
5819 if (s->parent_view->type == TOG_VIEW_LOG) {
5820 ls = &s->parent_view->state.log;
5821 old_selected_entry = ls->selected_entry;
5823 err = input_log_view(NULL, s->parent_view,
5824 up ? KEY_UP : KEY_DOWN);
5825 if (err)
5826 break;
5827 view->count = s->parent_view->count;
5829 if (old_selected_entry == ls->selected_entry)
5830 break;
5832 err = set_selected_commit(s, ls->selected_entry);
5833 if (err)
5834 break;
5835 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5836 struct tog_blame_view_state *bs;
5837 struct got_object_id *id, *prev_id;
5839 bs = &s->parent_view->state.blame;
5840 prev_id = get_annotation_for_line(bs->blame.lines,
5841 bs->blame.nlines, bs->last_diffed_line);
5843 err = input_blame_view(&view, s->parent_view,
5844 up ? KEY_UP : KEY_DOWN);
5845 if (err)
5846 break;
5847 view->count = s->parent_view->count;
5849 if (prev_id == NULL)
5850 break;
5851 id = get_selected_commit_id(bs->blame.lines,
5852 bs->blame.nlines, bs->first_displayed_line,
5853 bs->selected_line);
5854 if (id == NULL)
5855 break;
5857 if (!got_object_id_cmp(prev_id, id))
5858 break;
5860 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5861 if (err)
5862 break;
5864 s->first_displayed_line = 1;
5865 s->last_displayed_line = view->nlines;
5866 s->matched_line = 0;
5867 view->x = 0;
5869 diff_view_indicate_progress(view);
5870 err = create_diff(s);
5871 break;
5872 default:
5873 view->count = 0;
5874 break;
5877 return err;
5880 static const struct got_error *
5881 cmd_diff(int argc, char *argv[])
5883 const struct got_error *error;
5884 struct got_repository *repo = NULL;
5885 struct got_worktree *worktree = NULL;
5886 struct got_object_id *id1 = NULL, *id2 = NULL;
5887 char *repo_path = NULL, *cwd = NULL;
5888 char *id_str1 = NULL, *id_str2 = NULL;
5889 char *label1 = NULL, *label2 = NULL;
5890 int diff_context = 3, ignore_whitespace = 0;
5891 int ch, force_text_diff = 0;
5892 const char *errstr;
5893 struct tog_view *view;
5894 int *pack_fds = NULL;
5896 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5897 switch (ch) {
5898 case 'a':
5899 force_text_diff = 1;
5900 break;
5901 case 'C':
5902 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5903 &errstr);
5904 if (errstr != NULL)
5905 errx(1, "number of context lines is %s: %s",
5906 errstr, errstr);
5907 break;
5908 case 'r':
5909 repo_path = realpath(optarg, NULL);
5910 if (repo_path == NULL)
5911 return got_error_from_errno2("realpath",
5912 optarg);
5913 got_path_strip_trailing_slashes(repo_path);
5914 break;
5915 case 'w':
5916 ignore_whitespace = 1;
5917 break;
5918 default:
5919 usage_diff();
5920 /* NOTREACHED */
5924 argc -= optind;
5925 argv += optind;
5927 if (argc == 0) {
5928 usage_diff(); /* TODO show local worktree changes */
5929 } else if (argc == 2) {
5930 id_str1 = argv[0];
5931 id_str2 = argv[1];
5932 } else
5933 usage_diff();
5935 error = got_repo_pack_fds_open(&pack_fds);
5936 if (error)
5937 goto done;
5939 if (repo_path == NULL) {
5940 cwd = getcwd(NULL, 0);
5941 if (cwd == NULL)
5942 return got_error_from_errno("getcwd");
5943 error = got_worktree_open(&worktree, cwd);
5944 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5945 goto done;
5946 if (worktree)
5947 repo_path =
5948 strdup(got_worktree_get_repo_path(worktree));
5949 else
5950 repo_path = strdup(cwd);
5951 if (repo_path == NULL) {
5952 error = got_error_from_errno("strdup");
5953 goto done;
5957 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5958 if (error)
5959 goto done;
5961 init_curses();
5963 error = apply_unveil(got_repo_get_path(repo), NULL);
5964 if (error)
5965 goto done;
5967 error = tog_load_refs(repo, 0);
5968 if (error)
5969 goto done;
5971 error = got_repo_match_object_id(&id1, &label1, id_str1,
5972 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5973 if (error)
5974 goto done;
5976 error = got_repo_match_object_id(&id2, &label2, id_str2,
5977 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5978 if (error)
5979 goto done;
5981 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5982 if (view == NULL) {
5983 error = got_error_from_errno("view_open");
5984 goto done;
5986 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5987 ignore_whitespace, force_text_diff, NULL, repo);
5988 if (error)
5989 goto done;
5990 error = view_loop(view);
5991 done:
5992 free(label1);
5993 free(label2);
5994 free(repo_path);
5995 free(cwd);
5996 if (repo) {
5997 const struct got_error *close_err = got_repo_close(repo);
5998 if (error == NULL)
5999 error = close_err;
6001 if (worktree)
6002 got_worktree_close(worktree);
6003 if (pack_fds) {
6004 const struct got_error *pack_err =
6005 got_repo_pack_fds_close(pack_fds);
6006 if (error == NULL)
6007 error = pack_err;
6009 tog_free_refs();
6010 return error;
6013 __dead static void
6014 usage_blame(void)
6016 endwin();
6017 fprintf(stderr,
6018 "usage: %s blame [-c commit] [-r repository-path] path\n",
6019 getprogname());
6020 exit(1);
6023 struct tog_blame_line {
6024 int annotated;
6025 struct got_object_id *id;
6028 static const struct got_error *
6029 draw_blame(struct tog_view *view)
6031 struct tog_blame_view_state *s = &view->state.blame;
6032 struct tog_blame *blame = &s->blame;
6033 regmatch_t *regmatch = &view->regmatch;
6034 const struct got_error *err;
6035 int lineno = 0, nprinted = 0;
6036 char *line = NULL;
6037 size_t linesize = 0;
6038 ssize_t linelen;
6039 wchar_t *wline;
6040 int width;
6041 struct tog_blame_line *blame_line;
6042 struct got_object_id *prev_id = NULL;
6043 char *id_str;
6044 struct tog_color *tc;
6046 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6047 if (err)
6048 return err;
6050 rewind(blame->f);
6051 werase(view->window);
6053 if (asprintf(&line, "commit %s", id_str) == -1) {
6054 err = got_error_from_errno("asprintf");
6055 free(id_str);
6056 return err;
6059 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6060 free(line);
6061 line = NULL;
6062 if (err)
6063 return err;
6064 if (view_needs_focus_indication(view))
6065 wstandout(view->window);
6066 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6067 if (tc)
6068 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6069 waddwstr(view->window, wline);
6070 while (width++ < view->ncols)
6071 waddch(view->window, ' ');
6072 if (tc)
6073 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6074 if (view_needs_focus_indication(view))
6075 wstandend(view->window);
6076 free(wline);
6077 wline = NULL;
6079 if (view->gline > blame->nlines)
6080 view->gline = blame->nlines;
6082 if (tog_io.wait_for_ui) {
6083 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6084 int rc;
6086 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6087 if (rc)
6088 return got_error_set_errno(rc, "pthread_cond_wait");
6089 tog_io.wait_for_ui = 0;
6092 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6093 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6094 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6095 free(id_str);
6096 return got_error_from_errno("asprintf");
6098 free(id_str);
6099 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6100 free(line);
6101 line = NULL;
6102 if (err)
6103 return err;
6104 waddwstr(view->window, wline);
6105 free(wline);
6106 wline = NULL;
6107 if (width < view->ncols - 1)
6108 waddch(view->window, '\n');
6110 s->eof = 0;
6111 view->maxx = 0;
6112 while (nprinted < view->nlines - 2) {
6113 linelen = getline(&line, &linesize, blame->f);
6114 if (linelen == -1) {
6115 if (feof(blame->f)) {
6116 s->eof = 1;
6117 break;
6119 free(line);
6120 return got_ferror(blame->f, GOT_ERR_IO);
6122 if (++lineno < s->first_displayed_line)
6123 continue;
6124 if (view->gline && !gotoline(view, &lineno, &nprinted))
6125 continue;
6127 /* Set view->maxx based on full line length. */
6128 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6129 if (err) {
6130 free(line);
6131 return err;
6133 free(wline);
6134 wline = NULL;
6135 view->maxx = MAX(view->maxx, width);
6137 if (nprinted == s->selected_line - 1)
6138 wstandout(view->window);
6140 if (blame->nlines > 0) {
6141 blame_line = &blame->lines[lineno - 1];
6142 if (blame_line->annotated && prev_id &&
6143 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6144 !(nprinted == s->selected_line - 1)) {
6145 waddstr(view->window, " ");
6146 } else if (blame_line->annotated) {
6147 char *id_str;
6148 err = got_object_id_str(&id_str,
6149 blame_line->id);
6150 if (err) {
6151 free(line);
6152 return err;
6154 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6155 if (tc)
6156 wattr_on(view->window,
6157 COLOR_PAIR(tc->colorpair), NULL);
6158 wprintw(view->window, "%.8s", id_str);
6159 if (tc)
6160 wattr_off(view->window,
6161 COLOR_PAIR(tc->colorpair), NULL);
6162 free(id_str);
6163 prev_id = blame_line->id;
6164 } else {
6165 waddstr(view->window, "........");
6166 prev_id = NULL;
6168 } else {
6169 waddstr(view->window, "........");
6170 prev_id = NULL;
6173 if (nprinted == s->selected_line - 1)
6174 wstandend(view->window);
6175 waddstr(view->window, " ");
6177 if (view->ncols <= 9) {
6178 width = 9;
6179 } else if (s->first_displayed_line + nprinted ==
6180 s->matched_line &&
6181 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6182 err = add_matched_line(&width, line, view->ncols - 9, 9,
6183 view->window, view->x, regmatch);
6184 if (err) {
6185 free(line);
6186 return err;
6188 width += 9;
6189 } else {
6190 int skip;
6191 err = format_line(&wline, &width, &skip, line,
6192 view->x, view->ncols - 9, 9, 1);
6193 if (err) {
6194 free(line);
6195 return err;
6197 waddwstr(view->window, &wline[skip]);
6198 width += 9;
6199 free(wline);
6200 wline = NULL;
6203 if (width <= view->ncols - 1)
6204 waddch(view->window, '\n');
6205 if (++nprinted == 1)
6206 s->first_displayed_line = lineno;
6208 free(line);
6209 s->last_displayed_line = lineno;
6211 view_border(view);
6213 return NULL;
6216 static const struct got_error *
6217 blame_cb(void *arg, int nlines, int lineno,
6218 struct got_commit_object *commit, struct got_object_id *id)
6220 const struct got_error *err = NULL;
6221 struct tog_blame_cb_args *a = arg;
6222 struct tog_blame_line *line;
6223 int errcode;
6225 if (nlines != a->nlines ||
6226 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6227 return got_error(GOT_ERR_RANGE);
6229 errcode = pthread_mutex_lock(&tog_mutex);
6230 if (errcode)
6231 return got_error_set_errno(errcode, "pthread_mutex_lock");
6233 if (*a->quit) { /* user has quit the blame view */
6234 err = got_error(GOT_ERR_ITER_COMPLETED);
6235 goto done;
6238 if (lineno == -1)
6239 goto done; /* no change in this commit */
6241 line = &a->lines[lineno - 1];
6242 if (line->annotated)
6243 goto done;
6245 line->id = got_object_id_dup(id);
6246 if (line->id == NULL) {
6247 err = got_error_from_errno("got_object_id_dup");
6248 goto done;
6250 line->annotated = 1;
6251 done:
6252 errcode = pthread_mutex_unlock(&tog_mutex);
6253 if (errcode)
6254 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6255 return err;
6258 static void *
6259 blame_thread(void *arg)
6261 const struct got_error *err, *close_err;
6262 struct tog_blame_thread_args *ta = arg;
6263 struct tog_blame_cb_args *a = ta->cb_args;
6264 int errcode, fd1 = -1, fd2 = -1;
6265 FILE *f1 = NULL, *f2 = NULL;
6267 fd1 = got_opentempfd();
6268 if (fd1 == -1)
6269 return (void *)got_error_from_errno("got_opentempfd");
6271 fd2 = got_opentempfd();
6272 if (fd2 == -1) {
6273 err = got_error_from_errno("got_opentempfd");
6274 goto done;
6277 f1 = got_opentemp();
6278 if (f1 == NULL) {
6279 err = (void *)got_error_from_errno("got_opentemp");
6280 goto done;
6282 f2 = got_opentemp();
6283 if (f2 == NULL) {
6284 err = (void *)got_error_from_errno("got_opentemp");
6285 goto done;
6288 err = block_signals_used_by_main_thread();
6289 if (err)
6290 goto done;
6292 err = got_blame(ta->path, a->commit_id, ta->repo,
6293 tog_diff_algo, blame_cb, ta->cb_args,
6294 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6295 if (err && err->code == GOT_ERR_CANCELLED)
6296 err = NULL;
6298 errcode = pthread_mutex_lock(&tog_mutex);
6299 if (errcode) {
6300 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6301 goto done;
6304 close_err = got_repo_close(ta->repo);
6305 if (err == NULL)
6306 err = close_err;
6307 ta->repo = NULL;
6308 *ta->complete = 1;
6310 if (tog_io.wait_for_ui) {
6311 errcode = pthread_cond_signal(&ta->blame_complete);
6312 if (errcode && err == NULL)
6313 err = got_error_set_errno(errcode,
6314 "pthread_cond_signal");
6317 errcode = pthread_mutex_unlock(&tog_mutex);
6318 if (errcode && err == NULL)
6319 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6321 done:
6322 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6323 err = got_error_from_errno("close");
6324 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6325 err = got_error_from_errno("close");
6326 if (f1 && fclose(f1) == EOF && err == NULL)
6327 err = got_error_from_errno("fclose");
6328 if (f2 && fclose(f2) == EOF && err == NULL)
6329 err = got_error_from_errno("fclose");
6331 return (void *)err;
6334 static struct got_object_id *
6335 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6336 int first_displayed_line, int selected_line)
6338 struct tog_blame_line *line;
6340 if (nlines <= 0)
6341 return NULL;
6343 line = &lines[first_displayed_line - 1 + selected_line - 1];
6344 if (!line->annotated)
6345 return NULL;
6347 return line->id;
6350 static struct got_object_id *
6351 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6352 int lineno)
6354 struct tog_blame_line *line;
6356 if (nlines <= 0 || lineno >= nlines)
6357 return NULL;
6359 line = &lines[lineno - 1];
6360 if (!line->annotated)
6361 return NULL;
6363 return line->id;
6366 static const struct got_error *
6367 stop_blame(struct tog_blame *blame)
6369 const struct got_error *err = NULL;
6370 int i;
6372 if (blame->thread) {
6373 int errcode;
6374 errcode = pthread_mutex_unlock(&tog_mutex);
6375 if (errcode)
6376 return got_error_set_errno(errcode,
6377 "pthread_mutex_unlock");
6378 errcode = pthread_join(blame->thread, (void **)&err);
6379 if (errcode)
6380 return got_error_set_errno(errcode, "pthread_join");
6381 errcode = pthread_mutex_lock(&tog_mutex);
6382 if (errcode)
6383 return got_error_set_errno(errcode,
6384 "pthread_mutex_lock");
6385 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6386 err = NULL;
6387 blame->thread = NULL;
6389 if (blame->thread_args.repo) {
6390 const struct got_error *close_err;
6391 close_err = got_repo_close(blame->thread_args.repo);
6392 if (err == NULL)
6393 err = close_err;
6394 blame->thread_args.repo = NULL;
6396 if (blame->f) {
6397 if (fclose(blame->f) == EOF && err == NULL)
6398 err = got_error_from_errno("fclose");
6399 blame->f = NULL;
6401 if (blame->lines) {
6402 for (i = 0; i < blame->nlines; i++)
6403 free(blame->lines[i].id);
6404 free(blame->lines);
6405 blame->lines = NULL;
6407 free(blame->cb_args.commit_id);
6408 blame->cb_args.commit_id = NULL;
6409 if (blame->pack_fds) {
6410 const struct got_error *pack_err =
6411 got_repo_pack_fds_close(blame->pack_fds);
6412 if (err == NULL)
6413 err = pack_err;
6414 blame->pack_fds = NULL;
6416 return err;
6419 static const struct got_error *
6420 cancel_blame_view(void *arg)
6422 const struct got_error *err = NULL;
6423 int *done = arg;
6424 int errcode;
6426 errcode = pthread_mutex_lock(&tog_mutex);
6427 if (errcode)
6428 return got_error_set_errno(errcode,
6429 "pthread_mutex_unlock");
6431 if (*done)
6432 err = got_error(GOT_ERR_CANCELLED);
6434 errcode = pthread_mutex_unlock(&tog_mutex);
6435 if (errcode)
6436 return got_error_set_errno(errcode,
6437 "pthread_mutex_lock");
6439 return err;
6442 static const struct got_error *
6443 run_blame(struct tog_view *view)
6445 struct tog_blame_view_state *s = &view->state.blame;
6446 struct tog_blame *blame = &s->blame;
6447 const struct got_error *err = NULL;
6448 struct got_commit_object *commit = NULL;
6449 struct got_blob_object *blob = NULL;
6450 struct got_repository *thread_repo = NULL;
6451 struct got_object_id *obj_id = NULL;
6452 int obj_type, fd = -1;
6453 int *pack_fds = NULL;
6455 err = got_object_open_as_commit(&commit, s->repo,
6456 &s->blamed_commit->id);
6457 if (err)
6458 return err;
6460 fd = got_opentempfd();
6461 if (fd == -1) {
6462 err = got_error_from_errno("got_opentempfd");
6463 goto done;
6466 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6467 if (err)
6468 goto done;
6470 err = got_object_get_type(&obj_type, s->repo, obj_id);
6471 if (err)
6472 goto done;
6474 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6475 err = got_error(GOT_ERR_OBJ_TYPE);
6476 goto done;
6479 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6480 if (err)
6481 goto done;
6482 blame->f = got_opentemp();
6483 if (blame->f == NULL) {
6484 err = got_error_from_errno("got_opentemp");
6485 goto done;
6487 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6488 &blame->line_offsets, blame->f, blob);
6489 if (err)
6490 goto done;
6491 if (blame->nlines == 0) {
6492 s->blame_complete = 1;
6493 goto done;
6496 /* Don't include \n at EOF in the blame line count. */
6497 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6498 blame->nlines--;
6500 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6501 if (blame->lines == NULL) {
6502 err = got_error_from_errno("calloc");
6503 goto done;
6506 err = got_repo_pack_fds_open(&pack_fds);
6507 if (err)
6508 goto done;
6509 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6510 pack_fds);
6511 if (err)
6512 goto done;
6514 blame->pack_fds = pack_fds;
6515 blame->cb_args.view = view;
6516 blame->cb_args.lines = blame->lines;
6517 blame->cb_args.nlines = blame->nlines;
6518 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6519 if (blame->cb_args.commit_id == NULL) {
6520 err = got_error_from_errno("got_object_id_dup");
6521 goto done;
6523 blame->cb_args.quit = &s->done;
6525 blame->thread_args.path = s->path;
6526 blame->thread_args.repo = thread_repo;
6527 blame->thread_args.cb_args = &blame->cb_args;
6528 blame->thread_args.complete = &s->blame_complete;
6529 blame->thread_args.cancel_cb = cancel_blame_view;
6530 blame->thread_args.cancel_arg = &s->done;
6531 s->blame_complete = 0;
6533 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6534 s->first_displayed_line = 1;
6535 s->last_displayed_line = view->nlines;
6536 s->selected_line = 1;
6538 s->matched_line = 0;
6540 done:
6541 if (commit)
6542 got_object_commit_close(commit);
6543 if (fd != -1 && close(fd) == -1 && err == NULL)
6544 err = got_error_from_errno("close");
6545 if (blob)
6546 got_object_blob_close(blob);
6547 free(obj_id);
6548 if (err)
6549 stop_blame(blame);
6550 return err;
6553 static const struct got_error *
6554 open_blame_view(struct tog_view *view, char *path,
6555 struct got_object_id *commit_id, struct got_repository *repo)
6557 const struct got_error *err = NULL;
6558 struct tog_blame_view_state *s = &view->state.blame;
6560 STAILQ_INIT(&s->blamed_commits);
6562 s->path = strdup(path);
6563 if (s->path == NULL)
6564 return got_error_from_errno("strdup");
6566 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6567 if (err) {
6568 free(s->path);
6569 return err;
6572 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6573 s->first_displayed_line = 1;
6574 s->last_displayed_line = view->nlines;
6575 s->selected_line = 1;
6576 s->blame_complete = 0;
6577 s->repo = repo;
6578 s->commit_id = commit_id;
6579 memset(&s->blame, 0, sizeof(s->blame));
6581 STAILQ_INIT(&s->colors);
6582 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6583 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6584 get_color_value("TOG_COLOR_COMMIT"));
6585 if (err)
6586 return err;
6589 view->show = show_blame_view;
6590 view->input = input_blame_view;
6591 view->reset = reset_blame_view;
6592 view->close = close_blame_view;
6593 view->search_start = search_start_blame_view;
6594 view->search_setup = search_setup_blame_view;
6595 view->search_next = search_next_view_match;
6597 if (using_mock_io) {
6598 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6599 int rc;
6601 rc = pthread_cond_init(&bta->blame_complete, NULL);
6602 if (rc)
6603 return got_error_set_errno(rc, "pthread_cond_init");
6606 return run_blame(view);
6609 static const struct got_error *
6610 close_blame_view(struct tog_view *view)
6612 const struct got_error *err = NULL;
6613 struct tog_blame_view_state *s = &view->state.blame;
6615 if (s->blame.thread)
6616 err = stop_blame(&s->blame);
6618 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6619 struct got_object_qid *blamed_commit;
6620 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6621 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6622 got_object_qid_free(blamed_commit);
6625 if (using_mock_io) {
6626 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6627 int rc;
6629 rc = pthread_cond_destroy(&bta->blame_complete);
6630 if (rc && err == NULL)
6631 err = got_error_set_errno(rc, "pthread_cond_destroy");
6634 free(s->path);
6635 free_colors(&s->colors);
6636 return err;
6639 static const struct got_error *
6640 search_start_blame_view(struct tog_view *view)
6642 struct tog_blame_view_state *s = &view->state.blame;
6644 s->matched_line = 0;
6645 return NULL;
6648 static void
6649 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6650 size_t *nlines, int **first, int **last, int **match, int **selected)
6652 struct tog_blame_view_state *s = &view->state.blame;
6654 *f = s->blame.f;
6655 *nlines = s->blame.nlines;
6656 *line_offsets = s->blame.line_offsets;
6657 *match = &s->matched_line;
6658 *first = &s->first_displayed_line;
6659 *last = &s->last_displayed_line;
6660 *selected = &s->selected_line;
6663 static const struct got_error *
6664 show_blame_view(struct tog_view *view)
6666 const struct got_error *err = NULL;
6667 struct tog_blame_view_state *s = &view->state.blame;
6668 int errcode;
6670 if (s->blame.thread == NULL && !s->blame_complete) {
6671 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6672 &s->blame.thread_args);
6673 if (errcode)
6674 return got_error_set_errno(errcode, "pthread_create");
6676 if (!using_mock_io)
6677 halfdelay(1); /* fast refresh while annotating */
6680 if (s->blame_complete && !using_mock_io)
6681 halfdelay(10); /* disable fast refresh */
6683 err = draw_blame(view);
6685 view_border(view);
6686 return err;
6689 static const struct got_error *
6690 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6691 struct got_repository *repo, struct got_object_id *id)
6693 struct tog_view *log_view;
6694 const struct got_error *err = NULL;
6696 *new_view = NULL;
6698 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6699 if (log_view == NULL)
6700 return got_error_from_errno("view_open");
6702 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6703 if (err)
6704 view_close(log_view);
6705 else
6706 *new_view = log_view;
6708 return err;
6711 static const struct got_error *
6712 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6714 const struct got_error *err = NULL, *thread_err = NULL;
6715 struct tog_view *diff_view;
6716 struct tog_blame_view_state *s = &view->state.blame;
6717 int eos, nscroll, begin_y = 0, begin_x = 0;
6719 eos = nscroll = view->nlines - 2;
6720 if (view_is_hsplit_top(view))
6721 --eos; /* border */
6723 switch (ch) {
6724 case '0':
6725 case '$':
6726 case KEY_RIGHT:
6727 case 'l':
6728 case KEY_LEFT:
6729 case 'h':
6730 horizontal_scroll_input(view, ch);
6731 break;
6732 case 'q':
6733 s->done = 1;
6734 break;
6735 case 'g':
6736 case KEY_HOME:
6737 s->selected_line = 1;
6738 s->first_displayed_line = 1;
6739 view->count = 0;
6740 break;
6741 case 'G':
6742 case KEY_END:
6743 if (s->blame.nlines < eos) {
6744 s->selected_line = s->blame.nlines;
6745 s->first_displayed_line = 1;
6746 } else {
6747 s->selected_line = eos;
6748 s->first_displayed_line = s->blame.nlines - (eos - 1);
6750 view->count = 0;
6751 break;
6752 case 'k':
6753 case KEY_UP:
6754 case CTRL('p'):
6755 if (s->selected_line > 1)
6756 s->selected_line--;
6757 else if (s->selected_line == 1 &&
6758 s->first_displayed_line > 1)
6759 s->first_displayed_line--;
6760 else
6761 view->count = 0;
6762 break;
6763 case CTRL('u'):
6764 case 'u':
6765 nscroll /= 2;
6766 /* FALL THROUGH */
6767 case KEY_PPAGE:
6768 case CTRL('b'):
6769 case 'b':
6770 if (s->first_displayed_line == 1) {
6771 if (view->count > 1)
6772 nscroll += nscroll;
6773 s->selected_line = MAX(1, s->selected_line - nscroll);
6774 view->count = 0;
6775 break;
6777 if (s->first_displayed_line > nscroll)
6778 s->first_displayed_line -= nscroll;
6779 else
6780 s->first_displayed_line = 1;
6781 break;
6782 case 'j':
6783 case KEY_DOWN:
6784 case CTRL('n'):
6785 if (s->selected_line < eos && s->first_displayed_line +
6786 s->selected_line <= s->blame.nlines)
6787 s->selected_line++;
6788 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6789 s->first_displayed_line++;
6790 else
6791 view->count = 0;
6792 break;
6793 case 'c':
6794 case 'p': {
6795 struct got_object_id *id = NULL;
6797 view->count = 0;
6798 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6799 s->first_displayed_line, s->selected_line);
6800 if (id == NULL)
6801 break;
6802 if (ch == 'p') {
6803 struct got_commit_object *commit, *pcommit;
6804 struct got_object_qid *pid;
6805 struct got_object_id *blob_id = NULL;
6806 int obj_type;
6807 err = got_object_open_as_commit(&commit,
6808 s->repo, id);
6809 if (err)
6810 break;
6811 pid = STAILQ_FIRST(
6812 got_object_commit_get_parent_ids(commit));
6813 if (pid == NULL) {
6814 got_object_commit_close(commit);
6815 break;
6817 /* Check if path history ends here. */
6818 err = got_object_open_as_commit(&pcommit,
6819 s->repo, &pid->id);
6820 if (err)
6821 break;
6822 err = got_object_id_by_path(&blob_id, s->repo,
6823 pcommit, s->path);
6824 got_object_commit_close(pcommit);
6825 if (err) {
6826 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6827 err = NULL;
6828 got_object_commit_close(commit);
6829 break;
6831 err = got_object_get_type(&obj_type, s->repo,
6832 blob_id);
6833 free(blob_id);
6834 /* Can't blame non-blob type objects. */
6835 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6836 got_object_commit_close(commit);
6837 break;
6839 err = got_object_qid_alloc(&s->blamed_commit,
6840 &pid->id);
6841 got_object_commit_close(commit);
6842 } else {
6843 if (got_object_id_cmp(id,
6844 &s->blamed_commit->id) == 0)
6845 break;
6846 err = got_object_qid_alloc(&s->blamed_commit,
6847 id);
6849 if (err)
6850 break;
6851 s->done = 1;
6852 thread_err = stop_blame(&s->blame);
6853 s->done = 0;
6854 if (thread_err)
6855 break;
6856 STAILQ_INSERT_HEAD(&s->blamed_commits,
6857 s->blamed_commit, entry);
6858 err = run_blame(view);
6859 if (err)
6860 break;
6861 break;
6863 case 'C': {
6864 struct got_object_qid *first;
6866 view->count = 0;
6867 first = STAILQ_FIRST(&s->blamed_commits);
6868 if (!got_object_id_cmp(&first->id, s->commit_id))
6869 break;
6870 s->done = 1;
6871 thread_err = stop_blame(&s->blame);
6872 s->done = 0;
6873 if (thread_err)
6874 break;
6875 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6876 got_object_qid_free(s->blamed_commit);
6877 s->blamed_commit =
6878 STAILQ_FIRST(&s->blamed_commits);
6879 err = run_blame(view);
6880 if (err)
6881 break;
6882 break;
6884 case 'L':
6885 view->count = 0;
6886 s->id_to_log = get_selected_commit_id(s->blame.lines,
6887 s->blame.nlines, s->first_displayed_line, s->selected_line);
6888 if (s->id_to_log)
6889 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6890 break;
6891 case KEY_ENTER:
6892 case '\r': {
6893 struct got_object_id *id = NULL;
6894 struct got_object_qid *pid;
6895 struct got_commit_object *commit = NULL;
6897 view->count = 0;
6898 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6899 s->first_displayed_line, s->selected_line);
6900 if (id == NULL)
6901 break;
6902 err = got_object_open_as_commit(&commit, s->repo, id);
6903 if (err)
6904 break;
6905 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6906 if (*new_view) {
6907 /* traversed from diff view, release diff resources */
6908 err = close_diff_view(*new_view);
6909 if (err)
6910 break;
6911 diff_view = *new_view;
6912 } else {
6913 if (view_is_parent_view(view))
6914 view_get_split(view, &begin_y, &begin_x);
6916 diff_view = view_open(0, 0, begin_y, begin_x,
6917 TOG_VIEW_DIFF);
6918 if (diff_view == NULL) {
6919 got_object_commit_close(commit);
6920 err = got_error_from_errno("view_open");
6921 break;
6924 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6925 id, NULL, NULL, 3, 0, 0, view, s->repo);
6926 got_object_commit_close(commit);
6927 if (err) {
6928 view_close(diff_view);
6929 break;
6931 s->last_diffed_line = s->first_displayed_line - 1 +
6932 s->selected_line;
6933 if (*new_view)
6934 break; /* still open from active diff view */
6935 if (view_is_parent_view(view) &&
6936 view->mode == TOG_VIEW_SPLIT_HRZN) {
6937 err = view_init_hsplit(view, begin_y);
6938 if (err)
6939 break;
6942 view->focussed = 0;
6943 diff_view->focussed = 1;
6944 diff_view->mode = view->mode;
6945 diff_view->nlines = view->lines - begin_y;
6946 if (view_is_parent_view(view)) {
6947 view_transfer_size(diff_view, view);
6948 err = view_close_child(view);
6949 if (err)
6950 break;
6951 err = view_set_child(view, diff_view);
6952 if (err)
6953 break;
6954 view->focus_child = 1;
6955 } else
6956 *new_view = diff_view;
6957 if (err)
6958 break;
6959 break;
6961 case CTRL('d'):
6962 case 'd':
6963 nscroll /= 2;
6964 /* FALL THROUGH */
6965 case KEY_NPAGE:
6966 case CTRL('f'):
6967 case 'f':
6968 case ' ':
6969 if (s->last_displayed_line >= s->blame.nlines &&
6970 s->selected_line >= MIN(s->blame.nlines,
6971 view->nlines - 2)) {
6972 view->count = 0;
6973 break;
6975 if (s->last_displayed_line >= s->blame.nlines &&
6976 s->selected_line < view->nlines - 2) {
6977 s->selected_line +=
6978 MIN(nscroll, s->last_displayed_line -
6979 s->first_displayed_line - s->selected_line + 1);
6981 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6982 s->first_displayed_line += nscroll;
6983 else
6984 s->first_displayed_line =
6985 s->blame.nlines - (view->nlines - 3);
6986 break;
6987 case KEY_RESIZE:
6988 if (s->selected_line > view->nlines - 2) {
6989 s->selected_line = MIN(s->blame.nlines,
6990 view->nlines - 2);
6992 break;
6993 default:
6994 view->count = 0;
6995 break;
6997 return thread_err ? thread_err : err;
7000 static const struct got_error *
7001 reset_blame_view(struct tog_view *view)
7003 const struct got_error *err;
7004 struct tog_blame_view_state *s = &view->state.blame;
7006 view->count = 0;
7007 s->done = 1;
7008 err = stop_blame(&s->blame);
7009 s->done = 0;
7010 if (err)
7011 return err;
7012 return run_blame(view);
7015 static const struct got_error *
7016 cmd_blame(int argc, char *argv[])
7018 const struct got_error *error;
7019 struct got_repository *repo = NULL;
7020 struct got_worktree *worktree = NULL;
7021 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7022 char *link_target = NULL;
7023 struct got_object_id *commit_id = NULL;
7024 struct got_commit_object *commit = NULL;
7025 char *commit_id_str = NULL;
7026 int ch;
7027 struct tog_view *view = NULL;
7028 int *pack_fds = NULL;
7030 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7031 switch (ch) {
7032 case 'c':
7033 commit_id_str = optarg;
7034 break;
7035 case 'r':
7036 repo_path = realpath(optarg, NULL);
7037 if (repo_path == NULL)
7038 return got_error_from_errno2("realpath",
7039 optarg);
7040 break;
7041 default:
7042 usage_blame();
7043 /* NOTREACHED */
7047 argc -= optind;
7048 argv += optind;
7050 if (argc != 1)
7051 usage_blame();
7053 error = got_repo_pack_fds_open(&pack_fds);
7054 if (error != NULL)
7055 goto done;
7057 if (repo_path == NULL) {
7058 cwd = getcwd(NULL, 0);
7059 if (cwd == NULL)
7060 return got_error_from_errno("getcwd");
7061 error = got_worktree_open(&worktree, cwd);
7062 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7063 goto done;
7064 if (worktree)
7065 repo_path =
7066 strdup(got_worktree_get_repo_path(worktree));
7067 else
7068 repo_path = strdup(cwd);
7069 if (repo_path == NULL) {
7070 error = got_error_from_errno("strdup");
7071 goto done;
7075 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7076 if (error != NULL)
7077 goto done;
7079 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7080 worktree);
7081 if (error)
7082 goto done;
7084 init_curses();
7086 error = apply_unveil(got_repo_get_path(repo), NULL);
7087 if (error)
7088 goto done;
7090 error = tog_load_refs(repo, 0);
7091 if (error)
7092 goto done;
7094 if (commit_id_str == NULL) {
7095 struct got_reference *head_ref;
7096 error = got_ref_open(&head_ref, repo, worktree ?
7097 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7098 if (error != NULL)
7099 goto done;
7100 error = got_ref_resolve(&commit_id, repo, head_ref);
7101 got_ref_close(head_ref);
7102 } else {
7103 error = got_repo_match_object_id(&commit_id, NULL,
7104 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7106 if (error != NULL)
7107 goto done;
7109 error = got_object_open_as_commit(&commit, repo, commit_id);
7110 if (error)
7111 goto done;
7113 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7114 commit, repo);
7115 if (error)
7116 goto done;
7118 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7119 if (view == NULL) {
7120 error = got_error_from_errno("view_open");
7121 goto done;
7123 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7124 commit_id, repo);
7125 if (error != NULL) {
7126 if (view->close == NULL)
7127 close_blame_view(view);
7128 view_close(view);
7129 goto done;
7131 if (worktree) {
7132 /* Release work tree lock. */
7133 got_worktree_close(worktree);
7134 worktree = NULL;
7136 error = view_loop(view);
7137 done:
7138 free(repo_path);
7139 free(in_repo_path);
7140 free(link_target);
7141 free(cwd);
7142 free(commit_id);
7143 if (commit)
7144 got_object_commit_close(commit);
7145 if (worktree)
7146 got_worktree_close(worktree);
7147 if (repo) {
7148 const struct got_error *close_err = got_repo_close(repo);
7149 if (error == NULL)
7150 error = close_err;
7152 if (pack_fds) {
7153 const struct got_error *pack_err =
7154 got_repo_pack_fds_close(pack_fds);
7155 if (error == NULL)
7156 error = pack_err;
7158 tog_free_refs();
7159 return error;
7162 static const struct got_error *
7163 draw_tree_entries(struct tog_view *view, const char *parent_path)
7165 struct tog_tree_view_state *s = &view->state.tree;
7166 const struct got_error *err = NULL;
7167 struct got_tree_entry *te;
7168 wchar_t *wline;
7169 char *index = NULL;
7170 struct tog_color *tc;
7171 int width, n, nentries, scrollx, i = 1;
7172 int limit = view->nlines;
7174 s->ndisplayed = 0;
7175 if (view_is_hsplit_top(view))
7176 --limit; /* border */
7178 werase(view->window);
7180 if (limit == 0)
7181 return NULL;
7183 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7184 0, 0);
7185 if (err)
7186 return err;
7187 if (view_needs_focus_indication(view))
7188 wstandout(view->window);
7189 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7190 if (tc)
7191 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7192 waddwstr(view->window, wline);
7193 free(wline);
7194 wline = NULL;
7195 while (width++ < view->ncols)
7196 waddch(view->window, ' ');
7197 if (tc)
7198 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7199 if (view_needs_focus_indication(view))
7200 wstandend(view->window);
7201 if (--limit <= 0)
7202 return NULL;
7204 i += s->selected;
7205 if (s->first_displayed_entry) {
7206 i += got_tree_entry_get_index(s->first_displayed_entry);
7207 if (s->tree != s->root)
7208 ++i; /* account for ".." entry */
7210 nentries = got_object_tree_get_nentries(s->tree);
7211 if (asprintf(&index, "[%d/%d] %s",
7212 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7213 return got_error_from_errno("asprintf");
7214 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7215 free(index);
7216 if (err)
7217 return err;
7218 waddwstr(view->window, wline);
7219 free(wline);
7220 wline = NULL;
7221 if (width < view->ncols - 1)
7222 waddch(view->window, '\n');
7223 if (--limit <= 0)
7224 return NULL;
7225 waddch(view->window, '\n');
7226 if (--limit <= 0)
7227 return NULL;
7229 if (s->first_displayed_entry == NULL) {
7230 te = got_object_tree_get_first_entry(s->tree);
7231 if (s->selected == 0) {
7232 if (view->focussed)
7233 wstandout(view->window);
7234 s->selected_entry = NULL;
7236 waddstr(view->window, " ..\n"); /* parent directory */
7237 if (s->selected == 0 && view->focussed)
7238 wstandend(view->window);
7239 s->ndisplayed++;
7240 if (--limit <= 0)
7241 return NULL;
7242 n = 1;
7243 } else {
7244 n = 0;
7245 te = s->first_displayed_entry;
7248 view->maxx = 0;
7249 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7250 char *line = NULL, *id_str = NULL, *link_target = NULL;
7251 const char *modestr = "";
7252 mode_t mode;
7254 te = got_object_tree_get_entry(s->tree, i);
7255 mode = got_tree_entry_get_mode(te);
7257 if (s->show_ids) {
7258 err = got_object_id_str(&id_str,
7259 got_tree_entry_get_id(te));
7260 if (err)
7261 return got_error_from_errno(
7262 "got_object_id_str");
7264 if (got_object_tree_entry_is_submodule(te))
7265 modestr = "$";
7266 else if (S_ISLNK(mode)) {
7267 int i;
7269 err = got_tree_entry_get_symlink_target(&link_target,
7270 te, s->repo);
7271 if (err) {
7272 free(id_str);
7273 return err;
7275 for (i = 0; i < strlen(link_target); i++) {
7276 if (!isprint((unsigned char)link_target[i]))
7277 link_target[i] = '?';
7279 modestr = "@";
7281 else if (S_ISDIR(mode))
7282 modestr = "/";
7283 else if (mode & S_IXUSR)
7284 modestr = "*";
7285 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7286 got_tree_entry_get_name(te), modestr,
7287 link_target ? " -> ": "",
7288 link_target ? link_target : "") == -1) {
7289 free(id_str);
7290 free(link_target);
7291 return got_error_from_errno("asprintf");
7293 free(id_str);
7294 free(link_target);
7296 /* use full line width to determine view->maxx */
7297 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7298 if (err) {
7299 free(line);
7300 break;
7302 view->maxx = MAX(view->maxx, width);
7303 free(wline);
7304 wline = NULL;
7306 err = format_line(&wline, &width, &scrollx, line, view->x,
7307 view->ncols, 0, 0);
7308 if (err) {
7309 free(line);
7310 break;
7312 if (n == s->selected) {
7313 if (view->focussed)
7314 wstandout(view->window);
7315 s->selected_entry = te;
7317 tc = match_color(&s->colors, line);
7318 if (tc)
7319 wattr_on(view->window,
7320 COLOR_PAIR(tc->colorpair), NULL);
7321 waddwstr(view->window, &wline[scrollx]);
7322 if (tc)
7323 wattr_off(view->window,
7324 COLOR_PAIR(tc->colorpair), NULL);
7325 if (width < view->ncols)
7326 waddch(view->window, '\n');
7327 if (n == s->selected && view->focussed)
7328 wstandend(view->window);
7329 free(line);
7330 free(wline);
7331 wline = NULL;
7332 n++;
7333 s->ndisplayed++;
7334 s->last_displayed_entry = te;
7335 if (--limit <= 0)
7336 break;
7339 return err;
7342 static void
7343 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7345 struct got_tree_entry *te;
7346 int isroot = s->tree == s->root;
7347 int i = 0;
7349 if (s->first_displayed_entry == NULL)
7350 return;
7352 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7353 while (i++ < maxscroll) {
7354 if (te == NULL) {
7355 if (!isroot)
7356 s->first_displayed_entry = NULL;
7357 break;
7359 s->first_displayed_entry = te;
7360 te = got_tree_entry_get_prev(s->tree, te);
7364 static const struct got_error *
7365 tree_scroll_down(struct tog_view *view, int maxscroll)
7367 struct tog_tree_view_state *s = &view->state.tree;
7368 struct got_tree_entry *next, *last;
7369 int n = 0;
7371 if (s->first_displayed_entry)
7372 next = got_tree_entry_get_next(s->tree,
7373 s->first_displayed_entry);
7374 else
7375 next = got_object_tree_get_first_entry(s->tree);
7377 last = s->last_displayed_entry;
7378 while (next && n++ < maxscroll) {
7379 if (last) {
7380 s->last_displayed_entry = last;
7381 last = got_tree_entry_get_next(s->tree, last);
7383 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7384 s->first_displayed_entry = next;
7385 next = got_tree_entry_get_next(s->tree, next);
7389 return NULL;
7392 static const struct got_error *
7393 tree_entry_path(char **path, struct tog_parent_trees *parents,
7394 struct got_tree_entry *te)
7396 const struct got_error *err = NULL;
7397 struct tog_parent_tree *pt;
7398 size_t len = 2; /* for leading slash and NUL */
7400 TAILQ_FOREACH(pt, parents, entry)
7401 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7402 + 1 /* slash */;
7403 if (te)
7404 len += strlen(got_tree_entry_get_name(te));
7406 *path = calloc(1, len);
7407 if (path == NULL)
7408 return got_error_from_errno("calloc");
7410 (*path)[0] = '/';
7411 pt = TAILQ_LAST(parents, tog_parent_trees);
7412 while (pt) {
7413 const char *name = got_tree_entry_get_name(pt->selected_entry);
7414 if (strlcat(*path, name, len) >= len) {
7415 err = got_error(GOT_ERR_NO_SPACE);
7416 goto done;
7418 if (strlcat(*path, "/", len) >= len) {
7419 err = got_error(GOT_ERR_NO_SPACE);
7420 goto done;
7422 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7424 if (te) {
7425 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7426 err = got_error(GOT_ERR_NO_SPACE);
7427 goto done;
7430 done:
7431 if (err) {
7432 free(*path);
7433 *path = NULL;
7435 return err;
7438 static const struct got_error *
7439 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7440 struct got_tree_entry *te, struct tog_parent_trees *parents,
7441 struct got_object_id *commit_id, struct got_repository *repo)
7443 const struct got_error *err = NULL;
7444 char *path;
7445 struct tog_view *blame_view;
7447 *new_view = NULL;
7449 err = tree_entry_path(&path, parents, te);
7450 if (err)
7451 return err;
7453 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7454 if (blame_view == NULL) {
7455 err = got_error_from_errno("view_open");
7456 goto done;
7459 err = open_blame_view(blame_view, path, commit_id, repo);
7460 if (err) {
7461 if (err->code == GOT_ERR_CANCELLED)
7462 err = NULL;
7463 view_close(blame_view);
7464 } else
7465 *new_view = blame_view;
7466 done:
7467 free(path);
7468 return err;
7471 static const struct got_error *
7472 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7473 struct tog_tree_view_state *s)
7475 struct tog_view *log_view;
7476 const struct got_error *err = NULL;
7477 char *path;
7479 *new_view = NULL;
7481 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7482 if (log_view == NULL)
7483 return got_error_from_errno("view_open");
7485 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7486 if (err)
7487 return err;
7489 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7490 path, 0);
7491 if (err)
7492 view_close(log_view);
7493 else
7494 *new_view = log_view;
7495 free(path);
7496 return err;
7499 static const struct got_error *
7500 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7501 const char *head_ref_name, struct got_repository *repo)
7503 const struct got_error *err = NULL;
7504 char *commit_id_str = NULL;
7505 struct tog_tree_view_state *s = &view->state.tree;
7506 struct got_commit_object *commit = NULL;
7508 TAILQ_INIT(&s->parents);
7509 STAILQ_INIT(&s->colors);
7511 s->commit_id = got_object_id_dup(commit_id);
7512 if (s->commit_id == NULL) {
7513 err = got_error_from_errno("got_object_id_dup");
7514 goto done;
7517 err = got_object_open_as_commit(&commit, repo, commit_id);
7518 if (err)
7519 goto done;
7522 * The root is opened here and will be closed when the view is closed.
7523 * Any visited subtrees and their path-wise parents are opened and
7524 * closed on demand.
7526 err = got_object_open_as_tree(&s->root, repo,
7527 got_object_commit_get_tree_id(commit));
7528 if (err)
7529 goto done;
7530 s->tree = s->root;
7532 err = got_object_id_str(&commit_id_str, commit_id);
7533 if (err != NULL)
7534 goto done;
7536 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7537 err = got_error_from_errno("asprintf");
7538 goto done;
7541 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7542 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7543 if (head_ref_name) {
7544 s->head_ref_name = strdup(head_ref_name);
7545 if (s->head_ref_name == NULL) {
7546 err = got_error_from_errno("strdup");
7547 goto done;
7550 s->repo = repo;
7552 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7553 err = add_color(&s->colors, "\\$$",
7554 TOG_COLOR_TREE_SUBMODULE,
7555 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7556 if (err)
7557 goto done;
7558 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7559 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7560 if (err)
7561 goto done;
7562 err = add_color(&s->colors, "/$",
7563 TOG_COLOR_TREE_DIRECTORY,
7564 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7565 if (err)
7566 goto done;
7568 err = add_color(&s->colors, "\\*$",
7569 TOG_COLOR_TREE_EXECUTABLE,
7570 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7571 if (err)
7572 goto done;
7574 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7575 get_color_value("TOG_COLOR_COMMIT"));
7576 if (err)
7577 goto done;
7580 view->show = show_tree_view;
7581 view->input = input_tree_view;
7582 view->close = close_tree_view;
7583 view->search_start = search_start_tree_view;
7584 view->search_next = search_next_tree_view;
7585 done:
7586 free(commit_id_str);
7587 if (commit)
7588 got_object_commit_close(commit);
7589 if (err) {
7590 if (view->close == NULL)
7591 close_tree_view(view);
7592 view_close(view);
7594 return err;
7597 static const struct got_error *
7598 close_tree_view(struct tog_view *view)
7600 struct tog_tree_view_state *s = &view->state.tree;
7602 free_colors(&s->colors);
7603 free(s->tree_label);
7604 s->tree_label = NULL;
7605 free(s->commit_id);
7606 s->commit_id = NULL;
7607 free(s->head_ref_name);
7608 s->head_ref_name = NULL;
7609 while (!TAILQ_EMPTY(&s->parents)) {
7610 struct tog_parent_tree *parent;
7611 parent = TAILQ_FIRST(&s->parents);
7612 TAILQ_REMOVE(&s->parents, parent, entry);
7613 if (parent->tree != s->root)
7614 got_object_tree_close(parent->tree);
7615 free(parent);
7618 if (s->tree != NULL && s->tree != s->root)
7619 got_object_tree_close(s->tree);
7620 if (s->root)
7621 got_object_tree_close(s->root);
7622 return NULL;
7625 static const struct got_error *
7626 search_start_tree_view(struct tog_view *view)
7628 struct tog_tree_view_state *s = &view->state.tree;
7630 s->matched_entry = NULL;
7631 return NULL;
7634 static int
7635 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7637 regmatch_t regmatch;
7639 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7640 0) == 0;
7643 static const struct got_error *
7644 search_next_tree_view(struct tog_view *view)
7646 struct tog_tree_view_state *s = &view->state.tree;
7647 struct got_tree_entry *te = NULL;
7649 if (!view->searching) {
7650 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7651 return NULL;
7654 if (s->matched_entry) {
7655 if (view->searching == TOG_SEARCH_FORWARD) {
7656 if (s->selected_entry)
7657 te = got_tree_entry_get_next(s->tree,
7658 s->selected_entry);
7659 else
7660 te = got_object_tree_get_first_entry(s->tree);
7661 } else {
7662 if (s->selected_entry == NULL)
7663 te = got_object_tree_get_last_entry(s->tree);
7664 else
7665 te = got_tree_entry_get_prev(s->tree,
7666 s->selected_entry);
7668 } else {
7669 if (s->selected_entry)
7670 te = s->selected_entry;
7671 else if (view->searching == TOG_SEARCH_FORWARD)
7672 te = got_object_tree_get_first_entry(s->tree);
7673 else
7674 te = got_object_tree_get_last_entry(s->tree);
7677 while (1) {
7678 if (te == NULL) {
7679 if (s->matched_entry == NULL) {
7680 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7681 return NULL;
7683 if (view->searching == TOG_SEARCH_FORWARD)
7684 te = got_object_tree_get_first_entry(s->tree);
7685 else
7686 te = got_object_tree_get_last_entry(s->tree);
7689 if (match_tree_entry(te, &view->regex)) {
7690 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7691 s->matched_entry = te;
7692 break;
7695 if (view->searching == TOG_SEARCH_FORWARD)
7696 te = got_tree_entry_get_next(s->tree, te);
7697 else
7698 te = got_tree_entry_get_prev(s->tree, te);
7701 if (s->matched_entry) {
7702 s->first_displayed_entry = s->matched_entry;
7703 s->selected = 0;
7706 return NULL;
7709 static const struct got_error *
7710 show_tree_view(struct tog_view *view)
7712 const struct got_error *err = NULL;
7713 struct tog_tree_view_state *s = &view->state.tree;
7714 char *parent_path;
7716 err = tree_entry_path(&parent_path, &s->parents, NULL);
7717 if (err)
7718 return err;
7720 err = draw_tree_entries(view, parent_path);
7721 free(parent_path);
7723 view_border(view);
7724 return err;
7727 static const struct got_error *
7728 tree_goto_line(struct tog_view *view, int nlines)
7730 const struct got_error *err = NULL;
7731 struct tog_tree_view_state *s = &view->state.tree;
7732 struct got_tree_entry **fte, **lte, **ste;
7733 int g, last, first = 1, i = 1;
7734 int root = s->tree == s->root;
7735 int off = root ? 1 : 2;
7737 g = view->gline;
7738 view->gline = 0;
7740 if (g == 0)
7741 g = 1;
7742 else if (g > got_object_tree_get_nentries(s->tree))
7743 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7745 fte = &s->first_displayed_entry;
7746 lte = &s->last_displayed_entry;
7747 ste = &s->selected_entry;
7749 if (*fte != NULL) {
7750 first = got_tree_entry_get_index(*fte);
7751 first += off; /* account for ".." */
7753 last = got_tree_entry_get_index(*lte);
7754 last += off;
7756 if (g >= first && g <= last && g - first < nlines) {
7757 s->selected = g - first;
7758 return NULL; /* gline is on the current page */
7761 if (*ste != NULL) {
7762 i = got_tree_entry_get_index(*ste);
7763 i += off;
7766 if (i < g) {
7767 err = tree_scroll_down(view, g - i);
7768 if (err)
7769 return err;
7770 if (got_tree_entry_get_index(*lte) >=
7771 got_object_tree_get_nentries(s->tree) - 1 &&
7772 first + s->selected < g &&
7773 s->selected < s->ndisplayed - 1) {
7774 first = got_tree_entry_get_index(*fte);
7775 first += off;
7776 s->selected = g - first;
7778 } else if (i > g)
7779 tree_scroll_up(s, i - g);
7781 if (g < nlines &&
7782 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7783 s->selected = g - 1;
7785 return NULL;
7788 static const struct got_error *
7789 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7791 const struct got_error *err = NULL;
7792 struct tog_tree_view_state *s = &view->state.tree;
7793 struct got_tree_entry *te;
7794 int n, nscroll = view->nlines - 3;
7796 if (view->gline)
7797 return tree_goto_line(view, nscroll);
7799 switch (ch) {
7800 case '0':
7801 case '$':
7802 case KEY_RIGHT:
7803 case 'l':
7804 case KEY_LEFT:
7805 case 'h':
7806 horizontal_scroll_input(view, ch);
7807 break;
7808 case 'i':
7809 s->show_ids = !s->show_ids;
7810 view->count = 0;
7811 break;
7812 case 'L':
7813 view->count = 0;
7814 if (!s->selected_entry)
7815 break;
7816 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7817 break;
7818 case 'R':
7819 view->count = 0;
7820 err = view_request_new(new_view, view, TOG_VIEW_REF);
7821 break;
7822 case 'g':
7823 case '=':
7824 case KEY_HOME:
7825 s->selected = 0;
7826 view->count = 0;
7827 if (s->tree == s->root)
7828 s->first_displayed_entry =
7829 got_object_tree_get_first_entry(s->tree);
7830 else
7831 s->first_displayed_entry = NULL;
7832 break;
7833 case 'G':
7834 case '*':
7835 case KEY_END: {
7836 int eos = view->nlines - 3;
7838 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7839 --eos; /* border */
7840 s->selected = 0;
7841 view->count = 0;
7842 te = got_object_tree_get_last_entry(s->tree);
7843 for (n = 0; n < eos; n++) {
7844 if (te == NULL) {
7845 if (s->tree != s->root) {
7846 s->first_displayed_entry = NULL;
7847 n++;
7849 break;
7851 s->first_displayed_entry = te;
7852 te = got_tree_entry_get_prev(s->tree, te);
7854 if (n > 0)
7855 s->selected = n - 1;
7856 break;
7858 case 'k':
7859 case KEY_UP:
7860 case CTRL('p'):
7861 if (s->selected > 0) {
7862 s->selected--;
7863 break;
7865 tree_scroll_up(s, 1);
7866 if (s->selected_entry == NULL ||
7867 (s->tree == s->root && s->selected_entry ==
7868 got_object_tree_get_first_entry(s->tree)))
7869 view->count = 0;
7870 break;
7871 case CTRL('u'):
7872 case 'u':
7873 nscroll /= 2;
7874 /* FALL THROUGH */
7875 case KEY_PPAGE:
7876 case CTRL('b'):
7877 case 'b':
7878 if (s->tree == s->root) {
7879 if (got_object_tree_get_first_entry(s->tree) ==
7880 s->first_displayed_entry)
7881 s->selected -= MIN(s->selected, nscroll);
7882 } else {
7883 if (s->first_displayed_entry == NULL)
7884 s->selected -= MIN(s->selected, nscroll);
7886 tree_scroll_up(s, MAX(0, nscroll));
7887 if (s->selected_entry == NULL ||
7888 (s->tree == s->root && s->selected_entry ==
7889 got_object_tree_get_first_entry(s->tree)))
7890 view->count = 0;
7891 break;
7892 case 'j':
7893 case KEY_DOWN:
7894 case CTRL('n'):
7895 if (s->selected < s->ndisplayed - 1) {
7896 s->selected++;
7897 break;
7899 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7900 == NULL) {
7901 /* can't scroll any further */
7902 view->count = 0;
7903 break;
7905 tree_scroll_down(view, 1);
7906 break;
7907 case CTRL('d'):
7908 case 'd':
7909 nscroll /= 2;
7910 /* FALL THROUGH */
7911 case KEY_NPAGE:
7912 case CTRL('f'):
7913 case 'f':
7914 case ' ':
7915 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7916 == NULL) {
7917 /* can't scroll any further; move cursor down */
7918 if (s->selected < s->ndisplayed - 1)
7919 s->selected += MIN(nscroll,
7920 s->ndisplayed - s->selected - 1);
7921 else
7922 view->count = 0;
7923 break;
7925 tree_scroll_down(view, nscroll);
7926 break;
7927 case KEY_ENTER:
7928 case '\r':
7929 case KEY_BACKSPACE:
7930 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7931 struct tog_parent_tree *parent;
7932 /* user selected '..' */
7933 if (s->tree == s->root) {
7934 view->count = 0;
7935 break;
7937 parent = TAILQ_FIRST(&s->parents);
7938 TAILQ_REMOVE(&s->parents, parent,
7939 entry);
7940 got_object_tree_close(s->tree);
7941 s->tree = parent->tree;
7942 s->first_displayed_entry =
7943 parent->first_displayed_entry;
7944 s->selected_entry =
7945 parent->selected_entry;
7946 s->selected = parent->selected;
7947 if (s->selected > view->nlines - 3) {
7948 err = offset_selection_down(view);
7949 if (err)
7950 break;
7952 free(parent);
7953 } else if (S_ISDIR(got_tree_entry_get_mode(
7954 s->selected_entry))) {
7955 struct got_tree_object *subtree;
7956 view->count = 0;
7957 err = got_object_open_as_tree(&subtree, s->repo,
7958 got_tree_entry_get_id(s->selected_entry));
7959 if (err)
7960 break;
7961 err = tree_view_visit_subtree(s, subtree);
7962 if (err) {
7963 got_object_tree_close(subtree);
7964 break;
7966 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7967 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7968 break;
7969 case KEY_RESIZE:
7970 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7971 s->selected = view->nlines - 4;
7972 view->count = 0;
7973 break;
7974 default:
7975 view->count = 0;
7976 break;
7979 return err;
7982 __dead static void
7983 usage_tree(void)
7985 endwin();
7986 fprintf(stderr,
7987 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7988 getprogname());
7989 exit(1);
7992 static const struct got_error *
7993 cmd_tree(int argc, char *argv[])
7995 const struct got_error *error;
7996 struct got_repository *repo = NULL;
7997 struct got_worktree *worktree = NULL;
7998 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7999 struct got_object_id *commit_id = NULL;
8000 struct got_commit_object *commit = NULL;
8001 const char *commit_id_arg = NULL;
8002 char *label = NULL;
8003 struct got_reference *ref = NULL;
8004 const char *head_ref_name = NULL;
8005 int ch;
8006 struct tog_view *view;
8007 int *pack_fds = NULL;
8009 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8010 switch (ch) {
8011 case 'c':
8012 commit_id_arg = optarg;
8013 break;
8014 case 'r':
8015 repo_path = realpath(optarg, NULL);
8016 if (repo_path == NULL)
8017 return got_error_from_errno2("realpath",
8018 optarg);
8019 break;
8020 default:
8021 usage_tree();
8022 /* NOTREACHED */
8026 argc -= optind;
8027 argv += optind;
8029 if (argc > 1)
8030 usage_tree();
8032 error = got_repo_pack_fds_open(&pack_fds);
8033 if (error != NULL)
8034 goto done;
8036 if (repo_path == NULL) {
8037 cwd = getcwd(NULL, 0);
8038 if (cwd == NULL)
8039 return got_error_from_errno("getcwd");
8040 error = got_worktree_open(&worktree, cwd);
8041 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8042 goto done;
8043 if (worktree)
8044 repo_path =
8045 strdup(got_worktree_get_repo_path(worktree));
8046 else
8047 repo_path = strdup(cwd);
8048 if (repo_path == NULL) {
8049 error = got_error_from_errno("strdup");
8050 goto done;
8054 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8055 if (error != NULL)
8056 goto done;
8058 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8059 repo, worktree);
8060 if (error)
8061 goto done;
8063 init_curses();
8065 error = apply_unveil(got_repo_get_path(repo), NULL);
8066 if (error)
8067 goto done;
8069 error = tog_load_refs(repo, 0);
8070 if (error)
8071 goto done;
8073 if (commit_id_arg == NULL) {
8074 error = got_repo_match_object_id(&commit_id, &label,
8075 worktree ? got_worktree_get_head_ref_name(worktree) :
8076 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8077 if (error)
8078 goto done;
8079 head_ref_name = label;
8080 } else {
8081 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8082 if (error == NULL)
8083 head_ref_name = got_ref_get_name(ref);
8084 else if (error->code != GOT_ERR_NOT_REF)
8085 goto done;
8086 error = got_repo_match_object_id(&commit_id, NULL,
8087 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8088 if (error)
8089 goto done;
8092 error = got_object_open_as_commit(&commit, repo, commit_id);
8093 if (error)
8094 goto done;
8096 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8097 if (view == NULL) {
8098 error = got_error_from_errno("view_open");
8099 goto done;
8101 error = open_tree_view(view, commit_id, head_ref_name, repo);
8102 if (error)
8103 goto done;
8104 if (!got_path_is_root_dir(in_repo_path)) {
8105 error = tree_view_walk_path(&view->state.tree, commit,
8106 in_repo_path);
8107 if (error)
8108 goto done;
8111 if (worktree) {
8112 /* Release work tree lock. */
8113 got_worktree_close(worktree);
8114 worktree = NULL;
8116 error = view_loop(view);
8117 done:
8118 free(repo_path);
8119 free(cwd);
8120 free(commit_id);
8121 free(label);
8122 if (ref)
8123 got_ref_close(ref);
8124 if (repo) {
8125 const struct got_error *close_err = got_repo_close(repo);
8126 if (error == NULL)
8127 error = close_err;
8129 if (pack_fds) {
8130 const struct got_error *pack_err =
8131 got_repo_pack_fds_close(pack_fds);
8132 if (error == NULL)
8133 error = pack_err;
8135 tog_free_refs();
8136 return error;
8139 static const struct got_error *
8140 ref_view_load_refs(struct tog_ref_view_state *s)
8142 struct got_reflist_entry *sre;
8143 struct tog_reflist_entry *re;
8145 s->nrefs = 0;
8146 TAILQ_FOREACH(sre, &tog_refs, entry) {
8147 if (strncmp(got_ref_get_name(sre->ref),
8148 "refs/got/", 9) == 0 &&
8149 strncmp(got_ref_get_name(sre->ref),
8150 "refs/got/backup/", 16) != 0)
8151 continue;
8153 re = malloc(sizeof(*re));
8154 if (re == NULL)
8155 return got_error_from_errno("malloc");
8157 re->ref = got_ref_dup(sre->ref);
8158 if (re->ref == NULL)
8159 return got_error_from_errno("got_ref_dup");
8160 re->idx = s->nrefs++;
8161 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8164 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8165 return NULL;
8168 static void
8169 ref_view_free_refs(struct tog_ref_view_state *s)
8171 struct tog_reflist_entry *re;
8173 while (!TAILQ_EMPTY(&s->refs)) {
8174 re = TAILQ_FIRST(&s->refs);
8175 TAILQ_REMOVE(&s->refs, re, entry);
8176 got_ref_close(re->ref);
8177 free(re);
8181 static const struct got_error *
8182 open_ref_view(struct tog_view *view, struct got_repository *repo)
8184 const struct got_error *err = NULL;
8185 struct tog_ref_view_state *s = &view->state.ref;
8187 s->selected_entry = 0;
8188 s->repo = repo;
8190 TAILQ_INIT(&s->refs);
8191 STAILQ_INIT(&s->colors);
8193 err = ref_view_load_refs(s);
8194 if (err)
8195 goto done;
8197 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8198 err = add_color(&s->colors, "^refs/heads/",
8199 TOG_COLOR_REFS_HEADS,
8200 get_color_value("TOG_COLOR_REFS_HEADS"));
8201 if (err)
8202 goto done;
8204 err = add_color(&s->colors, "^refs/tags/",
8205 TOG_COLOR_REFS_TAGS,
8206 get_color_value("TOG_COLOR_REFS_TAGS"));
8207 if (err)
8208 goto done;
8210 err = add_color(&s->colors, "^refs/remotes/",
8211 TOG_COLOR_REFS_REMOTES,
8212 get_color_value("TOG_COLOR_REFS_REMOTES"));
8213 if (err)
8214 goto done;
8216 err = add_color(&s->colors, "^refs/got/backup/",
8217 TOG_COLOR_REFS_BACKUP,
8218 get_color_value("TOG_COLOR_REFS_BACKUP"));
8219 if (err)
8220 goto done;
8223 view->show = show_ref_view;
8224 view->input = input_ref_view;
8225 view->close = close_ref_view;
8226 view->search_start = search_start_ref_view;
8227 view->search_next = search_next_ref_view;
8228 done:
8229 if (err) {
8230 if (view->close == NULL)
8231 close_ref_view(view);
8232 view_close(view);
8234 return err;
8237 static const struct got_error *
8238 close_ref_view(struct tog_view *view)
8240 struct tog_ref_view_state *s = &view->state.ref;
8242 ref_view_free_refs(s);
8243 free_colors(&s->colors);
8245 return NULL;
8248 static const struct got_error *
8249 resolve_reflist_entry(struct got_object_id **commit_id,
8250 struct tog_reflist_entry *re, struct got_repository *repo)
8252 const struct got_error *err = NULL;
8253 struct got_object_id *obj_id;
8254 struct got_tag_object *tag = NULL;
8255 int obj_type;
8257 *commit_id = NULL;
8259 err = got_ref_resolve(&obj_id, repo, re->ref);
8260 if (err)
8261 return err;
8263 err = got_object_get_type(&obj_type, repo, obj_id);
8264 if (err)
8265 goto done;
8267 switch (obj_type) {
8268 case GOT_OBJ_TYPE_COMMIT:
8269 *commit_id = obj_id;
8270 break;
8271 case GOT_OBJ_TYPE_TAG:
8272 err = got_object_open_as_tag(&tag, repo, obj_id);
8273 if (err)
8274 goto done;
8275 free(obj_id);
8276 err = got_object_get_type(&obj_type, repo,
8277 got_object_tag_get_object_id(tag));
8278 if (err)
8279 goto done;
8280 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8281 err = got_error(GOT_ERR_OBJ_TYPE);
8282 goto done;
8284 *commit_id = got_object_id_dup(
8285 got_object_tag_get_object_id(tag));
8286 if (*commit_id == NULL) {
8287 err = got_error_from_errno("got_object_id_dup");
8288 goto done;
8290 break;
8291 default:
8292 err = got_error(GOT_ERR_OBJ_TYPE);
8293 break;
8296 done:
8297 if (tag)
8298 got_object_tag_close(tag);
8299 if (err) {
8300 free(*commit_id);
8301 *commit_id = NULL;
8303 return err;
8306 static const struct got_error *
8307 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8308 struct tog_reflist_entry *re, struct got_repository *repo)
8310 struct tog_view *log_view;
8311 const struct got_error *err = NULL;
8312 struct got_object_id *commit_id = NULL;
8314 *new_view = NULL;
8316 err = resolve_reflist_entry(&commit_id, re, repo);
8317 if (err) {
8318 if (err->code != GOT_ERR_OBJ_TYPE)
8319 return err;
8320 else
8321 return NULL;
8324 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8325 if (log_view == NULL) {
8326 err = got_error_from_errno("view_open");
8327 goto done;
8330 err = open_log_view(log_view, commit_id, repo,
8331 got_ref_get_name(re->ref), "", 0);
8332 done:
8333 if (err)
8334 view_close(log_view);
8335 else
8336 *new_view = log_view;
8337 free(commit_id);
8338 return err;
8341 static void
8342 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8344 struct tog_reflist_entry *re;
8345 int i = 0;
8347 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8348 return;
8350 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8351 while (i++ < maxscroll) {
8352 if (re == NULL)
8353 break;
8354 s->first_displayed_entry = re;
8355 re = TAILQ_PREV(re, tog_reflist_head, entry);
8359 static const struct got_error *
8360 ref_scroll_down(struct tog_view *view, int maxscroll)
8362 struct tog_ref_view_state *s = &view->state.ref;
8363 struct tog_reflist_entry *next, *last;
8364 int n = 0;
8366 if (s->first_displayed_entry)
8367 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8368 else
8369 next = TAILQ_FIRST(&s->refs);
8371 last = s->last_displayed_entry;
8372 while (next && n++ < maxscroll) {
8373 if (last) {
8374 s->last_displayed_entry = last;
8375 last = TAILQ_NEXT(last, entry);
8377 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8378 s->first_displayed_entry = next;
8379 next = TAILQ_NEXT(next, entry);
8383 return NULL;
8386 static const struct got_error *
8387 search_start_ref_view(struct tog_view *view)
8389 struct tog_ref_view_state *s = &view->state.ref;
8391 s->matched_entry = NULL;
8392 return NULL;
8395 static int
8396 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8398 regmatch_t regmatch;
8400 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8401 0) == 0;
8404 static const struct got_error *
8405 search_next_ref_view(struct tog_view *view)
8407 struct tog_ref_view_state *s = &view->state.ref;
8408 struct tog_reflist_entry *re = NULL;
8410 if (!view->searching) {
8411 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8412 return NULL;
8415 if (s->matched_entry) {
8416 if (view->searching == TOG_SEARCH_FORWARD) {
8417 if (s->selected_entry)
8418 re = TAILQ_NEXT(s->selected_entry, entry);
8419 else
8420 re = TAILQ_PREV(s->selected_entry,
8421 tog_reflist_head, entry);
8422 } else {
8423 if (s->selected_entry == NULL)
8424 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8425 else
8426 re = TAILQ_PREV(s->selected_entry,
8427 tog_reflist_head, entry);
8429 } else {
8430 if (s->selected_entry)
8431 re = s->selected_entry;
8432 else if (view->searching == TOG_SEARCH_FORWARD)
8433 re = TAILQ_FIRST(&s->refs);
8434 else
8435 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8438 while (1) {
8439 if (re == NULL) {
8440 if (s->matched_entry == NULL) {
8441 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8442 return NULL;
8444 if (view->searching == TOG_SEARCH_FORWARD)
8445 re = TAILQ_FIRST(&s->refs);
8446 else
8447 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8450 if (match_reflist_entry(re, &view->regex)) {
8451 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8452 s->matched_entry = re;
8453 break;
8456 if (view->searching == TOG_SEARCH_FORWARD)
8457 re = TAILQ_NEXT(re, entry);
8458 else
8459 re = TAILQ_PREV(re, tog_reflist_head, entry);
8462 if (s->matched_entry) {
8463 s->first_displayed_entry = s->matched_entry;
8464 s->selected = 0;
8467 return NULL;
8470 static const struct got_error *
8471 show_ref_view(struct tog_view *view)
8473 const struct got_error *err = NULL;
8474 struct tog_ref_view_state *s = &view->state.ref;
8475 struct tog_reflist_entry *re;
8476 char *line = NULL;
8477 wchar_t *wline;
8478 struct tog_color *tc;
8479 int width, n, scrollx;
8480 int limit = view->nlines;
8482 werase(view->window);
8484 s->ndisplayed = 0;
8485 if (view_is_hsplit_top(view))
8486 --limit; /* border */
8488 if (limit == 0)
8489 return NULL;
8491 re = s->first_displayed_entry;
8493 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8494 s->nrefs) == -1)
8495 return got_error_from_errno("asprintf");
8497 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8498 if (err) {
8499 free(line);
8500 return err;
8502 if (view_needs_focus_indication(view))
8503 wstandout(view->window);
8504 waddwstr(view->window, wline);
8505 while (width++ < view->ncols)
8506 waddch(view->window, ' ');
8507 if (view_needs_focus_indication(view))
8508 wstandend(view->window);
8509 free(wline);
8510 wline = NULL;
8511 free(line);
8512 line = NULL;
8513 if (--limit <= 0)
8514 return NULL;
8516 n = 0;
8517 view->maxx = 0;
8518 while (re && limit > 0) {
8519 char *line = NULL;
8520 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8522 if (s->show_date) {
8523 struct got_commit_object *ci;
8524 struct got_tag_object *tag;
8525 struct got_object_id *id;
8526 struct tm tm;
8527 time_t t;
8529 err = got_ref_resolve(&id, s->repo, re->ref);
8530 if (err)
8531 return err;
8532 err = got_object_open_as_tag(&tag, s->repo, id);
8533 if (err) {
8534 if (err->code != GOT_ERR_OBJ_TYPE) {
8535 free(id);
8536 return err;
8538 err = got_object_open_as_commit(&ci, s->repo,
8539 id);
8540 if (err) {
8541 free(id);
8542 return err;
8544 t = got_object_commit_get_committer_time(ci);
8545 got_object_commit_close(ci);
8546 } else {
8547 t = got_object_tag_get_tagger_time(tag);
8548 got_object_tag_close(tag);
8550 free(id);
8551 if (gmtime_r(&t, &tm) == NULL)
8552 return got_error_from_errno("gmtime_r");
8553 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8554 return got_error(GOT_ERR_NO_SPACE);
8556 if (got_ref_is_symbolic(re->ref)) {
8557 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8558 ymd : "", got_ref_get_name(re->ref),
8559 got_ref_get_symref_target(re->ref)) == -1)
8560 return got_error_from_errno("asprintf");
8561 } else if (s->show_ids) {
8562 struct got_object_id *id;
8563 char *id_str;
8564 err = got_ref_resolve(&id, s->repo, re->ref);
8565 if (err)
8566 return err;
8567 err = got_object_id_str(&id_str, id);
8568 if (err) {
8569 free(id);
8570 return err;
8572 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8573 got_ref_get_name(re->ref), id_str) == -1) {
8574 err = got_error_from_errno("asprintf");
8575 free(id);
8576 free(id_str);
8577 return err;
8579 free(id);
8580 free(id_str);
8581 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8582 got_ref_get_name(re->ref)) == -1)
8583 return got_error_from_errno("asprintf");
8585 /* use full line width to determine view->maxx */
8586 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8587 if (err) {
8588 free(line);
8589 return err;
8591 view->maxx = MAX(view->maxx, width);
8592 free(wline);
8593 wline = NULL;
8595 err = format_line(&wline, &width, &scrollx, line, view->x,
8596 view->ncols, 0, 0);
8597 if (err) {
8598 free(line);
8599 return err;
8601 if (n == s->selected) {
8602 if (view->focussed)
8603 wstandout(view->window);
8604 s->selected_entry = re;
8606 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8607 if (tc)
8608 wattr_on(view->window,
8609 COLOR_PAIR(tc->colorpair), NULL);
8610 waddwstr(view->window, &wline[scrollx]);
8611 if (tc)
8612 wattr_off(view->window,
8613 COLOR_PAIR(tc->colorpair), NULL);
8614 if (width < view->ncols)
8615 waddch(view->window, '\n');
8616 if (n == s->selected && view->focussed)
8617 wstandend(view->window);
8618 free(line);
8619 free(wline);
8620 wline = NULL;
8621 n++;
8622 s->ndisplayed++;
8623 s->last_displayed_entry = re;
8625 limit--;
8626 re = TAILQ_NEXT(re, entry);
8629 view_border(view);
8630 return err;
8633 static const struct got_error *
8634 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8635 struct tog_reflist_entry *re, struct got_repository *repo)
8637 const struct got_error *err = NULL;
8638 struct got_object_id *commit_id = NULL;
8639 struct tog_view *tree_view;
8641 *new_view = NULL;
8643 err = resolve_reflist_entry(&commit_id, re, repo);
8644 if (err) {
8645 if (err->code != GOT_ERR_OBJ_TYPE)
8646 return err;
8647 else
8648 return NULL;
8652 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8653 if (tree_view == NULL) {
8654 err = got_error_from_errno("view_open");
8655 goto done;
8658 err = open_tree_view(tree_view, commit_id,
8659 got_ref_get_name(re->ref), repo);
8660 if (err)
8661 goto done;
8663 *new_view = tree_view;
8664 done:
8665 free(commit_id);
8666 return err;
8669 static const struct got_error *
8670 ref_goto_line(struct tog_view *view, int nlines)
8672 const struct got_error *err = NULL;
8673 struct tog_ref_view_state *s = &view->state.ref;
8674 int g, idx = s->selected_entry->idx;
8676 g = view->gline;
8677 view->gline = 0;
8679 if (g == 0)
8680 g = 1;
8681 else if (g > s->nrefs)
8682 g = s->nrefs;
8684 if (g >= s->first_displayed_entry->idx + 1 &&
8685 g <= s->last_displayed_entry->idx + 1 &&
8686 g - s->first_displayed_entry->idx - 1 < nlines) {
8687 s->selected = g - s->first_displayed_entry->idx - 1;
8688 return NULL;
8691 if (idx + 1 < g) {
8692 err = ref_scroll_down(view, g - idx - 1);
8693 if (err)
8694 return err;
8695 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8696 s->first_displayed_entry->idx + s->selected < g &&
8697 s->selected < s->ndisplayed - 1)
8698 s->selected = g - s->first_displayed_entry->idx - 1;
8699 } else if (idx + 1 > g)
8700 ref_scroll_up(s, idx - g + 1);
8702 if (g < nlines && s->first_displayed_entry->idx == 0)
8703 s->selected = g - 1;
8705 return NULL;
8709 static const struct got_error *
8710 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8712 const struct got_error *err = NULL;
8713 struct tog_ref_view_state *s = &view->state.ref;
8714 struct tog_reflist_entry *re;
8715 int n, nscroll = view->nlines - 1;
8717 if (view->gline)
8718 return ref_goto_line(view, nscroll);
8720 switch (ch) {
8721 case '0':
8722 case '$':
8723 case KEY_RIGHT:
8724 case 'l':
8725 case KEY_LEFT:
8726 case 'h':
8727 horizontal_scroll_input(view, ch);
8728 break;
8729 case 'i':
8730 s->show_ids = !s->show_ids;
8731 view->count = 0;
8732 break;
8733 case 'm':
8734 s->show_date = !s->show_date;
8735 view->count = 0;
8736 break;
8737 case 'o':
8738 s->sort_by_date = !s->sort_by_date;
8739 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8740 view->count = 0;
8741 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8742 got_ref_cmp_by_commit_timestamp_descending :
8743 tog_ref_cmp_by_name, s->repo);
8744 if (err)
8745 break;
8746 got_reflist_object_id_map_free(tog_refs_idmap);
8747 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8748 &tog_refs, s->repo);
8749 if (err)
8750 break;
8751 ref_view_free_refs(s);
8752 err = ref_view_load_refs(s);
8753 break;
8754 case KEY_ENTER:
8755 case '\r':
8756 view->count = 0;
8757 if (!s->selected_entry)
8758 break;
8759 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8760 break;
8761 case 'T':
8762 view->count = 0;
8763 if (!s->selected_entry)
8764 break;
8765 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8766 break;
8767 case 'g':
8768 case '=':
8769 case KEY_HOME:
8770 s->selected = 0;
8771 view->count = 0;
8772 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8773 break;
8774 case 'G':
8775 case '*':
8776 case KEY_END: {
8777 int eos = view->nlines - 1;
8779 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8780 --eos; /* border */
8781 s->selected = 0;
8782 view->count = 0;
8783 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8784 for (n = 0; n < eos; n++) {
8785 if (re == NULL)
8786 break;
8787 s->first_displayed_entry = re;
8788 re = TAILQ_PREV(re, tog_reflist_head, entry);
8790 if (n > 0)
8791 s->selected = n - 1;
8792 break;
8794 case 'k':
8795 case KEY_UP:
8796 case CTRL('p'):
8797 if (s->selected > 0) {
8798 s->selected--;
8799 break;
8801 ref_scroll_up(s, 1);
8802 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8803 view->count = 0;
8804 break;
8805 case CTRL('u'):
8806 case 'u':
8807 nscroll /= 2;
8808 /* FALL THROUGH */
8809 case KEY_PPAGE:
8810 case CTRL('b'):
8811 case 'b':
8812 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8813 s->selected -= MIN(nscroll, s->selected);
8814 ref_scroll_up(s, MAX(0, nscroll));
8815 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8816 view->count = 0;
8817 break;
8818 case 'j':
8819 case KEY_DOWN:
8820 case CTRL('n'):
8821 if (s->selected < s->ndisplayed - 1) {
8822 s->selected++;
8823 break;
8825 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8826 /* can't scroll any further */
8827 view->count = 0;
8828 break;
8830 ref_scroll_down(view, 1);
8831 break;
8832 case CTRL('d'):
8833 case 'd':
8834 nscroll /= 2;
8835 /* FALL THROUGH */
8836 case KEY_NPAGE:
8837 case CTRL('f'):
8838 case 'f':
8839 case ' ':
8840 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8841 /* can't scroll any further; move cursor down */
8842 if (s->selected < s->ndisplayed - 1)
8843 s->selected += MIN(nscroll,
8844 s->ndisplayed - s->selected - 1);
8845 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8846 s->selected += s->ndisplayed - s->selected - 1;
8847 view->count = 0;
8848 break;
8850 ref_scroll_down(view, nscroll);
8851 break;
8852 case CTRL('l'):
8853 view->count = 0;
8854 tog_free_refs();
8855 err = tog_load_refs(s->repo, s->sort_by_date);
8856 if (err)
8857 break;
8858 ref_view_free_refs(s);
8859 err = ref_view_load_refs(s);
8860 break;
8861 case KEY_RESIZE:
8862 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8863 s->selected = view->nlines - 2;
8864 break;
8865 default:
8866 view->count = 0;
8867 break;
8870 return err;
8873 __dead static void
8874 usage_ref(void)
8876 endwin();
8877 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8878 getprogname());
8879 exit(1);
8882 static const struct got_error *
8883 cmd_ref(int argc, char *argv[])
8885 const struct got_error *error;
8886 struct got_repository *repo = NULL;
8887 struct got_worktree *worktree = NULL;
8888 char *cwd = NULL, *repo_path = NULL;
8889 int ch;
8890 struct tog_view *view;
8891 int *pack_fds = NULL;
8893 while ((ch = getopt(argc, argv, "r:")) != -1) {
8894 switch (ch) {
8895 case 'r':
8896 repo_path = realpath(optarg, NULL);
8897 if (repo_path == NULL)
8898 return got_error_from_errno2("realpath",
8899 optarg);
8900 break;
8901 default:
8902 usage_ref();
8903 /* NOTREACHED */
8907 argc -= optind;
8908 argv += optind;
8910 if (argc > 1)
8911 usage_ref();
8913 error = got_repo_pack_fds_open(&pack_fds);
8914 if (error != NULL)
8915 goto done;
8917 if (repo_path == NULL) {
8918 cwd = getcwd(NULL, 0);
8919 if (cwd == NULL)
8920 return got_error_from_errno("getcwd");
8921 error = got_worktree_open(&worktree, cwd);
8922 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8923 goto done;
8924 if (worktree)
8925 repo_path =
8926 strdup(got_worktree_get_repo_path(worktree));
8927 else
8928 repo_path = strdup(cwd);
8929 if (repo_path == NULL) {
8930 error = got_error_from_errno("strdup");
8931 goto done;
8935 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8936 if (error != NULL)
8937 goto done;
8939 init_curses();
8941 error = apply_unveil(got_repo_get_path(repo), NULL);
8942 if (error)
8943 goto done;
8945 error = tog_load_refs(repo, 0);
8946 if (error)
8947 goto done;
8949 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8950 if (view == NULL) {
8951 error = got_error_from_errno("view_open");
8952 goto done;
8955 error = open_ref_view(view, repo);
8956 if (error)
8957 goto done;
8959 if (worktree) {
8960 /* Release work tree lock. */
8961 got_worktree_close(worktree);
8962 worktree = NULL;
8964 error = view_loop(view);
8965 done:
8966 free(repo_path);
8967 free(cwd);
8968 if (repo) {
8969 const struct got_error *close_err = got_repo_close(repo);
8970 if (close_err)
8971 error = close_err;
8973 if (pack_fds) {
8974 const struct got_error *pack_err =
8975 got_repo_pack_fds_close(pack_fds);
8976 if (error == NULL)
8977 error = pack_err;
8979 tog_free_refs();
8980 return error;
8983 static const struct got_error*
8984 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8985 const char *str)
8987 size_t len;
8989 if (win == NULL)
8990 win = stdscr;
8992 len = strlen(str);
8993 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8995 if (focus)
8996 wstandout(win);
8997 if (mvwprintw(win, y, x, "%s", str) == ERR)
8998 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8999 if (focus)
9000 wstandend(win);
9002 return NULL;
9005 static const struct got_error *
9006 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9008 off_t *p;
9010 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9011 if (p == NULL) {
9012 free(*line_offsets);
9013 *line_offsets = NULL;
9014 return got_error_from_errno("reallocarray");
9017 *line_offsets = p;
9018 (*line_offsets)[*nlines] = off;
9019 ++(*nlines);
9020 return NULL;
9023 static const struct got_error *
9024 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9026 *ret = 0;
9028 for (;n > 0; --n, ++km) {
9029 char *t0, *t, *k;
9030 size_t len = 1;
9032 if (km->keys == NULL)
9033 continue;
9035 t = t0 = strdup(km->keys);
9036 if (t0 == NULL)
9037 return got_error_from_errno("strdup");
9039 len += strlen(t);
9040 while ((k = strsep(&t, " ")) != NULL)
9041 len += strlen(k) > 1 ? 2 : 0;
9042 free(t0);
9043 *ret = MAX(*ret, len);
9046 return NULL;
9050 * Write keymap section headers, keys, and key info in km to f.
9051 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9052 * wrap control and symbolic keys in guillemets, else use <>.
9054 static const struct got_error *
9055 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9057 int n, len = width;
9059 if (km->keys) {
9060 static const char *u8_glyph[] = {
9061 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9062 "\xe2\x80\xba" /* U+203A (utf8 >) */
9064 char *t0, *t, *k;
9065 int cs, s, first = 1;
9067 cs = got_locale_is_utf8();
9069 t = t0 = strdup(km->keys);
9070 if (t0 == NULL)
9071 return got_error_from_errno("strdup");
9073 len = strlen(km->keys);
9074 while ((k = strsep(&t, " ")) != NULL) {
9075 s = strlen(k) > 1; /* control or symbolic key */
9076 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9077 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9078 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9079 if (n < 0) {
9080 free(t0);
9081 return got_error_from_errno("fprintf");
9083 first = 0;
9084 len += s ? 2 : 0;
9085 *off += n;
9087 free(t0);
9089 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9090 if (n < 0)
9091 return got_error_from_errno("fprintf");
9092 *off += n;
9094 return NULL;
9097 static const struct got_error *
9098 format_help(struct tog_help_view_state *s)
9100 const struct got_error *err = NULL;
9101 off_t off = 0;
9102 int i, max, n, show = s->all;
9103 static const struct tog_key_map km[] = {
9104 #define KEYMAP_(info, type) { NULL, (info), type }
9105 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9106 GENERATE_HELP
9107 #undef KEYMAP_
9108 #undef KEY_
9111 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9112 if (err)
9113 return err;
9115 n = nitems(km);
9116 err = max_key_str(&max, km, n);
9117 if (err)
9118 return err;
9120 for (i = 0; i < n; ++i) {
9121 if (km[i].keys == NULL) {
9122 show = s->all;
9123 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9124 km[i].type == s->type || s->all)
9125 show = 1;
9127 if (show) {
9128 err = format_help_line(&off, s->f, &km[i], max);
9129 if (err)
9130 return err;
9131 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9132 if (err)
9133 return err;
9136 fputc('\n', s->f);
9137 ++off;
9138 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9139 return err;
9142 static const struct got_error *
9143 create_help(struct tog_help_view_state *s)
9145 FILE *f;
9146 const struct got_error *err;
9148 free(s->line_offsets);
9149 s->line_offsets = NULL;
9150 s->nlines = 0;
9152 f = got_opentemp();
9153 if (f == NULL)
9154 return got_error_from_errno("got_opentemp");
9155 s->f = f;
9157 err = format_help(s);
9158 if (err)
9159 return err;
9161 if (s->f && fflush(s->f) != 0)
9162 return got_error_from_errno("fflush");
9164 return NULL;
9167 static const struct got_error *
9168 search_start_help_view(struct tog_view *view)
9170 view->state.help.matched_line = 0;
9171 return NULL;
9174 static void
9175 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9176 size_t *nlines, int **first, int **last, int **match, int **selected)
9178 struct tog_help_view_state *s = &view->state.help;
9180 *f = s->f;
9181 *nlines = s->nlines;
9182 *line_offsets = s->line_offsets;
9183 *match = &s->matched_line;
9184 *first = &s->first_displayed_line;
9185 *last = &s->last_displayed_line;
9186 *selected = &s->selected_line;
9189 static const struct got_error *
9190 show_help_view(struct tog_view *view)
9192 struct tog_help_view_state *s = &view->state.help;
9193 const struct got_error *err;
9194 regmatch_t *regmatch = &view->regmatch;
9195 wchar_t *wline;
9196 char *line;
9197 ssize_t linelen;
9198 size_t linesz = 0;
9199 int width, nprinted = 0, rc = 0;
9200 int eos = view->nlines;
9202 if (view_is_hsplit_top(view))
9203 --eos; /* account for border */
9205 s->lineno = 0;
9206 rewind(s->f);
9207 werase(view->window);
9209 if (view->gline > s->nlines - 1)
9210 view->gline = s->nlines - 1;
9212 err = win_draw_center(view->window, 0, 0, view->ncols,
9213 view_needs_focus_indication(view),
9214 "tog help (press q to return to tog)");
9215 if (err)
9216 return err;
9217 if (eos <= 1)
9218 return NULL;
9219 waddstr(view->window, "\n\n");
9220 eos -= 2;
9222 s->eof = 0;
9223 view->maxx = 0;
9224 line = NULL;
9225 while (eos > 0 && nprinted < eos) {
9226 attr_t attr = 0;
9228 linelen = getline(&line, &linesz, s->f);
9229 if (linelen == -1) {
9230 if (!feof(s->f)) {
9231 free(line);
9232 return got_ferror(s->f, GOT_ERR_IO);
9234 s->eof = 1;
9235 break;
9237 if (++s->lineno < s->first_displayed_line)
9238 continue;
9239 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9240 continue;
9241 if (s->lineno == view->hiline)
9242 attr = A_STANDOUT;
9244 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9245 view->x ? 1 : 0);
9246 if (err) {
9247 free(line);
9248 return err;
9250 view->maxx = MAX(view->maxx, width);
9251 free(wline);
9252 wline = NULL;
9254 if (attr)
9255 wattron(view->window, attr);
9256 if (s->first_displayed_line + nprinted == s->matched_line &&
9257 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9258 err = add_matched_line(&width, line, view->ncols - 1, 0,
9259 view->window, view->x, regmatch);
9260 if (err) {
9261 free(line);
9262 return err;
9264 } else {
9265 int skip;
9267 err = format_line(&wline, &width, &skip, line,
9268 view->x, view->ncols, 0, view->x ? 1 : 0);
9269 if (err) {
9270 free(line);
9271 return err;
9273 waddwstr(view->window, &wline[skip]);
9274 free(wline);
9275 wline = NULL;
9277 if (s->lineno == view->hiline) {
9278 while (width++ < view->ncols)
9279 waddch(view->window, ' ');
9280 } else {
9281 if (width < view->ncols)
9282 waddch(view->window, '\n');
9284 if (attr)
9285 wattroff(view->window, attr);
9286 if (++nprinted == 1)
9287 s->first_displayed_line = s->lineno;
9289 free(line);
9290 if (nprinted > 0)
9291 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9292 else
9293 s->last_displayed_line = s->first_displayed_line;
9295 view_border(view);
9297 if (s->eof) {
9298 rc = waddnstr(view->window,
9299 "See the tog(1) manual page for full documentation",
9300 view->ncols - 1);
9301 if (rc == ERR)
9302 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9303 } else {
9304 wmove(view->window, view->nlines - 1, 0);
9305 wclrtoeol(view->window);
9306 wstandout(view->window);
9307 rc = waddnstr(view->window, "scroll down for more...",
9308 view->ncols - 1);
9309 if (rc == ERR)
9310 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9311 if (getcurx(view->window) < view->ncols - 6) {
9312 rc = wprintw(view->window, "[%.0f%%]",
9313 100.00 * s->last_displayed_line / s->nlines);
9314 if (rc == ERR)
9315 return got_error_msg(GOT_ERR_IO, "wprintw");
9317 wstandend(view->window);
9320 return NULL;
9323 static const struct got_error *
9324 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9326 struct tog_help_view_state *s = &view->state.help;
9327 const struct got_error *err = NULL;
9328 char *line = NULL;
9329 ssize_t linelen;
9330 size_t linesz = 0;
9331 int eos, nscroll;
9333 eos = nscroll = view->nlines;
9334 if (view_is_hsplit_top(view))
9335 --eos; /* border */
9337 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9339 switch (ch) {
9340 case '0':
9341 case '$':
9342 case KEY_RIGHT:
9343 case 'l':
9344 case KEY_LEFT:
9345 case 'h':
9346 horizontal_scroll_input(view, ch);
9347 break;
9348 case 'g':
9349 case KEY_HOME:
9350 s->first_displayed_line = 1;
9351 view->count = 0;
9352 break;
9353 case 'G':
9354 case KEY_END:
9355 view->count = 0;
9356 if (s->eof)
9357 break;
9358 s->first_displayed_line = (s->nlines - eos) + 3;
9359 s->eof = 1;
9360 break;
9361 case 'k':
9362 case KEY_UP:
9363 if (s->first_displayed_line > 1)
9364 --s->first_displayed_line;
9365 else
9366 view->count = 0;
9367 break;
9368 case CTRL('u'):
9369 case 'u':
9370 nscroll /= 2;
9371 /* FALL THROUGH */
9372 case KEY_PPAGE:
9373 case CTRL('b'):
9374 case 'b':
9375 if (s->first_displayed_line == 1) {
9376 view->count = 0;
9377 break;
9379 while (--nscroll > 0 && s->first_displayed_line > 1)
9380 s->first_displayed_line--;
9381 break;
9382 case 'j':
9383 case KEY_DOWN:
9384 case CTRL('n'):
9385 if (!s->eof)
9386 ++s->first_displayed_line;
9387 else
9388 view->count = 0;
9389 break;
9390 case CTRL('d'):
9391 case 'd':
9392 nscroll /= 2;
9393 /* FALL THROUGH */
9394 case KEY_NPAGE:
9395 case CTRL('f'):
9396 case 'f':
9397 case ' ':
9398 if (s->eof) {
9399 view->count = 0;
9400 break;
9402 while (!s->eof && --nscroll > 0) {
9403 linelen = getline(&line, &linesz, s->f);
9404 s->first_displayed_line++;
9405 if (linelen == -1) {
9406 if (feof(s->f))
9407 s->eof = 1;
9408 else
9409 err = got_ferror(s->f, GOT_ERR_IO);
9410 break;
9413 free(line);
9414 break;
9415 default:
9416 view->count = 0;
9417 break;
9420 return err;
9423 static const struct got_error *
9424 close_help_view(struct tog_view *view)
9426 struct tog_help_view_state *s = &view->state.help;
9428 free(s->line_offsets);
9429 s->line_offsets = NULL;
9430 if (fclose(s->f) == EOF)
9431 return got_error_from_errno("fclose");
9433 return NULL;
9436 static const struct got_error *
9437 reset_help_view(struct tog_view *view)
9439 struct tog_help_view_state *s = &view->state.help;
9442 if (s->f && fclose(s->f) == EOF)
9443 return got_error_from_errno("fclose");
9445 wclear(view->window);
9446 view->count = 0;
9447 view->x = 0;
9448 s->all = !s->all;
9449 s->first_displayed_line = 1;
9450 s->last_displayed_line = view->nlines;
9451 s->matched_line = 0;
9453 return create_help(s);
9456 static const struct got_error *
9457 open_help_view(struct tog_view *view, struct tog_view *parent)
9459 const struct got_error *err = NULL;
9460 struct tog_help_view_state *s = &view->state.help;
9462 s->type = (enum tog_keymap_type)parent->type;
9463 s->first_displayed_line = 1;
9464 s->last_displayed_line = view->nlines;
9465 s->selected_line = 1;
9467 view->show = show_help_view;
9468 view->input = input_help_view;
9469 view->reset = reset_help_view;
9470 view->close = close_help_view;
9471 view->search_start = search_start_help_view;
9472 view->search_setup = search_setup_help_view;
9473 view->search_next = search_next_view_match;
9475 err = create_help(s);
9476 return err;
9479 static const struct got_error *
9480 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9481 enum tog_view_type request, int y, int x)
9483 const struct got_error *err = NULL;
9485 *new_view = NULL;
9487 switch (request) {
9488 case TOG_VIEW_DIFF:
9489 if (view->type == TOG_VIEW_LOG) {
9490 struct tog_log_view_state *s = &view->state.log;
9492 err = open_diff_view_for_commit(new_view, y, x,
9493 s->selected_entry->commit, s->selected_entry->id,
9494 view, s->repo);
9495 } else
9496 return got_error_msg(GOT_ERR_NOT_IMPL,
9497 "parent/child view pair not supported");
9498 break;
9499 case TOG_VIEW_BLAME:
9500 if (view->type == TOG_VIEW_TREE) {
9501 struct tog_tree_view_state *s = &view->state.tree;
9503 err = blame_tree_entry(new_view, y, x,
9504 s->selected_entry, &s->parents, s->commit_id,
9505 s->repo);
9506 } else
9507 return got_error_msg(GOT_ERR_NOT_IMPL,
9508 "parent/child view pair not supported");
9509 break;
9510 case TOG_VIEW_LOG:
9511 if (view->type == TOG_VIEW_BLAME)
9512 err = log_annotated_line(new_view, y, x,
9513 view->state.blame.repo, view->state.blame.id_to_log);
9514 else if (view->type == TOG_VIEW_TREE)
9515 err = log_selected_tree_entry(new_view, y, x,
9516 &view->state.tree);
9517 else if (view->type == TOG_VIEW_REF)
9518 err = log_ref_entry(new_view, y, x,
9519 view->state.ref.selected_entry,
9520 view->state.ref.repo);
9521 else
9522 return got_error_msg(GOT_ERR_NOT_IMPL,
9523 "parent/child view pair not supported");
9524 break;
9525 case TOG_VIEW_TREE:
9526 if (view->type == TOG_VIEW_LOG)
9527 err = browse_commit_tree(new_view, y, x,
9528 view->state.log.selected_entry,
9529 view->state.log.in_repo_path,
9530 view->state.log.head_ref_name,
9531 view->state.log.repo);
9532 else if (view->type == TOG_VIEW_REF)
9533 err = browse_ref_tree(new_view, y, x,
9534 view->state.ref.selected_entry,
9535 view->state.ref.repo);
9536 else
9537 return got_error_msg(GOT_ERR_NOT_IMPL,
9538 "parent/child view pair not supported");
9539 break;
9540 case TOG_VIEW_REF:
9541 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9542 if (*new_view == NULL)
9543 return got_error_from_errno("view_open");
9544 if (view->type == TOG_VIEW_LOG)
9545 err = open_ref_view(*new_view, view->state.log.repo);
9546 else if (view->type == TOG_VIEW_TREE)
9547 err = open_ref_view(*new_view, view->state.tree.repo);
9548 else
9549 err = got_error_msg(GOT_ERR_NOT_IMPL,
9550 "parent/child view pair not supported");
9551 if (err)
9552 view_close(*new_view);
9553 break;
9554 case TOG_VIEW_HELP:
9555 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9556 if (*new_view == NULL)
9557 return got_error_from_errno("view_open");
9558 err = open_help_view(*new_view, view);
9559 if (err)
9560 view_close(*new_view);
9561 break;
9562 default:
9563 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9566 return err;
9570 * If view was scrolled down to move the selected line into view when opening a
9571 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9573 static void
9574 offset_selection_up(struct tog_view *view)
9576 switch (view->type) {
9577 case TOG_VIEW_BLAME: {
9578 struct tog_blame_view_state *s = &view->state.blame;
9579 if (s->first_displayed_line == 1) {
9580 s->selected_line = MAX(s->selected_line - view->offset,
9581 1);
9582 break;
9584 if (s->first_displayed_line > view->offset)
9585 s->first_displayed_line -= view->offset;
9586 else
9587 s->first_displayed_line = 1;
9588 s->selected_line += view->offset;
9589 break;
9591 case TOG_VIEW_LOG:
9592 log_scroll_up(&view->state.log, view->offset);
9593 view->state.log.selected += view->offset;
9594 break;
9595 case TOG_VIEW_REF:
9596 ref_scroll_up(&view->state.ref, view->offset);
9597 view->state.ref.selected += view->offset;
9598 break;
9599 case TOG_VIEW_TREE:
9600 tree_scroll_up(&view->state.tree, view->offset);
9601 view->state.tree.selected += view->offset;
9602 break;
9603 default:
9604 break;
9607 view->offset = 0;
9611 * If the selected line is in the section of screen covered by the bottom split,
9612 * scroll down offset lines to move it into view and index its new position.
9614 static const struct got_error *
9615 offset_selection_down(struct tog_view *view)
9617 const struct got_error *err = NULL;
9618 const struct got_error *(*scrolld)(struct tog_view *, int);
9619 int *selected = NULL;
9620 int header, offset;
9622 switch (view->type) {
9623 case TOG_VIEW_BLAME: {
9624 struct tog_blame_view_state *s = &view->state.blame;
9625 header = 3;
9626 scrolld = NULL;
9627 if (s->selected_line > view->nlines - header) {
9628 offset = abs(view->nlines - s->selected_line - header);
9629 s->first_displayed_line += offset;
9630 s->selected_line -= offset;
9631 view->offset = offset;
9633 break;
9635 case TOG_VIEW_LOG: {
9636 struct tog_log_view_state *s = &view->state.log;
9637 scrolld = &log_scroll_down;
9638 header = view_is_parent_view(view) ? 3 : 2;
9639 selected = &s->selected;
9640 break;
9642 case TOG_VIEW_REF: {
9643 struct tog_ref_view_state *s = &view->state.ref;
9644 scrolld = &ref_scroll_down;
9645 header = 3;
9646 selected = &s->selected;
9647 break;
9649 case TOG_VIEW_TREE: {
9650 struct tog_tree_view_state *s = &view->state.tree;
9651 scrolld = &tree_scroll_down;
9652 header = 5;
9653 selected = &s->selected;
9654 break;
9656 default:
9657 selected = NULL;
9658 scrolld = NULL;
9659 header = 0;
9660 break;
9663 if (selected && *selected > view->nlines - header) {
9664 offset = abs(view->nlines - *selected - header);
9665 view->offset = offset;
9666 if (scrolld && offset) {
9667 err = scrolld(view, offset);
9668 *selected -= offset;
9672 return err;
9675 static void
9676 list_commands(FILE *fp)
9678 size_t i;
9680 fprintf(fp, "commands:");
9681 for (i = 0; i < nitems(tog_commands); i++) {
9682 const struct tog_cmd *cmd = &tog_commands[i];
9683 fprintf(fp, " %s", cmd->name);
9685 fputc('\n', fp);
9688 __dead static void
9689 usage(int hflag, int status)
9691 FILE *fp = (status == 0) ? stdout : stderr;
9693 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9694 getprogname());
9695 if (hflag) {
9696 fprintf(fp, "lazy usage: %s path\n", getprogname());
9697 list_commands(fp);
9699 exit(status);
9702 static char **
9703 make_argv(int argc, ...)
9705 va_list ap;
9706 char **argv;
9707 int i;
9709 va_start(ap, argc);
9711 argv = calloc(argc, sizeof(char *));
9712 if (argv == NULL)
9713 err(1, "calloc");
9714 for (i = 0; i < argc; i++) {
9715 argv[i] = strdup(va_arg(ap, char *));
9716 if (argv[i] == NULL)
9717 err(1, "strdup");
9720 va_end(ap);
9721 return argv;
9725 * Try to convert 'tog path' into a 'tog log path' command.
9726 * The user could simply have mistyped the command rather than knowingly
9727 * provided a path. So check whether argv[0] can in fact be resolved
9728 * to a path in the HEAD commit and print a special error if not.
9729 * This hack is for mpi@ <3
9731 static const struct got_error *
9732 tog_log_with_path(int argc, char *argv[])
9734 const struct got_error *error = NULL, *close_err;
9735 const struct tog_cmd *cmd = NULL;
9736 struct got_repository *repo = NULL;
9737 struct got_worktree *worktree = NULL;
9738 struct got_object_id *commit_id = NULL, *id = NULL;
9739 struct got_commit_object *commit = NULL;
9740 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9741 char *commit_id_str = NULL, **cmd_argv = NULL;
9742 int *pack_fds = NULL;
9744 cwd = getcwd(NULL, 0);
9745 if (cwd == NULL)
9746 return got_error_from_errno("getcwd");
9748 error = got_repo_pack_fds_open(&pack_fds);
9749 if (error != NULL)
9750 goto done;
9752 error = got_worktree_open(&worktree, cwd);
9753 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9754 goto done;
9756 if (worktree)
9757 repo_path = strdup(got_worktree_get_repo_path(worktree));
9758 else
9759 repo_path = strdup(cwd);
9760 if (repo_path == NULL) {
9761 error = got_error_from_errno("strdup");
9762 goto done;
9765 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9766 if (error != NULL)
9767 goto done;
9769 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9770 repo, worktree);
9771 if (error)
9772 goto done;
9774 error = tog_load_refs(repo, 0);
9775 if (error)
9776 goto done;
9777 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9778 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9779 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9780 if (error)
9781 goto done;
9783 if (worktree) {
9784 got_worktree_close(worktree);
9785 worktree = NULL;
9788 error = got_object_open_as_commit(&commit, repo, commit_id);
9789 if (error)
9790 goto done;
9792 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9793 if (error) {
9794 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9795 goto done;
9796 fprintf(stderr, "%s: '%s' is no known command or path\n",
9797 getprogname(), argv[0]);
9798 usage(1, 1);
9799 /* not reached */
9802 error = got_object_id_str(&commit_id_str, commit_id);
9803 if (error)
9804 goto done;
9806 cmd = &tog_commands[0]; /* log */
9807 argc = 4;
9808 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9809 error = cmd->cmd_main(argc, cmd_argv);
9810 done:
9811 if (repo) {
9812 close_err = got_repo_close(repo);
9813 if (error == NULL)
9814 error = close_err;
9816 if (commit)
9817 got_object_commit_close(commit);
9818 if (worktree)
9819 got_worktree_close(worktree);
9820 if (pack_fds) {
9821 const struct got_error *pack_err =
9822 got_repo_pack_fds_close(pack_fds);
9823 if (error == NULL)
9824 error = pack_err;
9826 free(id);
9827 free(commit_id_str);
9828 free(commit_id);
9829 free(cwd);
9830 free(repo_path);
9831 free(in_repo_path);
9832 if (cmd_argv) {
9833 int i;
9834 for (i = 0; i < argc; i++)
9835 free(cmd_argv[i]);
9836 free(cmd_argv);
9838 tog_free_refs();
9839 return error;
9842 int
9843 main(int argc, char *argv[])
9845 const struct got_error *io_err, *error = NULL;
9846 const struct tog_cmd *cmd = NULL;
9847 int ch, hflag = 0, Vflag = 0;
9848 char **cmd_argv = NULL;
9849 static const struct option longopts[] = {
9850 { "version", no_argument, NULL, 'V' },
9851 { NULL, 0, NULL, 0}
9853 char *diff_algo_str = NULL;
9854 const char *test_script_path;
9856 setlocale(LC_CTYPE, "");
9859 * Test mode init must happen before pledge() because "tty" will
9860 * not allow TTY-related ioctls to occur via regular files.
9862 test_script_path = getenv("TOG_TEST_SCRIPT");
9863 if (test_script_path != NULL) {
9864 error = init_mock_term(test_script_path);
9865 if (error) {
9866 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9867 return 1;
9869 } else if (!isatty(STDIN_FILENO))
9870 errx(1, "standard input is not a tty");
9872 #if !defined(PROFILE)
9873 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9874 NULL) == -1)
9875 err(1, "pledge");
9876 #endif
9878 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9879 switch (ch) {
9880 case 'h':
9881 hflag = 1;
9882 break;
9883 case 'V':
9884 Vflag = 1;
9885 break;
9886 default:
9887 usage(hflag, 1);
9888 /* NOTREACHED */
9892 argc -= optind;
9893 argv += optind;
9894 optind = 1;
9895 optreset = 1;
9897 if (Vflag) {
9898 got_version_print_str();
9899 return 0;
9902 if (argc == 0) {
9903 if (hflag)
9904 usage(hflag, 0);
9905 /* Build an argument vector which runs a default command. */
9906 cmd = &tog_commands[0];
9907 argc = 1;
9908 cmd_argv = make_argv(argc, cmd->name);
9909 } else {
9910 size_t i;
9912 /* Did the user specify a command? */
9913 for (i = 0; i < nitems(tog_commands); i++) {
9914 if (strncmp(tog_commands[i].name, argv[0],
9915 strlen(argv[0])) == 0) {
9916 cmd = &tog_commands[i];
9917 break;
9922 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9923 if (diff_algo_str) {
9924 if (strcasecmp(diff_algo_str, "patience") == 0)
9925 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9926 if (strcasecmp(diff_algo_str, "myers") == 0)
9927 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9930 if (cmd == NULL) {
9931 if (argc != 1)
9932 usage(0, 1);
9933 /* No command specified; try log with a path */
9934 error = tog_log_with_path(argc, argv);
9935 } else {
9936 if (hflag)
9937 cmd->cmd_usage();
9938 else
9939 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9942 if (using_mock_io) {
9943 io_err = tog_io_close();
9944 if (error == NULL)
9945 error = io_err;
9947 endwin();
9948 if (cmd_argv) {
9949 int i;
9950 for (i = 0; i < argc; i++)
9951 free(cmd_argv[i]);
9952 free(cmd_argv);
9955 if (error && error->code != GOT_ERR_CANCELLED &&
9956 error->code != GOT_ERR_EOF &&
9957 error->code != GOT_ERR_PRIVSEP_EXIT &&
9958 error->code != GOT_ERR_PRIVSEP_PIPE &&
9959 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9960 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9961 return 0;