Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "got_compat.h"
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 #include <sys/ioctl.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #if defined(__FreeBSD__) || defined(__APPLE__)
26 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
27 #endif
28 #include <curses.h>
29 #include <panel.h>
30 #include <locale.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <err.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <wchar.h>
41 #include <time.h>
42 #include <pthread.h>
43 #include <libgen.h>
44 #include <regex.h>
45 #include <sched.h>
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
159 static const struct got_error *
160 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
161 struct got_reference* re2)
163 const char *name1 = got_ref_get_name(re1);
164 const char *name2 = got_ref_get_name(re2);
165 int isbackup1, isbackup2;
167 /* Sort backup refs towards the bottom of the list. */
168 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
169 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
170 if (!isbackup1 && isbackup2) {
171 *cmp = -1;
172 return NULL;
173 } else if (isbackup1 && !isbackup2) {
174 *cmp = 1;
175 return NULL;
178 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
179 return NULL;
182 static const struct got_error *
183 tog_load_refs(struct got_repository *repo, int sort_by_date)
185 const struct got_error *err;
187 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
188 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
189 repo);
190 if (err)
191 return err;
193 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
194 repo);
197 static void
198 tog_free_refs(void)
200 if (tog_refs_idmap) {
201 got_reflist_object_id_map_free(tog_refs_idmap);
202 tog_refs_idmap = NULL;
204 got_ref_list_free(&tog_refs);
207 static const struct got_error *
208 add_color(struct tog_colors *colors, const char *pattern,
209 int idx, short color)
211 const struct got_error *err = NULL;
212 struct tog_color *tc;
213 int regerr = 0;
215 if (idx < 1 || idx > COLOR_PAIRS - 1)
216 return NULL;
218 init_pair(idx, color, -1);
220 tc = calloc(1, sizeof(*tc));
221 if (tc == NULL)
222 return got_error_from_errno("calloc");
223 regerr = regcomp(&tc->regex, pattern,
224 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
225 if (regerr) {
226 static char regerr_msg[512];
227 static char err_msg[512];
228 regerror(regerr, &tc->regex, regerr_msg,
229 sizeof(regerr_msg));
230 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
231 regerr_msg);
232 err = got_error_msg(GOT_ERR_REGEX, err_msg);
233 free(tc);
234 return err;
236 tc->colorpair = idx;
237 STAILQ_INSERT_HEAD(colors, tc, entry);
238 return NULL;
241 static void
242 free_colors(struct tog_colors *colors)
244 struct tog_color *tc;
246 while (!STAILQ_EMPTY(colors)) {
247 tc = STAILQ_FIRST(colors);
248 STAILQ_REMOVE_HEAD(colors, entry);
249 regfree(&tc->regex);
250 free(tc);
254 static struct tog_color *
255 get_color(struct tog_colors *colors, int colorpair)
257 struct tog_color *tc = NULL;
259 STAILQ_FOREACH(tc, colors, entry) {
260 if (tc->colorpair == colorpair)
261 return tc;
264 return NULL;
267 static int
268 default_color_value(const char *envvar)
270 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
271 return COLOR_MAGENTA;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
273 return COLOR_CYAN;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
275 return COLOR_YELLOW;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
277 return COLOR_GREEN;
278 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
279 return COLOR_MAGENTA;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
283 return COLOR_CYAN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
285 return COLOR_GREEN;
286 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
291 return COLOR_YELLOW;
292 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
295 return COLOR_MAGENTA;
296 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
299 return COLOR_CYAN;
301 return -1;
304 static int
305 get_color_value(const char *envvar)
307 const char *val = getenv(envvar);
309 if (val == NULL)
310 return default_color_value(envvar);
312 if (strcasecmp(val, "black") == 0)
313 return COLOR_BLACK;
314 if (strcasecmp(val, "red") == 0)
315 return COLOR_RED;
316 if (strcasecmp(val, "green") == 0)
317 return COLOR_GREEN;
318 if (strcasecmp(val, "yellow") == 0)
319 return COLOR_YELLOW;
320 if (strcasecmp(val, "blue") == 0)
321 return COLOR_BLUE;
322 if (strcasecmp(val, "magenta") == 0)
323 return COLOR_MAGENTA;
324 if (strcasecmp(val, "cyan") == 0)
325 return COLOR_CYAN;
326 if (strcasecmp(val, "white") == 0)
327 return COLOR_WHITE;
328 if (strcasecmp(val, "default") == 0)
329 return -1;
331 return default_color_value(envvar);
334 struct tog_diff_view_state {
335 struct got_object_id *id1, *id2;
336 const char *label1, *label2;
337 FILE *f, *f1, *f2;
338 int fd1, fd2;
339 int lineno;
340 int first_displayed_line;
341 int last_displayed_line;
342 int eof;
343 int diff_context;
344 int ignore_whitespace;
345 int force_text_diff;
346 struct got_repository *repo;
347 struct got_diff_line *lines;
348 size_t nlines;
349 int matched_line;
350 int selected_line;
352 /* passed from log or blame view; may be NULL */
353 struct tog_view *parent_view;
354 };
356 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
357 static volatile sig_atomic_t tog_thread_error;
359 struct tog_log_thread_args {
360 pthread_cond_t need_commits;
361 pthread_cond_t commit_loaded;
362 int commits_needed;
363 int load_all;
364 struct got_commit_graph *graph;
365 struct commit_queue *real_commits;
366 const char *in_repo_path;
367 struct got_object_id *start_id;
368 struct got_repository *repo;
369 int *pack_fds;
370 int log_complete;
371 sig_atomic_t *quit;
372 struct commit_queue_entry **first_displayed_entry;
373 struct commit_queue_entry **selected_entry;
374 int *searching;
375 int *search_next_done;
376 regex_t *regex;
377 int *limiting;
378 int limit_match;
379 regex_t *limit_regex;
380 struct commit_queue *limit_commits;
381 };
383 struct tog_log_view_state {
384 struct commit_queue *commits;
385 struct commit_queue_entry *first_displayed_entry;
386 struct commit_queue_entry *last_displayed_entry;
387 struct commit_queue_entry *selected_entry;
388 struct commit_queue real_commits;
389 int selected;
390 char *in_repo_path;
391 char *head_ref_name;
392 int log_branches;
393 struct got_repository *repo;
394 struct got_object_id *start_id;
395 sig_atomic_t quit;
396 pthread_t thread;
397 struct tog_log_thread_args thread_args;
398 struct commit_queue_entry *matched_entry;
399 struct commit_queue_entry *search_entry;
400 struct tog_colors colors;
401 int use_committer;
402 int limit_view;
403 regex_t limit_regex;
404 struct commit_queue limit_commits;
405 };
407 #define TOG_COLOR_DIFF_MINUS 1
408 #define TOG_COLOR_DIFF_PLUS 2
409 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
410 #define TOG_COLOR_DIFF_META 4
411 #define TOG_COLOR_TREE_SUBMODULE 5
412 #define TOG_COLOR_TREE_SYMLINK 6
413 #define TOG_COLOR_TREE_DIRECTORY 7
414 #define TOG_COLOR_TREE_EXECUTABLE 8
415 #define TOG_COLOR_COMMIT 9
416 #define TOG_COLOR_AUTHOR 10
417 #define TOG_COLOR_DATE 11
418 #define TOG_COLOR_REFS_HEADS 12
419 #define TOG_COLOR_REFS_TAGS 13
420 #define TOG_COLOR_REFS_REMOTES 14
421 #define TOG_COLOR_REFS_BACKUP 15
423 struct tog_blame_cb_args {
424 struct tog_blame_line *lines; /* one per line */
425 int nlines;
427 struct tog_view *view;
428 struct got_object_id *commit_id;
429 int *quit;
430 };
432 struct tog_blame_thread_args {
433 const char *path;
434 struct got_repository *repo;
435 struct tog_blame_cb_args *cb_args;
436 int *complete;
437 got_cancel_cb cancel_cb;
438 void *cancel_arg;
439 pthread_cond_t blame_complete;
440 };
442 struct tog_blame {
443 FILE *f;
444 off_t filesize;
445 struct tog_blame_line *lines;
446 int nlines;
447 off_t *line_offsets;
448 pthread_t thread;
449 struct tog_blame_thread_args thread_args;
450 struct tog_blame_cb_args cb_args;
451 const char *path;
452 int *pack_fds;
453 };
455 struct tog_blame_view_state {
456 int first_displayed_line;
457 int last_displayed_line;
458 int selected_line;
459 int last_diffed_line;
460 int blame_complete;
461 int eof;
462 int done;
463 struct got_object_id_queue blamed_commits;
464 struct got_object_qid *blamed_commit;
465 char *path;
466 struct got_repository *repo;
467 struct got_object_id *commit_id;
468 struct got_object_id *id_to_log;
469 struct tog_blame blame;
470 int matched_line;
471 struct tog_colors colors;
472 };
474 struct tog_parent_tree {
475 TAILQ_ENTRY(tog_parent_tree) entry;
476 struct got_tree_object *tree;
477 struct got_tree_entry *first_displayed_entry;
478 struct got_tree_entry *selected_entry;
479 int selected;
480 };
482 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
484 struct tog_tree_view_state {
485 char *tree_label;
486 struct got_object_id *commit_id;/* commit which this tree belongs to */
487 struct got_tree_object *root; /* the commit's root tree entry */
488 struct got_tree_object *tree; /* currently displayed (sub-)tree */
489 struct got_tree_entry *first_displayed_entry;
490 struct got_tree_entry *last_displayed_entry;
491 struct got_tree_entry *selected_entry;
492 int ndisplayed, selected, show_ids;
493 struct tog_parent_trees parents; /* parent trees of current sub-tree */
494 char *head_ref_name;
495 struct got_repository *repo;
496 struct got_tree_entry *matched_entry;
497 struct tog_colors colors;
498 };
500 struct tog_reflist_entry {
501 TAILQ_ENTRY(tog_reflist_entry) entry;
502 struct got_reference *ref;
503 int idx;
504 };
506 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
508 struct tog_ref_view_state {
509 struct tog_reflist_head refs;
510 struct tog_reflist_entry *first_displayed_entry;
511 struct tog_reflist_entry *last_displayed_entry;
512 struct tog_reflist_entry *selected_entry;
513 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
514 struct got_repository *repo;
515 struct tog_reflist_entry *matched_entry;
516 struct tog_colors colors;
517 };
519 struct tog_help_view_state {
520 FILE *f;
521 off_t *line_offsets;
522 size_t nlines;
523 int lineno;
524 int first_displayed_line;
525 int last_displayed_line;
526 int eof;
527 int matched_line;
528 int selected_line;
529 int all;
530 enum tog_keymap_type type;
531 };
533 #define GENERATE_HELP \
534 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
535 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
536 KEY_("k C-p Up", "Move cursor or page up one line"), \
537 KEY_("j C-n Down", "Move cursor or page down one line"), \
538 KEY_("C-b b PgUp", "Scroll the view up one page"), \
539 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
540 KEY_("C-u u", "Scroll the view up one half page"), \
541 KEY_("C-d d", "Scroll the view down one half page"), \
542 KEY_("g", "Go to line N (default: first line)"), \
543 KEY_("Home =", "Go to the first line"), \
544 KEY_("G", "Go to line N (default: last line)"), \
545 KEY_("End *", "Go to the last line"), \
546 KEY_("l Right", "Scroll the view right"), \
547 KEY_("h Left", "Scroll the view left"), \
548 KEY_("$", "Scroll view to the rightmost position"), \
549 KEY_("0", "Scroll view to the leftmost position"), \
550 KEY_("-", "Decrease size of the focussed split"), \
551 KEY_("+", "Increase size of the focussed split"), \
552 KEY_("Tab", "Switch focus between views"), \
553 KEY_("F", "Toggle fullscreen mode"), \
554 KEY_("S", "Switch split-screen layout"), \
555 KEY_("/", "Open prompt to enter search term"), \
556 KEY_("n", "Find next line/token matching the current search term"), \
557 KEY_("N", "Find previous line/token matching the current search term"),\
558 KEY_("q", "Quit the focussed view; Quit help screen"), \
559 KEY_("Q", "Quit tog"), \
561 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
562 KEY_("< ,", "Move cursor up one commit"), \
563 KEY_("> .", "Move cursor down one commit"), \
564 KEY_("Enter", "Open diff view of the selected commit"), \
565 KEY_("B", "Reload the log view and toggle display of merged commits"), \
566 KEY_("R", "Open ref view of all repository references"), \
567 KEY_("T", "Display tree view of the repository from the selected" \
568 " commit"), \
569 KEY_("@", "Toggle between displaying author and committer name"), \
570 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
571 KEY_("C-g Backspace", "Cancel current search or log operation"), \
572 KEY_("C-l", "Reload the log view with new commits in the repository"), \
574 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
575 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
576 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
577 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
578 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
579 " data"), \
580 KEY_("(", "Go to the previous file in the diff"), \
581 KEY_(")", "Go to the next file in the diff"), \
582 KEY_("{", "Go to the previous hunk in the diff"), \
583 KEY_("}", "Go to the next hunk in the diff"), \
584 KEY_("[", "Decrease the number of context lines"), \
585 KEY_("]", "Increase the number of context lines"), \
586 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
588 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
589 KEY_("Enter", "Display diff view of the selected line's commit"), \
590 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
591 KEY_("L", "Open log view for the currently selected annotated line"), \
592 KEY_("C", "Reload view with the previously blamed commit"), \
593 KEY_("c", "Reload view with the version of the file found in the" \
594 " selected line's commit"), \
595 KEY_("p", "Reload view with the version of the file found in the" \
596 " selected line's parent commit"), \
598 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
599 KEY_("Enter", "Enter selected directory or open blame view of the" \
600 " selected file"), \
601 KEY_("L", "Open log view for the selected entry"), \
602 KEY_("R", "Open ref view of all repository references"), \
603 KEY_("i", "Show object IDs for all tree entries"), \
604 KEY_("Backspace", "Return to the parent directory"), \
606 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
607 KEY_("Enter", "Display log view of the selected reference"), \
608 KEY_("T", "Display tree view of the selected reference"), \
609 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
610 KEY_("m", "Toggle display of last modified date for each reference"), \
611 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
612 KEY_("C-l", "Reload view with all repository references")
614 struct tog_key_map {
615 const char *keys;
616 const char *info;
617 enum tog_keymap_type type;
618 };
620 /* curses io for tog regress */
621 struct tog_io {
622 FILE *cin;
623 FILE *cout;
624 FILE *f;
625 FILE *sdump;
626 int wait_for_ui;
627 } tog_io;
628 static int using_mock_io;
630 #define TOG_KEY_SCRDUMP SHRT_MIN
632 /*
633 * We implement two types of views: parent views and child views.
635 * The 'Tab' key switches focus between a parent view and its child view.
636 * Child views are shown side-by-side to their parent view, provided
637 * there is enough screen estate.
639 * When a new view is opened from within a parent view, this new view
640 * becomes a child view of the parent view, replacing any existing child.
642 * When a new view is opened from within a child view, this new view
643 * becomes a parent view which will obscure the views below until the
644 * user quits the new parent view by typing 'q'.
646 * This list of views contains parent views only.
647 * Child views are only pointed to by their parent view.
648 */
649 TAILQ_HEAD(tog_view_list_head, tog_view);
651 struct tog_view {
652 TAILQ_ENTRY(tog_view) entry;
653 WINDOW *window;
654 PANEL *panel;
655 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
656 int resized_y, resized_x; /* begin_y/x based on user resizing */
657 int maxx, x; /* max column and current start column */
658 int lines, cols; /* copies of LINES and COLS */
659 int nscrolled, offset; /* lines scrolled and hsplit line offset */
660 int gline, hiline; /* navigate to and highlight this nG line */
661 int ch, count; /* current keymap and count prefix */
662 int resized; /* set when in a resize event */
663 int focussed; /* Only set on one parent or child view at a time. */
664 int dying;
665 struct tog_view *parent;
666 struct tog_view *child;
668 /*
669 * This flag is initially set on parent views when a new child view
670 * is created. It gets toggled when the 'Tab' key switches focus
671 * between parent and child.
672 * The flag indicates whether focus should be passed on to our child
673 * view if this parent view gets picked for focus after another parent
674 * view was closed. This prevents child views from losing focus in such
675 * situations.
676 */
677 int focus_child;
679 enum tog_view_mode mode;
680 /* type-specific state */
681 enum tog_view_type type;
682 union {
683 struct tog_diff_view_state diff;
684 struct tog_log_view_state log;
685 struct tog_blame_view_state blame;
686 struct tog_tree_view_state tree;
687 struct tog_ref_view_state ref;
688 struct tog_help_view_state help;
689 } state;
691 const struct got_error *(*show)(struct tog_view *);
692 const struct got_error *(*input)(struct tog_view **,
693 struct tog_view *, int);
694 const struct got_error *(*reset)(struct tog_view *);
695 const struct got_error *(*resize)(struct tog_view *, int);
696 const struct got_error *(*close)(struct tog_view *);
698 const struct got_error *(*search_start)(struct tog_view *);
699 const struct got_error *(*search_next)(struct tog_view *);
700 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
701 int **, int **, int **, int **);
702 int search_started;
703 int searching;
704 #define TOG_SEARCH_FORWARD 1
705 #define TOG_SEARCH_BACKWARD 2
706 int search_next_done;
707 #define TOG_SEARCH_HAVE_MORE 1
708 #define TOG_SEARCH_NO_MORE 2
709 #define TOG_SEARCH_HAVE_NONE 3
710 regex_t regex;
711 regmatch_t regmatch;
712 const char *action;
713 };
715 static const struct got_error *open_diff_view(struct tog_view *,
716 struct got_object_id *, struct got_object_id *,
717 const char *, const char *, int, int, int, struct tog_view *,
718 struct got_repository *);
719 static const struct got_error *show_diff_view(struct tog_view *);
720 static const struct got_error *input_diff_view(struct tog_view **,
721 struct tog_view *, int);
722 static const struct got_error *reset_diff_view(struct tog_view *);
723 static const struct got_error* close_diff_view(struct tog_view *);
724 static const struct got_error *search_start_diff_view(struct tog_view *);
725 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
726 size_t *, int **, int **, int **, int **);
727 static const struct got_error *search_next_view_match(struct tog_view *);
729 static const struct got_error *open_log_view(struct tog_view *,
730 struct got_object_id *, struct got_repository *,
731 const char *, const char *, int);
732 static const struct got_error * show_log_view(struct tog_view *);
733 static const struct got_error *input_log_view(struct tog_view **,
734 struct tog_view *, int);
735 static const struct got_error *resize_log_view(struct tog_view *, int);
736 static const struct got_error *close_log_view(struct tog_view *);
737 static const struct got_error *search_start_log_view(struct tog_view *);
738 static const struct got_error *search_next_log_view(struct tog_view *);
740 static const struct got_error *open_blame_view(struct tog_view *, char *,
741 struct got_object_id *, struct got_repository *);
742 static const struct got_error *show_blame_view(struct tog_view *);
743 static const struct got_error *input_blame_view(struct tog_view **,
744 struct tog_view *, int);
745 static const struct got_error *reset_blame_view(struct tog_view *);
746 static const struct got_error *close_blame_view(struct tog_view *);
747 static const struct got_error *search_start_blame_view(struct tog_view *);
748 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
749 size_t *, int **, int **, int **, int **);
751 static const struct got_error *open_tree_view(struct tog_view *,
752 struct got_object_id *, const char *, struct got_repository *);
753 static const struct got_error *show_tree_view(struct tog_view *);
754 static const struct got_error *input_tree_view(struct tog_view **,
755 struct tog_view *, int);
756 static const struct got_error *close_tree_view(struct tog_view *);
757 static const struct got_error *search_start_tree_view(struct tog_view *);
758 static const struct got_error *search_next_tree_view(struct tog_view *);
760 static const struct got_error *open_ref_view(struct tog_view *,
761 struct got_repository *);
762 static const struct got_error *show_ref_view(struct tog_view *);
763 static const struct got_error *input_ref_view(struct tog_view **,
764 struct tog_view *, int);
765 static const struct got_error *close_ref_view(struct tog_view *);
766 static const struct got_error *search_start_ref_view(struct tog_view *);
767 static const struct got_error *search_next_ref_view(struct tog_view *);
769 static const struct got_error *open_help_view(struct tog_view *,
770 struct tog_view *);
771 static const struct got_error *show_help_view(struct tog_view *);
772 static const struct got_error *input_help_view(struct tog_view **,
773 struct tog_view *, int);
774 static const struct got_error *reset_help_view(struct tog_view *);
775 static const struct got_error* close_help_view(struct tog_view *);
776 static const struct got_error *search_start_help_view(struct tog_view *);
777 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
778 size_t *, int **, int **, int **, int **);
780 static volatile sig_atomic_t tog_sigwinch_received;
781 static volatile sig_atomic_t tog_sigpipe_received;
782 static volatile sig_atomic_t tog_sigcont_received;
783 static volatile sig_atomic_t tog_sigint_received;
784 static volatile sig_atomic_t tog_sigterm_received;
786 static void
787 tog_sigwinch(int signo)
789 tog_sigwinch_received = 1;
792 static void
793 tog_sigpipe(int signo)
795 tog_sigpipe_received = 1;
798 static void
799 tog_sigcont(int signo)
801 tog_sigcont_received = 1;
804 static void
805 tog_sigint(int signo)
807 tog_sigint_received = 1;
810 static void
811 tog_sigterm(int signo)
813 tog_sigterm_received = 1;
816 static int
817 tog_fatal_signal_received(void)
819 return (tog_sigpipe_received ||
820 tog_sigint_received || tog_sigterm_received);
823 static const struct got_error *
824 view_close(struct tog_view *view)
826 const struct got_error *err = NULL, *child_err = NULL;
828 if (view->child) {
829 child_err = view_close(view->child);
830 view->child = NULL;
832 if (view->close)
833 err = view->close(view);
834 if (view->panel)
835 del_panel(view->panel);
836 if (view->window)
837 delwin(view->window);
838 free(view);
839 return err ? err : child_err;
842 static struct tog_view *
843 view_open(int nlines, int ncols, int begin_y, int begin_x,
844 enum tog_view_type type)
846 struct tog_view *view = calloc(1, sizeof(*view));
848 if (view == NULL)
849 return NULL;
851 view->type = type;
852 view->lines = LINES;
853 view->cols = COLS;
854 view->nlines = nlines ? nlines : LINES - begin_y;
855 view->ncols = ncols ? ncols : COLS - begin_x;
856 view->begin_y = begin_y;
857 view->begin_x = begin_x;
858 view->window = newwin(nlines, ncols, begin_y, begin_x);
859 if (view->window == NULL) {
860 view_close(view);
861 return NULL;
863 view->panel = new_panel(view->window);
864 if (view->panel == NULL ||
865 set_panel_userptr(view->panel, view) != OK) {
866 view_close(view);
867 return NULL;
870 keypad(view->window, TRUE);
871 return view;
874 static int
875 view_split_begin_x(int begin_x)
877 if (begin_x > 0 || COLS < 120)
878 return 0;
879 return (COLS - MAX(COLS / 2, 80));
882 /* XXX Stub till we decide what to do. */
883 static int
884 view_split_begin_y(int lines)
886 return lines * HSPLIT_SCALE;
889 static const struct got_error *view_resize(struct tog_view *);
891 static const struct got_error *
892 view_splitscreen(struct tog_view *view)
894 const struct got_error *err = NULL;
896 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
897 if (view->resized_y && view->resized_y < view->lines)
898 view->begin_y = view->resized_y;
899 else
900 view->begin_y = view_split_begin_y(view->nlines);
901 view->begin_x = 0;
902 } else if (!view->resized) {
903 if (view->resized_x && view->resized_x < view->cols - 1 &&
904 view->cols > 119)
905 view->begin_x = view->resized_x;
906 else
907 view->begin_x = view_split_begin_x(0);
908 view->begin_y = 0;
910 view->nlines = LINES - view->begin_y;
911 view->ncols = COLS - view->begin_x;
912 view->lines = LINES;
913 view->cols = COLS;
914 err = view_resize(view);
915 if (err)
916 return err;
918 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
919 view->parent->nlines = view->begin_y;
921 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
922 return got_error_from_errno("mvwin");
924 return NULL;
927 static const struct got_error *
928 view_fullscreen(struct tog_view *view)
930 const struct got_error *err = NULL;
932 view->begin_x = 0;
933 view->begin_y = view->resized ? view->begin_y : 0;
934 view->nlines = view->resized ? view->nlines : LINES;
935 view->ncols = COLS;
936 view->lines = LINES;
937 view->cols = COLS;
938 err = view_resize(view);
939 if (err)
940 return err;
942 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
943 return got_error_from_errno("mvwin");
945 return NULL;
948 static int
949 view_is_parent_view(struct tog_view *view)
951 return view->parent == NULL;
954 static int
955 view_is_splitscreen(struct tog_view *view)
957 return view->begin_x > 0 || view->begin_y > 0;
960 static int
961 view_is_fullscreen(struct tog_view *view)
963 return view->nlines == LINES && view->ncols == COLS;
966 static int
967 view_is_hsplit_top(struct tog_view *view)
969 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
970 view_is_splitscreen(view->child);
973 static void
974 view_border(struct tog_view *view)
976 PANEL *panel;
977 const struct tog_view *view_above;
979 if (view->parent)
980 return view_border(view->parent);
982 panel = panel_above(view->panel);
983 if (panel == NULL)
984 return;
986 view_above = panel_userptr(panel);
987 if (view->mode == TOG_VIEW_SPLIT_HRZN)
988 mvwhline(view->window, view_above->begin_y - 1,
989 view->begin_x, ACS_HLINE, view->ncols);
990 else
991 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
992 ACS_VLINE, view->nlines);
995 static const struct got_error *view_init_hsplit(struct tog_view *, int);
996 static const struct got_error *request_log_commits(struct tog_view *);
997 static const struct got_error *offset_selection_down(struct tog_view *);
998 static void offset_selection_up(struct tog_view *);
999 static void view_get_split(struct tog_view *, int *, int *);
1001 static const struct got_error *
1002 view_resize(struct tog_view *view)
1004 const struct got_error *err = NULL;
1005 int dif, nlines, ncols;
1007 dif = LINES - view->lines; /* line difference */
1009 if (view->lines > LINES)
1010 nlines = view->nlines - (view->lines - LINES);
1011 else
1012 nlines = view->nlines + (LINES - view->lines);
1013 if (view->cols > COLS)
1014 ncols = view->ncols - (view->cols - COLS);
1015 else
1016 ncols = view->ncols + (COLS - view->cols);
1018 if (view->child) {
1019 int hs = view->child->begin_y;
1021 if (!view_is_fullscreen(view))
1022 view->child->begin_x = view_split_begin_x(view->begin_x);
1023 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1024 view->child->begin_x == 0) {
1025 ncols = COLS;
1027 view_fullscreen(view->child);
1028 if (view->child->focussed)
1029 show_panel(view->child->panel);
1030 else
1031 show_panel(view->panel);
1032 } else {
1033 ncols = view->child->begin_x;
1035 view_splitscreen(view->child);
1036 show_panel(view->child->panel);
1039 * XXX This is ugly and needs to be moved into the above
1040 * logic but "works" for now and my attempts at moving it
1041 * break either 'tab' or 'F' key maps in horizontal splits.
1043 if (hs) {
1044 err = view_splitscreen(view->child);
1045 if (err)
1046 return err;
1047 if (dif < 0) { /* top split decreased */
1048 err = offset_selection_down(view);
1049 if (err)
1050 return err;
1052 view_border(view);
1053 update_panels();
1054 doupdate();
1055 show_panel(view->child->panel);
1056 nlines = view->nlines;
1058 } else if (view->parent == NULL)
1059 ncols = COLS;
1061 if (view->resize && dif > 0) {
1062 err = view->resize(view, dif);
1063 if (err)
1064 return err;
1067 if (wresize(view->window, nlines, ncols) == ERR)
1068 return got_error_from_errno("wresize");
1069 if (replace_panel(view->panel, view->window) == ERR)
1070 return got_error_from_errno("replace_panel");
1071 wclear(view->window);
1073 view->nlines = nlines;
1074 view->ncols = ncols;
1075 view->lines = LINES;
1076 view->cols = COLS;
1078 return NULL;
1081 static const struct got_error *
1082 resize_log_view(struct tog_view *view, int increase)
1084 struct tog_log_view_state *s = &view->state.log;
1085 const struct got_error *err = NULL;
1086 int n = 0;
1088 if (s->selected_entry)
1089 n = s->selected_entry->idx + view->lines - s->selected;
1092 * Request commits to account for the increased
1093 * height so we have enough to populate the view.
1095 if (s->commits->ncommits < n) {
1096 view->nscrolled = n - s->commits->ncommits + increase + 1;
1097 err = request_log_commits(view);
1100 return err;
1103 static void
1104 view_adjust_offset(struct tog_view *view, int n)
1106 if (n == 0)
1107 return;
1109 if (view->parent && view->parent->offset) {
1110 if (view->parent->offset + n >= 0)
1111 view->parent->offset += n;
1112 else
1113 view->parent->offset = 0;
1114 } else if (view->offset) {
1115 if (view->offset - n >= 0)
1116 view->offset -= n;
1117 else
1118 view->offset = 0;
1122 static const struct got_error *
1123 view_resize_split(struct tog_view *view, int resize)
1125 const struct got_error *err = NULL;
1126 struct tog_view *v = NULL;
1128 if (view->parent)
1129 v = view->parent;
1130 else
1131 v = view;
1133 if (!v->child || !view_is_splitscreen(v->child))
1134 return NULL;
1136 v->resized = v->child->resized = resize; /* lock for resize event */
1138 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1139 if (v->child->resized_y)
1140 v->child->begin_y = v->child->resized_y;
1141 if (view->parent)
1142 v->child->begin_y -= resize;
1143 else
1144 v->child->begin_y += resize;
1145 if (v->child->begin_y < 3) {
1146 view->count = 0;
1147 v->child->begin_y = 3;
1148 } else if (v->child->begin_y > LINES - 1) {
1149 view->count = 0;
1150 v->child->begin_y = LINES - 1;
1152 v->ncols = COLS;
1153 v->child->ncols = COLS;
1154 view_adjust_offset(view, resize);
1155 err = view_init_hsplit(v, v->child->begin_y);
1156 if (err)
1157 return err;
1158 v->child->resized_y = v->child->begin_y;
1159 } else {
1160 if (v->child->resized_x)
1161 v->child->begin_x = v->child->resized_x;
1162 if (view->parent)
1163 v->child->begin_x -= resize;
1164 else
1165 v->child->begin_x += resize;
1166 if (v->child->begin_x < 11) {
1167 view->count = 0;
1168 v->child->begin_x = 11;
1169 } else if (v->child->begin_x > COLS - 1) {
1170 view->count = 0;
1171 v->child->begin_x = COLS - 1;
1173 v->child->resized_x = v->child->begin_x;
1176 v->child->mode = v->mode;
1177 v->child->nlines = v->lines - v->child->begin_y;
1178 v->child->ncols = v->cols - v->child->begin_x;
1179 v->focus_child = 1;
1181 err = view_fullscreen(v);
1182 if (err)
1183 return err;
1184 err = view_splitscreen(v->child);
1185 if (err)
1186 return err;
1188 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1189 err = offset_selection_down(v->child);
1190 if (err)
1191 return err;
1194 if (v->resize)
1195 err = v->resize(v, 0);
1196 else if (v->child->resize)
1197 err = v->child->resize(v->child, 0);
1199 v->resized = v->child->resized = 0;
1201 return err;
1204 static void
1205 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1207 struct tog_view *v = src->child ? src->child : src;
1209 dst->resized_x = v->resized_x;
1210 dst->resized_y = v->resized_y;
1213 static const struct got_error *
1214 view_close_child(struct tog_view *view)
1216 const struct got_error *err = NULL;
1218 if (view->child == NULL)
1219 return NULL;
1221 err = view_close(view->child);
1222 view->child = NULL;
1223 return err;
1226 static const struct got_error *
1227 view_set_child(struct tog_view *view, struct tog_view *child)
1229 const struct got_error *err = NULL;
1231 view->child = child;
1232 child->parent = view;
1234 err = view_resize(view);
1235 if (err)
1236 return err;
1238 if (view->child->resized_x || view->child->resized_y)
1239 err = view_resize_split(view, 0);
1241 return err;
1244 static const struct got_error *view_dispatch_request(struct tog_view **,
1245 struct tog_view *, enum tog_view_type, int, int);
1247 static const struct got_error *
1248 view_request_new(struct tog_view **requested, struct tog_view *view,
1249 enum tog_view_type request)
1251 struct tog_view *new_view = NULL;
1252 const struct got_error *err;
1253 int y = 0, x = 0;
1255 *requested = NULL;
1257 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1258 view_get_split(view, &y, &x);
1260 err = view_dispatch_request(&new_view, view, request, y, x);
1261 if (err)
1262 return err;
1264 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1265 request != TOG_VIEW_HELP) {
1266 err = view_init_hsplit(view, y);
1267 if (err)
1268 return err;
1271 view->focussed = 0;
1272 new_view->focussed = 1;
1273 new_view->mode = view->mode;
1274 new_view->nlines = request == TOG_VIEW_HELP ?
1275 view->lines : view->lines - y;
1277 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1278 view_transfer_size(new_view, view);
1279 err = view_close_child(view);
1280 if (err)
1281 return err;
1282 err = view_set_child(view, new_view);
1283 if (err)
1284 return err;
1285 view->focus_child = 1;
1286 } else
1287 *requested = new_view;
1289 return NULL;
1292 static void
1293 tog_resizeterm(void)
1295 int cols, lines;
1296 struct winsize size;
1298 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1299 cols = 80; /* Default */
1300 lines = 24;
1301 } else {
1302 cols = size.ws_col;
1303 lines = size.ws_row;
1305 resize_term(lines, cols);
1308 static const struct got_error *
1309 view_search_start(struct tog_view *view, int fast_refresh)
1311 const struct got_error *err = NULL;
1312 struct tog_view *v = view;
1313 char pattern[1024];
1314 int ret;
1316 if (view->search_started) {
1317 regfree(&view->regex);
1318 view->searching = 0;
1319 memset(&view->regmatch, 0, sizeof(view->regmatch));
1321 view->search_started = 0;
1323 if (view->nlines < 1)
1324 return NULL;
1326 if (view_is_hsplit_top(view))
1327 v = view->child;
1328 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1329 v = view->parent;
1331 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1332 wclrtoeol(v->window);
1334 nodelay(v->window, FALSE); /* block for search term input */
1335 nocbreak();
1336 echo();
1337 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1338 wrefresh(v->window);
1339 cbreak();
1340 noecho();
1341 nodelay(v->window, TRUE);
1342 if (!fast_refresh && !using_mock_io)
1343 halfdelay(10);
1344 if (ret == ERR)
1345 return NULL;
1347 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1348 err = view->search_start(view);
1349 if (err) {
1350 regfree(&view->regex);
1351 return err;
1353 view->search_started = 1;
1354 view->searching = TOG_SEARCH_FORWARD;
1355 view->search_next_done = 0;
1356 view->search_next(view);
1359 return NULL;
1362 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1363 static const struct got_error *
1364 switch_split(struct tog_view *view)
1366 const struct got_error *err = NULL;
1367 struct tog_view *v = NULL;
1369 if (view->parent)
1370 v = view->parent;
1371 else
1372 v = view;
1374 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1375 v->mode = TOG_VIEW_SPLIT_VERT;
1376 else
1377 v->mode = TOG_VIEW_SPLIT_HRZN;
1379 if (!v->child)
1380 return NULL;
1381 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1382 v->mode = TOG_VIEW_SPLIT_NONE;
1384 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1385 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1386 v->child->begin_y = v->child->resized_y;
1387 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1388 v->child->begin_x = v->child->resized_x;
1391 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1392 v->ncols = COLS;
1393 v->child->ncols = COLS;
1394 v->child->nscrolled = LINES - v->child->nlines;
1396 err = view_init_hsplit(v, v->child->begin_y);
1397 if (err)
1398 return err;
1400 v->child->mode = v->mode;
1401 v->child->nlines = v->lines - v->child->begin_y;
1402 v->focus_child = 1;
1404 err = view_fullscreen(v);
1405 if (err)
1406 return err;
1407 err = view_splitscreen(v->child);
1408 if (err)
1409 return err;
1411 if (v->mode == TOG_VIEW_SPLIT_NONE)
1412 v->mode = TOG_VIEW_SPLIT_VERT;
1413 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1414 err = offset_selection_down(v);
1415 if (err)
1416 return err;
1417 err = offset_selection_down(v->child);
1418 if (err)
1419 return err;
1420 } else {
1421 offset_selection_up(v);
1422 offset_selection_up(v->child);
1424 if (v->resize)
1425 err = v->resize(v, 0);
1426 else if (v->child->resize)
1427 err = v->child->resize(v->child, 0);
1429 return err;
1433 * Strip trailing whitespace from str starting at byte *n;
1434 * if *n < 0, use strlen(str). Return new str length in *n.
1436 static void
1437 strip_trailing_ws(char *str, int *n)
1439 size_t x = *n;
1441 if (str == NULL || *str == '\0')
1442 return;
1444 if (x < 0)
1445 x = strlen(str);
1447 while (x-- > 0 && isspace((unsigned char)str[x]))
1448 str[x] = '\0';
1450 *n = x + 1;
1454 * Extract visible substring of line y from the curses screen
1455 * and strip trailing whitespace. If vline is set, overwrite
1456 * line[vline] with '|' because the ACS_VLINE character is
1457 * written out as 'x'. Write the line to file f.
1459 static const struct got_error *
1460 view_write_line(FILE *f, int y, int vline)
1462 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1463 int r, w;
1465 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1466 if (r == ERR)
1467 return got_error_fmt(GOT_ERR_RANGE,
1468 "failed to extract line %d", y);
1471 * In some views, lines are padded with blanks to COLS width.
1472 * Strip them so we can diff without the -b flag when testing.
1474 strip_trailing_ws(line, &r);
1476 if (vline > 0)
1477 line[vline] = '|';
1479 w = fprintf(f, "%s\n", line);
1480 if (w != r + 1) /* \n */
1481 return got_ferror(f, GOT_ERR_IO);
1483 return NULL;
1487 * Capture the visible curses screen by writing each line to the
1488 * file at the path set via the TOG_SCR_DUMP environment variable.
1490 static const struct got_error *
1491 screendump(struct tog_view *view)
1493 const struct got_error *err;
1494 int i;
1496 err = got_opentemp_truncate(tog_io.sdump);
1497 if (err)
1498 return err;
1500 if ((view->child && view->child->begin_x) ||
1501 (view->parent && view->begin_x)) {
1502 int ncols = view->child ? view->ncols : view->parent->ncols;
1504 /* vertical splitscreen */
1505 for (i = 0; i < view->nlines; ++i) {
1506 err = view_write_line(tog_io.sdump, i, ncols - 1);
1507 if (err)
1508 goto done;
1510 } else {
1511 int hline = 0;
1513 /* fullscreen or horizontal splitscreen */
1514 if ((view->child && view->child->begin_y) ||
1515 (view->parent && view->begin_y)) /* hsplit */
1516 hline = view->child ?
1517 view->child->begin_y : view->begin_y;
1519 for (i = 0; i < view->lines; i++) {
1520 if (hline && i == hline - 1) {
1521 int c;
1523 /* ACS_HLINE writes out as 'q', overwrite it */
1524 for (c = 0; c < view->cols; ++c)
1525 fputc('-', tog_io.sdump);
1526 fputc('\n', tog_io.sdump);
1527 continue;
1530 err = view_write_line(tog_io.sdump, i, 0);
1531 if (err)
1532 goto done;
1536 done:
1537 return err;
1541 * Compute view->count from numeric input. Assign total to view->count and
1542 * return first non-numeric key entered.
1544 static int
1545 get_compound_key(struct tog_view *view, int c)
1547 struct tog_view *v = view;
1548 int x, n = 0;
1550 if (view_is_hsplit_top(view))
1551 v = view->child;
1552 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1553 v = view->parent;
1555 view->count = 0;
1556 cbreak(); /* block for input */
1557 nodelay(view->window, FALSE);
1558 wmove(v->window, v->nlines - 1, 0);
1559 wclrtoeol(v->window);
1560 waddch(v->window, ':');
1562 do {
1563 x = getcurx(v->window);
1564 if (x != ERR && x < view->ncols) {
1565 waddch(v->window, c);
1566 wrefresh(v->window);
1570 * Don't overflow. Max valid request should be the greatest
1571 * between the longest and total lines; cap at 10 million.
1573 if (n >= 9999999)
1574 n = 9999999;
1575 else
1576 n = n * 10 + (c - '0');
1577 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1579 if (c == 'G' || c == 'g') { /* nG key map */
1580 view->gline = view->hiline = n;
1581 n = 0;
1582 c = 0;
1585 /* Massage excessive or inapplicable values at the input handler. */
1586 view->count = n;
1588 return c;
1591 static void
1592 action_report(struct tog_view *view)
1594 struct tog_view *v = view;
1596 if (view_is_hsplit_top(view))
1597 v = view->child;
1598 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1599 v = view->parent;
1601 wmove(v->window, v->nlines - 1, 0);
1602 wclrtoeol(v->window);
1603 wprintw(v->window, ":%s", view->action);
1604 wrefresh(v->window);
1607 * Clear action status report. Only clear in blame view
1608 * once annotating is complete, otherwise it's too fast.
1610 if (view->type == TOG_VIEW_BLAME) {
1611 if (view->state.blame.blame_complete)
1612 view->action = NULL;
1613 } else
1614 view->action = NULL;
1618 * Read the next line from the test script and assign
1619 * key instruction to *ch. If at EOF, set the *done flag.
1621 static const struct got_error *
1622 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1624 const struct got_error *err = NULL;
1625 char *line = NULL;
1626 size_t linesz = 0;
1628 if (view->count && --view->count) {
1629 *ch = view->ch;
1630 return NULL;
1631 } else
1632 *ch = -1;
1634 if (getline(&line, &linesz, script) == -1) {
1635 if (feof(script)) {
1636 *done = 1;
1637 goto done;
1638 } else {
1639 err = got_ferror(script, GOT_ERR_IO);
1640 goto done;
1644 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1645 tog_io.wait_for_ui = 1;
1646 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1647 *ch = KEY_ENTER;
1648 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1649 *ch = KEY_RIGHT;
1650 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1651 *ch = KEY_LEFT;
1652 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1653 *ch = KEY_DOWN;
1654 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1655 *ch = KEY_UP;
1656 else if (strncasecmp(line, "TAB", 3) == 0)
1657 *ch = '\t';
1658 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1659 *ch = TOG_KEY_SCRDUMP;
1660 else if (isdigit((unsigned char)*line)) {
1661 char *t = line;
1663 while (isdigit((unsigned char)*t))
1664 ++t;
1665 view->ch = *ch = *t;
1666 *t = '\0';
1667 /* ignore error, view->count is 0 if instruction is invalid */
1668 view->count = strtonum(line, 0, INT_MAX, NULL);
1669 } else
1670 *ch = *line;
1672 done:
1673 free(line);
1674 return err;
1677 static const struct got_error *
1678 view_input(struct tog_view **new, int *done, struct tog_view *view,
1679 struct tog_view_list_head *views, int fast_refresh)
1681 const struct got_error *err = NULL;
1682 struct tog_view *v;
1683 int ch, errcode;
1685 *new = NULL;
1687 if (view->action)
1688 action_report(view);
1690 /* Clear "no matches" indicator. */
1691 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1692 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1693 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1694 view->count = 0;
1697 if (view->searching && !view->search_next_done) {
1698 errcode = pthread_mutex_unlock(&tog_mutex);
1699 if (errcode)
1700 return got_error_set_errno(errcode,
1701 "pthread_mutex_unlock");
1702 sched_yield();
1703 errcode = pthread_mutex_lock(&tog_mutex);
1704 if (errcode)
1705 return got_error_set_errno(errcode,
1706 "pthread_mutex_lock");
1707 view->search_next(view);
1708 return NULL;
1711 /* Allow threads to make progress while we are waiting for input. */
1712 errcode = pthread_mutex_unlock(&tog_mutex);
1713 if (errcode)
1714 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1716 if (using_mock_io) {
1717 err = tog_read_script_key(tog_io.f, view, &ch, done);
1718 if (err) {
1719 errcode = pthread_mutex_lock(&tog_mutex);
1720 return err;
1722 } else if (view->count && --view->count) {
1723 cbreak();
1724 nodelay(view->window, TRUE);
1725 ch = wgetch(view->window);
1726 /* let C-g or backspace abort unfinished count */
1727 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1728 view->count = 0;
1729 else
1730 ch = view->ch;
1731 } else {
1732 ch = wgetch(view->window);
1733 if (ch >= '1' && ch <= '9')
1734 view->ch = ch = get_compound_key(view, ch);
1736 if (view->hiline && ch != ERR && ch != 0)
1737 view->hiline = 0; /* key pressed, clear line highlight */
1738 nodelay(view->window, TRUE);
1739 errcode = pthread_mutex_lock(&tog_mutex);
1740 if (errcode)
1741 return got_error_set_errno(errcode, "pthread_mutex_lock");
1743 if (tog_sigwinch_received || tog_sigcont_received) {
1744 tog_resizeterm();
1745 tog_sigwinch_received = 0;
1746 tog_sigcont_received = 0;
1747 TAILQ_FOREACH(v, views, entry) {
1748 err = view_resize(v);
1749 if (err)
1750 return err;
1751 err = v->input(new, v, KEY_RESIZE);
1752 if (err)
1753 return err;
1754 if (v->child) {
1755 err = view_resize(v->child);
1756 if (err)
1757 return err;
1758 err = v->child->input(new, v->child,
1759 KEY_RESIZE);
1760 if (err)
1761 return err;
1762 if (v->child->resized_x || v->child->resized_y) {
1763 err = view_resize_split(v, 0);
1764 if (err)
1765 return err;
1771 switch (ch) {
1772 case '?':
1773 case 'H':
1774 case KEY_F(1):
1775 if (view->type == TOG_VIEW_HELP)
1776 err = view->reset(view);
1777 else
1778 err = view_request_new(new, view, TOG_VIEW_HELP);
1779 break;
1780 case '\t':
1781 view->count = 0;
1782 if (view->child) {
1783 view->focussed = 0;
1784 view->child->focussed = 1;
1785 view->focus_child = 1;
1786 } else if (view->parent) {
1787 view->focussed = 0;
1788 view->parent->focussed = 1;
1789 view->parent->focus_child = 0;
1790 if (!view_is_splitscreen(view)) {
1791 if (view->parent->resize) {
1792 err = view->parent->resize(view->parent,
1793 0);
1794 if (err)
1795 return err;
1797 offset_selection_up(view->parent);
1798 err = view_fullscreen(view->parent);
1799 if (err)
1800 return err;
1803 break;
1804 case 'q':
1805 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1806 if (view->parent->resize) {
1807 /* might need more commits to fill fullscreen */
1808 err = view->parent->resize(view->parent, 0);
1809 if (err)
1810 break;
1812 offset_selection_up(view->parent);
1814 err = view->input(new, view, ch);
1815 view->dying = 1;
1816 break;
1817 case 'Q':
1818 *done = 1;
1819 break;
1820 case 'F':
1821 view->count = 0;
1822 if (view_is_parent_view(view)) {
1823 if (view->child == NULL)
1824 break;
1825 if (view_is_splitscreen(view->child)) {
1826 view->focussed = 0;
1827 view->child->focussed = 1;
1828 err = view_fullscreen(view->child);
1829 } else {
1830 err = view_splitscreen(view->child);
1831 if (!err)
1832 err = view_resize_split(view, 0);
1834 if (err)
1835 break;
1836 err = view->child->input(new, view->child,
1837 KEY_RESIZE);
1838 } else {
1839 if (view_is_splitscreen(view)) {
1840 view->parent->focussed = 0;
1841 view->focussed = 1;
1842 err = view_fullscreen(view);
1843 } else {
1844 err = view_splitscreen(view);
1845 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1846 err = view_resize(view->parent);
1847 if (!err)
1848 err = view_resize_split(view, 0);
1850 if (err)
1851 break;
1852 err = view->input(new, view, KEY_RESIZE);
1854 if (err)
1855 break;
1856 if (view->resize) {
1857 err = view->resize(view, 0);
1858 if (err)
1859 break;
1861 if (view->parent) {
1862 if (view->parent->resize) {
1863 err = view->parent->resize(view->parent, 0);
1864 if (err != NULL)
1865 break;
1867 err = offset_selection_down(view->parent);
1868 if (err != NULL)
1869 break;
1871 err = offset_selection_down(view);
1872 break;
1873 case 'S':
1874 view->count = 0;
1875 err = switch_split(view);
1876 break;
1877 case '-':
1878 err = view_resize_split(view, -1);
1879 break;
1880 case '+':
1881 err = view_resize_split(view, 1);
1882 break;
1883 case KEY_RESIZE:
1884 break;
1885 case '/':
1886 view->count = 0;
1887 if (view->search_start)
1888 view_search_start(view, fast_refresh);
1889 else
1890 err = view->input(new, view, ch);
1891 break;
1892 case 'N':
1893 case 'n':
1894 if (view->search_started && view->search_next) {
1895 view->searching = (ch == 'n' ?
1896 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1897 view->search_next_done = 0;
1898 view->search_next(view);
1899 } else
1900 err = view->input(new, view, ch);
1901 break;
1902 case 'A':
1903 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1904 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1905 view->action = "Patience diff algorithm";
1906 } else {
1907 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1908 view->action = "Myers diff algorithm";
1910 TAILQ_FOREACH(v, views, entry) {
1911 if (v->reset) {
1912 err = v->reset(v);
1913 if (err)
1914 return err;
1916 if (v->child && v->child->reset) {
1917 err = v->child->reset(v->child);
1918 if (err)
1919 return err;
1922 break;
1923 case TOG_KEY_SCRDUMP:
1924 err = screendump(view);
1925 break;
1926 default:
1927 err = view->input(new, view, ch);
1928 break;
1931 return err;
1934 static int
1935 view_needs_focus_indication(struct tog_view *view)
1937 if (view_is_parent_view(view)) {
1938 if (view->child == NULL || view->child->focussed)
1939 return 0;
1940 if (!view_is_splitscreen(view->child))
1941 return 0;
1942 } else if (!view_is_splitscreen(view))
1943 return 0;
1945 return view->focussed;
1948 static const struct got_error *
1949 tog_io_close(void)
1951 const struct got_error *err = NULL;
1953 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1954 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1955 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1956 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1957 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1958 err = got_ferror(tog_io.f, GOT_ERR_IO);
1959 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1960 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1962 return err;
1965 static const struct got_error *
1966 view_loop(struct tog_view *view)
1968 const struct got_error *err = NULL;
1969 struct tog_view_list_head views;
1970 struct tog_view *new_view;
1971 char *mode;
1972 int fast_refresh = 10;
1973 int done = 0, errcode;
1975 mode = getenv("TOG_VIEW_SPLIT_MODE");
1976 if (!mode || !(*mode == 'h' || *mode == 'H'))
1977 view->mode = TOG_VIEW_SPLIT_VERT;
1978 else
1979 view->mode = TOG_VIEW_SPLIT_HRZN;
1981 errcode = pthread_mutex_lock(&tog_mutex);
1982 if (errcode)
1983 return got_error_set_errno(errcode, "pthread_mutex_lock");
1985 TAILQ_INIT(&views);
1986 TAILQ_INSERT_HEAD(&views, view, entry);
1988 view->focussed = 1;
1989 err = view->show(view);
1990 if (err)
1991 return err;
1992 update_panels();
1993 doupdate();
1994 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1995 !tog_fatal_signal_received()) {
1996 /* Refresh fast during initialization, then become slower. */
1997 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1998 halfdelay(10); /* switch to once per second */
2000 err = view_input(&new_view, &done, view, &views, fast_refresh);
2001 if (err)
2002 break;
2004 if (view->dying && view == TAILQ_FIRST(&views) &&
2005 TAILQ_NEXT(view, entry) == NULL)
2006 done = 1;
2007 if (done) {
2008 struct tog_view *v;
2011 * When we quit, scroll the screen up a single line
2012 * so we don't lose any information.
2014 TAILQ_FOREACH(v, &views, entry) {
2015 wmove(v->window, 0, 0);
2016 wdeleteln(v->window);
2017 wnoutrefresh(v->window);
2018 if (v->child && !view_is_fullscreen(v)) {
2019 wmove(v->child->window, 0, 0);
2020 wdeleteln(v->child->window);
2021 wnoutrefresh(v->child->window);
2024 doupdate();
2027 if (view->dying) {
2028 struct tog_view *v, *prev = NULL;
2030 if (view_is_parent_view(view))
2031 prev = TAILQ_PREV(view, tog_view_list_head,
2032 entry);
2033 else if (view->parent)
2034 prev = view->parent;
2036 if (view->parent) {
2037 view->parent->child = NULL;
2038 view->parent->focus_child = 0;
2039 /* Restore fullscreen line height. */
2040 view->parent->nlines = view->parent->lines;
2041 err = view_resize(view->parent);
2042 if (err)
2043 break;
2044 /* Make resized splits persist. */
2045 view_transfer_size(view->parent, view);
2046 } else
2047 TAILQ_REMOVE(&views, view, entry);
2049 err = view_close(view);
2050 if (err)
2051 goto done;
2053 view = NULL;
2054 TAILQ_FOREACH(v, &views, entry) {
2055 if (v->focussed)
2056 break;
2058 if (view == NULL && new_view == NULL) {
2059 /* No view has focus. Try to pick one. */
2060 if (prev)
2061 view = prev;
2062 else if (!TAILQ_EMPTY(&views)) {
2063 view = TAILQ_LAST(&views,
2064 tog_view_list_head);
2066 if (view) {
2067 if (view->focus_child) {
2068 view->child->focussed = 1;
2069 view = view->child;
2070 } else
2071 view->focussed = 1;
2075 if (new_view) {
2076 struct tog_view *v, *t;
2077 /* Only allow one parent view per type. */
2078 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2079 if (v->type != new_view->type)
2080 continue;
2081 TAILQ_REMOVE(&views, v, entry);
2082 err = view_close(v);
2083 if (err)
2084 goto done;
2085 break;
2087 TAILQ_INSERT_TAIL(&views, new_view, entry);
2088 view = new_view;
2090 if (view && !done) {
2091 if (view_is_parent_view(view)) {
2092 if (view->child && view->child->focussed)
2093 view = view->child;
2094 } else {
2095 if (view->parent && view->parent->focussed)
2096 view = view->parent;
2098 show_panel(view->panel);
2099 if (view->child && view_is_splitscreen(view->child))
2100 show_panel(view->child->panel);
2101 if (view->parent && view_is_splitscreen(view)) {
2102 err = view->parent->show(view->parent);
2103 if (err)
2104 goto done;
2106 err = view->show(view);
2107 if (err)
2108 goto done;
2109 if (view->child) {
2110 err = view->child->show(view->child);
2111 if (err)
2112 goto done;
2114 update_panels();
2115 doupdate();
2118 done:
2119 while (!TAILQ_EMPTY(&views)) {
2120 const struct got_error *close_err;
2121 view = TAILQ_FIRST(&views);
2122 TAILQ_REMOVE(&views, view, entry);
2123 close_err = view_close(view);
2124 if (close_err && err == NULL)
2125 err = close_err;
2128 errcode = pthread_mutex_unlock(&tog_mutex);
2129 if (errcode && err == NULL)
2130 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2132 return err;
2135 __dead static void
2136 usage_log(void)
2138 endwin();
2139 fprintf(stderr,
2140 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2141 getprogname());
2142 exit(1);
2145 /* Create newly allocated wide-character string equivalent to a byte string. */
2146 static const struct got_error *
2147 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2149 char *vis = NULL;
2150 const struct got_error *err = NULL;
2152 *ws = NULL;
2153 *wlen = mbstowcs(NULL, s, 0);
2154 if (*wlen == (size_t)-1) {
2155 int vislen;
2156 if (errno != EILSEQ)
2157 return got_error_from_errno("mbstowcs");
2159 /* byte string invalid in current encoding; try to "fix" it */
2160 err = got_mbsavis(&vis, &vislen, s);
2161 if (err)
2162 return err;
2163 *wlen = mbstowcs(NULL, vis, 0);
2164 if (*wlen == (size_t)-1) {
2165 err = got_error_from_errno("mbstowcs"); /* give up */
2166 goto done;
2170 *ws = calloc(*wlen + 1, sizeof(**ws));
2171 if (*ws == NULL) {
2172 err = got_error_from_errno("calloc");
2173 goto done;
2176 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2177 err = got_error_from_errno("mbstowcs");
2178 done:
2179 free(vis);
2180 if (err) {
2181 free(*ws);
2182 *ws = NULL;
2183 *wlen = 0;
2185 return err;
2188 static const struct got_error *
2189 expand_tab(char **ptr, const char *src)
2191 char *dst;
2192 size_t len, n, idx = 0, sz = 0;
2194 *ptr = NULL;
2195 n = len = strlen(src);
2196 dst = malloc(n + 1);
2197 if (dst == NULL)
2198 return got_error_from_errno("malloc");
2200 while (idx < len && src[idx]) {
2201 const char c = src[idx];
2203 if (c == '\t') {
2204 size_t nb = TABSIZE - sz % TABSIZE;
2205 char *p;
2207 p = realloc(dst, n + nb);
2208 if (p == NULL) {
2209 free(dst);
2210 return got_error_from_errno("realloc");
2213 dst = p;
2214 n += nb;
2215 memset(dst + sz, ' ', nb);
2216 sz += nb;
2217 } else
2218 dst[sz++] = src[idx];
2219 ++idx;
2222 dst[sz] = '\0';
2223 *ptr = dst;
2224 return NULL;
2228 * Advance at most n columns from wline starting at offset off.
2229 * Return the index to the first character after the span operation.
2230 * Return the combined column width of all spanned wide character in
2231 * *rcol.
2233 static int
2234 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2236 int width, i, cols = 0;
2238 if (n == 0) {
2239 *rcol = cols;
2240 return off;
2243 for (i = off; wline[i] != L'\0'; ++i) {
2244 if (wline[i] == L'\t')
2245 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2246 else
2247 width = wcwidth(wline[i]);
2249 if (width == -1) {
2250 width = 1;
2251 wline[i] = L'.';
2254 if (cols + width > n)
2255 break;
2256 cols += width;
2259 *rcol = cols;
2260 return i;
2264 * Format a line for display, ensuring that it won't overflow a width limit.
2265 * With scrolling, the width returned refers to the scrolled version of the
2266 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2268 static const struct got_error *
2269 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2270 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2272 const struct got_error *err = NULL;
2273 int cols;
2274 wchar_t *wline = NULL;
2275 char *exstr = NULL;
2276 size_t wlen;
2277 int i, scrollx;
2279 *wlinep = NULL;
2280 *widthp = 0;
2282 if (expand) {
2283 err = expand_tab(&exstr, line);
2284 if (err)
2285 return err;
2288 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2289 free(exstr);
2290 if (err)
2291 return err;
2293 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2295 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2296 wline[wlen - 1] = L'\0';
2297 wlen--;
2299 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2300 wline[wlen - 1] = L'\0';
2301 wlen--;
2304 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2305 wline[i] = L'\0';
2307 if (widthp)
2308 *widthp = cols;
2309 if (scrollxp)
2310 *scrollxp = scrollx;
2311 if (err)
2312 free(wline);
2313 else
2314 *wlinep = wline;
2315 return err;
2318 static const struct got_error*
2319 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2320 struct got_object_id *id, struct got_repository *repo)
2322 static const struct got_error *err = NULL;
2323 struct got_reflist_entry *re;
2324 char *s;
2325 const char *name;
2327 *refs_str = NULL;
2329 TAILQ_FOREACH(re, refs, entry) {
2330 struct got_tag_object *tag = NULL;
2331 struct got_object_id *ref_id;
2332 int cmp;
2334 name = got_ref_get_name(re->ref);
2335 if (strcmp(name, GOT_REF_HEAD) == 0)
2336 continue;
2337 if (strncmp(name, "refs/", 5) == 0)
2338 name += 5;
2339 if (strncmp(name, "got/", 4) == 0 &&
2340 strncmp(name, "got/backup/", 11) != 0)
2341 continue;
2342 if (strncmp(name, "heads/", 6) == 0)
2343 name += 6;
2344 if (strncmp(name, "remotes/", 8) == 0) {
2345 name += 8;
2346 s = strstr(name, "/" GOT_REF_HEAD);
2347 if (s != NULL && s[strlen(s)] == '\0')
2348 continue;
2350 err = got_ref_resolve(&ref_id, repo, re->ref);
2351 if (err)
2352 break;
2353 if (strncmp(name, "tags/", 5) == 0) {
2354 err = got_object_open_as_tag(&tag, repo, ref_id);
2355 if (err) {
2356 if (err->code != GOT_ERR_OBJ_TYPE) {
2357 free(ref_id);
2358 break;
2360 /* Ref points at something other than a tag. */
2361 err = NULL;
2362 tag = NULL;
2365 cmp = got_object_id_cmp(tag ?
2366 got_object_tag_get_object_id(tag) : ref_id, id);
2367 free(ref_id);
2368 if (tag)
2369 got_object_tag_close(tag);
2370 if (cmp != 0)
2371 continue;
2372 s = *refs_str;
2373 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2374 s ? ", " : "", name) == -1) {
2375 err = got_error_from_errno("asprintf");
2376 free(s);
2377 *refs_str = NULL;
2378 break;
2380 free(s);
2383 return err;
2386 static const struct got_error *
2387 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2388 int col_tab_align)
2390 char *smallerthan;
2392 smallerthan = strchr(author, '<');
2393 if (smallerthan && smallerthan[1] != '\0')
2394 author = smallerthan + 1;
2395 author[strcspn(author, "@>")] = '\0';
2396 return format_line(wauthor, author_width, NULL, author, 0, limit,
2397 col_tab_align, 0);
2400 static const struct got_error *
2401 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2402 struct got_object_id *id, const size_t date_display_cols,
2403 int author_display_cols)
2405 struct tog_log_view_state *s = &view->state.log;
2406 const struct got_error *err = NULL;
2407 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
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 if (refs) {
2503 char *refs_str, *newlogmsg;
2504 wchar_t *ws;
2506 err = build_refs_str(&refs_str, refs, id, s->repo);
2507 if (err)
2508 goto done;
2511 * The length of this wide-char sub-string will be
2512 * needed later for colorization.
2514 err = mbs2ws(&ws, &wrefstr_len, refs_str);
2515 if (err)
2516 goto done;
2517 free(ws);
2519 wrefstr_len += 2; /* account for '[' and ']' */
2521 if (asprintf(&newlogmsg, "[%s] %s", refs_str, logmsg) == -1) {
2522 err = got_error_from_errno("asprintf");
2523 free(refs_str);
2524 goto done;
2526 free(refs_str);
2528 free(logmsg0);
2529 logmsg0 = newlogmsg;
2530 logmsg = logmsg0;
2533 limit = avail - col;
2534 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2535 limit--; /* for the border */
2536 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2537 limit, col, 1);
2538 if (err)
2539 goto done;
2540 if (wrefstr_len > 0 && scrollx < wrefstr_len) {
2541 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2542 if (tc)
2543 wattr_on(view->window,
2544 COLOR_PAIR(tc->colorpair), NULL);
2545 waddnwstr(view->window, &wlogmsg[scrollx],
2546 wrefstr_len - scrollx);
2547 if (tc)
2548 wattr_off(view->window,
2549 COLOR_PAIR(tc->colorpair), NULL);
2550 waddwstr(view->window, &wlogmsg[wrefstr_len]);
2551 } else
2552 waddwstr(view->window, &wlogmsg[scrollx]);
2553 col += MAX(logmsg_width, 0);
2554 while (col < avail) {
2555 waddch(view->window, ' ');
2556 col++;
2558 done:
2559 free(logmsg0);
2560 free(wlogmsg);
2561 free(author);
2562 free(wauthor);
2563 free(line);
2564 return err;
2567 static struct commit_queue_entry *
2568 alloc_commit_queue_entry(struct got_commit_object *commit,
2569 struct got_object_id *id)
2571 struct commit_queue_entry *entry;
2572 struct got_object_id *dup;
2574 entry = calloc(1, sizeof(*entry));
2575 if (entry == NULL)
2576 return NULL;
2578 dup = got_object_id_dup(id);
2579 if (dup == NULL) {
2580 free(entry);
2581 return NULL;
2584 entry->id = dup;
2585 entry->commit = commit;
2586 return entry;
2589 static void
2590 pop_commit(struct commit_queue *commits)
2592 struct commit_queue_entry *entry;
2594 entry = TAILQ_FIRST(&commits->head);
2595 TAILQ_REMOVE(&commits->head, entry, entry);
2596 got_object_commit_close(entry->commit);
2597 commits->ncommits--;
2598 free(entry->id);
2599 free(entry);
2602 static void
2603 free_commits(struct commit_queue *commits)
2605 while (!TAILQ_EMPTY(&commits->head))
2606 pop_commit(commits);
2609 static const struct got_error *
2610 match_commit(int *have_match, struct got_object_id *id,
2611 struct got_commit_object *commit, regex_t *regex)
2613 const struct got_error *err = NULL;
2614 regmatch_t regmatch;
2615 char *id_str = NULL, *logmsg = NULL;
2617 *have_match = 0;
2619 err = got_object_id_str(&id_str, id);
2620 if (err)
2621 return err;
2623 err = got_object_commit_get_logmsg(&logmsg, commit);
2624 if (err)
2625 goto done;
2627 if (regexec(regex, got_object_commit_get_author(commit), 1,
2628 &regmatch, 0) == 0 ||
2629 regexec(regex, got_object_commit_get_committer(commit), 1,
2630 &regmatch, 0) == 0 ||
2631 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2632 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2633 *have_match = 1;
2634 done:
2635 free(id_str);
2636 free(logmsg);
2637 return err;
2640 static const struct got_error *
2641 queue_commits(struct tog_log_thread_args *a)
2643 const struct got_error *err = NULL;
2646 * We keep all commits open throughout the lifetime of the log
2647 * view in order to avoid having to re-fetch commits from disk
2648 * while updating the display.
2650 do {
2651 struct got_object_id id;
2652 struct got_commit_object *commit;
2653 struct commit_queue_entry *entry;
2654 int limit_match = 0;
2655 int errcode;
2657 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2658 NULL, NULL);
2659 if (err)
2660 break;
2662 err = got_object_open_as_commit(&commit, a->repo, &id);
2663 if (err)
2664 break;
2665 entry = alloc_commit_queue_entry(commit, &id);
2666 if (entry == NULL) {
2667 err = got_error_from_errno("alloc_commit_queue_entry");
2668 break;
2671 errcode = pthread_mutex_lock(&tog_mutex);
2672 if (errcode) {
2673 err = got_error_set_errno(errcode,
2674 "pthread_mutex_lock");
2675 break;
2678 entry->idx = a->real_commits->ncommits;
2679 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2680 a->real_commits->ncommits++;
2682 if (*a->limiting) {
2683 err = match_commit(&limit_match, &id, commit,
2684 a->limit_regex);
2685 if (err)
2686 break;
2688 if (limit_match) {
2689 struct commit_queue_entry *matched;
2691 matched = alloc_commit_queue_entry(
2692 entry->commit, entry->id);
2693 if (matched == NULL) {
2694 err = got_error_from_errno(
2695 "alloc_commit_queue_entry");
2696 break;
2698 matched->commit = entry->commit;
2699 got_object_commit_retain(entry->commit);
2701 matched->idx = a->limit_commits->ncommits;
2702 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2703 matched, entry);
2704 a->limit_commits->ncommits++;
2708 * This is how we signal log_thread() that we
2709 * have found a match, and that it should be
2710 * counted as a new entry for the view.
2712 a->limit_match = limit_match;
2715 if (*a->searching == TOG_SEARCH_FORWARD &&
2716 !*a->search_next_done) {
2717 int have_match;
2718 err = match_commit(&have_match, &id, commit, a->regex);
2719 if (err)
2720 break;
2722 if (*a->limiting) {
2723 if (limit_match && have_match)
2724 *a->search_next_done =
2725 TOG_SEARCH_HAVE_MORE;
2726 } else if (have_match)
2727 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2730 errcode = pthread_mutex_unlock(&tog_mutex);
2731 if (errcode && err == NULL)
2732 err = got_error_set_errno(errcode,
2733 "pthread_mutex_unlock");
2734 if (err)
2735 break;
2736 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2738 return err;
2741 static void
2742 select_commit(struct tog_log_view_state *s)
2744 struct commit_queue_entry *entry;
2745 int ncommits = 0;
2747 entry = s->first_displayed_entry;
2748 while (entry) {
2749 if (ncommits == s->selected) {
2750 s->selected_entry = entry;
2751 break;
2753 entry = TAILQ_NEXT(entry, entry);
2754 ncommits++;
2758 static const struct got_error *
2759 draw_commits(struct tog_view *view)
2761 const struct got_error *err = NULL;
2762 struct tog_log_view_state *s = &view->state.log;
2763 struct commit_queue_entry *entry = s->selected_entry;
2764 int limit = view->nlines;
2765 int width;
2766 int ncommits, author_cols = 4;
2767 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2768 char *refs_str = NULL;
2769 wchar_t *wline;
2770 struct tog_color *tc;
2771 static const size_t date_display_cols = 12;
2773 if (view_is_hsplit_top(view))
2774 --limit; /* account for border */
2776 if (s->selected_entry &&
2777 !(view->searching && view->search_next_done == 0)) {
2778 struct got_reflist_head *refs;
2779 err = got_object_id_str(&id_str, s->selected_entry->id);
2780 if (err)
2781 return err;
2782 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2783 s->selected_entry->id);
2784 if (refs) {
2785 err = build_refs_str(&refs_str, refs,
2786 s->selected_entry->id, s->repo);
2787 if (err)
2788 goto done;
2792 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2793 halfdelay(10); /* disable fast refresh */
2795 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2796 if (asprintf(&ncommits_str, " [%d/%d] %s",
2797 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2798 (view->searching && !view->search_next_done) ?
2799 "searching..." : "loading...") == -1) {
2800 err = got_error_from_errno("asprintf");
2801 goto done;
2803 } else {
2804 const char *search_str = NULL;
2805 const char *limit_str = NULL;
2807 if (view->searching) {
2808 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2809 search_str = "no more matches";
2810 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2811 search_str = "no matches found";
2812 else if (!view->search_next_done)
2813 search_str = "searching...";
2816 if (s->limit_view && s->commits->ncommits == 0)
2817 limit_str = "no matches found";
2819 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2820 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2821 search_str ? search_str : (refs_str ? refs_str : ""),
2822 limit_str ? limit_str : "") == -1) {
2823 err = got_error_from_errno("asprintf");
2824 goto done;
2828 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2829 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2830 "........................................",
2831 s->in_repo_path, ncommits_str) == -1) {
2832 err = got_error_from_errno("asprintf");
2833 header = NULL;
2834 goto done;
2836 } else if (asprintf(&header, "commit %s%s",
2837 id_str ? id_str : "........................................",
2838 ncommits_str) == -1) {
2839 err = got_error_from_errno("asprintf");
2840 header = NULL;
2841 goto done;
2843 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2844 if (err)
2845 goto done;
2847 werase(view->window);
2849 if (view_needs_focus_indication(view))
2850 wstandout(view->window);
2851 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2852 if (tc)
2853 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2854 waddwstr(view->window, wline);
2855 while (width < view->ncols) {
2856 waddch(view->window, ' ');
2857 width++;
2859 if (tc)
2860 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2861 if (view_needs_focus_indication(view))
2862 wstandend(view->window);
2863 free(wline);
2864 if (limit <= 1)
2865 goto done;
2867 /* Grow author column size if necessary, and set view->maxx. */
2868 entry = s->first_displayed_entry;
2869 ncommits = 0;
2870 view->maxx = 0;
2871 while (entry) {
2872 struct got_commit_object *c = entry->commit;
2873 char *author, *eol, *msg, *msg0;
2874 wchar_t *wauthor, *wmsg;
2875 int width;
2876 if (ncommits >= limit - 1)
2877 break;
2878 if (s->use_committer)
2879 author = strdup(got_object_commit_get_committer(c));
2880 else
2881 author = strdup(got_object_commit_get_author(c));
2882 if (author == NULL) {
2883 err = got_error_from_errno("strdup");
2884 goto done;
2886 err = format_author(&wauthor, &width, author, COLS,
2887 date_display_cols);
2888 if (author_cols < width)
2889 author_cols = width;
2890 free(wauthor);
2891 free(author);
2892 if (err)
2893 goto done;
2894 err = got_object_commit_get_logmsg(&msg0, c);
2895 if (err)
2896 goto done;
2897 msg = msg0;
2898 while (*msg == '\n')
2899 ++msg;
2900 if ((eol = strchr(msg, '\n')))
2901 *eol = '\0';
2902 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2903 date_display_cols + author_cols, 0);
2904 if (err)
2905 goto done;
2906 view->maxx = MAX(view->maxx, width);
2907 free(msg0);
2908 free(wmsg);
2909 ncommits++;
2910 entry = TAILQ_NEXT(entry, entry);
2913 entry = s->first_displayed_entry;
2914 s->last_displayed_entry = s->first_displayed_entry;
2915 ncommits = 0;
2916 while (entry) {
2917 if (ncommits >= limit - 1)
2918 break;
2919 if (ncommits == s->selected)
2920 wstandout(view->window);
2921 err = draw_commit(view, entry->commit, entry->id,
2922 date_display_cols, author_cols);
2923 if (ncommits == s->selected)
2924 wstandend(view->window);
2925 if (err)
2926 goto done;
2927 ncommits++;
2928 s->last_displayed_entry = entry;
2929 entry = TAILQ_NEXT(entry, entry);
2932 view_border(view);
2933 done:
2934 free(id_str);
2935 free(refs_str);
2936 free(ncommits_str);
2937 free(header);
2938 return err;
2941 static void
2942 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2944 struct commit_queue_entry *entry;
2945 int nscrolled = 0;
2947 entry = TAILQ_FIRST(&s->commits->head);
2948 if (s->first_displayed_entry == entry)
2949 return;
2951 entry = s->first_displayed_entry;
2952 while (entry && nscrolled < maxscroll) {
2953 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2954 if (entry) {
2955 s->first_displayed_entry = entry;
2956 nscrolled++;
2961 static const struct got_error *
2962 trigger_log_thread(struct tog_view *view, int wait)
2964 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2965 int errcode;
2967 if (!using_mock_io)
2968 halfdelay(1); /* fast refresh while loading commits */
2970 while (!ta->log_complete && !tog_thread_error &&
2971 (ta->commits_needed > 0 || ta->load_all)) {
2972 /* Wake the log thread. */
2973 errcode = pthread_cond_signal(&ta->need_commits);
2974 if (errcode)
2975 return got_error_set_errno(errcode,
2976 "pthread_cond_signal");
2979 * The mutex will be released while the view loop waits
2980 * in wgetch(), at which time the log thread will run.
2982 if (!wait)
2983 break;
2985 /* Display progress update in log view. */
2986 show_log_view(view);
2987 update_panels();
2988 doupdate();
2990 /* Wait right here while next commit is being loaded. */
2991 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2992 if (errcode)
2993 return got_error_set_errno(errcode,
2994 "pthread_cond_wait");
2996 /* Display progress update in log view. */
2997 show_log_view(view);
2998 update_panels();
2999 doupdate();
3002 return NULL;
3005 static const struct got_error *
3006 request_log_commits(struct tog_view *view)
3008 struct tog_log_view_state *state = &view->state.log;
3009 const struct got_error *err = NULL;
3011 if (state->thread_args.log_complete)
3012 return NULL;
3014 state->thread_args.commits_needed += view->nscrolled;
3015 err = trigger_log_thread(view, 1);
3016 view->nscrolled = 0;
3018 return err;
3021 static const struct got_error *
3022 log_scroll_down(struct tog_view *view, int maxscroll)
3024 struct tog_log_view_state *s = &view->state.log;
3025 const struct got_error *err = NULL;
3026 struct commit_queue_entry *pentry;
3027 int nscrolled = 0, ncommits_needed;
3029 if (s->last_displayed_entry == NULL)
3030 return NULL;
3032 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3033 if (s->commits->ncommits < ncommits_needed &&
3034 !s->thread_args.log_complete) {
3036 * Ask the log thread for required amount of commits.
3038 s->thread_args.commits_needed +=
3039 ncommits_needed - s->commits->ncommits;
3040 err = trigger_log_thread(view, 1);
3041 if (err)
3042 return err;
3045 do {
3046 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3047 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3048 break;
3050 s->last_displayed_entry = pentry ?
3051 pentry : s->last_displayed_entry;
3053 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3054 if (pentry == NULL)
3055 break;
3056 s->first_displayed_entry = pentry;
3057 } while (++nscrolled < maxscroll);
3059 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3060 view->nscrolled += nscrolled;
3061 else
3062 view->nscrolled = 0;
3064 return err;
3067 static const struct got_error *
3068 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3069 struct got_commit_object *commit, struct got_object_id *commit_id,
3070 struct tog_view *log_view, struct got_repository *repo)
3072 const struct got_error *err;
3073 struct got_object_qid *parent_id;
3074 struct tog_view *diff_view;
3076 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3077 if (diff_view == NULL)
3078 return got_error_from_errno("view_open");
3080 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3081 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3082 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3083 if (err == NULL)
3084 *new_view = diff_view;
3085 return err;
3088 static const struct got_error *
3089 tree_view_visit_subtree(struct tog_tree_view_state *s,
3090 struct got_tree_object *subtree)
3092 struct tog_parent_tree *parent;
3094 parent = calloc(1, sizeof(*parent));
3095 if (parent == NULL)
3096 return got_error_from_errno("calloc");
3098 parent->tree = s->tree;
3099 parent->first_displayed_entry = s->first_displayed_entry;
3100 parent->selected_entry = s->selected_entry;
3101 parent->selected = s->selected;
3102 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3103 s->tree = subtree;
3104 s->selected = 0;
3105 s->first_displayed_entry = NULL;
3106 return NULL;
3109 static const struct got_error *
3110 tree_view_walk_path(struct tog_tree_view_state *s,
3111 struct got_commit_object *commit, const char *path)
3113 const struct got_error *err = NULL;
3114 struct got_tree_object *tree = NULL;
3115 const char *p;
3116 char *slash, *subpath = NULL;
3118 /* Walk the path and open corresponding tree objects. */
3119 p = path;
3120 while (*p) {
3121 struct got_tree_entry *te;
3122 struct got_object_id *tree_id;
3123 char *te_name;
3125 while (p[0] == '/')
3126 p++;
3128 /* Ensure the correct subtree entry is selected. */
3129 slash = strchr(p, '/');
3130 if (slash == NULL)
3131 te_name = strdup(p);
3132 else
3133 te_name = strndup(p, slash - p);
3134 if (te_name == NULL) {
3135 err = got_error_from_errno("strndup");
3136 break;
3138 te = got_object_tree_find_entry(s->tree, te_name);
3139 if (te == NULL) {
3140 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3141 free(te_name);
3142 break;
3144 free(te_name);
3145 s->first_displayed_entry = s->selected_entry = te;
3147 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3148 break; /* jump to this file's entry */
3150 slash = strchr(p, '/');
3151 if (slash)
3152 subpath = strndup(path, slash - path);
3153 else
3154 subpath = strdup(path);
3155 if (subpath == NULL) {
3156 err = got_error_from_errno("strdup");
3157 break;
3160 err = got_object_id_by_path(&tree_id, s->repo, commit,
3161 subpath);
3162 if (err)
3163 break;
3165 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3166 free(tree_id);
3167 if (err)
3168 break;
3170 err = tree_view_visit_subtree(s, tree);
3171 if (err) {
3172 got_object_tree_close(tree);
3173 break;
3175 if (slash == NULL)
3176 break;
3177 free(subpath);
3178 subpath = NULL;
3179 p = slash;
3182 free(subpath);
3183 return err;
3186 static const struct got_error *
3187 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3188 struct commit_queue_entry *entry, const char *path,
3189 const char *head_ref_name, struct got_repository *repo)
3191 const struct got_error *err = NULL;
3192 struct tog_tree_view_state *s;
3193 struct tog_view *tree_view;
3195 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3196 if (tree_view == NULL)
3197 return got_error_from_errno("view_open");
3199 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3200 if (err)
3201 return err;
3202 s = &tree_view->state.tree;
3204 *new_view = tree_view;
3206 if (got_path_is_root_dir(path))
3207 return NULL;
3209 return tree_view_walk_path(s, entry->commit, path);
3212 static const struct got_error *
3213 block_signals_used_by_main_thread(void)
3215 sigset_t sigset;
3216 int errcode;
3218 if (sigemptyset(&sigset) == -1)
3219 return got_error_from_errno("sigemptyset");
3221 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3222 if (sigaddset(&sigset, SIGWINCH) == -1)
3223 return got_error_from_errno("sigaddset");
3224 if (sigaddset(&sigset, SIGCONT) == -1)
3225 return got_error_from_errno("sigaddset");
3226 if (sigaddset(&sigset, SIGINT) == -1)
3227 return got_error_from_errno("sigaddset");
3228 if (sigaddset(&sigset, SIGTERM) == -1)
3229 return got_error_from_errno("sigaddset");
3231 /* ncurses handles SIGTSTP */
3232 if (sigaddset(&sigset, SIGTSTP) == -1)
3233 return got_error_from_errno("sigaddset");
3235 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3236 if (errcode)
3237 return got_error_set_errno(errcode, "pthread_sigmask");
3239 return NULL;
3242 static void *
3243 log_thread(void *arg)
3245 const struct got_error *err = NULL;
3246 int errcode = 0;
3247 struct tog_log_thread_args *a = arg;
3248 int done = 0;
3251 * Sync startup with main thread such that we begin our
3252 * work once view_input() has released the mutex.
3254 errcode = pthread_mutex_lock(&tog_mutex);
3255 if (errcode) {
3256 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3257 return (void *)err;
3260 err = block_signals_used_by_main_thread();
3261 if (err) {
3262 pthread_mutex_unlock(&tog_mutex);
3263 goto done;
3266 while (!done && !err && !tog_fatal_signal_received()) {
3267 errcode = pthread_mutex_unlock(&tog_mutex);
3268 if (errcode) {
3269 err = got_error_set_errno(errcode,
3270 "pthread_mutex_unlock");
3271 goto done;
3273 err = queue_commits(a);
3274 if (err) {
3275 if (err->code != GOT_ERR_ITER_COMPLETED)
3276 goto done;
3277 err = NULL;
3278 done = 1;
3279 } else if (a->commits_needed > 0 && !a->load_all) {
3280 if (*a->limiting) {
3281 if (a->limit_match)
3282 a->commits_needed--;
3283 } else
3284 a->commits_needed--;
3287 errcode = pthread_mutex_lock(&tog_mutex);
3288 if (errcode) {
3289 err = got_error_set_errno(errcode,
3290 "pthread_mutex_lock");
3291 goto done;
3292 } else if (*a->quit)
3293 done = 1;
3294 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3295 *a->first_displayed_entry =
3296 TAILQ_FIRST(&a->limit_commits->head);
3297 *a->selected_entry = *a->first_displayed_entry;
3298 } else if (*a->first_displayed_entry == NULL) {
3299 *a->first_displayed_entry =
3300 TAILQ_FIRST(&a->real_commits->head);
3301 *a->selected_entry = *a->first_displayed_entry;
3304 errcode = pthread_cond_signal(&a->commit_loaded);
3305 if (errcode) {
3306 err = got_error_set_errno(errcode,
3307 "pthread_cond_signal");
3308 pthread_mutex_unlock(&tog_mutex);
3309 goto done;
3312 if (done)
3313 a->commits_needed = 0;
3314 else {
3315 if (a->commits_needed == 0 && !a->load_all) {
3316 errcode = pthread_cond_wait(&a->need_commits,
3317 &tog_mutex);
3318 if (errcode) {
3319 err = got_error_set_errno(errcode,
3320 "pthread_cond_wait");
3321 pthread_mutex_unlock(&tog_mutex);
3322 goto done;
3324 if (*a->quit)
3325 done = 1;
3329 a->log_complete = 1;
3330 errcode = pthread_mutex_unlock(&tog_mutex);
3331 if (errcode)
3332 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3333 done:
3334 if (err) {
3335 tog_thread_error = 1;
3336 pthread_cond_signal(&a->commit_loaded);
3338 return (void *)err;
3341 static const struct got_error *
3342 stop_log_thread(struct tog_log_view_state *s)
3344 const struct got_error *err = NULL, *thread_err = NULL;
3345 int errcode;
3347 if (s->thread) {
3348 s->quit = 1;
3349 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3350 if (errcode)
3351 return got_error_set_errno(errcode,
3352 "pthread_cond_signal");
3353 errcode = pthread_mutex_unlock(&tog_mutex);
3354 if (errcode)
3355 return got_error_set_errno(errcode,
3356 "pthread_mutex_unlock");
3357 errcode = pthread_join(s->thread, (void **)&thread_err);
3358 if (errcode)
3359 return got_error_set_errno(errcode, "pthread_join");
3360 errcode = pthread_mutex_lock(&tog_mutex);
3361 if (errcode)
3362 return got_error_set_errno(errcode,
3363 "pthread_mutex_lock");
3364 s->thread = 0; //NULL;
3367 if (s->thread_args.repo) {
3368 err = got_repo_close(s->thread_args.repo);
3369 s->thread_args.repo = NULL;
3372 if (s->thread_args.pack_fds) {
3373 const struct got_error *pack_err =
3374 got_repo_pack_fds_close(s->thread_args.pack_fds);
3375 if (err == NULL)
3376 err = pack_err;
3377 s->thread_args.pack_fds = NULL;
3380 if (s->thread_args.graph) {
3381 got_commit_graph_close(s->thread_args.graph);
3382 s->thread_args.graph = NULL;
3385 return err ? err : thread_err;
3388 static const struct got_error *
3389 close_log_view(struct tog_view *view)
3391 const struct got_error *err = NULL;
3392 struct tog_log_view_state *s = &view->state.log;
3393 int errcode;
3395 err = stop_log_thread(s);
3397 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3398 if (errcode && err == NULL)
3399 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3401 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3402 if (errcode && err == NULL)
3403 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3405 free_commits(&s->limit_commits);
3406 free_commits(&s->real_commits);
3407 free(s->in_repo_path);
3408 s->in_repo_path = NULL;
3409 free(s->start_id);
3410 s->start_id = NULL;
3411 free(s->head_ref_name);
3412 s->head_ref_name = NULL;
3413 return err;
3417 * We use two queues to implement the limit feature: first consists of
3418 * commits matching the current limit_regex; second is the real queue
3419 * of all known commits (real_commits). When the user starts limiting,
3420 * we swap queues such that all movement and displaying functionality
3421 * works with very slight change.
3423 static const struct got_error *
3424 limit_log_view(struct tog_view *view)
3426 struct tog_log_view_state *s = &view->state.log;
3427 struct commit_queue_entry *entry;
3428 struct tog_view *v = view;
3429 const struct got_error *err = NULL;
3430 char pattern[1024];
3431 int ret;
3433 if (view_is_hsplit_top(view))
3434 v = view->child;
3435 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3436 v = view->parent;
3438 /* Get the pattern */
3439 wmove(v->window, v->nlines - 1, 0);
3440 wclrtoeol(v->window);
3441 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3442 nodelay(v->window, FALSE);
3443 nocbreak();
3444 echo();
3445 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3446 cbreak();
3447 noecho();
3448 nodelay(v->window, TRUE);
3449 if (ret == ERR)
3450 return NULL;
3452 if (*pattern == '\0') {
3454 * Safety measure for the situation where the user
3455 * resets limit without previously limiting anything.
3457 if (!s->limit_view)
3458 return NULL;
3461 * User could have pressed Ctrl+L, which refreshed the
3462 * commit queues, it means we can't save previously
3463 * (before limit took place) displayed entries,
3464 * because they would point to already free'ed memory,
3465 * so we are forced to always select first entry of
3466 * the queue.
3468 s->commits = &s->real_commits;
3469 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3470 s->selected_entry = s->first_displayed_entry;
3471 s->selected = 0;
3472 s->limit_view = 0;
3474 return NULL;
3477 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3478 return NULL;
3480 s->limit_view = 1;
3482 /* Clear the screen while loading limit view */
3483 s->first_displayed_entry = NULL;
3484 s->last_displayed_entry = NULL;
3485 s->selected_entry = NULL;
3486 s->commits = &s->limit_commits;
3488 /* Prepare limit queue for new search */
3489 free_commits(&s->limit_commits);
3490 s->limit_commits.ncommits = 0;
3492 /* First process commits, which are in queue already */
3493 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3494 int have_match = 0;
3496 err = match_commit(&have_match, entry->id,
3497 entry->commit, &s->limit_regex);
3498 if (err)
3499 return err;
3501 if (have_match) {
3502 struct commit_queue_entry *matched;
3504 matched = alloc_commit_queue_entry(entry->commit,
3505 entry->id);
3506 if (matched == NULL) {
3507 err = got_error_from_errno(
3508 "alloc_commit_queue_entry");
3509 break;
3511 matched->commit = entry->commit;
3512 got_object_commit_retain(entry->commit);
3514 matched->idx = s->limit_commits.ncommits;
3515 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3516 matched, entry);
3517 s->limit_commits.ncommits++;
3521 /* Second process all the commits, until we fill the screen */
3522 if (s->limit_commits.ncommits < view->nlines - 1 &&
3523 !s->thread_args.log_complete) {
3524 s->thread_args.commits_needed +=
3525 view->nlines - s->limit_commits.ncommits - 1;
3526 err = trigger_log_thread(view, 1);
3527 if (err)
3528 return err;
3531 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3532 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3533 s->selected = 0;
3535 return NULL;
3538 static const struct got_error *
3539 search_start_log_view(struct tog_view *view)
3541 struct tog_log_view_state *s = &view->state.log;
3543 s->matched_entry = NULL;
3544 s->search_entry = NULL;
3545 return NULL;
3548 static const struct got_error *
3549 search_next_log_view(struct tog_view *view)
3551 const struct got_error *err = NULL;
3552 struct tog_log_view_state *s = &view->state.log;
3553 struct commit_queue_entry *entry;
3555 /* Display progress update in log view. */
3556 show_log_view(view);
3557 update_panels();
3558 doupdate();
3560 if (s->search_entry) {
3561 int errcode, ch;
3562 errcode = pthread_mutex_unlock(&tog_mutex);
3563 if (errcode)
3564 return got_error_set_errno(errcode,
3565 "pthread_mutex_unlock");
3566 ch = wgetch(view->window);
3567 errcode = pthread_mutex_lock(&tog_mutex);
3568 if (errcode)
3569 return got_error_set_errno(errcode,
3570 "pthread_mutex_lock");
3571 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3572 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3573 return NULL;
3575 if (view->searching == TOG_SEARCH_FORWARD)
3576 entry = TAILQ_NEXT(s->search_entry, entry);
3577 else
3578 entry = TAILQ_PREV(s->search_entry,
3579 commit_queue_head, entry);
3580 } else if (s->matched_entry) {
3582 * If the user has moved the cursor after we hit a match,
3583 * the position from where we should continue searching
3584 * might have changed.
3586 if (view->searching == TOG_SEARCH_FORWARD)
3587 entry = TAILQ_NEXT(s->selected_entry, entry);
3588 else
3589 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3590 entry);
3591 } else {
3592 entry = s->selected_entry;
3595 while (1) {
3596 int have_match = 0;
3598 if (entry == NULL) {
3599 if (s->thread_args.log_complete ||
3600 view->searching == TOG_SEARCH_BACKWARD) {
3601 view->search_next_done =
3602 (s->matched_entry == NULL ?
3603 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3604 s->search_entry = NULL;
3605 return NULL;
3608 * Poke the log thread for more commits and return,
3609 * allowing the main loop to make progress. Search
3610 * will resume at s->search_entry once we come back.
3612 s->thread_args.commits_needed++;
3613 return trigger_log_thread(view, 0);
3616 err = match_commit(&have_match, entry->id, entry->commit,
3617 &view->regex);
3618 if (err)
3619 break;
3620 if (have_match) {
3621 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3622 s->matched_entry = entry;
3623 break;
3626 s->search_entry = entry;
3627 if (view->searching == TOG_SEARCH_FORWARD)
3628 entry = TAILQ_NEXT(entry, entry);
3629 else
3630 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3633 if (s->matched_entry) {
3634 int cur = s->selected_entry->idx;
3635 while (cur < s->matched_entry->idx) {
3636 err = input_log_view(NULL, view, KEY_DOWN);
3637 if (err)
3638 return err;
3639 cur++;
3641 while (cur > s->matched_entry->idx) {
3642 err = input_log_view(NULL, view, KEY_UP);
3643 if (err)
3644 return err;
3645 cur--;
3649 s->search_entry = NULL;
3651 return NULL;
3654 static const struct got_error *
3655 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3656 struct got_repository *repo, const char *head_ref_name,
3657 const char *in_repo_path, int log_branches)
3659 const struct got_error *err = NULL;
3660 struct tog_log_view_state *s = &view->state.log;
3661 struct got_repository *thread_repo = NULL;
3662 struct got_commit_graph *thread_graph = NULL;
3663 int errcode;
3665 if (in_repo_path != s->in_repo_path) {
3666 free(s->in_repo_path);
3667 s->in_repo_path = strdup(in_repo_path);
3668 if (s->in_repo_path == NULL) {
3669 err = got_error_from_errno("strdup");
3670 goto done;
3674 /* The commit queue only contains commits being displayed. */
3675 TAILQ_INIT(&s->real_commits.head);
3676 s->real_commits.ncommits = 0;
3677 s->commits = &s->real_commits;
3679 TAILQ_INIT(&s->limit_commits.head);
3680 s->limit_view = 0;
3681 s->limit_commits.ncommits = 0;
3683 s->repo = repo;
3684 if (head_ref_name) {
3685 s->head_ref_name = strdup(head_ref_name);
3686 if (s->head_ref_name == NULL) {
3687 err = got_error_from_errno("strdup");
3688 goto done;
3691 s->start_id = got_object_id_dup(start_id);
3692 if (s->start_id == NULL) {
3693 err = got_error_from_errno("got_object_id_dup");
3694 goto done;
3696 s->log_branches = log_branches;
3697 s->use_committer = 1;
3699 STAILQ_INIT(&s->colors);
3700 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3701 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3702 get_color_value("TOG_COLOR_COMMIT"));
3703 if (err)
3704 goto done;
3705 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3706 get_color_value("TOG_COLOR_AUTHOR"));
3707 if (err) {
3708 free_colors(&s->colors);
3709 goto done;
3711 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3712 get_color_value("TOG_COLOR_DATE"));
3713 if (err) {
3714 free_colors(&s->colors);
3715 goto done;
3719 view->show = show_log_view;
3720 view->input = input_log_view;
3721 view->resize = resize_log_view;
3722 view->close = close_log_view;
3723 view->search_start = search_start_log_view;
3724 view->search_next = search_next_log_view;
3726 if (s->thread_args.pack_fds == NULL) {
3727 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3728 if (err)
3729 goto done;
3731 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3732 s->thread_args.pack_fds);
3733 if (err)
3734 goto done;
3735 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3736 !s->log_branches);
3737 if (err)
3738 goto done;
3739 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3740 s->repo, NULL, NULL);
3741 if (err)
3742 goto done;
3744 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3745 if (errcode) {
3746 err = got_error_set_errno(errcode, "pthread_cond_init");
3747 goto done;
3749 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3750 if (errcode) {
3751 err = got_error_set_errno(errcode, "pthread_cond_init");
3752 goto done;
3755 s->thread_args.commits_needed = view->nlines;
3756 s->thread_args.graph = thread_graph;
3757 s->thread_args.real_commits = &s->real_commits;
3758 s->thread_args.limit_commits = &s->limit_commits;
3759 s->thread_args.in_repo_path = s->in_repo_path;
3760 s->thread_args.start_id = s->start_id;
3761 s->thread_args.repo = thread_repo;
3762 s->thread_args.log_complete = 0;
3763 s->thread_args.quit = &s->quit;
3764 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3765 s->thread_args.selected_entry = &s->selected_entry;
3766 s->thread_args.searching = &view->searching;
3767 s->thread_args.search_next_done = &view->search_next_done;
3768 s->thread_args.regex = &view->regex;
3769 s->thread_args.limiting = &s->limit_view;
3770 s->thread_args.limit_regex = &s->limit_regex;
3771 s->thread_args.limit_commits = &s->limit_commits;
3772 done:
3773 if (err) {
3774 if (view->close == NULL)
3775 close_log_view(view);
3776 view_close(view);
3778 return err;
3781 static const struct got_error *
3782 show_log_view(struct tog_view *view)
3784 const struct got_error *err;
3785 struct tog_log_view_state *s = &view->state.log;
3787 if (s->thread == 0) { //NULL) {
3788 int errcode = pthread_create(&s->thread, NULL, log_thread,
3789 &s->thread_args);
3790 if (errcode)
3791 return got_error_set_errno(errcode, "pthread_create");
3792 if (s->thread_args.commits_needed > 0) {
3793 err = trigger_log_thread(view, 1);
3794 if (err)
3795 return err;
3799 return draw_commits(view);
3802 static void
3803 log_move_cursor_up(struct tog_view *view, int page, int home)
3805 struct tog_log_view_state *s = &view->state.log;
3807 if (s->first_displayed_entry == NULL)
3808 return;
3809 if (s->selected_entry->idx == 0)
3810 view->count = 0;
3812 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3813 || home)
3814 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3816 if (!page && !home && s->selected > 0)
3817 --s->selected;
3818 else
3819 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3821 select_commit(s);
3822 return;
3825 static const struct got_error *
3826 log_move_cursor_down(struct tog_view *view, int page)
3828 struct tog_log_view_state *s = &view->state.log;
3829 const struct got_error *err = NULL;
3830 int eos = view->nlines - 2;
3832 if (s->first_displayed_entry == NULL)
3833 return NULL;
3835 if (s->thread_args.log_complete &&
3836 s->selected_entry->idx >= s->commits->ncommits - 1)
3837 return NULL;
3839 if (view_is_hsplit_top(view))
3840 --eos; /* border consumes the last line */
3842 if (!page) {
3843 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3844 ++s->selected;
3845 else
3846 err = log_scroll_down(view, 1);
3847 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3848 struct commit_queue_entry *entry;
3849 int n;
3851 s->selected = 0;
3852 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3853 s->last_displayed_entry = entry;
3854 for (n = 0; n <= eos; n++) {
3855 if (entry == NULL)
3856 break;
3857 s->first_displayed_entry = entry;
3858 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3860 if (n > 0)
3861 s->selected = n - 1;
3862 } else {
3863 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3864 s->thread_args.log_complete)
3865 s->selected += MIN(page,
3866 s->commits->ncommits - s->selected_entry->idx - 1);
3867 else
3868 err = log_scroll_down(view, page);
3870 if (err)
3871 return err;
3874 * We might necessarily overshoot in horizontal
3875 * splits; if so, select the last displayed commit.
3877 if (s->first_displayed_entry && s->last_displayed_entry) {
3878 s->selected = MIN(s->selected,
3879 s->last_displayed_entry->idx -
3880 s->first_displayed_entry->idx);
3883 select_commit(s);
3885 if (s->thread_args.log_complete &&
3886 s->selected_entry->idx == s->commits->ncommits - 1)
3887 view->count = 0;
3889 return NULL;
3892 static void
3893 view_get_split(struct tog_view *view, int *y, int *x)
3895 *x = 0;
3896 *y = 0;
3898 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3899 if (view->child && view->child->resized_y)
3900 *y = view->child->resized_y;
3901 else if (view->resized_y)
3902 *y = view->resized_y;
3903 else
3904 *y = view_split_begin_y(view->lines);
3905 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3906 if (view->child && view->child->resized_x)
3907 *x = view->child->resized_x;
3908 else if (view->resized_x)
3909 *x = view->resized_x;
3910 else
3911 *x = view_split_begin_x(view->begin_x);
3915 /* Split view horizontally at y and offset view->state->selected line. */
3916 static const struct got_error *
3917 view_init_hsplit(struct tog_view *view, int y)
3919 const struct got_error *err = NULL;
3921 view->nlines = y;
3922 view->ncols = COLS;
3923 err = view_resize(view);
3924 if (err)
3925 return err;
3927 err = offset_selection_down(view);
3929 return err;
3932 static const struct got_error *
3933 log_goto_line(struct tog_view *view, int nlines)
3935 const struct got_error *err = NULL;
3936 struct tog_log_view_state *s = &view->state.log;
3937 int g, idx = s->selected_entry->idx;
3939 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3940 return NULL;
3942 g = view->gline;
3943 view->gline = 0;
3945 if (g >= s->first_displayed_entry->idx + 1 &&
3946 g <= s->last_displayed_entry->idx + 1 &&
3947 g - s->first_displayed_entry->idx - 1 < nlines) {
3948 s->selected = g - s->first_displayed_entry->idx - 1;
3949 select_commit(s);
3950 return NULL;
3953 if (idx + 1 < g) {
3954 err = log_move_cursor_down(view, g - idx - 1);
3955 if (!err && g > s->selected_entry->idx + 1)
3956 err = log_move_cursor_down(view,
3957 g - s->first_displayed_entry->idx - 1);
3958 if (err)
3959 return err;
3960 } else if (idx + 1 > g)
3961 log_move_cursor_up(view, idx - g + 1, 0);
3963 if (g < nlines && s->first_displayed_entry->idx == 0)
3964 s->selected = g - 1;
3966 select_commit(s);
3967 return NULL;
3971 static void
3972 horizontal_scroll_input(struct tog_view *view, int ch)
3975 switch (ch) {
3976 case KEY_LEFT:
3977 case 'h':
3978 view->x -= MIN(view->x, 2);
3979 if (view->x <= 0)
3980 view->count = 0;
3981 break;
3982 case KEY_RIGHT:
3983 case 'l':
3984 if (view->x + view->ncols / 2 < view->maxx)
3985 view->x += 2;
3986 else
3987 view->count = 0;
3988 break;
3989 case '0':
3990 view->x = 0;
3991 break;
3992 case '$':
3993 view->x = MAX(view->maxx - view->ncols / 2, 0);
3994 view->count = 0;
3995 break;
3996 default:
3997 break;
4001 static const struct got_error *
4002 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4004 const struct got_error *err = NULL;
4005 struct tog_log_view_state *s = &view->state.log;
4006 int eos, nscroll;
4008 if (s->thread_args.load_all) {
4009 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4010 s->thread_args.load_all = 0;
4011 else if (s->thread_args.log_complete) {
4012 err = log_move_cursor_down(view, s->commits->ncommits);
4013 s->thread_args.load_all = 0;
4015 if (err)
4016 return err;
4019 eos = nscroll = view->nlines - 1;
4020 if (view_is_hsplit_top(view))
4021 --eos; /* border */
4023 if (view->gline)
4024 return log_goto_line(view, eos);
4026 switch (ch) {
4027 case '&':
4028 err = limit_log_view(view);
4029 break;
4030 case 'q':
4031 s->quit = 1;
4032 break;
4033 case '0':
4034 case '$':
4035 case KEY_RIGHT:
4036 case 'l':
4037 case KEY_LEFT:
4038 case 'h':
4039 horizontal_scroll_input(view, ch);
4040 break;
4041 case 'k':
4042 case KEY_UP:
4043 case '<':
4044 case ',':
4045 case CTRL('p'):
4046 log_move_cursor_up(view, 0, 0);
4047 break;
4048 case 'g':
4049 case '=':
4050 case KEY_HOME:
4051 log_move_cursor_up(view, 0, 1);
4052 view->count = 0;
4053 break;
4054 case CTRL('u'):
4055 case 'u':
4056 nscroll /= 2;
4057 /* FALL THROUGH */
4058 case KEY_PPAGE:
4059 case CTRL('b'):
4060 case 'b':
4061 log_move_cursor_up(view, nscroll, 0);
4062 break;
4063 case 'j':
4064 case KEY_DOWN:
4065 case '>':
4066 case '.':
4067 case CTRL('n'):
4068 err = log_move_cursor_down(view, 0);
4069 break;
4070 case '@':
4071 s->use_committer = !s->use_committer;
4072 view->action = s->use_committer ?
4073 "show committer" : "show commit author";
4074 break;
4075 case 'G':
4076 case '*':
4077 case KEY_END: {
4078 /* We don't know yet how many commits, so we're forced to
4079 * traverse them all. */
4080 view->count = 0;
4081 s->thread_args.load_all = 1;
4082 if (!s->thread_args.log_complete)
4083 return trigger_log_thread(view, 0);
4084 err = log_move_cursor_down(view, s->commits->ncommits);
4085 s->thread_args.load_all = 0;
4086 break;
4088 case CTRL('d'):
4089 case 'd':
4090 nscroll /= 2;
4091 /* FALL THROUGH */
4092 case KEY_NPAGE:
4093 case CTRL('f'):
4094 case 'f':
4095 case ' ':
4096 err = log_move_cursor_down(view, nscroll);
4097 break;
4098 case KEY_RESIZE:
4099 if (s->selected > view->nlines - 2)
4100 s->selected = view->nlines - 2;
4101 if (s->selected > s->commits->ncommits - 1)
4102 s->selected = s->commits->ncommits - 1;
4103 select_commit(s);
4104 if (s->commits->ncommits < view->nlines - 1 &&
4105 !s->thread_args.log_complete) {
4106 s->thread_args.commits_needed += (view->nlines - 1) -
4107 s->commits->ncommits;
4108 err = trigger_log_thread(view, 1);
4110 break;
4111 case KEY_ENTER:
4112 case '\r':
4113 view->count = 0;
4114 if (s->selected_entry == NULL)
4115 break;
4116 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4117 break;
4118 case 'T':
4119 view->count = 0;
4120 if (s->selected_entry == NULL)
4121 break;
4122 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4123 break;
4124 case KEY_BACKSPACE:
4125 case CTRL('l'):
4126 case 'B':
4127 view->count = 0;
4128 if (ch == KEY_BACKSPACE &&
4129 got_path_is_root_dir(s->in_repo_path))
4130 break;
4131 err = stop_log_thread(s);
4132 if (err)
4133 return err;
4134 if (ch == KEY_BACKSPACE) {
4135 char *parent_path;
4136 err = got_path_dirname(&parent_path, s->in_repo_path);
4137 if (err)
4138 return err;
4139 free(s->in_repo_path);
4140 s->in_repo_path = parent_path;
4141 s->thread_args.in_repo_path = s->in_repo_path;
4142 } else if (ch == CTRL('l')) {
4143 struct got_object_id *start_id;
4144 err = got_repo_match_object_id(&start_id, NULL,
4145 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4146 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4147 if (err) {
4148 if (s->head_ref_name == NULL ||
4149 err->code != GOT_ERR_NOT_REF)
4150 return err;
4151 /* Try to cope with deleted references. */
4152 free(s->head_ref_name);
4153 s->head_ref_name = NULL;
4154 err = got_repo_match_object_id(&start_id,
4155 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4156 &tog_refs, s->repo);
4157 if (err)
4158 return err;
4160 free(s->start_id);
4161 s->start_id = start_id;
4162 s->thread_args.start_id = s->start_id;
4163 } else /* 'B' */
4164 s->log_branches = !s->log_branches;
4166 if (s->thread_args.pack_fds == NULL) {
4167 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4168 if (err)
4169 return err;
4171 err = got_repo_open(&s->thread_args.repo,
4172 got_repo_get_path(s->repo), NULL,
4173 s->thread_args.pack_fds);
4174 if (err)
4175 return err;
4176 tog_free_refs();
4177 err = tog_load_refs(s->repo, 0);
4178 if (err)
4179 return err;
4180 err = got_commit_graph_open(&s->thread_args.graph,
4181 s->in_repo_path, !s->log_branches);
4182 if (err)
4183 return err;
4184 err = got_commit_graph_iter_start(s->thread_args.graph,
4185 s->start_id, s->repo, NULL, NULL);
4186 if (err)
4187 return err;
4188 free_commits(&s->real_commits);
4189 free_commits(&s->limit_commits);
4190 s->first_displayed_entry = NULL;
4191 s->last_displayed_entry = NULL;
4192 s->selected_entry = NULL;
4193 s->selected = 0;
4194 s->thread_args.log_complete = 0;
4195 s->quit = 0;
4196 s->thread_args.commits_needed = view->lines;
4197 s->matched_entry = NULL;
4198 s->search_entry = NULL;
4199 view->offset = 0;
4200 break;
4201 case 'R':
4202 view->count = 0;
4203 err = view_request_new(new_view, view, TOG_VIEW_REF);
4204 break;
4205 default:
4206 view->count = 0;
4207 break;
4210 return err;
4213 static const struct got_error *
4214 apply_unveil(const char *repo_path, const char *worktree_path)
4216 const struct got_error *error;
4218 #ifdef PROFILE
4219 if (unveil("gmon.out", "rwc") != 0)
4220 return got_error_from_errno2("unveil", "gmon.out");
4221 #endif
4222 if (repo_path && unveil(repo_path, "r") != 0)
4223 return got_error_from_errno2("unveil", repo_path);
4225 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4226 return got_error_from_errno2("unveil", worktree_path);
4228 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4229 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4231 error = got_privsep_unveil_exec_helpers();
4232 if (error != NULL)
4233 return error;
4235 if (unveil(NULL, NULL) != 0)
4236 return got_error_from_errno("unveil");
4238 return NULL;
4241 static const struct got_error *
4242 init_mock_term(const char *test_script_path)
4244 const struct got_error *err = NULL;
4245 const char *screen_dump_path;
4246 int in;
4248 if (test_script_path == NULL || *test_script_path == '\0')
4249 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4251 tog_io.f = fopen(test_script_path, "re");
4252 if (tog_io.f == NULL) {
4253 err = got_error_from_errno_fmt("fopen: %s",
4254 test_script_path);
4255 goto done;
4258 /* test mode, we don't want any output */
4259 tog_io.cout = fopen("/dev/null", "w+");
4260 if (tog_io.cout == NULL) {
4261 err = got_error_from_errno2("fopen", "/dev/null");
4262 goto done;
4265 in = dup(fileno(tog_io.cout));
4266 if (in == -1) {
4267 err = got_error_from_errno("dup");
4268 goto done;
4270 tog_io.cin = fdopen(in, "r");
4271 if (tog_io.cin == NULL) {
4272 err = got_error_from_errno("fdopen");
4273 close(in);
4274 goto done;
4277 screen_dump_path = getenv("TOG_SCR_DUMP");
4278 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4279 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4280 tog_io.sdump = fopen(screen_dump_path, "wex");
4281 if (tog_io.sdump == NULL) {
4282 err = got_error_from_errno2("fopen", screen_dump_path);
4283 goto done;
4286 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4287 err = got_error_from_errno("fseeko");
4288 goto done;
4291 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4292 err = got_error_msg(GOT_ERR_IO,
4293 "newterm: failed to initialise curses");
4295 using_mock_io = 1;
4297 done:
4298 if (err)
4299 tog_io_close();
4300 return err;
4303 static void
4304 init_curses(void)
4307 * Override default signal handlers before starting ncurses.
4308 * This should prevent ncurses from installing its own
4309 * broken cleanup() signal handler.
4311 signal(SIGWINCH, tog_sigwinch);
4312 signal(SIGPIPE, tog_sigpipe);
4313 signal(SIGCONT, tog_sigcont);
4314 signal(SIGINT, tog_sigint);
4315 signal(SIGTERM, tog_sigterm);
4317 if (using_mock_io) /* In test mode we use a fake terminal */
4318 return;
4320 initscr();
4322 cbreak();
4323 halfdelay(1); /* Fast refresh while initial view is loading. */
4324 noecho();
4325 nonl();
4326 intrflush(stdscr, FALSE);
4327 keypad(stdscr, TRUE);
4328 curs_set(0);
4329 if (getenv("TOG_COLORS") != NULL) {
4330 start_color();
4331 use_default_colors();
4334 return;
4337 static const struct got_error *
4338 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4339 struct got_repository *repo, struct got_worktree *worktree)
4341 const struct got_error *err = NULL;
4343 if (argc == 0) {
4344 *in_repo_path = strdup("/");
4345 if (*in_repo_path == NULL)
4346 return got_error_from_errno("strdup");
4347 return NULL;
4350 if (worktree) {
4351 const char *prefix = got_worktree_get_path_prefix(worktree);
4352 char *p;
4354 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4355 if (err)
4356 return err;
4357 if (asprintf(in_repo_path, "%s%s%s", prefix,
4358 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4359 p) == -1) {
4360 err = got_error_from_errno("asprintf");
4361 *in_repo_path = NULL;
4363 free(p);
4364 } else
4365 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4367 return err;
4370 static const struct got_error *
4371 cmd_log(int argc, char *argv[])
4373 const struct got_error *error;
4374 struct got_repository *repo = NULL;
4375 struct got_worktree *worktree = NULL;
4376 struct got_object_id *start_id = NULL;
4377 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4378 char *start_commit = NULL, *label = NULL;
4379 struct got_reference *ref = NULL;
4380 const char *head_ref_name = NULL;
4381 int ch, log_branches = 0;
4382 struct tog_view *view;
4383 int *pack_fds = NULL;
4385 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4386 switch (ch) {
4387 case 'b':
4388 log_branches = 1;
4389 break;
4390 case 'c':
4391 start_commit = optarg;
4392 break;
4393 case 'r':
4394 repo_path = realpath(optarg, NULL);
4395 if (repo_path == NULL)
4396 return got_error_from_errno2("realpath",
4397 optarg);
4398 break;
4399 default:
4400 usage_log();
4401 /* NOTREACHED */
4405 argc -= optind;
4406 argv += optind;
4408 if (argc > 1)
4409 usage_log();
4411 error = got_repo_pack_fds_open(&pack_fds);
4412 if (error != NULL)
4413 goto done;
4415 if (repo_path == NULL) {
4416 cwd = getcwd(NULL, 0);
4417 if (cwd == NULL)
4418 return got_error_from_errno("getcwd");
4419 error = got_worktree_open(&worktree, cwd);
4420 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4421 goto done;
4422 if (worktree)
4423 repo_path =
4424 strdup(got_worktree_get_repo_path(worktree));
4425 else
4426 repo_path = strdup(cwd);
4427 if (repo_path == NULL) {
4428 error = got_error_from_errno("strdup");
4429 goto done;
4433 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4434 if (error != NULL)
4435 goto done;
4437 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4438 repo, worktree);
4439 if (error)
4440 goto done;
4442 init_curses();
4444 error = apply_unveil(got_repo_get_path(repo),
4445 worktree ? got_worktree_get_root_path(worktree) : NULL);
4446 if (error)
4447 goto done;
4449 /* already loaded by tog_log_with_path()? */
4450 if (TAILQ_EMPTY(&tog_refs)) {
4451 error = tog_load_refs(repo, 0);
4452 if (error)
4453 goto done;
4456 if (start_commit == NULL) {
4457 error = got_repo_match_object_id(&start_id, &label,
4458 worktree ? got_worktree_get_head_ref_name(worktree) :
4459 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4460 if (error)
4461 goto done;
4462 head_ref_name = label;
4463 } else {
4464 error = got_ref_open(&ref, repo, start_commit, 0);
4465 if (error == NULL)
4466 head_ref_name = got_ref_get_name(ref);
4467 else if (error->code != GOT_ERR_NOT_REF)
4468 goto done;
4469 error = got_repo_match_object_id(&start_id, NULL,
4470 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4471 if (error)
4472 goto done;
4475 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4476 if (view == NULL) {
4477 error = got_error_from_errno("view_open");
4478 goto done;
4480 error = open_log_view(view, start_id, repo, head_ref_name,
4481 in_repo_path, log_branches);
4482 if (error)
4483 goto done;
4484 if (worktree) {
4485 /* Release work tree lock. */
4486 got_worktree_close(worktree);
4487 worktree = NULL;
4489 error = view_loop(view);
4490 done:
4491 free(in_repo_path);
4492 free(repo_path);
4493 free(cwd);
4494 free(start_id);
4495 free(label);
4496 if (ref)
4497 got_ref_close(ref);
4498 if (repo) {
4499 const struct got_error *close_err = got_repo_close(repo);
4500 if (error == NULL)
4501 error = close_err;
4503 if (worktree)
4504 got_worktree_close(worktree);
4505 if (pack_fds) {
4506 const struct got_error *pack_err =
4507 got_repo_pack_fds_close(pack_fds);
4508 if (error == NULL)
4509 error = pack_err;
4511 tog_free_refs();
4512 return error;
4515 __dead static void
4516 usage_diff(void)
4518 endwin();
4519 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4520 "object1 object2\n", getprogname());
4521 exit(1);
4524 static int
4525 match_line(const char *line, regex_t *regex, size_t nmatch,
4526 regmatch_t *regmatch)
4528 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4531 static struct tog_color *
4532 match_color(struct tog_colors *colors, const char *line)
4534 struct tog_color *tc = NULL;
4536 STAILQ_FOREACH(tc, colors, entry) {
4537 if (match_line(line, &tc->regex, 0, NULL))
4538 return tc;
4541 return NULL;
4544 static const struct got_error *
4545 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4546 WINDOW *window, int skipcol, regmatch_t *regmatch)
4548 const struct got_error *err = NULL;
4549 char *exstr = NULL;
4550 wchar_t *wline = NULL;
4551 int rme, rms, n, width, scrollx;
4552 int width0 = 0, width1 = 0, width2 = 0;
4553 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4555 *wtotal = 0;
4557 rms = regmatch->rm_so;
4558 rme = regmatch->rm_eo;
4560 err = expand_tab(&exstr, line);
4561 if (err)
4562 return err;
4564 /* Split the line into 3 segments, according to match offsets. */
4565 seg0 = strndup(exstr, rms);
4566 if (seg0 == NULL) {
4567 err = got_error_from_errno("strndup");
4568 goto done;
4570 seg1 = strndup(exstr + rms, rme - rms);
4571 if (seg1 == NULL) {
4572 err = got_error_from_errno("strndup");
4573 goto done;
4575 seg2 = strdup(exstr + rme);
4576 if (seg2 == NULL) {
4577 err = got_error_from_errno("strndup");
4578 goto done;
4581 /* draw up to matched token if we haven't scrolled past it */
4582 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4583 col_tab_align, 1);
4584 if (err)
4585 goto done;
4586 n = MAX(width0 - skipcol, 0);
4587 if (n) {
4588 free(wline);
4589 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4590 wlimit, col_tab_align, 1);
4591 if (err)
4592 goto done;
4593 waddwstr(window, &wline[scrollx]);
4594 wlimit -= width;
4595 *wtotal += width;
4598 if (wlimit > 0) {
4599 int i = 0, w = 0;
4600 size_t wlen;
4602 free(wline);
4603 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4604 col_tab_align, 1);
4605 if (err)
4606 goto done;
4607 wlen = wcslen(wline);
4608 while (i < wlen) {
4609 width = wcwidth(wline[i]);
4610 if (width == -1) {
4611 /* should not happen, tabs are expanded */
4612 err = got_error(GOT_ERR_RANGE);
4613 goto done;
4615 if (width0 + w + width > skipcol)
4616 break;
4617 w += width;
4618 i++;
4620 /* draw (visible part of) matched token (if scrolled into it) */
4621 if (width1 - w > 0) {
4622 wattron(window, A_STANDOUT);
4623 waddwstr(window, &wline[i]);
4624 wattroff(window, A_STANDOUT);
4625 wlimit -= (width1 - w);
4626 *wtotal += (width1 - w);
4630 if (wlimit > 0) { /* draw rest of line */
4631 free(wline);
4632 if (skipcol > width0 + width1) {
4633 err = format_line(&wline, &width2, &scrollx, seg2,
4634 skipcol - (width0 + width1), wlimit,
4635 col_tab_align, 1);
4636 if (err)
4637 goto done;
4638 waddwstr(window, &wline[scrollx]);
4639 } else {
4640 err = format_line(&wline, &width2, NULL, seg2, 0,
4641 wlimit, col_tab_align, 1);
4642 if (err)
4643 goto done;
4644 waddwstr(window, wline);
4646 *wtotal += width2;
4648 done:
4649 free(wline);
4650 free(exstr);
4651 free(seg0);
4652 free(seg1);
4653 free(seg2);
4654 return err;
4657 static int
4658 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4660 FILE *f = NULL;
4661 int *eof, *first, *selected;
4663 if (view->type == TOG_VIEW_DIFF) {
4664 struct tog_diff_view_state *s = &view->state.diff;
4666 first = &s->first_displayed_line;
4667 selected = first;
4668 eof = &s->eof;
4669 f = s->f;
4670 } else if (view->type == TOG_VIEW_HELP) {
4671 struct tog_help_view_state *s = &view->state.help;
4673 first = &s->first_displayed_line;
4674 selected = first;
4675 eof = &s->eof;
4676 f = s->f;
4677 } else if (view->type == TOG_VIEW_BLAME) {
4678 struct tog_blame_view_state *s = &view->state.blame;
4680 first = &s->first_displayed_line;
4681 selected = &s->selected_line;
4682 eof = &s->eof;
4683 f = s->blame.f;
4684 } else
4685 return 0;
4687 /* Center gline in the middle of the page like vi(1). */
4688 if (*lineno < view->gline - (view->nlines - 3) / 2)
4689 return 0;
4690 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4691 rewind(f);
4692 *eof = 0;
4693 *first = 1;
4694 *lineno = 0;
4695 *nprinted = 0;
4696 return 0;
4699 *selected = view->gline <= (view->nlines - 3) / 2 ?
4700 view->gline : (view->nlines - 3) / 2 + 1;
4701 view->gline = 0;
4703 return 1;
4706 static const struct got_error *
4707 draw_file(struct tog_view *view, const char *header)
4709 struct tog_diff_view_state *s = &view->state.diff;
4710 regmatch_t *regmatch = &view->regmatch;
4711 const struct got_error *err;
4712 int nprinted = 0;
4713 char *line;
4714 size_t linesize = 0;
4715 ssize_t linelen;
4716 wchar_t *wline;
4717 int width;
4718 int max_lines = view->nlines;
4719 int nlines = s->nlines;
4720 off_t line_offset;
4722 s->lineno = s->first_displayed_line - 1;
4723 line_offset = s->lines[s->first_displayed_line - 1].offset;
4724 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4725 return got_error_from_errno("fseek");
4727 werase(view->window);
4729 if (view->gline > s->nlines - 1)
4730 view->gline = s->nlines - 1;
4732 if (header) {
4733 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4734 1 : view->gline - (view->nlines - 3) / 2 :
4735 s->lineno + s->selected_line;
4737 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4738 return got_error_from_errno("asprintf");
4739 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4740 0, 0);
4741 free(line);
4742 if (err)
4743 return err;
4745 if (view_needs_focus_indication(view))
4746 wstandout(view->window);
4747 waddwstr(view->window, wline);
4748 free(wline);
4749 wline = NULL;
4750 while (width++ < view->ncols)
4751 waddch(view->window, ' ');
4752 if (view_needs_focus_indication(view))
4753 wstandend(view->window);
4755 if (max_lines <= 1)
4756 return NULL;
4757 max_lines--;
4760 s->eof = 0;
4761 view->maxx = 0;
4762 line = NULL;
4763 while (max_lines > 0 && nprinted < max_lines) {
4764 enum got_diff_line_type linetype;
4765 attr_t attr = 0;
4767 linelen = getline(&line, &linesize, s->f);
4768 if (linelen == -1) {
4769 if (feof(s->f)) {
4770 s->eof = 1;
4771 break;
4773 free(line);
4774 return got_ferror(s->f, GOT_ERR_IO);
4777 if (++s->lineno < s->first_displayed_line)
4778 continue;
4779 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4780 continue;
4781 if (s->lineno == view->hiline)
4782 attr = A_STANDOUT;
4784 /* Set view->maxx based on full line length. */
4785 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4786 view->x ? 1 : 0);
4787 if (err) {
4788 free(line);
4789 return err;
4791 view->maxx = MAX(view->maxx, width);
4792 free(wline);
4793 wline = NULL;
4795 linetype = s->lines[s->lineno].type;
4796 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4797 linetype < GOT_DIFF_LINE_CONTEXT)
4798 attr |= COLOR_PAIR(linetype);
4799 if (attr)
4800 wattron(view->window, attr);
4801 if (s->first_displayed_line + nprinted == s->matched_line &&
4802 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4803 err = add_matched_line(&width, line, view->ncols, 0,
4804 view->window, view->x, regmatch);
4805 if (err) {
4806 free(line);
4807 return err;
4809 } else {
4810 int skip;
4811 err = format_line(&wline, &width, &skip, line,
4812 view->x, view->ncols, 0, view->x ? 1 : 0);
4813 if (err) {
4814 free(line);
4815 return err;
4817 waddwstr(view->window, &wline[skip]);
4818 free(wline);
4819 wline = NULL;
4821 if (s->lineno == view->hiline) {
4822 /* highlight full gline length */
4823 while (width++ < view->ncols)
4824 waddch(view->window, ' ');
4825 } else {
4826 if (width <= view->ncols - 1)
4827 waddch(view->window, '\n');
4829 if (attr)
4830 wattroff(view->window, attr);
4831 if (++nprinted == 1)
4832 s->first_displayed_line = s->lineno;
4834 free(line);
4835 if (nprinted >= 1)
4836 s->last_displayed_line = s->first_displayed_line +
4837 (nprinted - 1);
4838 else
4839 s->last_displayed_line = s->first_displayed_line;
4841 view_border(view);
4843 if (s->eof) {
4844 while (nprinted < view->nlines) {
4845 waddch(view->window, '\n');
4846 nprinted++;
4849 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4850 view->ncols, 0, 0);
4851 if (err) {
4852 return err;
4855 wstandout(view->window);
4856 waddwstr(view->window, wline);
4857 free(wline);
4858 wline = NULL;
4859 wstandend(view->window);
4862 return NULL;
4865 static char *
4866 get_datestr(time_t *time, char *datebuf)
4868 struct tm mytm, *tm;
4869 char *p, *s;
4871 tm = gmtime_r(time, &mytm);
4872 if (tm == NULL)
4873 return NULL;
4874 s = asctime_r(tm, datebuf);
4875 if (s == NULL)
4876 return NULL;
4877 p = strchr(s, '\n');
4878 if (p)
4879 *p = '\0';
4880 return s;
4883 static const struct got_error *
4884 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4885 off_t off, uint8_t type)
4887 struct got_diff_line *p;
4889 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4890 if (p == NULL)
4891 return got_error_from_errno("reallocarray");
4892 *lines = p;
4893 (*lines)[*nlines].offset = off;
4894 (*lines)[*nlines].type = type;
4895 (*nlines)++;
4897 return NULL;
4900 static const struct got_error *
4901 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4902 struct got_diff_line *s_lines, size_t s_nlines)
4904 struct got_diff_line *p;
4905 char buf[BUFSIZ];
4906 size_t i, r;
4908 if (fseeko(src, 0L, SEEK_SET) == -1)
4909 return got_error_from_errno("fseeko");
4911 for (;;) {
4912 r = fread(buf, 1, sizeof(buf), src);
4913 if (r == 0) {
4914 if (ferror(src))
4915 return got_error_from_errno("fread");
4916 if (feof(src))
4917 break;
4919 if (fwrite(buf, 1, r, dst) != r)
4920 return got_ferror(dst, GOT_ERR_IO);
4923 if (s_nlines == 0 && *d_nlines == 0)
4924 return NULL;
4927 * If commit info was in dst, increment line offsets
4928 * of the appended diff content, but skip s_lines[0]
4929 * because offset zero is already in *d_lines.
4931 if (*d_nlines > 0) {
4932 for (i = 1; i < s_nlines; ++i)
4933 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4935 if (s_nlines > 0) {
4936 --s_nlines;
4937 ++s_lines;
4941 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4942 if (p == NULL) {
4943 /* d_lines is freed in close_diff_view() */
4944 return got_error_from_errno("reallocarray");
4947 *d_lines = p;
4949 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4950 *d_nlines += s_nlines;
4952 return NULL;
4955 static const struct got_error *
4956 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4957 struct got_object_id *commit_id, struct got_reflist_head *refs,
4958 struct got_repository *repo, int ignore_ws, int force_text_diff,
4959 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4961 const struct got_error *err = NULL;
4962 char datebuf[26], *datestr;
4963 struct got_commit_object *commit;
4964 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4965 time_t committer_time;
4966 const char *author, *committer;
4967 char *refs_str = NULL;
4968 struct got_pathlist_entry *pe;
4969 off_t outoff = 0;
4970 int n;
4972 if (refs) {
4973 err = build_refs_str(&refs_str, refs, commit_id, repo);
4974 if (err)
4975 return err;
4978 err = got_object_open_as_commit(&commit, repo, commit_id);
4979 if (err)
4980 return err;
4982 err = got_object_id_str(&id_str, commit_id);
4983 if (err) {
4984 err = got_error_from_errno("got_object_id_str");
4985 goto done;
4988 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4989 if (err)
4990 goto done;
4992 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4993 refs_str ? refs_str : "", refs_str ? ")" : "");
4994 if (n < 0) {
4995 err = got_error_from_errno("fprintf");
4996 goto done;
4998 outoff += n;
4999 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5000 if (err)
5001 goto done;
5003 n = fprintf(outfile, "from: %s\n",
5004 got_object_commit_get_author(commit));
5005 if (n < 0) {
5006 err = got_error_from_errno("fprintf");
5007 goto done;
5009 outoff += n;
5010 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5011 if (err)
5012 goto done;
5014 author = got_object_commit_get_author(commit);
5015 committer = got_object_commit_get_committer(commit);
5016 if (strcmp(author, committer) != 0) {
5017 n = fprintf(outfile, "via: %s\n", committer);
5018 if (n < 0) {
5019 err = got_error_from_errno("fprintf");
5020 goto done;
5022 outoff += n;
5023 err = add_line_metadata(lines, nlines, outoff,
5024 GOT_DIFF_LINE_AUTHOR);
5025 if (err)
5026 goto done;
5028 committer_time = got_object_commit_get_committer_time(commit);
5029 datestr = get_datestr(&committer_time, datebuf);
5030 if (datestr) {
5031 n = fprintf(outfile, "date: %s UTC\n", datestr);
5032 if (n < 0) {
5033 err = got_error_from_errno("fprintf");
5034 goto done;
5036 outoff += n;
5037 err = add_line_metadata(lines, nlines, outoff,
5038 GOT_DIFF_LINE_DATE);
5039 if (err)
5040 goto done;
5042 if (got_object_commit_get_nparents(commit) > 1) {
5043 const struct got_object_id_queue *parent_ids;
5044 struct got_object_qid *qid;
5045 int pn = 1;
5046 parent_ids = got_object_commit_get_parent_ids(commit);
5047 STAILQ_FOREACH(qid, parent_ids, entry) {
5048 err = got_object_id_str(&id_str, &qid->id);
5049 if (err)
5050 goto done;
5051 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5052 if (n < 0) {
5053 err = got_error_from_errno("fprintf");
5054 goto done;
5056 outoff += n;
5057 err = add_line_metadata(lines, nlines, outoff,
5058 GOT_DIFF_LINE_META);
5059 if (err)
5060 goto done;
5061 free(id_str);
5062 id_str = NULL;
5066 err = got_object_commit_get_logmsg(&logmsg, commit);
5067 if (err)
5068 goto done;
5069 s = logmsg;
5070 while ((line = strsep(&s, "\n")) != NULL) {
5071 n = fprintf(outfile, "%s\n", line);
5072 if (n < 0) {
5073 err = got_error_from_errno("fprintf");
5074 goto done;
5076 outoff += n;
5077 err = add_line_metadata(lines, nlines, outoff,
5078 GOT_DIFF_LINE_LOGMSG);
5079 if (err)
5080 goto done;
5083 TAILQ_FOREACH(pe, dsa->paths, entry) {
5084 struct got_diff_changed_path *cp = pe->data;
5085 int pad = dsa->max_path_len - pe->path_len + 1;
5087 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5088 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5089 dsa->rm_cols + 1, cp->rm);
5090 if (n < 0) {
5091 err = got_error_from_errno("fprintf");
5092 goto done;
5094 outoff += n;
5095 err = add_line_metadata(lines, nlines, outoff,
5096 GOT_DIFF_LINE_CHANGES);
5097 if (err)
5098 goto done;
5101 fputc('\n', outfile);
5102 outoff++;
5103 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5104 if (err)
5105 goto done;
5107 n = fprintf(outfile,
5108 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5109 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5110 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5111 if (n < 0) {
5112 err = got_error_from_errno("fprintf");
5113 goto done;
5115 outoff += n;
5116 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5117 if (err)
5118 goto done;
5120 fputc('\n', outfile);
5121 outoff++;
5122 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5123 done:
5124 free(id_str);
5125 free(logmsg);
5126 free(refs_str);
5127 got_object_commit_close(commit);
5128 if (err) {
5129 free(*lines);
5130 *lines = NULL;
5131 *nlines = 0;
5133 return err;
5136 static const struct got_error *
5137 create_diff(struct tog_diff_view_state *s)
5139 const struct got_error *err = NULL;
5140 FILE *f = NULL, *tmp_diff_file = NULL;
5141 int obj_type;
5142 struct got_diff_line *lines = NULL;
5143 struct got_pathlist_head changed_paths;
5145 TAILQ_INIT(&changed_paths);
5147 free(s->lines);
5148 s->lines = malloc(sizeof(*s->lines));
5149 if (s->lines == NULL)
5150 return got_error_from_errno("malloc");
5151 s->nlines = 0;
5153 f = got_opentemp();
5154 if (f == NULL) {
5155 err = got_error_from_errno("got_opentemp");
5156 goto done;
5158 tmp_diff_file = got_opentemp();
5159 if (tmp_diff_file == NULL) {
5160 err = got_error_from_errno("got_opentemp");
5161 goto done;
5163 if (s->f && fclose(s->f) == EOF) {
5164 err = got_error_from_errno("fclose");
5165 goto done;
5167 s->f = f;
5169 if (s->id1)
5170 err = got_object_get_type(&obj_type, s->repo, s->id1);
5171 else
5172 err = got_object_get_type(&obj_type, s->repo, s->id2);
5173 if (err)
5174 goto done;
5176 switch (obj_type) {
5177 case GOT_OBJ_TYPE_BLOB:
5178 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5179 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5180 s->label1, s->label2, tog_diff_algo, s->diff_context,
5181 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5182 s->f);
5183 break;
5184 case GOT_OBJ_TYPE_TREE:
5185 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5186 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5187 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5188 s->force_text_diff, NULL, s->repo, s->f);
5189 break;
5190 case GOT_OBJ_TYPE_COMMIT: {
5191 const struct got_object_id_queue *parent_ids;
5192 struct got_object_qid *pid;
5193 struct got_commit_object *commit2;
5194 struct got_reflist_head *refs;
5195 size_t nlines = 0;
5196 struct got_diffstat_cb_arg dsa = {
5197 0, 0, 0, 0, 0, 0,
5198 &changed_paths,
5199 s->ignore_whitespace,
5200 s->force_text_diff,
5201 tog_diff_algo
5204 lines = malloc(sizeof(*lines));
5205 if (lines == NULL) {
5206 err = got_error_from_errno("malloc");
5207 goto done;
5210 /* build diff first in tmp file then append to commit info */
5211 err = got_diff_objects_as_commits(&lines, &nlines,
5212 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5213 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5214 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5215 if (err)
5216 break;
5218 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5219 if (err)
5220 goto done;
5221 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5222 /* Show commit info if we're diffing to a parent/root commit. */
5223 if (s->id1 == NULL) {
5224 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5225 refs, s->repo, s->ignore_whitespace,
5226 s->force_text_diff, &dsa, s->f);
5227 if (err)
5228 goto done;
5229 } else {
5230 parent_ids = got_object_commit_get_parent_ids(commit2);
5231 STAILQ_FOREACH(pid, parent_ids, entry) {
5232 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5233 err = write_commit_info(&s->lines,
5234 &s->nlines, s->id2, refs, s->repo,
5235 s->ignore_whitespace,
5236 s->force_text_diff, &dsa, s->f);
5237 if (err)
5238 goto done;
5239 break;
5243 got_object_commit_close(commit2);
5245 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5246 lines, nlines);
5247 break;
5249 default:
5250 err = got_error(GOT_ERR_OBJ_TYPE);
5251 break;
5253 done:
5254 free(lines);
5255 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5256 if (s->f && fflush(s->f) != 0 && err == NULL)
5257 err = got_error_from_errno("fflush");
5258 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5259 err = got_error_from_errno("fclose");
5260 return err;
5263 static void
5264 diff_view_indicate_progress(struct tog_view *view)
5266 mvwaddstr(view->window, 0, 0, "diffing...");
5267 update_panels();
5268 doupdate();
5271 static const struct got_error *
5272 search_start_diff_view(struct tog_view *view)
5274 struct tog_diff_view_state *s = &view->state.diff;
5276 s->matched_line = 0;
5277 return NULL;
5280 static void
5281 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5282 size_t *nlines, int **first, int **last, int **match, int **selected)
5284 struct tog_diff_view_state *s = &view->state.diff;
5286 *f = s->f;
5287 *nlines = s->nlines;
5288 *line_offsets = NULL;
5289 *match = &s->matched_line;
5290 *first = &s->first_displayed_line;
5291 *last = &s->last_displayed_line;
5292 *selected = &s->selected_line;
5295 static const struct got_error *
5296 search_next_view_match(struct tog_view *view)
5298 const struct got_error *err = NULL;
5299 FILE *f;
5300 int lineno;
5301 char *line = NULL;
5302 size_t linesize = 0;
5303 ssize_t linelen;
5304 off_t *line_offsets;
5305 size_t nlines = 0;
5306 int *first, *last, *match, *selected;
5308 if (!view->search_setup)
5309 return got_error_msg(GOT_ERR_NOT_IMPL,
5310 "view search not supported");
5311 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5312 &match, &selected);
5314 if (!view->searching) {
5315 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5316 return NULL;
5319 if (*match) {
5320 if (view->searching == TOG_SEARCH_FORWARD)
5321 lineno = *first + 1;
5322 else
5323 lineno = *first - 1;
5324 } else
5325 lineno = *first - 1 + *selected;
5327 while (1) {
5328 off_t offset;
5330 if (lineno <= 0 || lineno > nlines) {
5331 if (*match == 0) {
5332 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5333 break;
5336 if (view->searching == TOG_SEARCH_FORWARD)
5337 lineno = 1;
5338 else
5339 lineno = nlines;
5342 offset = view->type == TOG_VIEW_DIFF ?
5343 view->state.diff.lines[lineno - 1].offset :
5344 line_offsets[lineno - 1];
5345 if (fseeko(f, offset, SEEK_SET) != 0) {
5346 free(line);
5347 return got_error_from_errno("fseeko");
5349 linelen = getline(&line, &linesize, f);
5350 if (linelen != -1) {
5351 char *exstr;
5352 err = expand_tab(&exstr, line);
5353 if (err)
5354 break;
5355 if (match_line(exstr, &view->regex, 1,
5356 &view->regmatch)) {
5357 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5358 *match = lineno;
5359 free(exstr);
5360 break;
5362 free(exstr);
5364 if (view->searching == TOG_SEARCH_FORWARD)
5365 lineno++;
5366 else
5367 lineno--;
5369 free(line);
5371 if (*match) {
5372 *first = *match;
5373 *selected = 1;
5376 return err;
5379 static const struct got_error *
5380 close_diff_view(struct tog_view *view)
5382 const struct got_error *err = NULL;
5383 struct tog_diff_view_state *s = &view->state.diff;
5385 free(s->id1);
5386 s->id1 = NULL;
5387 free(s->id2);
5388 s->id2 = NULL;
5389 if (s->f && fclose(s->f) == EOF)
5390 err = got_error_from_errno("fclose");
5391 s->f = NULL;
5392 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5393 err = got_error_from_errno("fclose");
5394 s->f1 = NULL;
5395 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5396 err = got_error_from_errno("fclose");
5397 s->f2 = NULL;
5398 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5399 err = got_error_from_errno("close");
5400 s->fd1 = -1;
5401 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5402 err = got_error_from_errno("close");
5403 s->fd2 = -1;
5404 free(s->lines);
5405 s->lines = NULL;
5406 s->nlines = 0;
5407 return err;
5410 static const struct got_error *
5411 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5412 struct got_object_id *id2, const char *label1, const char *label2,
5413 int diff_context, int ignore_whitespace, int force_text_diff,
5414 struct tog_view *parent_view, struct got_repository *repo)
5416 const struct got_error *err;
5417 struct tog_diff_view_state *s = &view->state.diff;
5419 memset(s, 0, sizeof(*s));
5420 s->fd1 = -1;
5421 s->fd2 = -1;
5423 if (id1 != NULL && id2 != NULL) {
5424 int type1, type2;
5426 err = got_object_get_type(&type1, repo, id1);
5427 if (err)
5428 goto done;
5429 err = got_object_get_type(&type2, repo, id2);
5430 if (err)
5431 goto done;
5433 if (type1 != type2) {
5434 err = got_error(GOT_ERR_OBJ_TYPE);
5435 goto done;
5438 s->first_displayed_line = 1;
5439 s->last_displayed_line = view->nlines;
5440 s->selected_line = 1;
5441 s->repo = repo;
5442 s->id1 = id1;
5443 s->id2 = id2;
5444 s->label1 = label1;
5445 s->label2 = label2;
5447 if (id1) {
5448 s->id1 = got_object_id_dup(id1);
5449 if (s->id1 == NULL) {
5450 err = got_error_from_errno("got_object_id_dup");
5451 goto done;
5453 } else
5454 s->id1 = NULL;
5456 s->id2 = got_object_id_dup(id2);
5457 if (s->id2 == NULL) {
5458 err = got_error_from_errno("got_object_id_dup");
5459 goto done;
5462 s->f1 = got_opentemp();
5463 if (s->f1 == NULL) {
5464 err = got_error_from_errno("got_opentemp");
5465 goto done;
5468 s->f2 = got_opentemp();
5469 if (s->f2 == NULL) {
5470 err = got_error_from_errno("got_opentemp");
5471 goto done;
5474 s->fd1 = got_opentempfd();
5475 if (s->fd1 == -1) {
5476 err = got_error_from_errno("got_opentempfd");
5477 goto done;
5480 s->fd2 = got_opentempfd();
5481 if (s->fd2 == -1) {
5482 err = got_error_from_errno("got_opentempfd");
5483 goto done;
5486 s->diff_context = diff_context;
5487 s->ignore_whitespace = ignore_whitespace;
5488 s->force_text_diff = force_text_diff;
5489 s->parent_view = parent_view;
5490 s->repo = repo;
5492 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5493 int rc;
5495 rc = init_pair(GOT_DIFF_LINE_MINUS,
5496 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5497 if (rc != ERR)
5498 rc = init_pair(GOT_DIFF_LINE_PLUS,
5499 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5500 if (rc != ERR)
5501 rc = init_pair(GOT_DIFF_LINE_HUNK,
5502 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5503 if (rc != ERR)
5504 rc = init_pair(GOT_DIFF_LINE_META,
5505 get_color_value("TOG_COLOR_DIFF_META"), -1);
5506 if (rc != ERR)
5507 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5508 get_color_value("TOG_COLOR_DIFF_META"), -1);
5509 if (rc != ERR)
5510 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5511 get_color_value("TOG_COLOR_DIFF_META"), -1);
5512 if (rc != ERR)
5513 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5514 get_color_value("TOG_COLOR_DIFF_META"), -1);
5515 if (rc != ERR)
5516 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5517 get_color_value("TOG_COLOR_AUTHOR"), -1);
5518 if (rc != ERR)
5519 rc = init_pair(GOT_DIFF_LINE_DATE,
5520 get_color_value("TOG_COLOR_DATE"), -1);
5521 if (rc == ERR) {
5522 err = got_error(GOT_ERR_RANGE);
5523 goto done;
5527 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5528 view_is_splitscreen(view))
5529 show_log_view(parent_view); /* draw border */
5530 diff_view_indicate_progress(view);
5532 err = create_diff(s);
5534 view->show = show_diff_view;
5535 view->input = input_diff_view;
5536 view->reset = reset_diff_view;
5537 view->close = close_diff_view;
5538 view->search_start = search_start_diff_view;
5539 view->search_setup = search_setup_diff_view;
5540 view->search_next = search_next_view_match;
5541 done:
5542 if (err) {
5543 if (view->close == NULL)
5544 close_diff_view(view);
5545 view_close(view);
5547 return err;
5550 static const struct got_error *
5551 show_diff_view(struct tog_view *view)
5553 const struct got_error *err;
5554 struct tog_diff_view_state *s = &view->state.diff;
5555 char *id_str1 = NULL, *id_str2, *header;
5556 const char *label1, *label2;
5558 if (s->id1) {
5559 err = got_object_id_str(&id_str1, s->id1);
5560 if (err)
5561 return err;
5562 label1 = s->label1 ? s->label1 : id_str1;
5563 } else
5564 label1 = "/dev/null";
5566 err = got_object_id_str(&id_str2, s->id2);
5567 if (err)
5568 return err;
5569 label2 = s->label2 ? s->label2 : id_str2;
5571 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5572 err = got_error_from_errno("asprintf");
5573 free(id_str1);
5574 free(id_str2);
5575 return err;
5577 free(id_str1);
5578 free(id_str2);
5580 err = draw_file(view, header);
5581 free(header);
5582 return err;
5585 static const struct got_error *
5586 set_selected_commit(struct tog_diff_view_state *s,
5587 struct commit_queue_entry *entry)
5589 const struct got_error *err;
5590 const struct got_object_id_queue *parent_ids;
5591 struct got_commit_object *selected_commit;
5592 struct got_object_qid *pid;
5594 free(s->id2);
5595 s->id2 = got_object_id_dup(entry->id);
5596 if (s->id2 == NULL)
5597 return got_error_from_errno("got_object_id_dup");
5599 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5600 if (err)
5601 return err;
5602 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5603 free(s->id1);
5604 pid = STAILQ_FIRST(parent_ids);
5605 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5606 got_object_commit_close(selected_commit);
5607 return NULL;
5610 static const struct got_error *
5611 reset_diff_view(struct tog_view *view)
5613 struct tog_diff_view_state *s = &view->state.diff;
5615 view->count = 0;
5616 wclear(view->window);
5617 s->first_displayed_line = 1;
5618 s->last_displayed_line = view->nlines;
5619 s->matched_line = 0;
5620 diff_view_indicate_progress(view);
5621 return create_diff(s);
5624 static void
5625 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5627 int start, i;
5629 i = start = s->first_displayed_line - 1;
5631 while (s->lines[i].type != type) {
5632 if (i == 0)
5633 i = s->nlines - 1;
5634 if (--i == start)
5635 return; /* do nothing, requested type not in file */
5638 s->selected_line = 1;
5639 s->first_displayed_line = i;
5642 static void
5643 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5645 int start, i;
5647 i = start = s->first_displayed_line + 1;
5649 while (s->lines[i].type != type) {
5650 if (i == s->nlines - 1)
5651 i = 0;
5652 if (++i == start)
5653 return; /* do nothing, requested type not in file */
5656 s->selected_line = 1;
5657 s->first_displayed_line = i;
5660 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5661 int, int, int);
5662 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5663 int, int);
5665 static const struct got_error *
5666 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5668 const struct got_error *err = NULL;
5669 struct tog_diff_view_state *s = &view->state.diff;
5670 struct tog_log_view_state *ls;
5671 struct commit_queue_entry *old_selected_entry;
5672 char *line = NULL;
5673 size_t linesize = 0;
5674 ssize_t linelen;
5675 int i, nscroll = view->nlines - 1, up = 0;
5677 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5679 switch (ch) {
5680 case '0':
5681 case '$':
5682 case KEY_RIGHT:
5683 case 'l':
5684 case KEY_LEFT:
5685 case 'h':
5686 horizontal_scroll_input(view, ch);
5687 break;
5688 case 'a':
5689 case 'w':
5690 if (ch == 'a') {
5691 s->force_text_diff = !s->force_text_diff;
5692 view->action = s->force_text_diff ?
5693 "force ASCII text enabled" :
5694 "force ASCII text disabled";
5696 else if (ch == 'w') {
5697 s->ignore_whitespace = !s->ignore_whitespace;
5698 view->action = s->ignore_whitespace ?
5699 "ignore whitespace enabled" :
5700 "ignore whitespace disabled";
5702 err = reset_diff_view(view);
5703 break;
5704 case 'g':
5705 case KEY_HOME:
5706 s->first_displayed_line = 1;
5707 view->count = 0;
5708 break;
5709 case 'G':
5710 case KEY_END:
5711 view->count = 0;
5712 if (s->eof)
5713 break;
5715 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5716 s->eof = 1;
5717 break;
5718 case 'k':
5719 case KEY_UP:
5720 case CTRL('p'):
5721 if (s->first_displayed_line > 1)
5722 s->first_displayed_line--;
5723 else
5724 view->count = 0;
5725 break;
5726 case CTRL('u'):
5727 case 'u':
5728 nscroll /= 2;
5729 /* FALL THROUGH */
5730 case KEY_PPAGE:
5731 case CTRL('b'):
5732 case 'b':
5733 if (s->first_displayed_line == 1) {
5734 view->count = 0;
5735 break;
5737 i = 0;
5738 while (i++ < nscroll && s->first_displayed_line > 1)
5739 s->first_displayed_line--;
5740 break;
5741 case 'j':
5742 case KEY_DOWN:
5743 case CTRL('n'):
5744 if (!s->eof)
5745 s->first_displayed_line++;
5746 else
5747 view->count = 0;
5748 break;
5749 case CTRL('d'):
5750 case 'd':
5751 nscroll /= 2;
5752 /* FALL THROUGH */
5753 case KEY_NPAGE:
5754 case CTRL('f'):
5755 case 'f':
5756 case ' ':
5757 if (s->eof) {
5758 view->count = 0;
5759 break;
5761 i = 0;
5762 while (!s->eof && i++ < nscroll) {
5763 linelen = getline(&line, &linesize, s->f);
5764 s->first_displayed_line++;
5765 if (linelen == -1) {
5766 if (feof(s->f)) {
5767 s->eof = 1;
5768 } else
5769 err = got_ferror(s->f, GOT_ERR_IO);
5770 break;
5773 free(line);
5774 break;
5775 case '(':
5776 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5777 break;
5778 case ')':
5779 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5780 break;
5781 case '{':
5782 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5783 break;
5784 case '}':
5785 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5786 break;
5787 case '[':
5788 if (s->diff_context > 0) {
5789 s->diff_context--;
5790 s->matched_line = 0;
5791 diff_view_indicate_progress(view);
5792 err = create_diff(s);
5793 if (s->first_displayed_line + view->nlines - 1 >
5794 s->nlines) {
5795 s->first_displayed_line = 1;
5796 s->last_displayed_line = view->nlines;
5798 } else
5799 view->count = 0;
5800 break;
5801 case ']':
5802 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5803 s->diff_context++;
5804 s->matched_line = 0;
5805 diff_view_indicate_progress(view);
5806 err = create_diff(s);
5807 } else
5808 view->count = 0;
5809 break;
5810 case '<':
5811 case ',':
5812 case 'K':
5813 up = 1;
5814 /* FALL THROUGH */
5815 case '>':
5816 case '.':
5817 case 'J':
5818 if (s->parent_view == NULL) {
5819 view->count = 0;
5820 break;
5822 s->parent_view->count = view->count;
5824 if (s->parent_view->type == TOG_VIEW_LOG) {
5825 ls = &s->parent_view->state.log;
5826 old_selected_entry = ls->selected_entry;
5828 err = input_log_view(NULL, s->parent_view,
5829 up ? KEY_UP : KEY_DOWN);
5830 if (err)
5831 break;
5832 view->count = s->parent_view->count;
5834 if (old_selected_entry == ls->selected_entry)
5835 break;
5837 err = set_selected_commit(s, ls->selected_entry);
5838 if (err)
5839 break;
5840 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5841 struct tog_blame_view_state *bs;
5842 struct got_object_id *id, *prev_id;
5844 bs = &s->parent_view->state.blame;
5845 prev_id = get_annotation_for_line(bs->blame.lines,
5846 bs->blame.nlines, bs->last_diffed_line);
5848 err = input_blame_view(&view, s->parent_view,
5849 up ? KEY_UP : KEY_DOWN);
5850 if (err)
5851 break;
5852 view->count = s->parent_view->count;
5854 if (prev_id == NULL)
5855 break;
5856 id = get_selected_commit_id(bs->blame.lines,
5857 bs->blame.nlines, bs->first_displayed_line,
5858 bs->selected_line);
5859 if (id == NULL)
5860 break;
5862 if (!got_object_id_cmp(prev_id, id))
5863 break;
5865 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5866 if (err)
5867 break;
5869 s->first_displayed_line = 1;
5870 s->last_displayed_line = view->nlines;
5871 s->matched_line = 0;
5872 view->x = 0;
5874 diff_view_indicate_progress(view);
5875 err = create_diff(s);
5876 break;
5877 default:
5878 view->count = 0;
5879 break;
5882 return err;
5885 static const struct got_error *
5886 cmd_diff(int argc, char *argv[])
5888 const struct got_error *error;
5889 struct got_repository *repo = NULL;
5890 struct got_worktree *worktree = NULL;
5891 struct got_object_id *id1 = NULL, *id2 = NULL;
5892 char *repo_path = NULL, *cwd = NULL;
5893 char *id_str1 = NULL, *id_str2 = NULL;
5894 char *label1 = NULL, *label2 = NULL;
5895 int diff_context = 3, ignore_whitespace = 0;
5896 int ch, force_text_diff = 0;
5897 const char *errstr;
5898 struct tog_view *view;
5899 int *pack_fds = NULL;
5901 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5902 switch (ch) {
5903 case 'a':
5904 force_text_diff = 1;
5905 break;
5906 case 'C':
5907 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5908 &errstr);
5909 if (errstr != NULL)
5910 errx(1, "number of context lines is %s: %s",
5911 errstr, errstr);
5912 break;
5913 case 'r':
5914 repo_path = realpath(optarg, NULL);
5915 if (repo_path == NULL)
5916 return got_error_from_errno2("realpath",
5917 optarg);
5918 got_path_strip_trailing_slashes(repo_path);
5919 break;
5920 case 'w':
5921 ignore_whitespace = 1;
5922 break;
5923 default:
5924 usage_diff();
5925 /* NOTREACHED */
5929 argc -= optind;
5930 argv += optind;
5932 if (argc == 0) {
5933 usage_diff(); /* TODO show local worktree changes */
5934 } else if (argc == 2) {
5935 id_str1 = argv[0];
5936 id_str2 = argv[1];
5937 } else
5938 usage_diff();
5940 error = got_repo_pack_fds_open(&pack_fds);
5941 if (error)
5942 goto done;
5944 if (repo_path == NULL) {
5945 cwd = getcwd(NULL, 0);
5946 if (cwd == NULL)
5947 return got_error_from_errno("getcwd");
5948 error = got_worktree_open(&worktree, cwd);
5949 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5950 goto done;
5951 if (worktree)
5952 repo_path =
5953 strdup(got_worktree_get_repo_path(worktree));
5954 else
5955 repo_path = strdup(cwd);
5956 if (repo_path == NULL) {
5957 error = got_error_from_errno("strdup");
5958 goto done;
5962 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5963 if (error)
5964 goto done;
5966 init_curses();
5968 error = apply_unveil(got_repo_get_path(repo), NULL);
5969 if (error)
5970 goto done;
5972 error = tog_load_refs(repo, 0);
5973 if (error)
5974 goto done;
5976 error = got_repo_match_object_id(&id1, &label1, id_str1,
5977 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5978 if (error)
5979 goto done;
5981 error = got_repo_match_object_id(&id2, &label2, id_str2,
5982 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5983 if (error)
5984 goto done;
5986 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5987 if (view == NULL) {
5988 error = got_error_from_errno("view_open");
5989 goto done;
5991 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5992 ignore_whitespace, force_text_diff, NULL, repo);
5993 if (error)
5994 goto done;
5995 error = view_loop(view);
5996 done:
5997 free(label1);
5998 free(label2);
5999 free(repo_path);
6000 free(cwd);
6001 if (repo) {
6002 const struct got_error *close_err = got_repo_close(repo);
6003 if (error == NULL)
6004 error = close_err;
6006 if (worktree)
6007 got_worktree_close(worktree);
6008 if (pack_fds) {
6009 const struct got_error *pack_err =
6010 got_repo_pack_fds_close(pack_fds);
6011 if (error == NULL)
6012 error = pack_err;
6014 tog_free_refs();
6015 return error;
6018 __dead static void
6019 usage_blame(void)
6021 endwin();
6022 fprintf(stderr,
6023 "usage: %s blame [-c commit] [-r repository-path] path\n",
6024 getprogname());
6025 exit(1);
6028 struct tog_blame_line {
6029 int annotated;
6030 struct got_object_id *id;
6033 static const struct got_error *
6034 draw_blame(struct tog_view *view)
6036 struct tog_blame_view_state *s = &view->state.blame;
6037 struct tog_blame *blame = &s->blame;
6038 regmatch_t *regmatch = &view->regmatch;
6039 const struct got_error *err;
6040 int lineno = 0, nprinted = 0;
6041 char *line = NULL;
6042 size_t linesize = 0;
6043 ssize_t linelen;
6044 wchar_t *wline;
6045 int width;
6046 struct tog_blame_line *blame_line;
6047 struct got_object_id *prev_id = NULL;
6048 char *id_str;
6049 struct tog_color *tc;
6051 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6052 if (err)
6053 return err;
6055 rewind(blame->f);
6056 werase(view->window);
6058 if (asprintf(&line, "commit %s", id_str) == -1) {
6059 err = got_error_from_errno("asprintf");
6060 free(id_str);
6061 return err;
6064 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6065 free(line);
6066 line = NULL;
6067 if (err)
6068 return err;
6069 if (view_needs_focus_indication(view))
6070 wstandout(view->window);
6071 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6072 if (tc)
6073 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6074 waddwstr(view->window, wline);
6075 while (width++ < view->ncols)
6076 waddch(view->window, ' ');
6077 if (tc)
6078 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6079 if (view_needs_focus_indication(view))
6080 wstandend(view->window);
6081 free(wline);
6082 wline = NULL;
6084 if (view->gline > blame->nlines)
6085 view->gline = blame->nlines;
6087 if (tog_io.wait_for_ui) {
6088 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6089 int rc;
6091 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6092 if (rc)
6093 return got_error_set_errno(rc, "pthread_cond_wait");
6094 tog_io.wait_for_ui = 0;
6097 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6098 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6099 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6100 free(id_str);
6101 return got_error_from_errno("asprintf");
6103 free(id_str);
6104 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6105 free(line);
6106 line = NULL;
6107 if (err)
6108 return err;
6109 waddwstr(view->window, wline);
6110 free(wline);
6111 wline = NULL;
6112 if (width < view->ncols - 1)
6113 waddch(view->window, '\n');
6115 s->eof = 0;
6116 view->maxx = 0;
6117 while (nprinted < view->nlines - 2) {
6118 linelen = getline(&line, &linesize, blame->f);
6119 if (linelen == -1) {
6120 if (feof(blame->f)) {
6121 s->eof = 1;
6122 break;
6124 free(line);
6125 return got_ferror(blame->f, GOT_ERR_IO);
6127 if (++lineno < s->first_displayed_line)
6128 continue;
6129 if (view->gline && !gotoline(view, &lineno, &nprinted))
6130 continue;
6132 /* Set view->maxx based on full line length. */
6133 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6134 if (err) {
6135 free(line);
6136 return err;
6138 free(wline);
6139 wline = NULL;
6140 view->maxx = MAX(view->maxx, width);
6142 if (nprinted == s->selected_line - 1)
6143 wstandout(view->window);
6145 if (blame->nlines > 0) {
6146 blame_line = &blame->lines[lineno - 1];
6147 if (blame_line->annotated && prev_id &&
6148 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6149 !(nprinted == s->selected_line - 1)) {
6150 waddstr(view->window, " ");
6151 } else if (blame_line->annotated) {
6152 char *id_str;
6153 err = got_object_id_str(&id_str,
6154 blame_line->id);
6155 if (err) {
6156 free(line);
6157 return err;
6159 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6160 if (tc)
6161 wattr_on(view->window,
6162 COLOR_PAIR(tc->colorpair), NULL);
6163 wprintw(view->window, "%.8s", id_str);
6164 if (tc)
6165 wattr_off(view->window,
6166 COLOR_PAIR(tc->colorpair), NULL);
6167 free(id_str);
6168 prev_id = blame_line->id;
6169 } else {
6170 waddstr(view->window, "........");
6171 prev_id = NULL;
6173 } else {
6174 waddstr(view->window, "........");
6175 prev_id = NULL;
6178 if (nprinted == s->selected_line - 1)
6179 wstandend(view->window);
6180 waddstr(view->window, " ");
6182 if (view->ncols <= 9) {
6183 width = 9;
6184 } else if (s->first_displayed_line + nprinted ==
6185 s->matched_line &&
6186 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6187 err = add_matched_line(&width, line, view->ncols - 9, 9,
6188 view->window, view->x, regmatch);
6189 if (err) {
6190 free(line);
6191 return err;
6193 width += 9;
6194 } else {
6195 int skip;
6196 err = format_line(&wline, &width, &skip, line,
6197 view->x, view->ncols - 9, 9, 1);
6198 if (err) {
6199 free(line);
6200 return err;
6202 waddwstr(view->window, &wline[skip]);
6203 width += 9;
6204 free(wline);
6205 wline = NULL;
6208 if (width <= view->ncols - 1)
6209 waddch(view->window, '\n');
6210 if (++nprinted == 1)
6211 s->first_displayed_line = lineno;
6213 free(line);
6214 s->last_displayed_line = lineno;
6216 view_border(view);
6218 return NULL;
6221 static const struct got_error *
6222 blame_cb(void *arg, int nlines, int lineno,
6223 struct got_commit_object *commit, struct got_object_id *id)
6225 const struct got_error *err = NULL;
6226 struct tog_blame_cb_args *a = arg;
6227 struct tog_blame_line *line;
6228 int errcode;
6230 if (nlines != a->nlines ||
6231 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6232 return got_error(GOT_ERR_RANGE);
6234 errcode = pthread_mutex_lock(&tog_mutex);
6235 if (errcode)
6236 return got_error_set_errno(errcode, "pthread_mutex_lock");
6238 if (*a->quit) { /* user has quit the blame view */
6239 err = got_error(GOT_ERR_ITER_COMPLETED);
6240 goto done;
6243 if (lineno == -1)
6244 goto done; /* no change in this commit */
6246 line = &a->lines[lineno - 1];
6247 if (line->annotated)
6248 goto done;
6250 line->id = got_object_id_dup(id);
6251 if (line->id == NULL) {
6252 err = got_error_from_errno("got_object_id_dup");
6253 goto done;
6255 line->annotated = 1;
6256 done:
6257 errcode = pthread_mutex_unlock(&tog_mutex);
6258 if (errcode)
6259 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6260 return err;
6263 static void *
6264 blame_thread(void *arg)
6266 const struct got_error *err, *close_err;
6267 struct tog_blame_thread_args *ta = arg;
6268 struct tog_blame_cb_args *a = ta->cb_args;
6269 int errcode, fd1 = -1, fd2 = -1;
6270 FILE *f1 = NULL, *f2 = NULL;
6272 fd1 = got_opentempfd();
6273 if (fd1 == -1)
6274 return (void *)got_error_from_errno("got_opentempfd");
6276 fd2 = got_opentempfd();
6277 if (fd2 == -1) {
6278 err = got_error_from_errno("got_opentempfd");
6279 goto done;
6282 f1 = got_opentemp();
6283 if (f1 == NULL) {
6284 err = (void *)got_error_from_errno("got_opentemp");
6285 goto done;
6287 f2 = got_opentemp();
6288 if (f2 == NULL) {
6289 err = (void *)got_error_from_errno("got_opentemp");
6290 goto done;
6293 err = block_signals_used_by_main_thread();
6294 if (err)
6295 goto done;
6297 err = got_blame(ta->path, a->commit_id, ta->repo,
6298 tog_diff_algo, blame_cb, ta->cb_args,
6299 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6300 if (err && err->code == GOT_ERR_CANCELLED)
6301 err = NULL;
6303 errcode = pthread_mutex_lock(&tog_mutex);
6304 if (errcode) {
6305 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6306 goto done;
6309 close_err = got_repo_close(ta->repo);
6310 if (err == NULL)
6311 err = close_err;
6312 ta->repo = NULL;
6313 *ta->complete = 1;
6315 if (tog_io.wait_for_ui) {
6316 errcode = pthread_cond_signal(&ta->blame_complete);
6317 if (errcode && err == NULL)
6318 err = got_error_set_errno(errcode,
6319 "pthread_cond_signal");
6322 errcode = pthread_mutex_unlock(&tog_mutex);
6323 if (errcode && err == NULL)
6324 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6326 done:
6327 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6328 err = got_error_from_errno("close");
6329 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6330 err = got_error_from_errno("close");
6331 if (f1 && fclose(f1) == EOF && err == NULL)
6332 err = got_error_from_errno("fclose");
6333 if (f2 && fclose(f2) == EOF && err == NULL)
6334 err = got_error_from_errno("fclose");
6336 return (void *)err;
6339 static struct got_object_id *
6340 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6341 int first_displayed_line, int selected_line)
6343 struct tog_blame_line *line;
6345 if (nlines <= 0)
6346 return NULL;
6348 line = &lines[first_displayed_line - 1 + selected_line - 1];
6349 if (!line->annotated)
6350 return NULL;
6352 return line->id;
6355 static struct got_object_id *
6356 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6357 int lineno)
6359 struct tog_blame_line *line;
6361 if (nlines <= 0 || lineno >= nlines)
6362 return NULL;
6364 line = &lines[lineno - 1];
6365 if (!line->annotated)
6366 return NULL;
6368 return line->id;
6371 static const struct got_error *
6372 stop_blame(struct tog_blame *blame)
6374 const struct got_error *err = NULL;
6375 int i;
6377 if (blame->thread) {
6378 int errcode;
6379 errcode = pthread_mutex_unlock(&tog_mutex);
6380 if (errcode)
6381 return got_error_set_errno(errcode,
6382 "pthread_mutex_unlock");
6383 errcode = pthread_join(blame->thread, (void **)&err);
6384 if (errcode)
6385 return got_error_set_errno(errcode, "pthread_join");
6386 errcode = pthread_mutex_lock(&tog_mutex);
6387 if (errcode)
6388 return got_error_set_errno(errcode,
6389 "pthread_mutex_lock");
6390 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6391 err = NULL;
6392 blame->thread = 0; //NULL;
6394 if (blame->thread_args.repo) {
6395 const struct got_error *close_err;
6396 close_err = got_repo_close(blame->thread_args.repo);
6397 if (err == NULL)
6398 err = close_err;
6399 blame->thread_args.repo = NULL;
6401 if (blame->f) {
6402 if (fclose(blame->f) == EOF && err == NULL)
6403 err = got_error_from_errno("fclose");
6404 blame->f = NULL;
6406 if (blame->lines) {
6407 for (i = 0; i < blame->nlines; i++)
6408 free(blame->lines[i].id);
6409 free(blame->lines);
6410 blame->lines = NULL;
6412 free(blame->cb_args.commit_id);
6413 blame->cb_args.commit_id = NULL;
6414 if (blame->pack_fds) {
6415 const struct got_error *pack_err =
6416 got_repo_pack_fds_close(blame->pack_fds);
6417 if (err == NULL)
6418 err = pack_err;
6419 blame->pack_fds = NULL;
6421 return err;
6424 static const struct got_error *
6425 cancel_blame_view(void *arg)
6427 const struct got_error *err = NULL;
6428 int *done = arg;
6429 int errcode;
6431 errcode = pthread_mutex_lock(&tog_mutex);
6432 if (errcode)
6433 return got_error_set_errno(errcode,
6434 "pthread_mutex_unlock");
6436 if (*done)
6437 err = got_error(GOT_ERR_CANCELLED);
6439 errcode = pthread_mutex_unlock(&tog_mutex);
6440 if (errcode)
6441 return got_error_set_errno(errcode,
6442 "pthread_mutex_lock");
6444 return err;
6447 static const struct got_error *
6448 run_blame(struct tog_view *view)
6450 struct tog_blame_view_state *s = &view->state.blame;
6451 struct tog_blame *blame = &s->blame;
6452 const struct got_error *err = NULL;
6453 struct got_commit_object *commit = NULL;
6454 struct got_blob_object *blob = NULL;
6455 struct got_repository *thread_repo = NULL;
6456 struct got_object_id *obj_id = NULL;
6457 int obj_type, fd = -1;
6458 int *pack_fds = NULL;
6460 err = got_object_open_as_commit(&commit, s->repo,
6461 &s->blamed_commit->id);
6462 if (err)
6463 return err;
6465 fd = got_opentempfd();
6466 if (fd == -1) {
6467 err = got_error_from_errno("got_opentempfd");
6468 goto done;
6471 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6472 if (err)
6473 goto done;
6475 err = got_object_get_type(&obj_type, s->repo, obj_id);
6476 if (err)
6477 goto done;
6479 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6480 err = got_error(GOT_ERR_OBJ_TYPE);
6481 goto done;
6484 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6485 if (err)
6486 goto done;
6487 blame->f = got_opentemp();
6488 if (blame->f == NULL) {
6489 err = got_error_from_errno("got_opentemp");
6490 goto done;
6492 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6493 &blame->line_offsets, blame->f, blob);
6494 if (err)
6495 goto done;
6496 if (blame->nlines == 0) {
6497 s->blame_complete = 1;
6498 goto done;
6501 /* Don't include \n at EOF in the blame line count. */
6502 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6503 blame->nlines--;
6505 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6506 if (blame->lines == NULL) {
6507 err = got_error_from_errno("calloc");
6508 goto done;
6511 err = got_repo_pack_fds_open(&pack_fds);
6512 if (err)
6513 goto done;
6514 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6515 pack_fds);
6516 if (err)
6517 goto done;
6519 blame->pack_fds = pack_fds;
6520 blame->cb_args.view = view;
6521 blame->cb_args.lines = blame->lines;
6522 blame->cb_args.nlines = blame->nlines;
6523 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6524 if (blame->cb_args.commit_id == NULL) {
6525 err = got_error_from_errno("got_object_id_dup");
6526 goto done;
6528 blame->cb_args.quit = &s->done;
6530 blame->thread_args.path = s->path;
6531 blame->thread_args.repo = thread_repo;
6532 blame->thread_args.cb_args = &blame->cb_args;
6533 blame->thread_args.complete = &s->blame_complete;
6534 blame->thread_args.cancel_cb = cancel_blame_view;
6535 blame->thread_args.cancel_arg = &s->done;
6536 s->blame_complete = 0;
6538 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6539 s->first_displayed_line = 1;
6540 s->last_displayed_line = view->nlines;
6541 s->selected_line = 1;
6543 s->matched_line = 0;
6545 done:
6546 if (commit)
6547 got_object_commit_close(commit);
6548 if (fd != -1 && close(fd) == -1 && err == NULL)
6549 err = got_error_from_errno("close");
6550 if (blob)
6551 got_object_blob_close(blob);
6552 free(obj_id);
6553 if (err)
6554 stop_blame(blame);
6555 return err;
6558 static const struct got_error *
6559 open_blame_view(struct tog_view *view, char *path,
6560 struct got_object_id *commit_id, struct got_repository *repo)
6562 const struct got_error *err = NULL;
6563 struct tog_blame_view_state *s = &view->state.blame;
6565 STAILQ_INIT(&s->blamed_commits);
6567 s->path = strdup(path);
6568 if (s->path == NULL)
6569 return got_error_from_errno("strdup");
6571 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6572 if (err) {
6573 free(s->path);
6574 return err;
6577 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6578 s->first_displayed_line = 1;
6579 s->last_displayed_line = view->nlines;
6580 s->selected_line = 1;
6581 s->blame_complete = 0;
6582 s->repo = repo;
6583 s->commit_id = commit_id;
6584 memset(&s->blame, 0, sizeof(s->blame));
6586 STAILQ_INIT(&s->colors);
6587 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6588 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6589 get_color_value("TOG_COLOR_COMMIT"));
6590 if (err)
6591 return err;
6594 view->show = show_blame_view;
6595 view->input = input_blame_view;
6596 view->reset = reset_blame_view;
6597 view->close = close_blame_view;
6598 view->search_start = search_start_blame_view;
6599 view->search_setup = search_setup_blame_view;
6600 view->search_next = search_next_view_match;
6602 if (using_mock_io) {
6603 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6604 int rc;
6606 rc = pthread_cond_init(&bta->blame_complete, NULL);
6607 if (rc)
6608 return got_error_set_errno(rc, "pthread_cond_init");
6611 return run_blame(view);
6614 static const struct got_error *
6615 close_blame_view(struct tog_view *view)
6617 const struct got_error *err = NULL;
6618 struct tog_blame_view_state *s = &view->state.blame;
6620 if (s->blame.thread)
6621 err = stop_blame(&s->blame);
6623 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6624 struct got_object_qid *blamed_commit;
6625 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6626 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6627 got_object_qid_free(blamed_commit);
6630 if (using_mock_io) {
6631 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6632 int rc;
6634 rc = pthread_cond_destroy(&bta->blame_complete);
6635 if (rc && err == NULL)
6636 err = got_error_set_errno(rc, "pthread_cond_destroy");
6639 free(s->path);
6640 free_colors(&s->colors);
6641 return err;
6644 static const struct got_error *
6645 search_start_blame_view(struct tog_view *view)
6647 struct tog_blame_view_state *s = &view->state.blame;
6649 s->matched_line = 0;
6650 return NULL;
6653 static void
6654 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6655 size_t *nlines, int **first, int **last, int **match, int **selected)
6657 struct tog_blame_view_state *s = &view->state.blame;
6659 *f = s->blame.f;
6660 *nlines = s->blame.nlines;
6661 *line_offsets = s->blame.line_offsets;
6662 *match = &s->matched_line;
6663 *first = &s->first_displayed_line;
6664 *last = &s->last_displayed_line;
6665 *selected = &s->selected_line;
6668 static const struct got_error *
6669 show_blame_view(struct tog_view *view)
6671 const struct got_error *err = NULL;
6672 struct tog_blame_view_state *s = &view->state.blame;
6673 int errcode;
6675 if (s->blame.thread == 0 && !s->blame_complete) {
6676 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6677 &s->blame.thread_args);
6678 if (errcode)
6679 return got_error_set_errno(errcode, "pthread_create");
6681 if (!using_mock_io)
6682 halfdelay(1); /* fast refresh while annotating */
6685 if (s->blame_complete && !using_mock_io)
6686 halfdelay(10); /* disable fast refresh */
6688 err = draw_blame(view);
6690 view_border(view);
6691 return err;
6694 static const struct got_error *
6695 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6696 struct got_repository *repo, struct got_object_id *id)
6698 struct tog_view *log_view;
6699 const struct got_error *err = NULL;
6701 *new_view = NULL;
6703 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6704 if (log_view == NULL)
6705 return got_error_from_errno("view_open");
6707 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6708 if (err)
6709 view_close(log_view);
6710 else
6711 *new_view = log_view;
6713 return err;
6716 static const struct got_error *
6717 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6719 const struct got_error *err = NULL, *thread_err = NULL;
6720 struct tog_view *diff_view;
6721 struct tog_blame_view_state *s = &view->state.blame;
6722 int eos, nscroll, begin_y = 0, begin_x = 0;
6724 eos = nscroll = view->nlines - 2;
6725 if (view_is_hsplit_top(view))
6726 --eos; /* border */
6728 switch (ch) {
6729 case '0':
6730 case '$':
6731 case KEY_RIGHT:
6732 case 'l':
6733 case KEY_LEFT:
6734 case 'h':
6735 horizontal_scroll_input(view, ch);
6736 break;
6737 case 'q':
6738 s->done = 1;
6739 break;
6740 case 'g':
6741 case KEY_HOME:
6742 s->selected_line = 1;
6743 s->first_displayed_line = 1;
6744 view->count = 0;
6745 break;
6746 case 'G':
6747 case KEY_END:
6748 if (s->blame.nlines < eos) {
6749 s->selected_line = s->blame.nlines;
6750 s->first_displayed_line = 1;
6751 } else {
6752 s->selected_line = eos;
6753 s->first_displayed_line = s->blame.nlines - (eos - 1);
6755 view->count = 0;
6756 break;
6757 case 'k':
6758 case KEY_UP:
6759 case CTRL('p'):
6760 if (s->selected_line > 1)
6761 s->selected_line--;
6762 else if (s->selected_line == 1 &&
6763 s->first_displayed_line > 1)
6764 s->first_displayed_line--;
6765 else
6766 view->count = 0;
6767 break;
6768 case CTRL('u'):
6769 case 'u':
6770 nscroll /= 2;
6771 /* FALL THROUGH */
6772 case KEY_PPAGE:
6773 case CTRL('b'):
6774 case 'b':
6775 if (s->first_displayed_line == 1) {
6776 if (view->count > 1)
6777 nscroll += nscroll;
6778 s->selected_line = MAX(1, s->selected_line - nscroll);
6779 view->count = 0;
6780 break;
6782 if (s->first_displayed_line > nscroll)
6783 s->first_displayed_line -= nscroll;
6784 else
6785 s->first_displayed_line = 1;
6786 break;
6787 case 'j':
6788 case KEY_DOWN:
6789 case CTRL('n'):
6790 if (s->selected_line < eos && s->first_displayed_line +
6791 s->selected_line <= s->blame.nlines)
6792 s->selected_line++;
6793 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6794 s->first_displayed_line++;
6795 else
6796 view->count = 0;
6797 break;
6798 case 'c':
6799 case 'p': {
6800 struct got_object_id *id = NULL;
6802 view->count = 0;
6803 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6804 s->first_displayed_line, s->selected_line);
6805 if (id == NULL)
6806 break;
6807 if (ch == 'p') {
6808 struct got_commit_object *commit, *pcommit;
6809 struct got_object_qid *pid;
6810 struct got_object_id *blob_id = NULL;
6811 int obj_type;
6812 err = got_object_open_as_commit(&commit,
6813 s->repo, id);
6814 if (err)
6815 break;
6816 pid = STAILQ_FIRST(
6817 got_object_commit_get_parent_ids(commit));
6818 if (pid == NULL) {
6819 got_object_commit_close(commit);
6820 break;
6822 /* Check if path history ends here. */
6823 err = got_object_open_as_commit(&pcommit,
6824 s->repo, &pid->id);
6825 if (err)
6826 break;
6827 err = got_object_id_by_path(&blob_id, s->repo,
6828 pcommit, s->path);
6829 got_object_commit_close(pcommit);
6830 if (err) {
6831 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6832 err = NULL;
6833 got_object_commit_close(commit);
6834 break;
6836 err = got_object_get_type(&obj_type, s->repo,
6837 blob_id);
6838 free(blob_id);
6839 /* Can't blame non-blob type objects. */
6840 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6841 got_object_commit_close(commit);
6842 break;
6844 err = got_object_qid_alloc(&s->blamed_commit,
6845 &pid->id);
6846 got_object_commit_close(commit);
6847 } else {
6848 if (got_object_id_cmp(id,
6849 &s->blamed_commit->id) == 0)
6850 break;
6851 err = got_object_qid_alloc(&s->blamed_commit,
6852 id);
6854 if (err)
6855 break;
6856 s->done = 1;
6857 thread_err = stop_blame(&s->blame);
6858 s->done = 0;
6859 if (thread_err)
6860 break;
6861 STAILQ_INSERT_HEAD(&s->blamed_commits,
6862 s->blamed_commit, entry);
6863 err = run_blame(view);
6864 if (err)
6865 break;
6866 break;
6868 case 'C': {
6869 struct got_object_qid *first;
6871 view->count = 0;
6872 first = STAILQ_FIRST(&s->blamed_commits);
6873 if (!got_object_id_cmp(&first->id, s->commit_id))
6874 break;
6875 s->done = 1;
6876 thread_err = stop_blame(&s->blame);
6877 s->done = 0;
6878 if (thread_err)
6879 break;
6880 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6881 got_object_qid_free(s->blamed_commit);
6882 s->blamed_commit =
6883 STAILQ_FIRST(&s->blamed_commits);
6884 err = run_blame(view);
6885 if (err)
6886 break;
6887 break;
6889 case 'L':
6890 view->count = 0;
6891 s->id_to_log = get_selected_commit_id(s->blame.lines,
6892 s->blame.nlines, s->first_displayed_line, s->selected_line);
6893 if (s->id_to_log)
6894 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6895 break;
6896 case KEY_ENTER:
6897 case '\r': {
6898 struct got_object_id *id = NULL;
6899 struct got_object_qid *pid;
6900 struct got_commit_object *commit = NULL;
6902 view->count = 0;
6903 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6904 s->first_displayed_line, s->selected_line);
6905 if (id == NULL)
6906 break;
6907 err = got_object_open_as_commit(&commit, s->repo, id);
6908 if (err)
6909 break;
6910 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6911 if (*new_view) {
6912 /* traversed from diff view, release diff resources */
6913 err = close_diff_view(*new_view);
6914 if (err)
6915 break;
6916 diff_view = *new_view;
6917 } else {
6918 if (view_is_parent_view(view))
6919 view_get_split(view, &begin_y, &begin_x);
6921 diff_view = view_open(0, 0, begin_y, begin_x,
6922 TOG_VIEW_DIFF);
6923 if (diff_view == NULL) {
6924 got_object_commit_close(commit);
6925 err = got_error_from_errno("view_open");
6926 break;
6929 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6930 id, NULL, NULL, 3, 0, 0, view, s->repo);
6931 got_object_commit_close(commit);
6932 if (err) {
6933 view_close(diff_view);
6934 break;
6936 s->last_diffed_line = s->first_displayed_line - 1 +
6937 s->selected_line;
6938 if (*new_view)
6939 break; /* still open from active diff view */
6940 if (view_is_parent_view(view) &&
6941 view->mode == TOG_VIEW_SPLIT_HRZN) {
6942 err = view_init_hsplit(view, begin_y);
6943 if (err)
6944 break;
6947 view->focussed = 0;
6948 diff_view->focussed = 1;
6949 diff_view->mode = view->mode;
6950 diff_view->nlines = view->lines - begin_y;
6951 if (view_is_parent_view(view)) {
6952 view_transfer_size(diff_view, view);
6953 err = view_close_child(view);
6954 if (err)
6955 break;
6956 err = view_set_child(view, diff_view);
6957 if (err)
6958 break;
6959 view->focus_child = 1;
6960 } else
6961 *new_view = diff_view;
6962 if (err)
6963 break;
6964 break;
6966 case CTRL('d'):
6967 case 'd':
6968 nscroll /= 2;
6969 /* FALL THROUGH */
6970 case KEY_NPAGE:
6971 case CTRL('f'):
6972 case 'f':
6973 case ' ':
6974 if (s->last_displayed_line >= s->blame.nlines &&
6975 s->selected_line >= MIN(s->blame.nlines,
6976 view->nlines - 2)) {
6977 view->count = 0;
6978 break;
6980 if (s->last_displayed_line >= s->blame.nlines &&
6981 s->selected_line < view->nlines - 2) {
6982 s->selected_line +=
6983 MIN(nscroll, s->last_displayed_line -
6984 s->first_displayed_line - s->selected_line + 1);
6986 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6987 s->first_displayed_line += nscroll;
6988 else
6989 s->first_displayed_line =
6990 s->blame.nlines - (view->nlines - 3);
6991 break;
6992 case KEY_RESIZE:
6993 if (s->selected_line > view->nlines - 2) {
6994 s->selected_line = MIN(s->blame.nlines,
6995 view->nlines - 2);
6997 break;
6998 default:
6999 view->count = 0;
7000 break;
7002 return thread_err ? thread_err : err;
7005 static const struct got_error *
7006 reset_blame_view(struct tog_view *view)
7008 const struct got_error *err;
7009 struct tog_blame_view_state *s = &view->state.blame;
7011 view->count = 0;
7012 s->done = 1;
7013 err = stop_blame(&s->blame);
7014 s->done = 0;
7015 if (err)
7016 return err;
7017 return run_blame(view);
7020 static const struct got_error *
7021 cmd_blame(int argc, char *argv[])
7023 const struct got_error *error;
7024 struct got_repository *repo = NULL;
7025 struct got_worktree *worktree = NULL;
7026 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7027 char *link_target = NULL;
7028 struct got_object_id *commit_id = NULL;
7029 struct got_commit_object *commit = NULL;
7030 char *commit_id_str = NULL;
7031 int ch;
7032 struct tog_view *view = NULL;
7033 int *pack_fds = NULL;
7035 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7036 switch (ch) {
7037 case 'c':
7038 commit_id_str = optarg;
7039 break;
7040 case 'r':
7041 repo_path = realpath(optarg, NULL);
7042 if (repo_path == NULL)
7043 return got_error_from_errno2("realpath",
7044 optarg);
7045 break;
7046 default:
7047 usage_blame();
7048 /* NOTREACHED */
7052 argc -= optind;
7053 argv += optind;
7055 if (argc != 1)
7056 usage_blame();
7058 error = got_repo_pack_fds_open(&pack_fds);
7059 if (error != NULL)
7060 goto done;
7062 if (repo_path == NULL) {
7063 cwd = getcwd(NULL, 0);
7064 if (cwd == NULL)
7065 return got_error_from_errno("getcwd");
7066 error = got_worktree_open(&worktree, cwd);
7067 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7068 goto done;
7069 if (worktree)
7070 repo_path =
7071 strdup(got_worktree_get_repo_path(worktree));
7072 else
7073 repo_path = strdup(cwd);
7074 if (repo_path == NULL) {
7075 error = got_error_from_errno("strdup");
7076 goto done;
7080 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7081 if (error != NULL)
7082 goto done;
7084 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7085 worktree);
7086 if (error)
7087 goto done;
7089 init_curses();
7091 error = apply_unveil(got_repo_get_path(repo), NULL);
7092 if (error)
7093 goto done;
7095 error = tog_load_refs(repo, 0);
7096 if (error)
7097 goto done;
7099 if (commit_id_str == NULL) {
7100 struct got_reference *head_ref;
7101 error = got_ref_open(&head_ref, repo, worktree ?
7102 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7103 if (error != NULL)
7104 goto done;
7105 error = got_ref_resolve(&commit_id, repo, head_ref);
7106 got_ref_close(head_ref);
7107 } else {
7108 error = got_repo_match_object_id(&commit_id, NULL,
7109 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7111 if (error != NULL)
7112 goto done;
7114 error = got_object_open_as_commit(&commit, repo, commit_id);
7115 if (error)
7116 goto done;
7118 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7119 commit, repo);
7120 if (error)
7121 goto done;
7123 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7124 if (view == NULL) {
7125 error = got_error_from_errno("view_open");
7126 goto done;
7128 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7129 commit_id, repo);
7130 if (error != NULL) {
7131 if (view->close == NULL)
7132 close_blame_view(view);
7133 view_close(view);
7134 goto done;
7136 if (worktree) {
7137 /* Release work tree lock. */
7138 got_worktree_close(worktree);
7139 worktree = NULL;
7141 error = view_loop(view);
7142 done:
7143 free(repo_path);
7144 free(in_repo_path);
7145 free(link_target);
7146 free(cwd);
7147 free(commit_id);
7148 if (commit)
7149 got_object_commit_close(commit);
7150 if (worktree)
7151 got_worktree_close(worktree);
7152 if (repo) {
7153 const struct got_error *close_err = got_repo_close(repo);
7154 if (error == NULL)
7155 error = close_err;
7157 if (pack_fds) {
7158 const struct got_error *pack_err =
7159 got_repo_pack_fds_close(pack_fds);
7160 if (error == NULL)
7161 error = pack_err;
7163 tog_free_refs();
7164 return error;
7167 static const struct got_error *
7168 draw_tree_entries(struct tog_view *view, const char *parent_path)
7170 struct tog_tree_view_state *s = &view->state.tree;
7171 const struct got_error *err = NULL;
7172 struct got_tree_entry *te;
7173 wchar_t *wline;
7174 char *index = NULL;
7175 struct tog_color *tc;
7176 int width, n, nentries, scrollx, i = 1;
7177 int limit = view->nlines;
7179 s->ndisplayed = 0;
7180 if (view_is_hsplit_top(view))
7181 --limit; /* border */
7183 werase(view->window);
7185 if (limit == 0)
7186 return NULL;
7188 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7189 0, 0);
7190 if (err)
7191 return err;
7192 if (view_needs_focus_indication(view))
7193 wstandout(view->window);
7194 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7195 if (tc)
7196 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7197 waddwstr(view->window, wline);
7198 free(wline);
7199 wline = NULL;
7200 while (width++ < view->ncols)
7201 waddch(view->window, ' ');
7202 if (tc)
7203 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7204 if (view_needs_focus_indication(view))
7205 wstandend(view->window);
7206 if (--limit <= 0)
7207 return NULL;
7209 i += s->selected;
7210 if (s->first_displayed_entry) {
7211 i += got_tree_entry_get_index(s->first_displayed_entry);
7212 if (s->tree != s->root)
7213 ++i; /* account for ".." entry */
7215 nentries = got_object_tree_get_nentries(s->tree);
7216 if (asprintf(&index, "[%d/%d] %s",
7217 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7218 return got_error_from_errno("asprintf");
7219 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7220 free(index);
7221 if (err)
7222 return err;
7223 waddwstr(view->window, wline);
7224 free(wline);
7225 wline = NULL;
7226 if (width < view->ncols - 1)
7227 waddch(view->window, '\n');
7228 if (--limit <= 0)
7229 return NULL;
7230 waddch(view->window, '\n');
7231 if (--limit <= 0)
7232 return NULL;
7234 if (s->first_displayed_entry == NULL) {
7235 te = got_object_tree_get_first_entry(s->tree);
7236 if (s->selected == 0) {
7237 if (view->focussed)
7238 wstandout(view->window);
7239 s->selected_entry = NULL;
7241 waddstr(view->window, " ..\n"); /* parent directory */
7242 if (s->selected == 0 && view->focussed)
7243 wstandend(view->window);
7244 s->ndisplayed++;
7245 if (--limit <= 0)
7246 return NULL;
7247 n = 1;
7248 } else {
7249 n = 0;
7250 te = s->first_displayed_entry;
7253 view->maxx = 0;
7254 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7255 char *line = NULL, *id_str = NULL, *link_target = NULL;
7256 const char *modestr = "";
7257 mode_t mode;
7259 te = got_object_tree_get_entry(s->tree, i);
7260 mode = got_tree_entry_get_mode(te);
7262 if (s->show_ids) {
7263 err = got_object_id_str(&id_str,
7264 got_tree_entry_get_id(te));
7265 if (err)
7266 return got_error_from_errno(
7267 "got_object_id_str");
7269 if (got_object_tree_entry_is_submodule(te))
7270 modestr = "$";
7271 else if (S_ISLNK(mode)) {
7272 int i;
7274 err = got_tree_entry_get_symlink_target(&link_target,
7275 te, s->repo);
7276 if (err) {
7277 free(id_str);
7278 return err;
7280 for (i = 0; i < strlen(link_target); i++) {
7281 if (!isprint((unsigned char)link_target[i]))
7282 link_target[i] = '?';
7284 modestr = "@";
7286 else if (S_ISDIR(mode))
7287 modestr = "/";
7288 else if (mode & S_IXUSR)
7289 modestr = "*";
7290 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7291 got_tree_entry_get_name(te), modestr,
7292 link_target ? " -> ": "",
7293 link_target ? link_target : "") == -1) {
7294 free(id_str);
7295 free(link_target);
7296 return got_error_from_errno("asprintf");
7298 free(id_str);
7299 free(link_target);
7301 /* use full line width to determine view->maxx */
7302 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7303 if (err) {
7304 free(line);
7305 break;
7307 view->maxx = MAX(view->maxx, width);
7308 free(wline);
7309 wline = NULL;
7311 err = format_line(&wline, &width, &scrollx, line, view->x,
7312 view->ncols, 0, 0);
7313 if (err) {
7314 free(line);
7315 break;
7317 if (n == s->selected) {
7318 if (view->focussed)
7319 wstandout(view->window);
7320 s->selected_entry = te;
7322 tc = match_color(&s->colors, line);
7323 if (tc)
7324 wattr_on(view->window,
7325 COLOR_PAIR(tc->colorpair), NULL);
7326 waddwstr(view->window, &wline[scrollx]);
7327 if (tc)
7328 wattr_off(view->window,
7329 COLOR_PAIR(tc->colorpair), NULL);
7330 if (width < view->ncols)
7331 waddch(view->window, '\n');
7332 if (n == s->selected && view->focussed)
7333 wstandend(view->window);
7334 free(line);
7335 free(wline);
7336 wline = NULL;
7337 n++;
7338 s->ndisplayed++;
7339 s->last_displayed_entry = te;
7340 if (--limit <= 0)
7341 break;
7344 return err;
7347 static void
7348 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7350 struct got_tree_entry *te;
7351 int isroot = s->tree == s->root;
7352 int i = 0;
7354 if (s->first_displayed_entry == NULL)
7355 return;
7357 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7358 while (i++ < maxscroll) {
7359 if (te == NULL) {
7360 if (!isroot)
7361 s->first_displayed_entry = NULL;
7362 break;
7364 s->first_displayed_entry = te;
7365 te = got_tree_entry_get_prev(s->tree, te);
7369 static const struct got_error *
7370 tree_scroll_down(struct tog_view *view, int maxscroll)
7372 struct tog_tree_view_state *s = &view->state.tree;
7373 struct got_tree_entry *next, *last;
7374 int n = 0;
7376 if (s->first_displayed_entry)
7377 next = got_tree_entry_get_next(s->tree,
7378 s->first_displayed_entry);
7379 else
7380 next = got_object_tree_get_first_entry(s->tree);
7382 last = s->last_displayed_entry;
7383 while (next && n++ < maxscroll) {
7384 if (last) {
7385 s->last_displayed_entry = last;
7386 last = got_tree_entry_get_next(s->tree, last);
7388 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7389 s->first_displayed_entry = next;
7390 next = got_tree_entry_get_next(s->tree, next);
7394 return NULL;
7397 static const struct got_error *
7398 tree_entry_path(char **path, struct tog_parent_trees *parents,
7399 struct got_tree_entry *te)
7401 const struct got_error *err = NULL;
7402 struct tog_parent_tree *pt;
7403 size_t len = 2; /* for leading slash and NUL */
7405 TAILQ_FOREACH(pt, parents, entry)
7406 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7407 + 1 /* slash */;
7408 if (te)
7409 len += strlen(got_tree_entry_get_name(te));
7411 *path = calloc(1, len);
7412 if (path == NULL)
7413 return got_error_from_errno("calloc");
7415 (*path)[0] = '/';
7416 pt = TAILQ_LAST(parents, tog_parent_trees);
7417 while (pt) {
7418 const char *name = got_tree_entry_get_name(pt->selected_entry);
7419 if (strlcat(*path, name, len) >= len) {
7420 err = got_error(GOT_ERR_NO_SPACE);
7421 goto done;
7423 if (strlcat(*path, "/", len) >= len) {
7424 err = got_error(GOT_ERR_NO_SPACE);
7425 goto done;
7427 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7429 if (te) {
7430 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7431 err = got_error(GOT_ERR_NO_SPACE);
7432 goto done;
7435 done:
7436 if (err) {
7437 free(*path);
7438 *path = NULL;
7440 return err;
7443 static const struct got_error *
7444 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7445 struct got_tree_entry *te, struct tog_parent_trees *parents,
7446 struct got_object_id *commit_id, struct got_repository *repo)
7448 const struct got_error *err = NULL;
7449 char *path;
7450 struct tog_view *blame_view;
7452 *new_view = NULL;
7454 err = tree_entry_path(&path, parents, te);
7455 if (err)
7456 return err;
7458 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7459 if (blame_view == NULL) {
7460 err = got_error_from_errno("view_open");
7461 goto done;
7464 err = open_blame_view(blame_view, path, commit_id, repo);
7465 if (err) {
7466 if (err->code == GOT_ERR_CANCELLED)
7467 err = NULL;
7468 view_close(blame_view);
7469 } else
7470 *new_view = blame_view;
7471 done:
7472 free(path);
7473 return err;
7476 static const struct got_error *
7477 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7478 struct tog_tree_view_state *s)
7480 struct tog_view *log_view;
7481 const struct got_error *err = NULL;
7482 char *path;
7484 *new_view = NULL;
7486 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7487 if (log_view == NULL)
7488 return got_error_from_errno("view_open");
7490 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7491 if (err)
7492 return err;
7494 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7495 path, 0);
7496 if (err)
7497 view_close(log_view);
7498 else
7499 *new_view = log_view;
7500 free(path);
7501 return err;
7504 static const struct got_error *
7505 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7506 const char *head_ref_name, struct got_repository *repo)
7508 const struct got_error *err = NULL;
7509 char *commit_id_str = NULL;
7510 struct tog_tree_view_state *s = &view->state.tree;
7511 struct got_commit_object *commit = NULL;
7513 TAILQ_INIT(&s->parents);
7514 STAILQ_INIT(&s->colors);
7516 s->commit_id = got_object_id_dup(commit_id);
7517 if (s->commit_id == NULL) {
7518 err = got_error_from_errno("got_object_id_dup");
7519 goto done;
7522 err = got_object_open_as_commit(&commit, repo, commit_id);
7523 if (err)
7524 goto done;
7527 * The root is opened here and will be closed when the view is closed.
7528 * Any visited subtrees and their path-wise parents are opened and
7529 * closed on demand.
7531 err = got_object_open_as_tree(&s->root, repo,
7532 got_object_commit_get_tree_id(commit));
7533 if (err)
7534 goto done;
7535 s->tree = s->root;
7537 err = got_object_id_str(&commit_id_str, commit_id);
7538 if (err != NULL)
7539 goto done;
7541 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7542 err = got_error_from_errno("asprintf");
7543 goto done;
7546 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7547 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7548 if (head_ref_name) {
7549 s->head_ref_name = strdup(head_ref_name);
7550 if (s->head_ref_name == NULL) {
7551 err = got_error_from_errno("strdup");
7552 goto done;
7555 s->repo = repo;
7557 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7558 err = add_color(&s->colors, "\\$$",
7559 TOG_COLOR_TREE_SUBMODULE,
7560 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7561 if (err)
7562 goto done;
7563 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7564 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7565 if (err)
7566 goto done;
7567 err = add_color(&s->colors, "/$",
7568 TOG_COLOR_TREE_DIRECTORY,
7569 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7570 if (err)
7571 goto done;
7573 err = add_color(&s->colors, "\\*$",
7574 TOG_COLOR_TREE_EXECUTABLE,
7575 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7576 if (err)
7577 goto done;
7579 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7580 get_color_value("TOG_COLOR_COMMIT"));
7581 if (err)
7582 goto done;
7585 view->show = show_tree_view;
7586 view->input = input_tree_view;
7587 view->close = close_tree_view;
7588 view->search_start = search_start_tree_view;
7589 view->search_next = search_next_tree_view;
7590 done:
7591 free(commit_id_str);
7592 if (commit)
7593 got_object_commit_close(commit);
7594 if (err) {
7595 if (view->close == NULL)
7596 close_tree_view(view);
7597 view_close(view);
7599 return err;
7602 static const struct got_error *
7603 close_tree_view(struct tog_view *view)
7605 struct tog_tree_view_state *s = &view->state.tree;
7607 free_colors(&s->colors);
7608 free(s->tree_label);
7609 s->tree_label = NULL;
7610 free(s->commit_id);
7611 s->commit_id = NULL;
7612 free(s->head_ref_name);
7613 s->head_ref_name = NULL;
7614 while (!TAILQ_EMPTY(&s->parents)) {
7615 struct tog_parent_tree *parent;
7616 parent = TAILQ_FIRST(&s->parents);
7617 TAILQ_REMOVE(&s->parents, parent, entry);
7618 if (parent->tree != s->root)
7619 got_object_tree_close(parent->tree);
7620 free(parent);
7623 if (s->tree != NULL && s->tree != s->root)
7624 got_object_tree_close(s->tree);
7625 if (s->root)
7626 got_object_tree_close(s->root);
7627 return NULL;
7630 static const struct got_error *
7631 search_start_tree_view(struct tog_view *view)
7633 struct tog_tree_view_state *s = &view->state.tree;
7635 s->matched_entry = NULL;
7636 return NULL;
7639 static int
7640 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7642 regmatch_t regmatch;
7644 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7645 0) == 0;
7648 static const struct got_error *
7649 search_next_tree_view(struct tog_view *view)
7651 struct tog_tree_view_state *s = &view->state.tree;
7652 struct got_tree_entry *te = NULL;
7654 if (!view->searching) {
7655 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7656 return NULL;
7659 if (s->matched_entry) {
7660 if (view->searching == TOG_SEARCH_FORWARD) {
7661 if (s->selected_entry)
7662 te = got_tree_entry_get_next(s->tree,
7663 s->selected_entry);
7664 else
7665 te = got_object_tree_get_first_entry(s->tree);
7666 } else {
7667 if (s->selected_entry == NULL)
7668 te = got_object_tree_get_last_entry(s->tree);
7669 else
7670 te = got_tree_entry_get_prev(s->tree,
7671 s->selected_entry);
7673 } else {
7674 if (s->selected_entry)
7675 te = s->selected_entry;
7676 else if (view->searching == TOG_SEARCH_FORWARD)
7677 te = got_object_tree_get_first_entry(s->tree);
7678 else
7679 te = got_object_tree_get_last_entry(s->tree);
7682 while (1) {
7683 if (te == NULL) {
7684 if (s->matched_entry == NULL) {
7685 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7686 return NULL;
7688 if (view->searching == TOG_SEARCH_FORWARD)
7689 te = got_object_tree_get_first_entry(s->tree);
7690 else
7691 te = got_object_tree_get_last_entry(s->tree);
7694 if (match_tree_entry(te, &view->regex)) {
7695 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7696 s->matched_entry = te;
7697 break;
7700 if (view->searching == TOG_SEARCH_FORWARD)
7701 te = got_tree_entry_get_next(s->tree, te);
7702 else
7703 te = got_tree_entry_get_prev(s->tree, te);
7706 if (s->matched_entry) {
7707 s->first_displayed_entry = s->matched_entry;
7708 s->selected = 0;
7711 return NULL;
7714 static const struct got_error *
7715 show_tree_view(struct tog_view *view)
7717 const struct got_error *err = NULL;
7718 struct tog_tree_view_state *s = &view->state.tree;
7719 char *parent_path;
7721 err = tree_entry_path(&parent_path, &s->parents, NULL);
7722 if (err)
7723 return err;
7725 err = draw_tree_entries(view, parent_path);
7726 free(parent_path);
7728 view_border(view);
7729 return err;
7732 static const struct got_error *
7733 tree_goto_line(struct tog_view *view, int nlines)
7735 const struct got_error *err = NULL;
7736 struct tog_tree_view_state *s = &view->state.tree;
7737 struct got_tree_entry **fte, **lte, **ste;
7738 int g, last, first = 1, i = 1;
7739 int root = s->tree == s->root;
7740 int off = root ? 1 : 2;
7742 g = view->gline;
7743 view->gline = 0;
7745 if (g == 0)
7746 g = 1;
7747 else if (g > got_object_tree_get_nentries(s->tree))
7748 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7750 fte = &s->first_displayed_entry;
7751 lte = &s->last_displayed_entry;
7752 ste = &s->selected_entry;
7754 if (*fte != NULL) {
7755 first = got_tree_entry_get_index(*fte);
7756 first += off; /* account for ".." */
7758 last = got_tree_entry_get_index(*lte);
7759 last += off;
7761 if (g >= first && g <= last && g - first < nlines) {
7762 s->selected = g - first;
7763 return NULL; /* gline is on the current page */
7766 if (*ste != NULL) {
7767 i = got_tree_entry_get_index(*ste);
7768 i += off;
7771 if (i < g) {
7772 err = tree_scroll_down(view, g - i);
7773 if (err)
7774 return err;
7775 if (got_tree_entry_get_index(*lte) >=
7776 got_object_tree_get_nentries(s->tree) - 1 &&
7777 first + s->selected < g &&
7778 s->selected < s->ndisplayed - 1) {
7779 first = got_tree_entry_get_index(*fte);
7780 first += off;
7781 s->selected = g - first;
7783 } else if (i > g)
7784 tree_scroll_up(s, i - g);
7786 if (g < nlines &&
7787 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7788 s->selected = g - 1;
7790 return NULL;
7793 static const struct got_error *
7794 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7796 const struct got_error *err = NULL;
7797 struct tog_tree_view_state *s = &view->state.tree;
7798 struct got_tree_entry *te;
7799 int n, nscroll = view->nlines - 3;
7801 if (view->gline)
7802 return tree_goto_line(view, nscroll);
7804 switch (ch) {
7805 case '0':
7806 case '$':
7807 case KEY_RIGHT:
7808 case 'l':
7809 case KEY_LEFT:
7810 case 'h':
7811 horizontal_scroll_input(view, ch);
7812 break;
7813 case 'i':
7814 s->show_ids = !s->show_ids;
7815 view->count = 0;
7816 break;
7817 case 'L':
7818 view->count = 0;
7819 if (!s->selected_entry)
7820 break;
7821 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7822 break;
7823 case 'R':
7824 view->count = 0;
7825 err = view_request_new(new_view, view, TOG_VIEW_REF);
7826 break;
7827 case 'g':
7828 case '=':
7829 case KEY_HOME:
7830 s->selected = 0;
7831 view->count = 0;
7832 if (s->tree == s->root)
7833 s->first_displayed_entry =
7834 got_object_tree_get_first_entry(s->tree);
7835 else
7836 s->first_displayed_entry = NULL;
7837 break;
7838 case 'G':
7839 case '*':
7840 case KEY_END: {
7841 int eos = view->nlines - 3;
7843 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7844 --eos; /* border */
7845 s->selected = 0;
7846 view->count = 0;
7847 te = got_object_tree_get_last_entry(s->tree);
7848 for (n = 0; n < eos; n++) {
7849 if (te == NULL) {
7850 if (s->tree != s->root) {
7851 s->first_displayed_entry = NULL;
7852 n++;
7854 break;
7856 s->first_displayed_entry = te;
7857 te = got_tree_entry_get_prev(s->tree, te);
7859 if (n > 0)
7860 s->selected = n - 1;
7861 break;
7863 case 'k':
7864 case KEY_UP:
7865 case CTRL('p'):
7866 if (s->selected > 0) {
7867 s->selected--;
7868 break;
7870 tree_scroll_up(s, 1);
7871 if (s->selected_entry == NULL ||
7872 (s->tree == s->root && s->selected_entry ==
7873 got_object_tree_get_first_entry(s->tree)))
7874 view->count = 0;
7875 break;
7876 case CTRL('u'):
7877 case 'u':
7878 nscroll /= 2;
7879 /* FALL THROUGH */
7880 case KEY_PPAGE:
7881 case CTRL('b'):
7882 case 'b':
7883 if (s->tree == s->root) {
7884 if (got_object_tree_get_first_entry(s->tree) ==
7885 s->first_displayed_entry)
7886 s->selected -= MIN(s->selected, nscroll);
7887 } else {
7888 if (s->first_displayed_entry == NULL)
7889 s->selected -= MIN(s->selected, nscroll);
7891 tree_scroll_up(s, MAX(0, nscroll));
7892 if (s->selected_entry == NULL ||
7893 (s->tree == s->root && s->selected_entry ==
7894 got_object_tree_get_first_entry(s->tree)))
7895 view->count = 0;
7896 break;
7897 case 'j':
7898 case KEY_DOWN:
7899 case CTRL('n'):
7900 if (s->selected < s->ndisplayed - 1) {
7901 s->selected++;
7902 break;
7904 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7905 == NULL) {
7906 /* can't scroll any further */
7907 view->count = 0;
7908 break;
7910 tree_scroll_down(view, 1);
7911 break;
7912 case CTRL('d'):
7913 case 'd':
7914 nscroll /= 2;
7915 /* FALL THROUGH */
7916 case KEY_NPAGE:
7917 case CTRL('f'):
7918 case 'f':
7919 case ' ':
7920 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7921 == NULL) {
7922 /* can't scroll any further; move cursor down */
7923 if (s->selected < s->ndisplayed - 1)
7924 s->selected += MIN(nscroll,
7925 s->ndisplayed - s->selected - 1);
7926 else
7927 view->count = 0;
7928 break;
7930 tree_scroll_down(view, nscroll);
7931 break;
7932 case KEY_ENTER:
7933 case '\r':
7934 case KEY_BACKSPACE:
7935 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7936 struct tog_parent_tree *parent;
7937 /* user selected '..' */
7938 if (s->tree == s->root) {
7939 view->count = 0;
7940 break;
7942 parent = TAILQ_FIRST(&s->parents);
7943 TAILQ_REMOVE(&s->parents, parent,
7944 entry);
7945 got_object_tree_close(s->tree);
7946 s->tree = parent->tree;
7947 s->first_displayed_entry =
7948 parent->first_displayed_entry;
7949 s->selected_entry =
7950 parent->selected_entry;
7951 s->selected = parent->selected;
7952 if (s->selected > view->nlines - 3) {
7953 err = offset_selection_down(view);
7954 if (err)
7955 break;
7957 free(parent);
7958 } else if (S_ISDIR(got_tree_entry_get_mode(
7959 s->selected_entry))) {
7960 struct got_tree_object *subtree;
7961 view->count = 0;
7962 err = got_object_open_as_tree(&subtree, s->repo,
7963 got_tree_entry_get_id(s->selected_entry));
7964 if (err)
7965 break;
7966 err = tree_view_visit_subtree(s, subtree);
7967 if (err) {
7968 got_object_tree_close(subtree);
7969 break;
7971 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7972 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7973 break;
7974 case KEY_RESIZE:
7975 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7976 s->selected = view->nlines - 4;
7977 view->count = 0;
7978 break;
7979 default:
7980 view->count = 0;
7981 break;
7984 return err;
7987 __dead static void
7988 usage_tree(void)
7990 endwin();
7991 fprintf(stderr,
7992 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7993 getprogname());
7994 exit(1);
7997 static const struct got_error *
7998 cmd_tree(int argc, char *argv[])
8000 const struct got_error *error;
8001 struct got_repository *repo = NULL;
8002 struct got_worktree *worktree = NULL;
8003 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8004 struct got_object_id *commit_id = NULL;
8005 struct got_commit_object *commit = NULL;
8006 const char *commit_id_arg = NULL;
8007 char *label = NULL;
8008 struct got_reference *ref = NULL;
8009 const char *head_ref_name = NULL;
8010 int ch;
8011 struct tog_view *view;
8012 int *pack_fds = NULL;
8014 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8015 switch (ch) {
8016 case 'c':
8017 commit_id_arg = optarg;
8018 break;
8019 case 'r':
8020 repo_path = realpath(optarg, NULL);
8021 if (repo_path == NULL)
8022 return got_error_from_errno2("realpath",
8023 optarg);
8024 break;
8025 default:
8026 usage_tree();
8027 /* NOTREACHED */
8031 argc -= optind;
8032 argv += optind;
8034 if (argc > 1)
8035 usage_tree();
8037 error = got_repo_pack_fds_open(&pack_fds);
8038 if (error != NULL)
8039 goto done;
8041 if (repo_path == NULL) {
8042 cwd = getcwd(NULL, 0);
8043 if (cwd == NULL)
8044 return got_error_from_errno("getcwd");
8045 error = got_worktree_open(&worktree, cwd);
8046 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8047 goto done;
8048 if (worktree)
8049 repo_path =
8050 strdup(got_worktree_get_repo_path(worktree));
8051 else
8052 repo_path = strdup(cwd);
8053 if (repo_path == NULL) {
8054 error = got_error_from_errno("strdup");
8055 goto done;
8059 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8060 if (error != NULL)
8061 goto done;
8063 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8064 repo, worktree);
8065 if (error)
8066 goto done;
8068 init_curses();
8070 error = apply_unveil(got_repo_get_path(repo), NULL);
8071 if (error)
8072 goto done;
8074 error = tog_load_refs(repo, 0);
8075 if (error)
8076 goto done;
8078 if (commit_id_arg == NULL) {
8079 error = got_repo_match_object_id(&commit_id, &label,
8080 worktree ? got_worktree_get_head_ref_name(worktree) :
8081 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8082 if (error)
8083 goto done;
8084 head_ref_name = label;
8085 } else {
8086 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8087 if (error == NULL)
8088 head_ref_name = got_ref_get_name(ref);
8089 else if (error->code != GOT_ERR_NOT_REF)
8090 goto done;
8091 error = got_repo_match_object_id(&commit_id, NULL,
8092 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8093 if (error)
8094 goto done;
8097 error = got_object_open_as_commit(&commit, repo, commit_id);
8098 if (error)
8099 goto done;
8101 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8102 if (view == NULL) {
8103 error = got_error_from_errno("view_open");
8104 goto done;
8106 error = open_tree_view(view, commit_id, head_ref_name, repo);
8107 if (error)
8108 goto done;
8109 if (!got_path_is_root_dir(in_repo_path)) {
8110 error = tree_view_walk_path(&view->state.tree, commit,
8111 in_repo_path);
8112 if (error)
8113 goto done;
8116 if (worktree) {
8117 /* Release work tree lock. */
8118 got_worktree_close(worktree);
8119 worktree = NULL;
8121 error = view_loop(view);
8122 done:
8123 free(repo_path);
8124 free(cwd);
8125 free(commit_id);
8126 free(label);
8127 if (ref)
8128 got_ref_close(ref);
8129 if (repo) {
8130 const struct got_error *close_err = got_repo_close(repo);
8131 if (error == NULL)
8132 error = close_err;
8134 if (pack_fds) {
8135 const struct got_error *pack_err =
8136 got_repo_pack_fds_close(pack_fds);
8137 if (error == NULL)
8138 error = pack_err;
8140 tog_free_refs();
8141 return error;
8144 static const struct got_error *
8145 ref_view_load_refs(struct tog_ref_view_state *s)
8147 struct got_reflist_entry *sre;
8148 struct tog_reflist_entry *re;
8150 s->nrefs = 0;
8151 TAILQ_FOREACH(sre, &tog_refs, entry) {
8152 if (strncmp(got_ref_get_name(sre->ref),
8153 "refs/got/", 9) == 0 &&
8154 strncmp(got_ref_get_name(sre->ref),
8155 "refs/got/backup/", 16) != 0)
8156 continue;
8158 re = malloc(sizeof(*re));
8159 if (re == NULL)
8160 return got_error_from_errno("malloc");
8162 re->ref = got_ref_dup(sre->ref);
8163 if (re->ref == NULL)
8164 return got_error_from_errno("got_ref_dup");
8165 re->idx = s->nrefs++;
8166 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8169 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8170 return NULL;
8173 static void
8174 ref_view_free_refs(struct tog_ref_view_state *s)
8176 struct tog_reflist_entry *re;
8178 while (!TAILQ_EMPTY(&s->refs)) {
8179 re = TAILQ_FIRST(&s->refs);
8180 TAILQ_REMOVE(&s->refs, re, entry);
8181 got_ref_close(re->ref);
8182 free(re);
8186 static const struct got_error *
8187 open_ref_view(struct tog_view *view, struct got_repository *repo)
8189 const struct got_error *err = NULL;
8190 struct tog_ref_view_state *s = &view->state.ref;
8192 s->selected_entry = 0;
8193 s->repo = repo;
8195 TAILQ_INIT(&s->refs);
8196 STAILQ_INIT(&s->colors);
8198 err = ref_view_load_refs(s);
8199 if (err)
8200 goto done;
8202 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8203 err = add_color(&s->colors, "^refs/heads/",
8204 TOG_COLOR_REFS_HEADS,
8205 get_color_value("TOG_COLOR_REFS_HEADS"));
8206 if (err)
8207 goto done;
8209 err = add_color(&s->colors, "^refs/tags/",
8210 TOG_COLOR_REFS_TAGS,
8211 get_color_value("TOG_COLOR_REFS_TAGS"));
8212 if (err)
8213 goto done;
8215 err = add_color(&s->colors, "^refs/remotes/",
8216 TOG_COLOR_REFS_REMOTES,
8217 get_color_value("TOG_COLOR_REFS_REMOTES"));
8218 if (err)
8219 goto done;
8221 err = add_color(&s->colors, "^refs/got/backup/",
8222 TOG_COLOR_REFS_BACKUP,
8223 get_color_value("TOG_COLOR_REFS_BACKUP"));
8224 if (err)
8225 goto done;
8228 view->show = show_ref_view;
8229 view->input = input_ref_view;
8230 view->close = close_ref_view;
8231 view->search_start = search_start_ref_view;
8232 view->search_next = search_next_ref_view;
8233 done:
8234 if (err) {
8235 if (view->close == NULL)
8236 close_ref_view(view);
8237 view_close(view);
8239 return err;
8242 static const struct got_error *
8243 close_ref_view(struct tog_view *view)
8245 struct tog_ref_view_state *s = &view->state.ref;
8247 ref_view_free_refs(s);
8248 free_colors(&s->colors);
8250 return NULL;
8253 static const struct got_error *
8254 resolve_reflist_entry(struct got_object_id **commit_id,
8255 struct tog_reflist_entry *re, struct got_repository *repo)
8257 const struct got_error *err = NULL;
8258 struct got_object_id *obj_id;
8259 struct got_tag_object *tag = NULL;
8260 int obj_type;
8262 *commit_id = NULL;
8264 err = got_ref_resolve(&obj_id, repo, re->ref);
8265 if (err)
8266 return err;
8268 err = got_object_get_type(&obj_type, repo, obj_id);
8269 if (err)
8270 goto done;
8272 switch (obj_type) {
8273 case GOT_OBJ_TYPE_COMMIT:
8274 *commit_id = obj_id;
8275 break;
8276 case GOT_OBJ_TYPE_TAG:
8277 err = got_object_open_as_tag(&tag, repo, obj_id);
8278 if (err)
8279 goto done;
8280 free(obj_id);
8281 err = got_object_get_type(&obj_type, repo,
8282 got_object_tag_get_object_id(tag));
8283 if (err)
8284 goto done;
8285 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8286 err = got_error(GOT_ERR_OBJ_TYPE);
8287 goto done;
8289 *commit_id = got_object_id_dup(
8290 got_object_tag_get_object_id(tag));
8291 if (*commit_id == NULL) {
8292 err = got_error_from_errno("got_object_id_dup");
8293 goto done;
8295 break;
8296 default:
8297 err = got_error(GOT_ERR_OBJ_TYPE);
8298 break;
8301 done:
8302 if (tag)
8303 got_object_tag_close(tag);
8304 if (err) {
8305 free(*commit_id);
8306 *commit_id = NULL;
8308 return err;
8311 static const struct got_error *
8312 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8313 struct tog_reflist_entry *re, struct got_repository *repo)
8315 struct tog_view *log_view;
8316 const struct got_error *err = NULL;
8317 struct got_object_id *commit_id = NULL;
8319 *new_view = NULL;
8321 err = resolve_reflist_entry(&commit_id, re, repo);
8322 if (err) {
8323 if (err->code != GOT_ERR_OBJ_TYPE)
8324 return err;
8325 else
8326 return NULL;
8329 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8330 if (log_view == NULL) {
8331 err = got_error_from_errno("view_open");
8332 goto done;
8335 err = open_log_view(log_view, commit_id, repo,
8336 got_ref_get_name(re->ref), "", 0);
8337 done:
8338 if (err)
8339 view_close(log_view);
8340 else
8341 *new_view = log_view;
8342 free(commit_id);
8343 return err;
8346 static void
8347 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8349 struct tog_reflist_entry *re;
8350 int i = 0;
8352 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8353 return;
8355 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8356 while (i++ < maxscroll) {
8357 if (re == NULL)
8358 break;
8359 s->first_displayed_entry = re;
8360 re = TAILQ_PREV(re, tog_reflist_head, entry);
8364 static const struct got_error *
8365 ref_scroll_down(struct tog_view *view, int maxscroll)
8367 struct tog_ref_view_state *s = &view->state.ref;
8368 struct tog_reflist_entry *next, *last;
8369 int n = 0;
8371 if (s->first_displayed_entry)
8372 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8373 else
8374 next = TAILQ_FIRST(&s->refs);
8376 last = s->last_displayed_entry;
8377 while (next && n++ < maxscroll) {
8378 if (last) {
8379 s->last_displayed_entry = last;
8380 last = TAILQ_NEXT(last, entry);
8382 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8383 s->first_displayed_entry = next;
8384 next = TAILQ_NEXT(next, entry);
8388 return NULL;
8391 static const struct got_error *
8392 search_start_ref_view(struct tog_view *view)
8394 struct tog_ref_view_state *s = &view->state.ref;
8396 s->matched_entry = NULL;
8397 return NULL;
8400 static int
8401 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8403 regmatch_t regmatch;
8405 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8406 0) == 0;
8409 static const struct got_error *
8410 search_next_ref_view(struct tog_view *view)
8412 struct tog_ref_view_state *s = &view->state.ref;
8413 struct tog_reflist_entry *re = NULL;
8415 if (!view->searching) {
8416 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8417 return NULL;
8420 if (s->matched_entry) {
8421 if (view->searching == TOG_SEARCH_FORWARD) {
8422 if (s->selected_entry)
8423 re = TAILQ_NEXT(s->selected_entry, entry);
8424 else
8425 re = TAILQ_PREV(s->selected_entry,
8426 tog_reflist_head, entry);
8427 } else {
8428 if (s->selected_entry == NULL)
8429 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8430 else
8431 re = TAILQ_PREV(s->selected_entry,
8432 tog_reflist_head, entry);
8434 } else {
8435 if (s->selected_entry)
8436 re = s->selected_entry;
8437 else if (view->searching == TOG_SEARCH_FORWARD)
8438 re = TAILQ_FIRST(&s->refs);
8439 else
8440 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8443 while (1) {
8444 if (re == NULL) {
8445 if (s->matched_entry == NULL) {
8446 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8447 return NULL;
8449 if (view->searching == TOG_SEARCH_FORWARD)
8450 re = TAILQ_FIRST(&s->refs);
8451 else
8452 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8455 if (match_reflist_entry(re, &view->regex)) {
8456 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8457 s->matched_entry = re;
8458 break;
8461 if (view->searching == TOG_SEARCH_FORWARD)
8462 re = TAILQ_NEXT(re, entry);
8463 else
8464 re = TAILQ_PREV(re, tog_reflist_head, entry);
8467 if (s->matched_entry) {
8468 s->first_displayed_entry = s->matched_entry;
8469 s->selected = 0;
8472 return NULL;
8475 static const struct got_error *
8476 show_ref_view(struct tog_view *view)
8478 const struct got_error *err = NULL;
8479 struct tog_ref_view_state *s = &view->state.ref;
8480 struct tog_reflist_entry *re;
8481 char *line = NULL;
8482 wchar_t *wline;
8483 struct tog_color *tc;
8484 int width, n, scrollx;
8485 int limit = view->nlines;
8487 werase(view->window);
8489 s->ndisplayed = 0;
8490 if (view_is_hsplit_top(view))
8491 --limit; /* border */
8493 if (limit == 0)
8494 return NULL;
8496 re = s->first_displayed_entry;
8498 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8499 s->nrefs) == -1)
8500 return got_error_from_errno("asprintf");
8502 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8503 if (err) {
8504 free(line);
8505 return err;
8507 if (view_needs_focus_indication(view))
8508 wstandout(view->window);
8509 waddwstr(view->window, wline);
8510 while (width++ < view->ncols)
8511 waddch(view->window, ' ');
8512 if (view_needs_focus_indication(view))
8513 wstandend(view->window);
8514 free(wline);
8515 wline = NULL;
8516 free(line);
8517 line = NULL;
8518 if (--limit <= 0)
8519 return NULL;
8521 n = 0;
8522 view->maxx = 0;
8523 while (re && limit > 0) {
8524 char *line = NULL;
8525 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8527 if (s->show_date) {
8528 struct got_commit_object *ci;
8529 struct got_tag_object *tag;
8530 struct got_object_id *id;
8531 struct tm tm;
8532 time_t t;
8534 err = got_ref_resolve(&id, s->repo, re->ref);
8535 if (err)
8536 return err;
8537 err = got_object_open_as_tag(&tag, s->repo, id);
8538 if (err) {
8539 if (err->code != GOT_ERR_OBJ_TYPE) {
8540 free(id);
8541 return err;
8543 err = got_object_open_as_commit(&ci, s->repo,
8544 id);
8545 if (err) {
8546 free(id);
8547 return err;
8549 t = got_object_commit_get_committer_time(ci);
8550 got_object_commit_close(ci);
8551 } else {
8552 t = got_object_tag_get_tagger_time(tag);
8553 got_object_tag_close(tag);
8555 free(id);
8556 if (gmtime_r(&t, &tm) == NULL)
8557 return got_error_from_errno("gmtime_r");
8558 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8559 return got_error(GOT_ERR_NO_SPACE);
8561 if (got_ref_is_symbolic(re->ref)) {
8562 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8563 ymd : "", got_ref_get_name(re->ref),
8564 got_ref_get_symref_target(re->ref)) == -1)
8565 return got_error_from_errno("asprintf");
8566 } else if (s->show_ids) {
8567 struct got_object_id *id;
8568 char *id_str;
8569 err = got_ref_resolve(&id, s->repo, re->ref);
8570 if (err)
8571 return err;
8572 err = got_object_id_str(&id_str, id);
8573 if (err) {
8574 free(id);
8575 return err;
8577 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8578 got_ref_get_name(re->ref), id_str) == -1) {
8579 err = got_error_from_errno("asprintf");
8580 free(id);
8581 free(id_str);
8582 return err;
8584 free(id);
8585 free(id_str);
8586 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8587 got_ref_get_name(re->ref)) == -1)
8588 return got_error_from_errno("asprintf");
8590 /* use full line width to determine view->maxx */
8591 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8592 if (err) {
8593 free(line);
8594 return err;
8596 view->maxx = MAX(view->maxx, width);
8597 free(wline);
8598 wline = NULL;
8600 err = format_line(&wline, &width, &scrollx, line, view->x,
8601 view->ncols, 0, 0);
8602 if (err) {
8603 free(line);
8604 return err;
8606 if (n == s->selected) {
8607 if (view->focussed)
8608 wstandout(view->window);
8609 s->selected_entry = re;
8611 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8612 if (tc)
8613 wattr_on(view->window,
8614 COLOR_PAIR(tc->colorpair), NULL);
8615 waddwstr(view->window, &wline[scrollx]);
8616 if (tc)
8617 wattr_off(view->window,
8618 COLOR_PAIR(tc->colorpair), NULL);
8619 if (width < view->ncols)
8620 waddch(view->window, '\n');
8621 if (n == s->selected && view->focussed)
8622 wstandend(view->window);
8623 free(line);
8624 free(wline);
8625 wline = NULL;
8626 n++;
8627 s->ndisplayed++;
8628 s->last_displayed_entry = re;
8630 limit--;
8631 re = TAILQ_NEXT(re, entry);
8634 view_border(view);
8635 return err;
8638 static const struct got_error *
8639 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8640 struct tog_reflist_entry *re, struct got_repository *repo)
8642 const struct got_error *err = NULL;
8643 struct got_object_id *commit_id = NULL;
8644 struct tog_view *tree_view;
8646 *new_view = NULL;
8648 err = resolve_reflist_entry(&commit_id, re, repo);
8649 if (err) {
8650 if (err->code != GOT_ERR_OBJ_TYPE)
8651 return err;
8652 else
8653 return NULL;
8657 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8658 if (tree_view == NULL) {
8659 err = got_error_from_errno("view_open");
8660 goto done;
8663 err = open_tree_view(tree_view, commit_id,
8664 got_ref_get_name(re->ref), repo);
8665 if (err)
8666 goto done;
8668 *new_view = tree_view;
8669 done:
8670 free(commit_id);
8671 return err;
8674 static const struct got_error *
8675 ref_goto_line(struct tog_view *view, int nlines)
8677 const struct got_error *err = NULL;
8678 struct tog_ref_view_state *s = &view->state.ref;
8679 int g, idx = s->selected_entry->idx;
8681 g = view->gline;
8682 view->gline = 0;
8684 if (g == 0)
8685 g = 1;
8686 else if (g > s->nrefs)
8687 g = s->nrefs;
8689 if (g >= s->first_displayed_entry->idx + 1 &&
8690 g <= s->last_displayed_entry->idx + 1 &&
8691 g - s->first_displayed_entry->idx - 1 < nlines) {
8692 s->selected = g - s->first_displayed_entry->idx - 1;
8693 return NULL;
8696 if (idx + 1 < g) {
8697 err = ref_scroll_down(view, g - idx - 1);
8698 if (err)
8699 return err;
8700 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8701 s->first_displayed_entry->idx + s->selected < g &&
8702 s->selected < s->ndisplayed - 1)
8703 s->selected = g - s->first_displayed_entry->idx - 1;
8704 } else if (idx + 1 > g)
8705 ref_scroll_up(s, idx - g + 1);
8707 if (g < nlines && s->first_displayed_entry->idx == 0)
8708 s->selected = g - 1;
8710 return NULL;
8714 static const struct got_error *
8715 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8717 const struct got_error *err = NULL;
8718 struct tog_ref_view_state *s = &view->state.ref;
8719 struct tog_reflist_entry *re;
8720 int n, nscroll = view->nlines - 1;
8722 if (view->gline)
8723 return ref_goto_line(view, nscroll);
8725 switch (ch) {
8726 case '0':
8727 case '$':
8728 case KEY_RIGHT:
8729 case 'l':
8730 case KEY_LEFT:
8731 case 'h':
8732 horizontal_scroll_input(view, ch);
8733 break;
8734 case 'i':
8735 s->show_ids = !s->show_ids;
8736 view->count = 0;
8737 break;
8738 case 'm':
8739 s->show_date = !s->show_date;
8740 view->count = 0;
8741 break;
8742 case 'o':
8743 s->sort_by_date = !s->sort_by_date;
8744 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8745 view->count = 0;
8746 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8747 got_ref_cmp_by_commit_timestamp_descending :
8748 tog_ref_cmp_by_name, s->repo);
8749 if (err)
8750 break;
8751 got_reflist_object_id_map_free(tog_refs_idmap);
8752 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8753 &tog_refs, s->repo);
8754 if (err)
8755 break;
8756 ref_view_free_refs(s);
8757 err = ref_view_load_refs(s);
8758 break;
8759 case KEY_ENTER:
8760 case '\r':
8761 view->count = 0;
8762 if (!s->selected_entry)
8763 break;
8764 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8765 break;
8766 case 'T':
8767 view->count = 0;
8768 if (!s->selected_entry)
8769 break;
8770 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8771 break;
8772 case 'g':
8773 case '=':
8774 case KEY_HOME:
8775 s->selected = 0;
8776 view->count = 0;
8777 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8778 break;
8779 case 'G':
8780 case '*':
8781 case KEY_END: {
8782 int eos = view->nlines - 1;
8784 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8785 --eos; /* border */
8786 s->selected = 0;
8787 view->count = 0;
8788 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8789 for (n = 0; n < eos; n++) {
8790 if (re == NULL)
8791 break;
8792 s->first_displayed_entry = re;
8793 re = TAILQ_PREV(re, tog_reflist_head, entry);
8795 if (n > 0)
8796 s->selected = n - 1;
8797 break;
8799 case 'k':
8800 case KEY_UP:
8801 case CTRL('p'):
8802 if (s->selected > 0) {
8803 s->selected--;
8804 break;
8806 ref_scroll_up(s, 1);
8807 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8808 view->count = 0;
8809 break;
8810 case CTRL('u'):
8811 case 'u':
8812 nscroll /= 2;
8813 /* FALL THROUGH */
8814 case KEY_PPAGE:
8815 case CTRL('b'):
8816 case 'b':
8817 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8818 s->selected -= MIN(nscroll, s->selected);
8819 ref_scroll_up(s, MAX(0, nscroll));
8820 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8821 view->count = 0;
8822 break;
8823 case 'j':
8824 case KEY_DOWN:
8825 case CTRL('n'):
8826 if (s->selected < s->ndisplayed - 1) {
8827 s->selected++;
8828 break;
8830 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8831 /* can't scroll any further */
8832 view->count = 0;
8833 break;
8835 ref_scroll_down(view, 1);
8836 break;
8837 case CTRL('d'):
8838 case 'd':
8839 nscroll /= 2;
8840 /* FALL THROUGH */
8841 case KEY_NPAGE:
8842 case CTRL('f'):
8843 case 'f':
8844 case ' ':
8845 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8846 /* can't scroll any further; move cursor down */
8847 if (s->selected < s->ndisplayed - 1)
8848 s->selected += MIN(nscroll,
8849 s->ndisplayed - s->selected - 1);
8850 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8851 s->selected += s->ndisplayed - s->selected - 1;
8852 view->count = 0;
8853 break;
8855 ref_scroll_down(view, nscroll);
8856 break;
8857 case CTRL('l'):
8858 view->count = 0;
8859 tog_free_refs();
8860 err = tog_load_refs(s->repo, s->sort_by_date);
8861 if (err)
8862 break;
8863 ref_view_free_refs(s);
8864 err = ref_view_load_refs(s);
8865 break;
8866 case KEY_RESIZE:
8867 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8868 s->selected = view->nlines - 2;
8869 break;
8870 default:
8871 view->count = 0;
8872 break;
8875 return err;
8878 __dead static void
8879 usage_ref(void)
8881 endwin();
8882 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8883 getprogname());
8884 exit(1);
8887 static const struct got_error *
8888 cmd_ref(int argc, char *argv[])
8890 const struct got_error *error;
8891 struct got_repository *repo = NULL;
8892 struct got_worktree *worktree = NULL;
8893 char *cwd = NULL, *repo_path = NULL;
8894 int ch;
8895 struct tog_view *view;
8896 int *pack_fds = NULL;
8898 while ((ch = getopt(argc, argv, "r:")) != -1) {
8899 switch (ch) {
8900 case 'r':
8901 repo_path = realpath(optarg, NULL);
8902 if (repo_path == NULL)
8903 return got_error_from_errno2("realpath",
8904 optarg);
8905 break;
8906 default:
8907 usage_ref();
8908 /* NOTREACHED */
8912 argc -= optind;
8913 argv += optind;
8915 if (argc > 1)
8916 usage_ref();
8918 error = got_repo_pack_fds_open(&pack_fds);
8919 if (error != NULL)
8920 goto done;
8922 if (repo_path == NULL) {
8923 cwd = getcwd(NULL, 0);
8924 if (cwd == NULL)
8925 return got_error_from_errno("getcwd");
8926 error = got_worktree_open(&worktree, cwd);
8927 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8928 goto done;
8929 if (worktree)
8930 repo_path =
8931 strdup(got_worktree_get_repo_path(worktree));
8932 else
8933 repo_path = strdup(cwd);
8934 if (repo_path == NULL) {
8935 error = got_error_from_errno("strdup");
8936 goto done;
8940 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8941 if (error != NULL)
8942 goto done;
8944 init_curses();
8946 error = apply_unveil(got_repo_get_path(repo), NULL);
8947 if (error)
8948 goto done;
8950 error = tog_load_refs(repo, 0);
8951 if (error)
8952 goto done;
8954 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8955 if (view == NULL) {
8956 error = got_error_from_errno("view_open");
8957 goto done;
8960 error = open_ref_view(view, repo);
8961 if (error)
8962 goto done;
8964 if (worktree) {
8965 /* Release work tree lock. */
8966 got_worktree_close(worktree);
8967 worktree = NULL;
8969 error = view_loop(view);
8970 done:
8971 free(repo_path);
8972 free(cwd);
8973 if (repo) {
8974 const struct got_error *close_err = got_repo_close(repo);
8975 if (close_err)
8976 error = close_err;
8978 if (pack_fds) {
8979 const struct got_error *pack_err =
8980 got_repo_pack_fds_close(pack_fds);
8981 if (error == NULL)
8982 error = pack_err;
8984 tog_free_refs();
8985 return error;
8988 static const struct got_error*
8989 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8990 const char *str)
8992 size_t len;
8994 if (win == NULL)
8995 win = stdscr;
8997 len = strlen(str);
8998 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9000 if (focus)
9001 wstandout(win);
9002 if (mvwprintw(win, y, x, "%s", str) == ERR)
9003 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9004 if (focus)
9005 wstandend(win);
9007 return NULL;
9010 static const struct got_error *
9011 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9013 off_t *p;
9015 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9016 if (p == NULL) {
9017 free(*line_offsets);
9018 *line_offsets = NULL;
9019 return got_error_from_errno("reallocarray");
9022 *line_offsets = p;
9023 (*line_offsets)[*nlines] = off;
9024 ++(*nlines);
9025 return NULL;
9028 static const struct got_error *
9029 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9031 *ret = 0;
9033 for (;n > 0; --n, ++km) {
9034 char *t0, *t, *k;
9035 size_t len = 1;
9037 if (km->keys == NULL)
9038 continue;
9040 t = t0 = strdup(km->keys);
9041 if (t0 == NULL)
9042 return got_error_from_errno("strdup");
9044 len += strlen(t);
9045 while ((k = strsep(&t, " ")) != NULL)
9046 len += strlen(k) > 1 ? 2 : 0;
9047 free(t0);
9048 *ret = MAX(*ret, len);
9051 return NULL;
9055 * Write keymap section headers, keys, and key info in km to f.
9056 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9057 * wrap control and symbolic keys in guillemets, else use <>.
9059 static const struct got_error *
9060 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9062 int n, len = width;
9064 if (km->keys) {
9065 static const char *u8_glyph[] = {
9066 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9067 "\xe2\x80\xba" /* U+203A (utf8 >) */
9069 char *t0, *t, *k;
9070 int cs, s, first = 1;
9072 cs = got_locale_is_utf8();
9074 t = t0 = strdup(km->keys);
9075 if (t0 == NULL)
9076 return got_error_from_errno("strdup");
9078 len = strlen(km->keys);
9079 while ((k = strsep(&t, " ")) != NULL) {
9080 s = strlen(k) > 1; /* control or symbolic key */
9081 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9082 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9083 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9084 if (n < 0) {
9085 free(t0);
9086 return got_error_from_errno("fprintf");
9088 first = 0;
9089 len += s ? 2 : 0;
9090 *off += n;
9092 free(t0);
9094 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9095 if (n < 0)
9096 return got_error_from_errno("fprintf");
9097 *off += n;
9099 return NULL;
9102 static const struct got_error *
9103 format_help(struct tog_help_view_state *s)
9105 const struct got_error *err = NULL;
9106 off_t off = 0;
9107 int i, max, n, show = s->all;
9108 static const struct tog_key_map km[] = {
9109 #define KEYMAP_(info, type) { NULL, (info), type }
9110 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9111 GENERATE_HELP
9112 #undef KEYMAP_
9113 #undef KEY_
9116 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9117 if (err)
9118 return err;
9120 n = nitems(km);
9121 err = max_key_str(&max, km, n);
9122 if (err)
9123 return err;
9125 for (i = 0; i < n; ++i) {
9126 if (km[i].keys == NULL) {
9127 show = s->all;
9128 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9129 km[i].type == s->type || s->all)
9130 show = 1;
9132 if (show) {
9133 err = format_help_line(&off, s->f, &km[i], max);
9134 if (err)
9135 return err;
9136 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9137 if (err)
9138 return err;
9141 fputc('\n', s->f);
9142 ++off;
9143 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9144 return err;
9147 static const struct got_error *
9148 create_help(struct tog_help_view_state *s)
9150 FILE *f;
9151 const struct got_error *err;
9153 free(s->line_offsets);
9154 s->line_offsets = NULL;
9155 s->nlines = 0;
9157 f = got_opentemp();
9158 if (f == NULL)
9159 return got_error_from_errno("got_opentemp");
9160 s->f = f;
9162 err = format_help(s);
9163 if (err)
9164 return err;
9166 if (s->f && fflush(s->f) != 0)
9167 return got_error_from_errno("fflush");
9169 return NULL;
9172 static const struct got_error *
9173 search_start_help_view(struct tog_view *view)
9175 view->state.help.matched_line = 0;
9176 return NULL;
9179 static void
9180 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9181 size_t *nlines, int **first, int **last, int **match, int **selected)
9183 struct tog_help_view_state *s = &view->state.help;
9185 *f = s->f;
9186 *nlines = s->nlines;
9187 *line_offsets = s->line_offsets;
9188 *match = &s->matched_line;
9189 *first = &s->first_displayed_line;
9190 *last = &s->last_displayed_line;
9191 *selected = &s->selected_line;
9194 static const struct got_error *
9195 show_help_view(struct tog_view *view)
9197 struct tog_help_view_state *s = &view->state.help;
9198 const struct got_error *err;
9199 regmatch_t *regmatch = &view->regmatch;
9200 wchar_t *wline;
9201 char *line;
9202 ssize_t linelen;
9203 size_t linesz = 0;
9204 int width, nprinted = 0, rc = 0;
9205 int eos = view->nlines;
9207 if (view_is_hsplit_top(view))
9208 --eos; /* account for border */
9210 s->lineno = 0;
9211 rewind(s->f);
9212 werase(view->window);
9214 if (view->gline > s->nlines - 1)
9215 view->gline = s->nlines - 1;
9217 err = win_draw_center(view->window, 0, 0, view->ncols,
9218 view_needs_focus_indication(view),
9219 "tog help (press q to return to tog)");
9220 if (err)
9221 return err;
9222 if (eos <= 1)
9223 return NULL;
9224 waddstr(view->window, "\n\n");
9225 eos -= 2;
9227 s->eof = 0;
9228 view->maxx = 0;
9229 line = NULL;
9230 while (eos > 0 && nprinted < eos) {
9231 attr_t attr = 0;
9233 linelen = getline(&line, &linesz, s->f);
9234 if (linelen == -1) {
9235 if (!feof(s->f)) {
9236 free(line);
9237 return got_ferror(s->f, GOT_ERR_IO);
9239 s->eof = 1;
9240 break;
9242 if (++s->lineno < s->first_displayed_line)
9243 continue;
9244 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9245 continue;
9246 if (s->lineno == view->hiline)
9247 attr = A_STANDOUT;
9249 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9250 view->x ? 1 : 0);
9251 if (err) {
9252 free(line);
9253 return err;
9255 view->maxx = MAX(view->maxx, width);
9256 free(wline);
9257 wline = NULL;
9259 if (attr)
9260 wattron(view->window, attr);
9261 if (s->first_displayed_line + nprinted == s->matched_line &&
9262 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9263 err = add_matched_line(&width, line, view->ncols - 1, 0,
9264 view->window, view->x, regmatch);
9265 if (err) {
9266 free(line);
9267 return err;
9269 } else {
9270 int skip;
9272 err = format_line(&wline, &width, &skip, line,
9273 view->x, view->ncols, 0, view->x ? 1 : 0);
9274 if (err) {
9275 free(line);
9276 return err;
9278 waddwstr(view->window, &wline[skip]);
9279 free(wline);
9280 wline = NULL;
9282 if (s->lineno == view->hiline) {
9283 while (width++ < view->ncols)
9284 waddch(view->window, ' ');
9285 } else {
9286 if (width < view->ncols)
9287 waddch(view->window, '\n');
9289 if (attr)
9290 wattroff(view->window, attr);
9291 if (++nprinted == 1)
9292 s->first_displayed_line = s->lineno;
9294 free(line);
9295 if (nprinted > 0)
9296 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9297 else
9298 s->last_displayed_line = s->first_displayed_line;
9300 view_border(view);
9302 if (s->eof) {
9303 rc = waddnstr(view->window,
9304 "See the tog(1) manual page for full documentation",
9305 view->ncols - 1);
9306 if (rc == ERR)
9307 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9308 } else {
9309 wmove(view->window, view->nlines - 1, 0);
9310 wclrtoeol(view->window);
9311 wstandout(view->window);
9312 rc = waddnstr(view->window, "scroll down for more...",
9313 view->ncols - 1);
9314 if (rc == ERR)
9315 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9316 if (getcurx(view->window) < view->ncols - 6) {
9317 rc = wprintw(view->window, "[%.0f%%]",
9318 100.00 * s->last_displayed_line / s->nlines);
9319 if (rc == ERR)
9320 return got_error_msg(GOT_ERR_IO, "wprintw");
9322 wstandend(view->window);
9325 return NULL;
9328 static const struct got_error *
9329 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9331 struct tog_help_view_state *s = &view->state.help;
9332 const struct got_error *err = NULL;
9333 char *line = NULL;
9334 ssize_t linelen;
9335 size_t linesz = 0;
9336 int eos, nscroll;
9338 eos = nscroll = view->nlines;
9339 if (view_is_hsplit_top(view))
9340 --eos; /* border */
9342 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9344 switch (ch) {
9345 case '0':
9346 case '$':
9347 case KEY_RIGHT:
9348 case 'l':
9349 case KEY_LEFT:
9350 case 'h':
9351 horizontal_scroll_input(view, ch);
9352 break;
9353 case 'g':
9354 case KEY_HOME:
9355 s->first_displayed_line = 1;
9356 view->count = 0;
9357 break;
9358 case 'G':
9359 case KEY_END:
9360 view->count = 0;
9361 if (s->eof)
9362 break;
9363 s->first_displayed_line = (s->nlines - eos) + 3;
9364 s->eof = 1;
9365 break;
9366 case 'k':
9367 case KEY_UP:
9368 if (s->first_displayed_line > 1)
9369 --s->first_displayed_line;
9370 else
9371 view->count = 0;
9372 break;
9373 case CTRL('u'):
9374 case 'u':
9375 nscroll /= 2;
9376 /* FALL THROUGH */
9377 case KEY_PPAGE:
9378 case CTRL('b'):
9379 case 'b':
9380 if (s->first_displayed_line == 1) {
9381 view->count = 0;
9382 break;
9384 while (--nscroll > 0 && s->first_displayed_line > 1)
9385 s->first_displayed_line--;
9386 break;
9387 case 'j':
9388 case KEY_DOWN:
9389 case CTRL('n'):
9390 if (!s->eof)
9391 ++s->first_displayed_line;
9392 else
9393 view->count = 0;
9394 break;
9395 case CTRL('d'):
9396 case 'd':
9397 nscroll /= 2;
9398 /* FALL THROUGH */
9399 case KEY_NPAGE:
9400 case CTRL('f'):
9401 case 'f':
9402 case ' ':
9403 if (s->eof) {
9404 view->count = 0;
9405 break;
9407 while (!s->eof && --nscroll > 0) {
9408 linelen = getline(&line, &linesz, s->f);
9409 s->first_displayed_line++;
9410 if (linelen == -1) {
9411 if (feof(s->f))
9412 s->eof = 1;
9413 else
9414 err = got_ferror(s->f, GOT_ERR_IO);
9415 break;
9418 free(line);
9419 break;
9420 default:
9421 view->count = 0;
9422 break;
9425 return err;
9428 static const struct got_error *
9429 close_help_view(struct tog_view *view)
9431 struct tog_help_view_state *s = &view->state.help;
9433 free(s->line_offsets);
9434 s->line_offsets = NULL;
9435 if (fclose(s->f) == EOF)
9436 return got_error_from_errno("fclose");
9438 return NULL;
9441 static const struct got_error *
9442 reset_help_view(struct tog_view *view)
9444 struct tog_help_view_state *s = &view->state.help;
9447 if (s->f && fclose(s->f) == EOF)
9448 return got_error_from_errno("fclose");
9450 wclear(view->window);
9451 view->count = 0;
9452 view->x = 0;
9453 s->all = !s->all;
9454 s->first_displayed_line = 1;
9455 s->last_displayed_line = view->nlines;
9456 s->matched_line = 0;
9458 return create_help(s);
9461 static const struct got_error *
9462 open_help_view(struct tog_view *view, struct tog_view *parent)
9464 const struct got_error *err = NULL;
9465 struct tog_help_view_state *s = &view->state.help;
9467 s->type = (enum tog_keymap_type)parent->type;
9468 s->first_displayed_line = 1;
9469 s->last_displayed_line = view->nlines;
9470 s->selected_line = 1;
9472 view->show = show_help_view;
9473 view->input = input_help_view;
9474 view->reset = reset_help_view;
9475 view->close = close_help_view;
9476 view->search_start = search_start_help_view;
9477 view->search_setup = search_setup_help_view;
9478 view->search_next = search_next_view_match;
9480 err = create_help(s);
9481 return err;
9484 static const struct got_error *
9485 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9486 enum tog_view_type request, int y, int x)
9488 const struct got_error *err = NULL;
9490 *new_view = NULL;
9492 switch (request) {
9493 case TOG_VIEW_DIFF:
9494 if (view->type == TOG_VIEW_LOG) {
9495 struct tog_log_view_state *s = &view->state.log;
9497 err = open_diff_view_for_commit(new_view, y, x,
9498 s->selected_entry->commit, s->selected_entry->id,
9499 view, s->repo);
9500 } else
9501 return got_error_msg(GOT_ERR_NOT_IMPL,
9502 "parent/child view pair not supported");
9503 break;
9504 case TOG_VIEW_BLAME:
9505 if (view->type == TOG_VIEW_TREE) {
9506 struct tog_tree_view_state *s = &view->state.tree;
9508 err = blame_tree_entry(new_view, y, x,
9509 s->selected_entry, &s->parents, s->commit_id,
9510 s->repo);
9511 } else
9512 return got_error_msg(GOT_ERR_NOT_IMPL,
9513 "parent/child view pair not supported");
9514 break;
9515 case TOG_VIEW_LOG:
9516 if (view->type == TOG_VIEW_BLAME)
9517 err = log_annotated_line(new_view, y, x,
9518 view->state.blame.repo, view->state.blame.id_to_log);
9519 else if (view->type == TOG_VIEW_TREE)
9520 err = log_selected_tree_entry(new_view, y, x,
9521 &view->state.tree);
9522 else if (view->type == TOG_VIEW_REF)
9523 err = log_ref_entry(new_view, y, x,
9524 view->state.ref.selected_entry,
9525 view->state.ref.repo);
9526 else
9527 return got_error_msg(GOT_ERR_NOT_IMPL,
9528 "parent/child view pair not supported");
9529 break;
9530 case TOG_VIEW_TREE:
9531 if (view->type == TOG_VIEW_LOG)
9532 err = browse_commit_tree(new_view, y, x,
9533 view->state.log.selected_entry,
9534 view->state.log.in_repo_path,
9535 view->state.log.head_ref_name,
9536 view->state.log.repo);
9537 else if (view->type == TOG_VIEW_REF)
9538 err = browse_ref_tree(new_view, y, x,
9539 view->state.ref.selected_entry,
9540 view->state.ref.repo);
9541 else
9542 return got_error_msg(GOT_ERR_NOT_IMPL,
9543 "parent/child view pair not supported");
9544 break;
9545 case TOG_VIEW_REF:
9546 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9547 if (*new_view == NULL)
9548 return got_error_from_errno("view_open");
9549 if (view->type == TOG_VIEW_LOG)
9550 err = open_ref_view(*new_view, view->state.log.repo);
9551 else if (view->type == TOG_VIEW_TREE)
9552 err = open_ref_view(*new_view, view->state.tree.repo);
9553 else
9554 err = got_error_msg(GOT_ERR_NOT_IMPL,
9555 "parent/child view pair not supported");
9556 if (err)
9557 view_close(*new_view);
9558 break;
9559 case TOG_VIEW_HELP:
9560 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9561 if (*new_view == NULL)
9562 return got_error_from_errno("view_open");
9563 err = open_help_view(*new_view, view);
9564 if (err)
9565 view_close(*new_view);
9566 break;
9567 default:
9568 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9571 return err;
9575 * If view was scrolled down to move the selected line into view when opening a
9576 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9578 static void
9579 offset_selection_up(struct tog_view *view)
9581 switch (view->type) {
9582 case TOG_VIEW_BLAME: {
9583 struct tog_blame_view_state *s = &view->state.blame;
9584 if (s->first_displayed_line == 1) {
9585 s->selected_line = MAX(s->selected_line - view->offset,
9586 1);
9587 break;
9589 if (s->first_displayed_line > view->offset)
9590 s->first_displayed_line -= view->offset;
9591 else
9592 s->first_displayed_line = 1;
9593 s->selected_line += view->offset;
9594 break;
9596 case TOG_VIEW_LOG:
9597 log_scroll_up(&view->state.log, view->offset);
9598 view->state.log.selected += view->offset;
9599 break;
9600 case TOG_VIEW_REF:
9601 ref_scroll_up(&view->state.ref, view->offset);
9602 view->state.ref.selected += view->offset;
9603 break;
9604 case TOG_VIEW_TREE:
9605 tree_scroll_up(&view->state.tree, view->offset);
9606 view->state.tree.selected += view->offset;
9607 break;
9608 default:
9609 break;
9612 view->offset = 0;
9616 * If the selected line is in the section of screen covered by the bottom split,
9617 * scroll down offset lines to move it into view and index its new position.
9619 static const struct got_error *
9620 offset_selection_down(struct tog_view *view)
9622 const struct got_error *err = NULL;
9623 const struct got_error *(*scrolld)(struct tog_view *, int);
9624 int *selected = NULL;
9625 int header, offset;
9627 switch (view->type) {
9628 case TOG_VIEW_BLAME: {
9629 struct tog_blame_view_state *s = &view->state.blame;
9630 header = 3;
9631 scrolld = NULL;
9632 if (s->selected_line > view->nlines - header) {
9633 offset = abs(view->nlines - s->selected_line - header);
9634 s->first_displayed_line += offset;
9635 s->selected_line -= offset;
9636 view->offset = offset;
9638 break;
9640 case TOG_VIEW_LOG: {
9641 struct tog_log_view_state *s = &view->state.log;
9642 scrolld = &log_scroll_down;
9643 header = view_is_parent_view(view) ? 3 : 2;
9644 selected = &s->selected;
9645 break;
9647 case TOG_VIEW_REF: {
9648 struct tog_ref_view_state *s = &view->state.ref;
9649 scrolld = &ref_scroll_down;
9650 header = 3;
9651 selected = &s->selected;
9652 break;
9654 case TOG_VIEW_TREE: {
9655 struct tog_tree_view_state *s = &view->state.tree;
9656 scrolld = &tree_scroll_down;
9657 header = 5;
9658 selected = &s->selected;
9659 break;
9661 default:
9662 selected = NULL;
9663 scrolld = NULL;
9664 header = 0;
9665 break;
9668 if (selected && *selected > view->nlines - header) {
9669 offset = abs(view->nlines - *selected - header);
9670 view->offset = offset;
9671 if (scrolld && offset) {
9672 err = scrolld(view, offset);
9673 *selected -= offset;
9677 return err;
9680 static void
9681 list_commands(FILE *fp)
9683 size_t i;
9685 fprintf(fp, "commands:");
9686 for (i = 0; i < nitems(tog_commands); i++) {
9687 const struct tog_cmd *cmd = &tog_commands[i];
9688 fprintf(fp, " %s", cmd->name);
9690 fputc('\n', fp);
9693 __dead static void
9694 usage(int hflag, int status)
9696 FILE *fp = (status == 0) ? stdout : stderr;
9698 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9699 getprogname());
9700 if (hflag) {
9701 fprintf(fp, "lazy usage: %s path\n", getprogname());
9702 list_commands(fp);
9704 exit(status);
9707 static char **
9708 make_argv(int argc, ...)
9710 va_list ap;
9711 char **argv;
9712 int i;
9714 va_start(ap, argc);
9716 argv = calloc(argc, sizeof(char *));
9717 if (argv == NULL)
9718 err(1, "calloc");
9719 for (i = 0; i < argc; i++) {
9720 argv[i] = strdup(va_arg(ap, char *));
9721 if (argv[i] == NULL)
9722 err(1, "strdup");
9725 va_end(ap);
9726 return argv;
9730 * Try to convert 'tog path' into a 'tog log path' command.
9731 * The user could simply have mistyped the command rather than knowingly
9732 * provided a path. So check whether argv[0] can in fact be resolved
9733 * to a path in the HEAD commit and print a special error if not.
9734 * This hack is for mpi@ <3
9736 static const struct got_error *
9737 tog_log_with_path(int argc, char *argv[])
9739 const struct got_error *error = NULL, *close_err;
9740 const struct tog_cmd *cmd = NULL;
9741 struct got_repository *repo = NULL;
9742 struct got_worktree *worktree = NULL;
9743 struct got_object_id *commit_id = NULL, *id = NULL;
9744 struct got_commit_object *commit = NULL;
9745 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9746 char *commit_id_str = NULL, **cmd_argv = NULL;
9747 int *pack_fds = NULL;
9749 cwd = getcwd(NULL, 0);
9750 if (cwd == NULL)
9751 return got_error_from_errno("getcwd");
9753 error = got_repo_pack_fds_open(&pack_fds);
9754 if (error != NULL)
9755 goto done;
9757 error = got_worktree_open(&worktree, cwd);
9758 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9759 goto done;
9761 if (worktree)
9762 repo_path = strdup(got_worktree_get_repo_path(worktree));
9763 else
9764 repo_path = strdup(cwd);
9765 if (repo_path == NULL) {
9766 error = got_error_from_errno("strdup");
9767 goto done;
9770 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9771 if (error != NULL)
9772 goto done;
9774 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9775 repo, worktree);
9776 if (error)
9777 goto done;
9779 error = tog_load_refs(repo, 0);
9780 if (error)
9781 goto done;
9782 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9783 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9784 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9785 if (error)
9786 goto done;
9788 if (worktree) {
9789 got_worktree_close(worktree);
9790 worktree = NULL;
9793 error = got_object_open_as_commit(&commit, repo, commit_id);
9794 if (error)
9795 goto done;
9797 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9798 if (error) {
9799 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9800 goto done;
9801 fprintf(stderr, "%s: '%s' is no known command or path\n",
9802 getprogname(), argv[0]);
9803 usage(1, 1);
9804 /* not reached */
9807 error = got_object_id_str(&commit_id_str, commit_id);
9808 if (error)
9809 goto done;
9811 cmd = &tog_commands[0]; /* log */
9812 argc = 4;
9813 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9814 error = cmd->cmd_main(argc, cmd_argv);
9815 done:
9816 if (repo) {
9817 close_err = got_repo_close(repo);
9818 if (error == NULL)
9819 error = close_err;
9821 if (commit)
9822 got_object_commit_close(commit);
9823 if (worktree)
9824 got_worktree_close(worktree);
9825 if (pack_fds) {
9826 const struct got_error *pack_err =
9827 got_repo_pack_fds_close(pack_fds);
9828 if (error == NULL)
9829 error = pack_err;
9831 free(id);
9832 free(commit_id_str);
9833 free(commit_id);
9834 free(cwd);
9835 free(repo_path);
9836 free(in_repo_path);
9837 if (cmd_argv) {
9838 int i;
9839 for (i = 0; i < argc; i++)
9840 free(cmd_argv[i]);
9841 free(cmd_argv);
9843 tog_free_refs();
9844 return error;
9847 int
9848 main(int argc, char *argv[])
9850 const struct got_error *io_err, *error = NULL;
9851 const struct tog_cmd *cmd = NULL;
9852 int ch, hflag = 0, Vflag = 0;
9853 char **cmd_argv = NULL;
9854 static const struct option longopts[] = {
9855 { "version", no_argument, NULL, 'V' },
9856 { NULL, 0, NULL, 0}
9858 char *diff_algo_str = NULL;
9859 const char *test_script_path;
9861 setlocale(LC_CTYPE, "");
9864 * Test mode init must happen before pledge() because "tty" will
9865 * not allow TTY-related ioctls to occur via regular files.
9867 test_script_path = getenv("TOG_TEST_SCRIPT");
9868 if (test_script_path != NULL) {
9869 error = init_mock_term(test_script_path);
9870 if (error) {
9871 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9872 return 1;
9874 } else if (!isatty(STDIN_FILENO))
9875 errx(1, "standard input is not a tty");
9877 #if !defined(PROFILE)
9878 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9879 NULL) == -1)
9880 err(1, "pledge");
9881 #endif
9883 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9884 switch (ch) {
9885 case 'h':
9886 hflag = 1;
9887 break;
9888 case 'V':
9889 Vflag = 1;
9890 break;
9891 default:
9892 usage(hflag, 1);
9893 /* NOTREACHED */
9897 argc -= optind;
9898 argv += optind;
9899 optind = 1;
9900 optreset = 1;
9902 if (Vflag) {
9903 got_version_print_str();
9904 return 0;
9907 if (argc == 0) {
9908 if (hflag)
9909 usage(hflag, 0);
9910 /* Build an argument vector which runs a default command. */
9911 cmd = &tog_commands[0];
9912 argc = 1;
9913 cmd_argv = make_argv(argc, cmd->name);
9914 } else {
9915 size_t i;
9917 /* Did the user specify a command? */
9918 for (i = 0; i < nitems(tog_commands); i++) {
9919 if (strncmp(tog_commands[i].name, argv[0],
9920 strlen(argv[0])) == 0) {
9921 cmd = &tog_commands[i];
9922 break;
9927 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9928 if (diff_algo_str) {
9929 if (strcasecmp(diff_algo_str, "patience") == 0)
9930 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9931 if (strcasecmp(diff_algo_str, "myers") == 0)
9932 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9935 if (cmd == NULL) {
9936 if (argc != 1)
9937 usage(0, 1);
9938 /* No command specified; try log with a path */
9939 error = tog_log_with_path(argc, argv);
9940 } else {
9941 if (hflag)
9942 cmd->cmd_usage();
9943 else
9944 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9947 if (using_mock_io) {
9948 io_err = tog_io_close();
9949 if (error == NULL)
9950 error = io_err;
9952 endwin();
9953 if (cmd_argv) {
9954 int i;
9955 for (i = 0; i < argc; i++)
9956 free(cmd_argv[i]);
9957 free(cmd_argv);
9960 if (error && error->code != GOT_ERR_CANCELLED &&
9961 error->code != GOT_ERR_EOF &&
9962 error->code != GOT_ERR_PRIVSEP_EXIT &&
9963 error->code != GOT_ERR_PRIVSEP_PIPE &&
9964 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9965 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9966 return 0;