Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "got_compat.h"
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 #include <sys/ioctl.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #if defined(__FreeBSD__) || defined(__APPLE__)
26 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
27 #endif
28 #include <curses.h>
29 #include <panel.h>
30 #include <locale.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <err.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <wchar.h>
41 #include <time.h>
42 #include <pthread.h>
43 #include <libgen.h>
44 #include <regex.h>
45 #include <sched.h>
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
159 static const struct got_error *
160 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
161 struct got_reference* re2)
163 const char *name1 = got_ref_get_name(re1);
164 const char *name2 = got_ref_get_name(re2);
165 int isbackup1, isbackup2;
167 /* Sort backup refs towards the bottom of the list. */
168 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
169 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
170 if (!isbackup1 && isbackup2) {
171 *cmp = -1;
172 return NULL;
173 } else if (isbackup1 && !isbackup2) {
174 *cmp = 1;
175 return NULL;
178 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
179 return NULL;
182 static const struct got_error *
183 tog_load_refs(struct got_repository *repo, int sort_by_date)
185 const struct got_error *err;
187 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
188 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
189 repo);
190 if (err)
191 return err;
193 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
194 repo);
197 static void
198 tog_free_refs(void)
200 if (tog_refs_idmap) {
201 got_reflist_object_id_map_free(tog_refs_idmap);
202 tog_refs_idmap = NULL;
204 got_ref_list_free(&tog_refs);
207 static const struct got_error *
208 add_color(struct tog_colors *colors, const char *pattern,
209 int idx, short color)
211 const struct got_error *err = NULL;
212 struct tog_color *tc;
213 int regerr = 0;
215 if (idx < 1 || idx > COLOR_PAIRS - 1)
216 return NULL;
218 init_pair(idx, color, -1);
220 tc = calloc(1, sizeof(*tc));
221 if (tc == NULL)
222 return got_error_from_errno("calloc");
223 regerr = regcomp(&tc->regex, pattern,
224 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
225 if (regerr) {
226 static char regerr_msg[512];
227 static char err_msg[512];
228 regerror(regerr, &tc->regex, regerr_msg,
229 sizeof(regerr_msg));
230 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
231 regerr_msg);
232 err = got_error_msg(GOT_ERR_REGEX, err_msg);
233 free(tc);
234 return err;
236 tc->colorpair = idx;
237 STAILQ_INSERT_HEAD(colors, tc, entry);
238 return NULL;
241 static void
242 free_colors(struct tog_colors *colors)
244 struct tog_color *tc;
246 while (!STAILQ_EMPTY(colors)) {
247 tc = STAILQ_FIRST(colors);
248 STAILQ_REMOVE_HEAD(colors, entry);
249 regfree(&tc->regex);
250 free(tc);
254 static struct tog_color *
255 get_color(struct tog_colors *colors, int colorpair)
257 struct tog_color *tc = NULL;
259 STAILQ_FOREACH(tc, colors, entry) {
260 if (tc->colorpair == colorpair)
261 return tc;
264 return NULL;
267 static int
268 default_color_value(const char *envvar)
270 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
271 return COLOR_MAGENTA;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
273 return COLOR_CYAN;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
275 return COLOR_YELLOW;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
277 return COLOR_GREEN;
278 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
279 return COLOR_MAGENTA;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
283 return COLOR_CYAN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
285 return COLOR_GREEN;
286 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
291 return COLOR_YELLOW;
292 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
295 return COLOR_MAGENTA;
296 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
299 return COLOR_CYAN;
301 return -1;
304 static int
305 get_color_value(const char *envvar)
307 const char *val = getenv(envvar);
309 if (val == NULL)
310 return default_color_value(envvar);
312 if (strcasecmp(val, "black") == 0)
313 return COLOR_BLACK;
314 if (strcasecmp(val, "red") == 0)
315 return COLOR_RED;
316 if (strcasecmp(val, "green") == 0)
317 return COLOR_GREEN;
318 if (strcasecmp(val, "yellow") == 0)
319 return COLOR_YELLOW;
320 if (strcasecmp(val, "blue") == 0)
321 return COLOR_BLUE;
322 if (strcasecmp(val, "magenta") == 0)
323 return COLOR_MAGENTA;
324 if (strcasecmp(val, "cyan") == 0)
325 return COLOR_CYAN;
326 if (strcasecmp(val, "white") == 0)
327 return COLOR_WHITE;
328 if (strcasecmp(val, "default") == 0)
329 return -1;
331 return default_color_value(envvar);
334 struct tog_diff_view_state {
335 struct got_object_id *id1, *id2;
336 const char *label1, *label2;
337 FILE *f, *f1, *f2;
338 int fd1, fd2;
339 int lineno;
340 int first_displayed_line;
341 int last_displayed_line;
342 int eof;
343 int diff_context;
344 int ignore_whitespace;
345 int force_text_diff;
346 struct got_repository *repo;
347 struct got_diff_line *lines;
348 size_t nlines;
349 int matched_line;
350 int selected_line;
352 /* passed from log or blame view; may be NULL */
353 struct tog_view *parent_view;
354 };
356 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
357 static volatile sig_atomic_t tog_thread_error;
359 struct tog_log_thread_args {
360 pthread_cond_t need_commits;
361 pthread_cond_t commit_loaded;
362 int commits_needed;
363 int load_all;
364 struct got_commit_graph *graph;
365 struct commit_queue *real_commits;
366 const char *in_repo_path;
367 struct got_object_id *start_id;
368 struct got_repository *repo;
369 int *pack_fds;
370 int log_complete;
371 sig_atomic_t *quit;
372 struct commit_queue_entry **first_displayed_entry;
373 struct commit_queue_entry **selected_entry;
374 int *searching;
375 int *search_next_done;
376 regex_t *regex;
377 int *limiting;
378 int limit_match;
379 regex_t *limit_regex;
380 struct commit_queue *limit_commits;
381 };
383 struct tog_log_view_state {
384 struct commit_queue *commits;
385 struct commit_queue_entry *first_displayed_entry;
386 struct commit_queue_entry *last_displayed_entry;
387 struct commit_queue_entry *selected_entry;
388 struct commit_queue real_commits;
389 int selected;
390 char *in_repo_path;
391 char *head_ref_name;
392 int log_branches;
393 struct got_repository *repo;
394 struct got_object_id *start_id;
395 sig_atomic_t quit;
396 pthread_t thread;
397 struct tog_log_thread_args thread_args;
398 struct commit_queue_entry *matched_entry;
399 struct commit_queue_entry *search_entry;
400 struct tog_colors colors;
401 int use_committer;
402 int limit_view;
403 regex_t limit_regex;
404 struct commit_queue limit_commits;
405 };
407 #define TOG_COLOR_DIFF_MINUS 1
408 #define TOG_COLOR_DIFF_PLUS 2
409 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
410 #define TOG_COLOR_DIFF_META 4
411 #define TOG_COLOR_TREE_SUBMODULE 5
412 #define TOG_COLOR_TREE_SYMLINK 6
413 #define TOG_COLOR_TREE_DIRECTORY 7
414 #define TOG_COLOR_TREE_EXECUTABLE 8
415 #define TOG_COLOR_COMMIT 9
416 #define TOG_COLOR_AUTHOR 10
417 #define TOG_COLOR_DATE 11
418 #define TOG_COLOR_REFS_HEADS 12
419 #define TOG_COLOR_REFS_TAGS 13
420 #define TOG_COLOR_REFS_REMOTES 14
421 #define TOG_COLOR_REFS_BACKUP 15
423 struct tog_blame_cb_args {
424 struct tog_blame_line *lines; /* one per line */
425 int nlines;
427 struct tog_view *view;
428 struct got_object_id *commit_id;
429 int *quit;
430 };
432 struct tog_blame_thread_args {
433 const char *path;
434 struct got_repository *repo;
435 struct tog_blame_cb_args *cb_args;
436 int *complete;
437 got_cancel_cb cancel_cb;
438 void *cancel_arg;
439 pthread_cond_t blame_complete;
440 };
442 struct tog_blame {
443 FILE *f;
444 off_t filesize;
445 struct tog_blame_line *lines;
446 int nlines;
447 off_t *line_offsets;
448 pthread_t thread;
449 struct tog_blame_thread_args thread_args;
450 struct tog_blame_cb_args cb_args;
451 const char *path;
452 int *pack_fds;
453 };
455 struct tog_blame_view_state {
456 int first_displayed_line;
457 int last_displayed_line;
458 int selected_line;
459 int last_diffed_line;
460 int blame_complete;
461 int eof;
462 int done;
463 struct got_object_id_queue blamed_commits;
464 struct got_object_qid *blamed_commit;
465 char *path;
466 struct got_repository *repo;
467 struct got_object_id *commit_id;
468 struct got_object_id *id_to_log;
469 struct tog_blame blame;
470 int matched_line;
471 struct tog_colors colors;
472 };
474 struct tog_parent_tree {
475 TAILQ_ENTRY(tog_parent_tree) entry;
476 struct got_tree_object *tree;
477 struct got_tree_entry *first_displayed_entry;
478 struct got_tree_entry *selected_entry;
479 int selected;
480 };
482 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
484 struct tog_tree_view_state {
485 char *tree_label;
486 struct got_object_id *commit_id;/* commit which this tree belongs to */
487 struct got_tree_object *root; /* the commit's root tree entry */
488 struct got_tree_object *tree; /* currently displayed (sub-)tree */
489 struct got_tree_entry *first_displayed_entry;
490 struct got_tree_entry *last_displayed_entry;
491 struct got_tree_entry *selected_entry;
492 int ndisplayed, selected, show_ids;
493 struct tog_parent_trees parents; /* parent trees of current sub-tree */
494 char *head_ref_name;
495 struct got_repository *repo;
496 struct got_tree_entry *matched_entry;
497 struct tog_colors colors;
498 };
500 struct tog_reflist_entry {
501 TAILQ_ENTRY(tog_reflist_entry) entry;
502 struct got_reference *ref;
503 int idx;
504 };
506 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
508 struct tog_ref_view_state {
509 struct tog_reflist_head refs;
510 struct tog_reflist_entry *first_displayed_entry;
511 struct tog_reflist_entry *last_displayed_entry;
512 struct tog_reflist_entry *selected_entry;
513 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
514 struct got_repository *repo;
515 struct tog_reflist_entry *matched_entry;
516 struct tog_colors colors;
517 };
519 struct tog_help_view_state {
520 FILE *f;
521 off_t *line_offsets;
522 size_t nlines;
523 int lineno;
524 int first_displayed_line;
525 int last_displayed_line;
526 int eof;
527 int matched_line;
528 int selected_line;
529 int all;
530 enum tog_keymap_type type;
531 };
533 #define GENERATE_HELP \
534 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
535 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
536 KEY_("k C-p Up", "Move cursor or page up one line"), \
537 KEY_("j C-n Down", "Move cursor or page down one line"), \
538 KEY_("C-b b PgUp", "Scroll the view up one page"), \
539 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
540 KEY_("C-u u", "Scroll the view up one half page"), \
541 KEY_("C-d d", "Scroll the view down one half page"), \
542 KEY_("g", "Go to line N (default: first line)"), \
543 KEY_("Home =", "Go to the first line"), \
544 KEY_("G", "Go to line N (default: last line)"), \
545 KEY_("End *", "Go to the last line"), \
546 KEY_("l Right", "Scroll the view right"), \
547 KEY_("h Left", "Scroll the view left"), \
548 KEY_("$", "Scroll view to the rightmost position"), \
549 KEY_("0", "Scroll view to the leftmost position"), \
550 KEY_("-", "Decrease size of the focussed split"), \
551 KEY_("+", "Increase size of the focussed split"), \
552 KEY_("Tab", "Switch focus between views"), \
553 KEY_("F", "Toggle fullscreen mode"), \
554 KEY_("S", "Switch split-screen layout"), \
555 KEY_("/", "Open prompt to enter search term"), \
556 KEY_("n", "Find next line/token matching the current search term"), \
557 KEY_("N", "Find previous line/token matching the current search term"),\
558 KEY_("q", "Quit the focussed view; Quit help screen"), \
559 KEY_("Q", "Quit tog"), \
561 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
562 KEY_("< ,", "Move cursor up one commit"), \
563 KEY_("> .", "Move cursor down one commit"), \
564 KEY_("Enter", "Open diff view of the selected commit"), \
565 KEY_("B", "Reload the log view and toggle display of merged commits"), \
566 KEY_("R", "Open ref view of all repository references"), \
567 KEY_("T", "Display tree view of the repository from the selected" \
568 " commit"), \
569 KEY_("@", "Toggle between displaying author and committer name"), \
570 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
571 KEY_("C-g Backspace", "Cancel current search or log operation"), \
572 KEY_("C-l", "Reload the log view with new commits in the repository"), \
574 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
575 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
576 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
577 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
578 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
579 " data"), \
580 KEY_("(", "Go to the previous file in the diff"), \
581 KEY_(")", "Go to the next file in the diff"), \
582 KEY_("{", "Go to the previous hunk in the diff"), \
583 KEY_("}", "Go to the next hunk in the diff"), \
584 KEY_("[", "Decrease the number of context lines"), \
585 KEY_("]", "Increase the number of context lines"), \
586 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
588 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
589 KEY_("Enter", "Display diff view of the selected line's commit"), \
590 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
591 KEY_("L", "Open log view for the currently selected annotated line"), \
592 KEY_("C", "Reload view with the previously blamed commit"), \
593 KEY_("c", "Reload view with the version of the file found in the" \
594 " selected line's commit"), \
595 KEY_("p", "Reload view with the version of the file found in the" \
596 " selected line's parent commit"), \
598 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
599 KEY_("Enter", "Enter selected directory or open blame view of the" \
600 " selected file"), \
601 KEY_("L", "Open log view for the selected entry"), \
602 KEY_("R", "Open ref view of all repository references"), \
603 KEY_("i", "Show object IDs for all tree entries"), \
604 KEY_("Backspace", "Return to the parent directory"), \
606 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
607 KEY_("Enter", "Display log view of the selected reference"), \
608 KEY_("T", "Display tree view of the selected reference"), \
609 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
610 KEY_("m", "Toggle display of last modified date for each reference"), \
611 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
612 KEY_("C-l", "Reload view with all repository references")
614 struct tog_key_map {
615 const char *keys;
616 const char *info;
617 enum tog_keymap_type type;
618 };
620 /* curses io for tog regress */
621 struct tog_io {
622 FILE *cin;
623 FILE *cout;
624 FILE *f;
625 FILE *sdump;
626 int wait_for_ui;
627 } tog_io;
628 static int using_mock_io;
630 #define TOG_KEY_SCRDUMP SHRT_MIN
632 /*
633 * We implement two types of views: parent views and child views.
635 * The 'Tab' key switches focus between a parent view and its child view.
636 * Child views are shown side-by-side to their parent view, provided
637 * there is enough screen estate.
639 * When a new view is opened from within a parent view, this new view
640 * becomes a child view of the parent view, replacing any existing child.
642 * When a new view is opened from within a child view, this new view
643 * becomes a parent view which will obscure the views below until the
644 * user quits the new parent view by typing 'q'.
646 * This list of views contains parent views only.
647 * Child views are only pointed to by their parent view.
648 */
649 TAILQ_HEAD(tog_view_list_head, tog_view);
651 struct tog_view {
652 TAILQ_ENTRY(tog_view) entry;
653 WINDOW *window;
654 PANEL *panel;
655 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
656 int resized_y, resized_x; /* begin_y/x based on user resizing */
657 int maxx, x; /* max column and current start column */
658 int lines, cols; /* copies of LINES and COLS */
659 int nscrolled, offset; /* lines scrolled and hsplit line offset */
660 int gline, hiline; /* navigate to and highlight this nG line */
661 int ch, count; /* current keymap and count prefix */
662 int resized; /* set when in a resize event */
663 int focussed; /* Only set on one parent or child view at a time. */
664 int dying;
665 struct tog_view *parent;
666 struct tog_view *child;
668 /*
669 * This flag is initially set on parent views when a new child view
670 * is created. It gets toggled when the 'Tab' key switches focus
671 * between parent and child.
672 * The flag indicates whether focus should be passed on to our child
673 * view if this parent view gets picked for focus after another parent
674 * view was closed. This prevents child views from losing focus in such
675 * situations.
676 */
677 int focus_child;
679 enum tog_view_mode mode;
680 /* type-specific state */
681 enum tog_view_type type;
682 union {
683 struct tog_diff_view_state diff;
684 struct tog_log_view_state log;
685 struct tog_blame_view_state blame;
686 struct tog_tree_view_state tree;
687 struct tog_ref_view_state ref;
688 struct tog_help_view_state help;
689 } state;
691 const struct got_error *(*show)(struct tog_view *);
692 const struct got_error *(*input)(struct tog_view **,
693 struct tog_view *, int);
694 const struct got_error *(*reset)(struct tog_view *);
695 const struct got_error *(*resize)(struct tog_view *, int);
696 const struct got_error *(*close)(struct tog_view *);
698 const struct got_error *(*search_start)(struct tog_view *);
699 const struct got_error *(*search_next)(struct tog_view *);
700 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
701 int **, int **, int **, int **);
702 int search_started;
703 int searching;
704 #define TOG_SEARCH_FORWARD 1
705 #define TOG_SEARCH_BACKWARD 2
706 int search_next_done;
707 #define TOG_SEARCH_HAVE_MORE 1
708 #define TOG_SEARCH_NO_MORE 2
709 #define TOG_SEARCH_HAVE_NONE 3
710 regex_t regex;
711 regmatch_t regmatch;
712 const char *action;
713 };
715 static const struct got_error *open_diff_view(struct tog_view *,
716 struct got_object_id *, struct got_object_id *,
717 const char *, const char *, int, int, int, struct tog_view *,
718 struct got_repository *);
719 static const struct got_error *show_diff_view(struct tog_view *);
720 static const struct got_error *input_diff_view(struct tog_view **,
721 struct tog_view *, int);
722 static const struct got_error *reset_diff_view(struct tog_view *);
723 static const struct got_error* close_diff_view(struct tog_view *);
724 static const struct got_error *search_start_diff_view(struct tog_view *);
725 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
726 size_t *, int **, int **, int **, int **);
727 static const struct got_error *search_next_view_match(struct tog_view *);
729 static const struct got_error *open_log_view(struct tog_view *,
730 struct got_object_id *, struct got_repository *,
731 const char *, const char *, int);
732 static const struct got_error * show_log_view(struct tog_view *);
733 static const struct got_error *input_log_view(struct tog_view **,
734 struct tog_view *, int);
735 static const struct got_error *resize_log_view(struct tog_view *, int);
736 static const struct got_error *close_log_view(struct tog_view *);
737 static const struct got_error *search_start_log_view(struct tog_view *);
738 static const struct got_error *search_next_log_view(struct tog_view *);
740 static const struct got_error *open_blame_view(struct tog_view *, char *,
741 struct got_object_id *, struct got_repository *);
742 static const struct got_error *show_blame_view(struct tog_view *);
743 static const struct got_error *input_blame_view(struct tog_view **,
744 struct tog_view *, int);
745 static const struct got_error *reset_blame_view(struct tog_view *);
746 static const struct got_error *close_blame_view(struct tog_view *);
747 static const struct got_error *search_start_blame_view(struct tog_view *);
748 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
749 size_t *, int **, int **, int **, int **);
751 static const struct got_error *open_tree_view(struct tog_view *,
752 struct got_object_id *, const char *, struct got_repository *);
753 static const struct got_error *show_tree_view(struct tog_view *);
754 static const struct got_error *input_tree_view(struct tog_view **,
755 struct tog_view *, int);
756 static const struct got_error *close_tree_view(struct tog_view *);
757 static const struct got_error *search_start_tree_view(struct tog_view *);
758 static const struct got_error *search_next_tree_view(struct tog_view *);
760 static const struct got_error *open_ref_view(struct tog_view *,
761 struct got_repository *);
762 static const struct got_error *show_ref_view(struct tog_view *);
763 static const struct got_error *input_ref_view(struct tog_view **,
764 struct tog_view *, int);
765 static const struct got_error *close_ref_view(struct tog_view *);
766 static const struct got_error *search_start_ref_view(struct tog_view *);
767 static const struct got_error *search_next_ref_view(struct tog_view *);
769 static const struct got_error *open_help_view(struct tog_view *,
770 struct tog_view *);
771 static const struct got_error *show_help_view(struct tog_view *);
772 static const struct got_error *input_help_view(struct tog_view **,
773 struct tog_view *, int);
774 static const struct got_error *reset_help_view(struct tog_view *);
775 static const struct got_error* close_help_view(struct tog_view *);
776 static const struct got_error *search_start_help_view(struct tog_view *);
777 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
778 size_t *, int **, int **, int **, int **);
780 static volatile sig_atomic_t tog_sigwinch_received;
781 static volatile sig_atomic_t tog_sigpipe_received;
782 static volatile sig_atomic_t tog_sigcont_received;
783 static volatile sig_atomic_t tog_sigint_received;
784 static volatile sig_atomic_t tog_sigterm_received;
786 static void
787 tog_sigwinch(int signo)
789 tog_sigwinch_received = 1;
792 static void
793 tog_sigpipe(int signo)
795 tog_sigpipe_received = 1;
798 static void
799 tog_sigcont(int signo)
801 tog_sigcont_received = 1;
804 static void
805 tog_sigint(int signo)
807 tog_sigint_received = 1;
810 static void
811 tog_sigterm(int signo)
813 tog_sigterm_received = 1;
816 static int
817 tog_fatal_signal_received(void)
819 return (tog_sigpipe_received ||
820 tog_sigint_received || tog_sigterm_received);
823 static const struct got_error *
824 view_close(struct tog_view *view)
826 const struct got_error *err = NULL, *child_err = NULL;
828 if (view->child) {
829 child_err = view_close(view->child);
830 view->child = NULL;
832 if (view->close)
833 err = view->close(view);
834 if (view->panel)
835 del_panel(view->panel);
836 if (view->window)
837 delwin(view->window);
838 free(view);
839 return err ? err : child_err;
842 static struct tog_view *
843 view_open(int nlines, int ncols, int begin_y, int begin_x,
844 enum tog_view_type type)
846 struct tog_view *view = calloc(1, sizeof(*view));
848 if (view == NULL)
849 return NULL;
851 view->type = type;
852 view->lines = LINES;
853 view->cols = COLS;
854 view->nlines = nlines ? nlines : LINES - begin_y;
855 view->ncols = ncols ? ncols : COLS - begin_x;
856 view->begin_y = begin_y;
857 view->begin_x = begin_x;
858 view->window = newwin(nlines, ncols, begin_y, begin_x);
859 if (view->window == NULL) {
860 view_close(view);
861 return NULL;
863 view->panel = new_panel(view->window);
864 if (view->panel == NULL ||
865 set_panel_userptr(view->panel, view) != OK) {
866 view_close(view);
867 return NULL;
870 keypad(view->window, TRUE);
871 return view;
874 static int
875 view_split_begin_x(int begin_x)
877 if (begin_x > 0 || COLS < 120)
878 return 0;
879 return (COLS - MAX(COLS / 2, 80));
882 /* XXX Stub till we decide what to do. */
883 static int
884 view_split_begin_y(int lines)
886 return lines * HSPLIT_SCALE;
889 static const struct got_error *view_resize(struct tog_view *);
891 static const struct got_error *
892 view_splitscreen(struct tog_view *view)
894 const struct got_error *err = NULL;
896 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
897 if (view->resized_y && view->resized_y < view->lines)
898 view->begin_y = view->resized_y;
899 else
900 view->begin_y = view_split_begin_y(view->nlines);
901 view->begin_x = 0;
902 } else if (!view->resized) {
903 if (view->resized_x && view->resized_x < view->cols - 1 &&
904 view->cols > 119)
905 view->begin_x = view->resized_x;
906 else
907 view->begin_x = view_split_begin_x(0);
908 view->begin_y = 0;
910 view->nlines = LINES - view->begin_y;
911 view->ncols = COLS - view->begin_x;
912 view->lines = LINES;
913 view->cols = COLS;
914 err = view_resize(view);
915 if (err)
916 return err;
918 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
919 view->parent->nlines = view->begin_y;
921 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
922 return got_error_from_errno("mvwin");
924 return NULL;
927 static const struct got_error *
928 view_fullscreen(struct tog_view *view)
930 const struct got_error *err = NULL;
932 view->begin_x = 0;
933 view->begin_y = view->resized ? view->begin_y : 0;
934 view->nlines = view->resized ? view->nlines : LINES;
935 view->ncols = COLS;
936 view->lines = LINES;
937 view->cols = COLS;
938 err = view_resize(view);
939 if (err)
940 return err;
942 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
943 return got_error_from_errno("mvwin");
945 return NULL;
948 static int
949 view_is_parent_view(struct tog_view *view)
951 return view->parent == NULL;
954 static int
955 view_is_splitscreen(struct tog_view *view)
957 return view->begin_x > 0 || view->begin_y > 0;
960 static int
961 view_is_fullscreen(struct tog_view *view)
963 return view->nlines == LINES && view->ncols == COLS;
966 static int
967 view_is_hsplit_top(struct tog_view *view)
969 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
970 view_is_splitscreen(view->child);
973 static void
974 view_border(struct tog_view *view)
976 PANEL *panel;
977 const struct tog_view *view_above;
979 if (view->parent)
980 return view_border(view->parent);
982 panel = panel_above(view->panel);
983 if (panel == NULL)
984 return;
986 view_above = panel_userptr(panel);
987 if (view->mode == TOG_VIEW_SPLIT_HRZN)
988 mvwhline(view->window, view_above->begin_y - 1,
989 view->begin_x, ACS_HLINE, view->ncols);
990 else
991 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
992 ACS_VLINE, view->nlines);
995 static const struct got_error *view_init_hsplit(struct tog_view *, int);
996 static const struct got_error *request_log_commits(struct tog_view *);
997 static const struct got_error *offset_selection_down(struct tog_view *);
998 static void offset_selection_up(struct tog_view *);
999 static void view_get_split(struct tog_view *, int *, int *);
1001 static const struct got_error *
1002 view_resize(struct tog_view *view)
1004 const struct got_error *err = NULL;
1005 int dif, nlines, ncols;
1007 dif = LINES - view->lines; /* line difference */
1009 if (view->lines > LINES)
1010 nlines = view->nlines - (view->lines - LINES);
1011 else
1012 nlines = view->nlines + (LINES - view->lines);
1013 if (view->cols > COLS)
1014 ncols = view->ncols - (view->cols - COLS);
1015 else
1016 ncols = view->ncols + (COLS - view->cols);
1018 if (view->child) {
1019 int hs = view->child->begin_y;
1021 if (!view_is_fullscreen(view))
1022 view->child->begin_x = view_split_begin_x(view->begin_x);
1023 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1024 view->child->begin_x == 0) {
1025 ncols = COLS;
1027 view_fullscreen(view->child);
1028 if (view->child->focussed)
1029 show_panel(view->child->panel);
1030 else
1031 show_panel(view->panel);
1032 } else {
1033 ncols = view->child->begin_x;
1035 view_splitscreen(view->child);
1036 show_panel(view->child->panel);
1039 * XXX This is ugly and needs to be moved into the above
1040 * logic but "works" for now and my attempts at moving it
1041 * break either 'tab' or 'F' key maps in horizontal splits.
1043 if (hs) {
1044 err = view_splitscreen(view->child);
1045 if (err)
1046 return err;
1047 if (dif < 0) { /* top split decreased */
1048 err = offset_selection_down(view);
1049 if (err)
1050 return err;
1052 view_border(view);
1053 update_panels();
1054 doupdate();
1055 show_panel(view->child->panel);
1056 nlines = view->nlines;
1058 } else if (view->parent == NULL)
1059 ncols = COLS;
1061 if (view->resize && dif > 0) {
1062 err = view->resize(view, dif);
1063 if (err)
1064 return err;
1067 if (wresize(view->window, nlines, ncols) == ERR)
1068 return got_error_from_errno("wresize");
1069 if (replace_panel(view->panel, view->window) == ERR)
1070 return got_error_from_errno("replace_panel");
1071 wclear(view->window);
1073 view->nlines = nlines;
1074 view->ncols = ncols;
1075 view->lines = LINES;
1076 view->cols = COLS;
1078 return NULL;
1081 static const struct got_error *
1082 resize_log_view(struct tog_view *view, int increase)
1084 struct tog_log_view_state *s = &view->state.log;
1085 const struct got_error *err = NULL;
1086 int n = 0;
1088 if (s->selected_entry)
1089 n = s->selected_entry->idx + view->lines - s->selected;
1092 * Request commits to account for the increased
1093 * height so we have enough to populate the view.
1095 if (s->commits->ncommits < n) {
1096 view->nscrolled = n - s->commits->ncommits + increase + 1;
1097 err = request_log_commits(view);
1100 return err;
1103 static void
1104 view_adjust_offset(struct tog_view *view, int n)
1106 if (n == 0)
1107 return;
1109 if (view->parent && view->parent->offset) {
1110 if (view->parent->offset + n >= 0)
1111 view->parent->offset += n;
1112 else
1113 view->parent->offset = 0;
1114 } else if (view->offset) {
1115 if (view->offset - n >= 0)
1116 view->offset -= n;
1117 else
1118 view->offset = 0;
1122 static const struct got_error *
1123 view_resize_split(struct tog_view *view, int resize)
1125 const struct got_error *err = NULL;
1126 struct tog_view *v = NULL;
1128 if (view->parent)
1129 v = view->parent;
1130 else
1131 v = view;
1133 if (!v->child || !view_is_splitscreen(v->child))
1134 return NULL;
1136 v->resized = v->child->resized = resize; /* lock for resize event */
1138 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1139 if (v->child->resized_y)
1140 v->child->begin_y = v->child->resized_y;
1141 if (view->parent)
1142 v->child->begin_y -= resize;
1143 else
1144 v->child->begin_y += resize;
1145 if (v->child->begin_y < 3) {
1146 view->count = 0;
1147 v->child->begin_y = 3;
1148 } else if (v->child->begin_y > LINES - 1) {
1149 view->count = 0;
1150 v->child->begin_y = LINES - 1;
1152 v->ncols = COLS;
1153 v->child->ncols = COLS;
1154 view_adjust_offset(view, resize);
1155 err = view_init_hsplit(v, v->child->begin_y);
1156 if (err)
1157 return err;
1158 v->child->resized_y = v->child->begin_y;
1159 } else {
1160 if (v->child->resized_x)
1161 v->child->begin_x = v->child->resized_x;
1162 if (view->parent)
1163 v->child->begin_x -= resize;
1164 else
1165 v->child->begin_x += resize;
1166 if (v->child->begin_x < 11) {
1167 view->count = 0;
1168 v->child->begin_x = 11;
1169 } else if (v->child->begin_x > COLS - 1) {
1170 view->count = 0;
1171 v->child->begin_x = COLS - 1;
1173 v->child->resized_x = v->child->begin_x;
1176 v->child->mode = v->mode;
1177 v->child->nlines = v->lines - v->child->begin_y;
1178 v->child->ncols = v->cols - v->child->begin_x;
1179 v->focus_child = 1;
1181 err = view_fullscreen(v);
1182 if (err)
1183 return err;
1184 err = view_splitscreen(v->child);
1185 if (err)
1186 return err;
1188 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1189 err = offset_selection_down(v->child);
1190 if (err)
1191 return err;
1194 if (v->resize)
1195 err = v->resize(v, 0);
1196 else if (v->child->resize)
1197 err = v->child->resize(v->child, 0);
1199 v->resized = v->child->resized = 0;
1201 return err;
1204 static void
1205 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1207 struct tog_view *v = src->child ? src->child : src;
1209 dst->resized_x = v->resized_x;
1210 dst->resized_y = v->resized_y;
1213 static const struct got_error *
1214 view_close_child(struct tog_view *view)
1216 const struct got_error *err = NULL;
1218 if (view->child == NULL)
1219 return NULL;
1221 err = view_close(view->child);
1222 view->child = NULL;
1223 return err;
1226 static const struct got_error *
1227 view_set_child(struct tog_view *view, struct tog_view *child)
1229 const struct got_error *err = NULL;
1231 view->child = child;
1232 child->parent = view;
1234 err = view_resize(view);
1235 if (err)
1236 return err;
1238 if (view->child->resized_x || view->child->resized_y)
1239 err = view_resize_split(view, 0);
1241 return err;
1244 static const struct got_error *view_dispatch_request(struct tog_view **,
1245 struct tog_view *, enum tog_view_type, int, int);
1247 static const struct got_error *
1248 view_request_new(struct tog_view **requested, struct tog_view *view,
1249 enum tog_view_type request)
1251 struct tog_view *new_view = NULL;
1252 const struct got_error *err;
1253 int y = 0, x = 0;
1255 *requested = NULL;
1257 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1258 view_get_split(view, &y, &x);
1260 err = view_dispatch_request(&new_view, view, request, y, x);
1261 if (err)
1262 return err;
1264 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1265 request != TOG_VIEW_HELP) {
1266 err = view_init_hsplit(view, y);
1267 if (err)
1268 return err;
1271 view->focussed = 0;
1272 new_view->focussed = 1;
1273 new_view->mode = view->mode;
1274 new_view->nlines = request == TOG_VIEW_HELP ?
1275 view->lines : view->lines - y;
1277 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1278 view_transfer_size(new_view, view);
1279 err = view_close_child(view);
1280 if (err)
1281 return err;
1282 err = view_set_child(view, new_view);
1283 if (err)
1284 return err;
1285 view->focus_child = 1;
1286 } else
1287 *requested = new_view;
1289 return NULL;
1292 static void
1293 tog_resizeterm(void)
1295 int cols, lines;
1296 struct winsize size;
1298 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1299 cols = 80; /* Default */
1300 lines = 24;
1301 } else {
1302 cols = size.ws_col;
1303 lines = size.ws_row;
1305 resize_term(lines, cols);
1308 static const struct got_error *
1309 view_search_start(struct tog_view *view, int fast_refresh)
1311 const struct got_error *err = NULL;
1312 struct tog_view *v = view;
1313 char pattern[1024];
1314 int ret;
1316 if (view->search_started) {
1317 regfree(&view->regex);
1318 view->searching = 0;
1319 memset(&view->regmatch, 0, sizeof(view->regmatch));
1321 view->search_started = 0;
1323 if (view->nlines < 1)
1324 return NULL;
1326 if (view_is_hsplit_top(view))
1327 v = view->child;
1328 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1329 v = view->parent;
1331 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1332 wclrtoeol(v->window);
1334 nodelay(v->window, FALSE); /* block for search term input */
1335 nocbreak();
1336 echo();
1337 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1338 wrefresh(v->window);
1339 cbreak();
1340 noecho();
1341 nodelay(v->window, TRUE);
1342 if (!fast_refresh && !using_mock_io)
1343 halfdelay(10);
1344 if (ret == ERR)
1345 return NULL;
1347 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1348 err = view->search_start(view);
1349 if (err) {
1350 regfree(&view->regex);
1351 return err;
1353 view->search_started = 1;
1354 view->searching = TOG_SEARCH_FORWARD;
1355 view->search_next_done = 0;
1356 view->search_next(view);
1359 return NULL;
1362 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1363 static const struct got_error *
1364 switch_split(struct tog_view *view)
1366 const struct got_error *err = NULL;
1367 struct tog_view *v = NULL;
1369 if (view->parent)
1370 v = view->parent;
1371 else
1372 v = view;
1374 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1375 v->mode = TOG_VIEW_SPLIT_VERT;
1376 else
1377 v->mode = TOG_VIEW_SPLIT_HRZN;
1379 if (!v->child)
1380 return NULL;
1381 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1382 v->mode = TOG_VIEW_SPLIT_NONE;
1384 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1385 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1386 v->child->begin_y = v->child->resized_y;
1387 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1388 v->child->begin_x = v->child->resized_x;
1391 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1392 v->ncols = COLS;
1393 v->child->ncols = COLS;
1394 v->child->nscrolled = LINES - v->child->nlines;
1396 err = view_init_hsplit(v, v->child->begin_y);
1397 if (err)
1398 return err;
1400 v->child->mode = v->mode;
1401 v->child->nlines = v->lines - v->child->begin_y;
1402 v->focus_child = 1;
1404 err = view_fullscreen(v);
1405 if (err)
1406 return err;
1407 err = view_splitscreen(v->child);
1408 if (err)
1409 return err;
1411 if (v->mode == TOG_VIEW_SPLIT_NONE)
1412 v->mode = TOG_VIEW_SPLIT_VERT;
1413 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1414 err = offset_selection_down(v);
1415 if (err)
1416 return err;
1417 err = offset_selection_down(v->child);
1418 if (err)
1419 return err;
1420 } else {
1421 offset_selection_up(v);
1422 offset_selection_up(v->child);
1424 if (v->resize)
1425 err = v->resize(v, 0);
1426 else if (v->child->resize)
1427 err = v->child->resize(v->child, 0);
1429 return err;
1433 * Strip trailing whitespace from str starting at byte *n;
1434 * if *n < 0, use strlen(str). Return new str length in *n.
1436 static void
1437 strip_trailing_ws(char *str, int *n)
1439 size_t x = *n;
1441 if (str == NULL || *str == '\0')
1442 return;
1444 if (x < 0)
1445 x = strlen(str);
1447 while (x-- > 0 && isspace((unsigned char)str[x]))
1448 str[x] = '\0';
1450 *n = x + 1;
1454 * Extract visible substring of line y from the curses screen
1455 * and strip trailing whitespace. If vline is set, overwrite
1456 * line[vline] with '|' because the ACS_VLINE character is
1457 * written out as 'x'. Write the line to file f.
1459 static const struct got_error *
1460 view_write_line(FILE *f, int y, int vline)
1462 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1463 int r, w;
1465 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1466 if (r == ERR)
1467 return got_error_fmt(GOT_ERR_RANGE,
1468 "failed to extract line %d", y);
1471 * In some views, lines are padded with blanks to COLS width.
1472 * Strip them so we can diff without the -b flag when testing.
1474 strip_trailing_ws(line, &r);
1476 if (vline > 0)
1477 line[vline] = '|';
1479 w = fprintf(f, "%s\n", line);
1480 if (w != r + 1) /* \n */
1481 return got_ferror(f, GOT_ERR_IO);
1483 return NULL;
1487 * Capture the visible curses screen by writing each line to the
1488 * file at the path set via the TOG_SCR_DUMP environment variable.
1490 static const struct got_error *
1491 screendump(struct tog_view *view)
1493 const struct got_error *err;
1494 int i;
1496 err = got_opentemp_truncate(tog_io.sdump);
1497 if (err)
1498 return err;
1500 if ((view->child && view->child->begin_x) ||
1501 (view->parent && view->begin_x)) {
1502 int ncols = view->child ? view->ncols : view->parent->ncols;
1504 /* vertical splitscreen */
1505 for (i = 0; i < view->nlines; ++i) {
1506 err = view_write_line(tog_io.sdump, i, ncols - 1);
1507 if (err)
1508 goto done;
1510 } else {
1511 int hline = 0;
1513 /* fullscreen or horizontal splitscreen */
1514 if ((view->child && view->child->begin_y) ||
1515 (view->parent && view->begin_y)) /* hsplit */
1516 hline = view->child ?
1517 view->child->begin_y : view->begin_y;
1519 for (i = 0; i < view->lines; i++) {
1520 if (hline && i == hline - 1) {
1521 int c;
1523 /* ACS_HLINE writes out as 'q', overwrite it */
1524 for (c = 0; c < view->cols; ++c)
1525 fputc('-', tog_io.sdump);
1526 fputc('\n', tog_io.sdump);
1527 continue;
1530 err = view_write_line(tog_io.sdump, i, 0);
1531 if (err)
1532 goto done;
1536 done:
1537 return err;
1541 * Compute view->count from numeric input. Assign total to view->count and
1542 * return first non-numeric key entered.
1544 static int
1545 get_compound_key(struct tog_view *view, int c)
1547 struct tog_view *v = view;
1548 int x, n = 0;
1550 if (view_is_hsplit_top(view))
1551 v = view->child;
1552 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1553 v = view->parent;
1555 view->count = 0;
1556 cbreak(); /* block for input */
1557 nodelay(view->window, FALSE);
1558 wmove(v->window, v->nlines - 1, 0);
1559 wclrtoeol(v->window);
1560 waddch(v->window, ':');
1562 do {
1563 x = getcurx(v->window);
1564 if (x != ERR && x < view->ncols) {
1565 waddch(v->window, c);
1566 wrefresh(v->window);
1570 * Don't overflow. Max valid request should be the greatest
1571 * between the longest and total lines; cap at 10 million.
1573 if (n >= 9999999)
1574 n = 9999999;
1575 else
1576 n = n * 10 + (c - '0');
1577 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1579 if (c == 'G' || c == 'g') { /* nG key map */
1580 view->gline = view->hiline = n;
1581 n = 0;
1582 c = 0;
1585 /* Massage excessive or inapplicable values at the input handler. */
1586 view->count = n;
1588 return c;
1591 static void
1592 action_report(struct tog_view *view)
1594 struct tog_view *v = view;
1596 if (view_is_hsplit_top(view))
1597 v = view->child;
1598 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1599 v = view->parent;
1601 wmove(v->window, v->nlines - 1, 0);
1602 wclrtoeol(v->window);
1603 wprintw(v->window, ":%s", view->action);
1604 wrefresh(v->window);
1607 * Clear action status report. Only clear in blame view
1608 * once annotating is complete, otherwise it's too fast.
1610 if (view->type == TOG_VIEW_BLAME) {
1611 if (view->state.blame.blame_complete)
1612 view->action = NULL;
1613 } else
1614 view->action = NULL;
1618 * Read the next line from the test script and assign
1619 * key instruction to *ch. If at EOF, set the *done flag.
1621 static const struct got_error *
1622 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1624 const struct got_error *err = NULL;
1625 char *line = NULL;
1626 size_t linesz = 0;
1628 if (view->count && --view->count) {
1629 *ch = view->ch;
1630 return NULL;
1631 } else
1632 *ch = -1;
1634 if (getline(&line, &linesz, script) == -1) {
1635 if (feof(script)) {
1636 *done = 1;
1637 goto done;
1638 } else {
1639 err = got_ferror(script, GOT_ERR_IO);
1640 goto done;
1644 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1645 tog_io.wait_for_ui = 1;
1646 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1647 *ch = KEY_ENTER;
1648 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1649 *ch = KEY_RIGHT;
1650 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1651 *ch = KEY_LEFT;
1652 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1653 *ch = KEY_DOWN;
1654 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1655 *ch = KEY_UP;
1656 else if (strncasecmp(line, "TAB", 3) == 0)
1657 *ch = '\t';
1658 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1659 *ch = TOG_KEY_SCRDUMP;
1660 else if (isdigit((unsigned char)*line)) {
1661 char *t = line;
1663 while (isdigit((unsigned char)*t))
1664 ++t;
1665 view->ch = *ch = *t;
1666 *t = '\0';
1667 /* ignore error, view->count is 0 if instruction is invalid */
1668 view->count = strtonum(line, 0, INT_MAX, NULL);
1669 } else
1670 *ch = *line;
1672 done:
1673 free(line);
1674 return err;
1677 static const struct got_error *
1678 view_input(struct tog_view **new, int *done, struct tog_view *view,
1679 struct tog_view_list_head *views, int fast_refresh)
1681 const struct got_error *err = NULL;
1682 struct tog_view *v;
1683 int ch, errcode;
1685 *new = NULL;
1687 if (view->action)
1688 action_report(view);
1690 /* Clear "no matches" indicator. */
1691 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1692 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1693 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1694 view->count = 0;
1697 if (view->searching && !view->search_next_done) {
1698 errcode = pthread_mutex_unlock(&tog_mutex);
1699 if (errcode)
1700 return got_error_set_errno(errcode,
1701 "pthread_mutex_unlock");
1702 sched_yield();
1703 errcode = pthread_mutex_lock(&tog_mutex);
1704 if (errcode)
1705 return got_error_set_errno(errcode,
1706 "pthread_mutex_lock");
1707 view->search_next(view);
1708 return NULL;
1711 /* Allow threads to make progress while we are waiting for input. */
1712 errcode = pthread_mutex_unlock(&tog_mutex);
1713 if (errcode)
1714 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1716 if (using_mock_io) {
1717 err = tog_read_script_key(tog_io.f, view, &ch, done);
1718 if (err) {
1719 errcode = pthread_mutex_lock(&tog_mutex);
1720 return err;
1722 } else if (view->count && --view->count) {
1723 cbreak();
1724 nodelay(view->window, TRUE);
1725 ch = wgetch(view->window);
1726 /* let C-g or backspace abort unfinished count */
1727 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1728 view->count = 0;
1729 else
1730 ch = view->ch;
1731 } else {
1732 ch = wgetch(view->window);
1733 if (ch >= '1' && ch <= '9')
1734 view->ch = ch = get_compound_key(view, ch);
1736 if (view->hiline && ch != ERR && ch != 0)
1737 view->hiline = 0; /* key pressed, clear line highlight */
1738 nodelay(view->window, TRUE);
1739 errcode = pthread_mutex_lock(&tog_mutex);
1740 if (errcode)
1741 return got_error_set_errno(errcode, "pthread_mutex_lock");
1743 if (tog_sigwinch_received || tog_sigcont_received) {
1744 tog_resizeterm();
1745 tog_sigwinch_received = 0;
1746 tog_sigcont_received = 0;
1747 TAILQ_FOREACH(v, views, entry) {
1748 err = view_resize(v);
1749 if (err)
1750 return err;
1751 err = v->input(new, v, KEY_RESIZE);
1752 if (err)
1753 return err;
1754 if (v->child) {
1755 err = view_resize(v->child);
1756 if (err)
1757 return err;
1758 err = v->child->input(new, v->child,
1759 KEY_RESIZE);
1760 if (err)
1761 return err;
1762 if (v->child->resized_x || v->child->resized_y) {
1763 err = view_resize_split(v, 0);
1764 if (err)
1765 return err;
1771 switch (ch) {
1772 case '?':
1773 case 'H':
1774 case KEY_F(1):
1775 if (view->type == TOG_VIEW_HELP)
1776 err = view->reset(view);
1777 else
1778 err = view_request_new(new, view, TOG_VIEW_HELP);
1779 break;
1780 case '\t':
1781 view->count = 0;
1782 if (view->child) {
1783 view->focussed = 0;
1784 view->child->focussed = 1;
1785 view->focus_child = 1;
1786 } else if (view->parent) {
1787 view->focussed = 0;
1788 view->parent->focussed = 1;
1789 view->parent->focus_child = 0;
1790 if (!view_is_splitscreen(view)) {
1791 if (view->parent->resize) {
1792 err = view->parent->resize(view->parent,
1793 0);
1794 if (err)
1795 return err;
1797 offset_selection_up(view->parent);
1798 err = view_fullscreen(view->parent);
1799 if (err)
1800 return err;
1803 break;
1804 case 'q':
1805 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1806 if (view->parent->resize) {
1807 /* might need more commits to fill fullscreen */
1808 err = view->parent->resize(view->parent, 0);
1809 if (err)
1810 break;
1812 offset_selection_up(view->parent);
1814 err = view->input(new, view, ch);
1815 view->dying = 1;
1816 break;
1817 case 'Q':
1818 *done = 1;
1819 break;
1820 case 'F':
1821 view->count = 0;
1822 if (view_is_parent_view(view)) {
1823 if (view->child == NULL)
1824 break;
1825 if (view_is_splitscreen(view->child)) {
1826 view->focussed = 0;
1827 view->child->focussed = 1;
1828 err = view_fullscreen(view->child);
1829 } else {
1830 err = view_splitscreen(view->child);
1831 if (!err)
1832 err = view_resize_split(view, 0);
1834 if (err)
1835 break;
1836 err = view->child->input(new, view->child,
1837 KEY_RESIZE);
1838 } else {
1839 if (view_is_splitscreen(view)) {
1840 view->parent->focussed = 0;
1841 view->focussed = 1;
1842 err = view_fullscreen(view);
1843 } else {
1844 err = view_splitscreen(view);
1845 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1846 err = view_resize(view->parent);
1847 if (!err)
1848 err = view_resize_split(view, 0);
1850 if (err)
1851 break;
1852 err = view->input(new, view, KEY_RESIZE);
1854 if (err)
1855 break;
1856 if (view->resize) {
1857 err = view->resize(view, 0);
1858 if (err)
1859 break;
1861 if (view->parent) {
1862 if (view->parent->resize) {
1863 err = view->parent->resize(view->parent, 0);
1864 if (err != NULL)
1865 break;
1867 err = offset_selection_down(view->parent);
1868 if (err != NULL)
1869 break;
1871 err = offset_selection_down(view);
1872 break;
1873 case 'S':
1874 view->count = 0;
1875 err = switch_split(view);
1876 break;
1877 case '-':
1878 err = view_resize_split(view, -1);
1879 break;
1880 case '+':
1881 err = view_resize_split(view, 1);
1882 break;
1883 case KEY_RESIZE:
1884 break;
1885 case '/':
1886 view->count = 0;
1887 if (view->search_start)
1888 view_search_start(view, fast_refresh);
1889 else
1890 err = view->input(new, view, ch);
1891 break;
1892 case 'N':
1893 case 'n':
1894 if (view->search_started && view->search_next) {
1895 view->searching = (ch == 'n' ?
1896 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1897 view->search_next_done = 0;
1898 view->search_next(view);
1899 } else
1900 err = view->input(new, view, ch);
1901 break;
1902 case 'A':
1903 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1904 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1905 view->action = "Patience diff algorithm";
1906 } else {
1907 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1908 view->action = "Myers diff algorithm";
1910 TAILQ_FOREACH(v, views, entry) {
1911 if (v->reset) {
1912 err = v->reset(v);
1913 if (err)
1914 return err;
1916 if (v->child && v->child->reset) {
1917 err = v->child->reset(v->child);
1918 if (err)
1919 return err;
1922 break;
1923 case TOG_KEY_SCRDUMP:
1924 err = screendump(view);
1925 break;
1926 default:
1927 err = view->input(new, view, ch);
1928 break;
1931 return err;
1934 static int
1935 view_needs_focus_indication(struct tog_view *view)
1937 if (view_is_parent_view(view)) {
1938 if (view->child == NULL || view->child->focussed)
1939 return 0;
1940 if (!view_is_splitscreen(view->child))
1941 return 0;
1942 } else if (!view_is_splitscreen(view))
1943 return 0;
1945 return view->focussed;
1948 static const struct got_error *
1949 tog_io_close(void)
1951 const struct got_error *err = NULL;
1953 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1954 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1955 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1956 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1957 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1958 err = got_ferror(tog_io.f, GOT_ERR_IO);
1959 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1960 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1962 return err;
1965 static const struct got_error *
1966 view_loop(struct tog_view *view)
1968 const struct got_error *err = NULL;
1969 struct tog_view_list_head views;
1970 struct tog_view *new_view;
1971 char *mode;
1972 int fast_refresh = 10;
1973 int done = 0, errcode;
1975 mode = getenv("TOG_VIEW_SPLIT_MODE");
1976 if (!mode || !(*mode == 'h' || *mode == 'H'))
1977 view->mode = TOG_VIEW_SPLIT_VERT;
1978 else
1979 view->mode = TOG_VIEW_SPLIT_HRZN;
1981 errcode = pthread_mutex_lock(&tog_mutex);
1982 if (errcode)
1983 return got_error_set_errno(errcode, "pthread_mutex_lock");
1985 TAILQ_INIT(&views);
1986 TAILQ_INSERT_HEAD(&views, view, entry);
1988 view->focussed = 1;
1989 err = view->show(view);
1990 if (err)
1991 return err;
1992 update_panels();
1993 doupdate();
1994 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1995 !tog_fatal_signal_received()) {
1996 /* Refresh fast during initialization, then become slower. */
1997 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1998 halfdelay(10); /* switch to once per second */
2000 err = view_input(&new_view, &done, view, &views, fast_refresh);
2001 if (err)
2002 break;
2004 if (view->dying && view == TAILQ_FIRST(&views) &&
2005 TAILQ_NEXT(view, entry) == NULL)
2006 done = 1;
2007 if (done) {
2008 struct tog_view *v;
2011 * When we quit, scroll the screen up a single line
2012 * so we don't lose any information.
2014 TAILQ_FOREACH(v, &views, entry) {
2015 wmove(v->window, 0, 0);
2016 wdeleteln(v->window);
2017 wnoutrefresh(v->window);
2018 if (v->child && !view_is_fullscreen(v)) {
2019 wmove(v->child->window, 0, 0);
2020 wdeleteln(v->child->window);
2021 wnoutrefresh(v->child->window);
2024 doupdate();
2027 if (view->dying) {
2028 struct tog_view *v, *prev = NULL;
2030 if (view_is_parent_view(view))
2031 prev = TAILQ_PREV(view, tog_view_list_head,
2032 entry);
2033 else if (view->parent)
2034 prev = view->parent;
2036 if (view->parent) {
2037 view->parent->child = NULL;
2038 view->parent->focus_child = 0;
2039 /* Restore fullscreen line height. */
2040 view->parent->nlines = view->parent->lines;
2041 err = view_resize(view->parent);
2042 if (err)
2043 break;
2044 /* Make resized splits persist. */
2045 view_transfer_size(view->parent, view);
2046 } else
2047 TAILQ_REMOVE(&views, view, entry);
2049 err = view_close(view);
2050 if (err)
2051 goto done;
2053 view = NULL;
2054 TAILQ_FOREACH(v, &views, entry) {
2055 if (v->focussed)
2056 break;
2058 if (view == NULL && new_view == NULL) {
2059 /* No view has focus. Try to pick one. */
2060 if (prev)
2061 view = prev;
2062 else if (!TAILQ_EMPTY(&views)) {
2063 view = TAILQ_LAST(&views,
2064 tog_view_list_head);
2066 if (view) {
2067 if (view->focus_child) {
2068 view->child->focussed = 1;
2069 view = view->child;
2070 } else
2071 view->focussed = 1;
2075 if (new_view) {
2076 struct tog_view *v, *t;
2077 /* Only allow one parent view per type. */
2078 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2079 if (v->type != new_view->type)
2080 continue;
2081 TAILQ_REMOVE(&views, v, entry);
2082 err = view_close(v);
2083 if (err)
2084 goto done;
2085 break;
2087 TAILQ_INSERT_TAIL(&views, new_view, entry);
2088 view = new_view;
2090 if (view && !done) {
2091 if (view_is_parent_view(view)) {
2092 if (view->child && view->child->focussed)
2093 view = view->child;
2094 } else {
2095 if (view->parent && view->parent->focussed)
2096 view = view->parent;
2098 show_panel(view->panel);
2099 if (view->child && view_is_splitscreen(view->child))
2100 show_panel(view->child->panel);
2101 if (view->parent && view_is_splitscreen(view)) {
2102 err = view->parent->show(view->parent);
2103 if (err)
2104 goto done;
2106 err = view->show(view);
2107 if (err)
2108 goto done;
2109 if (view->child) {
2110 err = view->child->show(view->child);
2111 if (err)
2112 goto done;
2114 update_panels();
2115 doupdate();
2118 done:
2119 while (!TAILQ_EMPTY(&views)) {
2120 const struct got_error *close_err;
2121 view = TAILQ_FIRST(&views);
2122 TAILQ_REMOVE(&views, view, entry);
2123 close_err = view_close(view);
2124 if (close_err && err == NULL)
2125 err = close_err;
2128 errcode = pthread_mutex_unlock(&tog_mutex);
2129 if (errcode && err == NULL)
2130 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2132 return err;
2135 __dead static void
2136 usage_log(void)
2138 endwin();
2139 fprintf(stderr,
2140 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2141 getprogname());
2142 exit(1);
2145 /* Create newly allocated wide-character string equivalent to a byte string. */
2146 static const struct got_error *
2147 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2149 char *vis = NULL;
2150 const struct got_error *err = NULL;
2152 *ws = NULL;
2153 *wlen = mbstowcs(NULL, s, 0);
2154 if (*wlen == (size_t)-1) {
2155 int vislen;
2156 if (errno != EILSEQ)
2157 return got_error_from_errno("mbstowcs");
2159 /* byte string invalid in current encoding; try to "fix" it */
2160 err = got_mbsavis(&vis, &vislen, s);
2161 if (err)
2162 return err;
2163 *wlen = mbstowcs(NULL, vis, 0);
2164 if (*wlen == (size_t)-1) {
2165 err = got_error_from_errno("mbstowcs"); /* give up */
2166 goto done;
2170 *ws = calloc(*wlen + 1, sizeof(**ws));
2171 if (*ws == NULL) {
2172 err = got_error_from_errno("calloc");
2173 goto done;
2176 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2177 err = got_error_from_errno("mbstowcs");
2178 done:
2179 free(vis);
2180 if (err) {
2181 free(*ws);
2182 *ws = NULL;
2183 *wlen = 0;
2185 return err;
2188 static const struct got_error *
2189 expand_tab(char **ptr, const char *src)
2191 char *dst;
2192 size_t len, n, idx = 0, sz = 0;
2194 *ptr = NULL;
2195 n = len = strlen(src);
2196 dst = malloc(n + 1);
2197 if (dst == NULL)
2198 return got_error_from_errno("malloc");
2200 while (idx < len && src[idx]) {
2201 const char c = src[idx];
2203 if (c == '\t') {
2204 size_t nb = TABSIZE - sz % TABSIZE;
2205 char *p;
2207 p = realloc(dst, n + nb);
2208 if (p == NULL) {
2209 free(dst);
2210 return got_error_from_errno("realloc");
2213 dst = p;
2214 n += nb;
2215 memset(dst + sz, ' ', nb);
2216 sz += nb;
2217 } else
2218 dst[sz++] = src[idx];
2219 ++idx;
2222 dst[sz] = '\0';
2223 *ptr = dst;
2224 return NULL;
2228 * Advance at most n columns from wline starting at offset off.
2229 * Return the index to the first character after the span operation.
2230 * Return the combined column width of all spanned wide character in
2231 * *rcol.
2233 static int
2234 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2236 int width, i, cols = 0;
2238 if (n == 0) {
2239 *rcol = cols;
2240 return off;
2243 for (i = off; wline[i] != L'\0'; ++i) {
2244 if (wline[i] == L'\t')
2245 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2246 else
2247 width = wcwidth(wline[i]);
2249 if (width == -1) {
2250 width = 1;
2251 wline[i] = L'.';
2254 if (cols + width > n)
2255 break;
2256 cols += width;
2259 *rcol = cols;
2260 return i;
2264 * Format a line for display, ensuring that it won't overflow a width limit.
2265 * With scrolling, the width returned refers to the scrolled version of the
2266 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2268 static const struct got_error *
2269 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2270 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2272 const struct got_error *err = NULL;
2273 int cols;
2274 wchar_t *wline = NULL;
2275 char *exstr = NULL;
2276 size_t wlen;
2277 int i, scrollx;
2279 *wlinep = NULL;
2280 *widthp = 0;
2282 if (expand) {
2283 err = expand_tab(&exstr, line);
2284 if (err)
2285 return err;
2288 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2289 free(exstr);
2290 if (err)
2291 return err;
2293 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2295 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2296 wline[wlen - 1] = L'\0';
2297 wlen--;
2299 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2300 wline[wlen - 1] = L'\0';
2301 wlen--;
2304 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2305 wline[i] = L'\0';
2307 if (widthp)
2308 *widthp = cols;
2309 if (scrollxp)
2310 *scrollxp = scrollx;
2311 if (err)
2312 free(wline);
2313 else
2314 *wlinep = wline;
2315 return err;
2318 static const struct got_error*
2319 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2320 struct got_object_id *id, struct got_repository *repo)
2322 static const struct got_error *err = NULL;
2323 struct got_reflist_entry *re;
2324 char *s;
2325 const char *name;
2327 *refs_str = NULL;
2329 TAILQ_FOREACH(re, refs, entry) {
2330 struct got_tag_object *tag = NULL;
2331 struct got_object_id *ref_id;
2332 int cmp;
2334 name = got_ref_get_name(re->ref);
2335 if (strcmp(name, GOT_REF_HEAD) == 0)
2336 continue;
2337 if (strncmp(name, "refs/", 5) == 0)
2338 name += 5;
2339 if (strncmp(name, "got/", 4) == 0 &&
2340 strncmp(name, "got/backup/", 11) != 0)
2341 continue;
2342 if (strncmp(name, "heads/", 6) == 0)
2343 name += 6;
2344 if (strncmp(name, "remotes/", 8) == 0) {
2345 name += 8;
2346 s = strstr(name, "/" GOT_REF_HEAD);
2347 if (s != NULL && s[strlen(s)] == '\0')
2348 continue;
2350 err = got_ref_resolve(&ref_id, repo, re->ref);
2351 if (err)
2352 break;
2353 if (strncmp(name, "tags/", 5) == 0) {
2354 err = got_object_open_as_tag(&tag, repo, ref_id);
2355 if (err) {
2356 if (err->code != GOT_ERR_OBJ_TYPE) {
2357 free(ref_id);
2358 break;
2360 /* Ref points at something other than a tag. */
2361 err = NULL;
2362 tag = NULL;
2365 cmp = got_object_id_cmp(tag ?
2366 got_object_tag_get_object_id(tag) : ref_id, id);
2367 free(ref_id);
2368 if (tag)
2369 got_object_tag_close(tag);
2370 if (cmp != 0)
2371 continue;
2372 s = *refs_str;
2373 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2374 s ? ", " : "", name) == -1) {
2375 err = got_error_from_errno("asprintf");
2376 free(s);
2377 *refs_str = NULL;
2378 break;
2380 free(s);
2383 return err;
2386 static const struct got_error *
2387 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2388 int col_tab_align)
2390 char *smallerthan;
2392 smallerthan = strchr(author, '<');
2393 if (smallerthan && smallerthan[1] != '\0')
2394 author = smallerthan + 1;
2395 author[strcspn(author, "@>")] = '\0';
2396 return format_line(wauthor, author_width, NULL, author, 0, limit,
2397 col_tab_align, 0);
2400 static const struct got_error *
2401 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2402 struct got_object_id *id, const size_t date_display_cols,
2403 int author_display_cols)
2405 struct tog_log_view_state *s = &view->state.log;
2406 const struct got_error *err = NULL;
2407 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2408 char *logmsg0 = NULL, *logmsg = NULL;
2409 char *author = NULL;
2410 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2411 int author_width, logmsg_width;
2412 char *newline, *line = NULL;
2413 int col, limit, scrollx;
2414 const int avail = view->ncols;
2415 struct tm tm;
2416 time_t committer_time;
2417 struct tog_color *tc;
2419 committer_time = got_object_commit_get_committer_time(commit);
2420 if (gmtime_r(&committer_time, &tm) == NULL)
2421 return got_error_from_errno("gmtime_r");
2422 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2423 return got_error(GOT_ERR_NO_SPACE);
2425 if (avail <= date_display_cols)
2426 limit = MIN(sizeof(datebuf) - 1, avail);
2427 else
2428 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2429 tc = get_color(&s->colors, TOG_COLOR_DATE);
2430 if (tc)
2431 wattr_on(view->window,
2432 COLOR_PAIR(tc->colorpair), NULL);
2433 waddnstr(view->window, datebuf, limit);
2434 if (tc)
2435 wattr_off(view->window,
2436 COLOR_PAIR(tc->colorpair), NULL);
2437 col = limit;
2438 if (col > avail)
2439 goto done;
2441 if (avail >= 120) {
2442 char *id_str;
2443 err = got_object_id_str(&id_str, id);
2444 if (err)
2445 goto done;
2446 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2447 if (tc)
2448 wattr_on(view->window,
2449 COLOR_PAIR(tc->colorpair), NULL);
2450 wprintw(view->window, "%.8s ", id_str);
2451 if (tc)
2452 wattr_off(view->window,
2453 COLOR_PAIR(tc->colorpair), NULL);
2454 free(id_str);
2455 col += 9;
2456 if (col > avail)
2457 goto done;
2460 if (s->use_committer)
2461 author = strdup(got_object_commit_get_committer(commit));
2462 else
2463 author = strdup(got_object_commit_get_author(commit));
2464 if (author == NULL) {
2465 err = got_error_from_errno("strdup");
2466 goto done;
2468 err = format_author(&wauthor, &author_width, author, avail - col, col);
2469 if (err)
2470 goto done;
2471 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2472 if (tc)
2473 wattr_on(view->window,
2474 COLOR_PAIR(tc->colorpair), NULL);
2475 waddwstr(view->window, wauthor);
2476 col += author_width;
2477 while (col < avail && author_width < author_display_cols + 2) {
2478 waddch(view->window, ' ');
2479 col++;
2480 author_width++;
2482 if (tc)
2483 wattr_off(view->window,
2484 COLOR_PAIR(tc->colorpair), NULL);
2485 if (col > avail)
2486 goto done;
2488 err = got_object_commit_get_logmsg(&logmsg0, commit);
2489 if (err)
2490 goto done;
2491 logmsg = logmsg0;
2492 while (*logmsg == '\n')
2493 logmsg++;
2494 newline = strchr(logmsg, '\n');
2495 if (newline)
2496 *newline = '\0';
2497 limit = avail - col;
2498 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2499 limit--; /* for the border */
2500 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2501 limit, col, 1);
2502 if (err)
2503 goto done;
2504 waddwstr(view->window, &wlogmsg[scrollx]);
2505 col += MAX(logmsg_width, 0);
2506 while (col < avail) {
2507 waddch(view->window, ' ');
2508 col++;
2510 done:
2511 free(logmsg0);
2512 free(wlogmsg);
2513 free(author);
2514 free(wauthor);
2515 free(line);
2516 return err;
2519 static struct commit_queue_entry *
2520 alloc_commit_queue_entry(struct got_commit_object *commit,
2521 struct got_object_id *id)
2523 struct commit_queue_entry *entry;
2524 struct got_object_id *dup;
2526 entry = calloc(1, sizeof(*entry));
2527 if (entry == NULL)
2528 return NULL;
2530 dup = got_object_id_dup(id);
2531 if (dup == NULL) {
2532 free(entry);
2533 return NULL;
2536 entry->id = dup;
2537 entry->commit = commit;
2538 return entry;
2541 static void
2542 pop_commit(struct commit_queue *commits)
2544 struct commit_queue_entry *entry;
2546 entry = TAILQ_FIRST(&commits->head);
2547 TAILQ_REMOVE(&commits->head, entry, entry);
2548 got_object_commit_close(entry->commit);
2549 commits->ncommits--;
2550 free(entry->id);
2551 free(entry);
2554 static void
2555 free_commits(struct commit_queue *commits)
2557 while (!TAILQ_EMPTY(&commits->head))
2558 pop_commit(commits);
2561 static const struct got_error *
2562 match_commit(int *have_match, struct got_object_id *id,
2563 struct got_commit_object *commit, regex_t *regex)
2565 const struct got_error *err = NULL;
2566 regmatch_t regmatch;
2567 char *id_str = NULL, *logmsg = NULL;
2569 *have_match = 0;
2571 err = got_object_id_str(&id_str, id);
2572 if (err)
2573 return err;
2575 err = got_object_commit_get_logmsg(&logmsg, commit);
2576 if (err)
2577 goto done;
2579 if (regexec(regex, got_object_commit_get_author(commit), 1,
2580 &regmatch, 0) == 0 ||
2581 regexec(regex, got_object_commit_get_committer(commit), 1,
2582 &regmatch, 0) == 0 ||
2583 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2584 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2585 *have_match = 1;
2586 done:
2587 free(id_str);
2588 free(logmsg);
2589 return err;
2592 static const struct got_error *
2593 queue_commits(struct tog_log_thread_args *a)
2595 const struct got_error *err = NULL;
2598 * We keep all commits open throughout the lifetime of the log
2599 * view in order to avoid having to re-fetch commits from disk
2600 * while updating the display.
2602 do {
2603 struct got_object_id id;
2604 struct got_commit_object *commit;
2605 struct commit_queue_entry *entry;
2606 int limit_match = 0;
2607 int errcode;
2609 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2610 NULL, NULL);
2611 if (err)
2612 break;
2614 err = got_object_open_as_commit(&commit, a->repo, &id);
2615 if (err)
2616 break;
2617 entry = alloc_commit_queue_entry(commit, &id);
2618 if (entry == NULL) {
2619 err = got_error_from_errno("alloc_commit_queue_entry");
2620 break;
2623 errcode = pthread_mutex_lock(&tog_mutex);
2624 if (errcode) {
2625 err = got_error_set_errno(errcode,
2626 "pthread_mutex_lock");
2627 break;
2630 entry->idx = a->real_commits->ncommits;
2631 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2632 a->real_commits->ncommits++;
2634 if (*a->limiting) {
2635 err = match_commit(&limit_match, &id, commit,
2636 a->limit_regex);
2637 if (err)
2638 break;
2640 if (limit_match) {
2641 struct commit_queue_entry *matched;
2643 matched = alloc_commit_queue_entry(
2644 entry->commit, entry->id);
2645 if (matched == NULL) {
2646 err = got_error_from_errno(
2647 "alloc_commit_queue_entry");
2648 break;
2650 matched->commit = entry->commit;
2651 got_object_commit_retain(entry->commit);
2653 matched->idx = a->limit_commits->ncommits;
2654 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2655 matched, entry);
2656 a->limit_commits->ncommits++;
2660 * This is how we signal log_thread() that we
2661 * have found a match, and that it should be
2662 * counted as a new entry for the view.
2664 a->limit_match = limit_match;
2667 if (*a->searching == TOG_SEARCH_FORWARD &&
2668 !*a->search_next_done) {
2669 int have_match;
2670 err = match_commit(&have_match, &id, commit, a->regex);
2671 if (err)
2672 break;
2674 if (*a->limiting) {
2675 if (limit_match && have_match)
2676 *a->search_next_done =
2677 TOG_SEARCH_HAVE_MORE;
2678 } else if (have_match)
2679 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2682 errcode = pthread_mutex_unlock(&tog_mutex);
2683 if (errcode && err == NULL)
2684 err = got_error_set_errno(errcode,
2685 "pthread_mutex_unlock");
2686 if (err)
2687 break;
2688 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2690 return err;
2693 static void
2694 select_commit(struct tog_log_view_state *s)
2696 struct commit_queue_entry *entry;
2697 int ncommits = 0;
2699 entry = s->first_displayed_entry;
2700 while (entry) {
2701 if (ncommits == s->selected) {
2702 s->selected_entry = entry;
2703 break;
2705 entry = TAILQ_NEXT(entry, entry);
2706 ncommits++;
2710 static const struct got_error *
2711 draw_commits(struct tog_view *view)
2713 const struct got_error *err = NULL;
2714 struct tog_log_view_state *s = &view->state.log;
2715 struct commit_queue_entry *entry = s->selected_entry;
2716 int limit = view->nlines;
2717 int width;
2718 int ncommits, author_cols = 4;
2719 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2720 char *refs_str = NULL;
2721 wchar_t *wline;
2722 struct tog_color *tc;
2723 static const size_t date_display_cols = 12;
2725 if (view_is_hsplit_top(view))
2726 --limit; /* account for border */
2728 if (s->selected_entry &&
2729 !(view->searching && view->search_next_done == 0)) {
2730 struct got_reflist_head *refs;
2731 err = got_object_id_str(&id_str, s->selected_entry->id);
2732 if (err)
2733 return err;
2734 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2735 s->selected_entry->id);
2736 if (refs) {
2737 err = build_refs_str(&refs_str, refs,
2738 s->selected_entry->id, s->repo);
2739 if (err)
2740 goto done;
2744 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2745 halfdelay(10); /* disable fast refresh */
2747 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2748 if (asprintf(&ncommits_str, " [%d/%d] %s",
2749 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2750 (view->searching && !view->search_next_done) ?
2751 "searching..." : "loading...") == -1) {
2752 err = got_error_from_errno("asprintf");
2753 goto done;
2755 } else {
2756 const char *search_str = NULL;
2757 const char *limit_str = NULL;
2759 if (view->searching) {
2760 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2761 search_str = "no more matches";
2762 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2763 search_str = "no matches found";
2764 else if (!view->search_next_done)
2765 search_str = "searching...";
2768 if (s->limit_view && s->commits->ncommits == 0)
2769 limit_str = "no matches found";
2771 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2772 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2773 search_str ? search_str : (refs_str ? refs_str : ""),
2774 limit_str ? limit_str : "") == -1) {
2775 err = got_error_from_errno("asprintf");
2776 goto done;
2780 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2781 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2782 "........................................",
2783 s->in_repo_path, ncommits_str) == -1) {
2784 err = got_error_from_errno("asprintf");
2785 header = NULL;
2786 goto done;
2788 } else if (asprintf(&header, "commit %s%s",
2789 id_str ? id_str : "........................................",
2790 ncommits_str) == -1) {
2791 err = got_error_from_errno("asprintf");
2792 header = NULL;
2793 goto done;
2795 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2796 if (err)
2797 goto done;
2799 werase(view->window);
2801 if (view_needs_focus_indication(view))
2802 wstandout(view->window);
2803 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2804 if (tc)
2805 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2806 waddwstr(view->window, wline);
2807 while (width < view->ncols) {
2808 waddch(view->window, ' ');
2809 width++;
2811 if (tc)
2812 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2813 if (view_needs_focus_indication(view))
2814 wstandend(view->window);
2815 free(wline);
2816 if (limit <= 1)
2817 goto done;
2819 /* Grow author column size if necessary, and set view->maxx. */
2820 entry = s->first_displayed_entry;
2821 ncommits = 0;
2822 view->maxx = 0;
2823 while (entry) {
2824 struct got_commit_object *c = entry->commit;
2825 char *author, *eol, *msg, *msg0;
2826 wchar_t *wauthor, *wmsg;
2827 int width;
2828 if (ncommits >= limit - 1)
2829 break;
2830 if (s->use_committer)
2831 author = strdup(got_object_commit_get_committer(c));
2832 else
2833 author = strdup(got_object_commit_get_author(c));
2834 if (author == NULL) {
2835 err = got_error_from_errno("strdup");
2836 goto done;
2838 err = format_author(&wauthor, &width, author, COLS,
2839 date_display_cols);
2840 if (author_cols < width)
2841 author_cols = width;
2842 free(wauthor);
2843 free(author);
2844 if (err)
2845 goto done;
2846 err = got_object_commit_get_logmsg(&msg0, c);
2847 if (err)
2848 goto done;
2849 msg = msg0;
2850 while (*msg == '\n')
2851 ++msg;
2852 if ((eol = strchr(msg, '\n')))
2853 *eol = '\0';
2854 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2855 date_display_cols + author_cols, 0);
2856 if (err)
2857 goto done;
2858 view->maxx = MAX(view->maxx, width);
2859 free(msg0);
2860 free(wmsg);
2861 ncommits++;
2862 entry = TAILQ_NEXT(entry, entry);
2865 entry = s->first_displayed_entry;
2866 s->last_displayed_entry = s->first_displayed_entry;
2867 ncommits = 0;
2868 while (entry) {
2869 if (ncommits >= limit - 1)
2870 break;
2871 if (ncommits == s->selected)
2872 wstandout(view->window);
2873 err = draw_commit(view, entry->commit, entry->id,
2874 date_display_cols, author_cols);
2875 if (ncommits == s->selected)
2876 wstandend(view->window);
2877 if (err)
2878 goto done;
2879 ncommits++;
2880 s->last_displayed_entry = entry;
2881 entry = TAILQ_NEXT(entry, entry);
2884 view_border(view);
2885 done:
2886 free(id_str);
2887 free(refs_str);
2888 free(ncommits_str);
2889 free(header);
2890 return err;
2893 static void
2894 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2896 struct commit_queue_entry *entry;
2897 int nscrolled = 0;
2899 entry = TAILQ_FIRST(&s->commits->head);
2900 if (s->first_displayed_entry == entry)
2901 return;
2903 entry = s->first_displayed_entry;
2904 while (entry && nscrolled < maxscroll) {
2905 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2906 if (entry) {
2907 s->first_displayed_entry = entry;
2908 nscrolled++;
2913 static const struct got_error *
2914 trigger_log_thread(struct tog_view *view, int wait)
2916 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2917 int errcode;
2919 if (!using_mock_io)
2920 halfdelay(1); /* fast refresh while loading commits */
2922 while (!ta->log_complete && !tog_thread_error &&
2923 (ta->commits_needed > 0 || ta->load_all)) {
2924 /* Wake the log thread. */
2925 errcode = pthread_cond_signal(&ta->need_commits);
2926 if (errcode)
2927 return got_error_set_errno(errcode,
2928 "pthread_cond_signal");
2931 * The mutex will be released while the view loop waits
2932 * in wgetch(), at which time the log thread will run.
2934 if (!wait)
2935 break;
2937 /* Display progress update in log view. */
2938 show_log_view(view);
2939 update_panels();
2940 doupdate();
2942 /* Wait right here while next commit is being loaded. */
2943 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2944 if (errcode)
2945 return got_error_set_errno(errcode,
2946 "pthread_cond_wait");
2948 /* Display progress update in log view. */
2949 show_log_view(view);
2950 update_panels();
2951 doupdate();
2954 return NULL;
2957 static const struct got_error *
2958 request_log_commits(struct tog_view *view)
2960 struct tog_log_view_state *state = &view->state.log;
2961 const struct got_error *err = NULL;
2963 if (state->thread_args.log_complete)
2964 return NULL;
2966 state->thread_args.commits_needed += view->nscrolled;
2967 err = trigger_log_thread(view, 1);
2968 view->nscrolled = 0;
2970 return err;
2973 static const struct got_error *
2974 log_scroll_down(struct tog_view *view, int maxscroll)
2976 struct tog_log_view_state *s = &view->state.log;
2977 const struct got_error *err = NULL;
2978 struct commit_queue_entry *pentry;
2979 int nscrolled = 0, ncommits_needed;
2981 if (s->last_displayed_entry == NULL)
2982 return NULL;
2984 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2985 if (s->commits->ncommits < ncommits_needed &&
2986 !s->thread_args.log_complete) {
2988 * Ask the log thread for required amount of commits.
2990 s->thread_args.commits_needed +=
2991 ncommits_needed - s->commits->ncommits;
2992 err = trigger_log_thread(view, 1);
2993 if (err)
2994 return err;
2997 do {
2998 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2999 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3000 break;
3002 s->last_displayed_entry = pentry ?
3003 pentry : s->last_displayed_entry;
3005 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3006 if (pentry == NULL)
3007 break;
3008 s->first_displayed_entry = pentry;
3009 } while (++nscrolled < maxscroll);
3011 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3012 view->nscrolled += nscrolled;
3013 else
3014 view->nscrolled = 0;
3016 return err;
3019 static const struct got_error *
3020 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3021 struct got_commit_object *commit, struct got_object_id *commit_id,
3022 struct tog_view *log_view, struct got_repository *repo)
3024 const struct got_error *err;
3025 struct got_object_qid *parent_id;
3026 struct tog_view *diff_view;
3028 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3029 if (diff_view == NULL)
3030 return got_error_from_errno("view_open");
3032 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3033 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3034 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3035 if (err == NULL)
3036 *new_view = diff_view;
3037 return err;
3040 static const struct got_error *
3041 tree_view_visit_subtree(struct tog_tree_view_state *s,
3042 struct got_tree_object *subtree)
3044 struct tog_parent_tree *parent;
3046 parent = calloc(1, sizeof(*parent));
3047 if (parent == NULL)
3048 return got_error_from_errno("calloc");
3050 parent->tree = s->tree;
3051 parent->first_displayed_entry = s->first_displayed_entry;
3052 parent->selected_entry = s->selected_entry;
3053 parent->selected = s->selected;
3054 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3055 s->tree = subtree;
3056 s->selected = 0;
3057 s->first_displayed_entry = NULL;
3058 return NULL;
3061 static const struct got_error *
3062 tree_view_walk_path(struct tog_tree_view_state *s,
3063 struct got_commit_object *commit, const char *path)
3065 const struct got_error *err = NULL;
3066 struct got_tree_object *tree = NULL;
3067 const char *p;
3068 char *slash, *subpath = NULL;
3070 /* Walk the path and open corresponding tree objects. */
3071 p = path;
3072 while (*p) {
3073 struct got_tree_entry *te;
3074 struct got_object_id *tree_id;
3075 char *te_name;
3077 while (p[0] == '/')
3078 p++;
3080 /* Ensure the correct subtree entry is selected. */
3081 slash = strchr(p, '/');
3082 if (slash == NULL)
3083 te_name = strdup(p);
3084 else
3085 te_name = strndup(p, slash - p);
3086 if (te_name == NULL) {
3087 err = got_error_from_errno("strndup");
3088 break;
3090 te = got_object_tree_find_entry(s->tree, te_name);
3091 if (te == NULL) {
3092 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3093 free(te_name);
3094 break;
3096 free(te_name);
3097 s->first_displayed_entry = s->selected_entry = te;
3099 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3100 break; /* jump to this file's entry */
3102 slash = strchr(p, '/');
3103 if (slash)
3104 subpath = strndup(path, slash - path);
3105 else
3106 subpath = strdup(path);
3107 if (subpath == NULL) {
3108 err = got_error_from_errno("strdup");
3109 break;
3112 err = got_object_id_by_path(&tree_id, s->repo, commit,
3113 subpath);
3114 if (err)
3115 break;
3117 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3118 free(tree_id);
3119 if (err)
3120 break;
3122 err = tree_view_visit_subtree(s, tree);
3123 if (err) {
3124 got_object_tree_close(tree);
3125 break;
3127 if (slash == NULL)
3128 break;
3129 free(subpath);
3130 subpath = NULL;
3131 p = slash;
3134 free(subpath);
3135 return err;
3138 static const struct got_error *
3139 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3140 struct commit_queue_entry *entry, const char *path,
3141 const char *head_ref_name, struct got_repository *repo)
3143 const struct got_error *err = NULL;
3144 struct tog_tree_view_state *s;
3145 struct tog_view *tree_view;
3147 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3148 if (tree_view == NULL)
3149 return got_error_from_errno("view_open");
3151 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3152 if (err)
3153 return err;
3154 s = &tree_view->state.tree;
3156 *new_view = tree_view;
3158 if (got_path_is_root_dir(path))
3159 return NULL;
3161 return tree_view_walk_path(s, entry->commit, path);
3164 static const struct got_error *
3165 block_signals_used_by_main_thread(void)
3167 sigset_t sigset;
3168 int errcode;
3170 if (sigemptyset(&sigset) == -1)
3171 return got_error_from_errno("sigemptyset");
3173 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3174 if (sigaddset(&sigset, SIGWINCH) == -1)
3175 return got_error_from_errno("sigaddset");
3176 if (sigaddset(&sigset, SIGCONT) == -1)
3177 return got_error_from_errno("sigaddset");
3178 if (sigaddset(&sigset, SIGINT) == -1)
3179 return got_error_from_errno("sigaddset");
3180 if (sigaddset(&sigset, SIGTERM) == -1)
3181 return got_error_from_errno("sigaddset");
3183 /* ncurses handles SIGTSTP */
3184 if (sigaddset(&sigset, SIGTSTP) == -1)
3185 return got_error_from_errno("sigaddset");
3187 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3188 if (errcode)
3189 return got_error_set_errno(errcode, "pthread_sigmask");
3191 return NULL;
3194 static void *
3195 log_thread(void *arg)
3197 const struct got_error *err = NULL;
3198 int errcode = 0;
3199 struct tog_log_thread_args *a = arg;
3200 int done = 0;
3203 * Sync startup with main thread such that we begin our
3204 * work once view_input() has released the mutex.
3206 errcode = pthread_mutex_lock(&tog_mutex);
3207 if (errcode) {
3208 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3209 return (void *)err;
3212 err = block_signals_used_by_main_thread();
3213 if (err) {
3214 pthread_mutex_unlock(&tog_mutex);
3215 goto done;
3218 while (!done && !err && !tog_fatal_signal_received()) {
3219 errcode = pthread_mutex_unlock(&tog_mutex);
3220 if (errcode) {
3221 err = got_error_set_errno(errcode,
3222 "pthread_mutex_unlock");
3223 goto done;
3225 err = queue_commits(a);
3226 if (err) {
3227 if (err->code != GOT_ERR_ITER_COMPLETED)
3228 goto done;
3229 err = NULL;
3230 done = 1;
3231 } else if (a->commits_needed > 0 && !a->load_all) {
3232 if (*a->limiting) {
3233 if (a->limit_match)
3234 a->commits_needed--;
3235 } else
3236 a->commits_needed--;
3239 errcode = pthread_mutex_lock(&tog_mutex);
3240 if (errcode) {
3241 err = got_error_set_errno(errcode,
3242 "pthread_mutex_lock");
3243 goto done;
3244 } else if (*a->quit)
3245 done = 1;
3246 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3247 *a->first_displayed_entry =
3248 TAILQ_FIRST(&a->limit_commits->head);
3249 *a->selected_entry = *a->first_displayed_entry;
3250 } else if (*a->first_displayed_entry == NULL) {
3251 *a->first_displayed_entry =
3252 TAILQ_FIRST(&a->real_commits->head);
3253 *a->selected_entry = *a->first_displayed_entry;
3256 errcode = pthread_cond_signal(&a->commit_loaded);
3257 if (errcode) {
3258 err = got_error_set_errno(errcode,
3259 "pthread_cond_signal");
3260 pthread_mutex_unlock(&tog_mutex);
3261 goto done;
3264 if (done)
3265 a->commits_needed = 0;
3266 else {
3267 if (a->commits_needed == 0 && !a->load_all) {
3268 errcode = pthread_cond_wait(&a->need_commits,
3269 &tog_mutex);
3270 if (errcode) {
3271 err = got_error_set_errno(errcode,
3272 "pthread_cond_wait");
3273 pthread_mutex_unlock(&tog_mutex);
3274 goto done;
3276 if (*a->quit)
3277 done = 1;
3281 a->log_complete = 1;
3282 errcode = pthread_mutex_unlock(&tog_mutex);
3283 if (errcode)
3284 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3285 done:
3286 if (err) {
3287 tog_thread_error = 1;
3288 pthread_cond_signal(&a->commit_loaded);
3290 return (void *)err;
3293 static const struct got_error *
3294 stop_log_thread(struct tog_log_view_state *s)
3296 const struct got_error *err = NULL, *thread_err = NULL;
3297 int errcode;
3299 if (s->thread) {
3300 s->quit = 1;
3301 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3302 if (errcode)
3303 return got_error_set_errno(errcode,
3304 "pthread_cond_signal");
3305 errcode = pthread_mutex_unlock(&tog_mutex);
3306 if (errcode)
3307 return got_error_set_errno(errcode,
3308 "pthread_mutex_unlock");
3309 errcode = pthread_join(s->thread, (void **)&thread_err);
3310 if (errcode)
3311 return got_error_set_errno(errcode, "pthread_join");
3312 errcode = pthread_mutex_lock(&tog_mutex);
3313 if (errcode)
3314 return got_error_set_errno(errcode,
3315 "pthread_mutex_lock");
3316 s->thread = 0; //NULL;
3319 if (s->thread_args.repo) {
3320 err = got_repo_close(s->thread_args.repo);
3321 s->thread_args.repo = NULL;
3324 if (s->thread_args.pack_fds) {
3325 const struct got_error *pack_err =
3326 got_repo_pack_fds_close(s->thread_args.pack_fds);
3327 if (err == NULL)
3328 err = pack_err;
3329 s->thread_args.pack_fds = NULL;
3332 if (s->thread_args.graph) {
3333 got_commit_graph_close(s->thread_args.graph);
3334 s->thread_args.graph = NULL;
3337 return err ? err : thread_err;
3340 static const struct got_error *
3341 close_log_view(struct tog_view *view)
3343 const struct got_error *err = NULL;
3344 struct tog_log_view_state *s = &view->state.log;
3345 int errcode;
3347 err = stop_log_thread(s);
3349 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3350 if (errcode && err == NULL)
3351 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3353 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3354 if (errcode && err == NULL)
3355 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3357 free_commits(&s->limit_commits);
3358 free_commits(&s->real_commits);
3359 free(s->in_repo_path);
3360 s->in_repo_path = NULL;
3361 free(s->start_id);
3362 s->start_id = NULL;
3363 free(s->head_ref_name);
3364 s->head_ref_name = NULL;
3365 return err;
3369 * We use two queues to implement the limit feature: first consists of
3370 * commits matching the current limit_regex; second is the real queue
3371 * of all known commits (real_commits). When the user starts limiting,
3372 * we swap queues such that all movement and displaying functionality
3373 * works with very slight change.
3375 static const struct got_error *
3376 limit_log_view(struct tog_view *view)
3378 struct tog_log_view_state *s = &view->state.log;
3379 struct commit_queue_entry *entry;
3380 struct tog_view *v = view;
3381 const struct got_error *err = NULL;
3382 char pattern[1024];
3383 int ret;
3385 if (view_is_hsplit_top(view))
3386 v = view->child;
3387 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3388 v = view->parent;
3390 /* Get the pattern */
3391 wmove(v->window, v->nlines - 1, 0);
3392 wclrtoeol(v->window);
3393 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3394 nodelay(v->window, FALSE);
3395 nocbreak();
3396 echo();
3397 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3398 cbreak();
3399 noecho();
3400 nodelay(v->window, TRUE);
3401 if (ret == ERR)
3402 return NULL;
3404 if (*pattern == '\0') {
3406 * Safety measure for the situation where the user
3407 * resets limit without previously limiting anything.
3409 if (!s->limit_view)
3410 return NULL;
3413 * User could have pressed Ctrl+L, which refreshed the
3414 * commit queues, it means we can't save previously
3415 * (before limit took place) displayed entries,
3416 * because they would point to already free'ed memory,
3417 * so we are forced to always select first entry of
3418 * the queue.
3420 s->commits = &s->real_commits;
3421 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3422 s->selected_entry = s->first_displayed_entry;
3423 s->selected = 0;
3424 s->limit_view = 0;
3426 return NULL;
3429 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3430 return NULL;
3432 s->limit_view = 1;
3434 /* Clear the screen while loading limit view */
3435 s->first_displayed_entry = NULL;
3436 s->last_displayed_entry = NULL;
3437 s->selected_entry = NULL;
3438 s->commits = &s->limit_commits;
3440 /* Prepare limit queue for new search */
3441 free_commits(&s->limit_commits);
3442 s->limit_commits.ncommits = 0;
3444 /* First process commits, which are in queue already */
3445 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3446 int have_match = 0;
3448 err = match_commit(&have_match, entry->id,
3449 entry->commit, &s->limit_regex);
3450 if (err)
3451 return err;
3453 if (have_match) {
3454 struct commit_queue_entry *matched;
3456 matched = alloc_commit_queue_entry(entry->commit,
3457 entry->id);
3458 if (matched == NULL) {
3459 err = got_error_from_errno(
3460 "alloc_commit_queue_entry");
3461 break;
3463 matched->commit = entry->commit;
3464 got_object_commit_retain(entry->commit);
3466 matched->idx = s->limit_commits.ncommits;
3467 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3468 matched, entry);
3469 s->limit_commits.ncommits++;
3473 /* Second process all the commits, until we fill the screen */
3474 if (s->limit_commits.ncommits < view->nlines - 1 &&
3475 !s->thread_args.log_complete) {
3476 s->thread_args.commits_needed +=
3477 view->nlines - s->limit_commits.ncommits - 1;
3478 err = trigger_log_thread(view, 1);
3479 if (err)
3480 return err;
3483 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3484 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3485 s->selected = 0;
3487 return NULL;
3490 static const struct got_error *
3491 search_start_log_view(struct tog_view *view)
3493 struct tog_log_view_state *s = &view->state.log;
3495 s->matched_entry = NULL;
3496 s->search_entry = NULL;
3497 return NULL;
3500 static const struct got_error *
3501 search_next_log_view(struct tog_view *view)
3503 const struct got_error *err = NULL;
3504 struct tog_log_view_state *s = &view->state.log;
3505 struct commit_queue_entry *entry;
3507 /* Display progress update in log view. */
3508 show_log_view(view);
3509 update_panels();
3510 doupdate();
3512 if (s->search_entry) {
3513 int errcode, ch;
3514 errcode = pthread_mutex_unlock(&tog_mutex);
3515 if (errcode)
3516 return got_error_set_errno(errcode,
3517 "pthread_mutex_unlock");
3518 ch = wgetch(view->window);
3519 errcode = pthread_mutex_lock(&tog_mutex);
3520 if (errcode)
3521 return got_error_set_errno(errcode,
3522 "pthread_mutex_lock");
3523 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3524 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3525 return NULL;
3527 if (view->searching == TOG_SEARCH_FORWARD)
3528 entry = TAILQ_NEXT(s->search_entry, entry);
3529 else
3530 entry = TAILQ_PREV(s->search_entry,
3531 commit_queue_head, entry);
3532 } else if (s->matched_entry) {
3534 * If the user has moved the cursor after we hit a match,
3535 * the position from where we should continue searching
3536 * might have changed.
3538 if (view->searching == TOG_SEARCH_FORWARD)
3539 entry = TAILQ_NEXT(s->selected_entry, entry);
3540 else
3541 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3542 entry);
3543 } else {
3544 entry = s->selected_entry;
3547 while (1) {
3548 int have_match = 0;
3550 if (entry == NULL) {
3551 if (s->thread_args.log_complete ||
3552 view->searching == TOG_SEARCH_BACKWARD) {
3553 view->search_next_done =
3554 (s->matched_entry == NULL ?
3555 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3556 s->search_entry = NULL;
3557 return NULL;
3560 * Poke the log thread for more commits and return,
3561 * allowing the main loop to make progress. Search
3562 * will resume at s->search_entry once we come back.
3564 s->thread_args.commits_needed++;
3565 return trigger_log_thread(view, 0);
3568 err = match_commit(&have_match, entry->id, entry->commit,
3569 &view->regex);
3570 if (err)
3571 break;
3572 if (have_match) {
3573 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3574 s->matched_entry = entry;
3575 break;
3578 s->search_entry = entry;
3579 if (view->searching == TOG_SEARCH_FORWARD)
3580 entry = TAILQ_NEXT(entry, entry);
3581 else
3582 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3585 if (s->matched_entry) {
3586 int cur = s->selected_entry->idx;
3587 while (cur < s->matched_entry->idx) {
3588 err = input_log_view(NULL, view, KEY_DOWN);
3589 if (err)
3590 return err;
3591 cur++;
3593 while (cur > s->matched_entry->idx) {
3594 err = input_log_view(NULL, view, KEY_UP);
3595 if (err)
3596 return err;
3597 cur--;
3601 s->search_entry = NULL;
3603 return NULL;
3606 static const struct got_error *
3607 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3608 struct got_repository *repo, const char *head_ref_name,
3609 const char *in_repo_path, int log_branches)
3611 const struct got_error *err = NULL;
3612 struct tog_log_view_state *s = &view->state.log;
3613 struct got_repository *thread_repo = NULL;
3614 struct got_commit_graph *thread_graph = NULL;
3615 int errcode;
3617 if (in_repo_path != s->in_repo_path) {
3618 free(s->in_repo_path);
3619 s->in_repo_path = strdup(in_repo_path);
3620 if (s->in_repo_path == NULL) {
3621 err = got_error_from_errno("strdup");
3622 goto done;
3626 /* The commit queue only contains commits being displayed. */
3627 TAILQ_INIT(&s->real_commits.head);
3628 s->real_commits.ncommits = 0;
3629 s->commits = &s->real_commits;
3631 TAILQ_INIT(&s->limit_commits.head);
3632 s->limit_view = 0;
3633 s->limit_commits.ncommits = 0;
3635 s->repo = repo;
3636 if (head_ref_name) {
3637 s->head_ref_name = strdup(head_ref_name);
3638 if (s->head_ref_name == NULL) {
3639 err = got_error_from_errno("strdup");
3640 goto done;
3643 s->start_id = got_object_id_dup(start_id);
3644 if (s->start_id == NULL) {
3645 err = got_error_from_errno("got_object_id_dup");
3646 goto done;
3648 s->log_branches = log_branches;
3649 s->use_committer = 1;
3651 STAILQ_INIT(&s->colors);
3652 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3653 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3654 get_color_value("TOG_COLOR_COMMIT"));
3655 if (err)
3656 goto done;
3657 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3658 get_color_value("TOG_COLOR_AUTHOR"));
3659 if (err) {
3660 free_colors(&s->colors);
3661 goto done;
3663 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3664 get_color_value("TOG_COLOR_DATE"));
3665 if (err) {
3666 free_colors(&s->colors);
3667 goto done;
3671 view->show = show_log_view;
3672 view->input = input_log_view;
3673 view->resize = resize_log_view;
3674 view->close = close_log_view;
3675 view->search_start = search_start_log_view;
3676 view->search_next = search_next_log_view;
3678 if (s->thread_args.pack_fds == NULL) {
3679 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3680 if (err)
3681 goto done;
3683 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3684 s->thread_args.pack_fds);
3685 if (err)
3686 goto done;
3687 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3688 !s->log_branches);
3689 if (err)
3690 goto done;
3691 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3692 s->repo, NULL, NULL);
3693 if (err)
3694 goto done;
3696 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3697 if (errcode) {
3698 err = got_error_set_errno(errcode, "pthread_cond_init");
3699 goto done;
3701 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3702 if (errcode) {
3703 err = got_error_set_errno(errcode, "pthread_cond_init");
3704 goto done;
3707 s->thread_args.commits_needed = view->nlines;
3708 s->thread_args.graph = thread_graph;
3709 s->thread_args.real_commits = &s->real_commits;
3710 s->thread_args.limit_commits = &s->limit_commits;
3711 s->thread_args.in_repo_path = s->in_repo_path;
3712 s->thread_args.start_id = s->start_id;
3713 s->thread_args.repo = thread_repo;
3714 s->thread_args.log_complete = 0;
3715 s->thread_args.quit = &s->quit;
3716 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3717 s->thread_args.selected_entry = &s->selected_entry;
3718 s->thread_args.searching = &view->searching;
3719 s->thread_args.search_next_done = &view->search_next_done;
3720 s->thread_args.regex = &view->regex;
3721 s->thread_args.limiting = &s->limit_view;
3722 s->thread_args.limit_regex = &s->limit_regex;
3723 s->thread_args.limit_commits = &s->limit_commits;
3724 done:
3725 if (err) {
3726 if (view->close == NULL)
3727 close_log_view(view);
3728 view_close(view);
3730 return err;
3733 static const struct got_error *
3734 show_log_view(struct tog_view *view)
3736 const struct got_error *err;
3737 struct tog_log_view_state *s = &view->state.log;
3739 if (s->thread == 0) { //NULL) {
3740 int errcode = pthread_create(&s->thread, NULL, log_thread,
3741 &s->thread_args);
3742 if (errcode)
3743 return got_error_set_errno(errcode, "pthread_create");
3744 if (s->thread_args.commits_needed > 0) {
3745 err = trigger_log_thread(view, 1);
3746 if (err)
3747 return err;
3751 return draw_commits(view);
3754 static void
3755 log_move_cursor_up(struct tog_view *view, int page, int home)
3757 struct tog_log_view_state *s = &view->state.log;
3759 if (s->first_displayed_entry == NULL)
3760 return;
3761 if (s->selected_entry->idx == 0)
3762 view->count = 0;
3764 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3765 || home)
3766 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3768 if (!page && !home && s->selected > 0)
3769 --s->selected;
3770 else
3771 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3773 select_commit(s);
3774 return;
3777 static const struct got_error *
3778 log_move_cursor_down(struct tog_view *view, int page)
3780 struct tog_log_view_state *s = &view->state.log;
3781 const struct got_error *err = NULL;
3782 int eos = view->nlines - 2;
3784 if (s->first_displayed_entry == NULL)
3785 return NULL;
3787 if (s->thread_args.log_complete &&
3788 s->selected_entry->idx >= s->commits->ncommits - 1)
3789 return NULL;
3791 if (view_is_hsplit_top(view))
3792 --eos; /* border consumes the last line */
3794 if (!page) {
3795 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3796 ++s->selected;
3797 else
3798 err = log_scroll_down(view, 1);
3799 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3800 struct commit_queue_entry *entry;
3801 int n;
3803 s->selected = 0;
3804 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3805 s->last_displayed_entry = entry;
3806 for (n = 0; n <= eos; n++) {
3807 if (entry == NULL)
3808 break;
3809 s->first_displayed_entry = entry;
3810 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3812 if (n > 0)
3813 s->selected = n - 1;
3814 } else {
3815 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3816 s->thread_args.log_complete)
3817 s->selected += MIN(page,
3818 s->commits->ncommits - s->selected_entry->idx - 1);
3819 else
3820 err = log_scroll_down(view, page);
3822 if (err)
3823 return err;
3826 * We might necessarily overshoot in horizontal
3827 * splits; if so, select the last displayed commit.
3829 if (s->first_displayed_entry && s->last_displayed_entry) {
3830 s->selected = MIN(s->selected,
3831 s->last_displayed_entry->idx -
3832 s->first_displayed_entry->idx);
3835 select_commit(s);
3837 if (s->thread_args.log_complete &&
3838 s->selected_entry->idx == s->commits->ncommits - 1)
3839 view->count = 0;
3841 return NULL;
3844 static void
3845 view_get_split(struct tog_view *view, int *y, int *x)
3847 *x = 0;
3848 *y = 0;
3850 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3851 if (view->child && view->child->resized_y)
3852 *y = view->child->resized_y;
3853 else if (view->resized_y)
3854 *y = view->resized_y;
3855 else
3856 *y = view_split_begin_y(view->lines);
3857 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3858 if (view->child && view->child->resized_x)
3859 *x = view->child->resized_x;
3860 else if (view->resized_x)
3861 *x = view->resized_x;
3862 else
3863 *x = view_split_begin_x(view->begin_x);
3867 /* Split view horizontally at y and offset view->state->selected line. */
3868 static const struct got_error *
3869 view_init_hsplit(struct tog_view *view, int y)
3871 const struct got_error *err = NULL;
3873 view->nlines = y;
3874 view->ncols = COLS;
3875 err = view_resize(view);
3876 if (err)
3877 return err;
3879 err = offset_selection_down(view);
3881 return err;
3884 static const struct got_error *
3885 log_goto_line(struct tog_view *view, int nlines)
3887 const struct got_error *err = NULL;
3888 struct tog_log_view_state *s = &view->state.log;
3889 int g, idx = s->selected_entry->idx;
3891 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3892 return NULL;
3894 g = view->gline;
3895 view->gline = 0;
3897 if (g >= s->first_displayed_entry->idx + 1 &&
3898 g <= s->last_displayed_entry->idx + 1 &&
3899 g - s->first_displayed_entry->idx - 1 < nlines) {
3900 s->selected = g - s->first_displayed_entry->idx - 1;
3901 select_commit(s);
3902 return NULL;
3905 if (idx + 1 < g) {
3906 err = log_move_cursor_down(view, g - idx - 1);
3907 if (!err && g > s->selected_entry->idx + 1)
3908 err = log_move_cursor_down(view,
3909 g - s->first_displayed_entry->idx - 1);
3910 if (err)
3911 return err;
3912 } else if (idx + 1 > g)
3913 log_move_cursor_up(view, idx - g + 1, 0);
3915 if (g < nlines && s->first_displayed_entry->idx == 0)
3916 s->selected = g - 1;
3918 select_commit(s);
3919 return NULL;
3923 static void
3924 horizontal_scroll_input(struct tog_view *view, int ch)
3927 switch (ch) {
3928 case KEY_LEFT:
3929 case 'h':
3930 view->x -= MIN(view->x, 2);
3931 if (view->x <= 0)
3932 view->count = 0;
3933 break;
3934 case KEY_RIGHT:
3935 case 'l':
3936 if (view->x + view->ncols / 2 < view->maxx)
3937 view->x += 2;
3938 else
3939 view->count = 0;
3940 break;
3941 case '0':
3942 view->x = 0;
3943 break;
3944 case '$':
3945 view->x = MAX(view->maxx - view->ncols / 2, 0);
3946 view->count = 0;
3947 break;
3948 default:
3949 break;
3953 static const struct got_error *
3954 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3956 const struct got_error *err = NULL;
3957 struct tog_log_view_state *s = &view->state.log;
3958 int eos, nscroll;
3960 if (s->thread_args.load_all) {
3961 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3962 s->thread_args.load_all = 0;
3963 else if (s->thread_args.log_complete) {
3964 err = log_move_cursor_down(view, s->commits->ncommits);
3965 s->thread_args.load_all = 0;
3967 if (err)
3968 return err;
3971 eos = nscroll = view->nlines - 1;
3972 if (view_is_hsplit_top(view))
3973 --eos; /* border */
3975 if (view->gline)
3976 return log_goto_line(view, eos);
3978 switch (ch) {
3979 case '&':
3980 err = limit_log_view(view);
3981 break;
3982 case 'q':
3983 s->quit = 1;
3984 break;
3985 case '0':
3986 case '$':
3987 case KEY_RIGHT:
3988 case 'l':
3989 case KEY_LEFT:
3990 case 'h':
3991 horizontal_scroll_input(view, ch);
3992 break;
3993 case 'k':
3994 case KEY_UP:
3995 case '<':
3996 case ',':
3997 case CTRL('p'):
3998 log_move_cursor_up(view, 0, 0);
3999 break;
4000 case 'g':
4001 case '=':
4002 case KEY_HOME:
4003 log_move_cursor_up(view, 0, 1);
4004 view->count = 0;
4005 break;
4006 case CTRL('u'):
4007 case 'u':
4008 nscroll /= 2;
4009 /* FALL THROUGH */
4010 case KEY_PPAGE:
4011 case CTRL('b'):
4012 case 'b':
4013 log_move_cursor_up(view, nscroll, 0);
4014 break;
4015 case 'j':
4016 case KEY_DOWN:
4017 case '>':
4018 case '.':
4019 case CTRL('n'):
4020 err = log_move_cursor_down(view, 0);
4021 break;
4022 case '@':
4023 s->use_committer = !s->use_committer;
4024 view->action = s->use_committer ?
4025 "show committer" : "show commit author";
4026 break;
4027 case 'G':
4028 case '*':
4029 case KEY_END: {
4030 /* We don't know yet how many commits, so we're forced to
4031 * traverse them all. */
4032 view->count = 0;
4033 s->thread_args.load_all = 1;
4034 if (!s->thread_args.log_complete)
4035 return trigger_log_thread(view, 0);
4036 err = log_move_cursor_down(view, s->commits->ncommits);
4037 s->thread_args.load_all = 0;
4038 break;
4040 case CTRL('d'):
4041 case 'd':
4042 nscroll /= 2;
4043 /* FALL THROUGH */
4044 case KEY_NPAGE:
4045 case CTRL('f'):
4046 case 'f':
4047 case ' ':
4048 err = log_move_cursor_down(view, nscroll);
4049 break;
4050 case KEY_RESIZE:
4051 if (s->selected > view->nlines - 2)
4052 s->selected = view->nlines - 2;
4053 if (s->selected > s->commits->ncommits - 1)
4054 s->selected = s->commits->ncommits - 1;
4055 select_commit(s);
4056 if (s->commits->ncommits < view->nlines - 1 &&
4057 !s->thread_args.log_complete) {
4058 s->thread_args.commits_needed += (view->nlines - 1) -
4059 s->commits->ncommits;
4060 err = trigger_log_thread(view, 1);
4062 break;
4063 case KEY_ENTER:
4064 case '\r':
4065 view->count = 0;
4066 if (s->selected_entry == NULL)
4067 break;
4068 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4069 break;
4070 case 'T':
4071 view->count = 0;
4072 if (s->selected_entry == NULL)
4073 break;
4074 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4075 break;
4076 case KEY_BACKSPACE:
4077 case CTRL('l'):
4078 case 'B':
4079 view->count = 0;
4080 if (ch == KEY_BACKSPACE &&
4081 got_path_is_root_dir(s->in_repo_path))
4082 break;
4083 err = stop_log_thread(s);
4084 if (err)
4085 return err;
4086 if (ch == KEY_BACKSPACE) {
4087 char *parent_path;
4088 err = got_path_dirname(&parent_path, s->in_repo_path);
4089 if (err)
4090 return err;
4091 free(s->in_repo_path);
4092 s->in_repo_path = parent_path;
4093 s->thread_args.in_repo_path = s->in_repo_path;
4094 } else if (ch == CTRL('l')) {
4095 struct got_object_id *start_id;
4096 err = got_repo_match_object_id(&start_id, NULL,
4097 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4098 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4099 if (err) {
4100 if (s->head_ref_name == NULL ||
4101 err->code != GOT_ERR_NOT_REF)
4102 return err;
4103 /* Try to cope with deleted references. */
4104 free(s->head_ref_name);
4105 s->head_ref_name = NULL;
4106 err = got_repo_match_object_id(&start_id,
4107 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4108 &tog_refs, s->repo);
4109 if (err)
4110 return err;
4112 free(s->start_id);
4113 s->start_id = start_id;
4114 s->thread_args.start_id = s->start_id;
4115 } else /* 'B' */
4116 s->log_branches = !s->log_branches;
4118 if (s->thread_args.pack_fds == NULL) {
4119 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4120 if (err)
4121 return err;
4123 err = got_repo_open(&s->thread_args.repo,
4124 got_repo_get_path(s->repo), NULL,
4125 s->thread_args.pack_fds);
4126 if (err)
4127 return err;
4128 tog_free_refs();
4129 err = tog_load_refs(s->repo, 0);
4130 if (err)
4131 return err;
4132 err = got_commit_graph_open(&s->thread_args.graph,
4133 s->in_repo_path, !s->log_branches);
4134 if (err)
4135 return err;
4136 err = got_commit_graph_iter_start(s->thread_args.graph,
4137 s->start_id, s->repo, NULL, NULL);
4138 if (err)
4139 return err;
4140 free_commits(&s->real_commits);
4141 free_commits(&s->limit_commits);
4142 s->first_displayed_entry = NULL;
4143 s->last_displayed_entry = NULL;
4144 s->selected_entry = NULL;
4145 s->selected = 0;
4146 s->thread_args.log_complete = 0;
4147 s->quit = 0;
4148 s->thread_args.commits_needed = view->lines;
4149 s->matched_entry = NULL;
4150 s->search_entry = NULL;
4151 view->offset = 0;
4152 break;
4153 case 'R':
4154 view->count = 0;
4155 err = view_request_new(new_view, view, TOG_VIEW_REF);
4156 break;
4157 default:
4158 view->count = 0;
4159 break;
4162 return err;
4165 static const struct got_error *
4166 apply_unveil(const char *repo_path, const char *worktree_path)
4168 const struct got_error *error;
4170 #ifdef PROFILE
4171 if (unveil("gmon.out", "rwc") != 0)
4172 return got_error_from_errno2("unveil", "gmon.out");
4173 #endif
4174 if (repo_path && unveil(repo_path, "r") != 0)
4175 return got_error_from_errno2("unveil", repo_path);
4177 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4178 return got_error_from_errno2("unveil", worktree_path);
4180 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4181 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4183 error = got_privsep_unveil_exec_helpers();
4184 if (error != NULL)
4185 return error;
4187 if (unveil(NULL, NULL) != 0)
4188 return got_error_from_errno("unveil");
4190 return NULL;
4193 static const struct got_error *
4194 init_mock_term(const char *test_script_path)
4196 const struct got_error *err = NULL;
4197 const char *screen_dump_path;
4198 int in;
4200 if (test_script_path == NULL || *test_script_path == '\0')
4201 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4203 tog_io.f = fopen(test_script_path, "re");
4204 if (tog_io.f == NULL) {
4205 err = got_error_from_errno_fmt("fopen: %s",
4206 test_script_path);
4207 goto done;
4210 /* test mode, we don't want any output */
4211 tog_io.cout = fopen("/dev/null", "w+");
4212 if (tog_io.cout == NULL) {
4213 err = got_error_from_errno2("fopen", "/dev/null");
4214 goto done;
4217 in = dup(fileno(tog_io.cout));
4218 if (in == -1) {
4219 err = got_error_from_errno("dup");
4220 goto done;
4222 tog_io.cin = fdopen(in, "r");
4223 if (tog_io.cin == NULL) {
4224 err = got_error_from_errno("fdopen");
4225 close(in);
4226 goto done;
4229 screen_dump_path = getenv("TOG_SCR_DUMP");
4230 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4231 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4232 tog_io.sdump = fopen(screen_dump_path, "wex");
4233 if (tog_io.sdump == NULL) {
4234 err = got_error_from_errno2("fopen", screen_dump_path);
4235 goto done;
4238 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4239 err = got_error_from_errno("fseeko");
4240 goto done;
4243 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4244 err = got_error_msg(GOT_ERR_IO,
4245 "newterm: failed to initialise curses");
4247 using_mock_io = 1;
4249 done:
4250 if (err)
4251 tog_io_close();
4252 return err;
4255 static void
4256 init_curses(void)
4259 * Override default signal handlers before starting ncurses.
4260 * This should prevent ncurses from installing its own
4261 * broken cleanup() signal handler.
4263 signal(SIGWINCH, tog_sigwinch);
4264 signal(SIGPIPE, tog_sigpipe);
4265 signal(SIGCONT, tog_sigcont);
4266 signal(SIGINT, tog_sigint);
4267 signal(SIGTERM, tog_sigterm);
4269 if (using_mock_io) /* In test mode we use a fake terminal */
4270 return;
4272 initscr();
4274 cbreak();
4275 halfdelay(1); /* Fast refresh while initial view is loading. */
4276 noecho();
4277 nonl();
4278 intrflush(stdscr, FALSE);
4279 keypad(stdscr, TRUE);
4280 curs_set(0);
4281 if (getenv("TOG_COLORS") != NULL) {
4282 start_color();
4283 use_default_colors();
4286 return;
4289 static const struct got_error *
4290 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4291 struct got_repository *repo, struct got_worktree *worktree)
4293 const struct got_error *err = NULL;
4295 if (argc == 0) {
4296 *in_repo_path = strdup("/");
4297 if (*in_repo_path == NULL)
4298 return got_error_from_errno("strdup");
4299 return NULL;
4302 if (worktree) {
4303 const char *prefix = got_worktree_get_path_prefix(worktree);
4304 char *p;
4306 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4307 if (err)
4308 return err;
4309 if (asprintf(in_repo_path, "%s%s%s", prefix,
4310 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4311 p) == -1) {
4312 err = got_error_from_errno("asprintf");
4313 *in_repo_path = NULL;
4315 free(p);
4316 } else
4317 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4319 return err;
4322 static const struct got_error *
4323 cmd_log(int argc, char *argv[])
4325 const struct got_error *error;
4326 struct got_repository *repo = NULL;
4327 struct got_worktree *worktree = NULL;
4328 struct got_object_id *start_id = NULL;
4329 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4330 char *start_commit = NULL, *label = NULL;
4331 struct got_reference *ref = NULL;
4332 const char *head_ref_name = NULL;
4333 int ch, log_branches = 0;
4334 struct tog_view *view;
4335 int *pack_fds = NULL;
4337 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4338 switch (ch) {
4339 case 'b':
4340 log_branches = 1;
4341 break;
4342 case 'c':
4343 start_commit = optarg;
4344 break;
4345 case 'r':
4346 repo_path = realpath(optarg, NULL);
4347 if (repo_path == NULL)
4348 return got_error_from_errno2("realpath",
4349 optarg);
4350 break;
4351 default:
4352 usage_log();
4353 /* NOTREACHED */
4357 argc -= optind;
4358 argv += optind;
4360 if (argc > 1)
4361 usage_log();
4363 error = got_repo_pack_fds_open(&pack_fds);
4364 if (error != NULL)
4365 goto done;
4367 if (repo_path == NULL) {
4368 cwd = getcwd(NULL, 0);
4369 if (cwd == NULL)
4370 return got_error_from_errno("getcwd");
4371 error = got_worktree_open(&worktree, cwd);
4372 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4373 goto done;
4374 if (worktree)
4375 repo_path =
4376 strdup(got_worktree_get_repo_path(worktree));
4377 else
4378 repo_path = strdup(cwd);
4379 if (repo_path == NULL) {
4380 error = got_error_from_errno("strdup");
4381 goto done;
4385 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4386 if (error != NULL)
4387 goto done;
4389 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4390 repo, worktree);
4391 if (error)
4392 goto done;
4394 init_curses();
4396 error = apply_unveil(got_repo_get_path(repo),
4397 worktree ? got_worktree_get_root_path(worktree) : NULL);
4398 if (error)
4399 goto done;
4401 /* already loaded by tog_log_with_path()? */
4402 if (TAILQ_EMPTY(&tog_refs)) {
4403 error = tog_load_refs(repo, 0);
4404 if (error)
4405 goto done;
4408 if (start_commit == NULL) {
4409 error = got_repo_match_object_id(&start_id, &label,
4410 worktree ? got_worktree_get_head_ref_name(worktree) :
4411 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4412 if (error)
4413 goto done;
4414 head_ref_name = label;
4415 } else {
4416 error = got_ref_open(&ref, repo, start_commit, 0);
4417 if (error == NULL)
4418 head_ref_name = got_ref_get_name(ref);
4419 else if (error->code != GOT_ERR_NOT_REF)
4420 goto done;
4421 error = got_repo_match_object_id(&start_id, NULL,
4422 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4423 if (error)
4424 goto done;
4427 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4428 if (view == NULL) {
4429 error = got_error_from_errno("view_open");
4430 goto done;
4432 error = open_log_view(view, start_id, repo, head_ref_name,
4433 in_repo_path, log_branches);
4434 if (error)
4435 goto done;
4436 if (worktree) {
4437 /* Release work tree lock. */
4438 got_worktree_close(worktree);
4439 worktree = NULL;
4441 error = view_loop(view);
4442 done:
4443 free(in_repo_path);
4444 free(repo_path);
4445 free(cwd);
4446 free(start_id);
4447 free(label);
4448 if (ref)
4449 got_ref_close(ref);
4450 if (repo) {
4451 const struct got_error *close_err = got_repo_close(repo);
4452 if (error == NULL)
4453 error = close_err;
4455 if (worktree)
4456 got_worktree_close(worktree);
4457 if (pack_fds) {
4458 const struct got_error *pack_err =
4459 got_repo_pack_fds_close(pack_fds);
4460 if (error == NULL)
4461 error = pack_err;
4463 tog_free_refs();
4464 return error;
4467 __dead static void
4468 usage_diff(void)
4470 endwin();
4471 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4472 "object1 object2\n", getprogname());
4473 exit(1);
4476 static int
4477 match_line(const char *line, regex_t *regex, size_t nmatch,
4478 regmatch_t *regmatch)
4480 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4483 static struct tog_color *
4484 match_color(struct tog_colors *colors, const char *line)
4486 struct tog_color *tc = NULL;
4488 STAILQ_FOREACH(tc, colors, entry) {
4489 if (match_line(line, &tc->regex, 0, NULL))
4490 return tc;
4493 return NULL;
4496 static const struct got_error *
4497 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4498 WINDOW *window, int skipcol, regmatch_t *regmatch)
4500 const struct got_error *err = NULL;
4501 char *exstr = NULL;
4502 wchar_t *wline = NULL;
4503 int rme, rms, n, width, scrollx;
4504 int width0 = 0, width1 = 0, width2 = 0;
4505 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4507 *wtotal = 0;
4509 rms = regmatch->rm_so;
4510 rme = regmatch->rm_eo;
4512 err = expand_tab(&exstr, line);
4513 if (err)
4514 return err;
4516 /* Split the line into 3 segments, according to match offsets. */
4517 seg0 = strndup(exstr, rms);
4518 if (seg0 == NULL) {
4519 err = got_error_from_errno("strndup");
4520 goto done;
4522 seg1 = strndup(exstr + rms, rme - rms);
4523 if (seg1 == NULL) {
4524 err = got_error_from_errno("strndup");
4525 goto done;
4527 seg2 = strdup(exstr + rme);
4528 if (seg2 == NULL) {
4529 err = got_error_from_errno("strndup");
4530 goto done;
4533 /* draw up to matched token if we haven't scrolled past it */
4534 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4535 col_tab_align, 1);
4536 if (err)
4537 goto done;
4538 n = MAX(width0 - skipcol, 0);
4539 if (n) {
4540 free(wline);
4541 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4542 wlimit, col_tab_align, 1);
4543 if (err)
4544 goto done;
4545 waddwstr(window, &wline[scrollx]);
4546 wlimit -= width;
4547 *wtotal += width;
4550 if (wlimit > 0) {
4551 int i = 0, w = 0;
4552 size_t wlen;
4554 free(wline);
4555 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4556 col_tab_align, 1);
4557 if (err)
4558 goto done;
4559 wlen = wcslen(wline);
4560 while (i < wlen) {
4561 width = wcwidth(wline[i]);
4562 if (width == -1) {
4563 /* should not happen, tabs are expanded */
4564 err = got_error(GOT_ERR_RANGE);
4565 goto done;
4567 if (width0 + w + width > skipcol)
4568 break;
4569 w += width;
4570 i++;
4572 /* draw (visible part of) matched token (if scrolled into it) */
4573 if (width1 - w > 0) {
4574 wattron(window, A_STANDOUT);
4575 waddwstr(window, &wline[i]);
4576 wattroff(window, A_STANDOUT);
4577 wlimit -= (width1 - w);
4578 *wtotal += (width1 - w);
4582 if (wlimit > 0) { /* draw rest of line */
4583 free(wline);
4584 if (skipcol > width0 + width1) {
4585 err = format_line(&wline, &width2, &scrollx, seg2,
4586 skipcol - (width0 + width1), wlimit,
4587 col_tab_align, 1);
4588 if (err)
4589 goto done;
4590 waddwstr(window, &wline[scrollx]);
4591 } else {
4592 err = format_line(&wline, &width2, NULL, seg2, 0,
4593 wlimit, col_tab_align, 1);
4594 if (err)
4595 goto done;
4596 waddwstr(window, wline);
4598 *wtotal += width2;
4600 done:
4601 free(wline);
4602 free(exstr);
4603 free(seg0);
4604 free(seg1);
4605 free(seg2);
4606 return err;
4609 static int
4610 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4612 FILE *f = NULL;
4613 int *eof, *first, *selected;
4615 if (view->type == TOG_VIEW_DIFF) {
4616 struct tog_diff_view_state *s = &view->state.diff;
4618 first = &s->first_displayed_line;
4619 selected = first;
4620 eof = &s->eof;
4621 f = s->f;
4622 } else if (view->type == TOG_VIEW_HELP) {
4623 struct tog_help_view_state *s = &view->state.help;
4625 first = &s->first_displayed_line;
4626 selected = first;
4627 eof = &s->eof;
4628 f = s->f;
4629 } else if (view->type == TOG_VIEW_BLAME) {
4630 struct tog_blame_view_state *s = &view->state.blame;
4632 first = &s->first_displayed_line;
4633 selected = &s->selected_line;
4634 eof = &s->eof;
4635 f = s->blame.f;
4636 } else
4637 return 0;
4639 /* Center gline in the middle of the page like vi(1). */
4640 if (*lineno < view->gline - (view->nlines - 3) / 2)
4641 return 0;
4642 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4643 rewind(f);
4644 *eof = 0;
4645 *first = 1;
4646 *lineno = 0;
4647 *nprinted = 0;
4648 return 0;
4651 *selected = view->gline <= (view->nlines - 3) / 2 ?
4652 view->gline : (view->nlines - 3) / 2 + 1;
4653 view->gline = 0;
4655 return 1;
4658 static const struct got_error *
4659 draw_file(struct tog_view *view, const char *header)
4661 struct tog_diff_view_state *s = &view->state.diff;
4662 regmatch_t *regmatch = &view->regmatch;
4663 const struct got_error *err;
4664 int nprinted = 0;
4665 char *line;
4666 size_t linesize = 0;
4667 ssize_t linelen;
4668 wchar_t *wline;
4669 int width;
4670 int max_lines = view->nlines;
4671 int nlines = s->nlines;
4672 off_t line_offset;
4674 s->lineno = s->first_displayed_line - 1;
4675 line_offset = s->lines[s->first_displayed_line - 1].offset;
4676 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4677 return got_error_from_errno("fseek");
4679 werase(view->window);
4681 if (view->gline > s->nlines - 1)
4682 view->gline = s->nlines - 1;
4684 if (header) {
4685 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4686 1 : view->gline - (view->nlines - 3) / 2 :
4687 s->lineno + s->selected_line;
4689 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4690 return got_error_from_errno("asprintf");
4691 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4692 0, 0);
4693 free(line);
4694 if (err)
4695 return err;
4697 if (view_needs_focus_indication(view))
4698 wstandout(view->window);
4699 waddwstr(view->window, wline);
4700 free(wline);
4701 wline = NULL;
4702 while (width++ < view->ncols)
4703 waddch(view->window, ' ');
4704 if (view_needs_focus_indication(view))
4705 wstandend(view->window);
4707 if (max_lines <= 1)
4708 return NULL;
4709 max_lines--;
4712 s->eof = 0;
4713 view->maxx = 0;
4714 line = NULL;
4715 while (max_lines > 0 && nprinted < max_lines) {
4716 enum got_diff_line_type linetype;
4717 attr_t attr = 0;
4719 linelen = getline(&line, &linesize, s->f);
4720 if (linelen == -1) {
4721 if (feof(s->f)) {
4722 s->eof = 1;
4723 break;
4725 free(line);
4726 return got_ferror(s->f, GOT_ERR_IO);
4729 if (++s->lineno < s->first_displayed_line)
4730 continue;
4731 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4732 continue;
4733 if (s->lineno == view->hiline)
4734 attr = A_STANDOUT;
4736 /* Set view->maxx based on full line length. */
4737 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4738 view->x ? 1 : 0);
4739 if (err) {
4740 free(line);
4741 return err;
4743 view->maxx = MAX(view->maxx, width);
4744 free(wline);
4745 wline = NULL;
4747 linetype = s->lines[s->lineno].type;
4748 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4749 linetype < GOT_DIFF_LINE_CONTEXT)
4750 attr |= COLOR_PAIR(linetype);
4751 if (attr)
4752 wattron(view->window, attr);
4753 if (s->first_displayed_line + nprinted == s->matched_line &&
4754 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4755 err = add_matched_line(&width, line, view->ncols, 0,
4756 view->window, view->x, regmatch);
4757 if (err) {
4758 free(line);
4759 return err;
4761 } else {
4762 int skip;
4763 err = format_line(&wline, &width, &skip, line,
4764 view->x, view->ncols, 0, view->x ? 1 : 0);
4765 if (err) {
4766 free(line);
4767 return err;
4769 waddwstr(view->window, &wline[skip]);
4770 free(wline);
4771 wline = NULL;
4773 if (s->lineno == view->hiline) {
4774 /* highlight full gline length */
4775 while (width++ < view->ncols)
4776 waddch(view->window, ' ');
4777 } else {
4778 if (width <= view->ncols - 1)
4779 waddch(view->window, '\n');
4781 if (attr)
4782 wattroff(view->window, attr);
4783 if (++nprinted == 1)
4784 s->first_displayed_line = s->lineno;
4786 free(line);
4787 if (nprinted >= 1)
4788 s->last_displayed_line = s->first_displayed_line +
4789 (nprinted - 1);
4790 else
4791 s->last_displayed_line = s->first_displayed_line;
4793 view_border(view);
4795 if (s->eof) {
4796 while (nprinted < view->nlines) {
4797 waddch(view->window, '\n');
4798 nprinted++;
4801 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4802 view->ncols, 0, 0);
4803 if (err) {
4804 return err;
4807 wstandout(view->window);
4808 waddwstr(view->window, wline);
4809 free(wline);
4810 wline = NULL;
4811 wstandend(view->window);
4814 return NULL;
4817 static char *
4818 get_datestr(time_t *time, char *datebuf)
4820 struct tm mytm, *tm;
4821 char *p, *s;
4823 tm = gmtime_r(time, &mytm);
4824 if (tm == NULL)
4825 return NULL;
4826 s = asctime_r(tm, datebuf);
4827 if (s == NULL)
4828 return NULL;
4829 p = strchr(s, '\n');
4830 if (p)
4831 *p = '\0';
4832 return s;
4835 static const struct got_error *
4836 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4837 off_t off, uint8_t type)
4839 struct got_diff_line *p;
4841 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4842 if (p == NULL)
4843 return got_error_from_errno("reallocarray");
4844 *lines = p;
4845 (*lines)[*nlines].offset = off;
4846 (*lines)[*nlines].type = type;
4847 (*nlines)++;
4849 return NULL;
4852 static const struct got_error *
4853 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4854 struct got_diff_line *s_lines, size_t s_nlines)
4856 struct got_diff_line *p;
4857 char buf[BUFSIZ];
4858 size_t i, r;
4860 if (fseeko(src, 0L, SEEK_SET) == -1)
4861 return got_error_from_errno("fseeko");
4863 for (;;) {
4864 r = fread(buf, 1, sizeof(buf), src);
4865 if (r == 0) {
4866 if (ferror(src))
4867 return got_error_from_errno("fread");
4868 if (feof(src))
4869 break;
4871 if (fwrite(buf, 1, r, dst) != r)
4872 return got_ferror(dst, GOT_ERR_IO);
4875 if (s_nlines == 0 && *d_nlines == 0)
4876 return NULL;
4879 * If commit info was in dst, increment line offsets
4880 * of the appended diff content, but skip s_lines[0]
4881 * because offset zero is already in *d_lines.
4883 if (*d_nlines > 0) {
4884 for (i = 1; i < s_nlines; ++i)
4885 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4887 if (s_nlines > 0) {
4888 --s_nlines;
4889 ++s_lines;
4893 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4894 if (p == NULL) {
4895 /* d_lines is freed in close_diff_view() */
4896 return got_error_from_errno("reallocarray");
4899 *d_lines = p;
4901 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4902 *d_nlines += s_nlines;
4904 return NULL;
4907 static const struct got_error *
4908 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4909 struct got_object_id *commit_id, struct got_reflist_head *refs,
4910 struct got_repository *repo, int ignore_ws, int force_text_diff,
4911 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4913 const struct got_error *err = NULL;
4914 char datebuf[26], *datestr;
4915 struct got_commit_object *commit;
4916 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4917 time_t committer_time;
4918 const char *author, *committer;
4919 char *refs_str = NULL;
4920 struct got_pathlist_entry *pe;
4921 off_t outoff = 0;
4922 int n;
4924 if (refs) {
4925 err = build_refs_str(&refs_str, refs, commit_id, repo);
4926 if (err)
4927 return err;
4930 err = got_object_open_as_commit(&commit, repo, commit_id);
4931 if (err)
4932 return err;
4934 err = got_object_id_str(&id_str, commit_id);
4935 if (err) {
4936 err = got_error_from_errno("got_object_id_str");
4937 goto done;
4940 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4941 if (err)
4942 goto done;
4944 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4945 refs_str ? refs_str : "", refs_str ? ")" : "");
4946 if (n < 0) {
4947 err = got_error_from_errno("fprintf");
4948 goto done;
4950 outoff += n;
4951 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4952 if (err)
4953 goto done;
4955 n = fprintf(outfile, "from: %s\n",
4956 got_object_commit_get_author(commit));
4957 if (n < 0) {
4958 err = got_error_from_errno("fprintf");
4959 goto done;
4961 outoff += n;
4962 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4963 if (err)
4964 goto done;
4966 author = got_object_commit_get_author(commit);
4967 committer = got_object_commit_get_committer(commit);
4968 if (strcmp(author, committer) != 0) {
4969 n = fprintf(outfile, "via: %s\n", committer);
4970 if (n < 0) {
4971 err = got_error_from_errno("fprintf");
4972 goto done;
4974 outoff += n;
4975 err = add_line_metadata(lines, nlines, outoff,
4976 GOT_DIFF_LINE_AUTHOR);
4977 if (err)
4978 goto done;
4980 committer_time = got_object_commit_get_committer_time(commit);
4981 datestr = get_datestr(&committer_time, datebuf);
4982 if (datestr) {
4983 n = fprintf(outfile, "date: %s UTC\n", datestr);
4984 if (n < 0) {
4985 err = got_error_from_errno("fprintf");
4986 goto done;
4988 outoff += n;
4989 err = add_line_metadata(lines, nlines, outoff,
4990 GOT_DIFF_LINE_DATE);
4991 if (err)
4992 goto done;
4994 if (got_object_commit_get_nparents(commit) > 1) {
4995 const struct got_object_id_queue *parent_ids;
4996 struct got_object_qid *qid;
4997 int pn = 1;
4998 parent_ids = got_object_commit_get_parent_ids(commit);
4999 STAILQ_FOREACH(qid, parent_ids, entry) {
5000 err = got_object_id_str(&id_str, &qid->id);
5001 if (err)
5002 goto done;
5003 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5004 if (n < 0) {
5005 err = got_error_from_errno("fprintf");
5006 goto done;
5008 outoff += n;
5009 err = add_line_metadata(lines, nlines, outoff,
5010 GOT_DIFF_LINE_META);
5011 if (err)
5012 goto done;
5013 free(id_str);
5014 id_str = NULL;
5018 err = got_object_commit_get_logmsg(&logmsg, commit);
5019 if (err)
5020 goto done;
5021 s = logmsg;
5022 while ((line = strsep(&s, "\n")) != NULL) {
5023 n = fprintf(outfile, "%s\n", line);
5024 if (n < 0) {
5025 err = got_error_from_errno("fprintf");
5026 goto done;
5028 outoff += n;
5029 err = add_line_metadata(lines, nlines, outoff,
5030 GOT_DIFF_LINE_LOGMSG);
5031 if (err)
5032 goto done;
5035 TAILQ_FOREACH(pe, dsa->paths, entry) {
5036 struct got_diff_changed_path *cp = pe->data;
5037 int pad = dsa->max_path_len - pe->path_len + 1;
5039 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5040 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5041 dsa->rm_cols + 1, cp->rm);
5042 if (n < 0) {
5043 err = got_error_from_errno("fprintf");
5044 goto done;
5046 outoff += n;
5047 err = add_line_metadata(lines, nlines, outoff,
5048 GOT_DIFF_LINE_CHANGES);
5049 if (err)
5050 goto done;
5053 fputc('\n', outfile);
5054 outoff++;
5055 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5056 if (err)
5057 goto done;
5059 n = fprintf(outfile,
5060 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5061 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5062 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5063 if (n < 0) {
5064 err = got_error_from_errno("fprintf");
5065 goto done;
5067 outoff += n;
5068 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5069 if (err)
5070 goto done;
5072 fputc('\n', outfile);
5073 outoff++;
5074 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5075 done:
5076 free(id_str);
5077 free(logmsg);
5078 free(refs_str);
5079 got_object_commit_close(commit);
5080 if (err) {
5081 free(*lines);
5082 *lines = NULL;
5083 *nlines = 0;
5085 return err;
5088 static const struct got_error *
5089 create_diff(struct tog_diff_view_state *s)
5091 const struct got_error *err = NULL;
5092 FILE *f = NULL, *tmp_diff_file = NULL;
5093 int obj_type;
5094 struct got_diff_line *lines = NULL;
5095 struct got_pathlist_head changed_paths;
5097 TAILQ_INIT(&changed_paths);
5099 free(s->lines);
5100 s->lines = malloc(sizeof(*s->lines));
5101 if (s->lines == NULL)
5102 return got_error_from_errno("malloc");
5103 s->nlines = 0;
5105 f = got_opentemp();
5106 if (f == NULL) {
5107 err = got_error_from_errno("got_opentemp");
5108 goto done;
5110 tmp_diff_file = got_opentemp();
5111 if (tmp_diff_file == NULL) {
5112 err = got_error_from_errno("got_opentemp");
5113 goto done;
5115 if (s->f && fclose(s->f) == EOF) {
5116 err = got_error_from_errno("fclose");
5117 goto done;
5119 s->f = f;
5121 if (s->id1)
5122 err = got_object_get_type(&obj_type, s->repo, s->id1);
5123 else
5124 err = got_object_get_type(&obj_type, s->repo, s->id2);
5125 if (err)
5126 goto done;
5128 switch (obj_type) {
5129 case GOT_OBJ_TYPE_BLOB:
5130 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5131 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5132 s->label1, s->label2, tog_diff_algo, s->diff_context,
5133 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5134 s->f);
5135 break;
5136 case GOT_OBJ_TYPE_TREE:
5137 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5138 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5139 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5140 s->force_text_diff, NULL, s->repo, s->f);
5141 break;
5142 case GOT_OBJ_TYPE_COMMIT: {
5143 const struct got_object_id_queue *parent_ids;
5144 struct got_object_qid *pid;
5145 struct got_commit_object *commit2;
5146 struct got_reflist_head *refs;
5147 size_t nlines = 0;
5148 struct got_diffstat_cb_arg dsa = {
5149 0, 0, 0, 0, 0, 0,
5150 &changed_paths,
5151 s->ignore_whitespace,
5152 s->force_text_diff,
5153 tog_diff_algo
5156 lines = malloc(sizeof(*lines));
5157 if (lines == NULL) {
5158 err = got_error_from_errno("malloc");
5159 goto done;
5162 /* build diff first in tmp file then append to commit info */
5163 err = got_diff_objects_as_commits(&lines, &nlines,
5164 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5165 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5166 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5167 if (err)
5168 break;
5170 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5171 if (err)
5172 goto done;
5173 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5174 /* Show commit info if we're diffing to a parent/root commit. */
5175 if (s->id1 == NULL) {
5176 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5177 refs, s->repo, s->ignore_whitespace,
5178 s->force_text_diff, &dsa, s->f);
5179 if (err)
5180 goto done;
5181 } else {
5182 parent_ids = got_object_commit_get_parent_ids(commit2);
5183 STAILQ_FOREACH(pid, parent_ids, entry) {
5184 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5185 err = write_commit_info(&s->lines,
5186 &s->nlines, s->id2, refs, s->repo,
5187 s->ignore_whitespace,
5188 s->force_text_diff, &dsa, s->f);
5189 if (err)
5190 goto done;
5191 break;
5195 got_object_commit_close(commit2);
5197 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5198 lines, nlines);
5199 break;
5201 default:
5202 err = got_error(GOT_ERR_OBJ_TYPE);
5203 break;
5205 done:
5206 free(lines);
5207 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5208 if (s->f && fflush(s->f) != 0 && err == NULL)
5209 err = got_error_from_errno("fflush");
5210 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5211 err = got_error_from_errno("fclose");
5212 return err;
5215 static void
5216 diff_view_indicate_progress(struct tog_view *view)
5218 mvwaddstr(view->window, 0, 0, "diffing...");
5219 update_panels();
5220 doupdate();
5223 static const struct got_error *
5224 search_start_diff_view(struct tog_view *view)
5226 struct tog_diff_view_state *s = &view->state.diff;
5228 s->matched_line = 0;
5229 return NULL;
5232 static void
5233 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5234 size_t *nlines, int **first, int **last, int **match, int **selected)
5236 struct tog_diff_view_state *s = &view->state.diff;
5238 *f = s->f;
5239 *nlines = s->nlines;
5240 *line_offsets = NULL;
5241 *match = &s->matched_line;
5242 *first = &s->first_displayed_line;
5243 *last = &s->last_displayed_line;
5244 *selected = &s->selected_line;
5247 static const struct got_error *
5248 search_next_view_match(struct tog_view *view)
5250 const struct got_error *err = NULL;
5251 FILE *f;
5252 int lineno;
5253 char *line = NULL;
5254 size_t linesize = 0;
5255 ssize_t linelen;
5256 off_t *line_offsets;
5257 size_t nlines = 0;
5258 int *first, *last, *match, *selected;
5260 if (!view->search_setup)
5261 return got_error_msg(GOT_ERR_NOT_IMPL,
5262 "view search not supported");
5263 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5264 &match, &selected);
5266 if (!view->searching) {
5267 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5268 return NULL;
5271 if (*match) {
5272 if (view->searching == TOG_SEARCH_FORWARD)
5273 lineno = *first + 1;
5274 else
5275 lineno = *first - 1;
5276 } else
5277 lineno = *first - 1 + *selected;
5279 while (1) {
5280 off_t offset;
5282 if (lineno <= 0 || lineno > nlines) {
5283 if (*match == 0) {
5284 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5285 break;
5288 if (view->searching == TOG_SEARCH_FORWARD)
5289 lineno = 1;
5290 else
5291 lineno = nlines;
5294 offset = view->type == TOG_VIEW_DIFF ?
5295 view->state.diff.lines[lineno - 1].offset :
5296 line_offsets[lineno - 1];
5297 if (fseeko(f, offset, SEEK_SET) != 0) {
5298 free(line);
5299 return got_error_from_errno("fseeko");
5301 linelen = getline(&line, &linesize, f);
5302 if (linelen != -1) {
5303 char *exstr;
5304 err = expand_tab(&exstr, line);
5305 if (err)
5306 break;
5307 if (match_line(exstr, &view->regex, 1,
5308 &view->regmatch)) {
5309 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5310 *match = lineno;
5311 free(exstr);
5312 break;
5314 free(exstr);
5316 if (view->searching == TOG_SEARCH_FORWARD)
5317 lineno++;
5318 else
5319 lineno--;
5321 free(line);
5323 if (*match) {
5324 *first = *match;
5325 *selected = 1;
5328 return err;
5331 static const struct got_error *
5332 close_diff_view(struct tog_view *view)
5334 const struct got_error *err = NULL;
5335 struct tog_diff_view_state *s = &view->state.diff;
5337 free(s->id1);
5338 s->id1 = NULL;
5339 free(s->id2);
5340 s->id2 = NULL;
5341 if (s->f && fclose(s->f) == EOF)
5342 err = got_error_from_errno("fclose");
5343 s->f = NULL;
5344 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5345 err = got_error_from_errno("fclose");
5346 s->f1 = NULL;
5347 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5348 err = got_error_from_errno("fclose");
5349 s->f2 = NULL;
5350 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5351 err = got_error_from_errno("close");
5352 s->fd1 = -1;
5353 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5354 err = got_error_from_errno("close");
5355 s->fd2 = -1;
5356 free(s->lines);
5357 s->lines = NULL;
5358 s->nlines = 0;
5359 return err;
5362 static const struct got_error *
5363 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5364 struct got_object_id *id2, const char *label1, const char *label2,
5365 int diff_context, int ignore_whitespace, int force_text_diff,
5366 struct tog_view *parent_view, struct got_repository *repo)
5368 const struct got_error *err;
5369 struct tog_diff_view_state *s = &view->state.diff;
5371 memset(s, 0, sizeof(*s));
5372 s->fd1 = -1;
5373 s->fd2 = -1;
5375 if (id1 != NULL && id2 != NULL) {
5376 int type1, type2;
5378 err = got_object_get_type(&type1, repo, id1);
5379 if (err)
5380 goto done;
5381 err = got_object_get_type(&type2, repo, id2);
5382 if (err)
5383 goto done;
5385 if (type1 != type2) {
5386 err = got_error(GOT_ERR_OBJ_TYPE);
5387 goto done;
5390 s->first_displayed_line = 1;
5391 s->last_displayed_line = view->nlines;
5392 s->selected_line = 1;
5393 s->repo = repo;
5394 s->id1 = id1;
5395 s->id2 = id2;
5396 s->label1 = label1;
5397 s->label2 = label2;
5399 if (id1) {
5400 s->id1 = got_object_id_dup(id1);
5401 if (s->id1 == NULL) {
5402 err = got_error_from_errno("got_object_id_dup");
5403 goto done;
5405 } else
5406 s->id1 = NULL;
5408 s->id2 = got_object_id_dup(id2);
5409 if (s->id2 == NULL) {
5410 err = got_error_from_errno("got_object_id_dup");
5411 goto done;
5414 s->f1 = got_opentemp();
5415 if (s->f1 == NULL) {
5416 err = got_error_from_errno("got_opentemp");
5417 goto done;
5420 s->f2 = got_opentemp();
5421 if (s->f2 == NULL) {
5422 err = got_error_from_errno("got_opentemp");
5423 goto done;
5426 s->fd1 = got_opentempfd();
5427 if (s->fd1 == -1) {
5428 err = got_error_from_errno("got_opentempfd");
5429 goto done;
5432 s->fd2 = got_opentempfd();
5433 if (s->fd2 == -1) {
5434 err = got_error_from_errno("got_opentempfd");
5435 goto done;
5438 s->diff_context = diff_context;
5439 s->ignore_whitespace = ignore_whitespace;
5440 s->force_text_diff = force_text_diff;
5441 s->parent_view = parent_view;
5442 s->repo = repo;
5444 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5445 int rc;
5447 rc = init_pair(GOT_DIFF_LINE_MINUS,
5448 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5449 if (rc != ERR)
5450 rc = init_pair(GOT_DIFF_LINE_PLUS,
5451 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5452 if (rc != ERR)
5453 rc = init_pair(GOT_DIFF_LINE_HUNK,
5454 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5455 if (rc != ERR)
5456 rc = init_pair(GOT_DIFF_LINE_META,
5457 get_color_value("TOG_COLOR_DIFF_META"), -1);
5458 if (rc != ERR)
5459 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5460 get_color_value("TOG_COLOR_DIFF_META"), -1);
5461 if (rc != ERR)
5462 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5463 get_color_value("TOG_COLOR_DIFF_META"), -1);
5464 if (rc != ERR)
5465 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5466 get_color_value("TOG_COLOR_DIFF_META"), -1);
5467 if (rc != ERR)
5468 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5469 get_color_value("TOG_COLOR_AUTHOR"), -1);
5470 if (rc != ERR)
5471 rc = init_pair(GOT_DIFF_LINE_DATE,
5472 get_color_value("TOG_COLOR_DATE"), -1);
5473 if (rc == ERR) {
5474 err = got_error(GOT_ERR_RANGE);
5475 goto done;
5479 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5480 view_is_splitscreen(view))
5481 show_log_view(parent_view); /* draw border */
5482 diff_view_indicate_progress(view);
5484 err = create_diff(s);
5486 view->show = show_diff_view;
5487 view->input = input_diff_view;
5488 view->reset = reset_diff_view;
5489 view->close = close_diff_view;
5490 view->search_start = search_start_diff_view;
5491 view->search_setup = search_setup_diff_view;
5492 view->search_next = search_next_view_match;
5493 done:
5494 if (err) {
5495 if (view->close == NULL)
5496 close_diff_view(view);
5497 view_close(view);
5499 return err;
5502 static const struct got_error *
5503 show_diff_view(struct tog_view *view)
5505 const struct got_error *err;
5506 struct tog_diff_view_state *s = &view->state.diff;
5507 char *id_str1 = NULL, *id_str2, *header;
5508 const char *label1, *label2;
5510 if (s->id1) {
5511 err = got_object_id_str(&id_str1, s->id1);
5512 if (err)
5513 return err;
5514 label1 = s->label1 ? s->label1 : id_str1;
5515 } else
5516 label1 = "/dev/null";
5518 err = got_object_id_str(&id_str2, s->id2);
5519 if (err)
5520 return err;
5521 label2 = s->label2 ? s->label2 : id_str2;
5523 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5524 err = got_error_from_errno("asprintf");
5525 free(id_str1);
5526 free(id_str2);
5527 return err;
5529 free(id_str1);
5530 free(id_str2);
5532 err = draw_file(view, header);
5533 free(header);
5534 return err;
5537 static const struct got_error *
5538 set_selected_commit(struct tog_diff_view_state *s,
5539 struct commit_queue_entry *entry)
5541 const struct got_error *err;
5542 const struct got_object_id_queue *parent_ids;
5543 struct got_commit_object *selected_commit;
5544 struct got_object_qid *pid;
5546 free(s->id2);
5547 s->id2 = got_object_id_dup(entry->id);
5548 if (s->id2 == NULL)
5549 return got_error_from_errno("got_object_id_dup");
5551 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5552 if (err)
5553 return err;
5554 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5555 free(s->id1);
5556 pid = STAILQ_FIRST(parent_ids);
5557 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5558 got_object_commit_close(selected_commit);
5559 return NULL;
5562 static const struct got_error *
5563 reset_diff_view(struct tog_view *view)
5565 struct tog_diff_view_state *s = &view->state.diff;
5567 view->count = 0;
5568 wclear(view->window);
5569 s->first_displayed_line = 1;
5570 s->last_displayed_line = view->nlines;
5571 s->matched_line = 0;
5572 diff_view_indicate_progress(view);
5573 return create_diff(s);
5576 static void
5577 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5579 int start, i;
5581 i = start = s->first_displayed_line - 1;
5583 while (s->lines[i].type != type) {
5584 if (i == 0)
5585 i = s->nlines - 1;
5586 if (--i == start)
5587 return; /* do nothing, requested type not in file */
5590 s->selected_line = 1;
5591 s->first_displayed_line = i;
5594 static void
5595 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5597 int start, i;
5599 i = start = s->first_displayed_line + 1;
5601 while (s->lines[i].type != type) {
5602 if (i == s->nlines - 1)
5603 i = 0;
5604 if (++i == start)
5605 return; /* do nothing, requested type not in file */
5608 s->selected_line = 1;
5609 s->first_displayed_line = i;
5612 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5613 int, int, int);
5614 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5615 int, int);
5617 static const struct got_error *
5618 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5620 const struct got_error *err = NULL;
5621 struct tog_diff_view_state *s = &view->state.diff;
5622 struct tog_log_view_state *ls;
5623 struct commit_queue_entry *old_selected_entry;
5624 char *line = NULL;
5625 size_t linesize = 0;
5626 ssize_t linelen;
5627 int i, nscroll = view->nlines - 1, up = 0;
5629 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5631 switch (ch) {
5632 case '0':
5633 case '$':
5634 case KEY_RIGHT:
5635 case 'l':
5636 case KEY_LEFT:
5637 case 'h':
5638 horizontal_scroll_input(view, ch);
5639 break;
5640 case 'a':
5641 case 'w':
5642 if (ch == 'a') {
5643 s->force_text_diff = !s->force_text_diff;
5644 view->action = s->force_text_diff ?
5645 "force ASCII text enabled" :
5646 "force ASCII text disabled";
5648 else if (ch == 'w') {
5649 s->ignore_whitespace = !s->ignore_whitespace;
5650 view->action = s->ignore_whitespace ?
5651 "ignore whitespace enabled" :
5652 "ignore whitespace disabled";
5654 err = reset_diff_view(view);
5655 break;
5656 case 'g':
5657 case KEY_HOME:
5658 s->first_displayed_line = 1;
5659 view->count = 0;
5660 break;
5661 case 'G':
5662 case KEY_END:
5663 view->count = 0;
5664 if (s->eof)
5665 break;
5667 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5668 s->eof = 1;
5669 break;
5670 case 'k':
5671 case KEY_UP:
5672 case CTRL('p'):
5673 if (s->first_displayed_line > 1)
5674 s->first_displayed_line--;
5675 else
5676 view->count = 0;
5677 break;
5678 case CTRL('u'):
5679 case 'u':
5680 nscroll /= 2;
5681 /* FALL THROUGH */
5682 case KEY_PPAGE:
5683 case CTRL('b'):
5684 case 'b':
5685 if (s->first_displayed_line == 1) {
5686 view->count = 0;
5687 break;
5689 i = 0;
5690 while (i++ < nscroll && s->first_displayed_line > 1)
5691 s->first_displayed_line--;
5692 break;
5693 case 'j':
5694 case KEY_DOWN:
5695 case CTRL('n'):
5696 if (!s->eof)
5697 s->first_displayed_line++;
5698 else
5699 view->count = 0;
5700 break;
5701 case CTRL('d'):
5702 case 'd':
5703 nscroll /= 2;
5704 /* FALL THROUGH */
5705 case KEY_NPAGE:
5706 case CTRL('f'):
5707 case 'f':
5708 case ' ':
5709 if (s->eof) {
5710 view->count = 0;
5711 break;
5713 i = 0;
5714 while (!s->eof && i++ < nscroll) {
5715 linelen = getline(&line, &linesize, s->f);
5716 s->first_displayed_line++;
5717 if (linelen == -1) {
5718 if (feof(s->f)) {
5719 s->eof = 1;
5720 } else
5721 err = got_ferror(s->f, GOT_ERR_IO);
5722 break;
5725 free(line);
5726 break;
5727 case '(':
5728 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5729 break;
5730 case ')':
5731 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5732 break;
5733 case '{':
5734 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5735 break;
5736 case '}':
5737 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5738 break;
5739 case '[':
5740 if (s->diff_context > 0) {
5741 s->diff_context--;
5742 s->matched_line = 0;
5743 diff_view_indicate_progress(view);
5744 err = create_diff(s);
5745 if (s->first_displayed_line + view->nlines - 1 >
5746 s->nlines) {
5747 s->first_displayed_line = 1;
5748 s->last_displayed_line = view->nlines;
5750 } else
5751 view->count = 0;
5752 break;
5753 case ']':
5754 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5755 s->diff_context++;
5756 s->matched_line = 0;
5757 diff_view_indicate_progress(view);
5758 err = create_diff(s);
5759 } else
5760 view->count = 0;
5761 break;
5762 case '<':
5763 case ',':
5764 case 'K':
5765 up = 1;
5766 /* FALL THROUGH */
5767 case '>':
5768 case '.':
5769 case 'J':
5770 if (s->parent_view == NULL) {
5771 view->count = 0;
5772 break;
5774 s->parent_view->count = view->count;
5776 if (s->parent_view->type == TOG_VIEW_LOG) {
5777 ls = &s->parent_view->state.log;
5778 old_selected_entry = ls->selected_entry;
5780 err = input_log_view(NULL, s->parent_view,
5781 up ? KEY_UP : KEY_DOWN);
5782 if (err)
5783 break;
5784 view->count = s->parent_view->count;
5786 if (old_selected_entry == ls->selected_entry)
5787 break;
5789 err = set_selected_commit(s, ls->selected_entry);
5790 if (err)
5791 break;
5792 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5793 struct tog_blame_view_state *bs;
5794 struct got_object_id *id, *prev_id;
5796 bs = &s->parent_view->state.blame;
5797 prev_id = get_annotation_for_line(bs->blame.lines,
5798 bs->blame.nlines, bs->last_diffed_line);
5800 err = input_blame_view(&view, s->parent_view,
5801 up ? KEY_UP : KEY_DOWN);
5802 if (err)
5803 break;
5804 view->count = s->parent_view->count;
5806 if (prev_id == NULL)
5807 break;
5808 id = get_selected_commit_id(bs->blame.lines,
5809 bs->blame.nlines, bs->first_displayed_line,
5810 bs->selected_line);
5811 if (id == NULL)
5812 break;
5814 if (!got_object_id_cmp(prev_id, id))
5815 break;
5817 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5818 if (err)
5819 break;
5821 s->first_displayed_line = 1;
5822 s->last_displayed_line = view->nlines;
5823 s->matched_line = 0;
5824 view->x = 0;
5826 diff_view_indicate_progress(view);
5827 err = create_diff(s);
5828 break;
5829 default:
5830 view->count = 0;
5831 break;
5834 return err;
5837 static const struct got_error *
5838 cmd_diff(int argc, char *argv[])
5840 const struct got_error *error;
5841 struct got_repository *repo = NULL;
5842 struct got_worktree *worktree = NULL;
5843 struct got_object_id *id1 = NULL, *id2 = NULL;
5844 char *repo_path = NULL, *cwd = NULL;
5845 char *id_str1 = NULL, *id_str2 = NULL;
5846 char *label1 = NULL, *label2 = NULL;
5847 int diff_context = 3, ignore_whitespace = 0;
5848 int ch, force_text_diff = 0;
5849 const char *errstr;
5850 struct tog_view *view;
5851 int *pack_fds = NULL;
5853 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5854 switch (ch) {
5855 case 'a':
5856 force_text_diff = 1;
5857 break;
5858 case 'C':
5859 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5860 &errstr);
5861 if (errstr != NULL)
5862 errx(1, "number of context lines is %s: %s",
5863 errstr, errstr);
5864 break;
5865 case 'r':
5866 repo_path = realpath(optarg, NULL);
5867 if (repo_path == NULL)
5868 return got_error_from_errno2("realpath",
5869 optarg);
5870 got_path_strip_trailing_slashes(repo_path);
5871 break;
5872 case 'w':
5873 ignore_whitespace = 1;
5874 break;
5875 default:
5876 usage_diff();
5877 /* NOTREACHED */
5881 argc -= optind;
5882 argv += optind;
5884 if (argc == 0) {
5885 usage_diff(); /* TODO show local worktree changes */
5886 } else if (argc == 2) {
5887 id_str1 = argv[0];
5888 id_str2 = argv[1];
5889 } else
5890 usage_diff();
5892 error = got_repo_pack_fds_open(&pack_fds);
5893 if (error)
5894 goto done;
5896 if (repo_path == NULL) {
5897 cwd = getcwd(NULL, 0);
5898 if (cwd == NULL)
5899 return got_error_from_errno("getcwd");
5900 error = got_worktree_open(&worktree, cwd);
5901 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5902 goto done;
5903 if (worktree)
5904 repo_path =
5905 strdup(got_worktree_get_repo_path(worktree));
5906 else
5907 repo_path = strdup(cwd);
5908 if (repo_path == NULL) {
5909 error = got_error_from_errno("strdup");
5910 goto done;
5914 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5915 if (error)
5916 goto done;
5918 init_curses();
5920 error = apply_unveil(got_repo_get_path(repo), NULL);
5921 if (error)
5922 goto done;
5924 error = tog_load_refs(repo, 0);
5925 if (error)
5926 goto done;
5928 error = got_repo_match_object_id(&id1, &label1, id_str1,
5929 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5930 if (error)
5931 goto done;
5933 error = got_repo_match_object_id(&id2, &label2, id_str2,
5934 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5935 if (error)
5936 goto done;
5938 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5939 if (view == NULL) {
5940 error = got_error_from_errno("view_open");
5941 goto done;
5943 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5944 ignore_whitespace, force_text_diff, NULL, repo);
5945 if (error)
5946 goto done;
5947 error = view_loop(view);
5948 done:
5949 free(label1);
5950 free(label2);
5951 free(repo_path);
5952 free(cwd);
5953 if (repo) {
5954 const struct got_error *close_err = got_repo_close(repo);
5955 if (error == NULL)
5956 error = close_err;
5958 if (worktree)
5959 got_worktree_close(worktree);
5960 if (pack_fds) {
5961 const struct got_error *pack_err =
5962 got_repo_pack_fds_close(pack_fds);
5963 if (error == NULL)
5964 error = pack_err;
5966 tog_free_refs();
5967 return error;
5970 __dead static void
5971 usage_blame(void)
5973 endwin();
5974 fprintf(stderr,
5975 "usage: %s blame [-c commit] [-r repository-path] path\n",
5976 getprogname());
5977 exit(1);
5980 struct tog_blame_line {
5981 int annotated;
5982 struct got_object_id *id;
5985 static const struct got_error *
5986 draw_blame(struct tog_view *view)
5988 struct tog_blame_view_state *s = &view->state.blame;
5989 struct tog_blame *blame = &s->blame;
5990 regmatch_t *regmatch = &view->regmatch;
5991 const struct got_error *err;
5992 int lineno = 0, nprinted = 0;
5993 char *line = NULL;
5994 size_t linesize = 0;
5995 ssize_t linelen;
5996 wchar_t *wline;
5997 int width;
5998 struct tog_blame_line *blame_line;
5999 struct got_object_id *prev_id = NULL;
6000 char *id_str;
6001 struct tog_color *tc;
6003 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6004 if (err)
6005 return err;
6007 rewind(blame->f);
6008 werase(view->window);
6010 if (asprintf(&line, "commit %s", id_str) == -1) {
6011 err = got_error_from_errno("asprintf");
6012 free(id_str);
6013 return err;
6016 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6017 free(line);
6018 line = NULL;
6019 if (err)
6020 return err;
6021 if (view_needs_focus_indication(view))
6022 wstandout(view->window);
6023 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6024 if (tc)
6025 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6026 waddwstr(view->window, wline);
6027 while (width++ < view->ncols)
6028 waddch(view->window, ' ');
6029 if (tc)
6030 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6031 if (view_needs_focus_indication(view))
6032 wstandend(view->window);
6033 free(wline);
6034 wline = NULL;
6036 if (view->gline > blame->nlines)
6037 view->gline = blame->nlines;
6039 if (tog_io.wait_for_ui) {
6040 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6041 int rc;
6043 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6044 if (rc)
6045 return got_error_set_errno(rc, "pthread_cond_wait");
6046 tog_io.wait_for_ui = 0;
6049 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6050 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6051 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6052 free(id_str);
6053 return got_error_from_errno("asprintf");
6055 free(id_str);
6056 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6057 free(line);
6058 line = NULL;
6059 if (err)
6060 return err;
6061 waddwstr(view->window, wline);
6062 free(wline);
6063 wline = NULL;
6064 if (width < view->ncols - 1)
6065 waddch(view->window, '\n');
6067 s->eof = 0;
6068 view->maxx = 0;
6069 while (nprinted < view->nlines - 2) {
6070 linelen = getline(&line, &linesize, blame->f);
6071 if (linelen == -1) {
6072 if (feof(blame->f)) {
6073 s->eof = 1;
6074 break;
6076 free(line);
6077 return got_ferror(blame->f, GOT_ERR_IO);
6079 if (++lineno < s->first_displayed_line)
6080 continue;
6081 if (view->gline && !gotoline(view, &lineno, &nprinted))
6082 continue;
6084 /* Set view->maxx based on full line length. */
6085 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6086 if (err) {
6087 free(line);
6088 return err;
6090 free(wline);
6091 wline = NULL;
6092 view->maxx = MAX(view->maxx, width);
6094 if (nprinted == s->selected_line - 1)
6095 wstandout(view->window);
6097 if (blame->nlines > 0) {
6098 blame_line = &blame->lines[lineno - 1];
6099 if (blame_line->annotated && prev_id &&
6100 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6101 !(nprinted == s->selected_line - 1)) {
6102 waddstr(view->window, " ");
6103 } else if (blame_line->annotated) {
6104 char *id_str;
6105 err = got_object_id_str(&id_str,
6106 blame_line->id);
6107 if (err) {
6108 free(line);
6109 return err;
6111 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6112 if (tc)
6113 wattr_on(view->window,
6114 COLOR_PAIR(tc->colorpair), NULL);
6115 wprintw(view->window, "%.8s", id_str);
6116 if (tc)
6117 wattr_off(view->window,
6118 COLOR_PAIR(tc->colorpair), NULL);
6119 free(id_str);
6120 prev_id = blame_line->id;
6121 } else {
6122 waddstr(view->window, "........");
6123 prev_id = NULL;
6125 } else {
6126 waddstr(view->window, "........");
6127 prev_id = NULL;
6130 if (nprinted == s->selected_line - 1)
6131 wstandend(view->window);
6132 waddstr(view->window, " ");
6134 if (view->ncols <= 9) {
6135 width = 9;
6136 } else if (s->first_displayed_line + nprinted ==
6137 s->matched_line &&
6138 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6139 err = add_matched_line(&width, line, view->ncols - 9, 9,
6140 view->window, view->x, regmatch);
6141 if (err) {
6142 free(line);
6143 return err;
6145 width += 9;
6146 } else {
6147 int skip;
6148 err = format_line(&wline, &width, &skip, line,
6149 view->x, view->ncols - 9, 9, 1);
6150 if (err) {
6151 free(line);
6152 return err;
6154 waddwstr(view->window, &wline[skip]);
6155 width += 9;
6156 free(wline);
6157 wline = NULL;
6160 if (width <= view->ncols - 1)
6161 waddch(view->window, '\n');
6162 if (++nprinted == 1)
6163 s->first_displayed_line = lineno;
6165 free(line);
6166 s->last_displayed_line = lineno;
6168 view_border(view);
6170 return NULL;
6173 static const struct got_error *
6174 blame_cb(void *arg, int nlines, int lineno,
6175 struct got_commit_object *commit, struct got_object_id *id)
6177 const struct got_error *err = NULL;
6178 struct tog_blame_cb_args *a = arg;
6179 struct tog_blame_line *line;
6180 int errcode;
6182 if (nlines != a->nlines ||
6183 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6184 return got_error(GOT_ERR_RANGE);
6186 errcode = pthread_mutex_lock(&tog_mutex);
6187 if (errcode)
6188 return got_error_set_errno(errcode, "pthread_mutex_lock");
6190 if (*a->quit) { /* user has quit the blame view */
6191 err = got_error(GOT_ERR_ITER_COMPLETED);
6192 goto done;
6195 if (lineno == -1)
6196 goto done; /* no change in this commit */
6198 line = &a->lines[lineno - 1];
6199 if (line->annotated)
6200 goto done;
6202 line->id = got_object_id_dup(id);
6203 if (line->id == NULL) {
6204 err = got_error_from_errno("got_object_id_dup");
6205 goto done;
6207 line->annotated = 1;
6208 done:
6209 errcode = pthread_mutex_unlock(&tog_mutex);
6210 if (errcode)
6211 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6212 return err;
6215 static void *
6216 blame_thread(void *arg)
6218 const struct got_error *err, *close_err;
6219 struct tog_blame_thread_args *ta = arg;
6220 struct tog_blame_cb_args *a = ta->cb_args;
6221 int errcode, fd1 = -1, fd2 = -1;
6222 FILE *f1 = NULL, *f2 = NULL;
6224 fd1 = got_opentempfd();
6225 if (fd1 == -1)
6226 return (void *)got_error_from_errno("got_opentempfd");
6228 fd2 = got_opentempfd();
6229 if (fd2 == -1) {
6230 err = got_error_from_errno("got_opentempfd");
6231 goto done;
6234 f1 = got_opentemp();
6235 if (f1 == NULL) {
6236 err = (void *)got_error_from_errno("got_opentemp");
6237 goto done;
6239 f2 = got_opentemp();
6240 if (f2 == NULL) {
6241 err = (void *)got_error_from_errno("got_opentemp");
6242 goto done;
6245 err = block_signals_used_by_main_thread();
6246 if (err)
6247 goto done;
6249 err = got_blame(ta->path, a->commit_id, ta->repo,
6250 tog_diff_algo, blame_cb, ta->cb_args,
6251 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6252 if (err && err->code == GOT_ERR_CANCELLED)
6253 err = NULL;
6255 errcode = pthread_mutex_lock(&tog_mutex);
6256 if (errcode) {
6257 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6258 goto done;
6261 close_err = got_repo_close(ta->repo);
6262 if (err == NULL)
6263 err = close_err;
6264 ta->repo = NULL;
6265 *ta->complete = 1;
6267 if (tog_io.wait_for_ui) {
6268 errcode = pthread_cond_signal(&ta->blame_complete);
6269 if (errcode && err == NULL)
6270 err = got_error_set_errno(errcode,
6271 "pthread_cond_signal");
6274 errcode = pthread_mutex_unlock(&tog_mutex);
6275 if (errcode && err == NULL)
6276 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6278 done:
6279 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6280 err = got_error_from_errno("close");
6281 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6282 err = got_error_from_errno("close");
6283 if (f1 && fclose(f1) == EOF && err == NULL)
6284 err = got_error_from_errno("fclose");
6285 if (f2 && fclose(f2) == EOF && err == NULL)
6286 err = got_error_from_errno("fclose");
6288 return (void *)err;
6291 static struct got_object_id *
6292 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6293 int first_displayed_line, int selected_line)
6295 struct tog_blame_line *line;
6297 if (nlines <= 0)
6298 return NULL;
6300 line = &lines[first_displayed_line - 1 + selected_line - 1];
6301 if (!line->annotated)
6302 return NULL;
6304 return line->id;
6307 static struct got_object_id *
6308 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6309 int lineno)
6311 struct tog_blame_line *line;
6313 if (nlines <= 0 || lineno >= nlines)
6314 return NULL;
6316 line = &lines[lineno - 1];
6317 if (!line->annotated)
6318 return NULL;
6320 return line->id;
6323 static const struct got_error *
6324 stop_blame(struct tog_blame *blame)
6326 const struct got_error *err = NULL;
6327 int i;
6329 if (blame->thread) {
6330 int errcode;
6331 errcode = pthread_mutex_unlock(&tog_mutex);
6332 if (errcode)
6333 return got_error_set_errno(errcode,
6334 "pthread_mutex_unlock");
6335 errcode = pthread_join(blame->thread, (void **)&err);
6336 if (errcode)
6337 return got_error_set_errno(errcode, "pthread_join");
6338 errcode = pthread_mutex_lock(&tog_mutex);
6339 if (errcode)
6340 return got_error_set_errno(errcode,
6341 "pthread_mutex_lock");
6342 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6343 err = NULL;
6344 blame->thread = 0; //NULL;
6346 if (blame->thread_args.repo) {
6347 const struct got_error *close_err;
6348 close_err = got_repo_close(blame->thread_args.repo);
6349 if (err == NULL)
6350 err = close_err;
6351 blame->thread_args.repo = NULL;
6353 if (blame->f) {
6354 if (fclose(blame->f) == EOF && err == NULL)
6355 err = got_error_from_errno("fclose");
6356 blame->f = NULL;
6358 if (blame->lines) {
6359 for (i = 0; i < blame->nlines; i++)
6360 free(blame->lines[i].id);
6361 free(blame->lines);
6362 blame->lines = NULL;
6364 free(blame->cb_args.commit_id);
6365 blame->cb_args.commit_id = NULL;
6366 if (blame->pack_fds) {
6367 const struct got_error *pack_err =
6368 got_repo_pack_fds_close(blame->pack_fds);
6369 if (err == NULL)
6370 err = pack_err;
6371 blame->pack_fds = NULL;
6373 return err;
6376 static const struct got_error *
6377 cancel_blame_view(void *arg)
6379 const struct got_error *err = NULL;
6380 int *done = arg;
6381 int errcode;
6383 errcode = pthread_mutex_lock(&tog_mutex);
6384 if (errcode)
6385 return got_error_set_errno(errcode,
6386 "pthread_mutex_unlock");
6388 if (*done)
6389 err = got_error(GOT_ERR_CANCELLED);
6391 errcode = pthread_mutex_unlock(&tog_mutex);
6392 if (errcode)
6393 return got_error_set_errno(errcode,
6394 "pthread_mutex_lock");
6396 return err;
6399 static const struct got_error *
6400 run_blame(struct tog_view *view)
6402 struct tog_blame_view_state *s = &view->state.blame;
6403 struct tog_blame *blame = &s->blame;
6404 const struct got_error *err = NULL;
6405 struct got_commit_object *commit = NULL;
6406 struct got_blob_object *blob = NULL;
6407 struct got_repository *thread_repo = NULL;
6408 struct got_object_id *obj_id = NULL;
6409 int obj_type, fd = -1;
6410 int *pack_fds = NULL;
6412 err = got_object_open_as_commit(&commit, s->repo,
6413 &s->blamed_commit->id);
6414 if (err)
6415 return err;
6417 fd = got_opentempfd();
6418 if (fd == -1) {
6419 err = got_error_from_errno("got_opentempfd");
6420 goto done;
6423 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6424 if (err)
6425 goto done;
6427 err = got_object_get_type(&obj_type, s->repo, obj_id);
6428 if (err)
6429 goto done;
6431 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6432 err = got_error(GOT_ERR_OBJ_TYPE);
6433 goto done;
6436 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6437 if (err)
6438 goto done;
6439 blame->f = got_opentemp();
6440 if (blame->f == NULL) {
6441 err = got_error_from_errno("got_opentemp");
6442 goto done;
6444 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6445 &blame->line_offsets, blame->f, blob);
6446 if (err)
6447 goto done;
6448 if (blame->nlines == 0) {
6449 s->blame_complete = 1;
6450 goto done;
6453 /* Don't include \n at EOF in the blame line count. */
6454 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6455 blame->nlines--;
6457 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6458 if (blame->lines == NULL) {
6459 err = got_error_from_errno("calloc");
6460 goto done;
6463 err = got_repo_pack_fds_open(&pack_fds);
6464 if (err)
6465 goto done;
6466 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6467 pack_fds);
6468 if (err)
6469 goto done;
6471 blame->pack_fds = pack_fds;
6472 blame->cb_args.view = view;
6473 blame->cb_args.lines = blame->lines;
6474 blame->cb_args.nlines = blame->nlines;
6475 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6476 if (blame->cb_args.commit_id == NULL) {
6477 err = got_error_from_errno("got_object_id_dup");
6478 goto done;
6480 blame->cb_args.quit = &s->done;
6482 blame->thread_args.path = s->path;
6483 blame->thread_args.repo = thread_repo;
6484 blame->thread_args.cb_args = &blame->cb_args;
6485 blame->thread_args.complete = &s->blame_complete;
6486 blame->thread_args.cancel_cb = cancel_blame_view;
6487 blame->thread_args.cancel_arg = &s->done;
6488 s->blame_complete = 0;
6490 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6491 s->first_displayed_line = 1;
6492 s->last_displayed_line = view->nlines;
6493 s->selected_line = 1;
6495 s->matched_line = 0;
6497 done:
6498 if (commit)
6499 got_object_commit_close(commit);
6500 if (fd != -1 && close(fd) == -1 && err == NULL)
6501 err = got_error_from_errno("close");
6502 if (blob)
6503 got_object_blob_close(blob);
6504 free(obj_id);
6505 if (err)
6506 stop_blame(blame);
6507 return err;
6510 static const struct got_error *
6511 open_blame_view(struct tog_view *view, char *path,
6512 struct got_object_id *commit_id, struct got_repository *repo)
6514 const struct got_error *err = NULL;
6515 struct tog_blame_view_state *s = &view->state.blame;
6517 STAILQ_INIT(&s->blamed_commits);
6519 s->path = strdup(path);
6520 if (s->path == NULL)
6521 return got_error_from_errno("strdup");
6523 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6524 if (err) {
6525 free(s->path);
6526 return err;
6529 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6530 s->first_displayed_line = 1;
6531 s->last_displayed_line = view->nlines;
6532 s->selected_line = 1;
6533 s->blame_complete = 0;
6534 s->repo = repo;
6535 s->commit_id = commit_id;
6536 memset(&s->blame, 0, sizeof(s->blame));
6538 STAILQ_INIT(&s->colors);
6539 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6540 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6541 get_color_value("TOG_COLOR_COMMIT"));
6542 if (err)
6543 return err;
6546 view->show = show_blame_view;
6547 view->input = input_blame_view;
6548 view->reset = reset_blame_view;
6549 view->close = close_blame_view;
6550 view->search_start = search_start_blame_view;
6551 view->search_setup = search_setup_blame_view;
6552 view->search_next = search_next_view_match;
6554 if (using_mock_io) {
6555 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6556 int rc;
6558 rc = pthread_cond_init(&bta->blame_complete, NULL);
6559 if (rc)
6560 return got_error_set_errno(rc, "pthread_cond_init");
6563 return run_blame(view);
6566 static const struct got_error *
6567 close_blame_view(struct tog_view *view)
6569 const struct got_error *err = NULL;
6570 struct tog_blame_view_state *s = &view->state.blame;
6572 if (s->blame.thread)
6573 err = stop_blame(&s->blame);
6575 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6576 struct got_object_qid *blamed_commit;
6577 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6578 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6579 got_object_qid_free(blamed_commit);
6582 if (using_mock_io) {
6583 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6584 int rc;
6586 rc = pthread_cond_destroy(&bta->blame_complete);
6587 if (rc && err == NULL)
6588 err = got_error_set_errno(rc, "pthread_cond_destroy");
6591 free(s->path);
6592 free_colors(&s->colors);
6593 return err;
6596 static const struct got_error *
6597 search_start_blame_view(struct tog_view *view)
6599 struct tog_blame_view_state *s = &view->state.blame;
6601 s->matched_line = 0;
6602 return NULL;
6605 static void
6606 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6607 size_t *nlines, int **first, int **last, int **match, int **selected)
6609 struct tog_blame_view_state *s = &view->state.blame;
6611 *f = s->blame.f;
6612 *nlines = s->blame.nlines;
6613 *line_offsets = s->blame.line_offsets;
6614 *match = &s->matched_line;
6615 *first = &s->first_displayed_line;
6616 *last = &s->last_displayed_line;
6617 *selected = &s->selected_line;
6620 static const struct got_error *
6621 show_blame_view(struct tog_view *view)
6623 const struct got_error *err = NULL;
6624 struct tog_blame_view_state *s = &view->state.blame;
6625 int errcode;
6627 if (s->blame.thread == 0 && !s->blame_complete) {
6628 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6629 &s->blame.thread_args);
6630 if (errcode)
6631 return got_error_set_errno(errcode, "pthread_create");
6633 if (!using_mock_io)
6634 halfdelay(1); /* fast refresh while annotating */
6637 if (s->blame_complete && !using_mock_io)
6638 halfdelay(10); /* disable fast refresh */
6640 err = draw_blame(view);
6642 view_border(view);
6643 return err;
6646 static const struct got_error *
6647 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6648 struct got_repository *repo, struct got_object_id *id)
6650 struct tog_view *log_view;
6651 const struct got_error *err = NULL;
6653 *new_view = NULL;
6655 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6656 if (log_view == NULL)
6657 return got_error_from_errno("view_open");
6659 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6660 if (err)
6661 view_close(log_view);
6662 else
6663 *new_view = log_view;
6665 return err;
6668 static const struct got_error *
6669 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6671 const struct got_error *err = NULL, *thread_err = NULL;
6672 struct tog_view *diff_view;
6673 struct tog_blame_view_state *s = &view->state.blame;
6674 int eos, nscroll, begin_y = 0, begin_x = 0;
6676 eos = nscroll = view->nlines - 2;
6677 if (view_is_hsplit_top(view))
6678 --eos; /* border */
6680 switch (ch) {
6681 case '0':
6682 case '$':
6683 case KEY_RIGHT:
6684 case 'l':
6685 case KEY_LEFT:
6686 case 'h':
6687 horizontal_scroll_input(view, ch);
6688 break;
6689 case 'q':
6690 s->done = 1;
6691 break;
6692 case 'g':
6693 case KEY_HOME:
6694 s->selected_line = 1;
6695 s->first_displayed_line = 1;
6696 view->count = 0;
6697 break;
6698 case 'G':
6699 case KEY_END:
6700 if (s->blame.nlines < eos) {
6701 s->selected_line = s->blame.nlines;
6702 s->first_displayed_line = 1;
6703 } else {
6704 s->selected_line = eos;
6705 s->first_displayed_line = s->blame.nlines - (eos - 1);
6707 view->count = 0;
6708 break;
6709 case 'k':
6710 case KEY_UP:
6711 case CTRL('p'):
6712 if (s->selected_line > 1)
6713 s->selected_line--;
6714 else if (s->selected_line == 1 &&
6715 s->first_displayed_line > 1)
6716 s->first_displayed_line--;
6717 else
6718 view->count = 0;
6719 break;
6720 case CTRL('u'):
6721 case 'u':
6722 nscroll /= 2;
6723 /* FALL THROUGH */
6724 case KEY_PPAGE:
6725 case CTRL('b'):
6726 case 'b':
6727 if (s->first_displayed_line == 1) {
6728 if (view->count > 1)
6729 nscroll += nscroll;
6730 s->selected_line = MAX(1, s->selected_line - nscroll);
6731 view->count = 0;
6732 break;
6734 if (s->first_displayed_line > nscroll)
6735 s->first_displayed_line -= nscroll;
6736 else
6737 s->first_displayed_line = 1;
6738 break;
6739 case 'j':
6740 case KEY_DOWN:
6741 case CTRL('n'):
6742 if (s->selected_line < eos && s->first_displayed_line +
6743 s->selected_line <= s->blame.nlines)
6744 s->selected_line++;
6745 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6746 s->first_displayed_line++;
6747 else
6748 view->count = 0;
6749 break;
6750 case 'c':
6751 case 'p': {
6752 struct got_object_id *id = NULL;
6754 view->count = 0;
6755 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6756 s->first_displayed_line, s->selected_line);
6757 if (id == NULL)
6758 break;
6759 if (ch == 'p') {
6760 struct got_commit_object *commit, *pcommit;
6761 struct got_object_qid *pid;
6762 struct got_object_id *blob_id = NULL;
6763 int obj_type;
6764 err = got_object_open_as_commit(&commit,
6765 s->repo, id);
6766 if (err)
6767 break;
6768 pid = STAILQ_FIRST(
6769 got_object_commit_get_parent_ids(commit));
6770 if (pid == NULL) {
6771 got_object_commit_close(commit);
6772 break;
6774 /* Check if path history ends here. */
6775 err = got_object_open_as_commit(&pcommit,
6776 s->repo, &pid->id);
6777 if (err)
6778 break;
6779 err = got_object_id_by_path(&blob_id, s->repo,
6780 pcommit, s->path);
6781 got_object_commit_close(pcommit);
6782 if (err) {
6783 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6784 err = NULL;
6785 got_object_commit_close(commit);
6786 break;
6788 err = got_object_get_type(&obj_type, s->repo,
6789 blob_id);
6790 free(blob_id);
6791 /* Can't blame non-blob type objects. */
6792 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6793 got_object_commit_close(commit);
6794 break;
6796 err = got_object_qid_alloc(&s->blamed_commit,
6797 &pid->id);
6798 got_object_commit_close(commit);
6799 } else {
6800 if (got_object_id_cmp(id,
6801 &s->blamed_commit->id) == 0)
6802 break;
6803 err = got_object_qid_alloc(&s->blamed_commit,
6804 id);
6806 if (err)
6807 break;
6808 s->done = 1;
6809 thread_err = stop_blame(&s->blame);
6810 s->done = 0;
6811 if (thread_err)
6812 break;
6813 STAILQ_INSERT_HEAD(&s->blamed_commits,
6814 s->blamed_commit, entry);
6815 err = run_blame(view);
6816 if (err)
6817 break;
6818 break;
6820 case 'C': {
6821 struct got_object_qid *first;
6823 view->count = 0;
6824 first = STAILQ_FIRST(&s->blamed_commits);
6825 if (!got_object_id_cmp(&first->id, s->commit_id))
6826 break;
6827 s->done = 1;
6828 thread_err = stop_blame(&s->blame);
6829 s->done = 0;
6830 if (thread_err)
6831 break;
6832 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6833 got_object_qid_free(s->blamed_commit);
6834 s->blamed_commit =
6835 STAILQ_FIRST(&s->blamed_commits);
6836 err = run_blame(view);
6837 if (err)
6838 break;
6839 break;
6841 case 'L':
6842 view->count = 0;
6843 s->id_to_log = get_selected_commit_id(s->blame.lines,
6844 s->blame.nlines, s->first_displayed_line, s->selected_line);
6845 if (s->id_to_log)
6846 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6847 break;
6848 case KEY_ENTER:
6849 case '\r': {
6850 struct got_object_id *id = NULL;
6851 struct got_object_qid *pid;
6852 struct got_commit_object *commit = NULL;
6854 view->count = 0;
6855 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6856 s->first_displayed_line, s->selected_line);
6857 if (id == NULL)
6858 break;
6859 err = got_object_open_as_commit(&commit, s->repo, id);
6860 if (err)
6861 break;
6862 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6863 if (*new_view) {
6864 /* traversed from diff view, release diff resources */
6865 err = close_diff_view(*new_view);
6866 if (err)
6867 break;
6868 diff_view = *new_view;
6869 } else {
6870 if (view_is_parent_view(view))
6871 view_get_split(view, &begin_y, &begin_x);
6873 diff_view = view_open(0, 0, begin_y, begin_x,
6874 TOG_VIEW_DIFF);
6875 if (diff_view == NULL) {
6876 got_object_commit_close(commit);
6877 err = got_error_from_errno("view_open");
6878 break;
6881 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6882 id, NULL, NULL, 3, 0, 0, view, s->repo);
6883 got_object_commit_close(commit);
6884 if (err) {
6885 view_close(diff_view);
6886 break;
6888 s->last_diffed_line = s->first_displayed_line - 1 +
6889 s->selected_line;
6890 if (*new_view)
6891 break; /* still open from active diff view */
6892 if (view_is_parent_view(view) &&
6893 view->mode == TOG_VIEW_SPLIT_HRZN) {
6894 err = view_init_hsplit(view, begin_y);
6895 if (err)
6896 break;
6899 view->focussed = 0;
6900 diff_view->focussed = 1;
6901 diff_view->mode = view->mode;
6902 diff_view->nlines = view->lines - begin_y;
6903 if (view_is_parent_view(view)) {
6904 view_transfer_size(diff_view, view);
6905 err = view_close_child(view);
6906 if (err)
6907 break;
6908 err = view_set_child(view, diff_view);
6909 if (err)
6910 break;
6911 view->focus_child = 1;
6912 } else
6913 *new_view = diff_view;
6914 if (err)
6915 break;
6916 break;
6918 case CTRL('d'):
6919 case 'd':
6920 nscroll /= 2;
6921 /* FALL THROUGH */
6922 case KEY_NPAGE:
6923 case CTRL('f'):
6924 case 'f':
6925 case ' ':
6926 if (s->last_displayed_line >= s->blame.nlines &&
6927 s->selected_line >= MIN(s->blame.nlines,
6928 view->nlines - 2)) {
6929 view->count = 0;
6930 break;
6932 if (s->last_displayed_line >= s->blame.nlines &&
6933 s->selected_line < view->nlines - 2) {
6934 s->selected_line +=
6935 MIN(nscroll, s->last_displayed_line -
6936 s->first_displayed_line - s->selected_line + 1);
6938 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6939 s->first_displayed_line += nscroll;
6940 else
6941 s->first_displayed_line =
6942 s->blame.nlines - (view->nlines - 3);
6943 break;
6944 case KEY_RESIZE:
6945 if (s->selected_line > view->nlines - 2) {
6946 s->selected_line = MIN(s->blame.nlines,
6947 view->nlines - 2);
6949 break;
6950 default:
6951 view->count = 0;
6952 break;
6954 return thread_err ? thread_err : err;
6957 static const struct got_error *
6958 reset_blame_view(struct tog_view *view)
6960 const struct got_error *err;
6961 struct tog_blame_view_state *s = &view->state.blame;
6963 view->count = 0;
6964 s->done = 1;
6965 err = stop_blame(&s->blame);
6966 s->done = 0;
6967 if (err)
6968 return err;
6969 return run_blame(view);
6972 static const struct got_error *
6973 cmd_blame(int argc, char *argv[])
6975 const struct got_error *error;
6976 struct got_repository *repo = NULL;
6977 struct got_worktree *worktree = NULL;
6978 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6979 char *link_target = NULL;
6980 struct got_object_id *commit_id = NULL;
6981 struct got_commit_object *commit = NULL;
6982 char *commit_id_str = NULL;
6983 int ch;
6984 struct tog_view *view = NULL;
6985 int *pack_fds = NULL;
6987 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6988 switch (ch) {
6989 case 'c':
6990 commit_id_str = optarg;
6991 break;
6992 case 'r':
6993 repo_path = realpath(optarg, NULL);
6994 if (repo_path == NULL)
6995 return got_error_from_errno2("realpath",
6996 optarg);
6997 break;
6998 default:
6999 usage_blame();
7000 /* NOTREACHED */
7004 argc -= optind;
7005 argv += optind;
7007 if (argc != 1)
7008 usage_blame();
7010 error = got_repo_pack_fds_open(&pack_fds);
7011 if (error != NULL)
7012 goto done;
7014 if (repo_path == NULL) {
7015 cwd = getcwd(NULL, 0);
7016 if (cwd == NULL)
7017 return got_error_from_errno("getcwd");
7018 error = got_worktree_open(&worktree, cwd);
7019 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7020 goto done;
7021 if (worktree)
7022 repo_path =
7023 strdup(got_worktree_get_repo_path(worktree));
7024 else
7025 repo_path = strdup(cwd);
7026 if (repo_path == NULL) {
7027 error = got_error_from_errno("strdup");
7028 goto done;
7032 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7033 if (error != NULL)
7034 goto done;
7036 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7037 worktree);
7038 if (error)
7039 goto done;
7041 init_curses();
7043 error = apply_unveil(got_repo_get_path(repo), NULL);
7044 if (error)
7045 goto done;
7047 error = tog_load_refs(repo, 0);
7048 if (error)
7049 goto done;
7051 if (commit_id_str == NULL) {
7052 struct got_reference *head_ref;
7053 error = got_ref_open(&head_ref, repo, worktree ?
7054 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7055 if (error != NULL)
7056 goto done;
7057 error = got_ref_resolve(&commit_id, repo, head_ref);
7058 got_ref_close(head_ref);
7059 } else {
7060 error = got_repo_match_object_id(&commit_id, NULL,
7061 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7063 if (error != NULL)
7064 goto done;
7066 error = got_object_open_as_commit(&commit, repo, commit_id);
7067 if (error)
7068 goto done;
7070 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7071 commit, repo);
7072 if (error)
7073 goto done;
7075 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7076 if (view == NULL) {
7077 error = got_error_from_errno("view_open");
7078 goto done;
7080 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7081 commit_id, repo);
7082 if (error != NULL) {
7083 if (view->close == NULL)
7084 close_blame_view(view);
7085 view_close(view);
7086 goto done;
7088 if (worktree) {
7089 /* Release work tree lock. */
7090 got_worktree_close(worktree);
7091 worktree = NULL;
7093 error = view_loop(view);
7094 done:
7095 free(repo_path);
7096 free(in_repo_path);
7097 free(link_target);
7098 free(cwd);
7099 free(commit_id);
7100 if (commit)
7101 got_object_commit_close(commit);
7102 if (worktree)
7103 got_worktree_close(worktree);
7104 if (repo) {
7105 const struct got_error *close_err = got_repo_close(repo);
7106 if (error == NULL)
7107 error = close_err;
7109 if (pack_fds) {
7110 const struct got_error *pack_err =
7111 got_repo_pack_fds_close(pack_fds);
7112 if (error == NULL)
7113 error = pack_err;
7115 tog_free_refs();
7116 return error;
7119 static const struct got_error *
7120 draw_tree_entries(struct tog_view *view, const char *parent_path)
7122 struct tog_tree_view_state *s = &view->state.tree;
7123 const struct got_error *err = NULL;
7124 struct got_tree_entry *te;
7125 wchar_t *wline;
7126 char *index = NULL;
7127 struct tog_color *tc;
7128 int width, n, nentries, scrollx, i = 1;
7129 int limit = view->nlines;
7131 s->ndisplayed = 0;
7132 if (view_is_hsplit_top(view))
7133 --limit; /* border */
7135 werase(view->window);
7137 if (limit == 0)
7138 return NULL;
7140 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7141 0, 0);
7142 if (err)
7143 return err;
7144 if (view_needs_focus_indication(view))
7145 wstandout(view->window);
7146 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7147 if (tc)
7148 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7149 waddwstr(view->window, wline);
7150 free(wline);
7151 wline = NULL;
7152 while (width++ < view->ncols)
7153 waddch(view->window, ' ');
7154 if (tc)
7155 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7156 if (view_needs_focus_indication(view))
7157 wstandend(view->window);
7158 if (--limit <= 0)
7159 return NULL;
7161 i += s->selected;
7162 if (s->first_displayed_entry) {
7163 i += got_tree_entry_get_index(s->first_displayed_entry);
7164 if (s->tree != s->root)
7165 ++i; /* account for ".." entry */
7167 nentries = got_object_tree_get_nentries(s->tree);
7168 if (asprintf(&index, "[%d/%d] %s",
7169 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7170 return got_error_from_errno("asprintf");
7171 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7172 free(index);
7173 if (err)
7174 return err;
7175 waddwstr(view->window, wline);
7176 free(wline);
7177 wline = NULL;
7178 if (width < view->ncols - 1)
7179 waddch(view->window, '\n');
7180 if (--limit <= 0)
7181 return NULL;
7182 waddch(view->window, '\n');
7183 if (--limit <= 0)
7184 return NULL;
7186 if (s->first_displayed_entry == NULL) {
7187 te = got_object_tree_get_first_entry(s->tree);
7188 if (s->selected == 0) {
7189 if (view->focussed)
7190 wstandout(view->window);
7191 s->selected_entry = NULL;
7193 waddstr(view->window, " ..\n"); /* parent directory */
7194 if (s->selected == 0 && view->focussed)
7195 wstandend(view->window);
7196 s->ndisplayed++;
7197 if (--limit <= 0)
7198 return NULL;
7199 n = 1;
7200 } else {
7201 n = 0;
7202 te = s->first_displayed_entry;
7205 view->maxx = 0;
7206 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7207 char *line = NULL, *id_str = NULL, *link_target = NULL;
7208 const char *modestr = "";
7209 mode_t mode;
7211 te = got_object_tree_get_entry(s->tree, i);
7212 mode = got_tree_entry_get_mode(te);
7214 if (s->show_ids) {
7215 err = got_object_id_str(&id_str,
7216 got_tree_entry_get_id(te));
7217 if (err)
7218 return got_error_from_errno(
7219 "got_object_id_str");
7221 if (got_object_tree_entry_is_submodule(te))
7222 modestr = "$";
7223 else if (S_ISLNK(mode)) {
7224 int i;
7226 err = got_tree_entry_get_symlink_target(&link_target,
7227 te, s->repo);
7228 if (err) {
7229 free(id_str);
7230 return err;
7232 for (i = 0; i < strlen(link_target); i++) {
7233 if (!isprint((unsigned char)link_target[i]))
7234 link_target[i] = '?';
7236 modestr = "@";
7238 else if (S_ISDIR(mode))
7239 modestr = "/";
7240 else if (mode & S_IXUSR)
7241 modestr = "*";
7242 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7243 got_tree_entry_get_name(te), modestr,
7244 link_target ? " -> ": "",
7245 link_target ? link_target : "") == -1) {
7246 free(id_str);
7247 free(link_target);
7248 return got_error_from_errno("asprintf");
7250 free(id_str);
7251 free(link_target);
7253 /* use full line width to determine view->maxx */
7254 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7255 if (err) {
7256 free(line);
7257 break;
7259 view->maxx = MAX(view->maxx, width);
7260 free(wline);
7261 wline = NULL;
7263 err = format_line(&wline, &width, &scrollx, line, view->x,
7264 view->ncols, 0, 0);
7265 if (err) {
7266 free(line);
7267 break;
7269 if (n == s->selected) {
7270 if (view->focussed)
7271 wstandout(view->window);
7272 s->selected_entry = te;
7274 tc = match_color(&s->colors, line);
7275 if (tc)
7276 wattr_on(view->window,
7277 COLOR_PAIR(tc->colorpair), NULL);
7278 waddwstr(view->window, &wline[scrollx]);
7279 if (tc)
7280 wattr_off(view->window,
7281 COLOR_PAIR(tc->colorpair), NULL);
7282 if (width < view->ncols)
7283 waddch(view->window, '\n');
7284 if (n == s->selected && view->focussed)
7285 wstandend(view->window);
7286 free(line);
7287 free(wline);
7288 wline = NULL;
7289 n++;
7290 s->ndisplayed++;
7291 s->last_displayed_entry = te;
7292 if (--limit <= 0)
7293 break;
7296 return err;
7299 static void
7300 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7302 struct got_tree_entry *te;
7303 int isroot = s->tree == s->root;
7304 int i = 0;
7306 if (s->first_displayed_entry == NULL)
7307 return;
7309 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7310 while (i++ < maxscroll) {
7311 if (te == NULL) {
7312 if (!isroot)
7313 s->first_displayed_entry = NULL;
7314 break;
7316 s->first_displayed_entry = te;
7317 te = got_tree_entry_get_prev(s->tree, te);
7321 static const struct got_error *
7322 tree_scroll_down(struct tog_view *view, int maxscroll)
7324 struct tog_tree_view_state *s = &view->state.tree;
7325 struct got_tree_entry *next, *last;
7326 int n = 0;
7328 if (s->first_displayed_entry)
7329 next = got_tree_entry_get_next(s->tree,
7330 s->first_displayed_entry);
7331 else
7332 next = got_object_tree_get_first_entry(s->tree);
7334 last = s->last_displayed_entry;
7335 while (next && n++ < maxscroll) {
7336 if (last) {
7337 s->last_displayed_entry = last;
7338 last = got_tree_entry_get_next(s->tree, last);
7340 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7341 s->first_displayed_entry = next;
7342 next = got_tree_entry_get_next(s->tree, next);
7346 return NULL;
7349 static const struct got_error *
7350 tree_entry_path(char **path, struct tog_parent_trees *parents,
7351 struct got_tree_entry *te)
7353 const struct got_error *err = NULL;
7354 struct tog_parent_tree *pt;
7355 size_t len = 2; /* for leading slash and NUL */
7357 TAILQ_FOREACH(pt, parents, entry)
7358 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7359 + 1 /* slash */;
7360 if (te)
7361 len += strlen(got_tree_entry_get_name(te));
7363 *path = calloc(1, len);
7364 if (path == NULL)
7365 return got_error_from_errno("calloc");
7367 (*path)[0] = '/';
7368 pt = TAILQ_LAST(parents, tog_parent_trees);
7369 while (pt) {
7370 const char *name = got_tree_entry_get_name(pt->selected_entry);
7371 if (strlcat(*path, name, len) >= len) {
7372 err = got_error(GOT_ERR_NO_SPACE);
7373 goto done;
7375 if (strlcat(*path, "/", len) >= len) {
7376 err = got_error(GOT_ERR_NO_SPACE);
7377 goto done;
7379 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7381 if (te) {
7382 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7383 err = got_error(GOT_ERR_NO_SPACE);
7384 goto done;
7387 done:
7388 if (err) {
7389 free(*path);
7390 *path = NULL;
7392 return err;
7395 static const struct got_error *
7396 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7397 struct got_tree_entry *te, struct tog_parent_trees *parents,
7398 struct got_object_id *commit_id, struct got_repository *repo)
7400 const struct got_error *err = NULL;
7401 char *path;
7402 struct tog_view *blame_view;
7404 *new_view = NULL;
7406 err = tree_entry_path(&path, parents, te);
7407 if (err)
7408 return err;
7410 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7411 if (blame_view == NULL) {
7412 err = got_error_from_errno("view_open");
7413 goto done;
7416 err = open_blame_view(blame_view, path, commit_id, repo);
7417 if (err) {
7418 if (err->code == GOT_ERR_CANCELLED)
7419 err = NULL;
7420 view_close(blame_view);
7421 } else
7422 *new_view = blame_view;
7423 done:
7424 free(path);
7425 return err;
7428 static const struct got_error *
7429 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7430 struct tog_tree_view_state *s)
7432 struct tog_view *log_view;
7433 const struct got_error *err = NULL;
7434 char *path;
7436 *new_view = NULL;
7438 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7439 if (log_view == NULL)
7440 return got_error_from_errno("view_open");
7442 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7443 if (err)
7444 return err;
7446 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7447 path, 0);
7448 if (err)
7449 view_close(log_view);
7450 else
7451 *new_view = log_view;
7452 free(path);
7453 return err;
7456 static const struct got_error *
7457 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7458 const char *head_ref_name, struct got_repository *repo)
7460 const struct got_error *err = NULL;
7461 char *commit_id_str = NULL;
7462 struct tog_tree_view_state *s = &view->state.tree;
7463 struct got_commit_object *commit = NULL;
7465 TAILQ_INIT(&s->parents);
7466 STAILQ_INIT(&s->colors);
7468 s->commit_id = got_object_id_dup(commit_id);
7469 if (s->commit_id == NULL) {
7470 err = got_error_from_errno("got_object_id_dup");
7471 goto done;
7474 err = got_object_open_as_commit(&commit, repo, commit_id);
7475 if (err)
7476 goto done;
7479 * The root is opened here and will be closed when the view is closed.
7480 * Any visited subtrees and their path-wise parents are opened and
7481 * closed on demand.
7483 err = got_object_open_as_tree(&s->root, repo,
7484 got_object_commit_get_tree_id(commit));
7485 if (err)
7486 goto done;
7487 s->tree = s->root;
7489 err = got_object_id_str(&commit_id_str, commit_id);
7490 if (err != NULL)
7491 goto done;
7493 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7494 err = got_error_from_errno("asprintf");
7495 goto done;
7498 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7499 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7500 if (head_ref_name) {
7501 s->head_ref_name = strdup(head_ref_name);
7502 if (s->head_ref_name == NULL) {
7503 err = got_error_from_errno("strdup");
7504 goto done;
7507 s->repo = repo;
7509 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7510 err = add_color(&s->colors, "\\$$",
7511 TOG_COLOR_TREE_SUBMODULE,
7512 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7513 if (err)
7514 goto done;
7515 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7516 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7517 if (err)
7518 goto done;
7519 err = add_color(&s->colors, "/$",
7520 TOG_COLOR_TREE_DIRECTORY,
7521 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7522 if (err)
7523 goto done;
7525 err = add_color(&s->colors, "\\*$",
7526 TOG_COLOR_TREE_EXECUTABLE,
7527 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7528 if (err)
7529 goto done;
7531 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7532 get_color_value("TOG_COLOR_COMMIT"));
7533 if (err)
7534 goto done;
7537 view->show = show_tree_view;
7538 view->input = input_tree_view;
7539 view->close = close_tree_view;
7540 view->search_start = search_start_tree_view;
7541 view->search_next = search_next_tree_view;
7542 done:
7543 free(commit_id_str);
7544 if (commit)
7545 got_object_commit_close(commit);
7546 if (err) {
7547 if (view->close == NULL)
7548 close_tree_view(view);
7549 view_close(view);
7551 return err;
7554 static const struct got_error *
7555 close_tree_view(struct tog_view *view)
7557 struct tog_tree_view_state *s = &view->state.tree;
7559 free_colors(&s->colors);
7560 free(s->tree_label);
7561 s->tree_label = NULL;
7562 free(s->commit_id);
7563 s->commit_id = NULL;
7564 free(s->head_ref_name);
7565 s->head_ref_name = NULL;
7566 while (!TAILQ_EMPTY(&s->parents)) {
7567 struct tog_parent_tree *parent;
7568 parent = TAILQ_FIRST(&s->parents);
7569 TAILQ_REMOVE(&s->parents, parent, entry);
7570 if (parent->tree != s->root)
7571 got_object_tree_close(parent->tree);
7572 free(parent);
7575 if (s->tree != NULL && s->tree != s->root)
7576 got_object_tree_close(s->tree);
7577 if (s->root)
7578 got_object_tree_close(s->root);
7579 return NULL;
7582 static const struct got_error *
7583 search_start_tree_view(struct tog_view *view)
7585 struct tog_tree_view_state *s = &view->state.tree;
7587 s->matched_entry = NULL;
7588 return NULL;
7591 static int
7592 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7594 regmatch_t regmatch;
7596 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7597 0) == 0;
7600 static const struct got_error *
7601 search_next_tree_view(struct tog_view *view)
7603 struct tog_tree_view_state *s = &view->state.tree;
7604 struct got_tree_entry *te = NULL;
7606 if (!view->searching) {
7607 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7608 return NULL;
7611 if (s->matched_entry) {
7612 if (view->searching == TOG_SEARCH_FORWARD) {
7613 if (s->selected_entry)
7614 te = got_tree_entry_get_next(s->tree,
7615 s->selected_entry);
7616 else
7617 te = got_object_tree_get_first_entry(s->tree);
7618 } else {
7619 if (s->selected_entry == NULL)
7620 te = got_object_tree_get_last_entry(s->tree);
7621 else
7622 te = got_tree_entry_get_prev(s->tree,
7623 s->selected_entry);
7625 } else {
7626 if (s->selected_entry)
7627 te = s->selected_entry;
7628 else if (view->searching == TOG_SEARCH_FORWARD)
7629 te = got_object_tree_get_first_entry(s->tree);
7630 else
7631 te = got_object_tree_get_last_entry(s->tree);
7634 while (1) {
7635 if (te == NULL) {
7636 if (s->matched_entry == NULL) {
7637 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7638 return NULL;
7640 if (view->searching == TOG_SEARCH_FORWARD)
7641 te = got_object_tree_get_first_entry(s->tree);
7642 else
7643 te = got_object_tree_get_last_entry(s->tree);
7646 if (match_tree_entry(te, &view->regex)) {
7647 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7648 s->matched_entry = te;
7649 break;
7652 if (view->searching == TOG_SEARCH_FORWARD)
7653 te = got_tree_entry_get_next(s->tree, te);
7654 else
7655 te = got_tree_entry_get_prev(s->tree, te);
7658 if (s->matched_entry) {
7659 s->first_displayed_entry = s->matched_entry;
7660 s->selected = 0;
7663 return NULL;
7666 static const struct got_error *
7667 show_tree_view(struct tog_view *view)
7669 const struct got_error *err = NULL;
7670 struct tog_tree_view_state *s = &view->state.tree;
7671 char *parent_path;
7673 err = tree_entry_path(&parent_path, &s->parents, NULL);
7674 if (err)
7675 return err;
7677 err = draw_tree_entries(view, parent_path);
7678 free(parent_path);
7680 view_border(view);
7681 return err;
7684 static const struct got_error *
7685 tree_goto_line(struct tog_view *view, int nlines)
7687 const struct got_error *err = NULL;
7688 struct tog_tree_view_state *s = &view->state.tree;
7689 struct got_tree_entry **fte, **lte, **ste;
7690 int g, last, first = 1, i = 1;
7691 int root = s->tree == s->root;
7692 int off = root ? 1 : 2;
7694 g = view->gline;
7695 view->gline = 0;
7697 if (g == 0)
7698 g = 1;
7699 else if (g > got_object_tree_get_nentries(s->tree))
7700 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7702 fte = &s->first_displayed_entry;
7703 lte = &s->last_displayed_entry;
7704 ste = &s->selected_entry;
7706 if (*fte != NULL) {
7707 first = got_tree_entry_get_index(*fte);
7708 first += off; /* account for ".." */
7710 last = got_tree_entry_get_index(*lte);
7711 last += off;
7713 if (g >= first && g <= last && g - first < nlines) {
7714 s->selected = g - first;
7715 return NULL; /* gline is on the current page */
7718 if (*ste != NULL) {
7719 i = got_tree_entry_get_index(*ste);
7720 i += off;
7723 if (i < g) {
7724 err = tree_scroll_down(view, g - i);
7725 if (err)
7726 return err;
7727 if (got_tree_entry_get_index(*lte) >=
7728 got_object_tree_get_nentries(s->tree) - 1 &&
7729 first + s->selected < g &&
7730 s->selected < s->ndisplayed - 1) {
7731 first = got_tree_entry_get_index(*fte);
7732 first += off;
7733 s->selected = g - first;
7735 } else if (i > g)
7736 tree_scroll_up(s, i - g);
7738 if (g < nlines &&
7739 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7740 s->selected = g - 1;
7742 return NULL;
7745 static const struct got_error *
7746 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7748 const struct got_error *err = NULL;
7749 struct tog_tree_view_state *s = &view->state.tree;
7750 struct got_tree_entry *te;
7751 int n, nscroll = view->nlines - 3;
7753 if (view->gline)
7754 return tree_goto_line(view, nscroll);
7756 switch (ch) {
7757 case '0':
7758 case '$':
7759 case KEY_RIGHT:
7760 case 'l':
7761 case KEY_LEFT:
7762 case 'h':
7763 horizontal_scroll_input(view, ch);
7764 break;
7765 case 'i':
7766 s->show_ids = !s->show_ids;
7767 view->count = 0;
7768 break;
7769 case 'L':
7770 view->count = 0;
7771 if (!s->selected_entry)
7772 break;
7773 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7774 break;
7775 case 'R':
7776 view->count = 0;
7777 err = view_request_new(new_view, view, TOG_VIEW_REF);
7778 break;
7779 case 'g':
7780 case '=':
7781 case KEY_HOME:
7782 s->selected = 0;
7783 view->count = 0;
7784 if (s->tree == s->root)
7785 s->first_displayed_entry =
7786 got_object_tree_get_first_entry(s->tree);
7787 else
7788 s->first_displayed_entry = NULL;
7789 break;
7790 case 'G':
7791 case '*':
7792 case KEY_END: {
7793 int eos = view->nlines - 3;
7795 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7796 --eos; /* border */
7797 s->selected = 0;
7798 view->count = 0;
7799 te = got_object_tree_get_last_entry(s->tree);
7800 for (n = 0; n < eos; n++) {
7801 if (te == NULL) {
7802 if (s->tree != s->root) {
7803 s->first_displayed_entry = NULL;
7804 n++;
7806 break;
7808 s->first_displayed_entry = te;
7809 te = got_tree_entry_get_prev(s->tree, te);
7811 if (n > 0)
7812 s->selected = n - 1;
7813 break;
7815 case 'k':
7816 case KEY_UP:
7817 case CTRL('p'):
7818 if (s->selected > 0) {
7819 s->selected--;
7820 break;
7822 tree_scroll_up(s, 1);
7823 if (s->selected_entry == NULL ||
7824 (s->tree == s->root && s->selected_entry ==
7825 got_object_tree_get_first_entry(s->tree)))
7826 view->count = 0;
7827 break;
7828 case CTRL('u'):
7829 case 'u':
7830 nscroll /= 2;
7831 /* FALL THROUGH */
7832 case KEY_PPAGE:
7833 case CTRL('b'):
7834 case 'b':
7835 if (s->tree == s->root) {
7836 if (got_object_tree_get_first_entry(s->tree) ==
7837 s->first_displayed_entry)
7838 s->selected -= MIN(s->selected, nscroll);
7839 } else {
7840 if (s->first_displayed_entry == NULL)
7841 s->selected -= MIN(s->selected, nscroll);
7843 tree_scroll_up(s, MAX(0, nscroll));
7844 if (s->selected_entry == NULL ||
7845 (s->tree == s->root && s->selected_entry ==
7846 got_object_tree_get_first_entry(s->tree)))
7847 view->count = 0;
7848 break;
7849 case 'j':
7850 case KEY_DOWN:
7851 case CTRL('n'):
7852 if (s->selected < s->ndisplayed - 1) {
7853 s->selected++;
7854 break;
7856 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7857 == NULL) {
7858 /* can't scroll any further */
7859 view->count = 0;
7860 break;
7862 tree_scroll_down(view, 1);
7863 break;
7864 case CTRL('d'):
7865 case 'd':
7866 nscroll /= 2;
7867 /* FALL THROUGH */
7868 case KEY_NPAGE:
7869 case CTRL('f'):
7870 case 'f':
7871 case ' ':
7872 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7873 == NULL) {
7874 /* can't scroll any further; move cursor down */
7875 if (s->selected < s->ndisplayed - 1)
7876 s->selected += MIN(nscroll,
7877 s->ndisplayed - s->selected - 1);
7878 else
7879 view->count = 0;
7880 break;
7882 tree_scroll_down(view, nscroll);
7883 break;
7884 case KEY_ENTER:
7885 case '\r':
7886 case KEY_BACKSPACE:
7887 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7888 struct tog_parent_tree *parent;
7889 /* user selected '..' */
7890 if (s->tree == s->root) {
7891 view->count = 0;
7892 break;
7894 parent = TAILQ_FIRST(&s->parents);
7895 TAILQ_REMOVE(&s->parents, parent,
7896 entry);
7897 got_object_tree_close(s->tree);
7898 s->tree = parent->tree;
7899 s->first_displayed_entry =
7900 parent->first_displayed_entry;
7901 s->selected_entry =
7902 parent->selected_entry;
7903 s->selected = parent->selected;
7904 if (s->selected > view->nlines - 3) {
7905 err = offset_selection_down(view);
7906 if (err)
7907 break;
7909 free(parent);
7910 } else if (S_ISDIR(got_tree_entry_get_mode(
7911 s->selected_entry))) {
7912 struct got_tree_object *subtree;
7913 view->count = 0;
7914 err = got_object_open_as_tree(&subtree, s->repo,
7915 got_tree_entry_get_id(s->selected_entry));
7916 if (err)
7917 break;
7918 err = tree_view_visit_subtree(s, subtree);
7919 if (err) {
7920 got_object_tree_close(subtree);
7921 break;
7923 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7924 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7925 break;
7926 case KEY_RESIZE:
7927 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7928 s->selected = view->nlines - 4;
7929 view->count = 0;
7930 break;
7931 default:
7932 view->count = 0;
7933 break;
7936 return err;
7939 __dead static void
7940 usage_tree(void)
7942 endwin();
7943 fprintf(stderr,
7944 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7945 getprogname());
7946 exit(1);
7949 static const struct got_error *
7950 cmd_tree(int argc, char *argv[])
7952 const struct got_error *error;
7953 struct got_repository *repo = NULL;
7954 struct got_worktree *worktree = NULL;
7955 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7956 struct got_object_id *commit_id = NULL;
7957 struct got_commit_object *commit = NULL;
7958 const char *commit_id_arg = NULL;
7959 char *label = NULL;
7960 struct got_reference *ref = NULL;
7961 const char *head_ref_name = NULL;
7962 int ch;
7963 struct tog_view *view;
7964 int *pack_fds = NULL;
7966 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7967 switch (ch) {
7968 case 'c':
7969 commit_id_arg = optarg;
7970 break;
7971 case 'r':
7972 repo_path = realpath(optarg, NULL);
7973 if (repo_path == NULL)
7974 return got_error_from_errno2("realpath",
7975 optarg);
7976 break;
7977 default:
7978 usage_tree();
7979 /* NOTREACHED */
7983 argc -= optind;
7984 argv += optind;
7986 if (argc > 1)
7987 usage_tree();
7989 error = got_repo_pack_fds_open(&pack_fds);
7990 if (error != NULL)
7991 goto done;
7993 if (repo_path == NULL) {
7994 cwd = getcwd(NULL, 0);
7995 if (cwd == NULL)
7996 return got_error_from_errno("getcwd");
7997 error = got_worktree_open(&worktree, cwd);
7998 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7999 goto done;
8000 if (worktree)
8001 repo_path =
8002 strdup(got_worktree_get_repo_path(worktree));
8003 else
8004 repo_path = strdup(cwd);
8005 if (repo_path == NULL) {
8006 error = got_error_from_errno("strdup");
8007 goto done;
8011 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8012 if (error != NULL)
8013 goto done;
8015 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8016 repo, worktree);
8017 if (error)
8018 goto done;
8020 init_curses();
8022 error = apply_unveil(got_repo_get_path(repo), NULL);
8023 if (error)
8024 goto done;
8026 error = tog_load_refs(repo, 0);
8027 if (error)
8028 goto done;
8030 if (commit_id_arg == NULL) {
8031 error = got_repo_match_object_id(&commit_id, &label,
8032 worktree ? got_worktree_get_head_ref_name(worktree) :
8033 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8034 if (error)
8035 goto done;
8036 head_ref_name = label;
8037 } else {
8038 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8039 if (error == NULL)
8040 head_ref_name = got_ref_get_name(ref);
8041 else if (error->code != GOT_ERR_NOT_REF)
8042 goto done;
8043 error = got_repo_match_object_id(&commit_id, NULL,
8044 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8045 if (error)
8046 goto done;
8049 error = got_object_open_as_commit(&commit, repo, commit_id);
8050 if (error)
8051 goto done;
8053 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8054 if (view == NULL) {
8055 error = got_error_from_errno("view_open");
8056 goto done;
8058 error = open_tree_view(view, commit_id, head_ref_name, repo);
8059 if (error)
8060 goto done;
8061 if (!got_path_is_root_dir(in_repo_path)) {
8062 error = tree_view_walk_path(&view->state.tree, commit,
8063 in_repo_path);
8064 if (error)
8065 goto done;
8068 if (worktree) {
8069 /* Release work tree lock. */
8070 got_worktree_close(worktree);
8071 worktree = NULL;
8073 error = view_loop(view);
8074 done:
8075 free(repo_path);
8076 free(cwd);
8077 free(commit_id);
8078 free(label);
8079 if (ref)
8080 got_ref_close(ref);
8081 if (repo) {
8082 const struct got_error *close_err = got_repo_close(repo);
8083 if (error == NULL)
8084 error = close_err;
8086 if (pack_fds) {
8087 const struct got_error *pack_err =
8088 got_repo_pack_fds_close(pack_fds);
8089 if (error == NULL)
8090 error = pack_err;
8092 tog_free_refs();
8093 return error;
8096 static const struct got_error *
8097 ref_view_load_refs(struct tog_ref_view_state *s)
8099 struct got_reflist_entry *sre;
8100 struct tog_reflist_entry *re;
8102 s->nrefs = 0;
8103 TAILQ_FOREACH(sre, &tog_refs, entry) {
8104 if (strncmp(got_ref_get_name(sre->ref),
8105 "refs/got/", 9) == 0 &&
8106 strncmp(got_ref_get_name(sre->ref),
8107 "refs/got/backup/", 16) != 0)
8108 continue;
8110 re = malloc(sizeof(*re));
8111 if (re == NULL)
8112 return got_error_from_errno("malloc");
8114 re->ref = got_ref_dup(sre->ref);
8115 if (re->ref == NULL)
8116 return got_error_from_errno("got_ref_dup");
8117 re->idx = s->nrefs++;
8118 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8121 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8122 return NULL;
8125 static void
8126 ref_view_free_refs(struct tog_ref_view_state *s)
8128 struct tog_reflist_entry *re;
8130 while (!TAILQ_EMPTY(&s->refs)) {
8131 re = TAILQ_FIRST(&s->refs);
8132 TAILQ_REMOVE(&s->refs, re, entry);
8133 got_ref_close(re->ref);
8134 free(re);
8138 static const struct got_error *
8139 open_ref_view(struct tog_view *view, struct got_repository *repo)
8141 const struct got_error *err = NULL;
8142 struct tog_ref_view_state *s = &view->state.ref;
8144 s->selected_entry = 0;
8145 s->repo = repo;
8147 TAILQ_INIT(&s->refs);
8148 STAILQ_INIT(&s->colors);
8150 err = ref_view_load_refs(s);
8151 if (err)
8152 goto done;
8154 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8155 err = add_color(&s->colors, "^refs/heads/",
8156 TOG_COLOR_REFS_HEADS,
8157 get_color_value("TOG_COLOR_REFS_HEADS"));
8158 if (err)
8159 goto done;
8161 err = add_color(&s->colors, "^refs/tags/",
8162 TOG_COLOR_REFS_TAGS,
8163 get_color_value("TOG_COLOR_REFS_TAGS"));
8164 if (err)
8165 goto done;
8167 err = add_color(&s->colors, "^refs/remotes/",
8168 TOG_COLOR_REFS_REMOTES,
8169 get_color_value("TOG_COLOR_REFS_REMOTES"));
8170 if (err)
8171 goto done;
8173 err = add_color(&s->colors, "^refs/got/backup/",
8174 TOG_COLOR_REFS_BACKUP,
8175 get_color_value("TOG_COLOR_REFS_BACKUP"));
8176 if (err)
8177 goto done;
8180 view->show = show_ref_view;
8181 view->input = input_ref_view;
8182 view->close = close_ref_view;
8183 view->search_start = search_start_ref_view;
8184 view->search_next = search_next_ref_view;
8185 done:
8186 if (err) {
8187 if (view->close == NULL)
8188 close_ref_view(view);
8189 view_close(view);
8191 return err;
8194 static const struct got_error *
8195 close_ref_view(struct tog_view *view)
8197 struct tog_ref_view_state *s = &view->state.ref;
8199 ref_view_free_refs(s);
8200 free_colors(&s->colors);
8202 return NULL;
8205 static const struct got_error *
8206 resolve_reflist_entry(struct got_object_id **commit_id,
8207 struct tog_reflist_entry *re, struct got_repository *repo)
8209 const struct got_error *err = NULL;
8210 struct got_object_id *obj_id;
8211 struct got_tag_object *tag = NULL;
8212 int obj_type;
8214 *commit_id = NULL;
8216 err = got_ref_resolve(&obj_id, repo, re->ref);
8217 if (err)
8218 return err;
8220 err = got_object_get_type(&obj_type, repo, obj_id);
8221 if (err)
8222 goto done;
8224 switch (obj_type) {
8225 case GOT_OBJ_TYPE_COMMIT:
8226 *commit_id = obj_id;
8227 break;
8228 case GOT_OBJ_TYPE_TAG:
8229 err = got_object_open_as_tag(&tag, repo, obj_id);
8230 if (err)
8231 goto done;
8232 free(obj_id);
8233 err = got_object_get_type(&obj_type, repo,
8234 got_object_tag_get_object_id(tag));
8235 if (err)
8236 goto done;
8237 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8238 err = got_error(GOT_ERR_OBJ_TYPE);
8239 goto done;
8241 *commit_id = got_object_id_dup(
8242 got_object_tag_get_object_id(tag));
8243 if (*commit_id == NULL) {
8244 err = got_error_from_errno("got_object_id_dup");
8245 goto done;
8247 break;
8248 default:
8249 err = got_error(GOT_ERR_OBJ_TYPE);
8250 break;
8253 done:
8254 if (tag)
8255 got_object_tag_close(tag);
8256 if (err) {
8257 free(*commit_id);
8258 *commit_id = NULL;
8260 return err;
8263 static const struct got_error *
8264 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8265 struct tog_reflist_entry *re, struct got_repository *repo)
8267 struct tog_view *log_view;
8268 const struct got_error *err = NULL;
8269 struct got_object_id *commit_id = NULL;
8271 *new_view = NULL;
8273 err = resolve_reflist_entry(&commit_id, re, repo);
8274 if (err) {
8275 if (err->code != GOT_ERR_OBJ_TYPE)
8276 return err;
8277 else
8278 return NULL;
8281 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8282 if (log_view == NULL) {
8283 err = got_error_from_errno("view_open");
8284 goto done;
8287 err = open_log_view(log_view, commit_id, repo,
8288 got_ref_get_name(re->ref), "", 0);
8289 done:
8290 if (err)
8291 view_close(log_view);
8292 else
8293 *new_view = log_view;
8294 free(commit_id);
8295 return err;
8298 static void
8299 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8301 struct tog_reflist_entry *re;
8302 int i = 0;
8304 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8305 return;
8307 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8308 while (i++ < maxscroll) {
8309 if (re == NULL)
8310 break;
8311 s->first_displayed_entry = re;
8312 re = TAILQ_PREV(re, tog_reflist_head, entry);
8316 static const struct got_error *
8317 ref_scroll_down(struct tog_view *view, int maxscroll)
8319 struct tog_ref_view_state *s = &view->state.ref;
8320 struct tog_reflist_entry *next, *last;
8321 int n = 0;
8323 if (s->first_displayed_entry)
8324 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8325 else
8326 next = TAILQ_FIRST(&s->refs);
8328 last = s->last_displayed_entry;
8329 while (next && n++ < maxscroll) {
8330 if (last) {
8331 s->last_displayed_entry = last;
8332 last = TAILQ_NEXT(last, entry);
8334 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8335 s->first_displayed_entry = next;
8336 next = TAILQ_NEXT(next, entry);
8340 return NULL;
8343 static const struct got_error *
8344 search_start_ref_view(struct tog_view *view)
8346 struct tog_ref_view_state *s = &view->state.ref;
8348 s->matched_entry = NULL;
8349 return NULL;
8352 static int
8353 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8355 regmatch_t regmatch;
8357 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8358 0) == 0;
8361 static const struct got_error *
8362 search_next_ref_view(struct tog_view *view)
8364 struct tog_ref_view_state *s = &view->state.ref;
8365 struct tog_reflist_entry *re = NULL;
8367 if (!view->searching) {
8368 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8369 return NULL;
8372 if (s->matched_entry) {
8373 if (view->searching == TOG_SEARCH_FORWARD) {
8374 if (s->selected_entry)
8375 re = TAILQ_NEXT(s->selected_entry, entry);
8376 else
8377 re = TAILQ_PREV(s->selected_entry,
8378 tog_reflist_head, entry);
8379 } else {
8380 if (s->selected_entry == NULL)
8381 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8382 else
8383 re = TAILQ_PREV(s->selected_entry,
8384 tog_reflist_head, entry);
8386 } else {
8387 if (s->selected_entry)
8388 re = s->selected_entry;
8389 else if (view->searching == TOG_SEARCH_FORWARD)
8390 re = TAILQ_FIRST(&s->refs);
8391 else
8392 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8395 while (1) {
8396 if (re == NULL) {
8397 if (s->matched_entry == NULL) {
8398 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8399 return NULL;
8401 if (view->searching == TOG_SEARCH_FORWARD)
8402 re = TAILQ_FIRST(&s->refs);
8403 else
8404 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8407 if (match_reflist_entry(re, &view->regex)) {
8408 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8409 s->matched_entry = re;
8410 break;
8413 if (view->searching == TOG_SEARCH_FORWARD)
8414 re = TAILQ_NEXT(re, entry);
8415 else
8416 re = TAILQ_PREV(re, tog_reflist_head, entry);
8419 if (s->matched_entry) {
8420 s->first_displayed_entry = s->matched_entry;
8421 s->selected = 0;
8424 return NULL;
8427 static const struct got_error *
8428 show_ref_view(struct tog_view *view)
8430 const struct got_error *err = NULL;
8431 struct tog_ref_view_state *s = &view->state.ref;
8432 struct tog_reflist_entry *re;
8433 char *line = NULL;
8434 wchar_t *wline;
8435 struct tog_color *tc;
8436 int width, n, scrollx;
8437 int limit = view->nlines;
8439 werase(view->window);
8441 s->ndisplayed = 0;
8442 if (view_is_hsplit_top(view))
8443 --limit; /* border */
8445 if (limit == 0)
8446 return NULL;
8448 re = s->first_displayed_entry;
8450 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8451 s->nrefs) == -1)
8452 return got_error_from_errno("asprintf");
8454 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8455 if (err) {
8456 free(line);
8457 return err;
8459 if (view_needs_focus_indication(view))
8460 wstandout(view->window);
8461 waddwstr(view->window, wline);
8462 while (width++ < view->ncols)
8463 waddch(view->window, ' ');
8464 if (view_needs_focus_indication(view))
8465 wstandend(view->window);
8466 free(wline);
8467 wline = NULL;
8468 free(line);
8469 line = NULL;
8470 if (--limit <= 0)
8471 return NULL;
8473 n = 0;
8474 view->maxx = 0;
8475 while (re && limit > 0) {
8476 char *line = NULL;
8477 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8479 if (s->show_date) {
8480 struct got_commit_object *ci;
8481 struct got_tag_object *tag;
8482 struct got_object_id *id;
8483 struct tm tm;
8484 time_t t;
8486 err = got_ref_resolve(&id, s->repo, re->ref);
8487 if (err)
8488 return err;
8489 err = got_object_open_as_tag(&tag, s->repo, id);
8490 if (err) {
8491 if (err->code != GOT_ERR_OBJ_TYPE) {
8492 free(id);
8493 return err;
8495 err = got_object_open_as_commit(&ci, s->repo,
8496 id);
8497 if (err) {
8498 free(id);
8499 return err;
8501 t = got_object_commit_get_committer_time(ci);
8502 got_object_commit_close(ci);
8503 } else {
8504 t = got_object_tag_get_tagger_time(tag);
8505 got_object_tag_close(tag);
8507 free(id);
8508 if (gmtime_r(&t, &tm) == NULL)
8509 return got_error_from_errno("gmtime_r");
8510 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8511 return got_error(GOT_ERR_NO_SPACE);
8513 if (got_ref_is_symbolic(re->ref)) {
8514 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8515 ymd : "", got_ref_get_name(re->ref),
8516 got_ref_get_symref_target(re->ref)) == -1)
8517 return got_error_from_errno("asprintf");
8518 } else if (s->show_ids) {
8519 struct got_object_id *id;
8520 char *id_str;
8521 err = got_ref_resolve(&id, s->repo, re->ref);
8522 if (err)
8523 return err;
8524 err = got_object_id_str(&id_str, id);
8525 if (err) {
8526 free(id);
8527 return err;
8529 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8530 got_ref_get_name(re->ref), id_str) == -1) {
8531 err = got_error_from_errno("asprintf");
8532 free(id);
8533 free(id_str);
8534 return err;
8536 free(id);
8537 free(id_str);
8538 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8539 got_ref_get_name(re->ref)) == -1)
8540 return got_error_from_errno("asprintf");
8542 /* use full line width to determine view->maxx */
8543 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8544 if (err) {
8545 free(line);
8546 return err;
8548 view->maxx = MAX(view->maxx, width);
8549 free(wline);
8550 wline = NULL;
8552 err = format_line(&wline, &width, &scrollx, line, view->x,
8553 view->ncols, 0, 0);
8554 if (err) {
8555 free(line);
8556 return err;
8558 if (n == s->selected) {
8559 if (view->focussed)
8560 wstandout(view->window);
8561 s->selected_entry = re;
8563 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8564 if (tc)
8565 wattr_on(view->window,
8566 COLOR_PAIR(tc->colorpair), NULL);
8567 waddwstr(view->window, &wline[scrollx]);
8568 if (tc)
8569 wattr_off(view->window,
8570 COLOR_PAIR(tc->colorpair), NULL);
8571 if (width < view->ncols)
8572 waddch(view->window, '\n');
8573 if (n == s->selected && view->focussed)
8574 wstandend(view->window);
8575 free(line);
8576 free(wline);
8577 wline = NULL;
8578 n++;
8579 s->ndisplayed++;
8580 s->last_displayed_entry = re;
8582 limit--;
8583 re = TAILQ_NEXT(re, entry);
8586 view_border(view);
8587 return err;
8590 static const struct got_error *
8591 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8592 struct tog_reflist_entry *re, struct got_repository *repo)
8594 const struct got_error *err = NULL;
8595 struct got_object_id *commit_id = NULL;
8596 struct tog_view *tree_view;
8598 *new_view = NULL;
8600 err = resolve_reflist_entry(&commit_id, re, repo);
8601 if (err) {
8602 if (err->code != GOT_ERR_OBJ_TYPE)
8603 return err;
8604 else
8605 return NULL;
8609 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8610 if (tree_view == NULL) {
8611 err = got_error_from_errno("view_open");
8612 goto done;
8615 err = open_tree_view(tree_view, commit_id,
8616 got_ref_get_name(re->ref), repo);
8617 if (err)
8618 goto done;
8620 *new_view = tree_view;
8621 done:
8622 free(commit_id);
8623 return err;
8626 static const struct got_error *
8627 ref_goto_line(struct tog_view *view, int nlines)
8629 const struct got_error *err = NULL;
8630 struct tog_ref_view_state *s = &view->state.ref;
8631 int g, idx = s->selected_entry->idx;
8633 g = view->gline;
8634 view->gline = 0;
8636 if (g == 0)
8637 g = 1;
8638 else if (g > s->nrefs)
8639 g = s->nrefs;
8641 if (g >= s->first_displayed_entry->idx + 1 &&
8642 g <= s->last_displayed_entry->idx + 1 &&
8643 g - s->first_displayed_entry->idx - 1 < nlines) {
8644 s->selected = g - s->first_displayed_entry->idx - 1;
8645 return NULL;
8648 if (idx + 1 < g) {
8649 err = ref_scroll_down(view, g - idx - 1);
8650 if (err)
8651 return err;
8652 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8653 s->first_displayed_entry->idx + s->selected < g &&
8654 s->selected < s->ndisplayed - 1)
8655 s->selected = g - s->first_displayed_entry->idx - 1;
8656 } else if (idx + 1 > g)
8657 ref_scroll_up(s, idx - g + 1);
8659 if (g < nlines && s->first_displayed_entry->idx == 0)
8660 s->selected = g - 1;
8662 return NULL;
8666 static const struct got_error *
8667 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8669 const struct got_error *err = NULL;
8670 struct tog_ref_view_state *s = &view->state.ref;
8671 struct tog_reflist_entry *re;
8672 int n, nscroll = view->nlines - 1;
8674 if (view->gline)
8675 return ref_goto_line(view, nscroll);
8677 switch (ch) {
8678 case '0':
8679 case '$':
8680 case KEY_RIGHT:
8681 case 'l':
8682 case KEY_LEFT:
8683 case 'h':
8684 horizontal_scroll_input(view, ch);
8685 break;
8686 case 'i':
8687 s->show_ids = !s->show_ids;
8688 view->count = 0;
8689 break;
8690 case 'm':
8691 s->show_date = !s->show_date;
8692 view->count = 0;
8693 break;
8694 case 'o':
8695 s->sort_by_date = !s->sort_by_date;
8696 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8697 view->count = 0;
8698 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8699 got_ref_cmp_by_commit_timestamp_descending :
8700 tog_ref_cmp_by_name, s->repo);
8701 if (err)
8702 break;
8703 got_reflist_object_id_map_free(tog_refs_idmap);
8704 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8705 &tog_refs, s->repo);
8706 if (err)
8707 break;
8708 ref_view_free_refs(s);
8709 err = ref_view_load_refs(s);
8710 break;
8711 case KEY_ENTER:
8712 case '\r':
8713 view->count = 0;
8714 if (!s->selected_entry)
8715 break;
8716 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8717 break;
8718 case 'T':
8719 view->count = 0;
8720 if (!s->selected_entry)
8721 break;
8722 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8723 break;
8724 case 'g':
8725 case '=':
8726 case KEY_HOME:
8727 s->selected = 0;
8728 view->count = 0;
8729 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8730 break;
8731 case 'G':
8732 case '*':
8733 case KEY_END: {
8734 int eos = view->nlines - 1;
8736 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8737 --eos; /* border */
8738 s->selected = 0;
8739 view->count = 0;
8740 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8741 for (n = 0; n < eos; n++) {
8742 if (re == NULL)
8743 break;
8744 s->first_displayed_entry = re;
8745 re = TAILQ_PREV(re, tog_reflist_head, entry);
8747 if (n > 0)
8748 s->selected = n - 1;
8749 break;
8751 case 'k':
8752 case KEY_UP:
8753 case CTRL('p'):
8754 if (s->selected > 0) {
8755 s->selected--;
8756 break;
8758 ref_scroll_up(s, 1);
8759 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8760 view->count = 0;
8761 break;
8762 case CTRL('u'):
8763 case 'u':
8764 nscroll /= 2;
8765 /* FALL THROUGH */
8766 case KEY_PPAGE:
8767 case CTRL('b'):
8768 case 'b':
8769 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8770 s->selected -= MIN(nscroll, s->selected);
8771 ref_scroll_up(s, MAX(0, nscroll));
8772 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8773 view->count = 0;
8774 break;
8775 case 'j':
8776 case KEY_DOWN:
8777 case CTRL('n'):
8778 if (s->selected < s->ndisplayed - 1) {
8779 s->selected++;
8780 break;
8782 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8783 /* can't scroll any further */
8784 view->count = 0;
8785 break;
8787 ref_scroll_down(view, 1);
8788 break;
8789 case CTRL('d'):
8790 case 'd':
8791 nscroll /= 2;
8792 /* FALL THROUGH */
8793 case KEY_NPAGE:
8794 case CTRL('f'):
8795 case 'f':
8796 case ' ':
8797 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8798 /* can't scroll any further; move cursor down */
8799 if (s->selected < s->ndisplayed - 1)
8800 s->selected += MIN(nscroll,
8801 s->ndisplayed - s->selected - 1);
8802 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8803 s->selected += s->ndisplayed - s->selected - 1;
8804 view->count = 0;
8805 break;
8807 ref_scroll_down(view, nscroll);
8808 break;
8809 case CTRL('l'):
8810 view->count = 0;
8811 tog_free_refs();
8812 err = tog_load_refs(s->repo, s->sort_by_date);
8813 if (err)
8814 break;
8815 ref_view_free_refs(s);
8816 err = ref_view_load_refs(s);
8817 break;
8818 case KEY_RESIZE:
8819 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8820 s->selected = view->nlines - 2;
8821 break;
8822 default:
8823 view->count = 0;
8824 break;
8827 return err;
8830 __dead static void
8831 usage_ref(void)
8833 endwin();
8834 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8835 getprogname());
8836 exit(1);
8839 static const struct got_error *
8840 cmd_ref(int argc, char *argv[])
8842 const struct got_error *error;
8843 struct got_repository *repo = NULL;
8844 struct got_worktree *worktree = NULL;
8845 char *cwd = NULL, *repo_path = NULL;
8846 int ch;
8847 struct tog_view *view;
8848 int *pack_fds = NULL;
8850 while ((ch = getopt(argc, argv, "r:")) != -1) {
8851 switch (ch) {
8852 case 'r':
8853 repo_path = realpath(optarg, NULL);
8854 if (repo_path == NULL)
8855 return got_error_from_errno2("realpath",
8856 optarg);
8857 break;
8858 default:
8859 usage_ref();
8860 /* NOTREACHED */
8864 argc -= optind;
8865 argv += optind;
8867 if (argc > 1)
8868 usage_ref();
8870 error = got_repo_pack_fds_open(&pack_fds);
8871 if (error != NULL)
8872 goto done;
8874 if (repo_path == NULL) {
8875 cwd = getcwd(NULL, 0);
8876 if (cwd == NULL)
8877 return got_error_from_errno("getcwd");
8878 error = got_worktree_open(&worktree, cwd);
8879 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8880 goto done;
8881 if (worktree)
8882 repo_path =
8883 strdup(got_worktree_get_repo_path(worktree));
8884 else
8885 repo_path = strdup(cwd);
8886 if (repo_path == NULL) {
8887 error = got_error_from_errno("strdup");
8888 goto done;
8892 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8893 if (error != NULL)
8894 goto done;
8896 init_curses();
8898 error = apply_unveil(got_repo_get_path(repo), NULL);
8899 if (error)
8900 goto done;
8902 error = tog_load_refs(repo, 0);
8903 if (error)
8904 goto done;
8906 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8907 if (view == NULL) {
8908 error = got_error_from_errno("view_open");
8909 goto done;
8912 error = open_ref_view(view, repo);
8913 if (error)
8914 goto done;
8916 if (worktree) {
8917 /* Release work tree lock. */
8918 got_worktree_close(worktree);
8919 worktree = NULL;
8921 error = view_loop(view);
8922 done:
8923 free(repo_path);
8924 free(cwd);
8925 if (repo) {
8926 const struct got_error *close_err = got_repo_close(repo);
8927 if (close_err)
8928 error = close_err;
8930 if (pack_fds) {
8931 const struct got_error *pack_err =
8932 got_repo_pack_fds_close(pack_fds);
8933 if (error == NULL)
8934 error = pack_err;
8936 tog_free_refs();
8937 return error;
8940 static const struct got_error*
8941 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8942 const char *str)
8944 size_t len;
8946 if (win == NULL)
8947 win = stdscr;
8949 len = strlen(str);
8950 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8952 if (focus)
8953 wstandout(win);
8954 if (mvwprintw(win, y, x, "%s", str) == ERR)
8955 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8956 if (focus)
8957 wstandend(win);
8959 return NULL;
8962 static const struct got_error *
8963 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8965 off_t *p;
8967 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8968 if (p == NULL) {
8969 free(*line_offsets);
8970 *line_offsets = NULL;
8971 return got_error_from_errno("reallocarray");
8974 *line_offsets = p;
8975 (*line_offsets)[*nlines] = off;
8976 ++(*nlines);
8977 return NULL;
8980 static const struct got_error *
8981 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8983 *ret = 0;
8985 for (;n > 0; --n, ++km) {
8986 char *t0, *t, *k;
8987 size_t len = 1;
8989 if (km->keys == NULL)
8990 continue;
8992 t = t0 = strdup(km->keys);
8993 if (t0 == NULL)
8994 return got_error_from_errno("strdup");
8996 len += strlen(t);
8997 while ((k = strsep(&t, " ")) != NULL)
8998 len += strlen(k) > 1 ? 2 : 0;
8999 free(t0);
9000 *ret = MAX(*ret, len);
9003 return NULL;
9007 * Write keymap section headers, keys, and key info in km to f.
9008 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9009 * wrap control and symbolic keys in guillemets, else use <>.
9011 static const struct got_error *
9012 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9014 int n, len = width;
9016 if (km->keys) {
9017 static const char *u8_glyph[] = {
9018 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9019 "\xe2\x80\xba" /* U+203A (utf8 >) */
9021 char *t0, *t, *k;
9022 int cs, s, first = 1;
9024 cs = got_locale_is_utf8();
9026 t = t0 = strdup(km->keys);
9027 if (t0 == NULL)
9028 return got_error_from_errno("strdup");
9030 len = strlen(km->keys);
9031 while ((k = strsep(&t, " ")) != NULL) {
9032 s = strlen(k) > 1; /* control or symbolic key */
9033 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9034 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9035 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9036 if (n < 0) {
9037 free(t0);
9038 return got_error_from_errno("fprintf");
9040 first = 0;
9041 len += s ? 2 : 0;
9042 *off += n;
9044 free(t0);
9046 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9047 if (n < 0)
9048 return got_error_from_errno("fprintf");
9049 *off += n;
9051 return NULL;
9054 static const struct got_error *
9055 format_help(struct tog_help_view_state *s)
9057 const struct got_error *err = NULL;
9058 off_t off = 0;
9059 int i, max, n, show = s->all;
9060 static const struct tog_key_map km[] = {
9061 #define KEYMAP_(info, type) { NULL, (info), type }
9062 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9063 GENERATE_HELP
9064 #undef KEYMAP_
9065 #undef KEY_
9068 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9069 if (err)
9070 return err;
9072 n = nitems(km);
9073 err = max_key_str(&max, km, n);
9074 if (err)
9075 return err;
9077 for (i = 0; i < n; ++i) {
9078 if (km[i].keys == NULL) {
9079 show = s->all;
9080 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9081 km[i].type == s->type || s->all)
9082 show = 1;
9084 if (show) {
9085 err = format_help_line(&off, s->f, &km[i], max);
9086 if (err)
9087 return err;
9088 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9089 if (err)
9090 return err;
9093 fputc('\n', s->f);
9094 ++off;
9095 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9096 return err;
9099 static const struct got_error *
9100 create_help(struct tog_help_view_state *s)
9102 FILE *f;
9103 const struct got_error *err;
9105 free(s->line_offsets);
9106 s->line_offsets = NULL;
9107 s->nlines = 0;
9109 f = got_opentemp();
9110 if (f == NULL)
9111 return got_error_from_errno("got_opentemp");
9112 s->f = f;
9114 err = format_help(s);
9115 if (err)
9116 return err;
9118 if (s->f && fflush(s->f) != 0)
9119 return got_error_from_errno("fflush");
9121 return NULL;
9124 static const struct got_error *
9125 search_start_help_view(struct tog_view *view)
9127 view->state.help.matched_line = 0;
9128 return NULL;
9131 static void
9132 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9133 size_t *nlines, int **first, int **last, int **match, int **selected)
9135 struct tog_help_view_state *s = &view->state.help;
9137 *f = s->f;
9138 *nlines = s->nlines;
9139 *line_offsets = s->line_offsets;
9140 *match = &s->matched_line;
9141 *first = &s->first_displayed_line;
9142 *last = &s->last_displayed_line;
9143 *selected = &s->selected_line;
9146 static const struct got_error *
9147 show_help_view(struct tog_view *view)
9149 struct tog_help_view_state *s = &view->state.help;
9150 const struct got_error *err;
9151 regmatch_t *regmatch = &view->regmatch;
9152 wchar_t *wline;
9153 char *line;
9154 ssize_t linelen;
9155 size_t linesz = 0;
9156 int width, nprinted = 0, rc = 0;
9157 int eos = view->nlines;
9159 if (view_is_hsplit_top(view))
9160 --eos; /* account for border */
9162 s->lineno = 0;
9163 rewind(s->f);
9164 werase(view->window);
9166 if (view->gline > s->nlines - 1)
9167 view->gline = s->nlines - 1;
9169 err = win_draw_center(view->window, 0, 0, view->ncols,
9170 view_needs_focus_indication(view),
9171 "tog help (press q to return to tog)");
9172 if (err)
9173 return err;
9174 if (eos <= 1)
9175 return NULL;
9176 waddstr(view->window, "\n\n");
9177 eos -= 2;
9179 s->eof = 0;
9180 view->maxx = 0;
9181 line = NULL;
9182 while (eos > 0 && nprinted < eos) {
9183 attr_t attr = 0;
9185 linelen = getline(&line, &linesz, s->f);
9186 if (linelen == -1) {
9187 if (!feof(s->f)) {
9188 free(line);
9189 return got_ferror(s->f, GOT_ERR_IO);
9191 s->eof = 1;
9192 break;
9194 if (++s->lineno < s->first_displayed_line)
9195 continue;
9196 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9197 continue;
9198 if (s->lineno == view->hiline)
9199 attr = A_STANDOUT;
9201 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9202 view->x ? 1 : 0);
9203 if (err) {
9204 free(line);
9205 return err;
9207 view->maxx = MAX(view->maxx, width);
9208 free(wline);
9209 wline = NULL;
9211 if (attr)
9212 wattron(view->window, attr);
9213 if (s->first_displayed_line + nprinted == s->matched_line &&
9214 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9215 err = add_matched_line(&width, line, view->ncols - 1, 0,
9216 view->window, view->x, regmatch);
9217 if (err) {
9218 free(line);
9219 return err;
9221 } else {
9222 int skip;
9224 err = format_line(&wline, &width, &skip, line,
9225 view->x, view->ncols, 0, view->x ? 1 : 0);
9226 if (err) {
9227 free(line);
9228 return err;
9230 waddwstr(view->window, &wline[skip]);
9231 free(wline);
9232 wline = NULL;
9234 if (s->lineno == view->hiline) {
9235 while (width++ < view->ncols)
9236 waddch(view->window, ' ');
9237 } else {
9238 if (width < view->ncols)
9239 waddch(view->window, '\n');
9241 if (attr)
9242 wattroff(view->window, attr);
9243 if (++nprinted == 1)
9244 s->first_displayed_line = s->lineno;
9246 free(line);
9247 if (nprinted > 0)
9248 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9249 else
9250 s->last_displayed_line = s->first_displayed_line;
9252 view_border(view);
9254 if (s->eof) {
9255 rc = waddnstr(view->window,
9256 "See the tog(1) manual page for full documentation",
9257 view->ncols - 1);
9258 if (rc == ERR)
9259 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9260 } else {
9261 wmove(view->window, view->nlines - 1, 0);
9262 wclrtoeol(view->window);
9263 wstandout(view->window);
9264 rc = waddnstr(view->window, "scroll down for more...",
9265 view->ncols - 1);
9266 if (rc == ERR)
9267 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9268 if (getcurx(view->window) < view->ncols - 6) {
9269 rc = wprintw(view->window, "[%.0f%%]",
9270 100.00 * s->last_displayed_line / s->nlines);
9271 if (rc == ERR)
9272 return got_error_msg(GOT_ERR_IO, "wprintw");
9274 wstandend(view->window);
9277 return NULL;
9280 static const struct got_error *
9281 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9283 struct tog_help_view_state *s = &view->state.help;
9284 const struct got_error *err = NULL;
9285 char *line = NULL;
9286 ssize_t linelen;
9287 size_t linesz = 0;
9288 int eos, nscroll;
9290 eos = nscroll = view->nlines;
9291 if (view_is_hsplit_top(view))
9292 --eos; /* border */
9294 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9296 switch (ch) {
9297 case '0':
9298 case '$':
9299 case KEY_RIGHT:
9300 case 'l':
9301 case KEY_LEFT:
9302 case 'h':
9303 horizontal_scroll_input(view, ch);
9304 break;
9305 case 'g':
9306 case KEY_HOME:
9307 s->first_displayed_line = 1;
9308 view->count = 0;
9309 break;
9310 case 'G':
9311 case KEY_END:
9312 view->count = 0;
9313 if (s->eof)
9314 break;
9315 s->first_displayed_line = (s->nlines - eos) + 3;
9316 s->eof = 1;
9317 break;
9318 case 'k':
9319 case KEY_UP:
9320 if (s->first_displayed_line > 1)
9321 --s->first_displayed_line;
9322 else
9323 view->count = 0;
9324 break;
9325 case CTRL('u'):
9326 case 'u':
9327 nscroll /= 2;
9328 /* FALL THROUGH */
9329 case KEY_PPAGE:
9330 case CTRL('b'):
9331 case 'b':
9332 if (s->first_displayed_line == 1) {
9333 view->count = 0;
9334 break;
9336 while (--nscroll > 0 && s->first_displayed_line > 1)
9337 s->first_displayed_line--;
9338 break;
9339 case 'j':
9340 case KEY_DOWN:
9341 case CTRL('n'):
9342 if (!s->eof)
9343 ++s->first_displayed_line;
9344 else
9345 view->count = 0;
9346 break;
9347 case CTRL('d'):
9348 case 'd':
9349 nscroll /= 2;
9350 /* FALL THROUGH */
9351 case KEY_NPAGE:
9352 case CTRL('f'):
9353 case 'f':
9354 case ' ':
9355 if (s->eof) {
9356 view->count = 0;
9357 break;
9359 while (!s->eof && --nscroll > 0) {
9360 linelen = getline(&line, &linesz, s->f);
9361 s->first_displayed_line++;
9362 if (linelen == -1) {
9363 if (feof(s->f))
9364 s->eof = 1;
9365 else
9366 err = got_ferror(s->f, GOT_ERR_IO);
9367 break;
9370 free(line);
9371 break;
9372 default:
9373 view->count = 0;
9374 break;
9377 return err;
9380 static const struct got_error *
9381 close_help_view(struct tog_view *view)
9383 struct tog_help_view_state *s = &view->state.help;
9385 free(s->line_offsets);
9386 s->line_offsets = NULL;
9387 if (fclose(s->f) == EOF)
9388 return got_error_from_errno("fclose");
9390 return NULL;
9393 static const struct got_error *
9394 reset_help_view(struct tog_view *view)
9396 struct tog_help_view_state *s = &view->state.help;
9399 if (s->f && fclose(s->f) == EOF)
9400 return got_error_from_errno("fclose");
9402 wclear(view->window);
9403 view->count = 0;
9404 view->x = 0;
9405 s->all = !s->all;
9406 s->first_displayed_line = 1;
9407 s->last_displayed_line = view->nlines;
9408 s->matched_line = 0;
9410 return create_help(s);
9413 static const struct got_error *
9414 open_help_view(struct tog_view *view, struct tog_view *parent)
9416 const struct got_error *err = NULL;
9417 struct tog_help_view_state *s = &view->state.help;
9419 s->type = (enum tog_keymap_type)parent->type;
9420 s->first_displayed_line = 1;
9421 s->last_displayed_line = view->nlines;
9422 s->selected_line = 1;
9424 view->show = show_help_view;
9425 view->input = input_help_view;
9426 view->reset = reset_help_view;
9427 view->close = close_help_view;
9428 view->search_start = search_start_help_view;
9429 view->search_setup = search_setup_help_view;
9430 view->search_next = search_next_view_match;
9432 err = create_help(s);
9433 return err;
9436 static const struct got_error *
9437 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9438 enum tog_view_type request, int y, int x)
9440 const struct got_error *err = NULL;
9442 *new_view = NULL;
9444 switch (request) {
9445 case TOG_VIEW_DIFF:
9446 if (view->type == TOG_VIEW_LOG) {
9447 struct tog_log_view_state *s = &view->state.log;
9449 err = open_diff_view_for_commit(new_view, y, x,
9450 s->selected_entry->commit, s->selected_entry->id,
9451 view, s->repo);
9452 } else
9453 return got_error_msg(GOT_ERR_NOT_IMPL,
9454 "parent/child view pair not supported");
9455 break;
9456 case TOG_VIEW_BLAME:
9457 if (view->type == TOG_VIEW_TREE) {
9458 struct tog_tree_view_state *s = &view->state.tree;
9460 err = blame_tree_entry(new_view, y, x,
9461 s->selected_entry, &s->parents, s->commit_id,
9462 s->repo);
9463 } else
9464 return got_error_msg(GOT_ERR_NOT_IMPL,
9465 "parent/child view pair not supported");
9466 break;
9467 case TOG_VIEW_LOG:
9468 if (view->type == TOG_VIEW_BLAME)
9469 err = log_annotated_line(new_view, y, x,
9470 view->state.blame.repo, view->state.blame.id_to_log);
9471 else if (view->type == TOG_VIEW_TREE)
9472 err = log_selected_tree_entry(new_view, y, x,
9473 &view->state.tree);
9474 else if (view->type == TOG_VIEW_REF)
9475 err = log_ref_entry(new_view, y, x,
9476 view->state.ref.selected_entry,
9477 view->state.ref.repo);
9478 else
9479 return got_error_msg(GOT_ERR_NOT_IMPL,
9480 "parent/child view pair not supported");
9481 break;
9482 case TOG_VIEW_TREE:
9483 if (view->type == TOG_VIEW_LOG)
9484 err = browse_commit_tree(new_view, y, x,
9485 view->state.log.selected_entry,
9486 view->state.log.in_repo_path,
9487 view->state.log.head_ref_name,
9488 view->state.log.repo);
9489 else if (view->type == TOG_VIEW_REF)
9490 err = browse_ref_tree(new_view, y, x,
9491 view->state.ref.selected_entry,
9492 view->state.ref.repo);
9493 else
9494 return got_error_msg(GOT_ERR_NOT_IMPL,
9495 "parent/child view pair not supported");
9496 break;
9497 case TOG_VIEW_REF:
9498 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9499 if (*new_view == NULL)
9500 return got_error_from_errno("view_open");
9501 if (view->type == TOG_VIEW_LOG)
9502 err = open_ref_view(*new_view, view->state.log.repo);
9503 else if (view->type == TOG_VIEW_TREE)
9504 err = open_ref_view(*new_view, view->state.tree.repo);
9505 else
9506 err = got_error_msg(GOT_ERR_NOT_IMPL,
9507 "parent/child view pair not supported");
9508 if (err)
9509 view_close(*new_view);
9510 break;
9511 case TOG_VIEW_HELP:
9512 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9513 if (*new_view == NULL)
9514 return got_error_from_errno("view_open");
9515 err = open_help_view(*new_view, view);
9516 if (err)
9517 view_close(*new_view);
9518 break;
9519 default:
9520 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9523 return err;
9527 * If view was scrolled down to move the selected line into view when opening a
9528 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9530 static void
9531 offset_selection_up(struct tog_view *view)
9533 switch (view->type) {
9534 case TOG_VIEW_BLAME: {
9535 struct tog_blame_view_state *s = &view->state.blame;
9536 if (s->first_displayed_line == 1) {
9537 s->selected_line = MAX(s->selected_line - view->offset,
9538 1);
9539 break;
9541 if (s->first_displayed_line > view->offset)
9542 s->first_displayed_line -= view->offset;
9543 else
9544 s->first_displayed_line = 1;
9545 s->selected_line += view->offset;
9546 break;
9548 case TOG_VIEW_LOG:
9549 log_scroll_up(&view->state.log, view->offset);
9550 view->state.log.selected += view->offset;
9551 break;
9552 case TOG_VIEW_REF:
9553 ref_scroll_up(&view->state.ref, view->offset);
9554 view->state.ref.selected += view->offset;
9555 break;
9556 case TOG_VIEW_TREE:
9557 tree_scroll_up(&view->state.tree, view->offset);
9558 view->state.tree.selected += view->offset;
9559 break;
9560 default:
9561 break;
9564 view->offset = 0;
9568 * If the selected line is in the section of screen covered by the bottom split,
9569 * scroll down offset lines to move it into view and index its new position.
9571 static const struct got_error *
9572 offset_selection_down(struct tog_view *view)
9574 const struct got_error *err = NULL;
9575 const struct got_error *(*scrolld)(struct tog_view *, int);
9576 int *selected = NULL;
9577 int header, offset;
9579 switch (view->type) {
9580 case TOG_VIEW_BLAME: {
9581 struct tog_blame_view_state *s = &view->state.blame;
9582 header = 3;
9583 scrolld = NULL;
9584 if (s->selected_line > view->nlines - header) {
9585 offset = abs(view->nlines - s->selected_line - header);
9586 s->first_displayed_line += offset;
9587 s->selected_line -= offset;
9588 view->offset = offset;
9590 break;
9592 case TOG_VIEW_LOG: {
9593 struct tog_log_view_state *s = &view->state.log;
9594 scrolld = &log_scroll_down;
9595 header = view_is_parent_view(view) ? 3 : 2;
9596 selected = &s->selected;
9597 break;
9599 case TOG_VIEW_REF: {
9600 struct tog_ref_view_state *s = &view->state.ref;
9601 scrolld = &ref_scroll_down;
9602 header = 3;
9603 selected = &s->selected;
9604 break;
9606 case TOG_VIEW_TREE: {
9607 struct tog_tree_view_state *s = &view->state.tree;
9608 scrolld = &tree_scroll_down;
9609 header = 5;
9610 selected = &s->selected;
9611 break;
9613 default:
9614 selected = NULL;
9615 scrolld = NULL;
9616 header = 0;
9617 break;
9620 if (selected && *selected > view->nlines - header) {
9621 offset = abs(view->nlines - *selected - header);
9622 view->offset = offset;
9623 if (scrolld && offset) {
9624 err = scrolld(view, offset);
9625 *selected -= offset;
9629 return err;
9632 static void
9633 list_commands(FILE *fp)
9635 size_t i;
9637 fprintf(fp, "commands:");
9638 for (i = 0; i < nitems(tog_commands); i++) {
9639 const struct tog_cmd *cmd = &tog_commands[i];
9640 fprintf(fp, " %s", cmd->name);
9642 fputc('\n', fp);
9645 __dead static void
9646 usage(int hflag, int status)
9648 FILE *fp = (status == 0) ? stdout : stderr;
9650 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9651 getprogname());
9652 if (hflag) {
9653 fprintf(fp, "lazy usage: %s path\n", getprogname());
9654 list_commands(fp);
9656 exit(status);
9659 static char **
9660 make_argv(int argc, ...)
9662 va_list ap;
9663 char **argv;
9664 int i;
9666 va_start(ap, argc);
9668 argv = calloc(argc, sizeof(char *));
9669 if (argv == NULL)
9670 err(1, "calloc");
9671 for (i = 0; i < argc; i++) {
9672 argv[i] = strdup(va_arg(ap, char *));
9673 if (argv[i] == NULL)
9674 err(1, "strdup");
9677 va_end(ap);
9678 return argv;
9682 * Try to convert 'tog path' into a 'tog log path' command.
9683 * The user could simply have mistyped the command rather than knowingly
9684 * provided a path. So check whether argv[0] can in fact be resolved
9685 * to a path in the HEAD commit and print a special error if not.
9686 * This hack is for mpi@ <3
9688 static const struct got_error *
9689 tog_log_with_path(int argc, char *argv[])
9691 const struct got_error *error = NULL, *close_err;
9692 const struct tog_cmd *cmd = NULL;
9693 struct got_repository *repo = NULL;
9694 struct got_worktree *worktree = NULL;
9695 struct got_object_id *commit_id = NULL, *id = NULL;
9696 struct got_commit_object *commit = NULL;
9697 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9698 char *commit_id_str = NULL, **cmd_argv = NULL;
9699 int *pack_fds = NULL;
9701 cwd = getcwd(NULL, 0);
9702 if (cwd == NULL)
9703 return got_error_from_errno("getcwd");
9705 error = got_repo_pack_fds_open(&pack_fds);
9706 if (error != NULL)
9707 goto done;
9709 error = got_worktree_open(&worktree, cwd);
9710 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9711 goto done;
9713 if (worktree)
9714 repo_path = strdup(got_worktree_get_repo_path(worktree));
9715 else
9716 repo_path = strdup(cwd);
9717 if (repo_path == NULL) {
9718 error = got_error_from_errno("strdup");
9719 goto done;
9722 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9723 if (error != NULL)
9724 goto done;
9726 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9727 repo, worktree);
9728 if (error)
9729 goto done;
9731 error = tog_load_refs(repo, 0);
9732 if (error)
9733 goto done;
9734 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9735 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9736 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9737 if (error)
9738 goto done;
9740 if (worktree) {
9741 got_worktree_close(worktree);
9742 worktree = NULL;
9745 error = got_object_open_as_commit(&commit, repo, commit_id);
9746 if (error)
9747 goto done;
9749 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9750 if (error) {
9751 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9752 goto done;
9753 fprintf(stderr, "%s: '%s' is no known command or path\n",
9754 getprogname(), argv[0]);
9755 usage(1, 1);
9756 /* not reached */
9759 error = got_object_id_str(&commit_id_str, commit_id);
9760 if (error)
9761 goto done;
9763 cmd = &tog_commands[0]; /* log */
9764 argc = 4;
9765 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9766 error = cmd->cmd_main(argc, cmd_argv);
9767 done:
9768 if (repo) {
9769 close_err = got_repo_close(repo);
9770 if (error == NULL)
9771 error = close_err;
9773 if (commit)
9774 got_object_commit_close(commit);
9775 if (worktree)
9776 got_worktree_close(worktree);
9777 if (pack_fds) {
9778 const struct got_error *pack_err =
9779 got_repo_pack_fds_close(pack_fds);
9780 if (error == NULL)
9781 error = pack_err;
9783 free(id);
9784 free(commit_id_str);
9785 free(commit_id);
9786 free(cwd);
9787 free(repo_path);
9788 free(in_repo_path);
9789 if (cmd_argv) {
9790 int i;
9791 for (i = 0; i < argc; i++)
9792 free(cmd_argv[i]);
9793 free(cmd_argv);
9795 tog_free_refs();
9796 return error;
9799 int
9800 main(int argc, char *argv[])
9802 const struct got_error *io_err, *error = NULL;
9803 const struct tog_cmd *cmd = NULL;
9804 int ch, hflag = 0, Vflag = 0;
9805 char **cmd_argv = NULL;
9806 static const struct option longopts[] = {
9807 { "version", no_argument, NULL, 'V' },
9808 { NULL, 0, NULL, 0}
9810 char *diff_algo_str = NULL;
9811 const char *test_script_path;
9813 setlocale(LC_CTYPE, "");
9816 * Test mode init must happen before pledge() because "tty" will
9817 * not allow TTY-related ioctls to occur via regular files.
9819 test_script_path = getenv("TOG_TEST_SCRIPT");
9820 if (test_script_path != NULL) {
9821 error = init_mock_term(test_script_path);
9822 if (error) {
9823 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9824 return 1;
9826 } else if (!isatty(STDIN_FILENO))
9827 errx(1, "standard input is not a tty");
9829 #if !defined(PROFILE)
9830 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9831 NULL) == -1)
9832 err(1, "pledge");
9833 #endif
9835 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9836 switch (ch) {
9837 case 'h':
9838 hflag = 1;
9839 break;
9840 case 'V':
9841 Vflag = 1;
9842 break;
9843 default:
9844 usage(hflag, 1);
9845 /* NOTREACHED */
9849 argc -= optind;
9850 argv += optind;
9851 optind = 1;
9852 optreset = 1;
9854 if (Vflag) {
9855 got_version_print_str();
9856 return 0;
9859 if (argc == 0) {
9860 if (hflag)
9861 usage(hflag, 0);
9862 /* Build an argument vector which runs a default command. */
9863 cmd = &tog_commands[0];
9864 argc = 1;
9865 cmd_argv = make_argv(argc, cmd->name);
9866 } else {
9867 size_t i;
9869 /* Did the user specify a command? */
9870 for (i = 0; i < nitems(tog_commands); i++) {
9871 if (strncmp(tog_commands[i].name, argv[0],
9872 strlen(argv[0])) == 0) {
9873 cmd = &tog_commands[i];
9874 break;
9879 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9880 if (diff_algo_str) {
9881 if (strcasecmp(diff_algo_str, "patience") == 0)
9882 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9883 if (strcasecmp(diff_algo_str, "myers") == 0)
9884 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9887 if (cmd == NULL) {
9888 if (argc != 1)
9889 usage(0, 1);
9890 /* No command specified; try log with a path */
9891 error = tog_log_with_path(argc, argv);
9892 } else {
9893 if (hflag)
9894 cmd->cmd_usage();
9895 else
9896 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9899 if (using_mock_io) {
9900 io_err = tog_io_close();
9901 if (error == NULL)
9902 error = io_err;
9904 endwin();
9905 if (cmd_argv) {
9906 int i;
9907 for (i = 0; i < argc; i++)
9908 free(cmd_argv[i]);
9909 free(cmd_argv);
9912 if (error && error->code != GOT_ERR_CANCELLED &&
9913 error->code != GOT_ERR_EOF &&
9914 error->code != GOT_ERR_PRIVSEP_EXIT &&
9915 error->code != GOT_ERR_PRIVSEP_PIPE &&
9916 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9917 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9918 return 0;