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, "SCREENDUMP", 10) == 0)
1657 *ch = TOG_KEY_SCRDUMP;
1658 else if (isdigit((unsigned char)*line)) {
1659 char *t = line;
1661 while (isdigit((unsigned char)*t))
1662 ++t;
1663 view->ch = *ch = *t;
1664 *t = '\0';
1665 /* ignore error, view->count is 0 if instruction is invalid */
1666 view->count = strtonum(line, 0, INT_MAX, NULL);
1667 } else
1668 *ch = *line;
1670 done:
1671 free(line);
1672 return err;
1675 static const struct got_error *
1676 view_input(struct tog_view **new, int *done, struct tog_view *view,
1677 struct tog_view_list_head *views, int fast_refresh)
1679 const struct got_error *err = NULL;
1680 struct tog_view *v;
1681 int ch, errcode;
1683 *new = NULL;
1685 if (view->action)
1686 action_report(view);
1688 /* Clear "no matches" indicator. */
1689 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1690 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1691 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1692 view->count = 0;
1695 if (view->searching && !view->search_next_done) {
1696 errcode = pthread_mutex_unlock(&tog_mutex);
1697 if (errcode)
1698 return got_error_set_errno(errcode,
1699 "pthread_mutex_unlock");
1700 sched_yield();
1701 errcode = pthread_mutex_lock(&tog_mutex);
1702 if (errcode)
1703 return got_error_set_errno(errcode,
1704 "pthread_mutex_lock");
1705 view->search_next(view);
1706 return NULL;
1709 /* Allow threads to make progress while we are waiting for input. */
1710 errcode = pthread_mutex_unlock(&tog_mutex);
1711 if (errcode)
1712 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1714 if (using_mock_io) {
1715 err = tog_read_script_key(tog_io.f, view, &ch, done);
1716 if (err) {
1717 errcode = pthread_mutex_lock(&tog_mutex);
1718 return err;
1720 } else if (view->count && --view->count) {
1721 cbreak();
1722 nodelay(view->window, TRUE);
1723 ch = wgetch(view->window);
1724 /* let C-g or backspace abort unfinished count */
1725 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1726 view->count = 0;
1727 else
1728 ch = view->ch;
1729 } else {
1730 ch = wgetch(view->window);
1731 if (ch >= '1' && ch <= '9')
1732 view->ch = ch = get_compound_key(view, ch);
1734 if (view->hiline && ch != ERR && ch != 0)
1735 view->hiline = 0; /* key pressed, clear line highlight */
1736 nodelay(view->window, TRUE);
1737 errcode = pthread_mutex_lock(&tog_mutex);
1738 if (errcode)
1739 return got_error_set_errno(errcode, "pthread_mutex_lock");
1741 if (tog_sigwinch_received || tog_sigcont_received) {
1742 tog_resizeterm();
1743 tog_sigwinch_received = 0;
1744 tog_sigcont_received = 0;
1745 TAILQ_FOREACH(v, views, entry) {
1746 err = view_resize(v);
1747 if (err)
1748 return err;
1749 err = v->input(new, v, KEY_RESIZE);
1750 if (err)
1751 return err;
1752 if (v->child) {
1753 err = view_resize(v->child);
1754 if (err)
1755 return err;
1756 err = v->child->input(new, v->child,
1757 KEY_RESIZE);
1758 if (err)
1759 return err;
1760 if (v->child->resized_x || v->child->resized_y) {
1761 err = view_resize_split(v, 0);
1762 if (err)
1763 return err;
1769 switch (ch) {
1770 case '?':
1771 case 'H':
1772 case KEY_F(1):
1773 if (view->type == TOG_VIEW_HELP)
1774 err = view->reset(view);
1775 else
1776 err = view_request_new(new, view, TOG_VIEW_HELP);
1777 break;
1778 case '\t':
1779 view->count = 0;
1780 if (view->child) {
1781 view->focussed = 0;
1782 view->child->focussed = 1;
1783 view->focus_child = 1;
1784 } else if (view->parent) {
1785 view->focussed = 0;
1786 view->parent->focussed = 1;
1787 view->parent->focus_child = 0;
1788 if (!view_is_splitscreen(view)) {
1789 if (view->parent->resize) {
1790 err = view->parent->resize(view->parent,
1791 0);
1792 if (err)
1793 return err;
1795 offset_selection_up(view->parent);
1796 err = view_fullscreen(view->parent);
1797 if (err)
1798 return err;
1801 break;
1802 case 'q':
1803 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1804 if (view->parent->resize) {
1805 /* might need more commits to fill fullscreen */
1806 err = view->parent->resize(view->parent, 0);
1807 if (err)
1808 break;
1810 offset_selection_up(view->parent);
1812 err = view->input(new, view, ch);
1813 view->dying = 1;
1814 break;
1815 case 'Q':
1816 *done = 1;
1817 break;
1818 case 'F':
1819 view->count = 0;
1820 if (view_is_parent_view(view)) {
1821 if (view->child == NULL)
1822 break;
1823 if (view_is_splitscreen(view->child)) {
1824 view->focussed = 0;
1825 view->child->focussed = 1;
1826 err = view_fullscreen(view->child);
1827 } else {
1828 err = view_splitscreen(view->child);
1829 if (!err)
1830 err = view_resize_split(view, 0);
1832 if (err)
1833 break;
1834 err = view->child->input(new, view->child,
1835 KEY_RESIZE);
1836 } else {
1837 if (view_is_splitscreen(view)) {
1838 view->parent->focussed = 0;
1839 view->focussed = 1;
1840 err = view_fullscreen(view);
1841 } else {
1842 err = view_splitscreen(view);
1843 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1844 err = view_resize(view->parent);
1845 if (!err)
1846 err = view_resize_split(view, 0);
1848 if (err)
1849 break;
1850 err = view->input(new, view, KEY_RESIZE);
1852 if (err)
1853 break;
1854 if (view->resize) {
1855 err = view->resize(view, 0);
1856 if (err)
1857 break;
1859 if (view->parent)
1860 err = offset_selection_down(view->parent);
1861 if (!err)
1862 err = offset_selection_down(view);
1863 break;
1864 case 'S':
1865 view->count = 0;
1866 err = switch_split(view);
1867 break;
1868 case '-':
1869 err = view_resize_split(view, -1);
1870 break;
1871 case '+':
1872 err = view_resize_split(view, 1);
1873 break;
1874 case KEY_RESIZE:
1875 break;
1876 case '/':
1877 view->count = 0;
1878 if (view->search_start)
1879 view_search_start(view, fast_refresh);
1880 else
1881 err = view->input(new, view, ch);
1882 break;
1883 case 'N':
1884 case 'n':
1885 if (view->search_started && view->search_next) {
1886 view->searching = (ch == 'n' ?
1887 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1888 view->search_next_done = 0;
1889 view->search_next(view);
1890 } else
1891 err = view->input(new, view, ch);
1892 break;
1893 case 'A':
1894 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1895 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1896 view->action = "Patience diff algorithm";
1897 } else {
1898 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1899 view->action = "Myers diff algorithm";
1901 TAILQ_FOREACH(v, views, entry) {
1902 if (v->reset) {
1903 err = v->reset(v);
1904 if (err)
1905 return err;
1907 if (v->child && v->child->reset) {
1908 err = v->child->reset(v->child);
1909 if (err)
1910 return err;
1913 break;
1914 case TOG_KEY_SCRDUMP:
1915 err = screendump(view);
1916 break;
1917 default:
1918 err = view->input(new, view, ch);
1919 break;
1922 return err;
1925 static int
1926 view_needs_focus_indication(struct tog_view *view)
1928 if (view_is_parent_view(view)) {
1929 if (view->child == NULL || view->child->focussed)
1930 return 0;
1931 if (!view_is_splitscreen(view->child))
1932 return 0;
1933 } else if (!view_is_splitscreen(view))
1934 return 0;
1936 return view->focussed;
1939 static const struct got_error *
1940 tog_io_close(void)
1942 const struct got_error *err = NULL;
1944 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1945 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1946 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1947 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1948 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1949 err = got_ferror(tog_io.f, GOT_ERR_IO);
1950 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1951 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1953 return err;
1956 static const struct got_error *
1957 view_loop(struct tog_view *view)
1959 const struct got_error *err = NULL;
1960 struct tog_view_list_head views;
1961 struct tog_view *new_view;
1962 char *mode;
1963 int fast_refresh = 10;
1964 int done = 0, errcode;
1966 mode = getenv("TOG_VIEW_SPLIT_MODE");
1967 if (!mode || !(*mode == 'h' || *mode == 'H'))
1968 view->mode = TOG_VIEW_SPLIT_VERT;
1969 else
1970 view->mode = TOG_VIEW_SPLIT_HRZN;
1972 errcode = pthread_mutex_lock(&tog_mutex);
1973 if (errcode)
1974 return got_error_set_errno(errcode, "pthread_mutex_lock");
1976 TAILQ_INIT(&views);
1977 TAILQ_INSERT_HEAD(&views, view, entry);
1979 view->focussed = 1;
1980 err = view->show(view);
1981 if (err)
1982 return err;
1983 update_panels();
1984 doupdate();
1985 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1986 !tog_fatal_signal_received()) {
1987 /* Refresh fast during initialization, then become slower. */
1988 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1989 halfdelay(10); /* switch to once per second */
1991 err = view_input(&new_view, &done, view, &views, fast_refresh);
1992 if (err)
1993 break;
1995 if (view->dying && view == TAILQ_FIRST(&views) &&
1996 TAILQ_NEXT(view, entry) == NULL)
1997 done = 1;
1998 if (done) {
1999 struct tog_view *v;
2002 * When we quit, scroll the screen up a single line
2003 * so we don't lose any information.
2005 TAILQ_FOREACH(v, &views, entry) {
2006 wmove(v->window, 0, 0);
2007 wdeleteln(v->window);
2008 wnoutrefresh(v->window);
2009 if (v->child && !view_is_fullscreen(v)) {
2010 wmove(v->child->window, 0, 0);
2011 wdeleteln(v->child->window);
2012 wnoutrefresh(v->child->window);
2015 doupdate();
2018 if (view->dying) {
2019 struct tog_view *v, *prev = NULL;
2021 if (view_is_parent_view(view))
2022 prev = TAILQ_PREV(view, tog_view_list_head,
2023 entry);
2024 else if (view->parent)
2025 prev = view->parent;
2027 if (view->parent) {
2028 view->parent->child = NULL;
2029 view->parent->focus_child = 0;
2030 /* Restore fullscreen line height. */
2031 view->parent->nlines = view->parent->lines;
2032 err = view_resize(view->parent);
2033 if (err)
2034 break;
2035 /* Make resized splits persist. */
2036 view_transfer_size(view->parent, view);
2037 } else
2038 TAILQ_REMOVE(&views, view, entry);
2040 err = view_close(view);
2041 if (err)
2042 goto done;
2044 view = NULL;
2045 TAILQ_FOREACH(v, &views, entry) {
2046 if (v->focussed)
2047 break;
2049 if (view == NULL && new_view == NULL) {
2050 /* No view has focus. Try to pick one. */
2051 if (prev)
2052 view = prev;
2053 else if (!TAILQ_EMPTY(&views)) {
2054 view = TAILQ_LAST(&views,
2055 tog_view_list_head);
2057 if (view) {
2058 if (view->focus_child) {
2059 view->child->focussed = 1;
2060 view = view->child;
2061 } else
2062 view->focussed = 1;
2066 if (new_view) {
2067 struct tog_view *v, *t;
2068 /* Only allow one parent view per type. */
2069 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2070 if (v->type != new_view->type)
2071 continue;
2072 TAILQ_REMOVE(&views, v, entry);
2073 err = view_close(v);
2074 if (err)
2075 goto done;
2076 break;
2078 TAILQ_INSERT_TAIL(&views, new_view, entry);
2079 view = new_view;
2081 if (view && !done) {
2082 if (view_is_parent_view(view)) {
2083 if (view->child && view->child->focussed)
2084 view = view->child;
2085 } else {
2086 if (view->parent && view->parent->focussed)
2087 view = view->parent;
2089 show_panel(view->panel);
2090 if (view->child && view_is_splitscreen(view->child))
2091 show_panel(view->child->panel);
2092 if (view->parent && view_is_splitscreen(view)) {
2093 err = view->parent->show(view->parent);
2094 if (err)
2095 goto done;
2097 err = view->show(view);
2098 if (err)
2099 goto done;
2100 if (view->child) {
2101 err = view->child->show(view->child);
2102 if (err)
2103 goto done;
2105 update_panels();
2106 doupdate();
2109 done:
2110 while (!TAILQ_EMPTY(&views)) {
2111 const struct got_error *close_err;
2112 view = TAILQ_FIRST(&views);
2113 TAILQ_REMOVE(&views, view, entry);
2114 close_err = view_close(view);
2115 if (close_err && err == NULL)
2116 err = close_err;
2119 errcode = pthread_mutex_unlock(&tog_mutex);
2120 if (errcode && err == NULL)
2121 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2123 return err;
2126 __dead static void
2127 usage_log(void)
2129 endwin();
2130 fprintf(stderr,
2131 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2132 getprogname());
2133 exit(1);
2136 /* Create newly allocated wide-character string equivalent to a byte string. */
2137 static const struct got_error *
2138 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2140 char *vis = NULL;
2141 const struct got_error *err = NULL;
2143 *ws = NULL;
2144 *wlen = mbstowcs(NULL, s, 0);
2145 if (*wlen == (size_t)-1) {
2146 int vislen;
2147 if (errno != EILSEQ)
2148 return got_error_from_errno("mbstowcs");
2150 /* byte string invalid in current encoding; try to "fix" it */
2151 err = got_mbsavis(&vis, &vislen, s);
2152 if (err)
2153 return err;
2154 *wlen = mbstowcs(NULL, vis, 0);
2155 if (*wlen == (size_t)-1) {
2156 err = got_error_from_errno("mbstowcs"); /* give up */
2157 goto done;
2161 *ws = calloc(*wlen + 1, sizeof(**ws));
2162 if (*ws == NULL) {
2163 err = got_error_from_errno("calloc");
2164 goto done;
2167 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2168 err = got_error_from_errno("mbstowcs");
2169 done:
2170 free(vis);
2171 if (err) {
2172 free(*ws);
2173 *ws = NULL;
2174 *wlen = 0;
2176 return err;
2179 static const struct got_error *
2180 expand_tab(char **ptr, const char *src)
2182 char *dst;
2183 size_t len, n, idx = 0, sz = 0;
2185 *ptr = NULL;
2186 n = len = strlen(src);
2187 dst = malloc(n + 1);
2188 if (dst == NULL)
2189 return got_error_from_errno("malloc");
2191 while (idx < len && src[idx]) {
2192 const char c = src[idx];
2194 if (c == '\t') {
2195 size_t nb = TABSIZE - sz % TABSIZE;
2196 char *p;
2198 p = realloc(dst, n + nb);
2199 if (p == NULL) {
2200 free(dst);
2201 return got_error_from_errno("realloc");
2204 dst = p;
2205 n += nb;
2206 memset(dst + sz, ' ', nb);
2207 sz += nb;
2208 } else
2209 dst[sz++] = src[idx];
2210 ++idx;
2213 dst[sz] = '\0';
2214 *ptr = dst;
2215 return NULL;
2219 * Advance at most n columns from wline starting at offset off.
2220 * Return the index to the first character after the span operation.
2221 * Return the combined column width of all spanned wide character in
2222 * *rcol.
2224 static int
2225 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2227 int width, i, cols = 0;
2229 if (n == 0) {
2230 *rcol = cols;
2231 return off;
2234 for (i = off; wline[i] != L'\0'; ++i) {
2235 if (wline[i] == L'\t')
2236 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2237 else
2238 width = wcwidth(wline[i]);
2240 if (width == -1) {
2241 width = 1;
2242 wline[i] = L'.';
2245 if (cols + width > n)
2246 break;
2247 cols += width;
2250 *rcol = cols;
2251 return i;
2255 * Format a line for display, ensuring that it won't overflow a width limit.
2256 * With scrolling, the width returned refers to the scrolled version of the
2257 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2259 static const struct got_error *
2260 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2261 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2263 const struct got_error *err = NULL;
2264 int cols;
2265 wchar_t *wline = NULL;
2266 char *exstr = NULL;
2267 size_t wlen;
2268 int i, scrollx;
2270 *wlinep = NULL;
2271 *widthp = 0;
2273 if (expand) {
2274 err = expand_tab(&exstr, line);
2275 if (err)
2276 return err;
2279 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2280 free(exstr);
2281 if (err)
2282 return err;
2284 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2286 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2287 wline[wlen - 1] = L'\0';
2288 wlen--;
2290 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2291 wline[wlen - 1] = L'\0';
2292 wlen--;
2295 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2296 wline[i] = L'\0';
2298 if (widthp)
2299 *widthp = cols;
2300 if (scrollxp)
2301 *scrollxp = scrollx;
2302 if (err)
2303 free(wline);
2304 else
2305 *wlinep = wline;
2306 return err;
2309 static const struct got_error*
2310 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2311 struct got_object_id *id, struct got_repository *repo)
2313 static const struct got_error *err = NULL;
2314 struct got_reflist_entry *re;
2315 char *s;
2316 const char *name;
2318 *refs_str = NULL;
2320 TAILQ_FOREACH(re, refs, entry) {
2321 struct got_tag_object *tag = NULL;
2322 struct got_object_id *ref_id;
2323 int cmp;
2325 name = got_ref_get_name(re->ref);
2326 if (strcmp(name, GOT_REF_HEAD) == 0)
2327 continue;
2328 if (strncmp(name, "refs/", 5) == 0)
2329 name += 5;
2330 if (strncmp(name, "got/", 4) == 0 &&
2331 strncmp(name, "got/backup/", 11) != 0)
2332 continue;
2333 if (strncmp(name, "heads/", 6) == 0)
2334 name += 6;
2335 if (strncmp(name, "remotes/", 8) == 0) {
2336 name += 8;
2337 s = strstr(name, "/" GOT_REF_HEAD);
2338 if (s != NULL && s[strlen(s)] == '\0')
2339 continue;
2341 err = got_ref_resolve(&ref_id, repo, re->ref);
2342 if (err)
2343 break;
2344 if (strncmp(name, "tags/", 5) == 0) {
2345 err = got_object_open_as_tag(&tag, repo, ref_id);
2346 if (err) {
2347 if (err->code != GOT_ERR_OBJ_TYPE) {
2348 free(ref_id);
2349 break;
2351 /* Ref points at something other than a tag. */
2352 err = NULL;
2353 tag = NULL;
2356 cmp = got_object_id_cmp(tag ?
2357 got_object_tag_get_object_id(tag) : ref_id, id);
2358 free(ref_id);
2359 if (tag)
2360 got_object_tag_close(tag);
2361 if (cmp != 0)
2362 continue;
2363 s = *refs_str;
2364 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2365 s ? ", " : "", name) == -1) {
2366 err = got_error_from_errno("asprintf");
2367 free(s);
2368 *refs_str = NULL;
2369 break;
2371 free(s);
2374 return err;
2377 static const struct got_error *
2378 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2379 int col_tab_align)
2381 char *smallerthan;
2383 smallerthan = strchr(author, '<');
2384 if (smallerthan && smallerthan[1] != '\0')
2385 author = smallerthan + 1;
2386 author[strcspn(author, "@>")] = '\0';
2387 return format_line(wauthor, author_width, NULL, author, 0, limit,
2388 col_tab_align, 0);
2391 static const struct got_error *
2392 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2393 struct got_object_id *id, const size_t date_display_cols,
2394 int author_display_cols)
2396 struct tog_log_view_state *s = &view->state.log;
2397 const struct got_error *err = NULL;
2398 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2399 char *logmsg0 = NULL, *logmsg = NULL;
2400 char *author = NULL;
2401 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2402 int author_width, logmsg_width;
2403 char *newline, *line = NULL;
2404 int col, limit, scrollx;
2405 const int avail = view->ncols;
2406 struct tm tm;
2407 time_t committer_time;
2408 struct tog_color *tc;
2410 committer_time = got_object_commit_get_committer_time(commit);
2411 if (gmtime_r(&committer_time, &tm) == NULL)
2412 return got_error_from_errno("gmtime_r");
2413 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2414 return got_error(GOT_ERR_NO_SPACE);
2416 if (avail <= date_display_cols)
2417 limit = MIN(sizeof(datebuf) - 1, avail);
2418 else
2419 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2420 tc = get_color(&s->colors, TOG_COLOR_DATE);
2421 if (tc)
2422 wattr_on(view->window,
2423 COLOR_PAIR(tc->colorpair), NULL);
2424 waddnstr(view->window, datebuf, limit);
2425 if (tc)
2426 wattr_off(view->window,
2427 COLOR_PAIR(tc->colorpair), NULL);
2428 col = limit;
2429 if (col > avail)
2430 goto done;
2432 if (avail >= 120) {
2433 char *id_str;
2434 err = got_object_id_str(&id_str, id);
2435 if (err)
2436 goto done;
2437 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2438 if (tc)
2439 wattr_on(view->window,
2440 COLOR_PAIR(tc->colorpair), NULL);
2441 wprintw(view->window, "%.8s ", id_str);
2442 if (tc)
2443 wattr_off(view->window,
2444 COLOR_PAIR(tc->colorpair), NULL);
2445 free(id_str);
2446 col += 9;
2447 if (col > avail)
2448 goto done;
2451 if (s->use_committer)
2452 author = strdup(got_object_commit_get_committer(commit));
2453 else
2454 author = strdup(got_object_commit_get_author(commit));
2455 if (author == NULL) {
2456 err = got_error_from_errno("strdup");
2457 goto done;
2459 err = format_author(&wauthor, &author_width, author, avail - col, col);
2460 if (err)
2461 goto done;
2462 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2463 if (tc)
2464 wattr_on(view->window,
2465 COLOR_PAIR(tc->colorpair), NULL);
2466 waddwstr(view->window, wauthor);
2467 col += author_width;
2468 while (col < avail && author_width < author_display_cols + 2) {
2469 waddch(view->window, ' ');
2470 col++;
2471 author_width++;
2473 if (tc)
2474 wattr_off(view->window,
2475 COLOR_PAIR(tc->colorpair), NULL);
2476 if (col > avail)
2477 goto done;
2479 err = got_object_commit_get_logmsg(&logmsg0, commit);
2480 if (err)
2481 goto done;
2482 logmsg = logmsg0;
2483 while (*logmsg == '\n')
2484 logmsg++;
2485 newline = strchr(logmsg, '\n');
2486 if (newline)
2487 *newline = '\0';
2488 limit = avail - col;
2489 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2490 limit--; /* for the border */
2491 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2492 limit, col, 1);
2493 if (err)
2494 goto done;
2495 waddwstr(view->window, &wlogmsg[scrollx]);
2496 col += MAX(logmsg_width, 0);
2497 while (col < avail) {
2498 waddch(view->window, ' ');
2499 col++;
2501 done:
2502 free(logmsg0);
2503 free(wlogmsg);
2504 free(author);
2505 free(wauthor);
2506 free(line);
2507 return err;
2510 static struct commit_queue_entry *
2511 alloc_commit_queue_entry(struct got_commit_object *commit,
2512 struct got_object_id *id)
2514 struct commit_queue_entry *entry;
2515 struct got_object_id *dup;
2517 entry = calloc(1, sizeof(*entry));
2518 if (entry == NULL)
2519 return NULL;
2521 dup = got_object_id_dup(id);
2522 if (dup == NULL) {
2523 free(entry);
2524 return NULL;
2527 entry->id = dup;
2528 entry->commit = commit;
2529 return entry;
2532 static void
2533 pop_commit(struct commit_queue *commits)
2535 struct commit_queue_entry *entry;
2537 entry = TAILQ_FIRST(&commits->head);
2538 TAILQ_REMOVE(&commits->head, entry, entry);
2539 got_object_commit_close(entry->commit);
2540 commits->ncommits--;
2541 free(entry->id);
2542 free(entry);
2545 static void
2546 free_commits(struct commit_queue *commits)
2548 while (!TAILQ_EMPTY(&commits->head))
2549 pop_commit(commits);
2552 static const struct got_error *
2553 match_commit(int *have_match, struct got_object_id *id,
2554 struct got_commit_object *commit, regex_t *regex)
2556 const struct got_error *err = NULL;
2557 regmatch_t regmatch;
2558 char *id_str = NULL, *logmsg = NULL;
2560 *have_match = 0;
2562 err = got_object_id_str(&id_str, id);
2563 if (err)
2564 return err;
2566 err = got_object_commit_get_logmsg(&logmsg, commit);
2567 if (err)
2568 goto done;
2570 if (regexec(regex, got_object_commit_get_author(commit), 1,
2571 &regmatch, 0) == 0 ||
2572 regexec(regex, got_object_commit_get_committer(commit), 1,
2573 &regmatch, 0) == 0 ||
2574 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2575 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2576 *have_match = 1;
2577 done:
2578 free(id_str);
2579 free(logmsg);
2580 return err;
2583 static const struct got_error *
2584 queue_commits(struct tog_log_thread_args *a)
2586 const struct got_error *err = NULL;
2589 * We keep all commits open throughout the lifetime of the log
2590 * view in order to avoid having to re-fetch commits from disk
2591 * while updating the display.
2593 do {
2594 struct got_object_id id;
2595 struct got_commit_object *commit;
2596 struct commit_queue_entry *entry;
2597 int limit_match = 0;
2598 int errcode;
2600 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2601 NULL, NULL);
2602 if (err)
2603 break;
2605 err = got_object_open_as_commit(&commit, a->repo, &id);
2606 if (err)
2607 break;
2608 entry = alloc_commit_queue_entry(commit, &id);
2609 if (entry == NULL) {
2610 err = got_error_from_errno("alloc_commit_queue_entry");
2611 break;
2614 errcode = pthread_mutex_lock(&tog_mutex);
2615 if (errcode) {
2616 err = got_error_set_errno(errcode,
2617 "pthread_mutex_lock");
2618 break;
2621 entry->idx = a->real_commits->ncommits;
2622 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2623 a->real_commits->ncommits++;
2625 if (*a->limiting) {
2626 err = match_commit(&limit_match, &id, commit,
2627 a->limit_regex);
2628 if (err)
2629 break;
2631 if (limit_match) {
2632 struct commit_queue_entry *matched;
2634 matched = alloc_commit_queue_entry(
2635 entry->commit, entry->id);
2636 if (matched == NULL) {
2637 err = got_error_from_errno(
2638 "alloc_commit_queue_entry");
2639 break;
2641 matched->commit = entry->commit;
2642 got_object_commit_retain(entry->commit);
2644 matched->idx = a->limit_commits->ncommits;
2645 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2646 matched, entry);
2647 a->limit_commits->ncommits++;
2651 * This is how we signal log_thread() that we
2652 * have found a match, and that it should be
2653 * counted as a new entry for the view.
2655 a->limit_match = limit_match;
2658 if (*a->searching == TOG_SEARCH_FORWARD &&
2659 !*a->search_next_done) {
2660 int have_match;
2661 err = match_commit(&have_match, &id, commit, a->regex);
2662 if (err)
2663 break;
2665 if (*a->limiting) {
2666 if (limit_match && have_match)
2667 *a->search_next_done =
2668 TOG_SEARCH_HAVE_MORE;
2669 } else if (have_match)
2670 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2673 errcode = pthread_mutex_unlock(&tog_mutex);
2674 if (errcode && err == NULL)
2675 err = got_error_set_errno(errcode,
2676 "pthread_mutex_unlock");
2677 if (err)
2678 break;
2679 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2681 return err;
2684 static void
2685 select_commit(struct tog_log_view_state *s)
2687 struct commit_queue_entry *entry;
2688 int ncommits = 0;
2690 entry = s->first_displayed_entry;
2691 while (entry) {
2692 if (ncommits == s->selected) {
2693 s->selected_entry = entry;
2694 break;
2696 entry = TAILQ_NEXT(entry, entry);
2697 ncommits++;
2701 static const struct got_error *
2702 draw_commits(struct tog_view *view)
2704 const struct got_error *err = NULL;
2705 struct tog_log_view_state *s = &view->state.log;
2706 struct commit_queue_entry *entry = s->selected_entry;
2707 int limit = view->nlines;
2708 int width;
2709 int ncommits, author_cols = 4;
2710 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2711 char *refs_str = NULL;
2712 wchar_t *wline;
2713 struct tog_color *tc;
2714 static const size_t date_display_cols = 12;
2716 if (view_is_hsplit_top(view))
2717 --limit; /* account for border */
2719 if (s->selected_entry &&
2720 !(view->searching && view->search_next_done == 0)) {
2721 struct got_reflist_head *refs;
2722 err = got_object_id_str(&id_str, s->selected_entry->id);
2723 if (err)
2724 return err;
2725 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2726 s->selected_entry->id);
2727 if (refs) {
2728 err = build_refs_str(&refs_str, refs,
2729 s->selected_entry->id, s->repo);
2730 if (err)
2731 goto done;
2735 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2736 halfdelay(10); /* disable fast refresh */
2738 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2739 if (asprintf(&ncommits_str, " [%d/%d] %s",
2740 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2741 (view->searching && !view->search_next_done) ?
2742 "searching..." : "loading...") == -1) {
2743 err = got_error_from_errno("asprintf");
2744 goto done;
2746 } else {
2747 const char *search_str = NULL;
2748 const char *limit_str = NULL;
2750 if (view->searching) {
2751 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2752 search_str = "no more matches";
2753 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2754 search_str = "no matches found";
2755 else if (!view->search_next_done)
2756 search_str = "searching...";
2759 if (s->limit_view && s->commits->ncommits == 0)
2760 limit_str = "no matches found";
2762 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2763 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2764 search_str ? search_str : (refs_str ? refs_str : ""),
2765 limit_str ? limit_str : "") == -1) {
2766 err = got_error_from_errno("asprintf");
2767 goto done;
2771 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2772 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2773 "........................................",
2774 s->in_repo_path, ncommits_str) == -1) {
2775 err = got_error_from_errno("asprintf");
2776 header = NULL;
2777 goto done;
2779 } else if (asprintf(&header, "commit %s%s",
2780 id_str ? id_str : "........................................",
2781 ncommits_str) == -1) {
2782 err = got_error_from_errno("asprintf");
2783 header = NULL;
2784 goto done;
2786 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2787 if (err)
2788 goto done;
2790 werase(view->window);
2792 if (view_needs_focus_indication(view))
2793 wstandout(view->window);
2794 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2795 if (tc)
2796 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2797 waddwstr(view->window, wline);
2798 while (width < view->ncols) {
2799 waddch(view->window, ' ');
2800 width++;
2802 if (tc)
2803 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2804 if (view_needs_focus_indication(view))
2805 wstandend(view->window);
2806 free(wline);
2807 if (limit <= 1)
2808 goto done;
2810 /* Grow author column size if necessary, and set view->maxx. */
2811 entry = s->first_displayed_entry;
2812 ncommits = 0;
2813 view->maxx = 0;
2814 while (entry) {
2815 struct got_commit_object *c = entry->commit;
2816 char *author, *eol, *msg, *msg0;
2817 wchar_t *wauthor, *wmsg;
2818 int width;
2819 if (ncommits >= limit - 1)
2820 break;
2821 if (s->use_committer)
2822 author = strdup(got_object_commit_get_committer(c));
2823 else
2824 author = strdup(got_object_commit_get_author(c));
2825 if (author == NULL) {
2826 err = got_error_from_errno("strdup");
2827 goto done;
2829 err = format_author(&wauthor, &width, author, COLS,
2830 date_display_cols);
2831 if (author_cols < width)
2832 author_cols = width;
2833 free(wauthor);
2834 free(author);
2835 if (err)
2836 goto done;
2837 err = got_object_commit_get_logmsg(&msg0, c);
2838 if (err)
2839 goto done;
2840 msg = msg0;
2841 while (*msg == '\n')
2842 ++msg;
2843 if ((eol = strchr(msg, '\n')))
2844 *eol = '\0';
2845 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2846 date_display_cols + author_cols, 0);
2847 if (err)
2848 goto done;
2849 view->maxx = MAX(view->maxx, width);
2850 free(msg0);
2851 free(wmsg);
2852 ncommits++;
2853 entry = TAILQ_NEXT(entry, entry);
2856 entry = s->first_displayed_entry;
2857 s->last_displayed_entry = s->first_displayed_entry;
2858 ncommits = 0;
2859 while (entry) {
2860 if (ncommits >= limit - 1)
2861 break;
2862 if (ncommits == s->selected)
2863 wstandout(view->window);
2864 err = draw_commit(view, entry->commit, entry->id,
2865 date_display_cols, author_cols);
2866 if (ncommits == s->selected)
2867 wstandend(view->window);
2868 if (err)
2869 goto done;
2870 ncommits++;
2871 s->last_displayed_entry = entry;
2872 entry = TAILQ_NEXT(entry, entry);
2875 view_border(view);
2876 done:
2877 free(id_str);
2878 free(refs_str);
2879 free(ncommits_str);
2880 free(header);
2881 return err;
2884 static void
2885 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2887 struct commit_queue_entry *entry;
2888 int nscrolled = 0;
2890 entry = TAILQ_FIRST(&s->commits->head);
2891 if (s->first_displayed_entry == entry)
2892 return;
2894 entry = s->first_displayed_entry;
2895 while (entry && nscrolled < maxscroll) {
2896 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2897 if (entry) {
2898 s->first_displayed_entry = entry;
2899 nscrolled++;
2904 static const struct got_error *
2905 trigger_log_thread(struct tog_view *view, int wait)
2907 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2908 int errcode;
2910 if (!using_mock_io)
2911 halfdelay(1); /* fast refresh while loading commits */
2913 while (!ta->log_complete && !tog_thread_error &&
2914 (ta->commits_needed > 0 || ta->load_all)) {
2915 /* Wake the log thread. */
2916 errcode = pthread_cond_signal(&ta->need_commits);
2917 if (errcode)
2918 return got_error_set_errno(errcode,
2919 "pthread_cond_signal");
2922 * The mutex will be released while the view loop waits
2923 * in wgetch(), at which time the log thread will run.
2925 if (!wait)
2926 break;
2928 /* Display progress update in log view. */
2929 show_log_view(view);
2930 update_panels();
2931 doupdate();
2933 /* Wait right here while next commit is being loaded. */
2934 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2935 if (errcode)
2936 return got_error_set_errno(errcode,
2937 "pthread_cond_wait");
2939 /* Display progress update in log view. */
2940 show_log_view(view);
2941 update_panels();
2942 doupdate();
2945 return NULL;
2948 static const struct got_error *
2949 request_log_commits(struct tog_view *view)
2951 struct tog_log_view_state *state = &view->state.log;
2952 const struct got_error *err = NULL;
2954 if (state->thread_args.log_complete)
2955 return NULL;
2957 state->thread_args.commits_needed += view->nscrolled;
2958 err = trigger_log_thread(view, 1);
2959 view->nscrolled = 0;
2961 return err;
2964 static const struct got_error *
2965 log_scroll_down(struct tog_view *view, int maxscroll)
2967 struct tog_log_view_state *s = &view->state.log;
2968 const struct got_error *err = NULL;
2969 struct commit_queue_entry *pentry;
2970 int nscrolled = 0, ncommits_needed;
2972 if (s->last_displayed_entry == NULL)
2973 return NULL;
2975 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2976 if (s->commits->ncommits < ncommits_needed &&
2977 !s->thread_args.log_complete) {
2979 * Ask the log thread for required amount of commits.
2981 s->thread_args.commits_needed +=
2982 ncommits_needed - s->commits->ncommits;
2983 err = trigger_log_thread(view, 1);
2984 if (err)
2985 return err;
2988 do {
2989 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2990 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2991 break;
2993 s->last_displayed_entry = pentry ?
2994 pentry : s->last_displayed_entry;
2996 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2997 if (pentry == NULL)
2998 break;
2999 s->first_displayed_entry = pentry;
3000 } while (++nscrolled < maxscroll);
3002 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3003 view->nscrolled += nscrolled;
3004 else
3005 view->nscrolled = 0;
3007 return err;
3010 static const struct got_error *
3011 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3012 struct got_commit_object *commit, struct got_object_id *commit_id,
3013 struct tog_view *log_view, struct got_repository *repo)
3015 const struct got_error *err;
3016 struct got_object_qid *parent_id;
3017 struct tog_view *diff_view;
3019 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3020 if (diff_view == NULL)
3021 return got_error_from_errno("view_open");
3023 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3024 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3025 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3026 if (err == NULL)
3027 *new_view = diff_view;
3028 return err;
3031 static const struct got_error *
3032 tree_view_visit_subtree(struct tog_tree_view_state *s,
3033 struct got_tree_object *subtree)
3035 struct tog_parent_tree *parent;
3037 parent = calloc(1, sizeof(*parent));
3038 if (parent == NULL)
3039 return got_error_from_errno("calloc");
3041 parent->tree = s->tree;
3042 parent->first_displayed_entry = s->first_displayed_entry;
3043 parent->selected_entry = s->selected_entry;
3044 parent->selected = s->selected;
3045 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3046 s->tree = subtree;
3047 s->selected = 0;
3048 s->first_displayed_entry = NULL;
3049 return NULL;
3052 static const struct got_error *
3053 tree_view_walk_path(struct tog_tree_view_state *s,
3054 struct got_commit_object *commit, const char *path)
3056 const struct got_error *err = NULL;
3057 struct got_tree_object *tree = NULL;
3058 const char *p;
3059 char *slash, *subpath = NULL;
3061 /* Walk the path and open corresponding tree objects. */
3062 p = path;
3063 while (*p) {
3064 struct got_tree_entry *te;
3065 struct got_object_id *tree_id;
3066 char *te_name;
3068 while (p[0] == '/')
3069 p++;
3071 /* Ensure the correct subtree entry is selected. */
3072 slash = strchr(p, '/');
3073 if (slash == NULL)
3074 te_name = strdup(p);
3075 else
3076 te_name = strndup(p, slash - p);
3077 if (te_name == NULL) {
3078 err = got_error_from_errno("strndup");
3079 break;
3081 te = got_object_tree_find_entry(s->tree, te_name);
3082 if (te == NULL) {
3083 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3084 free(te_name);
3085 break;
3087 free(te_name);
3088 s->first_displayed_entry = s->selected_entry = te;
3090 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3091 break; /* jump to this file's entry */
3093 slash = strchr(p, '/');
3094 if (slash)
3095 subpath = strndup(path, slash - path);
3096 else
3097 subpath = strdup(path);
3098 if (subpath == NULL) {
3099 err = got_error_from_errno("strdup");
3100 break;
3103 err = got_object_id_by_path(&tree_id, s->repo, commit,
3104 subpath);
3105 if (err)
3106 break;
3108 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3109 free(tree_id);
3110 if (err)
3111 break;
3113 err = tree_view_visit_subtree(s, tree);
3114 if (err) {
3115 got_object_tree_close(tree);
3116 break;
3118 if (slash == NULL)
3119 break;
3120 free(subpath);
3121 subpath = NULL;
3122 p = slash;
3125 free(subpath);
3126 return err;
3129 static const struct got_error *
3130 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3131 struct commit_queue_entry *entry, const char *path,
3132 const char *head_ref_name, struct got_repository *repo)
3134 const struct got_error *err = NULL;
3135 struct tog_tree_view_state *s;
3136 struct tog_view *tree_view;
3138 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3139 if (tree_view == NULL)
3140 return got_error_from_errno("view_open");
3142 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3143 if (err)
3144 return err;
3145 s = &tree_view->state.tree;
3147 *new_view = tree_view;
3149 if (got_path_is_root_dir(path))
3150 return NULL;
3152 return tree_view_walk_path(s, entry->commit, path);
3155 static const struct got_error *
3156 block_signals_used_by_main_thread(void)
3158 sigset_t sigset;
3159 int errcode;
3161 if (sigemptyset(&sigset) == -1)
3162 return got_error_from_errno("sigemptyset");
3164 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3165 if (sigaddset(&sigset, SIGWINCH) == -1)
3166 return got_error_from_errno("sigaddset");
3167 if (sigaddset(&sigset, SIGCONT) == -1)
3168 return got_error_from_errno("sigaddset");
3169 if (sigaddset(&sigset, SIGINT) == -1)
3170 return got_error_from_errno("sigaddset");
3171 if (sigaddset(&sigset, SIGTERM) == -1)
3172 return got_error_from_errno("sigaddset");
3174 /* ncurses handles SIGTSTP */
3175 if (sigaddset(&sigset, SIGTSTP) == -1)
3176 return got_error_from_errno("sigaddset");
3178 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3179 if (errcode)
3180 return got_error_set_errno(errcode, "pthread_sigmask");
3182 return NULL;
3185 static void *
3186 log_thread(void *arg)
3188 const struct got_error *err = NULL;
3189 int errcode = 0;
3190 struct tog_log_thread_args *a = arg;
3191 int done = 0;
3194 * Sync startup with main thread such that we begin our
3195 * work once view_input() has released the mutex.
3197 errcode = pthread_mutex_lock(&tog_mutex);
3198 if (errcode) {
3199 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3200 return (void *)err;
3203 err = block_signals_used_by_main_thread();
3204 if (err) {
3205 pthread_mutex_unlock(&tog_mutex);
3206 goto done;
3209 while (!done && !err && !tog_fatal_signal_received()) {
3210 errcode = pthread_mutex_unlock(&tog_mutex);
3211 if (errcode) {
3212 err = got_error_set_errno(errcode,
3213 "pthread_mutex_unlock");
3214 goto done;
3216 err = queue_commits(a);
3217 if (err) {
3218 if (err->code != GOT_ERR_ITER_COMPLETED)
3219 goto done;
3220 err = NULL;
3221 done = 1;
3222 } else if (a->commits_needed > 0 && !a->load_all) {
3223 if (*a->limiting) {
3224 if (a->limit_match)
3225 a->commits_needed--;
3226 } else
3227 a->commits_needed--;
3230 errcode = pthread_mutex_lock(&tog_mutex);
3231 if (errcode) {
3232 err = got_error_set_errno(errcode,
3233 "pthread_mutex_lock");
3234 goto done;
3235 } else if (*a->quit)
3236 done = 1;
3237 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3238 *a->first_displayed_entry =
3239 TAILQ_FIRST(&a->limit_commits->head);
3240 *a->selected_entry = *a->first_displayed_entry;
3241 } else if (*a->first_displayed_entry == NULL) {
3242 *a->first_displayed_entry =
3243 TAILQ_FIRST(&a->real_commits->head);
3244 *a->selected_entry = *a->first_displayed_entry;
3247 errcode = pthread_cond_signal(&a->commit_loaded);
3248 if (errcode) {
3249 err = got_error_set_errno(errcode,
3250 "pthread_cond_signal");
3251 pthread_mutex_unlock(&tog_mutex);
3252 goto done;
3255 if (done)
3256 a->commits_needed = 0;
3257 else {
3258 if (a->commits_needed == 0 && !a->load_all) {
3259 errcode = pthread_cond_wait(&a->need_commits,
3260 &tog_mutex);
3261 if (errcode) {
3262 err = got_error_set_errno(errcode,
3263 "pthread_cond_wait");
3264 pthread_mutex_unlock(&tog_mutex);
3265 goto done;
3267 if (*a->quit)
3268 done = 1;
3272 a->log_complete = 1;
3273 errcode = pthread_mutex_unlock(&tog_mutex);
3274 if (errcode)
3275 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3276 done:
3277 if (err) {
3278 tog_thread_error = 1;
3279 pthread_cond_signal(&a->commit_loaded);
3281 return (void *)err;
3284 static const struct got_error *
3285 stop_log_thread(struct tog_log_view_state *s)
3287 const struct got_error *err = NULL, *thread_err = NULL;
3288 int errcode;
3290 if (s->thread) {
3291 s->quit = 1;
3292 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3293 if (errcode)
3294 return got_error_set_errno(errcode,
3295 "pthread_cond_signal");
3296 errcode = pthread_mutex_unlock(&tog_mutex);
3297 if (errcode)
3298 return got_error_set_errno(errcode,
3299 "pthread_mutex_unlock");
3300 errcode = pthread_join(s->thread, (void **)&thread_err);
3301 if (errcode)
3302 return got_error_set_errno(errcode, "pthread_join");
3303 errcode = pthread_mutex_lock(&tog_mutex);
3304 if (errcode)
3305 return got_error_set_errno(errcode,
3306 "pthread_mutex_lock");
3307 s->thread = 0; //NULL;
3310 if (s->thread_args.repo) {
3311 err = got_repo_close(s->thread_args.repo);
3312 s->thread_args.repo = NULL;
3315 if (s->thread_args.pack_fds) {
3316 const struct got_error *pack_err =
3317 got_repo_pack_fds_close(s->thread_args.pack_fds);
3318 if (err == NULL)
3319 err = pack_err;
3320 s->thread_args.pack_fds = NULL;
3323 if (s->thread_args.graph) {
3324 got_commit_graph_close(s->thread_args.graph);
3325 s->thread_args.graph = NULL;
3328 return err ? err : thread_err;
3331 static const struct got_error *
3332 close_log_view(struct tog_view *view)
3334 const struct got_error *err = NULL;
3335 struct tog_log_view_state *s = &view->state.log;
3336 int errcode;
3338 err = stop_log_thread(s);
3340 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3341 if (errcode && err == NULL)
3342 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3344 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3345 if (errcode && err == NULL)
3346 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3348 free_commits(&s->limit_commits);
3349 free_commits(&s->real_commits);
3350 free(s->in_repo_path);
3351 s->in_repo_path = NULL;
3352 free(s->start_id);
3353 s->start_id = NULL;
3354 free(s->head_ref_name);
3355 s->head_ref_name = NULL;
3356 return err;
3360 * We use two queues to implement the limit feature: first consists of
3361 * commits matching the current limit_regex; second is the real queue
3362 * of all known commits (real_commits). When the user starts limiting,
3363 * we swap queues such that all movement and displaying functionality
3364 * works with very slight change.
3366 static const struct got_error *
3367 limit_log_view(struct tog_view *view)
3369 struct tog_log_view_state *s = &view->state.log;
3370 struct commit_queue_entry *entry;
3371 struct tog_view *v = view;
3372 const struct got_error *err = NULL;
3373 char pattern[1024];
3374 int ret;
3376 if (view_is_hsplit_top(view))
3377 v = view->child;
3378 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3379 v = view->parent;
3381 /* Get the pattern */
3382 wmove(v->window, v->nlines - 1, 0);
3383 wclrtoeol(v->window);
3384 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3385 nodelay(v->window, FALSE);
3386 nocbreak();
3387 echo();
3388 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3389 cbreak();
3390 noecho();
3391 nodelay(v->window, TRUE);
3392 if (ret == ERR)
3393 return NULL;
3395 if (*pattern == '\0') {
3397 * Safety measure for the situation where the user
3398 * resets limit without previously limiting anything.
3400 if (!s->limit_view)
3401 return NULL;
3404 * User could have pressed Ctrl+L, which refreshed the
3405 * commit queues, it means we can't save previously
3406 * (before limit took place) displayed entries,
3407 * because they would point to already free'ed memory,
3408 * so we are forced to always select first entry of
3409 * the queue.
3411 s->commits = &s->real_commits;
3412 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3413 s->selected_entry = s->first_displayed_entry;
3414 s->selected = 0;
3415 s->limit_view = 0;
3417 return NULL;
3420 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3421 return NULL;
3423 s->limit_view = 1;
3425 /* Clear the screen while loading limit view */
3426 s->first_displayed_entry = NULL;
3427 s->last_displayed_entry = NULL;
3428 s->selected_entry = NULL;
3429 s->commits = &s->limit_commits;
3431 /* Prepare limit queue for new search */
3432 free_commits(&s->limit_commits);
3433 s->limit_commits.ncommits = 0;
3435 /* First process commits, which are in queue already */
3436 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3437 int have_match = 0;
3439 err = match_commit(&have_match, entry->id,
3440 entry->commit, &s->limit_regex);
3441 if (err)
3442 return err;
3444 if (have_match) {
3445 struct commit_queue_entry *matched;
3447 matched = alloc_commit_queue_entry(entry->commit,
3448 entry->id);
3449 if (matched == NULL) {
3450 err = got_error_from_errno(
3451 "alloc_commit_queue_entry");
3452 break;
3454 matched->commit = entry->commit;
3455 got_object_commit_retain(entry->commit);
3457 matched->idx = s->limit_commits.ncommits;
3458 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3459 matched, entry);
3460 s->limit_commits.ncommits++;
3464 /* Second process all the commits, until we fill the screen */
3465 if (s->limit_commits.ncommits < view->nlines - 1 &&
3466 !s->thread_args.log_complete) {
3467 s->thread_args.commits_needed +=
3468 view->nlines - s->limit_commits.ncommits - 1;
3469 err = trigger_log_thread(view, 1);
3470 if (err)
3471 return err;
3474 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3475 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3476 s->selected = 0;
3478 return NULL;
3481 static const struct got_error *
3482 search_start_log_view(struct tog_view *view)
3484 struct tog_log_view_state *s = &view->state.log;
3486 s->matched_entry = NULL;
3487 s->search_entry = NULL;
3488 return NULL;
3491 static const struct got_error *
3492 search_next_log_view(struct tog_view *view)
3494 const struct got_error *err = NULL;
3495 struct tog_log_view_state *s = &view->state.log;
3496 struct commit_queue_entry *entry;
3498 /* Display progress update in log view. */
3499 show_log_view(view);
3500 update_panels();
3501 doupdate();
3503 if (s->search_entry) {
3504 int errcode, ch;
3505 errcode = pthread_mutex_unlock(&tog_mutex);
3506 if (errcode)
3507 return got_error_set_errno(errcode,
3508 "pthread_mutex_unlock");
3509 ch = wgetch(view->window);
3510 errcode = pthread_mutex_lock(&tog_mutex);
3511 if (errcode)
3512 return got_error_set_errno(errcode,
3513 "pthread_mutex_lock");
3514 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3515 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3516 return NULL;
3518 if (view->searching == TOG_SEARCH_FORWARD)
3519 entry = TAILQ_NEXT(s->search_entry, entry);
3520 else
3521 entry = TAILQ_PREV(s->search_entry,
3522 commit_queue_head, entry);
3523 } else if (s->matched_entry) {
3525 * If the user has moved the cursor after we hit a match,
3526 * the position from where we should continue searching
3527 * might have changed.
3529 if (view->searching == TOG_SEARCH_FORWARD)
3530 entry = TAILQ_NEXT(s->selected_entry, entry);
3531 else
3532 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3533 entry);
3534 } else {
3535 entry = s->selected_entry;
3538 while (1) {
3539 int have_match = 0;
3541 if (entry == NULL) {
3542 if (s->thread_args.log_complete ||
3543 view->searching == TOG_SEARCH_BACKWARD) {
3544 view->search_next_done =
3545 (s->matched_entry == NULL ?
3546 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3547 s->search_entry = NULL;
3548 return NULL;
3551 * Poke the log thread for more commits and return,
3552 * allowing the main loop to make progress. Search
3553 * will resume at s->search_entry once we come back.
3555 s->thread_args.commits_needed++;
3556 return trigger_log_thread(view, 0);
3559 err = match_commit(&have_match, entry->id, entry->commit,
3560 &view->regex);
3561 if (err)
3562 break;
3563 if (have_match) {
3564 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3565 s->matched_entry = entry;
3566 break;
3569 s->search_entry = entry;
3570 if (view->searching == TOG_SEARCH_FORWARD)
3571 entry = TAILQ_NEXT(entry, entry);
3572 else
3573 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3576 if (s->matched_entry) {
3577 int cur = s->selected_entry->idx;
3578 while (cur < s->matched_entry->idx) {
3579 err = input_log_view(NULL, view, KEY_DOWN);
3580 if (err)
3581 return err;
3582 cur++;
3584 while (cur > s->matched_entry->idx) {
3585 err = input_log_view(NULL, view, KEY_UP);
3586 if (err)
3587 return err;
3588 cur--;
3592 s->search_entry = NULL;
3594 return NULL;
3597 static const struct got_error *
3598 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3599 struct got_repository *repo, const char *head_ref_name,
3600 const char *in_repo_path, int log_branches)
3602 const struct got_error *err = NULL;
3603 struct tog_log_view_state *s = &view->state.log;
3604 struct got_repository *thread_repo = NULL;
3605 struct got_commit_graph *thread_graph = NULL;
3606 int errcode;
3608 if (in_repo_path != s->in_repo_path) {
3609 free(s->in_repo_path);
3610 s->in_repo_path = strdup(in_repo_path);
3611 if (s->in_repo_path == NULL) {
3612 err = got_error_from_errno("strdup");
3613 goto done;
3617 /* The commit queue only contains commits being displayed. */
3618 TAILQ_INIT(&s->real_commits.head);
3619 s->real_commits.ncommits = 0;
3620 s->commits = &s->real_commits;
3622 TAILQ_INIT(&s->limit_commits.head);
3623 s->limit_view = 0;
3624 s->limit_commits.ncommits = 0;
3626 s->repo = repo;
3627 if (head_ref_name) {
3628 s->head_ref_name = strdup(head_ref_name);
3629 if (s->head_ref_name == NULL) {
3630 err = got_error_from_errno("strdup");
3631 goto done;
3634 s->start_id = got_object_id_dup(start_id);
3635 if (s->start_id == NULL) {
3636 err = got_error_from_errno("got_object_id_dup");
3637 goto done;
3639 s->log_branches = log_branches;
3640 s->use_committer = 1;
3642 STAILQ_INIT(&s->colors);
3643 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3644 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3645 get_color_value("TOG_COLOR_COMMIT"));
3646 if (err)
3647 goto done;
3648 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3649 get_color_value("TOG_COLOR_AUTHOR"));
3650 if (err) {
3651 free_colors(&s->colors);
3652 goto done;
3654 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3655 get_color_value("TOG_COLOR_DATE"));
3656 if (err) {
3657 free_colors(&s->colors);
3658 goto done;
3662 view->show = show_log_view;
3663 view->input = input_log_view;
3664 view->resize = resize_log_view;
3665 view->close = close_log_view;
3666 view->search_start = search_start_log_view;
3667 view->search_next = search_next_log_view;
3669 if (s->thread_args.pack_fds == NULL) {
3670 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3671 if (err)
3672 goto done;
3674 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3675 s->thread_args.pack_fds);
3676 if (err)
3677 goto done;
3678 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3679 !s->log_branches);
3680 if (err)
3681 goto done;
3682 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3683 s->repo, NULL, NULL);
3684 if (err)
3685 goto done;
3687 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3688 if (errcode) {
3689 err = got_error_set_errno(errcode, "pthread_cond_init");
3690 goto done;
3692 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3693 if (errcode) {
3694 err = got_error_set_errno(errcode, "pthread_cond_init");
3695 goto done;
3698 s->thread_args.commits_needed = view->nlines;
3699 s->thread_args.graph = thread_graph;
3700 s->thread_args.real_commits = &s->real_commits;
3701 s->thread_args.limit_commits = &s->limit_commits;
3702 s->thread_args.in_repo_path = s->in_repo_path;
3703 s->thread_args.start_id = s->start_id;
3704 s->thread_args.repo = thread_repo;
3705 s->thread_args.log_complete = 0;
3706 s->thread_args.quit = &s->quit;
3707 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3708 s->thread_args.selected_entry = &s->selected_entry;
3709 s->thread_args.searching = &view->searching;
3710 s->thread_args.search_next_done = &view->search_next_done;
3711 s->thread_args.regex = &view->regex;
3712 s->thread_args.limiting = &s->limit_view;
3713 s->thread_args.limit_regex = &s->limit_regex;
3714 s->thread_args.limit_commits = &s->limit_commits;
3715 done:
3716 if (err) {
3717 if (view->close == NULL)
3718 close_log_view(view);
3719 view_close(view);
3721 return err;
3724 static const struct got_error *
3725 show_log_view(struct tog_view *view)
3727 const struct got_error *err;
3728 struct tog_log_view_state *s = &view->state.log;
3730 if (s->thread == 0) { //NULL) {
3731 int errcode = pthread_create(&s->thread, NULL, log_thread,
3732 &s->thread_args);
3733 if (errcode)
3734 return got_error_set_errno(errcode, "pthread_create");
3735 if (s->thread_args.commits_needed > 0) {
3736 err = trigger_log_thread(view, 1);
3737 if (err)
3738 return err;
3742 return draw_commits(view);
3745 static void
3746 log_move_cursor_up(struct tog_view *view, int page, int home)
3748 struct tog_log_view_state *s = &view->state.log;
3750 if (s->first_displayed_entry == NULL)
3751 return;
3752 if (s->selected_entry->idx == 0)
3753 view->count = 0;
3755 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3756 || home)
3757 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3759 if (!page && !home && s->selected > 0)
3760 --s->selected;
3761 else
3762 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3764 select_commit(s);
3765 return;
3768 static const struct got_error *
3769 log_move_cursor_down(struct tog_view *view, int page)
3771 struct tog_log_view_state *s = &view->state.log;
3772 const struct got_error *err = NULL;
3773 int eos = view->nlines - 2;
3775 if (s->first_displayed_entry == NULL)
3776 return NULL;
3778 if (s->thread_args.log_complete &&
3779 s->selected_entry->idx >= s->commits->ncommits - 1)
3780 return NULL;
3782 if (view_is_hsplit_top(view))
3783 --eos; /* border consumes the last line */
3785 if (!page) {
3786 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3787 ++s->selected;
3788 else
3789 err = log_scroll_down(view, 1);
3790 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3791 struct commit_queue_entry *entry;
3792 int n;
3794 s->selected = 0;
3795 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3796 s->last_displayed_entry = entry;
3797 for (n = 0; n <= eos; n++) {
3798 if (entry == NULL)
3799 break;
3800 s->first_displayed_entry = entry;
3801 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3803 if (n > 0)
3804 s->selected = n - 1;
3805 } else {
3806 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3807 s->thread_args.log_complete)
3808 s->selected += MIN(page,
3809 s->commits->ncommits - s->selected_entry->idx - 1);
3810 else
3811 err = log_scroll_down(view, page);
3813 if (err)
3814 return err;
3817 * We might necessarily overshoot in horizontal
3818 * splits; if so, select the last displayed commit.
3820 if (s->first_displayed_entry && s->last_displayed_entry) {
3821 s->selected = MIN(s->selected,
3822 s->last_displayed_entry->idx -
3823 s->first_displayed_entry->idx);
3826 select_commit(s);
3828 if (s->thread_args.log_complete &&
3829 s->selected_entry->idx == s->commits->ncommits - 1)
3830 view->count = 0;
3832 return NULL;
3835 static void
3836 view_get_split(struct tog_view *view, int *y, int *x)
3838 *x = 0;
3839 *y = 0;
3841 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3842 if (view->child && view->child->resized_y)
3843 *y = view->child->resized_y;
3844 else if (view->resized_y)
3845 *y = view->resized_y;
3846 else
3847 *y = view_split_begin_y(view->lines);
3848 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3849 if (view->child && view->child->resized_x)
3850 *x = view->child->resized_x;
3851 else if (view->resized_x)
3852 *x = view->resized_x;
3853 else
3854 *x = view_split_begin_x(view->begin_x);
3858 /* Split view horizontally at y and offset view->state->selected line. */
3859 static const struct got_error *
3860 view_init_hsplit(struct tog_view *view, int y)
3862 const struct got_error *err = NULL;
3864 view->nlines = y;
3865 view->ncols = COLS;
3866 err = view_resize(view);
3867 if (err)
3868 return err;
3870 err = offset_selection_down(view);
3872 return err;
3875 static const struct got_error *
3876 log_goto_line(struct tog_view *view, int nlines)
3878 const struct got_error *err = NULL;
3879 struct tog_log_view_state *s = &view->state.log;
3880 int g, idx = s->selected_entry->idx;
3882 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3883 return NULL;
3885 g = view->gline;
3886 view->gline = 0;
3888 if (g >= s->first_displayed_entry->idx + 1 &&
3889 g <= s->last_displayed_entry->idx + 1 &&
3890 g - s->first_displayed_entry->idx - 1 < nlines) {
3891 s->selected = g - s->first_displayed_entry->idx - 1;
3892 select_commit(s);
3893 return NULL;
3896 if (idx + 1 < g) {
3897 err = log_move_cursor_down(view, g - idx - 1);
3898 if (!err && g > s->selected_entry->idx + 1)
3899 err = log_move_cursor_down(view,
3900 g - s->first_displayed_entry->idx - 1);
3901 if (err)
3902 return err;
3903 } else if (idx + 1 > g)
3904 log_move_cursor_up(view, idx - g + 1, 0);
3906 if (g < nlines && s->first_displayed_entry->idx == 0)
3907 s->selected = g - 1;
3909 select_commit(s);
3910 return NULL;
3914 static void
3915 horizontal_scroll_input(struct tog_view *view, int ch)
3918 switch (ch) {
3919 case KEY_LEFT:
3920 case 'h':
3921 view->x -= MIN(view->x, 2);
3922 if (view->x <= 0)
3923 view->count = 0;
3924 break;
3925 case KEY_RIGHT:
3926 case 'l':
3927 if (view->x + view->ncols / 2 < view->maxx)
3928 view->x += 2;
3929 else
3930 view->count = 0;
3931 break;
3932 case '0':
3933 view->x = 0;
3934 break;
3935 case '$':
3936 view->x = MAX(view->maxx - view->ncols / 2, 0);
3937 view->count = 0;
3938 break;
3939 default:
3940 break;
3944 static const struct got_error *
3945 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3947 const struct got_error *err = NULL;
3948 struct tog_log_view_state *s = &view->state.log;
3949 int eos, nscroll;
3951 if (s->thread_args.load_all) {
3952 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3953 s->thread_args.load_all = 0;
3954 else if (s->thread_args.log_complete) {
3955 err = log_move_cursor_down(view, s->commits->ncommits);
3956 s->thread_args.load_all = 0;
3958 if (err)
3959 return err;
3962 eos = nscroll = view->nlines - 1;
3963 if (view_is_hsplit_top(view))
3964 --eos; /* border */
3966 if (view->gline)
3967 return log_goto_line(view, eos);
3969 switch (ch) {
3970 case '&':
3971 err = limit_log_view(view);
3972 break;
3973 case 'q':
3974 s->quit = 1;
3975 break;
3976 case '0':
3977 case '$':
3978 case KEY_RIGHT:
3979 case 'l':
3980 case KEY_LEFT:
3981 case 'h':
3982 horizontal_scroll_input(view, ch);
3983 break;
3984 case 'k':
3985 case KEY_UP:
3986 case '<':
3987 case ',':
3988 case CTRL('p'):
3989 log_move_cursor_up(view, 0, 0);
3990 break;
3991 case 'g':
3992 case '=':
3993 case KEY_HOME:
3994 log_move_cursor_up(view, 0, 1);
3995 view->count = 0;
3996 break;
3997 case CTRL('u'):
3998 case 'u':
3999 nscroll /= 2;
4000 /* FALL THROUGH */
4001 case KEY_PPAGE:
4002 case CTRL('b'):
4003 case 'b':
4004 log_move_cursor_up(view, nscroll, 0);
4005 break;
4006 case 'j':
4007 case KEY_DOWN:
4008 case '>':
4009 case '.':
4010 case CTRL('n'):
4011 err = log_move_cursor_down(view, 0);
4012 break;
4013 case '@':
4014 s->use_committer = !s->use_committer;
4015 view->action = s->use_committer ?
4016 "show committer" : "show commit author";
4017 break;
4018 case 'G':
4019 case '*':
4020 case KEY_END: {
4021 /* We don't know yet how many commits, so we're forced to
4022 * traverse them all. */
4023 view->count = 0;
4024 s->thread_args.load_all = 1;
4025 if (!s->thread_args.log_complete)
4026 return trigger_log_thread(view, 0);
4027 err = log_move_cursor_down(view, s->commits->ncommits);
4028 s->thread_args.load_all = 0;
4029 break;
4031 case CTRL('d'):
4032 case 'd':
4033 nscroll /= 2;
4034 /* FALL THROUGH */
4035 case KEY_NPAGE:
4036 case CTRL('f'):
4037 case 'f':
4038 case ' ':
4039 err = log_move_cursor_down(view, nscroll);
4040 break;
4041 case KEY_RESIZE:
4042 if (s->selected > view->nlines - 2)
4043 s->selected = view->nlines - 2;
4044 if (s->selected > s->commits->ncommits - 1)
4045 s->selected = s->commits->ncommits - 1;
4046 select_commit(s);
4047 if (s->commits->ncommits < view->nlines - 1 &&
4048 !s->thread_args.log_complete) {
4049 s->thread_args.commits_needed += (view->nlines - 1) -
4050 s->commits->ncommits;
4051 err = trigger_log_thread(view, 1);
4053 break;
4054 case KEY_ENTER:
4055 case '\r':
4056 view->count = 0;
4057 if (s->selected_entry == NULL)
4058 break;
4059 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4060 break;
4061 case 'T':
4062 view->count = 0;
4063 if (s->selected_entry == NULL)
4064 break;
4065 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4066 break;
4067 case KEY_BACKSPACE:
4068 case CTRL('l'):
4069 case 'B':
4070 view->count = 0;
4071 if (ch == KEY_BACKSPACE &&
4072 got_path_is_root_dir(s->in_repo_path))
4073 break;
4074 err = stop_log_thread(s);
4075 if (err)
4076 return err;
4077 if (ch == KEY_BACKSPACE) {
4078 char *parent_path;
4079 err = got_path_dirname(&parent_path, s->in_repo_path);
4080 if (err)
4081 return err;
4082 free(s->in_repo_path);
4083 s->in_repo_path = parent_path;
4084 s->thread_args.in_repo_path = s->in_repo_path;
4085 } else if (ch == CTRL('l')) {
4086 struct got_object_id *start_id;
4087 err = got_repo_match_object_id(&start_id, NULL,
4088 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4089 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4090 if (err) {
4091 if (s->head_ref_name == NULL ||
4092 err->code != GOT_ERR_NOT_REF)
4093 return err;
4094 /* Try to cope with deleted references. */
4095 free(s->head_ref_name);
4096 s->head_ref_name = NULL;
4097 err = got_repo_match_object_id(&start_id,
4098 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4099 &tog_refs, s->repo);
4100 if (err)
4101 return err;
4103 free(s->start_id);
4104 s->start_id = start_id;
4105 s->thread_args.start_id = s->start_id;
4106 } else /* 'B' */
4107 s->log_branches = !s->log_branches;
4109 if (s->thread_args.pack_fds == NULL) {
4110 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4111 if (err)
4112 return err;
4114 err = got_repo_open(&s->thread_args.repo,
4115 got_repo_get_path(s->repo), NULL,
4116 s->thread_args.pack_fds);
4117 if (err)
4118 return err;
4119 tog_free_refs();
4120 err = tog_load_refs(s->repo, 0);
4121 if (err)
4122 return err;
4123 err = got_commit_graph_open(&s->thread_args.graph,
4124 s->in_repo_path, !s->log_branches);
4125 if (err)
4126 return err;
4127 err = got_commit_graph_iter_start(s->thread_args.graph,
4128 s->start_id, s->repo, NULL, NULL);
4129 if (err)
4130 return err;
4131 free_commits(&s->real_commits);
4132 free_commits(&s->limit_commits);
4133 s->first_displayed_entry = NULL;
4134 s->last_displayed_entry = NULL;
4135 s->selected_entry = NULL;
4136 s->selected = 0;
4137 s->thread_args.log_complete = 0;
4138 s->quit = 0;
4139 s->thread_args.commits_needed = view->lines;
4140 s->matched_entry = NULL;
4141 s->search_entry = NULL;
4142 view->offset = 0;
4143 break;
4144 case 'R':
4145 view->count = 0;
4146 err = view_request_new(new_view, view, TOG_VIEW_REF);
4147 break;
4148 default:
4149 view->count = 0;
4150 break;
4153 return err;
4156 static const struct got_error *
4157 apply_unveil(const char *repo_path, const char *worktree_path)
4159 const struct got_error *error;
4161 #ifdef PROFILE
4162 if (unveil("gmon.out", "rwc") != 0)
4163 return got_error_from_errno2("unveil", "gmon.out");
4164 #endif
4165 if (repo_path && unveil(repo_path, "r") != 0)
4166 return got_error_from_errno2("unveil", repo_path);
4168 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4169 return got_error_from_errno2("unveil", worktree_path);
4171 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4172 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4174 error = got_privsep_unveil_exec_helpers();
4175 if (error != NULL)
4176 return error;
4178 if (unveil(NULL, NULL) != 0)
4179 return got_error_from_errno("unveil");
4181 return NULL;
4184 static const struct got_error *
4185 init_mock_term(const char *test_script_path)
4187 const struct got_error *err = NULL;
4188 const char *screen_dump_path;
4189 int in;
4191 if (test_script_path == NULL || *test_script_path == '\0')
4192 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4194 tog_io.f = fopen(test_script_path, "re");
4195 if (tog_io.f == NULL) {
4196 err = got_error_from_errno_fmt("fopen: %s",
4197 test_script_path);
4198 goto done;
4201 /* test mode, we don't want any output */
4202 tog_io.cout = fopen("/dev/null", "w+");
4203 if (tog_io.cout == NULL) {
4204 err = got_error_from_errno2("fopen", "/dev/null");
4205 goto done;
4208 in = dup(fileno(tog_io.cout));
4209 if (in == -1) {
4210 err = got_error_from_errno("dup");
4211 goto done;
4213 tog_io.cin = fdopen(in, "r");
4214 if (tog_io.cin == NULL) {
4215 err = got_error_from_errno("fdopen");
4216 close(in);
4217 goto done;
4220 screen_dump_path = getenv("TOG_SCR_DUMP");
4221 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4222 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4223 tog_io.sdump = fopen(screen_dump_path, "wex");
4224 if (tog_io.sdump == NULL) {
4225 err = got_error_from_errno2("fopen", screen_dump_path);
4226 goto done;
4229 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4230 err = got_error_from_errno("fseeko");
4231 goto done;
4234 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4235 err = got_error_msg(GOT_ERR_IO,
4236 "newterm: failed to initialise curses");
4238 using_mock_io = 1;
4240 done:
4241 if (err)
4242 tog_io_close();
4243 return err;
4246 static void
4247 init_curses(void)
4250 * Override default signal handlers before starting ncurses.
4251 * This should prevent ncurses from installing its own
4252 * broken cleanup() signal handler.
4254 signal(SIGWINCH, tog_sigwinch);
4255 signal(SIGPIPE, tog_sigpipe);
4256 signal(SIGCONT, tog_sigcont);
4257 signal(SIGINT, tog_sigint);
4258 signal(SIGTERM, tog_sigterm);
4260 if (using_mock_io) /* In test mode we use a fake terminal */
4261 return;
4263 initscr();
4265 cbreak();
4266 halfdelay(1); /* Fast refresh while initial view is loading. */
4267 noecho();
4268 nonl();
4269 intrflush(stdscr, FALSE);
4270 keypad(stdscr, TRUE);
4271 curs_set(0);
4272 if (getenv("TOG_COLORS") != NULL) {
4273 start_color();
4274 use_default_colors();
4277 return;
4280 static const struct got_error *
4281 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4282 struct got_repository *repo, struct got_worktree *worktree)
4284 const struct got_error *err = NULL;
4286 if (argc == 0) {
4287 *in_repo_path = strdup("/");
4288 if (*in_repo_path == NULL)
4289 return got_error_from_errno("strdup");
4290 return NULL;
4293 if (worktree) {
4294 const char *prefix = got_worktree_get_path_prefix(worktree);
4295 char *p;
4297 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4298 if (err)
4299 return err;
4300 if (asprintf(in_repo_path, "%s%s%s", prefix,
4301 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4302 p) == -1) {
4303 err = got_error_from_errno("asprintf");
4304 *in_repo_path = NULL;
4306 free(p);
4307 } else
4308 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4310 return err;
4313 static const struct got_error *
4314 cmd_log(int argc, char *argv[])
4316 const struct got_error *error;
4317 struct got_repository *repo = NULL;
4318 struct got_worktree *worktree = NULL;
4319 struct got_object_id *start_id = NULL;
4320 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4321 char *start_commit = NULL, *label = NULL;
4322 struct got_reference *ref = NULL;
4323 const char *head_ref_name = NULL;
4324 int ch, log_branches = 0;
4325 struct tog_view *view;
4326 int *pack_fds = NULL;
4328 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4329 switch (ch) {
4330 case 'b':
4331 log_branches = 1;
4332 break;
4333 case 'c':
4334 start_commit = optarg;
4335 break;
4336 case 'r':
4337 repo_path = realpath(optarg, NULL);
4338 if (repo_path == NULL)
4339 return got_error_from_errno2("realpath",
4340 optarg);
4341 break;
4342 default:
4343 usage_log();
4344 /* NOTREACHED */
4348 argc -= optind;
4349 argv += optind;
4351 if (argc > 1)
4352 usage_log();
4354 error = got_repo_pack_fds_open(&pack_fds);
4355 if (error != NULL)
4356 goto done;
4358 if (repo_path == NULL) {
4359 cwd = getcwd(NULL, 0);
4360 if (cwd == NULL)
4361 return got_error_from_errno("getcwd");
4362 error = got_worktree_open(&worktree, cwd);
4363 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4364 goto done;
4365 if (worktree)
4366 repo_path =
4367 strdup(got_worktree_get_repo_path(worktree));
4368 else
4369 repo_path = strdup(cwd);
4370 if (repo_path == NULL) {
4371 error = got_error_from_errno("strdup");
4372 goto done;
4376 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4377 if (error != NULL)
4378 goto done;
4380 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4381 repo, worktree);
4382 if (error)
4383 goto done;
4385 init_curses();
4387 error = apply_unveil(got_repo_get_path(repo),
4388 worktree ? got_worktree_get_root_path(worktree) : NULL);
4389 if (error)
4390 goto done;
4392 /* already loaded by tog_log_with_path()? */
4393 if (TAILQ_EMPTY(&tog_refs)) {
4394 error = tog_load_refs(repo, 0);
4395 if (error)
4396 goto done;
4399 if (start_commit == NULL) {
4400 error = got_repo_match_object_id(&start_id, &label,
4401 worktree ? got_worktree_get_head_ref_name(worktree) :
4402 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4403 if (error)
4404 goto done;
4405 head_ref_name = label;
4406 } else {
4407 error = got_ref_open(&ref, repo, start_commit, 0);
4408 if (error == NULL)
4409 head_ref_name = got_ref_get_name(ref);
4410 else if (error->code != GOT_ERR_NOT_REF)
4411 goto done;
4412 error = got_repo_match_object_id(&start_id, NULL,
4413 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4414 if (error)
4415 goto done;
4418 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4419 if (view == NULL) {
4420 error = got_error_from_errno("view_open");
4421 goto done;
4423 error = open_log_view(view, start_id, repo, head_ref_name,
4424 in_repo_path, log_branches);
4425 if (error)
4426 goto done;
4427 if (worktree) {
4428 /* Release work tree lock. */
4429 got_worktree_close(worktree);
4430 worktree = NULL;
4432 error = view_loop(view);
4433 done:
4434 free(in_repo_path);
4435 free(repo_path);
4436 free(cwd);
4437 free(start_id);
4438 free(label);
4439 if (ref)
4440 got_ref_close(ref);
4441 if (repo) {
4442 const struct got_error *close_err = got_repo_close(repo);
4443 if (error == NULL)
4444 error = close_err;
4446 if (worktree)
4447 got_worktree_close(worktree);
4448 if (pack_fds) {
4449 const struct got_error *pack_err =
4450 got_repo_pack_fds_close(pack_fds);
4451 if (error == NULL)
4452 error = pack_err;
4454 tog_free_refs();
4455 return error;
4458 __dead static void
4459 usage_diff(void)
4461 endwin();
4462 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4463 "object1 object2\n", getprogname());
4464 exit(1);
4467 static int
4468 match_line(const char *line, regex_t *regex, size_t nmatch,
4469 regmatch_t *regmatch)
4471 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4474 static struct tog_color *
4475 match_color(struct tog_colors *colors, const char *line)
4477 struct tog_color *tc = NULL;
4479 STAILQ_FOREACH(tc, colors, entry) {
4480 if (match_line(line, &tc->regex, 0, NULL))
4481 return tc;
4484 return NULL;
4487 static const struct got_error *
4488 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4489 WINDOW *window, int skipcol, regmatch_t *regmatch)
4491 const struct got_error *err = NULL;
4492 char *exstr = NULL;
4493 wchar_t *wline = NULL;
4494 int rme, rms, n, width, scrollx;
4495 int width0 = 0, width1 = 0, width2 = 0;
4496 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4498 *wtotal = 0;
4500 rms = regmatch->rm_so;
4501 rme = regmatch->rm_eo;
4503 err = expand_tab(&exstr, line);
4504 if (err)
4505 return err;
4507 /* Split the line into 3 segments, according to match offsets. */
4508 seg0 = strndup(exstr, rms);
4509 if (seg0 == NULL) {
4510 err = got_error_from_errno("strndup");
4511 goto done;
4513 seg1 = strndup(exstr + rms, rme - rms);
4514 if (seg1 == NULL) {
4515 err = got_error_from_errno("strndup");
4516 goto done;
4518 seg2 = strdup(exstr + rme);
4519 if (seg2 == NULL) {
4520 err = got_error_from_errno("strndup");
4521 goto done;
4524 /* draw up to matched token if we haven't scrolled past it */
4525 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4526 col_tab_align, 1);
4527 if (err)
4528 goto done;
4529 n = MAX(width0 - skipcol, 0);
4530 if (n) {
4531 free(wline);
4532 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4533 wlimit, col_tab_align, 1);
4534 if (err)
4535 goto done;
4536 waddwstr(window, &wline[scrollx]);
4537 wlimit -= width;
4538 *wtotal += width;
4541 if (wlimit > 0) {
4542 int i = 0, w = 0;
4543 size_t wlen;
4545 free(wline);
4546 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4547 col_tab_align, 1);
4548 if (err)
4549 goto done;
4550 wlen = wcslen(wline);
4551 while (i < wlen) {
4552 width = wcwidth(wline[i]);
4553 if (width == -1) {
4554 /* should not happen, tabs are expanded */
4555 err = got_error(GOT_ERR_RANGE);
4556 goto done;
4558 if (width0 + w + width > skipcol)
4559 break;
4560 w += width;
4561 i++;
4563 /* draw (visible part of) matched token (if scrolled into it) */
4564 if (width1 - w > 0) {
4565 wattron(window, A_STANDOUT);
4566 waddwstr(window, &wline[i]);
4567 wattroff(window, A_STANDOUT);
4568 wlimit -= (width1 - w);
4569 *wtotal += (width1 - w);
4573 if (wlimit > 0) { /* draw rest of line */
4574 free(wline);
4575 if (skipcol > width0 + width1) {
4576 err = format_line(&wline, &width2, &scrollx, seg2,
4577 skipcol - (width0 + width1), wlimit,
4578 col_tab_align, 1);
4579 if (err)
4580 goto done;
4581 waddwstr(window, &wline[scrollx]);
4582 } else {
4583 err = format_line(&wline, &width2, NULL, seg2, 0,
4584 wlimit, col_tab_align, 1);
4585 if (err)
4586 goto done;
4587 waddwstr(window, wline);
4589 *wtotal += width2;
4591 done:
4592 free(wline);
4593 free(exstr);
4594 free(seg0);
4595 free(seg1);
4596 free(seg2);
4597 return err;
4600 static int
4601 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4603 FILE *f = NULL;
4604 int *eof, *first, *selected;
4606 if (view->type == TOG_VIEW_DIFF) {
4607 struct tog_diff_view_state *s = &view->state.diff;
4609 first = &s->first_displayed_line;
4610 selected = first;
4611 eof = &s->eof;
4612 f = s->f;
4613 } else if (view->type == TOG_VIEW_HELP) {
4614 struct tog_help_view_state *s = &view->state.help;
4616 first = &s->first_displayed_line;
4617 selected = first;
4618 eof = &s->eof;
4619 f = s->f;
4620 } else if (view->type == TOG_VIEW_BLAME) {
4621 struct tog_blame_view_state *s = &view->state.blame;
4623 first = &s->first_displayed_line;
4624 selected = &s->selected_line;
4625 eof = &s->eof;
4626 f = s->blame.f;
4627 } else
4628 return 0;
4630 /* Center gline in the middle of the page like vi(1). */
4631 if (*lineno < view->gline - (view->nlines - 3) / 2)
4632 return 0;
4633 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4634 rewind(f);
4635 *eof = 0;
4636 *first = 1;
4637 *lineno = 0;
4638 *nprinted = 0;
4639 return 0;
4642 *selected = view->gline <= (view->nlines - 3) / 2 ?
4643 view->gline : (view->nlines - 3) / 2 + 1;
4644 view->gline = 0;
4646 return 1;
4649 static const struct got_error *
4650 draw_file(struct tog_view *view, const char *header)
4652 struct tog_diff_view_state *s = &view->state.diff;
4653 regmatch_t *regmatch = &view->regmatch;
4654 const struct got_error *err;
4655 int nprinted = 0;
4656 char *line;
4657 size_t linesize = 0;
4658 ssize_t linelen;
4659 wchar_t *wline;
4660 int width;
4661 int max_lines = view->nlines;
4662 int nlines = s->nlines;
4663 off_t line_offset;
4665 s->lineno = s->first_displayed_line - 1;
4666 line_offset = s->lines[s->first_displayed_line - 1].offset;
4667 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4668 return got_error_from_errno("fseek");
4670 werase(view->window);
4672 if (view->gline > s->nlines - 1)
4673 view->gline = s->nlines - 1;
4675 if (header) {
4676 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4677 1 : view->gline - (view->nlines - 3) / 2 :
4678 s->lineno + s->selected_line;
4680 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4681 return got_error_from_errno("asprintf");
4682 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4683 0, 0);
4684 free(line);
4685 if (err)
4686 return err;
4688 if (view_needs_focus_indication(view))
4689 wstandout(view->window);
4690 waddwstr(view->window, wline);
4691 free(wline);
4692 wline = NULL;
4693 while (width++ < view->ncols)
4694 waddch(view->window, ' ');
4695 if (view_needs_focus_indication(view))
4696 wstandend(view->window);
4698 if (max_lines <= 1)
4699 return NULL;
4700 max_lines--;
4703 s->eof = 0;
4704 view->maxx = 0;
4705 line = NULL;
4706 while (max_lines > 0 && nprinted < max_lines) {
4707 enum got_diff_line_type linetype;
4708 attr_t attr = 0;
4710 linelen = getline(&line, &linesize, s->f);
4711 if (linelen == -1) {
4712 if (feof(s->f)) {
4713 s->eof = 1;
4714 break;
4716 free(line);
4717 return got_ferror(s->f, GOT_ERR_IO);
4720 if (++s->lineno < s->first_displayed_line)
4721 continue;
4722 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4723 continue;
4724 if (s->lineno == view->hiline)
4725 attr = A_STANDOUT;
4727 /* Set view->maxx based on full line length. */
4728 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4729 view->x ? 1 : 0);
4730 if (err) {
4731 free(line);
4732 return err;
4734 view->maxx = MAX(view->maxx, width);
4735 free(wline);
4736 wline = NULL;
4738 linetype = s->lines[s->lineno].type;
4739 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4740 linetype < GOT_DIFF_LINE_CONTEXT)
4741 attr |= COLOR_PAIR(linetype);
4742 if (attr)
4743 wattron(view->window, attr);
4744 if (s->first_displayed_line + nprinted == s->matched_line &&
4745 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4746 err = add_matched_line(&width, line, view->ncols, 0,
4747 view->window, view->x, regmatch);
4748 if (err) {
4749 free(line);
4750 return err;
4752 } else {
4753 int skip;
4754 err = format_line(&wline, &width, &skip, line,
4755 view->x, view->ncols, 0, view->x ? 1 : 0);
4756 if (err) {
4757 free(line);
4758 return err;
4760 waddwstr(view->window, &wline[skip]);
4761 free(wline);
4762 wline = NULL;
4764 if (s->lineno == view->hiline) {
4765 /* highlight full gline length */
4766 while (width++ < view->ncols)
4767 waddch(view->window, ' ');
4768 } else {
4769 if (width <= view->ncols - 1)
4770 waddch(view->window, '\n');
4772 if (attr)
4773 wattroff(view->window, attr);
4774 if (++nprinted == 1)
4775 s->first_displayed_line = s->lineno;
4777 free(line);
4778 if (nprinted >= 1)
4779 s->last_displayed_line = s->first_displayed_line +
4780 (nprinted - 1);
4781 else
4782 s->last_displayed_line = s->first_displayed_line;
4784 view_border(view);
4786 if (s->eof) {
4787 while (nprinted < view->nlines) {
4788 waddch(view->window, '\n');
4789 nprinted++;
4792 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4793 view->ncols, 0, 0);
4794 if (err) {
4795 return err;
4798 wstandout(view->window);
4799 waddwstr(view->window, wline);
4800 free(wline);
4801 wline = NULL;
4802 wstandend(view->window);
4805 return NULL;
4808 static char *
4809 get_datestr(time_t *time, char *datebuf)
4811 struct tm mytm, *tm;
4812 char *p, *s;
4814 tm = gmtime_r(time, &mytm);
4815 if (tm == NULL)
4816 return NULL;
4817 s = asctime_r(tm, datebuf);
4818 if (s == NULL)
4819 return NULL;
4820 p = strchr(s, '\n');
4821 if (p)
4822 *p = '\0';
4823 return s;
4826 static const struct got_error *
4827 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4828 off_t off, uint8_t type)
4830 struct got_diff_line *p;
4832 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4833 if (p == NULL)
4834 return got_error_from_errno("reallocarray");
4835 *lines = p;
4836 (*lines)[*nlines].offset = off;
4837 (*lines)[*nlines].type = type;
4838 (*nlines)++;
4840 return NULL;
4843 static const struct got_error *
4844 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4845 struct got_diff_line *s_lines, size_t s_nlines)
4847 struct got_diff_line *p;
4848 char buf[BUFSIZ];
4849 size_t i, r;
4851 if (fseeko(src, 0L, SEEK_SET) == -1)
4852 return got_error_from_errno("fseeko");
4854 for (;;) {
4855 r = fread(buf, 1, sizeof(buf), src);
4856 if (r == 0) {
4857 if (ferror(src))
4858 return got_error_from_errno("fread");
4859 if (feof(src))
4860 break;
4862 if (fwrite(buf, 1, r, dst) != r)
4863 return got_ferror(dst, GOT_ERR_IO);
4866 if (s_nlines == 0 && *d_nlines == 0)
4867 return NULL;
4870 * If commit info was in dst, increment line offsets
4871 * of the appended diff content, but skip s_lines[0]
4872 * because offset zero is already in *d_lines.
4874 if (*d_nlines > 0) {
4875 for (i = 1; i < s_nlines; ++i)
4876 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4878 if (s_nlines > 0) {
4879 --s_nlines;
4880 ++s_lines;
4884 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4885 if (p == NULL) {
4886 /* d_lines is freed in close_diff_view() */
4887 return got_error_from_errno("reallocarray");
4890 *d_lines = p;
4892 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4893 *d_nlines += s_nlines;
4895 return NULL;
4898 static const struct got_error *
4899 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4900 struct got_object_id *commit_id, struct got_reflist_head *refs,
4901 struct got_repository *repo, int ignore_ws, int force_text_diff,
4902 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4904 const struct got_error *err = NULL;
4905 char datebuf[26], *datestr;
4906 struct got_commit_object *commit;
4907 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4908 time_t committer_time;
4909 const char *author, *committer;
4910 char *refs_str = NULL;
4911 struct got_pathlist_entry *pe;
4912 off_t outoff = 0;
4913 int n;
4915 if (refs) {
4916 err = build_refs_str(&refs_str, refs, commit_id, repo);
4917 if (err)
4918 return err;
4921 err = got_object_open_as_commit(&commit, repo, commit_id);
4922 if (err)
4923 return err;
4925 err = got_object_id_str(&id_str, commit_id);
4926 if (err) {
4927 err = got_error_from_errno("got_object_id_str");
4928 goto done;
4931 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4932 if (err)
4933 goto done;
4935 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4936 refs_str ? refs_str : "", refs_str ? ")" : "");
4937 if (n < 0) {
4938 err = got_error_from_errno("fprintf");
4939 goto done;
4941 outoff += n;
4942 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4943 if (err)
4944 goto done;
4946 n = fprintf(outfile, "from: %s\n",
4947 got_object_commit_get_author(commit));
4948 if (n < 0) {
4949 err = got_error_from_errno("fprintf");
4950 goto done;
4952 outoff += n;
4953 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4954 if (err)
4955 goto done;
4957 author = got_object_commit_get_author(commit);
4958 committer = got_object_commit_get_committer(commit);
4959 if (strcmp(author, committer) != 0) {
4960 n = fprintf(outfile, "via: %s\n", committer);
4961 if (n < 0) {
4962 err = got_error_from_errno("fprintf");
4963 goto done;
4965 outoff += n;
4966 err = add_line_metadata(lines, nlines, outoff,
4967 GOT_DIFF_LINE_AUTHOR);
4968 if (err)
4969 goto done;
4971 committer_time = got_object_commit_get_committer_time(commit);
4972 datestr = get_datestr(&committer_time, datebuf);
4973 if (datestr) {
4974 n = fprintf(outfile, "date: %s UTC\n", datestr);
4975 if (n < 0) {
4976 err = got_error_from_errno("fprintf");
4977 goto done;
4979 outoff += n;
4980 err = add_line_metadata(lines, nlines, outoff,
4981 GOT_DIFF_LINE_DATE);
4982 if (err)
4983 goto done;
4985 if (got_object_commit_get_nparents(commit) > 1) {
4986 const struct got_object_id_queue *parent_ids;
4987 struct got_object_qid *qid;
4988 int pn = 1;
4989 parent_ids = got_object_commit_get_parent_ids(commit);
4990 STAILQ_FOREACH(qid, parent_ids, entry) {
4991 err = got_object_id_str(&id_str, &qid->id);
4992 if (err)
4993 goto done;
4994 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4995 if (n < 0) {
4996 err = got_error_from_errno("fprintf");
4997 goto done;
4999 outoff += n;
5000 err = add_line_metadata(lines, nlines, outoff,
5001 GOT_DIFF_LINE_META);
5002 if (err)
5003 goto done;
5004 free(id_str);
5005 id_str = NULL;
5009 err = got_object_commit_get_logmsg(&logmsg, commit);
5010 if (err)
5011 goto done;
5012 s = logmsg;
5013 while ((line = strsep(&s, "\n")) != NULL) {
5014 n = fprintf(outfile, "%s\n", line);
5015 if (n < 0) {
5016 err = got_error_from_errno("fprintf");
5017 goto done;
5019 outoff += n;
5020 err = add_line_metadata(lines, nlines, outoff,
5021 GOT_DIFF_LINE_LOGMSG);
5022 if (err)
5023 goto done;
5026 TAILQ_FOREACH(pe, dsa->paths, entry) {
5027 struct got_diff_changed_path *cp = pe->data;
5028 int pad = dsa->max_path_len - pe->path_len + 1;
5030 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5031 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5032 dsa->rm_cols + 1, cp->rm);
5033 if (n < 0) {
5034 err = got_error_from_errno("fprintf");
5035 goto done;
5037 outoff += n;
5038 err = add_line_metadata(lines, nlines, outoff,
5039 GOT_DIFF_LINE_CHANGES);
5040 if (err)
5041 goto done;
5044 fputc('\n', outfile);
5045 outoff++;
5046 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5047 if (err)
5048 goto done;
5050 n = fprintf(outfile,
5051 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5052 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5053 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5054 if (n < 0) {
5055 err = got_error_from_errno("fprintf");
5056 goto done;
5058 outoff += n;
5059 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5060 if (err)
5061 goto done;
5063 fputc('\n', outfile);
5064 outoff++;
5065 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5066 done:
5067 free(id_str);
5068 free(logmsg);
5069 free(refs_str);
5070 got_object_commit_close(commit);
5071 if (err) {
5072 free(*lines);
5073 *lines = NULL;
5074 *nlines = 0;
5076 return err;
5079 static const struct got_error *
5080 create_diff(struct tog_diff_view_state *s)
5082 const struct got_error *err = NULL;
5083 FILE *f = NULL, *tmp_diff_file = NULL;
5084 int obj_type;
5085 struct got_diff_line *lines = NULL;
5086 struct got_pathlist_head changed_paths;
5088 TAILQ_INIT(&changed_paths);
5090 free(s->lines);
5091 s->lines = malloc(sizeof(*s->lines));
5092 if (s->lines == NULL)
5093 return got_error_from_errno("malloc");
5094 s->nlines = 0;
5096 f = got_opentemp();
5097 if (f == NULL) {
5098 err = got_error_from_errno("got_opentemp");
5099 goto done;
5101 tmp_diff_file = got_opentemp();
5102 if (tmp_diff_file == NULL) {
5103 err = got_error_from_errno("got_opentemp");
5104 goto done;
5106 if (s->f && fclose(s->f) == EOF) {
5107 err = got_error_from_errno("fclose");
5108 goto done;
5110 s->f = f;
5112 if (s->id1)
5113 err = got_object_get_type(&obj_type, s->repo, s->id1);
5114 else
5115 err = got_object_get_type(&obj_type, s->repo, s->id2);
5116 if (err)
5117 goto done;
5119 switch (obj_type) {
5120 case GOT_OBJ_TYPE_BLOB:
5121 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5122 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5123 s->label1, s->label2, tog_diff_algo, s->diff_context,
5124 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5125 s->f);
5126 break;
5127 case GOT_OBJ_TYPE_TREE:
5128 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5129 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5130 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5131 s->force_text_diff, NULL, s->repo, s->f);
5132 break;
5133 case GOT_OBJ_TYPE_COMMIT: {
5134 const struct got_object_id_queue *parent_ids;
5135 struct got_object_qid *pid;
5136 struct got_commit_object *commit2;
5137 struct got_reflist_head *refs;
5138 size_t nlines = 0;
5139 struct got_diffstat_cb_arg dsa = {
5140 0, 0, 0, 0, 0, 0,
5141 &changed_paths,
5142 s->ignore_whitespace,
5143 s->force_text_diff,
5144 tog_diff_algo
5147 lines = malloc(sizeof(*lines));
5148 if (lines == NULL) {
5149 err = got_error_from_errno("malloc");
5150 goto done;
5153 /* build diff first in tmp file then append to commit info */
5154 err = got_diff_objects_as_commits(&lines, &nlines,
5155 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5156 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5157 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5158 if (err)
5159 break;
5161 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5162 if (err)
5163 goto done;
5164 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5165 /* Show commit info if we're diffing to a parent/root commit. */
5166 if (s->id1 == NULL) {
5167 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5168 refs, s->repo, s->ignore_whitespace,
5169 s->force_text_diff, &dsa, s->f);
5170 if (err)
5171 goto done;
5172 } else {
5173 parent_ids = got_object_commit_get_parent_ids(commit2);
5174 STAILQ_FOREACH(pid, parent_ids, entry) {
5175 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5176 err = write_commit_info(&s->lines,
5177 &s->nlines, s->id2, refs, s->repo,
5178 s->ignore_whitespace,
5179 s->force_text_diff, &dsa, s->f);
5180 if (err)
5181 goto done;
5182 break;
5186 got_object_commit_close(commit2);
5188 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5189 lines, nlines);
5190 break;
5192 default:
5193 err = got_error(GOT_ERR_OBJ_TYPE);
5194 break;
5196 done:
5197 free(lines);
5198 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5199 if (s->f && fflush(s->f) != 0 && err == NULL)
5200 err = got_error_from_errno("fflush");
5201 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5202 err = got_error_from_errno("fclose");
5203 return err;
5206 static void
5207 diff_view_indicate_progress(struct tog_view *view)
5209 mvwaddstr(view->window, 0, 0, "diffing...");
5210 update_panels();
5211 doupdate();
5214 static const struct got_error *
5215 search_start_diff_view(struct tog_view *view)
5217 struct tog_diff_view_state *s = &view->state.diff;
5219 s->matched_line = 0;
5220 return NULL;
5223 static void
5224 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5225 size_t *nlines, int **first, int **last, int **match, int **selected)
5227 struct tog_diff_view_state *s = &view->state.diff;
5229 *f = s->f;
5230 *nlines = s->nlines;
5231 *line_offsets = NULL;
5232 *match = &s->matched_line;
5233 *first = &s->first_displayed_line;
5234 *last = &s->last_displayed_line;
5235 *selected = &s->selected_line;
5238 static const struct got_error *
5239 search_next_view_match(struct tog_view *view)
5241 const struct got_error *err = NULL;
5242 FILE *f;
5243 int lineno;
5244 char *line = NULL;
5245 size_t linesize = 0;
5246 ssize_t linelen;
5247 off_t *line_offsets;
5248 size_t nlines = 0;
5249 int *first, *last, *match, *selected;
5251 if (!view->search_setup)
5252 return got_error_msg(GOT_ERR_NOT_IMPL,
5253 "view search not supported");
5254 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5255 &match, &selected);
5257 if (!view->searching) {
5258 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5259 return NULL;
5262 if (*match) {
5263 if (view->searching == TOG_SEARCH_FORWARD)
5264 lineno = *first + 1;
5265 else
5266 lineno = *first - 1;
5267 } else
5268 lineno = *first - 1 + *selected;
5270 while (1) {
5271 off_t offset;
5273 if (lineno <= 0 || lineno > nlines) {
5274 if (*match == 0) {
5275 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5276 break;
5279 if (view->searching == TOG_SEARCH_FORWARD)
5280 lineno = 1;
5281 else
5282 lineno = nlines;
5285 offset = view->type == TOG_VIEW_DIFF ?
5286 view->state.diff.lines[lineno - 1].offset :
5287 line_offsets[lineno - 1];
5288 if (fseeko(f, offset, SEEK_SET) != 0) {
5289 free(line);
5290 return got_error_from_errno("fseeko");
5292 linelen = getline(&line, &linesize, f);
5293 if (linelen != -1) {
5294 char *exstr;
5295 err = expand_tab(&exstr, line);
5296 if (err)
5297 break;
5298 if (match_line(exstr, &view->regex, 1,
5299 &view->regmatch)) {
5300 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5301 *match = lineno;
5302 free(exstr);
5303 break;
5305 free(exstr);
5307 if (view->searching == TOG_SEARCH_FORWARD)
5308 lineno++;
5309 else
5310 lineno--;
5312 free(line);
5314 if (*match) {
5315 *first = *match;
5316 *selected = 1;
5319 return err;
5322 static const struct got_error *
5323 close_diff_view(struct tog_view *view)
5325 const struct got_error *err = NULL;
5326 struct tog_diff_view_state *s = &view->state.diff;
5328 free(s->id1);
5329 s->id1 = NULL;
5330 free(s->id2);
5331 s->id2 = NULL;
5332 if (s->f && fclose(s->f) == EOF)
5333 err = got_error_from_errno("fclose");
5334 s->f = NULL;
5335 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5336 err = got_error_from_errno("fclose");
5337 s->f1 = NULL;
5338 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5339 err = got_error_from_errno("fclose");
5340 s->f2 = NULL;
5341 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5342 err = got_error_from_errno("close");
5343 s->fd1 = -1;
5344 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5345 err = got_error_from_errno("close");
5346 s->fd2 = -1;
5347 free(s->lines);
5348 s->lines = NULL;
5349 s->nlines = 0;
5350 return err;
5353 static const struct got_error *
5354 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5355 struct got_object_id *id2, const char *label1, const char *label2,
5356 int diff_context, int ignore_whitespace, int force_text_diff,
5357 struct tog_view *parent_view, struct got_repository *repo)
5359 const struct got_error *err;
5360 struct tog_diff_view_state *s = &view->state.diff;
5362 memset(s, 0, sizeof(*s));
5363 s->fd1 = -1;
5364 s->fd2 = -1;
5366 if (id1 != NULL && id2 != NULL) {
5367 int type1, type2;
5369 err = got_object_get_type(&type1, repo, id1);
5370 if (err)
5371 goto done;
5372 err = got_object_get_type(&type2, repo, id2);
5373 if (err)
5374 goto done;
5376 if (type1 != type2) {
5377 err = got_error(GOT_ERR_OBJ_TYPE);
5378 goto done;
5381 s->first_displayed_line = 1;
5382 s->last_displayed_line = view->nlines;
5383 s->selected_line = 1;
5384 s->repo = repo;
5385 s->id1 = id1;
5386 s->id2 = id2;
5387 s->label1 = label1;
5388 s->label2 = label2;
5390 if (id1) {
5391 s->id1 = got_object_id_dup(id1);
5392 if (s->id1 == NULL) {
5393 err = got_error_from_errno("got_object_id_dup");
5394 goto done;
5396 } else
5397 s->id1 = NULL;
5399 s->id2 = got_object_id_dup(id2);
5400 if (s->id2 == NULL) {
5401 err = got_error_from_errno("got_object_id_dup");
5402 goto done;
5405 s->f1 = got_opentemp();
5406 if (s->f1 == NULL) {
5407 err = got_error_from_errno("got_opentemp");
5408 goto done;
5411 s->f2 = got_opentemp();
5412 if (s->f2 == NULL) {
5413 err = got_error_from_errno("got_opentemp");
5414 goto done;
5417 s->fd1 = got_opentempfd();
5418 if (s->fd1 == -1) {
5419 err = got_error_from_errno("got_opentempfd");
5420 goto done;
5423 s->fd2 = got_opentempfd();
5424 if (s->fd2 == -1) {
5425 err = got_error_from_errno("got_opentempfd");
5426 goto done;
5429 s->diff_context = diff_context;
5430 s->ignore_whitespace = ignore_whitespace;
5431 s->force_text_diff = force_text_diff;
5432 s->parent_view = parent_view;
5433 s->repo = repo;
5435 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5436 int rc;
5438 rc = init_pair(GOT_DIFF_LINE_MINUS,
5439 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5440 if (rc != ERR)
5441 rc = init_pair(GOT_DIFF_LINE_PLUS,
5442 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5443 if (rc != ERR)
5444 rc = init_pair(GOT_DIFF_LINE_HUNK,
5445 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5446 if (rc != ERR)
5447 rc = init_pair(GOT_DIFF_LINE_META,
5448 get_color_value("TOG_COLOR_DIFF_META"), -1);
5449 if (rc != ERR)
5450 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5451 get_color_value("TOG_COLOR_DIFF_META"), -1);
5452 if (rc != ERR)
5453 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5454 get_color_value("TOG_COLOR_DIFF_META"), -1);
5455 if (rc != ERR)
5456 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5457 get_color_value("TOG_COLOR_DIFF_META"), -1);
5458 if (rc != ERR)
5459 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5460 get_color_value("TOG_COLOR_AUTHOR"), -1);
5461 if (rc != ERR)
5462 rc = init_pair(GOT_DIFF_LINE_DATE,
5463 get_color_value("TOG_COLOR_DATE"), -1);
5464 if (rc == ERR) {
5465 err = got_error(GOT_ERR_RANGE);
5466 goto done;
5470 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5471 view_is_splitscreen(view))
5472 show_log_view(parent_view); /* draw border */
5473 diff_view_indicate_progress(view);
5475 err = create_diff(s);
5477 view->show = show_diff_view;
5478 view->input = input_diff_view;
5479 view->reset = reset_diff_view;
5480 view->close = close_diff_view;
5481 view->search_start = search_start_diff_view;
5482 view->search_setup = search_setup_diff_view;
5483 view->search_next = search_next_view_match;
5484 done:
5485 if (err) {
5486 if (view->close == NULL)
5487 close_diff_view(view);
5488 view_close(view);
5490 return err;
5493 static const struct got_error *
5494 show_diff_view(struct tog_view *view)
5496 const struct got_error *err;
5497 struct tog_diff_view_state *s = &view->state.diff;
5498 char *id_str1 = NULL, *id_str2, *header;
5499 const char *label1, *label2;
5501 if (s->id1) {
5502 err = got_object_id_str(&id_str1, s->id1);
5503 if (err)
5504 return err;
5505 label1 = s->label1 ? s->label1 : id_str1;
5506 } else
5507 label1 = "/dev/null";
5509 err = got_object_id_str(&id_str2, s->id2);
5510 if (err)
5511 return err;
5512 label2 = s->label2 ? s->label2 : id_str2;
5514 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5515 err = got_error_from_errno("asprintf");
5516 free(id_str1);
5517 free(id_str2);
5518 return err;
5520 free(id_str1);
5521 free(id_str2);
5523 err = draw_file(view, header);
5524 free(header);
5525 return err;
5528 static const struct got_error *
5529 set_selected_commit(struct tog_diff_view_state *s,
5530 struct commit_queue_entry *entry)
5532 const struct got_error *err;
5533 const struct got_object_id_queue *parent_ids;
5534 struct got_commit_object *selected_commit;
5535 struct got_object_qid *pid;
5537 free(s->id2);
5538 s->id2 = got_object_id_dup(entry->id);
5539 if (s->id2 == NULL)
5540 return got_error_from_errno("got_object_id_dup");
5542 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5543 if (err)
5544 return err;
5545 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5546 free(s->id1);
5547 pid = STAILQ_FIRST(parent_ids);
5548 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5549 got_object_commit_close(selected_commit);
5550 return NULL;
5553 static const struct got_error *
5554 reset_diff_view(struct tog_view *view)
5556 struct tog_diff_view_state *s = &view->state.diff;
5558 view->count = 0;
5559 wclear(view->window);
5560 s->first_displayed_line = 1;
5561 s->last_displayed_line = view->nlines;
5562 s->matched_line = 0;
5563 diff_view_indicate_progress(view);
5564 return create_diff(s);
5567 static void
5568 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5570 int start, i;
5572 i = start = s->first_displayed_line - 1;
5574 while (s->lines[i].type != type) {
5575 if (i == 0)
5576 i = s->nlines - 1;
5577 if (--i == start)
5578 return; /* do nothing, requested type not in file */
5581 s->selected_line = 1;
5582 s->first_displayed_line = i;
5585 static void
5586 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5588 int start, i;
5590 i = start = s->first_displayed_line + 1;
5592 while (s->lines[i].type != type) {
5593 if (i == s->nlines - 1)
5594 i = 0;
5595 if (++i == start)
5596 return; /* do nothing, requested type not in file */
5599 s->selected_line = 1;
5600 s->first_displayed_line = i;
5603 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5604 int, int, int);
5605 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5606 int, int);
5608 static const struct got_error *
5609 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5611 const struct got_error *err = NULL;
5612 struct tog_diff_view_state *s = &view->state.diff;
5613 struct tog_log_view_state *ls;
5614 struct commit_queue_entry *old_selected_entry;
5615 char *line = NULL;
5616 size_t linesize = 0;
5617 ssize_t linelen;
5618 int i, nscroll = view->nlines - 1, up = 0;
5620 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5622 switch (ch) {
5623 case '0':
5624 case '$':
5625 case KEY_RIGHT:
5626 case 'l':
5627 case KEY_LEFT:
5628 case 'h':
5629 horizontal_scroll_input(view, ch);
5630 break;
5631 case 'a':
5632 case 'w':
5633 if (ch == 'a') {
5634 s->force_text_diff = !s->force_text_diff;
5635 view->action = s->force_text_diff ?
5636 "force ASCII text enabled" :
5637 "force ASCII text disabled";
5639 else if (ch == 'w') {
5640 s->ignore_whitespace = !s->ignore_whitespace;
5641 view->action = s->ignore_whitespace ?
5642 "ignore whitespace enabled" :
5643 "ignore whitespace disabled";
5645 err = reset_diff_view(view);
5646 break;
5647 case 'g':
5648 case KEY_HOME:
5649 s->first_displayed_line = 1;
5650 view->count = 0;
5651 break;
5652 case 'G':
5653 case KEY_END:
5654 view->count = 0;
5655 if (s->eof)
5656 break;
5658 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5659 s->eof = 1;
5660 break;
5661 case 'k':
5662 case KEY_UP:
5663 case CTRL('p'):
5664 if (s->first_displayed_line > 1)
5665 s->first_displayed_line--;
5666 else
5667 view->count = 0;
5668 break;
5669 case CTRL('u'):
5670 case 'u':
5671 nscroll /= 2;
5672 /* FALL THROUGH */
5673 case KEY_PPAGE:
5674 case CTRL('b'):
5675 case 'b':
5676 if (s->first_displayed_line == 1) {
5677 view->count = 0;
5678 break;
5680 i = 0;
5681 while (i++ < nscroll && s->first_displayed_line > 1)
5682 s->first_displayed_line--;
5683 break;
5684 case 'j':
5685 case KEY_DOWN:
5686 case CTRL('n'):
5687 if (!s->eof)
5688 s->first_displayed_line++;
5689 else
5690 view->count = 0;
5691 break;
5692 case CTRL('d'):
5693 case 'd':
5694 nscroll /= 2;
5695 /* FALL THROUGH */
5696 case KEY_NPAGE:
5697 case CTRL('f'):
5698 case 'f':
5699 case ' ':
5700 if (s->eof) {
5701 view->count = 0;
5702 break;
5704 i = 0;
5705 while (!s->eof && i++ < nscroll) {
5706 linelen = getline(&line, &linesize, s->f);
5707 s->first_displayed_line++;
5708 if (linelen == -1) {
5709 if (feof(s->f)) {
5710 s->eof = 1;
5711 } else
5712 err = got_ferror(s->f, GOT_ERR_IO);
5713 break;
5716 free(line);
5717 break;
5718 case '(':
5719 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5720 break;
5721 case ')':
5722 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5723 break;
5724 case '{':
5725 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5726 break;
5727 case '}':
5728 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5729 break;
5730 case '[':
5731 if (s->diff_context > 0) {
5732 s->diff_context--;
5733 s->matched_line = 0;
5734 diff_view_indicate_progress(view);
5735 err = create_diff(s);
5736 if (s->first_displayed_line + view->nlines - 1 >
5737 s->nlines) {
5738 s->first_displayed_line = 1;
5739 s->last_displayed_line = view->nlines;
5741 } else
5742 view->count = 0;
5743 break;
5744 case ']':
5745 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5746 s->diff_context++;
5747 s->matched_line = 0;
5748 diff_view_indicate_progress(view);
5749 err = create_diff(s);
5750 } else
5751 view->count = 0;
5752 break;
5753 case '<':
5754 case ',':
5755 case 'K':
5756 up = 1;
5757 /* FALL THROUGH */
5758 case '>':
5759 case '.':
5760 case 'J':
5761 if (s->parent_view == NULL) {
5762 view->count = 0;
5763 break;
5765 s->parent_view->count = view->count;
5767 if (s->parent_view->type == TOG_VIEW_LOG) {
5768 ls = &s->parent_view->state.log;
5769 old_selected_entry = ls->selected_entry;
5771 err = input_log_view(NULL, s->parent_view,
5772 up ? KEY_UP : KEY_DOWN);
5773 if (err)
5774 break;
5775 view->count = s->parent_view->count;
5777 if (old_selected_entry == ls->selected_entry)
5778 break;
5780 err = set_selected_commit(s, ls->selected_entry);
5781 if (err)
5782 break;
5783 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5784 struct tog_blame_view_state *bs;
5785 struct got_object_id *id, *prev_id;
5787 bs = &s->parent_view->state.blame;
5788 prev_id = get_annotation_for_line(bs->blame.lines,
5789 bs->blame.nlines, bs->last_diffed_line);
5791 err = input_blame_view(&view, s->parent_view,
5792 up ? KEY_UP : KEY_DOWN);
5793 if (err)
5794 break;
5795 view->count = s->parent_view->count;
5797 if (prev_id == NULL)
5798 break;
5799 id = get_selected_commit_id(bs->blame.lines,
5800 bs->blame.nlines, bs->first_displayed_line,
5801 bs->selected_line);
5802 if (id == NULL)
5803 break;
5805 if (!got_object_id_cmp(prev_id, id))
5806 break;
5808 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5809 if (err)
5810 break;
5812 s->first_displayed_line = 1;
5813 s->last_displayed_line = view->nlines;
5814 s->matched_line = 0;
5815 view->x = 0;
5817 diff_view_indicate_progress(view);
5818 err = create_diff(s);
5819 break;
5820 default:
5821 view->count = 0;
5822 break;
5825 return err;
5828 static const struct got_error *
5829 cmd_diff(int argc, char *argv[])
5831 const struct got_error *error;
5832 struct got_repository *repo = NULL;
5833 struct got_worktree *worktree = NULL;
5834 struct got_object_id *id1 = NULL, *id2 = NULL;
5835 char *repo_path = NULL, *cwd = NULL;
5836 char *id_str1 = NULL, *id_str2 = NULL;
5837 char *label1 = NULL, *label2 = NULL;
5838 int diff_context = 3, ignore_whitespace = 0;
5839 int ch, force_text_diff = 0;
5840 const char *errstr;
5841 struct tog_view *view;
5842 int *pack_fds = NULL;
5844 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5845 switch (ch) {
5846 case 'a':
5847 force_text_diff = 1;
5848 break;
5849 case 'C':
5850 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5851 &errstr);
5852 if (errstr != NULL)
5853 errx(1, "number of context lines is %s: %s",
5854 errstr, errstr);
5855 break;
5856 case 'r':
5857 repo_path = realpath(optarg, NULL);
5858 if (repo_path == NULL)
5859 return got_error_from_errno2("realpath",
5860 optarg);
5861 got_path_strip_trailing_slashes(repo_path);
5862 break;
5863 case 'w':
5864 ignore_whitespace = 1;
5865 break;
5866 default:
5867 usage_diff();
5868 /* NOTREACHED */
5872 argc -= optind;
5873 argv += optind;
5875 if (argc == 0) {
5876 usage_diff(); /* TODO show local worktree changes */
5877 } else if (argc == 2) {
5878 id_str1 = argv[0];
5879 id_str2 = argv[1];
5880 } else
5881 usage_diff();
5883 error = got_repo_pack_fds_open(&pack_fds);
5884 if (error)
5885 goto done;
5887 if (repo_path == NULL) {
5888 cwd = getcwd(NULL, 0);
5889 if (cwd == NULL)
5890 return got_error_from_errno("getcwd");
5891 error = got_worktree_open(&worktree, cwd);
5892 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5893 goto done;
5894 if (worktree)
5895 repo_path =
5896 strdup(got_worktree_get_repo_path(worktree));
5897 else
5898 repo_path = strdup(cwd);
5899 if (repo_path == NULL) {
5900 error = got_error_from_errno("strdup");
5901 goto done;
5905 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5906 if (error)
5907 goto done;
5909 init_curses();
5911 error = apply_unveil(got_repo_get_path(repo), NULL);
5912 if (error)
5913 goto done;
5915 error = tog_load_refs(repo, 0);
5916 if (error)
5917 goto done;
5919 error = got_repo_match_object_id(&id1, &label1, id_str1,
5920 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5921 if (error)
5922 goto done;
5924 error = got_repo_match_object_id(&id2, &label2, id_str2,
5925 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5926 if (error)
5927 goto done;
5929 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5930 if (view == NULL) {
5931 error = got_error_from_errno("view_open");
5932 goto done;
5934 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5935 ignore_whitespace, force_text_diff, NULL, repo);
5936 if (error)
5937 goto done;
5938 error = view_loop(view);
5939 done:
5940 free(label1);
5941 free(label2);
5942 free(repo_path);
5943 free(cwd);
5944 if (repo) {
5945 const struct got_error *close_err = got_repo_close(repo);
5946 if (error == NULL)
5947 error = close_err;
5949 if (worktree)
5950 got_worktree_close(worktree);
5951 if (pack_fds) {
5952 const struct got_error *pack_err =
5953 got_repo_pack_fds_close(pack_fds);
5954 if (error == NULL)
5955 error = pack_err;
5957 tog_free_refs();
5958 return error;
5961 __dead static void
5962 usage_blame(void)
5964 endwin();
5965 fprintf(stderr,
5966 "usage: %s blame [-c commit] [-r repository-path] path\n",
5967 getprogname());
5968 exit(1);
5971 struct tog_blame_line {
5972 int annotated;
5973 struct got_object_id *id;
5976 static const struct got_error *
5977 draw_blame(struct tog_view *view)
5979 struct tog_blame_view_state *s = &view->state.blame;
5980 struct tog_blame *blame = &s->blame;
5981 regmatch_t *regmatch = &view->regmatch;
5982 const struct got_error *err;
5983 int lineno = 0, nprinted = 0;
5984 char *line = NULL;
5985 size_t linesize = 0;
5986 ssize_t linelen;
5987 wchar_t *wline;
5988 int width;
5989 struct tog_blame_line *blame_line;
5990 struct got_object_id *prev_id = NULL;
5991 char *id_str;
5992 struct tog_color *tc;
5994 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5995 if (err)
5996 return err;
5998 rewind(blame->f);
5999 werase(view->window);
6001 if (asprintf(&line, "commit %s", id_str) == -1) {
6002 err = got_error_from_errno("asprintf");
6003 free(id_str);
6004 return err;
6007 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6008 free(line);
6009 line = NULL;
6010 if (err)
6011 return err;
6012 if (view_needs_focus_indication(view))
6013 wstandout(view->window);
6014 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6015 if (tc)
6016 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6017 waddwstr(view->window, wline);
6018 while (width++ < view->ncols)
6019 waddch(view->window, ' ');
6020 if (tc)
6021 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6022 if (view_needs_focus_indication(view))
6023 wstandend(view->window);
6024 free(wline);
6025 wline = NULL;
6027 if (view->gline > blame->nlines)
6028 view->gline = blame->nlines;
6030 if (tog_io.wait_for_ui) {
6031 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6032 int rc;
6034 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6035 if (rc)
6036 return got_error_set_errno(rc, "pthread_cond_wait");
6037 tog_io.wait_for_ui = 0;
6040 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6041 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6042 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6043 free(id_str);
6044 return got_error_from_errno("asprintf");
6046 free(id_str);
6047 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6048 free(line);
6049 line = NULL;
6050 if (err)
6051 return err;
6052 waddwstr(view->window, wline);
6053 free(wline);
6054 wline = NULL;
6055 if (width < view->ncols - 1)
6056 waddch(view->window, '\n');
6058 s->eof = 0;
6059 view->maxx = 0;
6060 while (nprinted < view->nlines - 2) {
6061 linelen = getline(&line, &linesize, blame->f);
6062 if (linelen == -1) {
6063 if (feof(blame->f)) {
6064 s->eof = 1;
6065 break;
6067 free(line);
6068 return got_ferror(blame->f, GOT_ERR_IO);
6070 if (++lineno < s->first_displayed_line)
6071 continue;
6072 if (view->gline && !gotoline(view, &lineno, &nprinted))
6073 continue;
6075 /* Set view->maxx based on full line length. */
6076 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6077 if (err) {
6078 free(line);
6079 return err;
6081 free(wline);
6082 wline = NULL;
6083 view->maxx = MAX(view->maxx, width);
6085 if (nprinted == s->selected_line - 1)
6086 wstandout(view->window);
6088 if (blame->nlines > 0) {
6089 blame_line = &blame->lines[lineno - 1];
6090 if (blame_line->annotated && prev_id &&
6091 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6092 !(nprinted == s->selected_line - 1)) {
6093 waddstr(view->window, " ");
6094 } else if (blame_line->annotated) {
6095 char *id_str;
6096 err = got_object_id_str(&id_str,
6097 blame_line->id);
6098 if (err) {
6099 free(line);
6100 return err;
6102 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6103 if (tc)
6104 wattr_on(view->window,
6105 COLOR_PAIR(tc->colorpair), NULL);
6106 wprintw(view->window, "%.8s", id_str);
6107 if (tc)
6108 wattr_off(view->window,
6109 COLOR_PAIR(tc->colorpair), NULL);
6110 free(id_str);
6111 prev_id = blame_line->id;
6112 } else {
6113 waddstr(view->window, "........");
6114 prev_id = NULL;
6116 } else {
6117 waddstr(view->window, "........");
6118 prev_id = NULL;
6121 if (nprinted == s->selected_line - 1)
6122 wstandend(view->window);
6123 waddstr(view->window, " ");
6125 if (view->ncols <= 9) {
6126 width = 9;
6127 } else if (s->first_displayed_line + nprinted ==
6128 s->matched_line &&
6129 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6130 err = add_matched_line(&width, line, view->ncols - 9, 9,
6131 view->window, view->x, regmatch);
6132 if (err) {
6133 free(line);
6134 return err;
6136 width += 9;
6137 } else {
6138 int skip;
6139 err = format_line(&wline, &width, &skip, line,
6140 view->x, view->ncols - 9, 9, 1);
6141 if (err) {
6142 free(line);
6143 return err;
6145 waddwstr(view->window, &wline[skip]);
6146 width += 9;
6147 free(wline);
6148 wline = NULL;
6151 if (width <= view->ncols - 1)
6152 waddch(view->window, '\n');
6153 if (++nprinted == 1)
6154 s->first_displayed_line = lineno;
6156 free(line);
6157 s->last_displayed_line = lineno;
6159 view_border(view);
6161 return NULL;
6164 static const struct got_error *
6165 blame_cb(void *arg, int nlines, int lineno,
6166 struct got_commit_object *commit, struct got_object_id *id)
6168 const struct got_error *err = NULL;
6169 struct tog_blame_cb_args *a = arg;
6170 struct tog_blame_line *line;
6171 int errcode;
6173 if (nlines != a->nlines ||
6174 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6175 return got_error(GOT_ERR_RANGE);
6177 errcode = pthread_mutex_lock(&tog_mutex);
6178 if (errcode)
6179 return got_error_set_errno(errcode, "pthread_mutex_lock");
6181 if (*a->quit) { /* user has quit the blame view */
6182 err = got_error(GOT_ERR_ITER_COMPLETED);
6183 goto done;
6186 if (lineno == -1)
6187 goto done; /* no change in this commit */
6189 line = &a->lines[lineno - 1];
6190 if (line->annotated)
6191 goto done;
6193 line->id = got_object_id_dup(id);
6194 if (line->id == NULL) {
6195 err = got_error_from_errno("got_object_id_dup");
6196 goto done;
6198 line->annotated = 1;
6199 done:
6200 errcode = pthread_mutex_unlock(&tog_mutex);
6201 if (errcode)
6202 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6203 return err;
6206 static void *
6207 blame_thread(void *arg)
6209 const struct got_error *err, *close_err;
6210 struct tog_blame_thread_args *ta = arg;
6211 struct tog_blame_cb_args *a = ta->cb_args;
6212 int errcode, fd1 = -1, fd2 = -1;
6213 FILE *f1 = NULL, *f2 = NULL;
6215 fd1 = got_opentempfd();
6216 if (fd1 == -1)
6217 return (void *)got_error_from_errno("got_opentempfd");
6219 fd2 = got_opentempfd();
6220 if (fd2 == -1) {
6221 err = got_error_from_errno("got_opentempfd");
6222 goto done;
6225 f1 = got_opentemp();
6226 if (f1 == NULL) {
6227 err = (void *)got_error_from_errno("got_opentemp");
6228 goto done;
6230 f2 = got_opentemp();
6231 if (f2 == NULL) {
6232 err = (void *)got_error_from_errno("got_opentemp");
6233 goto done;
6236 err = block_signals_used_by_main_thread();
6237 if (err)
6238 goto done;
6240 err = got_blame(ta->path, a->commit_id, ta->repo,
6241 tog_diff_algo, blame_cb, ta->cb_args,
6242 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6243 if (err && err->code == GOT_ERR_CANCELLED)
6244 err = NULL;
6246 errcode = pthread_mutex_lock(&tog_mutex);
6247 if (errcode) {
6248 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6249 goto done;
6252 close_err = got_repo_close(ta->repo);
6253 if (err == NULL)
6254 err = close_err;
6255 ta->repo = NULL;
6256 *ta->complete = 1;
6258 if (tog_io.wait_for_ui) {
6259 errcode = pthread_cond_signal(&ta->blame_complete);
6260 if (errcode && err == NULL)
6261 err = got_error_set_errno(errcode,
6262 "pthread_cond_signal");
6265 errcode = pthread_mutex_unlock(&tog_mutex);
6266 if (errcode && err == NULL)
6267 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6269 done:
6270 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6271 err = got_error_from_errno("close");
6272 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6273 err = got_error_from_errno("close");
6274 if (f1 && fclose(f1) == EOF && err == NULL)
6275 err = got_error_from_errno("fclose");
6276 if (f2 && fclose(f2) == EOF && err == NULL)
6277 err = got_error_from_errno("fclose");
6279 return (void *)err;
6282 static struct got_object_id *
6283 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6284 int first_displayed_line, int selected_line)
6286 struct tog_blame_line *line;
6288 if (nlines <= 0)
6289 return NULL;
6291 line = &lines[first_displayed_line - 1 + selected_line - 1];
6292 if (!line->annotated)
6293 return NULL;
6295 return line->id;
6298 static struct got_object_id *
6299 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6300 int lineno)
6302 struct tog_blame_line *line;
6304 if (nlines <= 0 || lineno >= nlines)
6305 return NULL;
6307 line = &lines[lineno - 1];
6308 if (!line->annotated)
6309 return NULL;
6311 return line->id;
6314 static const struct got_error *
6315 stop_blame(struct tog_blame *blame)
6317 const struct got_error *err = NULL;
6318 int i;
6320 if (blame->thread) {
6321 int errcode;
6322 errcode = pthread_mutex_unlock(&tog_mutex);
6323 if (errcode)
6324 return got_error_set_errno(errcode,
6325 "pthread_mutex_unlock");
6326 errcode = pthread_join(blame->thread, (void **)&err);
6327 if (errcode)
6328 return got_error_set_errno(errcode, "pthread_join");
6329 errcode = pthread_mutex_lock(&tog_mutex);
6330 if (errcode)
6331 return got_error_set_errno(errcode,
6332 "pthread_mutex_lock");
6333 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6334 err = NULL;
6335 blame->thread = 0; //NULL;
6337 if (blame->thread_args.repo) {
6338 const struct got_error *close_err;
6339 close_err = got_repo_close(blame->thread_args.repo);
6340 if (err == NULL)
6341 err = close_err;
6342 blame->thread_args.repo = NULL;
6344 if (blame->f) {
6345 if (fclose(blame->f) == EOF && err == NULL)
6346 err = got_error_from_errno("fclose");
6347 blame->f = NULL;
6349 if (blame->lines) {
6350 for (i = 0; i < blame->nlines; i++)
6351 free(blame->lines[i].id);
6352 free(blame->lines);
6353 blame->lines = NULL;
6355 free(blame->cb_args.commit_id);
6356 blame->cb_args.commit_id = NULL;
6357 if (blame->pack_fds) {
6358 const struct got_error *pack_err =
6359 got_repo_pack_fds_close(blame->pack_fds);
6360 if (err == NULL)
6361 err = pack_err;
6362 blame->pack_fds = NULL;
6364 return err;
6367 static const struct got_error *
6368 cancel_blame_view(void *arg)
6370 const struct got_error *err = NULL;
6371 int *done = arg;
6372 int errcode;
6374 errcode = pthread_mutex_lock(&tog_mutex);
6375 if (errcode)
6376 return got_error_set_errno(errcode,
6377 "pthread_mutex_unlock");
6379 if (*done)
6380 err = got_error(GOT_ERR_CANCELLED);
6382 errcode = pthread_mutex_unlock(&tog_mutex);
6383 if (errcode)
6384 return got_error_set_errno(errcode,
6385 "pthread_mutex_lock");
6387 return err;
6390 static const struct got_error *
6391 run_blame(struct tog_view *view)
6393 struct tog_blame_view_state *s = &view->state.blame;
6394 struct tog_blame *blame = &s->blame;
6395 const struct got_error *err = NULL;
6396 struct got_commit_object *commit = NULL;
6397 struct got_blob_object *blob = NULL;
6398 struct got_repository *thread_repo = NULL;
6399 struct got_object_id *obj_id = NULL;
6400 int obj_type, fd = -1;
6401 int *pack_fds = NULL;
6403 err = got_object_open_as_commit(&commit, s->repo,
6404 &s->blamed_commit->id);
6405 if (err)
6406 return err;
6408 fd = got_opentempfd();
6409 if (fd == -1) {
6410 err = got_error_from_errno("got_opentempfd");
6411 goto done;
6414 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6415 if (err)
6416 goto done;
6418 err = got_object_get_type(&obj_type, s->repo, obj_id);
6419 if (err)
6420 goto done;
6422 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6423 err = got_error(GOT_ERR_OBJ_TYPE);
6424 goto done;
6427 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6428 if (err)
6429 goto done;
6430 blame->f = got_opentemp();
6431 if (blame->f == NULL) {
6432 err = got_error_from_errno("got_opentemp");
6433 goto done;
6435 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6436 &blame->line_offsets, blame->f, blob);
6437 if (err)
6438 goto done;
6439 if (blame->nlines == 0) {
6440 s->blame_complete = 1;
6441 goto done;
6444 /* Don't include \n at EOF in the blame line count. */
6445 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6446 blame->nlines--;
6448 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6449 if (blame->lines == NULL) {
6450 err = got_error_from_errno("calloc");
6451 goto done;
6454 err = got_repo_pack_fds_open(&pack_fds);
6455 if (err)
6456 goto done;
6457 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6458 pack_fds);
6459 if (err)
6460 goto done;
6462 blame->pack_fds = pack_fds;
6463 blame->cb_args.view = view;
6464 blame->cb_args.lines = blame->lines;
6465 blame->cb_args.nlines = blame->nlines;
6466 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6467 if (blame->cb_args.commit_id == NULL) {
6468 err = got_error_from_errno("got_object_id_dup");
6469 goto done;
6471 blame->cb_args.quit = &s->done;
6473 blame->thread_args.path = s->path;
6474 blame->thread_args.repo = thread_repo;
6475 blame->thread_args.cb_args = &blame->cb_args;
6476 blame->thread_args.complete = &s->blame_complete;
6477 blame->thread_args.cancel_cb = cancel_blame_view;
6478 blame->thread_args.cancel_arg = &s->done;
6479 s->blame_complete = 0;
6481 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6482 s->first_displayed_line = 1;
6483 s->last_displayed_line = view->nlines;
6484 s->selected_line = 1;
6486 s->matched_line = 0;
6488 done:
6489 if (commit)
6490 got_object_commit_close(commit);
6491 if (fd != -1 && close(fd) == -1 && err == NULL)
6492 err = got_error_from_errno("close");
6493 if (blob)
6494 got_object_blob_close(blob);
6495 free(obj_id);
6496 if (err)
6497 stop_blame(blame);
6498 return err;
6501 static const struct got_error *
6502 open_blame_view(struct tog_view *view, char *path,
6503 struct got_object_id *commit_id, struct got_repository *repo)
6505 const struct got_error *err = NULL;
6506 struct tog_blame_view_state *s = &view->state.blame;
6508 STAILQ_INIT(&s->blamed_commits);
6510 s->path = strdup(path);
6511 if (s->path == NULL)
6512 return got_error_from_errno("strdup");
6514 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6515 if (err) {
6516 free(s->path);
6517 return err;
6520 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6521 s->first_displayed_line = 1;
6522 s->last_displayed_line = view->nlines;
6523 s->selected_line = 1;
6524 s->blame_complete = 0;
6525 s->repo = repo;
6526 s->commit_id = commit_id;
6527 memset(&s->blame, 0, sizeof(s->blame));
6529 STAILQ_INIT(&s->colors);
6530 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6531 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6532 get_color_value("TOG_COLOR_COMMIT"));
6533 if (err)
6534 return err;
6537 view->show = show_blame_view;
6538 view->input = input_blame_view;
6539 view->reset = reset_blame_view;
6540 view->close = close_blame_view;
6541 view->search_start = search_start_blame_view;
6542 view->search_setup = search_setup_blame_view;
6543 view->search_next = search_next_view_match;
6545 if (using_mock_io) {
6546 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6547 int rc;
6549 rc = pthread_cond_init(&bta->blame_complete, NULL);
6550 if (rc)
6551 return got_error_set_errno(rc, "pthread_cond_init");
6554 return run_blame(view);
6557 static const struct got_error *
6558 close_blame_view(struct tog_view *view)
6560 const struct got_error *err = NULL;
6561 struct tog_blame_view_state *s = &view->state.blame;
6563 if (s->blame.thread)
6564 err = stop_blame(&s->blame);
6566 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6567 struct got_object_qid *blamed_commit;
6568 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6569 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6570 got_object_qid_free(blamed_commit);
6573 if (using_mock_io) {
6574 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6575 int rc;
6577 rc = pthread_cond_destroy(&bta->blame_complete);
6578 if (rc && err == NULL)
6579 err = got_error_set_errno(rc, "pthread_cond_destroy");
6582 free(s->path);
6583 free_colors(&s->colors);
6584 return err;
6587 static const struct got_error *
6588 search_start_blame_view(struct tog_view *view)
6590 struct tog_blame_view_state *s = &view->state.blame;
6592 s->matched_line = 0;
6593 return NULL;
6596 static void
6597 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6598 size_t *nlines, int **first, int **last, int **match, int **selected)
6600 struct tog_blame_view_state *s = &view->state.blame;
6602 *f = s->blame.f;
6603 *nlines = s->blame.nlines;
6604 *line_offsets = s->blame.line_offsets;
6605 *match = &s->matched_line;
6606 *first = &s->first_displayed_line;
6607 *last = &s->last_displayed_line;
6608 *selected = &s->selected_line;
6611 static const struct got_error *
6612 show_blame_view(struct tog_view *view)
6614 const struct got_error *err = NULL;
6615 struct tog_blame_view_state *s = &view->state.blame;
6616 int errcode;
6618 if (s->blame.thread == 0 && !s->blame_complete) {
6619 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6620 &s->blame.thread_args);
6621 if (errcode)
6622 return got_error_set_errno(errcode, "pthread_create");
6624 if (!using_mock_io)
6625 halfdelay(1); /* fast refresh while annotating */
6628 if (s->blame_complete && !using_mock_io)
6629 halfdelay(10); /* disable fast refresh */
6631 err = draw_blame(view);
6633 view_border(view);
6634 return err;
6637 static const struct got_error *
6638 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6639 struct got_repository *repo, struct got_object_id *id)
6641 struct tog_view *log_view;
6642 const struct got_error *err = NULL;
6644 *new_view = NULL;
6646 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6647 if (log_view == NULL)
6648 return got_error_from_errno("view_open");
6650 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6651 if (err)
6652 view_close(log_view);
6653 else
6654 *new_view = log_view;
6656 return err;
6659 static const struct got_error *
6660 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6662 const struct got_error *err = NULL, *thread_err = NULL;
6663 struct tog_view *diff_view;
6664 struct tog_blame_view_state *s = &view->state.blame;
6665 int eos, nscroll, begin_y = 0, begin_x = 0;
6667 eos = nscroll = view->nlines - 2;
6668 if (view_is_hsplit_top(view))
6669 --eos; /* border */
6671 switch (ch) {
6672 case '0':
6673 case '$':
6674 case KEY_RIGHT:
6675 case 'l':
6676 case KEY_LEFT:
6677 case 'h':
6678 horizontal_scroll_input(view, ch);
6679 break;
6680 case 'q':
6681 s->done = 1;
6682 break;
6683 case 'g':
6684 case KEY_HOME:
6685 s->selected_line = 1;
6686 s->first_displayed_line = 1;
6687 view->count = 0;
6688 break;
6689 case 'G':
6690 case KEY_END:
6691 if (s->blame.nlines < eos) {
6692 s->selected_line = s->blame.nlines;
6693 s->first_displayed_line = 1;
6694 } else {
6695 s->selected_line = eos;
6696 s->first_displayed_line = s->blame.nlines - (eos - 1);
6698 view->count = 0;
6699 break;
6700 case 'k':
6701 case KEY_UP:
6702 case CTRL('p'):
6703 if (s->selected_line > 1)
6704 s->selected_line--;
6705 else if (s->selected_line == 1 &&
6706 s->first_displayed_line > 1)
6707 s->first_displayed_line--;
6708 else
6709 view->count = 0;
6710 break;
6711 case CTRL('u'):
6712 case 'u':
6713 nscroll /= 2;
6714 /* FALL THROUGH */
6715 case KEY_PPAGE:
6716 case CTRL('b'):
6717 case 'b':
6718 if (s->first_displayed_line == 1) {
6719 if (view->count > 1)
6720 nscroll += nscroll;
6721 s->selected_line = MAX(1, s->selected_line - nscroll);
6722 view->count = 0;
6723 break;
6725 if (s->first_displayed_line > nscroll)
6726 s->first_displayed_line -= nscroll;
6727 else
6728 s->first_displayed_line = 1;
6729 break;
6730 case 'j':
6731 case KEY_DOWN:
6732 case CTRL('n'):
6733 if (s->selected_line < eos && s->first_displayed_line +
6734 s->selected_line <= s->blame.nlines)
6735 s->selected_line++;
6736 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6737 s->first_displayed_line++;
6738 else
6739 view->count = 0;
6740 break;
6741 case 'c':
6742 case 'p': {
6743 struct got_object_id *id = NULL;
6745 view->count = 0;
6746 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6747 s->first_displayed_line, s->selected_line);
6748 if (id == NULL)
6749 break;
6750 if (ch == 'p') {
6751 struct got_commit_object *commit, *pcommit;
6752 struct got_object_qid *pid;
6753 struct got_object_id *blob_id = NULL;
6754 int obj_type;
6755 err = got_object_open_as_commit(&commit,
6756 s->repo, id);
6757 if (err)
6758 break;
6759 pid = STAILQ_FIRST(
6760 got_object_commit_get_parent_ids(commit));
6761 if (pid == NULL) {
6762 got_object_commit_close(commit);
6763 break;
6765 /* Check if path history ends here. */
6766 err = got_object_open_as_commit(&pcommit,
6767 s->repo, &pid->id);
6768 if (err)
6769 break;
6770 err = got_object_id_by_path(&blob_id, s->repo,
6771 pcommit, s->path);
6772 got_object_commit_close(pcommit);
6773 if (err) {
6774 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6775 err = NULL;
6776 got_object_commit_close(commit);
6777 break;
6779 err = got_object_get_type(&obj_type, s->repo,
6780 blob_id);
6781 free(blob_id);
6782 /* Can't blame non-blob type objects. */
6783 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6784 got_object_commit_close(commit);
6785 break;
6787 err = got_object_qid_alloc(&s->blamed_commit,
6788 &pid->id);
6789 got_object_commit_close(commit);
6790 } else {
6791 if (got_object_id_cmp(id,
6792 &s->blamed_commit->id) == 0)
6793 break;
6794 err = got_object_qid_alloc(&s->blamed_commit,
6795 id);
6797 if (err)
6798 break;
6799 s->done = 1;
6800 thread_err = stop_blame(&s->blame);
6801 s->done = 0;
6802 if (thread_err)
6803 break;
6804 STAILQ_INSERT_HEAD(&s->blamed_commits,
6805 s->blamed_commit, entry);
6806 err = run_blame(view);
6807 if (err)
6808 break;
6809 break;
6811 case 'C': {
6812 struct got_object_qid *first;
6814 view->count = 0;
6815 first = STAILQ_FIRST(&s->blamed_commits);
6816 if (!got_object_id_cmp(&first->id, s->commit_id))
6817 break;
6818 s->done = 1;
6819 thread_err = stop_blame(&s->blame);
6820 s->done = 0;
6821 if (thread_err)
6822 break;
6823 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6824 got_object_qid_free(s->blamed_commit);
6825 s->blamed_commit =
6826 STAILQ_FIRST(&s->blamed_commits);
6827 err = run_blame(view);
6828 if (err)
6829 break;
6830 break;
6832 case 'L':
6833 view->count = 0;
6834 s->id_to_log = get_selected_commit_id(s->blame.lines,
6835 s->blame.nlines, s->first_displayed_line, s->selected_line);
6836 if (s->id_to_log)
6837 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6838 break;
6839 case KEY_ENTER:
6840 case '\r': {
6841 struct got_object_id *id = NULL;
6842 struct got_object_qid *pid;
6843 struct got_commit_object *commit = NULL;
6845 view->count = 0;
6846 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6847 s->first_displayed_line, s->selected_line);
6848 if (id == NULL)
6849 break;
6850 err = got_object_open_as_commit(&commit, s->repo, id);
6851 if (err)
6852 break;
6853 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6854 if (*new_view) {
6855 /* traversed from diff view, release diff resources */
6856 err = close_diff_view(*new_view);
6857 if (err)
6858 break;
6859 diff_view = *new_view;
6860 } else {
6861 if (view_is_parent_view(view))
6862 view_get_split(view, &begin_y, &begin_x);
6864 diff_view = view_open(0, 0, begin_y, begin_x,
6865 TOG_VIEW_DIFF);
6866 if (diff_view == NULL) {
6867 got_object_commit_close(commit);
6868 err = got_error_from_errno("view_open");
6869 break;
6872 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6873 id, NULL, NULL, 3, 0, 0, view, s->repo);
6874 got_object_commit_close(commit);
6875 if (err) {
6876 view_close(diff_view);
6877 break;
6879 s->last_diffed_line = s->first_displayed_line - 1 +
6880 s->selected_line;
6881 if (*new_view)
6882 break; /* still open from active diff view */
6883 if (view_is_parent_view(view) &&
6884 view->mode == TOG_VIEW_SPLIT_HRZN) {
6885 err = view_init_hsplit(view, begin_y);
6886 if (err)
6887 break;
6890 view->focussed = 0;
6891 diff_view->focussed = 1;
6892 diff_view->mode = view->mode;
6893 diff_view->nlines = view->lines - begin_y;
6894 if (view_is_parent_view(view)) {
6895 view_transfer_size(diff_view, view);
6896 err = view_close_child(view);
6897 if (err)
6898 break;
6899 err = view_set_child(view, diff_view);
6900 if (err)
6901 break;
6902 view->focus_child = 1;
6903 } else
6904 *new_view = diff_view;
6905 if (err)
6906 break;
6907 break;
6909 case CTRL('d'):
6910 case 'd':
6911 nscroll /= 2;
6912 /* FALL THROUGH */
6913 case KEY_NPAGE:
6914 case CTRL('f'):
6915 case 'f':
6916 case ' ':
6917 if (s->last_displayed_line >= s->blame.nlines &&
6918 s->selected_line >= MIN(s->blame.nlines,
6919 view->nlines - 2)) {
6920 view->count = 0;
6921 break;
6923 if (s->last_displayed_line >= s->blame.nlines &&
6924 s->selected_line < view->nlines - 2) {
6925 s->selected_line +=
6926 MIN(nscroll, s->last_displayed_line -
6927 s->first_displayed_line - s->selected_line + 1);
6929 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6930 s->first_displayed_line += nscroll;
6931 else
6932 s->first_displayed_line =
6933 s->blame.nlines - (view->nlines - 3);
6934 break;
6935 case KEY_RESIZE:
6936 if (s->selected_line > view->nlines - 2) {
6937 s->selected_line = MIN(s->blame.nlines,
6938 view->nlines - 2);
6940 break;
6941 default:
6942 view->count = 0;
6943 break;
6945 return thread_err ? thread_err : err;
6948 static const struct got_error *
6949 reset_blame_view(struct tog_view *view)
6951 const struct got_error *err;
6952 struct tog_blame_view_state *s = &view->state.blame;
6954 view->count = 0;
6955 s->done = 1;
6956 err = stop_blame(&s->blame);
6957 s->done = 0;
6958 if (err)
6959 return err;
6960 return run_blame(view);
6963 static const struct got_error *
6964 cmd_blame(int argc, char *argv[])
6966 const struct got_error *error;
6967 struct got_repository *repo = NULL;
6968 struct got_worktree *worktree = NULL;
6969 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6970 char *link_target = NULL;
6971 struct got_object_id *commit_id = NULL;
6972 struct got_commit_object *commit = NULL;
6973 char *commit_id_str = NULL;
6974 int ch;
6975 struct tog_view *view = NULL;
6976 int *pack_fds = NULL;
6978 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6979 switch (ch) {
6980 case 'c':
6981 commit_id_str = optarg;
6982 break;
6983 case 'r':
6984 repo_path = realpath(optarg, NULL);
6985 if (repo_path == NULL)
6986 return got_error_from_errno2("realpath",
6987 optarg);
6988 break;
6989 default:
6990 usage_blame();
6991 /* NOTREACHED */
6995 argc -= optind;
6996 argv += optind;
6998 if (argc != 1)
6999 usage_blame();
7001 error = got_repo_pack_fds_open(&pack_fds);
7002 if (error != NULL)
7003 goto done;
7005 if (repo_path == NULL) {
7006 cwd = getcwd(NULL, 0);
7007 if (cwd == NULL)
7008 return got_error_from_errno("getcwd");
7009 error = got_worktree_open(&worktree, cwd);
7010 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7011 goto done;
7012 if (worktree)
7013 repo_path =
7014 strdup(got_worktree_get_repo_path(worktree));
7015 else
7016 repo_path = strdup(cwd);
7017 if (repo_path == NULL) {
7018 error = got_error_from_errno("strdup");
7019 goto done;
7023 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7024 if (error != NULL)
7025 goto done;
7027 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7028 worktree);
7029 if (error)
7030 goto done;
7032 init_curses();
7034 error = apply_unveil(got_repo_get_path(repo), NULL);
7035 if (error)
7036 goto done;
7038 error = tog_load_refs(repo, 0);
7039 if (error)
7040 goto done;
7042 if (commit_id_str == NULL) {
7043 struct got_reference *head_ref;
7044 error = got_ref_open(&head_ref, repo, worktree ?
7045 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7046 if (error != NULL)
7047 goto done;
7048 error = got_ref_resolve(&commit_id, repo, head_ref);
7049 got_ref_close(head_ref);
7050 } else {
7051 error = got_repo_match_object_id(&commit_id, NULL,
7052 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7054 if (error != NULL)
7055 goto done;
7057 error = got_object_open_as_commit(&commit, repo, commit_id);
7058 if (error)
7059 goto done;
7061 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7062 commit, repo);
7063 if (error)
7064 goto done;
7066 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7067 if (view == NULL) {
7068 error = got_error_from_errno("view_open");
7069 goto done;
7071 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7072 commit_id, repo);
7073 if (error != NULL) {
7074 if (view->close == NULL)
7075 close_blame_view(view);
7076 view_close(view);
7077 goto done;
7079 if (worktree) {
7080 /* Release work tree lock. */
7081 got_worktree_close(worktree);
7082 worktree = NULL;
7084 error = view_loop(view);
7085 done:
7086 free(repo_path);
7087 free(in_repo_path);
7088 free(link_target);
7089 free(cwd);
7090 free(commit_id);
7091 if (commit)
7092 got_object_commit_close(commit);
7093 if (worktree)
7094 got_worktree_close(worktree);
7095 if (repo) {
7096 const struct got_error *close_err = got_repo_close(repo);
7097 if (error == NULL)
7098 error = close_err;
7100 if (pack_fds) {
7101 const struct got_error *pack_err =
7102 got_repo_pack_fds_close(pack_fds);
7103 if (error == NULL)
7104 error = pack_err;
7106 tog_free_refs();
7107 return error;
7110 static const struct got_error *
7111 draw_tree_entries(struct tog_view *view, const char *parent_path)
7113 struct tog_tree_view_state *s = &view->state.tree;
7114 const struct got_error *err = NULL;
7115 struct got_tree_entry *te;
7116 wchar_t *wline;
7117 char *index = NULL;
7118 struct tog_color *tc;
7119 int width, n, nentries, scrollx, i = 1;
7120 int limit = view->nlines;
7122 s->ndisplayed = 0;
7123 if (view_is_hsplit_top(view))
7124 --limit; /* border */
7126 werase(view->window);
7128 if (limit == 0)
7129 return NULL;
7131 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7132 0, 0);
7133 if (err)
7134 return err;
7135 if (view_needs_focus_indication(view))
7136 wstandout(view->window);
7137 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7138 if (tc)
7139 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7140 waddwstr(view->window, wline);
7141 free(wline);
7142 wline = NULL;
7143 while (width++ < view->ncols)
7144 waddch(view->window, ' ');
7145 if (tc)
7146 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7147 if (view_needs_focus_indication(view))
7148 wstandend(view->window);
7149 if (--limit <= 0)
7150 return NULL;
7152 i += s->selected;
7153 if (s->first_displayed_entry) {
7154 i += got_tree_entry_get_index(s->first_displayed_entry);
7155 if (s->tree != s->root)
7156 ++i; /* account for ".." entry */
7158 nentries = got_object_tree_get_nentries(s->tree);
7159 if (asprintf(&index, "[%d/%d] %s",
7160 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7161 return got_error_from_errno("asprintf");
7162 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7163 free(index);
7164 if (err)
7165 return err;
7166 waddwstr(view->window, wline);
7167 free(wline);
7168 wline = NULL;
7169 if (width < view->ncols - 1)
7170 waddch(view->window, '\n');
7171 if (--limit <= 0)
7172 return NULL;
7173 waddch(view->window, '\n');
7174 if (--limit <= 0)
7175 return NULL;
7177 if (s->first_displayed_entry == NULL) {
7178 te = got_object_tree_get_first_entry(s->tree);
7179 if (s->selected == 0) {
7180 if (view->focussed)
7181 wstandout(view->window);
7182 s->selected_entry = NULL;
7184 waddstr(view->window, " ..\n"); /* parent directory */
7185 if (s->selected == 0 && view->focussed)
7186 wstandend(view->window);
7187 s->ndisplayed++;
7188 if (--limit <= 0)
7189 return NULL;
7190 n = 1;
7191 } else {
7192 n = 0;
7193 te = s->first_displayed_entry;
7196 view->maxx = 0;
7197 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7198 char *line = NULL, *id_str = NULL, *link_target = NULL;
7199 const char *modestr = "";
7200 mode_t mode;
7202 te = got_object_tree_get_entry(s->tree, i);
7203 mode = got_tree_entry_get_mode(te);
7205 if (s->show_ids) {
7206 err = got_object_id_str(&id_str,
7207 got_tree_entry_get_id(te));
7208 if (err)
7209 return got_error_from_errno(
7210 "got_object_id_str");
7212 if (got_object_tree_entry_is_submodule(te))
7213 modestr = "$";
7214 else if (S_ISLNK(mode)) {
7215 int i;
7217 err = got_tree_entry_get_symlink_target(&link_target,
7218 te, s->repo);
7219 if (err) {
7220 free(id_str);
7221 return err;
7223 for (i = 0; i < strlen(link_target); i++) {
7224 if (!isprint((unsigned char)link_target[i]))
7225 link_target[i] = '?';
7227 modestr = "@";
7229 else if (S_ISDIR(mode))
7230 modestr = "/";
7231 else if (mode & S_IXUSR)
7232 modestr = "*";
7233 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7234 got_tree_entry_get_name(te), modestr,
7235 link_target ? " -> ": "",
7236 link_target ? link_target : "") == -1) {
7237 free(id_str);
7238 free(link_target);
7239 return got_error_from_errno("asprintf");
7241 free(id_str);
7242 free(link_target);
7244 /* use full line width to determine view->maxx */
7245 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7246 if (err) {
7247 free(line);
7248 break;
7250 view->maxx = MAX(view->maxx, width);
7251 free(wline);
7252 wline = NULL;
7254 err = format_line(&wline, &width, &scrollx, line, view->x,
7255 view->ncols, 0, 0);
7256 if (err) {
7257 free(line);
7258 break;
7260 if (n == s->selected) {
7261 if (view->focussed)
7262 wstandout(view->window);
7263 s->selected_entry = te;
7265 tc = match_color(&s->colors, line);
7266 if (tc)
7267 wattr_on(view->window,
7268 COLOR_PAIR(tc->colorpair), NULL);
7269 waddwstr(view->window, &wline[scrollx]);
7270 if (tc)
7271 wattr_off(view->window,
7272 COLOR_PAIR(tc->colorpair), NULL);
7273 if (width < view->ncols)
7274 waddch(view->window, '\n');
7275 if (n == s->selected && view->focussed)
7276 wstandend(view->window);
7277 free(line);
7278 free(wline);
7279 wline = NULL;
7280 n++;
7281 s->ndisplayed++;
7282 s->last_displayed_entry = te;
7283 if (--limit <= 0)
7284 break;
7287 return err;
7290 static void
7291 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7293 struct got_tree_entry *te;
7294 int isroot = s->tree == s->root;
7295 int i = 0;
7297 if (s->first_displayed_entry == NULL)
7298 return;
7300 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7301 while (i++ < maxscroll) {
7302 if (te == NULL) {
7303 if (!isroot)
7304 s->first_displayed_entry = NULL;
7305 break;
7307 s->first_displayed_entry = te;
7308 te = got_tree_entry_get_prev(s->tree, te);
7312 static const struct got_error *
7313 tree_scroll_down(struct tog_view *view, int maxscroll)
7315 struct tog_tree_view_state *s = &view->state.tree;
7316 struct got_tree_entry *next, *last;
7317 int n = 0;
7319 if (s->first_displayed_entry)
7320 next = got_tree_entry_get_next(s->tree,
7321 s->first_displayed_entry);
7322 else
7323 next = got_object_tree_get_first_entry(s->tree);
7325 last = s->last_displayed_entry;
7326 while (next && n++ < maxscroll) {
7327 if (last) {
7328 s->last_displayed_entry = last;
7329 last = got_tree_entry_get_next(s->tree, last);
7331 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7332 s->first_displayed_entry = next;
7333 next = got_tree_entry_get_next(s->tree, next);
7337 return NULL;
7340 static const struct got_error *
7341 tree_entry_path(char **path, struct tog_parent_trees *parents,
7342 struct got_tree_entry *te)
7344 const struct got_error *err = NULL;
7345 struct tog_parent_tree *pt;
7346 size_t len = 2; /* for leading slash and NUL */
7348 TAILQ_FOREACH(pt, parents, entry)
7349 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7350 + 1 /* slash */;
7351 if (te)
7352 len += strlen(got_tree_entry_get_name(te));
7354 *path = calloc(1, len);
7355 if (path == NULL)
7356 return got_error_from_errno("calloc");
7358 (*path)[0] = '/';
7359 pt = TAILQ_LAST(parents, tog_parent_trees);
7360 while (pt) {
7361 const char *name = got_tree_entry_get_name(pt->selected_entry);
7362 if (strlcat(*path, name, len) >= len) {
7363 err = got_error(GOT_ERR_NO_SPACE);
7364 goto done;
7366 if (strlcat(*path, "/", len) >= len) {
7367 err = got_error(GOT_ERR_NO_SPACE);
7368 goto done;
7370 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7372 if (te) {
7373 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7374 err = got_error(GOT_ERR_NO_SPACE);
7375 goto done;
7378 done:
7379 if (err) {
7380 free(*path);
7381 *path = NULL;
7383 return err;
7386 static const struct got_error *
7387 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7388 struct got_tree_entry *te, struct tog_parent_trees *parents,
7389 struct got_object_id *commit_id, struct got_repository *repo)
7391 const struct got_error *err = NULL;
7392 char *path;
7393 struct tog_view *blame_view;
7395 *new_view = NULL;
7397 err = tree_entry_path(&path, parents, te);
7398 if (err)
7399 return err;
7401 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7402 if (blame_view == NULL) {
7403 err = got_error_from_errno("view_open");
7404 goto done;
7407 err = open_blame_view(blame_view, path, commit_id, repo);
7408 if (err) {
7409 if (err->code == GOT_ERR_CANCELLED)
7410 err = NULL;
7411 view_close(blame_view);
7412 } else
7413 *new_view = blame_view;
7414 done:
7415 free(path);
7416 return err;
7419 static const struct got_error *
7420 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7421 struct tog_tree_view_state *s)
7423 struct tog_view *log_view;
7424 const struct got_error *err = NULL;
7425 char *path;
7427 *new_view = NULL;
7429 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7430 if (log_view == NULL)
7431 return got_error_from_errno("view_open");
7433 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7434 if (err)
7435 return err;
7437 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7438 path, 0);
7439 if (err)
7440 view_close(log_view);
7441 else
7442 *new_view = log_view;
7443 free(path);
7444 return err;
7447 static const struct got_error *
7448 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7449 const char *head_ref_name, struct got_repository *repo)
7451 const struct got_error *err = NULL;
7452 char *commit_id_str = NULL;
7453 struct tog_tree_view_state *s = &view->state.tree;
7454 struct got_commit_object *commit = NULL;
7456 TAILQ_INIT(&s->parents);
7457 STAILQ_INIT(&s->colors);
7459 s->commit_id = got_object_id_dup(commit_id);
7460 if (s->commit_id == NULL) {
7461 err = got_error_from_errno("got_object_id_dup");
7462 goto done;
7465 err = got_object_open_as_commit(&commit, repo, commit_id);
7466 if (err)
7467 goto done;
7470 * The root is opened here and will be closed when the view is closed.
7471 * Any visited subtrees and their path-wise parents are opened and
7472 * closed on demand.
7474 err = got_object_open_as_tree(&s->root, repo,
7475 got_object_commit_get_tree_id(commit));
7476 if (err)
7477 goto done;
7478 s->tree = s->root;
7480 err = got_object_id_str(&commit_id_str, commit_id);
7481 if (err != NULL)
7482 goto done;
7484 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7485 err = got_error_from_errno("asprintf");
7486 goto done;
7489 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7490 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7491 if (head_ref_name) {
7492 s->head_ref_name = strdup(head_ref_name);
7493 if (s->head_ref_name == NULL) {
7494 err = got_error_from_errno("strdup");
7495 goto done;
7498 s->repo = repo;
7500 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7501 err = add_color(&s->colors, "\\$$",
7502 TOG_COLOR_TREE_SUBMODULE,
7503 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7504 if (err)
7505 goto done;
7506 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7507 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7508 if (err)
7509 goto done;
7510 err = add_color(&s->colors, "/$",
7511 TOG_COLOR_TREE_DIRECTORY,
7512 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7513 if (err)
7514 goto done;
7516 err = add_color(&s->colors, "\\*$",
7517 TOG_COLOR_TREE_EXECUTABLE,
7518 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7519 if (err)
7520 goto done;
7522 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7523 get_color_value("TOG_COLOR_COMMIT"));
7524 if (err)
7525 goto done;
7528 view->show = show_tree_view;
7529 view->input = input_tree_view;
7530 view->close = close_tree_view;
7531 view->search_start = search_start_tree_view;
7532 view->search_next = search_next_tree_view;
7533 done:
7534 free(commit_id_str);
7535 if (commit)
7536 got_object_commit_close(commit);
7537 if (err) {
7538 if (view->close == NULL)
7539 close_tree_view(view);
7540 view_close(view);
7542 return err;
7545 static const struct got_error *
7546 close_tree_view(struct tog_view *view)
7548 struct tog_tree_view_state *s = &view->state.tree;
7550 free_colors(&s->colors);
7551 free(s->tree_label);
7552 s->tree_label = NULL;
7553 free(s->commit_id);
7554 s->commit_id = NULL;
7555 free(s->head_ref_name);
7556 s->head_ref_name = NULL;
7557 while (!TAILQ_EMPTY(&s->parents)) {
7558 struct tog_parent_tree *parent;
7559 parent = TAILQ_FIRST(&s->parents);
7560 TAILQ_REMOVE(&s->parents, parent, entry);
7561 if (parent->tree != s->root)
7562 got_object_tree_close(parent->tree);
7563 free(parent);
7566 if (s->tree != NULL && s->tree != s->root)
7567 got_object_tree_close(s->tree);
7568 if (s->root)
7569 got_object_tree_close(s->root);
7570 return NULL;
7573 static const struct got_error *
7574 search_start_tree_view(struct tog_view *view)
7576 struct tog_tree_view_state *s = &view->state.tree;
7578 s->matched_entry = NULL;
7579 return NULL;
7582 static int
7583 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7585 regmatch_t regmatch;
7587 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7588 0) == 0;
7591 static const struct got_error *
7592 search_next_tree_view(struct tog_view *view)
7594 struct tog_tree_view_state *s = &view->state.tree;
7595 struct got_tree_entry *te = NULL;
7597 if (!view->searching) {
7598 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7599 return NULL;
7602 if (s->matched_entry) {
7603 if (view->searching == TOG_SEARCH_FORWARD) {
7604 if (s->selected_entry)
7605 te = got_tree_entry_get_next(s->tree,
7606 s->selected_entry);
7607 else
7608 te = got_object_tree_get_first_entry(s->tree);
7609 } else {
7610 if (s->selected_entry == NULL)
7611 te = got_object_tree_get_last_entry(s->tree);
7612 else
7613 te = got_tree_entry_get_prev(s->tree,
7614 s->selected_entry);
7616 } else {
7617 if (s->selected_entry)
7618 te = s->selected_entry;
7619 else if (view->searching == TOG_SEARCH_FORWARD)
7620 te = got_object_tree_get_first_entry(s->tree);
7621 else
7622 te = got_object_tree_get_last_entry(s->tree);
7625 while (1) {
7626 if (te == NULL) {
7627 if (s->matched_entry == NULL) {
7628 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7629 return NULL;
7631 if (view->searching == TOG_SEARCH_FORWARD)
7632 te = got_object_tree_get_first_entry(s->tree);
7633 else
7634 te = got_object_tree_get_last_entry(s->tree);
7637 if (match_tree_entry(te, &view->regex)) {
7638 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7639 s->matched_entry = te;
7640 break;
7643 if (view->searching == TOG_SEARCH_FORWARD)
7644 te = got_tree_entry_get_next(s->tree, te);
7645 else
7646 te = got_tree_entry_get_prev(s->tree, te);
7649 if (s->matched_entry) {
7650 s->first_displayed_entry = s->matched_entry;
7651 s->selected = 0;
7654 return NULL;
7657 static const struct got_error *
7658 show_tree_view(struct tog_view *view)
7660 const struct got_error *err = NULL;
7661 struct tog_tree_view_state *s = &view->state.tree;
7662 char *parent_path;
7664 err = tree_entry_path(&parent_path, &s->parents, NULL);
7665 if (err)
7666 return err;
7668 err = draw_tree_entries(view, parent_path);
7669 free(parent_path);
7671 view_border(view);
7672 return err;
7675 static const struct got_error *
7676 tree_goto_line(struct tog_view *view, int nlines)
7678 const struct got_error *err = NULL;
7679 struct tog_tree_view_state *s = &view->state.tree;
7680 struct got_tree_entry **fte, **lte, **ste;
7681 int g, last, first = 1, i = 1;
7682 int root = s->tree == s->root;
7683 int off = root ? 1 : 2;
7685 g = view->gline;
7686 view->gline = 0;
7688 if (g == 0)
7689 g = 1;
7690 else if (g > got_object_tree_get_nentries(s->tree))
7691 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7693 fte = &s->first_displayed_entry;
7694 lte = &s->last_displayed_entry;
7695 ste = &s->selected_entry;
7697 if (*fte != NULL) {
7698 first = got_tree_entry_get_index(*fte);
7699 first += off; /* account for ".." */
7701 last = got_tree_entry_get_index(*lte);
7702 last += off;
7704 if (g >= first && g <= last && g - first < nlines) {
7705 s->selected = g - first;
7706 return NULL; /* gline is on the current page */
7709 if (*ste != NULL) {
7710 i = got_tree_entry_get_index(*ste);
7711 i += off;
7714 if (i < g) {
7715 err = tree_scroll_down(view, g - i);
7716 if (err)
7717 return err;
7718 if (got_tree_entry_get_index(*lte) >=
7719 got_object_tree_get_nentries(s->tree) - 1 &&
7720 first + s->selected < g &&
7721 s->selected < s->ndisplayed - 1) {
7722 first = got_tree_entry_get_index(*fte);
7723 first += off;
7724 s->selected = g - first;
7726 } else if (i > g)
7727 tree_scroll_up(s, i - g);
7729 if (g < nlines &&
7730 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7731 s->selected = g - 1;
7733 return NULL;
7736 static const struct got_error *
7737 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7739 const struct got_error *err = NULL;
7740 struct tog_tree_view_state *s = &view->state.tree;
7741 struct got_tree_entry *te;
7742 int n, nscroll = view->nlines - 3;
7744 if (view->gline)
7745 return tree_goto_line(view, nscroll);
7747 switch (ch) {
7748 case '0':
7749 case '$':
7750 case KEY_RIGHT:
7751 case 'l':
7752 case KEY_LEFT:
7753 case 'h':
7754 horizontal_scroll_input(view, ch);
7755 break;
7756 case 'i':
7757 s->show_ids = !s->show_ids;
7758 view->count = 0;
7759 break;
7760 case 'L':
7761 view->count = 0;
7762 if (!s->selected_entry)
7763 break;
7764 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7765 break;
7766 case 'R':
7767 view->count = 0;
7768 err = view_request_new(new_view, view, TOG_VIEW_REF);
7769 break;
7770 case 'g':
7771 case '=':
7772 case KEY_HOME:
7773 s->selected = 0;
7774 view->count = 0;
7775 if (s->tree == s->root)
7776 s->first_displayed_entry =
7777 got_object_tree_get_first_entry(s->tree);
7778 else
7779 s->first_displayed_entry = NULL;
7780 break;
7781 case 'G':
7782 case '*':
7783 case KEY_END: {
7784 int eos = view->nlines - 3;
7786 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7787 --eos; /* border */
7788 s->selected = 0;
7789 view->count = 0;
7790 te = got_object_tree_get_last_entry(s->tree);
7791 for (n = 0; n < eos; n++) {
7792 if (te == NULL) {
7793 if (s->tree != s->root) {
7794 s->first_displayed_entry = NULL;
7795 n++;
7797 break;
7799 s->first_displayed_entry = te;
7800 te = got_tree_entry_get_prev(s->tree, te);
7802 if (n > 0)
7803 s->selected = n - 1;
7804 break;
7806 case 'k':
7807 case KEY_UP:
7808 case CTRL('p'):
7809 if (s->selected > 0) {
7810 s->selected--;
7811 break;
7813 tree_scroll_up(s, 1);
7814 if (s->selected_entry == NULL ||
7815 (s->tree == s->root && s->selected_entry ==
7816 got_object_tree_get_first_entry(s->tree)))
7817 view->count = 0;
7818 break;
7819 case CTRL('u'):
7820 case 'u':
7821 nscroll /= 2;
7822 /* FALL THROUGH */
7823 case KEY_PPAGE:
7824 case CTRL('b'):
7825 case 'b':
7826 if (s->tree == s->root) {
7827 if (got_object_tree_get_first_entry(s->tree) ==
7828 s->first_displayed_entry)
7829 s->selected -= MIN(s->selected, nscroll);
7830 } else {
7831 if (s->first_displayed_entry == NULL)
7832 s->selected -= MIN(s->selected, nscroll);
7834 tree_scroll_up(s, MAX(0, nscroll));
7835 if (s->selected_entry == NULL ||
7836 (s->tree == s->root && s->selected_entry ==
7837 got_object_tree_get_first_entry(s->tree)))
7838 view->count = 0;
7839 break;
7840 case 'j':
7841 case KEY_DOWN:
7842 case CTRL('n'):
7843 if (s->selected < s->ndisplayed - 1) {
7844 s->selected++;
7845 break;
7847 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7848 == NULL) {
7849 /* can't scroll any further */
7850 view->count = 0;
7851 break;
7853 tree_scroll_down(view, 1);
7854 break;
7855 case CTRL('d'):
7856 case 'd':
7857 nscroll /= 2;
7858 /* FALL THROUGH */
7859 case KEY_NPAGE:
7860 case CTRL('f'):
7861 case 'f':
7862 case ' ':
7863 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7864 == NULL) {
7865 /* can't scroll any further; move cursor down */
7866 if (s->selected < s->ndisplayed - 1)
7867 s->selected += MIN(nscroll,
7868 s->ndisplayed - s->selected - 1);
7869 else
7870 view->count = 0;
7871 break;
7873 tree_scroll_down(view, nscroll);
7874 break;
7875 case KEY_ENTER:
7876 case '\r':
7877 case KEY_BACKSPACE:
7878 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7879 struct tog_parent_tree *parent;
7880 /* user selected '..' */
7881 if (s->tree == s->root) {
7882 view->count = 0;
7883 break;
7885 parent = TAILQ_FIRST(&s->parents);
7886 TAILQ_REMOVE(&s->parents, parent,
7887 entry);
7888 got_object_tree_close(s->tree);
7889 s->tree = parent->tree;
7890 s->first_displayed_entry =
7891 parent->first_displayed_entry;
7892 s->selected_entry =
7893 parent->selected_entry;
7894 s->selected = parent->selected;
7895 if (s->selected > view->nlines - 3) {
7896 err = offset_selection_down(view);
7897 if (err)
7898 break;
7900 free(parent);
7901 } else if (S_ISDIR(got_tree_entry_get_mode(
7902 s->selected_entry))) {
7903 struct got_tree_object *subtree;
7904 view->count = 0;
7905 err = got_object_open_as_tree(&subtree, s->repo,
7906 got_tree_entry_get_id(s->selected_entry));
7907 if (err)
7908 break;
7909 err = tree_view_visit_subtree(s, subtree);
7910 if (err) {
7911 got_object_tree_close(subtree);
7912 break;
7914 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7915 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7916 break;
7917 case KEY_RESIZE:
7918 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7919 s->selected = view->nlines - 4;
7920 view->count = 0;
7921 break;
7922 default:
7923 view->count = 0;
7924 break;
7927 return err;
7930 __dead static void
7931 usage_tree(void)
7933 endwin();
7934 fprintf(stderr,
7935 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7936 getprogname());
7937 exit(1);
7940 static const struct got_error *
7941 cmd_tree(int argc, char *argv[])
7943 const struct got_error *error;
7944 struct got_repository *repo = NULL;
7945 struct got_worktree *worktree = NULL;
7946 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7947 struct got_object_id *commit_id = NULL;
7948 struct got_commit_object *commit = NULL;
7949 const char *commit_id_arg = NULL;
7950 char *label = NULL;
7951 struct got_reference *ref = NULL;
7952 const char *head_ref_name = NULL;
7953 int ch;
7954 struct tog_view *view;
7955 int *pack_fds = NULL;
7957 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7958 switch (ch) {
7959 case 'c':
7960 commit_id_arg = optarg;
7961 break;
7962 case 'r':
7963 repo_path = realpath(optarg, NULL);
7964 if (repo_path == NULL)
7965 return got_error_from_errno2("realpath",
7966 optarg);
7967 break;
7968 default:
7969 usage_tree();
7970 /* NOTREACHED */
7974 argc -= optind;
7975 argv += optind;
7977 if (argc > 1)
7978 usage_tree();
7980 error = got_repo_pack_fds_open(&pack_fds);
7981 if (error != NULL)
7982 goto done;
7984 if (repo_path == NULL) {
7985 cwd = getcwd(NULL, 0);
7986 if (cwd == NULL)
7987 return got_error_from_errno("getcwd");
7988 error = got_worktree_open(&worktree, cwd);
7989 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7990 goto done;
7991 if (worktree)
7992 repo_path =
7993 strdup(got_worktree_get_repo_path(worktree));
7994 else
7995 repo_path = strdup(cwd);
7996 if (repo_path == NULL) {
7997 error = got_error_from_errno("strdup");
7998 goto done;
8002 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8003 if (error != NULL)
8004 goto done;
8006 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8007 repo, worktree);
8008 if (error)
8009 goto done;
8011 init_curses();
8013 error = apply_unveil(got_repo_get_path(repo), NULL);
8014 if (error)
8015 goto done;
8017 error = tog_load_refs(repo, 0);
8018 if (error)
8019 goto done;
8021 if (commit_id_arg == NULL) {
8022 error = got_repo_match_object_id(&commit_id, &label,
8023 worktree ? got_worktree_get_head_ref_name(worktree) :
8024 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8025 if (error)
8026 goto done;
8027 head_ref_name = label;
8028 } else {
8029 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8030 if (error == NULL)
8031 head_ref_name = got_ref_get_name(ref);
8032 else if (error->code != GOT_ERR_NOT_REF)
8033 goto done;
8034 error = got_repo_match_object_id(&commit_id, NULL,
8035 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8036 if (error)
8037 goto done;
8040 error = got_object_open_as_commit(&commit, repo, commit_id);
8041 if (error)
8042 goto done;
8044 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8045 if (view == NULL) {
8046 error = got_error_from_errno("view_open");
8047 goto done;
8049 error = open_tree_view(view, commit_id, head_ref_name, repo);
8050 if (error)
8051 goto done;
8052 if (!got_path_is_root_dir(in_repo_path)) {
8053 error = tree_view_walk_path(&view->state.tree, commit,
8054 in_repo_path);
8055 if (error)
8056 goto done;
8059 if (worktree) {
8060 /* Release work tree lock. */
8061 got_worktree_close(worktree);
8062 worktree = NULL;
8064 error = view_loop(view);
8065 done:
8066 free(repo_path);
8067 free(cwd);
8068 free(commit_id);
8069 free(label);
8070 if (ref)
8071 got_ref_close(ref);
8072 if (repo) {
8073 const struct got_error *close_err = got_repo_close(repo);
8074 if (error == NULL)
8075 error = close_err;
8077 if (pack_fds) {
8078 const struct got_error *pack_err =
8079 got_repo_pack_fds_close(pack_fds);
8080 if (error == NULL)
8081 error = pack_err;
8083 tog_free_refs();
8084 return error;
8087 static const struct got_error *
8088 ref_view_load_refs(struct tog_ref_view_state *s)
8090 struct got_reflist_entry *sre;
8091 struct tog_reflist_entry *re;
8093 s->nrefs = 0;
8094 TAILQ_FOREACH(sre, &tog_refs, entry) {
8095 if (strncmp(got_ref_get_name(sre->ref),
8096 "refs/got/", 9) == 0 &&
8097 strncmp(got_ref_get_name(sre->ref),
8098 "refs/got/backup/", 16) != 0)
8099 continue;
8101 re = malloc(sizeof(*re));
8102 if (re == NULL)
8103 return got_error_from_errno("malloc");
8105 re->ref = got_ref_dup(sre->ref);
8106 if (re->ref == NULL)
8107 return got_error_from_errno("got_ref_dup");
8108 re->idx = s->nrefs++;
8109 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8112 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8113 return NULL;
8116 static void
8117 ref_view_free_refs(struct tog_ref_view_state *s)
8119 struct tog_reflist_entry *re;
8121 while (!TAILQ_EMPTY(&s->refs)) {
8122 re = TAILQ_FIRST(&s->refs);
8123 TAILQ_REMOVE(&s->refs, re, entry);
8124 got_ref_close(re->ref);
8125 free(re);
8129 static const struct got_error *
8130 open_ref_view(struct tog_view *view, struct got_repository *repo)
8132 const struct got_error *err = NULL;
8133 struct tog_ref_view_state *s = &view->state.ref;
8135 s->selected_entry = 0;
8136 s->repo = repo;
8138 TAILQ_INIT(&s->refs);
8139 STAILQ_INIT(&s->colors);
8141 err = ref_view_load_refs(s);
8142 if (err)
8143 goto done;
8145 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8146 err = add_color(&s->colors, "^refs/heads/",
8147 TOG_COLOR_REFS_HEADS,
8148 get_color_value("TOG_COLOR_REFS_HEADS"));
8149 if (err)
8150 goto done;
8152 err = add_color(&s->colors, "^refs/tags/",
8153 TOG_COLOR_REFS_TAGS,
8154 get_color_value("TOG_COLOR_REFS_TAGS"));
8155 if (err)
8156 goto done;
8158 err = add_color(&s->colors, "^refs/remotes/",
8159 TOG_COLOR_REFS_REMOTES,
8160 get_color_value("TOG_COLOR_REFS_REMOTES"));
8161 if (err)
8162 goto done;
8164 err = add_color(&s->colors, "^refs/got/backup/",
8165 TOG_COLOR_REFS_BACKUP,
8166 get_color_value("TOG_COLOR_REFS_BACKUP"));
8167 if (err)
8168 goto done;
8171 view->show = show_ref_view;
8172 view->input = input_ref_view;
8173 view->close = close_ref_view;
8174 view->search_start = search_start_ref_view;
8175 view->search_next = search_next_ref_view;
8176 done:
8177 if (err) {
8178 if (view->close == NULL)
8179 close_ref_view(view);
8180 view_close(view);
8182 return err;
8185 static const struct got_error *
8186 close_ref_view(struct tog_view *view)
8188 struct tog_ref_view_state *s = &view->state.ref;
8190 ref_view_free_refs(s);
8191 free_colors(&s->colors);
8193 return NULL;
8196 static const struct got_error *
8197 resolve_reflist_entry(struct got_object_id **commit_id,
8198 struct tog_reflist_entry *re, struct got_repository *repo)
8200 const struct got_error *err = NULL;
8201 struct got_object_id *obj_id;
8202 struct got_tag_object *tag = NULL;
8203 int obj_type;
8205 *commit_id = NULL;
8207 err = got_ref_resolve(&obj_id, repo, re->ref);
8208 if (err)
8209 return err;
8211 err = got_object_get_type(&obj_type, repo, obj_id);
8212 if (err)
8213 goto done;
8215 switch (obj_type) {
8216 case GOT_OBJ_TYPE_COMMIT:
8217 *commit_id = obj_id;
8218 break;
8219 case GOT_OBJ_TYPE_TAG:
8220 err = got_object_open_as_tag(&tag, repo, obj_id);
8221 if (err)
8222 goto done;
8223 free(obj_id);
8224 err = got_object_get_type(&obj_type, repo,
8225 got_object_tag_get_object_id(tag));
8226 if (err)
8227 goto done;
8228 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8229 err = got_error(GOT_ERR_OBJ_TYPE);
8230 goto done;
8232 *commit_id = got_object_id_dup(
8233 got_object_tag_get_object_id(tag));
8234 if (*commit_id == NULL) {
8235 err = got_error_from_errno("got_object_id_dup");
8236 goto done;
8238 break;
8239 default:
8240 err = got_error(GOT_ERR_OBJ_TYPE);
8241 break;
8244 done:
8245 if (tag)
8246 got_object_tag_close(tag);
8247 if (err) {
8248 free(*commit_id);
8249 *commit_id = NULL;
8251 return err;
8254 static const struct got_error *
8255 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8256 struct tog_reflist_entry *re, struct got_repository *repo)
8258 struct tog_view *log_view;
8259 const struct got_error *err = NULL;
8260 struct got_object_id *commit_id = NULL;
8262 *new_view = NULL;
8264 err = resolve_reflist_entry(&commit_id, re, repo);
8265 if (err) {
8266 if (err->code != GOT_ERR_OBJ_TYPE)
8267 return err;
8268 else
8269 return NULL;
8272 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8273 if (log_view == NULL) {
8274 err = got_error_from_errno("view_open");
8275 goto done;
8278 err = open_log_view(log_view, commit_id, repo,
8279 got_ref_get_name(re->ref), "", 0);
8280 done:
8281 if (err)
8282 view_close(log_view);
8283 else
8284 *new_view = log_view;
8285 free(commit_id);
8286 return err;
8289 static void
8290 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8292 struct tog_reflist_entry *re;
8293 int i = 0;
8295 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8296 return;
8298 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8299 while (i++ < maxscroll) {
8300 if (re == NULL)
8301 break;
8302 s->first_displayed_entry = re;
8303 re = TAILQ_PREV(re, tog_reflist_head, entry);
8307 static const struct got_error *
8308 ref_scroll_down(struct tog_view *view, int maxscroll)
8310 struct tog_ref_view_state *s = &view->state.ref;
8311 struct tog_reflist_entry *next, *last;
8312 int n = 0;
8314 if (s->first_displayed_entry)
8315 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8316 else
8317 next = TAILQ_FIRST(&s->refs);
8319 last = s->last_displayed_entry;
8320 while (next && n++ < maxscroll) {
8321 if (last) {
8322 s->last_displayed_entry = last;
8323 last = TAILQ_NEXT(last, entry);
8325 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8326 s->first_displayed_entry = next;
8327 next = TAILQ_NEXT(next, entry);
8331 return NULL;
8334 static const struct got_error *
8335 search_start_ref_view(struct tog_view *view)
8337 struct tog_ref_view_state *s = &view->state.ref;
8339 s->matched_entry = NULL;
8340 return NULL;
8343 static int
8344 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8346 regmatch_t regmatch;
8348 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8349 0) == 0;
8352 static const struct got_error *
8353 search_next_ref_view(struct tog_view *view)
8355 struct tog_ref_view_state *s = &view->state.ref;
8356 struct tog_reflist_entry *re = NULL;
8358 if (!view->searching) {
8359 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8360 return NULL;
8363 if (s->matched_entry) {
8364 if (view->searching == TOG_SEARCH_FORWARD) {
8365 if (s->selected_entry)
8366 re = TAILQ_NEXT(s->selected_entry, entry);
8367 else
8368 re = TAILQ_PREV(s->selected_entry,
8369 tog_reflist_head, entry);
8370 } else {
8371 if (s->selected_entry == NULL)
8372 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8373 else
8374 re = TAILQ_PREV(s->selected_entry,
8375 tog_reflist_head, entry);
8377 } else {
8378 if (s->selected_entry)
8379 re = s->selected_entry;
8380 else if (view->searching == TOG_SEARCH_FORWARD)
8381 re = TAILQ_FIRST(&s->refs);
8382 else
8383 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8386 while (1) {
8387 if (re == NULL) {
8388 if (s->matched_entry == NULL) {
8389 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8390 return NULL;
8392 if (view->searching == TOG_SEARCH_FORWARD)
8393 re = TAILQ_FIRST(&s->refs);
8394 else
8395 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8398 if (match_reflist_entry(re, &view->regex)) {
8399 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8400 s->matched_entry = re;
8401 break;
8404 if (view->searching == TOG_SEARCH_FORWARD)
8405 re = TAILQ_NEXT(re, entry);
8406 else
8407 re = TAILQ_PREV(re, tog_reflist_head, entry);
8410 if (s->matched_entry) {
8411 s->first_displayed_entry = s->matched_entry;
8412 s->selected = 0;
8415 return NULL;
8418 static const struct got_error *
8419 show_ref_view(struct tog_view *view)
8421 const struct got_error *err = NULL;
8422 struct tog_ref_view_state *s = &view->state.ref;
8423 struct tog_reflist_entry *re;
8424 char *line = NULL;
8425 wchar_t *wline;
8426 struct tog_color *tc;
8427 int width, n, scrollx;
8428 int limit = view->nlines;
8430 werase(view->window);
8432 s->ndisplayed = 0;
8433 if (view_is_hsplit_top(view))
8434 --limit; /* border */
8436 if (limit == 0)
8437 return NULL;
8439 re = s->first_displayed_entry;
8441 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8442 s->nrefs) == -1)
8443 return got_error_from_errno("asprintf");
8445 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8446 if (err) {
8447 free(line);
8448 return err;
8450 if (view_needs_focus_indication(view))
8451 wstandout(view->window);
8452 waddwstr(view->window, wline);
8453 while (width++ < view->ncols)
8454 waddch(view->window, ' ');
8455 if (view_needs_focus_indication(view))
8456 wstandend(view->window);
8457 free(wline);
8458 wline = NULL;
8459 free(line);
8460 line = NULL;
8461 if (--limit <= 0)
8462 return NULL;
8464 n = 0;
8465 view->maxx = 0;
8466 while (re && limit > 0) {
8467 char *line = NULL;
8468 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8470 if (s->show_date) {
8471 struct got_commit_object *ci;
8472 struct got_tag_object *tag;
8473 struct got_object_id *id;
8474 struct tm tm;
8475 time_t t;
8477 err = got_ref_resolve(&id, s->repo, re->ref);
8478 if (err)
8479 return err;
8480 err = got_object_open_as_tag(&tag, s->repo, id);
8481 if (err) {
8482 if (err->code != GOT_ERR_OBJ_TYPE) {
8483 free(id);
8484 return err;
8486 err = got_object_open_as_commit(&ci, s->repo,
8487 id);
8488 if (err) {
8489 free(id);
8490 return err;
8492 t = got_object_commit_get_committer_time(ci);
8493 got_object_commit_close(ci);
8494 } else {
8495 t = got_object_tag_get_tagger_time(tag);
8496 got_object_tag_close(tag);
8498 free(id);
8499 if (gmtime_r(&t, &tm) == NULL)
8500 return got_error_from_errno("gmtime_r");
8501 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8502 return got_error(GOT_ERR_NO_SPACE);
8504 if (got_ref_is_symbolic(re->ref)) {
8505 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8506 ymd : "", got_ref_get_name(re->ref),
8507 got_ref_get_symref_target(re->ref)) == -1)
8508 return got_error_from_errno("asprintf");
8509 } else if (s->show_ids) {
8510 struct got_object_id *id;
8511 char *id_str;
8512 err = got_ref_resolve(&id, s->repo, re->ref);
8513 if (err)
8514 return err;
8515 err = got_object_id_str(&id_str, id);
8516 if (err) {
8517 free(id);
8518 return err;
8520 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8521 got_ref_get_name(re->ref), id_str) == -1) {
8522 err = got_error_from_errno("asprintf");
8523 free(id);
8524 free(id_str);
8525 return err;
8527 free(id);
8528 free(id_str);
8529 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8530 got_ref_get_name(re->ref)) == -1)
8531 return got_error_from_errno("asprintf");
8533 /* use full line width to determine view->maxx */
8534 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8535 if (err) {
8536 free(line);
8537 return err;
8539 view->maxx = MAX(view->maxx, width);
8540 free(wline);
8541 wline = NULL;
8543 err = format_line(&wline, &width, &scrollx, line, view->x,
8544 view->ncols, 0, 0);
8545 if (err) {
8546 free(line);
8547 return err;
8549 if (n == s->selected) {
8550 if (view->focussed)
8551 wstandout(view->window);
8552 s->selected_entry = re;
8554 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8555 if (tc)
8556 wattr_on(view->window,
8557 COLOR_PAIR(tc->colorpair), NULL);
8558 waddwstr(view->window, &wline[scrollx]);
8559 if (tc)
8560 wattr_off(view->window,
8561 COLOR_PAIR(tc->colorpair), NULL);
8562 if (width < view->ncols)
8563 waddch(view->window, '\n');
8564 if (n == s->selected && view->focussed)
8565 wstandend(view->window);
8566 free(line);
8567 free(wline);
8568 wline = NULL;
8569 n++;
8570 s->ndisplayed++;
8571 s->last_displayed_entry = re;
8573 limit--;
8574 re = TAILQ_NEXT(re, entry);
8577 view_border(view);
8578 return err;
8581 static const struct got_error *
8582 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8583 struct tog_reflist_entry *re, struct got_repository *repo)
8585 const struct got_error *err = NULL;
8586 struct got_object_id *commit_id = NULL;
8587 struct tog_view *tree_view;
8589 *new_view = NULL;
8591 err = resolve_reflist_entry(&commit_id, re, repo);
8592 if (err) {
8593 if (err->code != GOT_ERR_OBJ_TYPE)
8594 return err;
8595 else
8596 return NULL;
8600 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8601 if (tree_view == NULL) {
8602 err = got_error_from_errno("view_open");
8603 goto done;
8606 err = open_tree_view(tree_view, commit_id,
8607 got_ref_get_name(re->ref), repo);
8608 if (err)
8609 goto done;
8611 *new_view = tree_view;
8612 done:
8613 free(commit_id);
8614 return err;
8617 static const struct got_error *
8618 ref_goto_line(struct tog_view *view, int nlines)
8620 const struct got_error *err = NULL;
8621 struct tog_ref_view_state *s = &view->state.ref;
8622 int g, idx = s->selected_entry->idx;
8624 g = view->gline;
8625 view->gline = 0;
8627 if (g == 0)
8628 g = 1;
8629 else if (g > s->nrefs)
8630 g = s->nrefs;
8632 if (g >= s->first_displayed_entry->idx + 1 &&
8633 g <= s->last_displayed_entry->idx + 1 &&
8634 g - s->first_displayed_entry->idx - 1 < nlines) {
8635 s->selected = g - s->first_displayed_entry->idx - 1;
8636 return NULL;
8639 if (idx + 1 < g) {
8640 err = ref_scroll_down(view, g - idx - 1);
8641 if (err)
8642 return err;
8643 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8644 s->first_displayed_entry->idx + s->selected < g &&
8645 s->selected < s->ndisplayed - 1)
8646 s->selected = g - s->first_displayed_entry->idx - 1;
8647 } else if (idx + 1 > g)
8648 ref_scroll_up(s, idx - g + 1);
8650 if (g < nlines && s->first_displayed_entry->idx == 0)
8651 s->selected = g - 1;
8653 return NULL;
8657 static const struct got_error *
8658 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8660 const struct got_error *err = NULL;
8661 struct tog_ref_view_state *s = &view->state.ref;
8662 struct tog_reflist_entry *re;
8663 int n, nscroll = view->nlines - 1;
8665 if (view->gline)
8666 return ref_goto_line(view, nscroll);
8668 switch (ch) {
8669 case '0':
8670 case '$':
8671 case KEY_RIGHT:
8672 case 'l':
8673 case KEY_LEFT:
8674 case 'h':
8675 horizontal_scroll_input(view, ch);
8676 break;
8677 case 'i':
8678 s->show_ids = !s->show_ids;
8679 view->count = 0;
8680 break;
8681 case 'm':
8682 s->show_date = !s->show_date;
8683 view->count = 0;
8684 break;
8685 case 'o':
8686 s->sort_by_date = !s->sort_by_date;
8687 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8688 view->count = 0;
8689 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8690 got_ref_cmp_by_commit_timestamp_descending :
8691 tog_ref_cmp_by_name, s->repo);
8692 if (err)
8693 break;
8694 got_reflist_object_id_map_free(tog_refs_idmap);
8695 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8696 &tog_refs, s->repo);
8697 if (err)
8698 break;
8699 ref_view_free_refs(s);
8700 err = ref_view_load_refs(s);
8701 break;
8702 case KEY_ENTER:
8703 case '\r':
8704 view->count = 0;
8705 if (!s->selected_entry)
8706 break;
8707 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8708 break;
8709 case 'T':
8710 view->count = 0;
8711 if (!s->selected_entry)
8712 break;
8713 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8714 break;
8715 case 'g':
8716 case '=':
8717 case KEY_HOME:
8718 s->selected = 0;
8719 view->count = 0;
8720 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8721 break;
8722 case 'G':
8723 case '*':
8724 case KEY_END: {
8725 int eos = view->nlines - 1;
8727 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8728 --eos; /* border */
8729 s->selected = 0;
8730 view->count = 0;
8731 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8732 for (n = 0; n < eos; n++) {
8733 if (re == NULL)
8734 break;
8735 s->first_displayed_entry = re;
8736 re = TAILQ_PREV(re, tog_reflist_head, entry);
8738 if (n > 0)
8739 s->selected = n - 1;
8740 break;
8742 case 'k':
8743 case KEY_UP:
8744 case CTRL('p'):
8745 if (s->selected > 0) {
8746 s->selected--;
8747 break;
8749 ref_scroll_up(s, 1);
8750 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8751 view->count = 0;
8752 break;
8753 case CTRL('u'):
8754 case 'u':
8755 nscroll /= 2;
8756 /* FALL THROUGH */
8757 case KEY_PPAGE:
8758 case CTRL('b'):
8759 case 'b':
8760 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8761 s->selected -= MIN(nscroll, s->selected);
8762 ref_scroll_up(s, MAX(0, nscroll));
8763 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8764 view->count = 0;
8765 break;
8766 case 'j':
8767 case KEY_DOWN:
8768 case CTRL('n'):
8769 if (s->selected < s->ndisplayed - 1) {
8770 s->selected++;
8771 break;
8773 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8774 /* can't scroll any further */
8775 view->count = 0;
8776 break;
8778 ref_scroll_down(view, 1);
8779 break;
8780 case CTRL('d'):
8781 case 'd':
8782 nscroll /= 2;
8783 /* FALL THROUGH */
8784 case KEY_NPAGE:
8785 case CTRL('f'):
8786 case 'f':
8787 case ' ':
8788 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8789 /* can't scroll any further; move cursor down */
8790 if (s->selected < s->ndisplayed - 1)
8791 s->selected += MIN(nscroll,
8792 s->ndisplayed - s->selected - 1);
8793 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8794 s->selected += s->ndisplayed - s->selected - 1;
8795 view->count = 0;
8796 break;
8798 ref_scroll_down(view, nscroll);
8799 break;
8800 case CTRL('l'):
8801 view->count = 0;
8802 tog_free_refs();
8803 err = tog_load_refs(s->repo, s->sort_by_date);
8804 if (err)
8805 break;
8806 ref_view_free_refs(s);
8807 err = ref_view_load_refs(s);
8808 break;
8809 case KEY_RESIZE:
8810 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8811 s->selected = view->nlines - 2;
8812 break;
8813 default:
8814 view->count = 0;
8815 break;
8818 return err;
8821 __dead static void
8822 usage_ref(void)
8824 endwin();
8825 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8826 getprogname());
8827 exit(1);
8830 static const struct got_error *
8831 cmd_ref(int argc, char *argv[])
8833 const struct got_error *error;
8834 struct got_repository *repo = NULL;
8835 struct got_worktree *worktree = NULL;
8836 char *cwd = NULL, *repo_path = NULL;
8837 int ch;
8838 struct tog_view *view;
8839 int *pack_fds = NULL;
8841 while ((ch = getopt(argc, argv, "r:")) != -1) {
8842 switch (ch) {
8843 case 'r':
8844 repo_path = realpath(optarg, NULL);
8845 if (repo_path == NULL)
8846 return got_error_from_errno2("realpath",
8847 optarg);
8848 break;
8849 default:
8850 usage_ref();
8851 /* NOTREACHED */
8855 argc -= optind;
8856 argv += optind;
8858 if (argc > 1)
8859 usage_ref();
8861 error = got_repo_pack_fds_open(&pack_fds);
8862 if (error != NULL)
8863 goto done;
8865 if (repo_path == NULL) {
8866 cwd = getcwd(NULL, 0);
8867 if (cwd == NULL)
8868 return got_error_from_errno("getcwd");
8869 error = got_worktree_open(&worktree, cwd);
8870 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8871 goto done;
8872 if (worktree)
8873 repo_path =
8874 strdup(got_worktree_get_repo_path(worktree));
8875 else
8876 repo_path = strdup(cwd);
8877 if (repo_path == NULL) {
8878 error = got_error_from_errno("strdup");
8879 goto done;
8883 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8884 if (error != NULL)
8885 goto done;
8887 init_curses();
8889 error = apply_unveil(got_repo_get_path(repo), NULL);
8890 if (error)
8891 goto done;
8893 error = tog_load_refs(repo, 0);
8894 if (error)
8895 goto done;
8897 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8898 if (view == NULL) {
8899 error = got_error_from_errno("view_open");
8900 goto done;
8903 error = open_ref_view(view, repo);
8904 if (error)
8905 goto done;
8907 if (worktree) {
8908 /* Release work tree lock. */
8909 got_worktree_close(worktree);
8910 worktree = NULL;
8912 error = view_loop(view);
8913 done:
8914 free(repo_path);
8915 free(cwd);
8916 if (repo) {
8917 const struct got_error *close_err = got_repo_close(repo);
8918 if (close_err)
8919 error = close_err;
8921 if (pack_fds) {
8922 const struct got_error *pack_err =
8923 got_repo_pack_fds_close(pack_fds);
8924 if (error == NULL)
8925 error = pack_err;
8927 tog_free_refs();
8928 return error;
8931 static const struct got_error*
8932 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8933 const char *str)
8935 size_t len;
8937 if (win == NULL)
8938 win = stdscr;
8940 len = strlen(str);
8941 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8943 if (focus)
8944 wstandout(win);
8945 if (mvwprintw(win, y, x, "%s", str) == ERR)
8946 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8947 if (focus)
8948 wstandend(win);
8950 return NULL;
8953 static const struct got_error *
8954 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8956 off_t *p;
8958 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8959 if (p == NULL) {
8960 free(*line_offsets);
8961 *line_offsets = NULL;
8962 return got_error_from_errno("reallocarray");
8965 *line_offsets = p;
8966 (*line_offsets)[*nlines] = off;
8967 ++(*nlines);
8968 return NULL;
8971 static const struct got_error *
8972 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8974 *ret = 0;
8976 for (;n > 0; --n, ++km) {
8977 char *t0, *t, *k;
8978 size_t len = 1;
8980 if (km->keys == NULL)
8981 continue;
8983 t = t0 = strdup(km->keys);
8984 if (t0 == NULL)
8985 return got_error_from_errno("strdup");
8987 len += strlen(t);
8988 while ((k = strsep(&t, " ")) != NULL)
8989 len += strlen(k) > 1 ? 2 : 0;
8990 free(t0);
8991 *ret = MAX(*ret, len);
8994 return NULL;
8998 * Write keymap section headers, keys, and key info in km to f.
8999 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9000 * wrap control and symbolic keys in guillemets, else use <>.
9002 static const struct got_error *
9003 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9005 int n, len = width;
9007 if (km->keys) {
9008 static const char *u8_glyph[] = {
9009 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9010 "\xe2\x80\xba" /* U+203A (utf8 >) */
9012 char *t0, *t, *k;
9013 int cs, s, first = 1;
9015 cs = got_locale_is_utf8();
9017 t = t0 = strdup(km->keys);
9018 if (t0 == NULL)
9019 return got_error_from_errno("strdup");
9021 len = strlen(km->keys);
9022 while ((k = strsep(&t, " ")) != NULL) {
9023 s = strlen(k) > 1; /* control or symbolic key */
9024 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9025 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9026 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9027 if (n < 0) {
9028 free(t0);
9029 return got_error_from_errno("fprintf");
9031 first = 0;
9032 len += s ? 2 : 0;
9033 *off += n;
9035 free(t0);
9037 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9038 if (n < 0)
9039 return got_error_from_errno("fprintf");
9040 *off += n;
9042 return NULL;
9045 static const struct got_error *
9046 format_help(struct tog_help_view_state *s)
9048 const struct got_error *err = NULL;
9049 off_t off = 0;
9050 int i, max, n, show = s->all;
9051 static const struct tog_key_map km[] = {
9052 #define KEYMAP_(info, type) { NULL, (info), type }
9053 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9054 GENERATE_HELP
9055 #undef KEYMAP_
9056 #undef KEY_
9059 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9060 if (err)
9061 return err;
9063 n = nitems(km);
9064 err = max_key_str(&max, km, n);
9065 if (err)
9066 return err;
9068 for (i = 0; i < n; ++i) {
9069 if (km[i].keys == NULL) {
9070 show = s->all;
9071 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9072 km[i].type == s->type || s->all)
9073 show = 1;
9075 if (show) {
9076 err = format_help_line(&off, s->f, &km[i], max);
9077 if (err)
9078 return err;
9079 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9080 if (err)
9081 return err;
9084 fputc('\n', s->f);
9085 ++off;
9086 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9087 return err;
9090 static const struct got_error *
9091 create_help(struct tog_help_view_state *s)
9093 FILE *f;
9094 const struct got_error *err;
9096 free(s->line_offsets);
9097 s->line_offsets = NULL;
9098 s->nlines = 0;
9100 f = got_opentemp();
9101 if (f == NULL)
9102 return got_error_from_errno("got_opentemp");
9103 s->f = f;
9105 err = format_help(s);
9106 if (err)
9107 return err;
9109 if (s->f && fflush(s->f) != 0)
9110 return got_error_from_errno("fflush");
9112 return NULL;
9115 static const struct got_error *
9116 search_start_help_view(struct tog_view *view)
9118 view->state.help.matched_line = 0;
9119 return NULL;
9122 static void
9123 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9124 size_t *nlines, int **first, int **last, int **match, int **selected)
9126 struct tog_help_view_state *s = &view->state.help;
9128 *f = s->f;
9129 *nlines = s->nlines;
9130 *line_offsets = s->line_offsets;
9131 *match = &s->matched_line;
9132 *first = &s->first_displayed_line;
9133 *last = &s->last_displayed_line;
9134 *selected = &s->selected_line;
9137 static const struct got_error *
9138 show_help_view(struct tog_view *view)
9140 struct tog_help_view_state *s = &view->state.help;
9141 const struct got_error *err;
9142 regmatch_t *regmatch = &view->regmatch;
9143 wchar_t *wline;
9144 char *line;
9145 ssize_t linelen;
9146 size_t linesz = 0;
9147 int width, nprinted = 0, rc = 0;
9148 int eos = view->nlines;
9150 if (view_is_hsplit_top(view))
9151 --eos; /* account for border */
9153 s->lineno = 0;
9154 rewind(s->f);
9155 werase(view->window);
9157 if (view->gline > s->nlines - 1)
9158 view->gline = s->nlines - 1;
9160 err = win_draw_center(view->window, 0, 0, view->ncols,
9161 view_needs_focus_indication(view),
9162 "tog help (press q to return to tog)");
9163 if (err)
9164 return err;
9165 if (eos <= 1)
9166 return NULL;
9167 waddstr(view->window, "\n\n");
9168 eos -= 2;
9170 s->eof = 0;
9171 view->maxx = 0;
9172 line = NULL;
9173 while (eos > 0 && nprinted < eos) {
9174 attr_t attr = 0;
9176 linelen = getline(&line, &linesz, s->f);
9177 if (linelen == -1) {
9178 if (!feof(s->f)) {
9179 free(line);
9180 return got_ferror(s->f, GOT_ERR_IO);
9182 s->eof = 1;
9183 break;
9185 if (++s->lineno < s->first_displayed_line)
9186 continue;
9187 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9188 continue;
9189 if (s->lineno == view->hiline)
9190 attr = A_STANDOUT;
9192 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9193 view->x ? 1 : 0);
9194 if (err) {
9195 free(line);
9196 return err;
9198 view->maxx = MAX(view->maxx, width);
9199 free(wline);
9200 wline = NULL;
9202 if (attr)
9203 wattron(view->window, attr);
9204 if (s->first_displayed_line + nprinted == s->matched_line &&
9205 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9206 err = add_matched_line(&width, line, view->ncols - 1, 0,
9207 view->window, view->x, regmatch);
9208 if (err) {
9209 free(line);
9210 return err;
9212 } else {
9213 int skip;
9215 err = format_line(&wline, &width, &skip, line,
9216 view->x, view->ncols, 0, view->x ? 1 : 0);
9217 if (err) {
9218 free(line);
9219 return err;
9221 waddwstr(view->window, &wline[skip]);
9222 free(wline);
9223 wline = NULL;
9225 if (s->lineno == view->hiline) {
9226 while (width++ < view->ncols)
9227 waddch(view->window, ' ');
9228 } else {
9229 if (width < view->ncols)
9230 waddch(view->window, '\n');
9232 if (attr)
9233 wattroff(view->window, attr);
9234 if (++nprinted == 1)
9235 s->first_displayed_line = s->lineno;
9237 free(line);
9238 if (nprinted > 0)
9239 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9240 else
9241 s->last_displayed_line = s->first_displayed_line;
9243 view_border(view);
9245 if (s->eof) {
9246 rc = waddnstr(view->window,
9247 "See the tog(1) manual page for full documentation",
9248 view->ncols - 1);
9249 if (rc == ERR)
9250 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9251 } else {
9252 wmove(view->window, view->nlines - 1, 0);
9253 wclrtoeol(view->window);
9254 wstandout(view->window);
9255 rc = waddnstr(view->window, "scroll down for more...",
9256 view->ncols - 1);
9257 if (rc == ERR)
9258 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9259 if (getcurx(view->window) < view->ncols - 6) {
9260 rc = wprintw(view->window, "[%.0f%%]",
9261 100.00 * s->last_displayed_line / s->nlines);
9262 if (rc == ERR)
9263 return got_error_msg(GOT_ERR_IO, "wprintw");
9265 wstandend(view->window);
9268 return NULL;
9271 static const struct got_error *
9272 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9274 struct tog_help_view_state *s = &view->state.help;
9275 const struct got_error *err = NULL;
9276 char *line = NULL;
9277 ssize_t linelen;
9278 size_t linesz = 0;
9279 int eos, nscroll;
9281 eos = nscroll = view->nlines;
9282 if (view_is_hsplit_top(view))
9283 --eos; /* border */
9285 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9287 switch (ch) {
9288 case '0':
9289 case '$':
9290 case KEY_RIGHT:
9291 case 'l':
9292 case KEY_LEFT:
9293 case 'h':
9294 horizontal_scroll_input(view, ch);
9295 break;
9296 case 'g':
9297 case KEY_HOME:
9298 s->first_displayed_line = 1;
9299 view->count = 0;
9300 break;
9301 case 'G':
9302 case KEY_END:
9303 view->count = 0;
9304 if (s->eof)
9305 break;
9306 s->first_displayed_line = (s->nlines - eos) + 3;
9307 s->eof = 1;
9308 break;
9309 case 'k':
9310 case KEY_UP:
9311 if (s->first_displayed_line > 1)
9312 --s->first_displayed_line;
9313 else
9314 view->count = 0;
9315 break;
9316 case CTRL('u'):
9317 case 'u':
9318 nscroll /= 2;
9319 /* FALL THROUGH */
9320 case KEY_PPAGE:
9321 case CTRL('b'):
9322 case 'b':
9323 if (s->first_displayed_line == 1) {
9324 view->count = 0;
9325 break;
9327 while (--nscroll > 0 && s->first_displayed_line > 1)
9328 s->first_displayed_line--;
9329 break;
9330 case 'j':
9331 case KEY_DOWN:
9332 case CTRL('n'):
9333 if (!s->eof)
9334 ++s->first_displayed_line;
9335 else
9336 view->count = 0;
9337 break;
9338 case CTRL('d'):
9339 case 'd':
9340 nscroll /= 2;
9341 /* FALL THROUGH */
9342 case KEY_NPAGE:
9343 case CTRL('f'):
9344 case 'f':
9345 case ' ':
9346 if (s->eof) {
9347 view->count = 0;
9348 break;
9350 while (!s->eof && --nscroll > 0) {
9351 linelen = getline(&line, &linesz, s->f);
9352 s->first_displayed_line++;
9353 if (linelen == -1) {
9354 if (feof(s->f))
9355 s->eof = 1;
9356 else
9357 err = got_ferror(s->f, GOT_ERR_IO);
9358 break;
9361 free(line);
9362 break;
9363 default:
9364 view->count = 0;
9365 break;
9368 return err;
9371 static const struct got_error *
9372 close_help_view(struct tog_view *view)
9374 struct tog_help_view_state *s = &view->state.help;
9376 free(s->line_offsets);
9377 s->line_offsets = NULL;
9378 if (fclose(s->f) == EOF)
9379 return got_error_from_errno("fclose");
9381 return NULL;
9384 static const struct got_error *
9385 reset_help_view(struct tog_view *view)
9387 struct tog_help_view_state *s = &view->state.help;
9390 if (s->f && fclose(s->f) == EOF)
9391 return got_error_from_errno("fclose");
9393 wclear(view->window);
9394 view->count = 0;
9395 view->x = 0;
9396 s->all = !s->all;
9397 s->first_displayed_line = 1;
9398 s->last_displayed_line = view->nlines;
9399 s->matched_line = 0;
9401 return create_help(s);
9404 static const struct got_error *
9405 open_help_view(struct tog_view *view, struct tog_view *parent)
9407 const struct got_error *err = NULL;
9408 struct tog_help_view_state *s = &view->state.help;
9410 s->type = (enum tog_keymap_type)parent->type;
9411 s->first_displayed_line = 1;
9412 s->last_displayed_line = view->nlines;
9413 s->selected_line = 1;
9415 view->show = show_help_view;
9416 view->input = input_help_view;
9417 view->reset = reset_help_view;
9418 view->close = close_help_view;
9419 view->search_start = search_start_help_view;
9420 view->search_setup = search_setup_help_view;
9421 view->search_next = search_next_view_match;
9423 err = create_help(s);
9424 return err;
9427 static const struct got_error *
9428 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9429 enum tog_view_type request, int y, int x)
9431 const struct got_error *err = NULL;
9433 *new_view = NULL;
9435 switch (request) {
9436 case TOG_VIEW_DIFF:
9437 if (view->type == TOG_VIEW_LOG) {
9438 struct tog_log_view_state *s = &view->state.log;
9440 err = open_diff_view_for_commit(new_view, y, x,
9441 s->selected_entry->commit, s->selected_entry->id,
9442 view, s->repo);
9443 } else
9444 return got_error_msg(GOT_ERR_NOT_IMPL,
9445 "parent/child view pair not supported");
9446 break;
9447 case TOG_VIEW_BLAME:
9448 if (view->type == TOG_VIEW_TREE) {
9449 struct tog_tree_view_state *s = &view->state.tree;
9451 err = blame_tree_entry(new_view, y, x,
9452 s->selected_entry, &s->parents, s->commit_id,
9453 s->repo);
9454 } else
9455 return got_error_msg(GOT_ERR_NOT_IMPL,
9456 "parent/child view pair not supported");
9457 break;
9458 case TOG_VIEW_LOG:
9459 if (view->type == TOG_VIEW_BLAME)
9460 err = log_annotated_line(new_view, y, x,
9461 view->state.blame.repo, view->state.blame.id_to_log);
9462 else if (view->type == TOG_VIEW_TREE)
9463 err = log_selected_tree_entry(new_view, y, x,
9464 &view->state.tree);
9465 else if (view->type == TOG_VIEW_REF)
9466 err = log_ref_entry(new_view, y, x,
9467 view->state.ref.selected_entry,
9468 view->state.ref.repo);
9469 else
9470 return got_error_msg(GOT_ERR_NOT_IMPL,
9471 "parent/child view pair not supported");
9472 break;
9473 case TOG_VIEW_TREE:
9474 if (view->type == TOG_VIEW_LOG)
9475 err = browse_commit_tree(new_view, y, x,
9476 view->state.log.selected_entry,
9477 view->state.log.in_repo_path,
9478 view->state.log.head_ref_name,
9479 view->state.log.repo);
9480 else if (view->type == TOG_VIEW_REF)
9481 err = browse_ref_tree(new_view, y, x,
9482 view->state.ref.selected_entry,
9483 view->state.ref.repo);
9484 else
9485 return got_error_msg(GOT_ERR_NOT_IMPL,
9486 "parent/child view pair not supported");
9487 break;
9488 case TOG_VIEW_REF:
9489 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9490 if (*new_view == NULL)
9491 return got_error_from_errno("view_open");
9492 if (view->type == TOG_VIEW_LOG)
9493 err = open_ref_view(*new_view, view->state.log.repo);
9494 else if (view->type == TOG_VIEW_TREE)
9495 err = open_ref_view(*new_view, view->state.tree.repo);
9496 else
9497 err = got_error_msg(GOT_ERR_NOT_IMPL,
9498 "parent/child view pair not supported");
9499 if (err)
9500 view_close(*new_view);
9501 break;
9502 case TOG_VIEW_HELP:
9503 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9504 if (*new_view == NULL)
9505 return got_error_from_errno("view_open");
9506 err = open_help_view(*new_view, view);
9507 if (err)
9508 view_close(*new_view);
9509 break;
9510 default:
9511 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9514 return err;
9518 * If view was scrolled down to move the selected line into view when opening a
9519 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9521 static void
9522 offset_selection_up(struct tog_view *view)
9524 switch (view->type) {
9525 case TOG_VIEW_BLAME: {
9526 struct tog_blame_view_state *s = &view->state.blame;
9527 if (s->first_displayed_line == 1) {
9528 s->selected_line = MAX(s->selected_line - view->offset,
9529 1);
9530 break;
9532 if (s->first_displayed_line > view->offset)
9533 s->first_displayed_line -= view->offset;
9534 else
9535 s->first_displayed_line = 1;
9536 s->selected_line += view->offset;
9537 break;
9539 case TOG_VIEW_LOG:
9540 log_scroll_up(&view->state.log, view->offset);
9541 view->state.log.selected += view->offset;
9542 break;
9543 case TOG_VIEW_REF:
9544 ref_scroll_up(&view->state.ref, view->offset);
9545 view->state.ref.selected += view->offset;
9546 break;
9547 case TOG_VIEW_TREE:
9548 tree_scroll_up(&view->state.tree, view->offset);
9549 view->state.tree.selected += view->offset;
9550 break;
9551 default:
9552 break;
9555 view->offset = 0;
9559 * If the selected line is in the section of screen covered by the bottom split,
9560 * scroll down offset lines to move it into view and index its new position.
9562 static const struct got_error *
9563 offset_selection_down(struct tog_view *view)
9565 const struct got_error *err = NULL;
9566 const struct got_error *(*scrolld)(struct tog_view *, int);
9567 int *selected = NULL;
9568 int header, offset;
9570 switch (view->type) {
9571 case TOG_VIEW_BLAME: {
9572 struct tog_blame_view_state *s = &view->state.blame;
9573 header = 3;
9574 scrolld = NULL;
9575 if (s->selected_line > view->nlines - header) {
9576 offset = abs(view->nlines - s->selected_line - header);
9577 s->first_displayed_line += offset;
9578 s->selected_line -= offset;
9579 view->offset = offset;
9581 break;
9583 case TOG_VIEW_LOG: {
9584 struct tog_log_view_state *s = &view->state.log;
9585 scrolld = &log_scroll_down;
9586 header = view_is_parent_view(view) ? 3 : 2;
9587 selected = &s->selected;
9588 break;
9590 case TOG_VIEW_REF: {
9591 struct tog_ref_view_state *s = &view->state.ref;
9592 scrolld = &ref_scroll_down;
9593 header = 3;
9594 selected = &s->selected;
9595 break;
9597 case TOG_VIEW_TREE: {
9598 struct tog_tree_view_state *s = &view->state.tree;
9599 scrolld = &tree_scroll_down;
9600 header = 5;
9601 selected = &s->selected;
9602 break;
9604 default:
9605 selected = NULL;
9606 scrolld = NULL;
9607 header = 0;
9608 break;
9611 if (selected && *selected > view->nlines - header) {
9612 offset = abs(view->nlines - *selected - header);
9613 view->offset = offset;
9614 if (scrolld && offset) {
9615 err = scrolld(view, offset);
9616 *selected -= offset;
9620 return err;
9623 static void
9624 list_commands(FILE *fp)
9626 size_t i;
9628 fprintf(fp, "commands:");
9629 for (i = 0; i < nitems(tog_commands); i++) {
9630 const struct tog_cmd *cmd = &tog_commands[i];
9631 fprintf(fp, " %s", cmd->name);
9633 fputc('\n', fp);
9636 __dead static void
9637 usage(int hflag, int status)
9639 FILE *fp = (status == 0) ? stdout : stderr;
9641 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9642 getprogname());
9643 if (hflag) {
9644 fprintf(fp, "lazy usage: %s path\n", getprogname());
9645 list_commands(fp);
9647 exit(status);
9650 static char **
9651 make_argv(int argc, ...)
9653 va_list ap;
9654 char **argv;
9655 int i;
9657 va_start(ap, argc);
9659 argv = calloc(argc, sizeof(char *));
9660 if (argv == NULL)
9661 err(1, "calloc");
9662 for (i = 0; i < argc; i++) {
9663 argv[i] = strdup(va_arg(ap, char *));
9664 if (argv[i] == NULL)
9665 err(1, "strdup");
9668 va_end(ap);
9669 return argv;
9673 * Try to convert 'tog path' into a 'tog log path' command.
9674 * The user could simply have mistyped the command rather than knowingly
9675 * provided a path. So check whether argv[0] can in fact be resolved
9676 * to a path in the HEAD commit and print a special error if not.
9677 * This hack is for mpi@ <3
9679 static const struct got_error *
9680 tog_log_with_path(int argc, char *argv[])
9682 const struct got_error *error = NULL, *close_err;
9683 const struct tog_cmd *cmd = NULL;
9684 struct got_repository *repo = NULL;
9685 struct got_worktree *worktree = NULL;
9686 struct got_object_id *commit_id = NULL, *id = NULL;
9687 struct got_commit_object *commit = NULL;
9688 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9689 char *commit_id_str = NULL, **cmd_argv = NULL;
9690 int *pack_fds = NULL;
9692 cwd = getcwd(NULL, 0);
9693 if (cwd == NULL)
9694 return got_error_from_errno("getcwd");
9696 error = got_repo_pack_fds_open(&pack_fds);
9697 if (error != NULL)
9698 goto done;
9700 error = got_worktree_open(&worktree, cwd);
9701 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9702 goto done;
9704 if (worktree)
9705 repo_path = strdup(got_worktree_get_repo_path(worktree));
9706 else
9707 repo_path = strdup(cwd);
9708 if (repo_path == NULL) {
9709 error = got_error_from_errno("strdup");
9710 goto done;
9713 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9714 if (error != NULL)
9715 goto done;
9717 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9718 repo, worktree);
9719 if (error)
9720 goto done;
9722 error = tog_load_refs(repo, 0);
9723 if (error)
9724 goto done;
9725 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9726 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9727 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9728 if (error)
9729 goto done;
9731 if (worktree) {
9732 got_worktree_close(worktree);
9733 worktree = NULL;
9736 error = got_object_open_as_commit(&commit, repo, commit_id);
9737 if (error)
9738 goto done;
9740 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9741 if (error) {
9742 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9743 goto done;
9744 fprintf(stderr, "%s: '%s' is no known command or path\n",
9745 getprogname(), argv[0]);
9746 usage(1, 1);
9747 /* not reached */
9750 error = got_object_id_str(&commit_id_str, commit_id);
9751 if (error)
9752 goto done;
9754 cmd = &tog_commands[0]; /* log */
9755 argc = 4;
9756 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9757 error = cmd->cmd_main(argc, cmd_argv);
9758 done:
9759 if (repo) {
9760 close_err = got_repo_close(repo);
9761 if (error == NULL)
9762 error = close_err;
9764 if (commit)
9765 got_object_commit_close(commit);
9766 if (worktree)
9767 got_worktree_close(worktree);
9768 if (pack_fds) {
9769 const struct got_error *pack_err =
9770 got_repo_pack_fds_close(pack_fds);
9771 if (error == NULL)
9772 error = pack_err;
9774 free(id);
9775 free(commit_id_str);
9776 free(commit_id);
9777 free(cwd);
9778 free(repo_path);
9779 free(in_repo_path);
9780 if (cmd_argv) {
9781 int i;
9782 for (i = 0; i < argc; i++)
9783 free(cmd_argv[i]);
9784 free(cmd_argv);
9786 tog_free_refs();
9787 return error;
9790 int
9791 main(int argc, char *argv[])
9793 const struct got_error *io_err, *error = NULL;
9794 const struct tog_cmd *cmd = NULL;
9795 int ch, hflag = 0, Vflag = 0;
9796 char **cmd_argv = NULL;
9797 static const struct option longopts[] = {
9798 { "version", no_argument, NULL, 'V' },
9799 { NULL, 0, NULL, 0}
9801 char *diff_algo_str = NULL;
9802 const char *test_script_path;
9804 setlocale(LC_CTYPE, "");
9807 * Test mode init must happen before pledge() because "tty" will
9808 * not allow TTY-related ioctls to occur via regular files.
9810 test_script_path = getenv("TOG_TEST_SCRIPT");
9811 if (test_script_path != NULL) {
9812 error = init_mock_term(test_script_path);
9813 if (error) {
9814 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9815 return 1;
9817 } else if (!isatty(STDIN_FILENO))
9818 errx(1, "standard input is not a tty");
9820 #if !defined(PROFILE)
9821 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9822 NULL) == -1)
9823 err(1, "pledge");
9824 #endif
9826 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9827 switch (ch) {
9828 case 'h':
9829 hflag = 1;
9830 break;
9831 case 'V':
9832 Vflag = 1;
9833 break;
9834 default:
9835 usage(hflag, 1);
9836 /* NOTREACHED */
9840 argc -= optind;
9841 argv += optind;
9842 optind = 1;
9843 optreset = 1;
9845 if (Vflag) {
9846 got_version_print_str();
9847 return 0;
9850 if (argc == 0) {
9851 if (hflag)
9852 usage(hflag, 0);
9853 /* Build an argument vector which runs a default command. */
9854 cmd = &tog_commands[0];
9855 argc = 1;
9856 cmd_argv = make_argv(argc, cmd->name);
9857 } else {
9858 size_t i;
9860 /* Did the user specify a command? */
9861 for (i = 0; i < nitems(tog_commands); i++) {
9862 if (strncmp(tog_commands[i].name, argv[0],
9863 strlen(argv[0])) == 0) {
9864 cmd = &tog_commands[i];
9865 break;
9870 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9871 if (diff_algo_str) {
9872 if (strcasecmp(diff_algo_str, "patience") == 0)
9873 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9874 if (strcasecmp(diff_algo_str, "myers") == 0)
9875 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9878 if (cmd == NULL) {
9879 if (argc != 1)
9880 usage(0, 1);
9881 /* No command specified; try log with a path */
9882 error = tog_log_with_path(argc, argv);
9883 } else {
9884 if (hflag)
9885 cmd->cmd_usage();
9886 else
9887 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9890 if (using_mock_io) {
9891 io_err = tog_io_close();
9892 if (error == NULL)
9893 error = io_err;
9895 endwin();
9896 if (cmd_argv) {
9897 int i;
9898 for (i = 0; i < argc; i++)
9899 free(cmd_argv[i]);
9900 free(cmd_argv);
9903 if (error && error->code != GOT_ERR_CANCELLED &&
9904 error->code != GOT_ERR_EOF &&
9905 error->code != GOT_ERR_PRIVSEP_EXIT &&
9906 error->code != GOT_ERR_PRIVSEP_PIPE &&
9907 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9908 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9909 return 0;