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.3 /* 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 int wait_for_ui;
626 } tog_io;
627 static int using_mock_io;
629 #define TOG_KEY_SCRDUMP SHRT_MIN
631 /*
632 * We implement two types of views: parent views and child views.
634 * The 'Tab' key switches focus between a parent view and its child view.
635 * Child views are shown side-by-side to their parent view, provided
636 * there is enough screen estate.
638 * When a new view is opened from within a parent view, this new view
639 * becomes a child view of the parent view, replacing any existing child.
641 * When a new view is opened from within a child view, this new view
642 * becomes a parent view which will obscure the views below until the
643 * user quits the new parent view by typing 'q'.
645 * This list of views contains parent views only.
646 * Child views are only pointed to by their parent view.
647 */
648 TAILQ_HEAD(tog_view_list_head, tog_view);
650 struct tog_view {
651 TAILQ_ENTRY(tog_view) entry;
652 WINDOW *window;
653 PANEL *panel;
654 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
655 int resized_y, resized_x; /* begin_y/x based on user resizing */
656 int maxx, x; /* max column and current start column */
657 int lines, cols; /* copies of LINES and COLS */
658 int nscrolled, offset; /* lines scrolled and hsplit line offset */
659 int gline, hiline; /* navigate to and highlight this nG line */
660 int ch, count; /* current keymap and count prefix */
661 int resized; /* set when in a resize event */
662 int focussed; /* Only set on one parent or child view at a time. */
663 int dying;
664 struct tog_view *parent;
665 struct tog_view *child;
667 /*
668 * This flag is initially set on parent views when a new child view
669 * is created. It gets toggled when the 'Tab' key switches focus
670 * between parent and child.
671 * The flag indicates whether focus should be passed on to our child
672 * view if this parent view gets picked for focus after another parent
673 * view was closed. This prevents child views from losing focus in such
674 * situations.
675 */
676 int focus_child;
678 enum tog_view_mode mode;
679 /* type-specific state */
680 enum tog_view_type type;
681 union {
682 struct tog_diff_view_state diff;
683 struct tog_log_view_state log;
684 struct tog_blame_view_state blame;
685 struct tog_tree_view_state tree;
686 struct tog_ref_view_state ref;
687 struct tog_help_view_state help;
688 } state;
690 const struct got_error *(*show)(struct tog_view *);
691 const struct got_error *(*input)(struct tog_view **,
692 struct tog_view *, int);
693 const struct got_error *(*reset)(struct tog_view *);
694 const struct got_error *(*resize)(struct tog_view *, int);
695 const struct got_error *(*close)(struct tog_view *);
697 const struct got_error *(*search_start)(struct tog_view *);
698 const struct got_error *(*search_next)(struct tog_view *);
699 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
700 int **, int **, int **, int **);
701 int search_started;
702 int searching;
703 #define TOG_SEARCH_FORWARD 1
704 #define TOG_SEARCH_BACKWARD 2
705 int search_next_done;
706 #define TOG_SEARCH_HAVE_MORE 1
707 #define TOG_SEARCH_NO_MORE 2
708 #define TOG_SEARCH_HAVE_NONE 3
709 regex_t regex;
710 regmatch_t regmatch;
711 const char *action;
712 };
714 static const struct got_error *open_diff_view(struct tog_view *,
715 struct got_object_id *, struct got_object_id *,
716 const char *, const char *, int, int, int, struct tog_view *,
717 struct got_repository *);
718 static const struct got_error *show_diff_view(struct tog_view *);
719 static const struct got_error *input_diff_view(struct tog_view **,
720 struct tog_view *, int);
721 static const struct got_error *reset_diff_view(struct tog_view *);
722 static const struct got_error* close_diff_view(struct tog_view *);
723 static const struct got_error *search_start_diff_view(struct tog_view *);
724 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
725 size_t *, int **, int **, int **, int **);
726 static const struct got_error *search_next_view_match(struct tog_view *);
728 static const struct got_error *open_log_view(struct tog_view *,
729 struct got_object_id *, struct got_repository *,
730 const char *, const char *, int);
731 static const struct got_error * show_log_view(struct tog_view *);
732 static const struct got_error *input_log_view(struct tog_view **,
733 struct tog_view *, int);
734 static const struct got_error *resize_log_view(struct tog_view *, int);
735 static const struct got_error *close_log_view(struct tog_view *);
736 static const struct got_error *search_start_log_view(struct tog_view *);
737 static const struct got_error *search_next_log_view(struct tog_view *);
739 static const struct got_error *open_blame_view(struct tog_view *, char *,
740 struct got_object_id *, struct got_repository *);
741 static const struct got_error *show_blame_view(struct tog_view *);
742 static const struct got_error *input_blame_view(struct tog_view **,
743 struct tog_view *, int);
744 static const struct got_error *reset_blame_view(struct tog_view *);
745 static const struct got_error *close_blame_view(struct tog_view *);
746 static const struct got_error *search_start_blame_view(struct tog_view *);
747 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
748 size_t *, int **, int **, int **, int **);
750 static const struct got_error *open_tree_view(struct tog_view *,
751 struct got_object_id *, const char *, struct got_repository *);
752 static const struct got_error *show_tree_view(struct tog_view *);
753 static const struct got_error *input_tree_view(struct tog_view **,
754 struct tog_view *, int);
755 static const struct got_error *close_tree_view(struct tog_view *);
756 static const struct got_error *search_start_tree_view(struct tog_view *);
757 static const struct got_error *search_next_tree_view(struct tog_view *);
759 static const struct got_error *open_ref_view(struct tog_view *,
760 struct got_repository *);
761 static const struct got_error *show_ref_view(struct tog_view *);
762 static const struct got_error *input_ref_view(struct tog_view **,
763 struct tog_view *, int);
764 static const struct got_error *close_ref_view(struct tog_view *);
765 static const struct got_error *search_start_ref_view(struct tog_view *);
766 static const struct got_error *search_next_ref_view(struct tog_view *);
768 static const struct got_error *open_help_view(struct tog_view *,
769 struct tog_view *);
770 static const struct got_error *show_help_view(struct tog_view *);
771 static const struct got_error *input_help_view(struct tog_view **,
772 struct tog_view *, int);
773 static const struct got_error *reset_help_view(struct tog_view *);
774 static const struct got_error* close_help_view(struct tog_view *);
775 static const struct got_error *search_start_help_view(struct tog_view *);
776 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
777 size_t *, int **, int **, int **, int **);
779 static volatile sig_atomic_t tog_sigwinch_received;
780 static volatile sig_atomic_t tog_sigpipe_received;
781 static volatile sig_atomic_t tog_sigcont_received;
782 static volatile sig_atomic_t tog_sigint_received;
783 static volatile sig_atomic_t tog_sigterm_received;
785 static void
786 tog_sigwinch(int signo)
788 tog_sigwinch_received = 1;
791 static void
792 tog_sigpipe(int signo)
794 tog_sigpipe_received = 1;
797 static void
798 tog_sigcont(int signo)
800 tog_sigcont_received = 1;
803 static void
804 tog_sigint(int signo)
806 tog_sigint_received = 1;
809 static void
810 tog_sigterm(int signo)
812 tog_sigterm_received = 1;
815 static int
816 tog_fatal_signal_received(void)
818 return (tog_sigpipe_received ||
819 tog_sigint_received || tog_sigterm_received);
822 static const struct got_error *
823 view_close(struct tog_view *view)
825 const struct got_error *err = NULL, *child_err = NULL;
827 if (view->child) {
828 child_err = view_close(view->child);
829 view->child = NULL;
831 if (view->close)
832 err = view->close(view);
833 if (view->panel)
834 del_panel(view->panel);
835 if (view->window)
836 delwin(view->window);
837 free(view);
838 return err ? err : child_err;
841 static struct tog_view *
842 view_open(int nlines, int ncols, int begin_y, int begin_x,
843 enum tog_view_type type)
845 struct tog_view *view = calloc(1, sizeof(*view));
847 if (view == NULL)
848 return NULL;
850 view->type = type;
851 view->lines = LINES;
852 view->cols = COLS;
853 view->nlines = nlines ? nlines : LINES - begin_y;
854 view->ncols = ncols ? ncols : COLS - begin_x;
855 view->begin_y = begin_y;
856 view->begin_x = begin_x;
857 view->window = newwin(nlines, ncols, begin_y, begin_x);
858 if (view->window == NULL) {
859 view_close(view);
860 return NULL;
862 view->panel = new_panel(view->window);
863 if (view->panel == NULL ||
864 set_panel_userptr(view->panel, view) != OK) {
865 view_close(view);
866 return NULL;
869 keypad(view->window, TRUE);
870 return view;
873 static int
874 view_split_begin_x(int begin_x)
876 if (begin_x > 0 || COLS < 120)
877 return 0;
878 return (COLS - MAX(COLS / 2, 80));
881 /* XXX Stub till we decide what to do. */
882 static int
883 view_split_begin_y(int lines)
885 return lines * HSPLIT_SCALE;
888 static const struct got_error *view_resize(struct tog_view *);
890 static const struct got_error *
891 view_splitscreen(struct tog_view *view)
893 const struct got_error *err = NULL;
895 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
896 if (view->resized_y && view->resized_y < view->lines)
897 view->begin_y = view->resized_y;
898 else
899 view->begin_y = view_split_begin_y(view->nlines);
900 view->begin_x = 0;
901 } else if (!view->resized) {
902 if (view->resized_x && view->resized_x < view->cols - 1 &&
903 view->cols > 119)
904 view->begin_x = view->resized_x;
905 else
906 view->begin_x = view_split_begin_x(0);
907 view->begin_y = 0;
909 view->nlines = LINES - view->begin_y;
910 view->ncols = COLS - view->begin_x;
911 view->lines = LINES;
912 view->cols = COLS;
913 err = view_resize(view);
914 if (err)
915 return err;
917 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
918 view->parent->nlines = view->begin_y;
920 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
921 return got_error_from_errno("mvwin");
923 return NULL;
926 static const struct got_error *
927 view_fullscreen(struct tog_view *view)
929 const struct got_error *err = NULL;
931 view->begin_x = 0;
932 view->begin_y = view->resized ? view->begin_y : 0;
933 view->nlines = view->resized ? view->nlines : LINES;
934 view->ncols = COLS;
935 view->lines = LINES;
936 view->cols = COLS;
937 err = view_resize(view);
938 if (err)
939 return err;
941 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
942 return got_error_from_errno("mvwin");
944 return NULL;
947 static int
948 view_is_parent_view(struct tog_view *view)
950 return view->parent == NULL;
953 static int
954 view_is_splitscreen(struct tog_view *view)
956 return view->begin_x > 0 || view->begin_y > 0;
959 static int
960 view_is_fullscreen(struct tog_view *view)
962 return view->nlines == LINES && view->ncols == COLS;
965 static int
966 view_is_hsplit_top(struct tog_view *view)
968 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
969 view_is_splitscreen(view->child);
972 static void
973 view_border(struct tog_view *view)
975 PANEL *panel;
976 const struct tog_view *view_above;
978 if (view->parent)
979 return view_border(view->parent);
981 panel = panel_above(view->panel);
982 if (panel == NULL)
983 return;
985 view_above = panel_userptr(panel);
986 if (view->mode == TOG_VIEW_SPLIT_HRZN)
987 mvwhline(view->window, view_above->begin_y - 1,
988 view->begin_x, got_locale_is_utf8() ?
989 ACS_HLINE : '-', view->ncols);
990 else
991 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
992 got_locale_is_utf8() ? 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 FILE *f = NULL;
1495 const char *path;
1496 int i;
1498 path = getenv("TOG_SCR_DUMP");
1499 if (path == NULL || *path == '\0')
1500 return got_error_msg(GOT_ERR_BAD_PATH,
1501 "TOG_SCR_DUMP path not set to capture screen dump");
1502 f = fopen(path, "wex");
1503 if (f == NULL)
1504 return got_error_from_errno_fmt("fopen: %s", path);
1506 if ((view->child && view->child->begin_x) ||
1507 (view->parent && view->begin_x)) {
1508 int ncols = view->child ? view->ncols : view->parent->ncols;
1510 /* vertical splitscreen */
1511 for (i = 0; i < view->nlines; ++i) {
1512 err = view_write_line(f, i, ncols - 1);
1513 if (err)
1514 goto done;
1516 } else {
1517 int hline = 0;
1519 /* fullscreen or horizontal splitscreen */
1520 if ((view->child && view->child->begin_y) ||
1521 (view->parent && view->begin_y)) /* hsplit */
1522 hline = view->child ?
1523 view->child->begin_y : view->begin_y;
1525 for (i = 0; i < view->lines; i++) {
1526 if (hline && i == hline - 1) {
1527 int c;
1529 /* ACS_HLINE writes out as 'q', overwrite it */
1530 for (c = 0; c < view->cols; ++c)
1531 fputc('-', f);
1532 fputc('\n', f);
1533 continue;
1536 err = view_write_line(f, i, 0);
1537 if (err)
1538 goto done;
1542 done:
1543 if (f && fclose(f) == EOF && err == NULL)
1544 err = got_ferror(f, GOT_ERR_IO);
1545 return err;
1549 * Compute view->count from numeric input. Assign total to view->count and
1550 * return first non-numeric key entered.
1552 static int
1553 get_compound_key(struct tog_view *view, int c)
1555 struct tog_view *v = view;
1556 int x, n = 0;
1558 if (view_is_hsplit_top(view))
1559 v = view->child;
1560 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1561 v = view->parent;
1563 view->count = 0;
1564 cbreak(); /* block for input */
1565 nodelay(view->window, FALSE);
1566 wmove(v->window, v->nlines - 1, 0);
1567 wclrtoeol(v->window);
1568 waddch(v->window, ':');
1570 do {
1571 x = getcurx(v->window);
1572 if (x != ERR && x < view->ncols) {
1573 waddch(v->window, c);
1574 wrefresh(v->window);
1578 * Don't overflow. Max valid request should be the greatest
1579 * between the longest and total lines; cap at 10 million.
1581 if (n >= 9999999)
1582 n = 9999999;
1583 else
1584 n = n * 10 + (c - '0');
1585 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1587 if (c == 'G' || c == 'g') { /* nG key map */
1588 view->gline = view->hiline = n;
1589 n = 0;
1590 c = 0;
1593 /* Massage excessive or inapplicable values at the input handler. */
1594 view->count = n;
1596 return c;
1599 static void
1600 action_report(struct tog_view *view)
1602 struct tog_view *v = view;
1604 if (view_is_hsplit_top(view))
1605 v = view->child;
1606 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1607 v = view->parent;
1609 wmove(v->window, v->nlines - 1, 0);
1610 wclrtoeol(v->window);
1611 wprintw(v->window, ":%s", view->action);
1612 wrefresh(v->window);
1615 * Clear action status report. Only clear in blame view
1616 * once annotating is complete, otherwise it's too fast.
1618 if (view->type == TOG_VIEW_BLAME) {
1619 if (view->state.blame.blame_complete)
1620 view->action = NULL;
1621 } else
1622 view->action = NULL;
1626 * Read the next line from the test script and assign
1627 * key instruction to *ch. If at EOF, set the *done flag.
1629 static const struct got_error *
1630 tog_read_script_key(FILE *script, int *ch, int *done)
1632 const struct got_error *err = NULL;
1633 char *line = NULL;
1634 size_t linesz = 0;
1636 *ch = -1;
1638 if (getline(&line, &linesz, script) == -1) {
1639 if (feof(script)) {
1640 *done = 1;
1641 goto done;
1642 } else {
1643 err = got_ferror(script, GOT_ERR_IO);
1644 goto done;
1648 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1649 tog_io.wait_for_ui = 1;
1650 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1651 *ch = KEY_ENTER;
1652 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1653 *ch = KEY_RIGHT;
1654 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1655 *ch = KEY_LEFT;
1656 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1657 *ch = KEY_DOWN;
1658 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1659 *ch = KEY_UP;
1660 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1661 *ch = TOG_KEY_SCRDUMP;
1662 else
1663 *ch = *line;
1665 done:
1666 free(line);
1667 return err;
1670 static const struct got_error *
1671 view_input(struct tog_view **new, int *done, struct tog_view *view,
1672 struct tog_view_list_head *views, int fast_refresh)
1674 const struct got_error *err = NULL;
1675 struct tog_view *v;
1676 int ch, errcode;
1678 *new = NULL;
1680 if (view->action)
1681 action_report(view);
1683 /* Clear "no matches" indicator. */
1684 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1685 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1686 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1687 view->count = 0;
1690 if (view->searching && !view->search_next_done) {
1691 errcode = pthread_mutex_unlock(&tog_mutex);
1692 if (errcode)
1693 return got_error_set_errno(errcode,
1694 "pthread_mutex_unlock");
1695 sched_yield();
1696 errcode = pthread_mutex_lock(&tog_mutex);
1697 if (errcode)
1698 return got_error_set_errno(errcode,
1699 "pthread_mutex_lock");
1700 view->search_next(view);
1701 return NULL;
1704 /* Allow threads to make progress while we are waiting for input. */
1705 errcode = pthread_mutex_unlock(&tog_mutex);
1706 if (errcode)
1707 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1709 if (using_mock_io) {
1710 err = tog_read_script_key(tog_io.f, &ch, done);
1711 if (err) {
1712 errcode = pthread_mutex_lock(&tog_mutex);
1713 return err;
1715 } else if (view->count && --view->count) {
1716 cbreak();
1717 nodelay(view->window, TRUE);
1718 ch = wgetch(view->window);
1719 /* let C-g or backspace abort unfinished count */
1720 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1721 view->count = 0;
1722 else
1723 ch = view->ch;
1724 } else {
1725 ch = wgetch(view->window);
1726 if (ch >= '1' && ch <= '9')
1727 view->ch = ch = get_compound_key(view, ch);
1729 if (view->hiline && ch != ERR && ch != 0)
1730 view->hiline = 0; /* key pressed, clear line highlight */
1731 nodelay(view->window, TRUE);
1732 errcode = pthread_mutex_lock(&tog_mutex);
1733 if (errcode)
1734 return got_error_set_errno(errcode, "pthread_mutex_lock");
1736 if (tog_sigwinch_received || tog_sigcont_received) {
1737 tog_resizeterm();
1738 tog_sigwinch_received = 0;
1739 tog_sigcont_received = 0;
1740 TAILQ_FOREACH(v, views, entry) {
1741 err = view_resize(v);
1742 if (err)
1743 return err;
1744 err = v->input(new, v, KEY_RESIZE);
1745 if (err)
1746 return err;
1747 if (v->child) {
1748 err = view_resize(v->child);
1749 if (err)
1750 return err;
1751 err = v->child->input(new, v->child,
1752 KEY_RESIZE);
1753 if (err)
1754 return err;
1755 if (v->child->resized_x || v->child->resized_y) {
1756 err = view_resize_split(v, 0);
1757 if (err)
1758 return err;
1764 switch (ch) {
1765 case '?':
1766 case 'H':
1767 case KEY_F(1):
1768 if (view->type == TOG_VIEW_HELP)
1769 err = view->reset(view);
1770 else
1771 err = view_request_new(new, view, TOG_VIEW_HELP);
1772 break;
1773 case '\t':
1774 view->count = 0;
1775 if (view->child) {
1776 view->focussed = 0;
1777 view->child->focussed = 1;
1778 view->focus_child = 1;
1779 } else if (view->parent) {
1780 view->focussed = 0;
1781 view->parent->focussed = 1;
1782 view->parent->focus_child = 0;
1783 if (!view_is_splitscreen(view)) {
1784 if (view->parent->resize) {
1785 err = view->parent->resize(view->parent,
1786 0);
1787 if (err)
1788 return err;
1790 offset_selection_up(view->parent);
1791 err = view_fullscreen(view->parent);
1792 if (err)
1793 return err;
1796 break;
1797 case 'q':
1798 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1799 if (view->parent->resize) {
1800 /* might need more commits to fill fullscreen */
1801 err = view->parent->resize(view->parent, 0);
1802 if (err)
1803 break;
1805 offset_selection_up(view->parent);
1807 err = view->input(new, view, ch);
1808 view->dying = 1;
1809 break;
1810 case 'Q':
1811 *done = 1;
1812 break;
1813 case 'F':
1814 view->count = 0;
1815 if (view_is_parent_view(view)) {
1816 if (view->child == NULL)
1817 break;
1818 if (view_is_splitscreen(view->child)) {
1819 view->focussed = 0;
1820 view->child->focussed = 1;
1821 err = view_fullscreen(view->child);
1822 } else {
1823 err = view_splitscreen(view->child);
1824 if (!err)
1825 err = view_resize_split(view, 0);
1827 if (err)
1828 break;
1829 err = view->child->input(new, view->child,
1830 KEY_RESIZE);
1831 } else {
1832 if (view_is_splitscreen(view)) {
1833 view->parent->focussed = 0;
1834 view->focussed = 1;
1835 err = view_fullscreen(view);
1836 } else {
1837 err = view_splitscreen(view);
1838 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1839 err = view_resize(view->parent);
1840 if (!err)
1841 err = view_resize_split(view, 0);
1843 if (err)
1844 break;
1845 err = view->input(new, view, KEY_RESIZE);
1847 if (err)
1848 break;
1849 if (view->resize) {
1850 err = view->resize(view, 0);
1851 if (err)
1852 break;
1854 if (view->parent)
1855 err = offset_selection_down(view->parent);
1856 if (!err)
1857 err = offset_selection_down(view);
1858 break;
1859 case 'S':
1860 view->count = 0;
1861 err = switch_split(view);
1862 break;
1863 case '-':
1864 err = view_resize_split(view, -1);
1865 break;
1866 case '+':
1867 err = view_resize_split(view, 1);
1868 break;
1869 case KEY_RESIZE:
1870 break;
1871 case '/':
1872 view->count = 0;
1873 if (view->search_start)
1874 view_search_start(view, fast_refresh);
1875 else
1876 err = view->input(new, view, ch);
1877 break;
1878 case 'N':
1879 case 'n':
1880 if (view->search_started && view->search_next) {
1881 view->searching = (ch == 'n' ?
1882 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1883 view->search_next_done = 0;
1884 view->search_next(view);
1885 } else
1886 err = view->input(new, view, ch);
1887 break;
1888 case 'A':
1889 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1890 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1891 view->action = "Patience diff algorithm";
1892 } else {
1893 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1894 view->action = "Myers diff algorithm";
1896 TAILQ_FOREACH(v, views, entry) {
1897 if (v->reset) {
1898 err = v->reset(v);
1899 if (err)
1900 return err;
1902 if (v->child && v->child->reset) {
1903 err = v->child->reset(v->child);
1904 if (err)
1905 return err;
1908 break;
1909 case TOG_KEY_SCRDUMP:
1910 err = screendump(view);
1911 break;
1912 default:
1913 err = view->input(new, view, ch);
1914 break;
1917 return err;
1920 static int
1921 view_needs_focus_indication(struct tog_view *view)
1923 if (view_is_parent_view(view)) {
1924 if (view->child == NULL || view->child->focussed)
1925 return 0;
1926 if (!view_is_splitscreen(view->child))
1927 return 0;
1928 } else if (!view_is_splitscreen(view))
1929 return 0;
1931 return view->focussed;
1934 static const struct got_error *
1935 tog_io_close(void)
1937 const struct got_error *err = NULL;
1939 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1940 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1941 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1942 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1943 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1944 err = got_ferror(tog_io.f, GOT_ERR_IO);
1946 return err;
1949 static const struct got_error *
1950 view_loop(struct tog_view *view)
1952 const struct got_error *err = NULL;
1953 struct tog_view_list_head views;
1954 struct tog_view *new_view;
1955 char *mode;
1956 int fast_refresh = 10;
1957 int done = 0, errcode;
1959 mode = getenv("TOG_VIEW_SPLIT_MODE");
1960 if (!mode || !(*mode == 'h' || *mode == 'H'))
1961 view->mode = TOG_VIEW_SPLIT_VERT;
1962 else
1963 view->mode = TOG_VIEW_SPLIT_HRZN;
1965 errcode = pthread_mutex_lock(&tog_mutex);
1966 if (errcode)
1967 return got_error_set_errno(errcode, "pthread_mutex_lock");
1969 TAILQ_INIT(&views);
1970 TAILQ_INSERT_HEAD(&views, view, entry);
1972 view->focussed = 1;
1973 err = view->show(view);
1974 if (err)
1975 return err;
1976 update_panels();
1977 doupdate();
1978 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1979 !tog_fatal_signal_received()) {
1980 /* Refresh fast during initialization, then become slower. */
1981 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1982 halfdelay(10); /* switch to once per second */
1984 err = view_input(&new_view, &done, view, &views, fast_refresh);
1985 if (err)
1986 break;
1988 if (view->dying && view == TAILQ_FIRST(&views) &&
1989 TAILQ_NEXT(view, entry) == NULL)
1990 done = 1;
1991 if (done) {
1992 struct tog_view *v;
1995 * When we quit, scroll the screen up a single line
1996 * so we don't lose any information.
1998 TAILQ_FOREACH(v, &views, entry) {
1999 wmove(v->window, 0, 0);
2000 wdeleteln(v->window);
2001 wnoutrefresh(v->window);
2002 if (v->child && !view_is_fullscreen(v)) {
2003 wmove(v->child->window, 0, 0);
2004 wdeleteln(v->child->window);
2005 wnoutrefresh(v->child->window);
2008 doupdate();
2011 if (view->dying) {
2012 struct tog_view *v, *prev = NULL;
2014 if (view_is_parent_view(view))
2015 prev = TAILQ_PREV(view, tog_view_list_head,
2016 entry);
2017 else if (view->parent)
2018 prev = view->parent;
2020 if (view->parent) {
2021 view->parent->child = NULL;
2022 view->parent->focus_child = 0;
2023 /* Restore fullscreen line height. */
2024 view->parent->nlines = view->parent->lines;
2025 err = view_resize(view->parent);
2026 if (err)
2027 break;
2028 /* Make resized splits persist. */
2029 view_transfer_size(view->parent, view);
2030 } else
2031 TAILQ_REMOVE(&views, view, entry);
2033 err = view_close(view);
2034 if (err)
2035 goto done;
2037 view = NULL;
2038 TAILQ_FOREACH(v, &views, entry) {
2039 if (v->focussed)
2040 break;
2042 if (view == NULL && new_view == NULL) {
2043 /* No view has focus. Try to pick one. */
2044 if (prev)
2045 view = prev;
2046 else if (!TAILQ_EMPTY(&views)) {
2047 view = TAILQ_LAST(&views,
2048 tog_view_list_head);
2050 if (view) {
2051 if (view->focus_child) {
2052 view->child->focussed = 1;
2053 view = view->child;
2054 } else
2055 view->focussed = 1;
2059 if (new_view) {
2060 struct tog_view *v, *t;
2061 /* Only allow one parent view per type. */
2062 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2063 if (v->type != new_view->type)
2064 continue;
2065 TAILQ_REMOVE(&views, v, entry);
2066 err = view_close(v);
2067 if (err)
2068 goto done;
2069 break;
2071 TAILQ_INSERT_TAIL(&views, new_view, entry);
2072 view = new_view;
2074 if (view && !done) {
2075 if (view_is_parent_view(view)) {
2076 if (view->child && view->child->focussed)
2077 view = view->child;
2078 } else {
2079 if (view->parent && view->parent->focussed)
2080 view = view->parent;
2082 show_panel(view->panel);
2083 if (view->child && view_is_splitscreen(view->child))
2084 show_panel(view->child->panel);
2085 if (view->parent && view_is_splitscreen(view)) {
2086 err = view->parent->show(view->parent);
2087 if (err)
2088 goto done;
2090 err = view->show(view);
2091 if (err)
2092 goto done;
2093 if (view->child) {
2094 err = view->child->show(view->child);
2095 if (err)
2096 goto done;
2098 update_panels();
2099 doupdate();
2102 done:
2103 while (!TAILQ_EMPTY(&views)) {
2104 const struct got_error *close_err;
2105 view = TAILQ_FIRST(&views);
2106 TAILQ_REMOVE(&views, view, entry);
2107 close_err = view_close(view);
2108 if (close_err && err == NULL)
2109 err = close_err;
2112 errcode = pthread_mutex_unlock(&tog_mutex);
2113 if (errcode && err == NULL)
2114 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2116 return err;
2119 __dead static void
2120 usage_log(void)
2122 endwin();
2123 fprintf(stderr,
2124 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2125 getprogname());
2126 exit(1);
2129 /* Create newly allocated wide-character string equivalent to a byte string. */
2130 static const struct got_error *
2131 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2133 char *vis = NULL;
2134 const struct got_error *err = NULL;
2136 *ws = NULL;
2137 *wlen = mbstowcs(NULL, s, 0);
2138 if (*wlen == (size_t)-1) {
2139 int vislen;
2140 if (errno != EILSEQ)
2141 return got_error_from_errno("mbstowcs");
2143 /* byte string invalid in current encoding; try to "fix" it */
2144 err = got_mbsavis(&vis, &vislen, s);
2145 if (err)
2146 return err;
2147 *wlen = mbstowcs(NULL, vis, 0);
2148 if (*wlen == (size_t)-1) {
2149 err = got_error_from_errno("mbstowcs"); /* give up */
2150 goto done;
2154 *ws = calloc(*wlen + 1, sizeof(**ws));
2155 if (*ws == NULL) {
2156 err = got_error_from_errno("calloc");
2157 goto done;
2160 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2161 err = got_error_from_errno("mbstowcs");
2162 done:
2163 free(vis);
2164 if (err) {
2165 free(*ws);
2166 *ws = NULL;
2167 *wlen = 0;
2169 return err;
2172 static const struct got_error *
2173 expand_tab(char **ptr, const char *src)
2175 char *dst;
2176 size_t len, n, idx = 0, sz = 0;
2178 *ptr = NULL;
2179 n = len = strlen(src);
2180 dst = malloc(n + 1);
2181 if (dst == NULL)
2182 return got_error_from_errno("malloc");
2184 while (idx < len && src[idx]) {
2185 const char c = src[idx];
2187 if (c == '\t') {
2188 size_t nb = TABSIZE - sz % TABSIZE;
2189 char *p;
2191 p = realloc(dst, n + nb);
2192 if (p == NULL) {
2193 free(dst);
2194 return got_error_from_errno("realloc");
2197 dst = p;
2198 n += nb;
2199 memset(dst + sz, ' ', nb);
2200 sz += nb;
2201 } else
2202 dst[sz++] = src[idx];
2203 ++idx;
2206 dst[sz] = '\0';
2207 *ptr = dst;
2208 return NULL;
2212 * Advance at most n columns from wline starting at offset off.
2213 * Return the index to the first character after the span operation.
2214 * Return the combined column width of all spanned wide character in
2215 * *rcol.
2217 static int
2218 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2220 int width, i, cols = 0;
2222 if (n == 0) {
2223 *rcol = cols;
2224 return off;
2227 for (i = off; wline[i] != L'\0'; ++i) {
2228 if (wline[i] == L'\t')
2229 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2230 else
2231 width = wcwidth(wline[i]);
2233 if (width == -1) {
2234 width = 1;
2235 wline[i] = L'.';
2238 if (cols + width > n)
2239 break;
2240 cols += width;
2243 *rcol = cols;
2244 return i;
2248 * Format a line for display, ensuring that it won't overflow a width limit.
2249 * With scrolling, the width returned refers to the scrolled version of the
2250 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2252 static const struct got_error *
2253 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2254 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2256 const struct got_error *err = NULL;
2257 int cols;
2258 wchar_t *wline = NULL;
2259 char *exstr = NULL;
2260 size_t wlen;
2261 int i, scrollx;
2263 *wlinep = NULL;
2264 *widthp = 0;
2266 if (expand) {
2267 err = expand_tab(&exstr, line);
2268 if (err)
2269 return err;
2272 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2273 free(exstr);
2274 if (err)
2275 return err;
2277 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2279 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2280 wline[wlen - 1] = L'\0';
2281 wlen--;
2283 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2284 wline[wlen - 1] = L'\0';
2285 wlen--;
2288 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2289 wline[i] = L'\0';
2291 if (widthp)
2292 *widthp = cols;
2293 if (scrollxp)
2294 *scrollxp = scrollx;
2295 if (err)
2296 free(wline);
2297 else
2298 *wlinep = wline;
2299 return err;
2302 static const struct got_error*
2303 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2304 struct got_object_id *id, struct got_repository *repo)
2306 static const struct got_error *err = NULL;
2307 struct got_reflist_entry *re;
2308 char *s;
2309 const char *name;
2311 *refs_str = NULL;
2313 TAILQ_FOREACH(re, refs, entry) {
2314 struct got_tag_object *tag = NULL;
2315 struct got_object_id *ref_id;
2316 int cmp;
2318 name = got_ref_get_name(re->ref);
2319 if (strcmp(name, GOT_REF_HEAD) == 0)
2320 continue;
2321 if (strncmp(name, "refs/", 5) == 0)
2322 name += 5;
2323 if (strncmp(name, "got/", 4) == 0 &&
2324 strncmp(name, "got/backup/", 11) != 0)
2325 continue;
2326 if (strncmp(name, "heads/", 6) == 0)
2327 name += 6;
2328 if (strncmp(name, "remotes/", 8) == 0) {
2329 name += 8;
2330 s = strstr(name, "/" GOT_REF_HEAD);
2331 if (s != NULL && s[strlen(s)] == '\0')
2332 continue;
2334 err = got_ref_resolve(&ref_id, repo, re->ref);
2335 if (err)
2336 break;
2337 if (strncmp(name, "tags/", 5) == 0) {
2338 err = got_object_open_as_tag(&tag, repo, ref_id);
2339 if (err) {
2340 if (err->code != GOT_ERR_OBJ_TYPE) {
2341 free(ref_id);
2342 break;
2344 /* Ref points at something other than a tag. */
2345 err = NULL;
2346 tag = NULL;
2349 cmp = got_object_id_cmp(tag ?
2350 got_object_tag_get_object_id(tag) : ref_id, id);
2351 free(ref_id);
2352 if (tag)
2353 got_object_tag_close(tag);
2354 if (cmp != 0)
2355 continue;
2356 s = *refs_str;
2357 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2358 s ? ", " : "", name) == -1) {
2359 err = got_error_from_errno("asprintf");
2360 free(s);
2361 *refs_str = NULL;
2362 break;
2364 free(s);
2367 return err;
2370 static const struct got_error *
2371 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2372 int col_tab_align)
2374 char *smallerthan;
2376 smallerthan = strchr(author, '<');
2377 if (smallerthan && smallerthan[1] != '\0')
2378 author = smallerthan + 1;
2379 author[strcspn(author, "@>")] = '\0';
2380 return format_line(wauthor, author_width, NULL, author, 0, limit,
2381 col_tab_align, 0);
2384 static const struct got_error *
2385 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2386 struct got_object_id *id, const size_t date_display_cols,
2387 int author_display_cols)
2389 struct tog_log_view_state *s = &view->state.log;
2390 const struct got_error *err = NULL;
2391 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2392 char *logmsg0 = NULL, *logmsg = NULL;
2393 char *author = NULL;
2394 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2395 int author_width, logmsg_width;
2396 char *newline, *line = NULL;
2397 int col, limit, scrollx;
2398 const int avail = view->ncols;
2399 struct tm tm;
2400 time_t committer_time;
2401 struct tog_color *tc;
2403 committer_time = got_object_commit_get_committer_time(commit);
2404 if (gmtime_r(&committer_time, &tm) == NULL)
2405 return got_error_from_errno("gmtime_r");
2406 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2407 return got_error(GOT_ERR_NO_SPACE);
2409 if (avail <= date_display_cols)
2410 limit = MIN(sizeof(datebuf) - 1, avail);
2411 else
2412 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2413 tc = get_color(&s->colors, TOG_COLOR_DATE);
2414 if (tc)
2415 wattr_on(view->window,
2416 COLOR_PAIR(tc->colorpair), NULL);
2417 waddnstr(view->window, datebuf, limit);
2418 if (tc)
2419 wattr_off(view->window,
2420 COLOR_PAIR(tc->colorpair), NULL);
2421 col = limit;
2422 if (col > avail)
2423 goto done;
2425 if (avail >= 120) {
2426 char *id_str;
2427 err = got_object_id_str(&id_str, id);
2428 if (err)
2429 goto done;
2430 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2431 if (tc)
2432 wattr_on(view->window,
2433 COLOR_PAIR(tc->colorpair), NULL);
2434 wprintw(view->window, "%.8s ", id_str);
2435 if (tc)
2436 wattr_off(view->window,
2437 COLOR_PAIR(tc->colorpair), NULL);
2438 free(id_str);
2439 col += 9;
2440 if (col > avail)
2441 goto done;
2444 if (s->use_committer)
2445 author = strdup(got_object_commit_get_committer(commit));
2446 else
2447 author = strdup(got_object_commit_get_author(commit));
2448 if (author == NULL) {
2449 err = got_error_from_errno("strdup");
2450 goto done;
2452 err = format_author(&wauthor, &author_width, author, avail - col, col);
2453 if (err)
2454 goto done;
2455 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2456 if (tc)
2457 wattr_on(view->window,
2458 COLOR_PAIR(tc->colorpair), NULL);
2459 waddwstr(view->window, wauthor);
2460 col += author_width;
2461 while (col < avail && author_width < author_display_cols + 2) {
2462 waddch(view->window, ' ');
2463 col++;
2464 author_width++;
2466 if (tc)
2467 wattr_off(view->window,
2468 COLOR_PAIR(tc->colorpair), NULL);
2469 if (col > avail)
2470 goto done;
2472 err = got_object_commit_get_logmsg(&logmsg0, commit);
2473 if (err)
2474 goto done;
2475 logmsg = logmsg0;
2476 while (*logmsg == '\n')
2477 logmsg++;
2478 newline = strchr(logmsg, '\n');
2479 if (newline)
2480 *newline = '\0';
2481 limit = avail - col;
2482 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2483 limit--; /* for the border */
2484 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2485 limit, col, 1);
2486 if (err)
2487 goto done;
2488 waddwstr(view->window, &wlogmsg[scrollx]);
2489 col += MAX(logmsg_width, 0);
2490 while (col < avail) {
2491 waddch(view->window, ' ');
2492 col++;
2494 done:
2495 free(logmsg0);
2496 free(wlogmsg);
2497 free(author);
2498 free(wauthor);
2499 free(line);
2500 return err;
2503 static struct commit_queue_entry *
2504 alloc_commit_queue_entry(struct got_commit_object *commit,
2505 struct got_object_id *id)
2507 struct commit_queue_entry *entry;
2508 struct got_object_id *dup;
2510 entry = calloc(1, sizeof(*entry));
2511 if (entry == NULL)
2512 return NULL;
2514 dup = got_object_id_dup(id);
2515 if (dup == NULL) {
2516 free(entry);
2517 return NULL;
2520 entry->id = dup;
2521 entry->commit = commit;
2522 return entry;
2525 static void
2526 pop_commit(struct commit_queue *commits)
2528 struct commit_queue_entry *entry;
2530 entry = TAILQ_FIRST(&commits->head);
2531 TAILQ_REMOVE(&commits->head, entry, entry);
2532 got_object_commit_close(entry->commit);
2533 commits->ncommits--;
2534 free(entry->id);
2535 free(entry);
2538 static void
2539 free_commits(struct commit_queue *commits)
2541 while (!TAILQ_EMPTY(&commits->head))
2542 pop_commit(commits);
2545 static const struct got_error *
2546 match_commit(int *have_match, struct got_object_id *id,
2547 struct got_commit_object *commit, regex_t *regex)
2549 const struct got_error *err = NULL;
2550 regmatch_t regmatch;
2551 char *id_str = NULL, *logmsg = NULL;
2553 *have_match = 0;
2555 err = got_object_id_str(&id_str, id);
2556 if (err)
2557 return err;
2559 err = got_object_commit_get_logmsg(&logmsg, commit);
2560 if (err)
2561 goto done;
2563 if (regexec(regex, got_object_commit_get_author(commit), 1,
2564 &regmatch, 0) == 0 ||
2565 regexec(regex, got_object_commit_get_committer(commit), 1,
2566 &regmatch, 0) == 0 ||
2567 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2568 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2569 *have_match = 1;
2570 done:
2571 free(id_str);
2572 free(logmsg);
2573 return err;
2576 static const struct got_error *
2577 queue_commits(struct tog_log_thread_args *a)
2579 const struct got_error *err = NULL;
2582 * We keep all commits open throughout the lifetime of the log
2583 * view in order to avoid having to re-fetch commits from disk
2584 * while updating the display.
2586 do {
2587 struct got_object_id id;
2588 struct got_commit_object *commit;
2589 struct commit_queue_entry *entry;
2590 int limit_match = 0;
2591 int errcode;
2593 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2594 NULL, NULL);
2595 if (err)
2596 break;
2598 err = got_object_open_as_commit(&commit, a->repo, &id);
2599 if (err)
2600 break;
2601 entry = alloc_commit_queue_entry(commit, &id);
2602 if (entry == NULL) {
2603 err = got_error_from_errno("alloc_commit_queue_entry");
2604 break;
2607 errcode = pthread_mutex_lock(&tog_mutex);
2608 if (errcode) {
2609 err = got_error_set_errno(errcode,
2610 "pthread_mutex_lock");
2611 break;
2614 entry->idx = a->real_commits->ncommits;
2615 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2616 a->real_commits->ncommits++;
2618 if (*a->limiting) {
2619 err = match_commit(&limit_match, &id, commit,
2620 a->limit_regex);
2621 if (err)
2622 break;
2624 if (limit_match) {
2625 struct commit_queue_entry *matched;
2627 matched = alloc_commit_queue_entry(
2628 entry->commit, entry->id);
2629 if (matched == NULL) {
2630 err = got_error_from_errno(
2631 "alloc_commit_queue_entry");
2632 break;
2634 matched->commit = entry->commit;
2635 got_object_commit_retain(entry->commit);
2637 matched->idx = a->limit_commits->ncommits;
2638 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2639 matched, entry);
2640 a->limit_commits->ncommits++;
2644 * This is how we signal log_thread() that we
2645 * have found a match, and that it should be
2646 * counted as a new entry for the view.
2648 a->limit_match = limit_match;
2651 if (*a->searching == TOG_SEARCH_FORWARD &&
2652 !*a->search_next_done) {
2653 int have_match;
2654 err = match_commit(&have_match, &id, commit, a->regex);
2655 if (err)
2656 break;
2658 if (*a->limiting) {
2659 if (limit_match && have_match)
2660 *a->search_next_done =
2661 TOG_SEARCH_HAVE_MORE;
2662 } else if (have_match)
2663 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2666 errcode = pthread_mutex_unlock(&tog_mutex);
2667 if (errcode && err == NULL)
2668 err = got_error_set_errno(errcode,
2669 "pthread_mutex_unlock");
2670 if (err)
2671 break;
2672 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2674 return err;
2677 static void
2678 select_commit(struct tog_log_view_state *s)
2680 struct commit_queue_entry *entry;
2681 int ncommits = 0;
2683 entry = s->first_displayed_entry;
2684 while (entry) {
2685 if (ncommits == s->selected) {
2686 s->selected_entry = entry;
2687 break;
2689 entry = TAILQ_NEXT(entry, entry);
2690 ncommits++;
2694 static const struct got_error *
2695 draw_commits(struct tog_view *view)
2697 const struct got_error *err = NULL;
2698 struct tog_log_view_state *s = &view->state.log;
2699 struct commit_queue_entry *entry = s->selected_entry;
2700 int limit = view->nlines;
2701 int width;
2702 int ncommits, author_cols = 4;
2703 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2704 char *refs_str = NULL;
2705 wchar_t *wline;
2706 struct tog_color *tc;
2707 static const size_t date_display_cols = 12;
2709 if (view_is_hsplit_top(view))
2710 --limit; /* account for border */
2712 if (s->selected_entry &&
2713 !(view->searching && view->search_next_done == 0)) {
2714 struct got_reflist_head *refs;
2715 err = got_object_id_str(&id_str, s->selected_entry->id);
2716 if (err)
2717 return err;
2718 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2719 s->selected_entry->id);
2720 if (refs) {
2721 err = build_refs_str(&refs_str, refs,
2722 s->selected_entry->id, s->repo);
2723 if (err)
2724 goto done;
2728 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2729 halfdelay(10); /* disable fast refresh */
2731 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2732 if (asprintf(&ncommits_str, " [%d/%d] %s",
2733 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2734 (view->searching && !view->search_next_done) ?
2735 "searching..." : "loading...") == -1) {
2736 err = got_error_from_errno("asprintf");
2737 goto done;
2739 } else {
2740 const char *search_str = NULL;
2741 const char *limit_str = NULL;
2743 if (view->searching) {
2744 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2745 search_str = "no more matches";
2746 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2747 search_str = "no matches found";
2748 else if (!view->search_next_done)
2749 search_str = "searching...";
2752 if (s->limit_view && s->commits->ncommits == 0)
2753 limit_str = "no matches found";
2755 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2756 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2757 search_str ? search_str : (refs_str ? refs_str : ""),
2758 limit_str ? limit_str : "") == -1) {
2759 err = got_error_from_errno("asprintf");
2760 goto done;
2764 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2765 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2766 "........................................",
2767 s->in_repo_path, ncommits_str) == -1) {
2768 err = got_error_from_errno("asprintf");
2769 header = NULL;
2770 goto done;
2772 } else if (asprintf(&header, "commit %s%s",
2773 id_str ? id_str : "........................................",
2774 ncommits_str) == -1) {
2775 err = got_error_from_errno("asprintf");
2776 header = NULL;
2777 goto done;
2779 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2780 if (err)
2781 goto done;
2783 werase(view->window);
2785 if (view_needs_focus_indication(view))
2786 wstandout(view->window);
2787 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2788 if (tc)
2789 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2790 waddwstr(view->window, wline);
2791 while (width < view->ncols) {
2792 waddch(view->window, ' ');
2793 width++;
2795 if (tc)
2796 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2797 if (view_needs_focus_indication(view))
2798 wstandend(view->window);
2799 free(wline);
2800 if (limit <= 1)
2801 goto done;
2803 /* Grow author column size if necessary, and set view->maxx. */
2804 entry = s->first_displayed_entry;
2805 ncommits = 0;
2806 view->maxx = 0;
2807 while (entry) {
2808 struct got_commit_object *c = entry->commit;
2809 char *author, *eol, *msg, *msg0;
2810 wchar_t *wauthor, *wmsg;
2811 int width;
2812 if (ncommits >= limit - 1)
2813 break;
2814 if (s->use_committer)
2815 author = strdup(got_object_commit_get_committer(c));
2816 else
2817 author = strdup(got_object_commit_get_author(c));
2818 if (author == NULL) {
2819 err = got_error_from_errno("strdup");
2820 goto done;
2822 err = format_author(&wauthor, &width, author, COLS,
2823 date_display_cols);
2824 if (author_cols < width)
2825 author_cols = width;
2826 free(wauthor);
2827 free(author);
2828 if (err)
2829 goto done;
2830 err = got_object_commit_get_logmsg(&msg0, c);
2831 if (err)
2832 goto done;
2833 msg = msg0;
2834 while (*msg == '\n')
2835 ++msg;
2836 if ((eol = strchr(msg, '\n')))
2837 *eol = '\0';
2838 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2839 date_display_cols + author_cols, 0);
2840 if (err)
2841 goto done;
2842 view->maxx = MAX(view->maxx, width);
2843 free(msg0);
2844 free(wmsg);
2845 ncommits++;
2846 entry = TAILQ_NEXT(entry, entry);
2849 entry = s->first_displayed_entry;
2850 s->last_displayed_entry = s->first_displayed_entry;
2851 ncommits = 0;
2852 while (entry) {
2853 if (ncommits >= limit - 1)
2854 break;
2855 if (ncommits == s->selected)
2856 wstandout(view->window);
2857 err = draw_commit(view, entry->commit, entry->id,
2858 date_display_cols, author_cols);
2859 if (ncommits == s->selected)
2860 wstandend(view->window);
2861 if (err)
2862 goto done;
2863 ncommits++;
2864 s->last_displayed_entry = entry;
2865 entry = TAILQ_NEXT(entry, entry);
2868 view_border(view);
2869 done:
2870 free(id_str);
2871 free(refs_str);
2872 free(ncommits_str);
2873 free(header);
2874 return err;
2877 static void
2878 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2880 struct commit_queue_entry *entry;
2881 int nscrolled = 0;
2883 entry = TAILQ_FIRST(&s->commits->head);
2884 if (s->first_displayed_entry == entry)
2885 return;
2887 entry = s->first_displayed_entry;
2888 while (entry && nscrolled < maxscroll) {
2889 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2890 if (entry) {
2891 s->first_displayed_entry = entry;
2892 nscrolled++;
2897 static const struct got_error *
2898 trigger_log_thread(struct tog_view *view, int wait)
2900 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2901 int errcode;
2903 if (!using_mock_io)
2904 halfdelay(1); /* fast refresh while loading commits */
2906 while (!ta->log_complete && !tog_thread_error &&
2907 (ta->commits_needed > 0 || ta->load_all)) {
2908 /* Wake the log thread. */
2909 errcode = pthread_cond_signal(&ta->need_commits);
2910 if (errcode)
2911 return got_error_set_errno(errcode,
2912 "pthread_cond_signal");
2915 * The mutex will be released while the view loop waits
2916 * in wgetch(), at which time the log thread will run.
2918 if (!wait)
2919 break;
2921 /* Display progress update in log view. */
2922 show_log_view(view);
2923 update_panels();
2924 doupdate();
2926 /* Wait right here while next commit is being loaded. */
2927 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2928 if (errcode)
2929 return got_error_set_errno(errcode,
2930 "pthread_cond_wait");
2932 /* Display progress update in log view. */
2933 show_log_view(view);
2934 update_panels();
2935 doupdate();
2938 return NULL;
2941 static const struct got_error *
2942 request_log_commits(struct tog_view *view)
2944 struct tog_log_view_state *state = &view->state.log;
2945 const struct got_error *err = NULL;
2947 if (state->thread_args.log_complete)
2948 return NULL;
2950 state->thread_args.commits_needed += view->nscrolled;
2951 err = trigger_log_thread(view, 1);
2952 view->nscrolled = 0;
2954 return err;
2957 static const struct got_error *
2958 log_scroll_down(struct tog_view *view, int maxscroll)
2960 struct tog_log_view_state *s = &view->state.log;
2961 const struct got_error *err = NULL;
2962 struct commit_queue_entry *pentry;
2963 int nscrolled = 0, ncommits_needed;
2965 if (s->last_displayed_entry == NULL)
2966 return NULL;
2968 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2969 if (s->commits->ncommits < ncommits_needed &&
2970 !s->thread_args.log_complete) {
2972 * Ask the log thread for required amount of commits.
2974 s->thread_args.commits_needed +=
2975 ncommits_needed - s->commits->ncommits;
2976 err = trigger_log_thread(view, 1);
2977 if (err)
2978 return err;
2981 do {
2982 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2983 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2984 break;
2986 s->last_displayed_entry = pentry ?
2987 pentry : s->last_displayed_entry;
2989 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2990 if (pentry == NULL)
2991 break;
2992 s->first_displayed_entry = pentry;
2993 } while (++nscrolled < maxscroll);
2995 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2996 view->nscrolled += nscrolled;
2997 else
2998 view->nscrolled = 0;
3000 return err;
3003 static const struct got_error *
3004 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3005 struct got_commit_object *commit, struct got_object_id *commit_id,
3006 struct tog_view *log_view, struct got_repository *repo)
3008 const struct got_error *err;
3009 struct got_object_qid *parent_id;
3010 struct tog_view *diff_view;
3012 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3013 if (diff_view == NULL)
3014 return got_error_from_errno("view_open");
3016 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3017 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3018 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3019 if (err == NULL)
3020 *new_view = diff_view;
3021 return err;
3024 static const struct got_error *
3025 tree_view_visit_subtree(struct tog_tree_view_state *s,
3026 struct got_tree_object *subtree)
3028 struct tog_parent_tree *parent;
3030 parent = calloc(1, sizeof(*parent));
3031 if (parent == NULL)
3032 return got_error_from_errno("calloc");
3034 parent->tree = s->tree;
3035 parent->first_displayed_entry = s->first_displayed_entry;
3036 parent->selected_entry = s->selected_entry;
3037 parent->selected = s->selected;
3038 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3039 s->tree = subtree;
3040 s->selected = 0;
3041 s->first_displayed_entry = NULL;
3042 return NULL;
3045 static const struct got_error *
3046 tree_view_walk_path(struct tog_tree_view_state *s,
3047 struct got_commit_object *commit, const char *path)
3049 const struct got_error *err = NULL;
3050 struct got_tree_object *tree = NULL;
3051 const char *p;
3052 char *slash, *subpath = NULL;
3054 /* Walk the path and open corresponding tree objects. */
3055 p = path;
3056 while (*p) {
3057 struct got_tree_entry *te;
3058 struct got_object_id *tree_id;
3059 char *te_name;
3061 while (p[0] == '/')
3062 p++;
3064 /* Ensure the correct subtree entry is selected. */
3065 slash = strchr(p, '/');
3066 if (slash == NULL)
3067 te_name = strdup(p);
3068 else
3069 te_name = strndup(p, slash - p);
3070 if (te_name == NULL) {
3071 err = got_error_from_errno("strndup");
3072 break;
3074 te = got_object_tree_find_entry(s->tree, te_name);
3075 if (te == NULL) {
3076 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3077 free(te_name);
3078 break;
3080 free(te_name);
3081 s->first_displayed_entry = s->selected_entry = te;
3083 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3084 break; /* jump to this file's entry */
3086 slash = strchr(p, '/');
3087 if (slash)
3088 subpath = strndup(path, slash - path);
3089 else
3090 subpath = strdup(path);
3091 if (subpath == NULL) {
3092 err = got_error_from_errno("strdup");
3093 break;
3096 err = got_object_id_by_path(&tree_id, s->repo, commit,
3097 subpath);
3098 if (err)
3099 break;
3101 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3102 free(tree_id);
3103 if (err)
3104 break;
3106 err = tree_view_visit_subtree(s, tree);
3107 if (err) {
3108 got_object_tree_close(tree);
3109 break;
3111 if (slash == NULL)
3112 break;
3113 free(subpath);
3114 subpath = NULL;
3115 p = slash;
3118 free(subpath);
3119 return err;
3122 static const struct got_error *
3123 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3124 struct commit_queue_entry *entry, const char *path,
3125 const char *head_ref_name, struct got_repository *repo)
3127 const struct got_error *err = NULL;
3128 struct tog_tree_view_state *s;
3129 struct tog_view *tree_view;
3131 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3132 if (tree_view == NULL)
3133 return got_error_from_errno("view_open");
3135 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3136 if (err)
3137 return err;
3138 s = &tree_view->state.tree;
3140 *new_view = tree_view;
3142 if (got_path_is_root_dir(path))
3143 return NULL;
3145 return tree_view_walk_path(s, entry->commit, path);
3148 static const struct got_error *
3149 block_signals_used_by_main_thread(void)
3151 sigset_t sigset;
3152 int errcode;
3154 if (sigemptyset(&sigset) == -1)
3155 return got_error_from_errno("sigemptyset");
3157 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3158 if (sigaddset(&sigset, SIGWINCH) == -1)
3159 return got_error_from_errno("sigaddset");
3160 if (sigaddset(&sigset, SIGCONT) == -1)
3161 return got_error_from_errno("sigaddset");
3162 if (sigaddset(&sigset, SIGINT) == -1)
3163 return got_error_from_errno("sigaddset");
3164 if (sigaddset(&sigset, SIGTERM) == -1)
3165 return got_error_from_errno("sigaddset");
3167 /* ncurses handles SIGTSTP */
3168 if (sigaddset(&sigset, SIGTSTP) == -1)
3169 return got_error_from_errno("sigaddset");
3171 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3172 if (errcode)
3173 return got_error_set_errno(errcode, "pthread_sigmask");
3175 return NULL;
3178 static void *
3179 log_thread(void *arg)
3181 const struct got_error *err = NULL;
3182 int errcode = 0;
3183 struct tog_log_thread_args *a = arg;
3184 int done = 0;
3187 * Sync startup with main thread such that we begin our
3188 * work once view_input() has released the mutex.
3190 errcode = pthread_mutex_lock(&tog_mutex);
3191 if (errcode) {
3192 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3193 return (void *)err;
3196 err = block_signals_used_by_main_thread();
3197 if (err) {
3198 pthread_mutex_unlock(&tog_mutex);
3199 goto done;
3202 while (!done && !err && !tog_fatal_signal_received()) {
3203 errcode = pthread_mutex_unlock(&tog_mutex);
3204 if (errcode) {
3205 err = got_error_set_errno(errcode,
3206 "pthread_mutex_unlock");
3207 goto done;
3209 err = queue_commits(a);
3210 if (err) {
3211 if (err->code != GOT_ERR_ITER_COMPLETED)
3212 goto done;
3213 err = NULL;
3214 done = 1;
3215 } else if (a->commits_needed > 0 && !a->load_all) {
3216 if (*a->limiting) {
3217 if (a->limit_match)
3218 a->commits_needed--;
3219 } else
3220 a->commits_needed--;
3223 errcode = pthread_mutex_lock(&tog_mutex);
3224 if (errcode) {
3225 err = got_error_set_errno(errcode,
3226 "pthread_mutex_lock");
3227 goto done;
3228 } else if (*a->quit)
3229 done = 1;
3230 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3231 *a->first_displayed_entry =
3232 TAILQ_FIRST(&a->limit_commits->head);
3233 *a->selected_entry = *a->first_displayed_entry;
3234 } else if (*a->first_displayed_entry == NULL) {
3235 *a->first_displayed_entry =
3236 TAILQ_FIRST(&a->real_commits->head);
3237 *a->selected_entry = *a->first_displayed_entry;
3240 errcode = pthread_cond_signal(&a->commit_loaded);
3241 if (errcode) {
3242 err = got_error_set_errno(errcode,
3243 "pthread_cond_signal");
3244 pthread_mutex_unlock(&tog_mutex);
3245 goto done;
3248 if (done)
3249 a->commits_needed = 0;
3250 else {
3251 if (a->commits_needed == 0 && !a->load_all) {
3252 errcode = pthread_cond_wait(&a->need_commits,
3253 &tog_mutex);
3254 if (errcode) {
3255 err = got_error_set_errno(errcode,
3256 "pthread_cond_wait");
3257 pthread_mutex_unlock(&tog_mutex);
3258 goto done;
3260 if (*a->quit)
3261 done = 1;
3265 a->log_complete = 1;
3266 errcode = pthread_mutex_unlock(&tog_mutex);
3267 if (errcode)
3268 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3269 done:
3270 if (err) {
3271 tog_thread_error = 1;
3272 pthread_cond_signal(&a->commit_loaded);
3274 return (void *)err;
3277 static const struct got_error *
3278 stop_log_thread(struct tog_log_view_state *s)
3280 const struct got_error *err = NULL, *thread_err = NULL;
3281 int errcode;
3283 if (s->thread) {
3284 s->quit = 1;
3285 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3286 if (errcode)
3287 return got_error_set_errno(errcode,
3288 "pthread_cond_signal");
3289 errcode = pthread_mutex_unlock(&tog_mutex);
3290 if (errcode)
3291 return got_error_set_errno(errcode,
3292 "pthread_mutex_unlock");
3293 errcode = pthread_join(s->thread, (void **)&thread_err);
3294 if (errcode)
3295 return got_error_set_errno(errcode, "pthread_join");
3296 errcode = pthread_mutex_lock(&tog_mutex);
3297 if (errcode)
3298 return got_error_set_errno(errcode,
3299 "pthread_mutex_lock");
3300 s->thread = 0; //NULL;
3303 if (s->thread_args.repo) {
3304 err = got_repo_close(s->thread_args.repo);
3305 s->thread_args.repo = NULL;
3308 if (s->thread_args.pack_fds) {
3309 const struct got_error *pack_err =
3310 got_repo_pack_fds_close(s->thread_args.pack_fds);
3311 if (err == NULL)
3312 err = pack_err;
3313 s->thread_args.pack_fds = NULL;
3316 if (s->thread_args.graph) {
3317 got_commit_graph_close(s->thread_args.graph);
3318 s->thread_args.graph = NULL;
3321 return err ? err : thread_err;
3324 static const struct got_error *
3325 close_log_view(struct tog_view *view)
3327 const struct got_error *err = NULL;
3328 struct tog_log_view_state *s = &view->state.log;
3329 int errcode;
3331 err = stop_log_thread(s);
3333 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3334 if (errcode && err == NULL)
3335 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3337 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3338 if (errcode && err == NULL)
3339 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3341 free_commits(&s->limit_commits);
3342 free_commits(&s->real_commits);
3343 free(s->in_repo_path);
3344 s->in_repo_path = NULL;
3345 free(s->start_id);
3346 s->start_id = NULL;
3347 free(s->head_ref_name);
3348 s->head_ref_name = NULL;
3349 return err;
3353 * We use two queues to implement the limit feature: first consists of
3354 * commits matching the current limit_regex; second is the real queue
3355 * of all known commits (real_commits). When the user starts limiting,
3356 * we swap queues such that all movement and displaying functionality
3357 * works with very slight change.
3359 static const struct got_error *
3360 limit_log_view(struct tog_view *view)
3362 struct tog_log_view_state *s = &view->state.log;
3363 struct commit_queue_entry *entry;
3364 struct tog_view *v = view;
3365 const struct got_error *err = NULL;
3366 char pattern[1024];
3367 int ret;
3369 if (view_is_hsplit_top(view))
3370 v = view->child;
3371 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3372 v = view->parent;
3374 /* Get the pattern */
3375 wmove(v->window, v->nlines - 1, 0);
3376 wclrtoeol(v->window);
3377 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3378 nodelay(v->window, FALSE);
3379 nocbreak();
3380 echo();
3381 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3382 cbreak();
3383 noecho();
3384 nodelay(v->window, TRUE);
3385 if (ret == ERR)
3386 return NULL;
3388 if (*pattern == '\0') {
3390 * Safety measure for the situation where the user
3391 * resets limit without previously limiting anything.
3393 if (!s->limit_view)
3394 return NULL;
3397 * User could have pressed Ctrl+L, which refreshed the
3398 * commit queues, it means we can't save previously
3399 * (before limit took place) displayed entries,
3400 * because they would point to already free'ed memory,
3401 * so we are forced to always select first entry of
3402 * the queue.
3404 s->commits = &s->real_commits;
3405 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3406 s->selected_entry = s->first_displayed_entry;
3407 s->selected = 0;
3408 s->limit_view = 0;
3410 return NULL;
3413 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3414 return NULL;
3416 s->limit_view = 1;
3418 /* Clear the screen while loading limit view */
3419 s->first_displayed_entry = NULL;
3420 s->last_displayed_entry = NULL;
3421 s->selected_entry = NULL;
3422 s->commits = &s->limit_commits;
3424 /* Prepare limit queue for new search */
3425 free_commits(&s->limit_commits);
3426 s->limit_commits.ncommits = 0;
3428 /* First process commits, which are in queue already */
3429 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3430 int have_match = 0;
3432 err = match_commit(&have_match, entry->id,
3433 entry->commit, &s->limit_regex);
3434 if (err)
3435 return err;
3437 if (have_match) {
3438 struct commit_queue_entry *matched;
3440 matched = alloc_commit_queue_entry(entry->commit,
3441 entry->id);
3442 if (matched == NULL) {
3443 err = got_error_from_errno(
3444 "alloc_commit_queue_entry");
3445 break;
3447 matched->commit = entry->commit;
3448 got_object_commit_retain(entry->commit);
3450 matched->idx = s->limit_commits.ncommits;
3451 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3452 matched, entry);
3453 s->limit_commits.ncommits++;
3457 /* Second process all the commits, until we fill the screen */
3458 if (s->limit_commits.ncommits < view->nlines - 1 &&
3459 !s->thread_args.log_complete) {
3460 s->thread_args.commits_needed +=
3461 view->nlines - s->limit_commits.ncommits - 1;
3462 err = trigger_log_thread(view, 1);
3463 if (err)
3464 return err;
3467 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3468 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3469 s->selected = 0;
3471 return NULL;
3474 static const struct got_error *
3475 search_start_log_view(struct tog_view *view)
3477 struct tog_log_view_state *s = &view->state.log;
3479 s->matched_entry = NULL;
3480 s->search_entry = NULL;
3481 return NULL;
3484 static const struct got_error *
3485 search_next_log_view(struct tog_view *view)
3487 const struct got_error *err = NULL;
3488 struct tog_log_view_state *s = &view->state.log;
3489 struct commit_queue_entry *entry;
3491 /* Display progress update in log view. */
3492 show_log_view(view);
3493 update_panels();
3494 doupdate();
3496 if (s->search_entry) {
3497 int errcode, ch;
3498 errcode = pthread_mutex_unlock(&tog_mutex);
3499 if (errcode)
3500 return got_error_set_errno(errcode,
3501 "pthread_mutex_unlock");
3502 ch = wgetch(view->window);
3503 errcode = pthread_mutex_lock(&tog_mutex);
3504 if (errcode)
3505 return got_error_set_errno(errcode,
3506 "pthread_mutex_lock");
3507 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3508 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3509 return NULL;
3511 if (view->searching == TOG_SEARCH_FORWARD)
3512 entry = TAILQ_NEXT(s->search_entry, entry);
3513 else
3514 entry = TAILQ_PREV(s->search_entry,
3515 commit_queue_head, entry);
3516 } else if (s->matched_entry) {
3518 * If the user has moved the cursor after we hit a match,
3519 * the position from where we should continue searching
3520 * might have changed.
3522 if (view->searching == TOG_SEARCH_FORWARD)
3523 entry = TAILQ_NEXT(s->selected_entry, entry);
3524 else
3525 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3526 entry);
3527 } else {
3528 entry = s->selected_entry;
3531 while (1) {
3532 int have_match = 0;
3534 if (entry == NULL) {
3535 if (s->thread_args.log_complete ||
3536 view->searching == TOG_SEARCH_BACKWARD) {
3537 view->search_next_done =
3538 (s->matched_entry == NULL ?
3539 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3540 s->search_entry = NULL;
3541 return NULL;
3544 * Poke the log thread for more commits and return,
3545 * allowing the main loop to make progress. Search
3546 * will resume at s->search_entry once we come back.
3548 s->thread_args.commits_needed++;
3549 return trigger_log_thread(view, 0);
3552 err = match_commit(&have_match, entry->id, entry->commit,
3553 &view->regex);
3554 if (err)
3555 break;
3556 if (have_match) {
3557 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3558 s->matched_entry = entry;
3559 break;
3562 s->search_entry = entry;
3563 if (view->searching == TOG_SEARCH_FORWARD)
3564 entry = TAILQ_NEXT(entry, entry);
3565 else
3566 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3569 if (s->matched_entry) {
3570 int cur = s->selected_entry->idx;
3571 while (cur < s->matched_entry->idx) {
3572 err = input_log_view(NULL, view, KEY_DOWN);
3573 if (err)
3574 return err;
3575 cur++;
3577 while (cur > s->matched_entry->idx) {
3578 err = input_log_view(NULL, view, KEY_UP);
3579 if (err)
3580 return err;
3581 cur--;
3585 s->search_entry = NULL;
3587 return NULL;
3590 static const struct got_error *
3591 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3592 struct got_repository *repo, const char *head_ref_name,
3593 const char *in_repo_path, int log_branches)
3595 const struct got_error *err = NULL;
3596 struct tog_log_view_state *s = &view->state.log;
3597 struct got_repository *thread_repo = NULL;
3598 struct got_commit_graph *thread_graph = NULL;
3599 int errcode;
3601 if (in_repo_path != s->in_repo_path) {
3602 free(s->in_repo_path);
3603 s->in_repo_path = strdup(in_repo_path);
3604 if (s->in_repo_path == NULL) {
3605 err = got_error_from_errno("strdup");
3606 goto done;
3610 /* The commit queue only contains commits being displayed. */
3611 TAILQ_INIT(&s->real_commits.head);
3612 s->real_commits.ncommits = 0;
3613 s->commits = &s->real_commits;
3615 TAILQ_INIT(&s->limit_commits.head);
3616 s->limit_view = 0;
3617 s->limit_commits.ncommits = 0;
3619 s->repo = repo;
3620 if (head_ref_name) {
3621 s->head_ref_name = strdup(head_ref_name);
3622 if (s->head_ref_name == NULL) {
3623 err = got_error_from_errno("strdup");
3624 goto done;
3627 s->start_id = got_object_id_dup(start_id);
3628 if (s->start_id == NULL) {
3629 err = got_error_from_errno("got_object_id_dup");
3630 goto done;
3632 s->log_branches = log_branches;
3633 s->use_committer = 1;
3635 STAILQ_INIT(&s->colors);
3636 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3637 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3638 get_color_value("TOG_COLOR_COMMIT"));
3639 if (err)
3640 goto done;
3641 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3642 get_color_value("TOG_COLOR_AUTHOR"));
3643 if (err) {
3644 free_colors(&s->colors);
3645 goto done;
3647 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3648 get_color_value("TOG_COLOR_DATE"));
3649 if (err) {
3650 free_colors(&s->colors);
3651 goto done;
3655 view->show = show_log_view;
3656 view->input = input_log_view;
3657 view->resize = resize_log_view;
3658 view->close = close_log_view;
3659 view->search_start = search_start_log_view;
3660 view->search_next = search_next_log_view;
3662 if (s->thread_args.pack_fds == NULL) {
3663 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3664 if (err)
3665 goto done;
3667 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3668 s->thread_args.pack_fds);
3669 if (err)
3670 goto done;
3671 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3672 !s->log_branches);
3673 if (err)
3674 goto done;
3675 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3676 s->repo, NULL, NULL);
3677 if (err)
3678 goto done;
3680 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3681 if (errcode) {
3682 err = got_error_set_errno(errcode, "pthread_cond_init");
3683 goto done;
3685 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3686 if (errcode) {
3687 err = got_error_set_errno(errcode, "pthread_cond_init");
3688 goto done;
3691 s->thread_args.commits_needed = view->nlines;
3692 s->thread_args.graph = thread_graph;
3693 s->thread_args.real_commits = &s->real_commits;
3694 s->thread_args.limit_commits = &s->limit_commits;
3695 s->thread_args.in_repo_path = s->in_repo_path;
3696 s->thread_args.start_id = s->start_id;
3697 s->thread_args.repo = thread_repo;
3698 s->thread_args.log_complete = 0;
3699 s->thread_args.quit = &s->quit;
3700 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3701 s->thread_args.selected_entry = &s->selected_entry;
3702 s->thread_args.searching = &view->searching;
3703 s->thread_args.search_next_done = &view->search_next_done;
3704 s->thread_args.regex = &view->regex;
3705 s->thread_args.limiting = &s->limit_view;
3706 s->thread_args.limit_regex = &s->limit_regex;
3707 s->thread_args.limit_commits = &s->limit_commits;
3708 done:
3709 if (err) {
3710 if (view->close == NULL)
3711 close_log_view(view);
3712 view_close(view);
3714 return err;
3717 static const struct got_error *
3718 show_log_view(struct tog_view *view)
3720 const struct got_error *err;
3721 struct tog_log_view_state *s = &view->state.log;
3723 if (s->thread == 0) { //NULL) {
3724 int errcode = pthread_create(&s->thread, NULL, log_thread,
3725 &s->thread_args);
3726 if (errcode)
3727 return got_error_set_errno(errcode, "pthread_create");
3728 if (s->thread_args.commits_needed > 0) {
3729 err = trigger_log_thread(view, 1);
3730 if (err)
3731 return err;
3735 return draw_commits(view);
3738 static void
3739 log_move_cursor_up(struct tog_view *view, int page, int home)
3741 struct tog_log_view_state *s = &view->state.log;
3743 if (s->first_displayed_entry == NULL)
3744 return;
3745 if (s->selected_entry->idx == 0)
3746 view->count = 0;
3748 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3749 || home)
3750 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3752 if (!page && !home && s->selected > 0)
3753 --s->selected;
3754 else
3755 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3757 select_commit(s);
3758 return;
3761 static const struct got_error *
3762 log_move_cursor_down(struct tog_view *view, int page)
3764 struct tog_log_view_state *s = &view->state.log;
3765 const struct got_error *err = NULL;
3766 int eos = view->nlines - 2;
3768 if (s->first_displayed_entry == NULL)
3769 return NULL;
3771 if (s->thread_args.log_complete &&
3772 s->selected_entry->idx >= s->commits->ncommits - 1)
3773 return NULL;
3775 if (view_is_hsplit_top(view))
3776 --eos; /* border consumes the last line */
3778 if (!page) {
3779 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3780 ++s->selected;
3781 else
3782 err = log_scroll_down(view, 1);
3783 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3784 struct commit_queue_entry *entry;
3785 int n;
3787 s->selected = 0;
3788 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3789 s->last_displayed_entry = entry;
3790 for (n = 0; n <= eos; n++) {
3791 if (entry == NULL)
3792 break;
3793 s->first_displayed_entry = entry;
3794 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3796 if (n > 0)
3797 s->selected = n - 1;
3798 } else {
3799 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3800 s->thread_args.log_complete)
3801 s->selected += MIN(page,
3802 s->commits->ncommits - s->selected_entry->idx - 1);
3803 else
3804 err = log_scroll_down(view, page);
3806 if (err)
3807 return err;
3810 * We might necessarily overshoot in horizontal
3811 * splits; if so, select the last displayed commit.
3813 if (s->first_displayed_entry && s->last_displayed_entry) {
3814 s->selected = MIN(s->selected,
3815 s->last_displayed_entry->idx -
3816 s->first_displayed_entry->idx);
3819 select_commit(s);
3821 if (s->thread_args.log_complete &&
3822 s->selected_entry->idx == s->commits->ncommits - 1)
3823 view->count = 0;
3825 return NULL;
3828 static void
3829 view_get_split(struct tog_view *view, int *y, int *x)
3831 *x = 0;
3832 *y = 0;
3834 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3835 if (view->child && view->child->resized_y)
3836 *y = view->child->resized_y;
3837 else if (view->resized_y)
3838 *y = view->resized_y;
3839 else
3840 *y = view_split_begin_y(view->lines);
3841 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3842 if (view->child && view->child->resized_x)
3843 *x = view->child->resized_x;
3844 else if (view->resized_x)
3845 *x = view->resized_x;
3846 else
3847 *x = view_split_begin_x(view->begin_x);
3851 /* Split view horizontally at y and offset view->state->selected line. */
3852 static const struct got_error *
3853 view_init_hsplit(struct tog_view *view, int y)
3855 const struct got_error *err = NULL;
3857 view->nlines = y;
3858 view->ncols = COLS;
3859 err = view_resize(view);
3860 if (err)
3861 return err;
3863 err = offset_selection_down(view);
3865 return err;
3868 static const struct got_error *
3869 log_goto_line(struct tog_view *view, int nlines)
3871 const struct got_error *err = NULL;
3872 struct tog_log_view_state *s = &view->state.log;
3873 int g, idx = s->selected_entry->idx;
3875 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3876 return NULL;
3878 g = view->gline;
3879 view->gline = 0;
3881 if (g >= s->first_displayed_entry->idx + 1 &&
3882 g <= s->last_displayed_entry->idx + 1 &&
3883 g - s->first_displayed_entry->idx - 1 < nlines) {
3884 s->selected = g - s->first_displayed_entry->idx - 1;
3885 select_commit(s);
3886 return NULL;
3889 if (idx + 1 < g) {
3890 err = log_move_cursor_down(view, g - idx - 1);
3891 if (!err && g > s->selected_entry->idx + 1)
3892 err = log_move_cursor_down(view,
3893 g - s->first_displayed_entry->idx - 1);
3894 if (err)
3895 return err;
3896 } else if (idx + 1 > g)
3897 log_move_cursor_up(view, idx - g + 1, 0);
3899 if (g < nlines && s->first_displayed_entry->idx == 0)
3900 s->selected = g - 1;
3902 select_commit(s);
3903 return NULL;
3907 static void
3908 horizontal_scroll_input(struct tog_view *view, int ch)
3911 switch (ch) {
3912 case KEY_LEFT:
3913 case 'h':
3914 view->x -= MIN(view->x, 2);
3915 if (view->x <= 0)
3916 view->count = 0;
3917 break;
3918 case KEY_RIGHT:
3919 case 'l':
3920 if (view->x + view->ncols / 2 < view->maxx)
3921 view->x += 2;
3922 else
3923 view->count = 0;
3924 break;
3925 case '0':
3926 view->x = 0;
3927 break;
3928 case '$':
3929 view->x = MAX(view->maxx - view->ncols / 2, 0);
3930 view->count = 0;
3931 break;
3932 default:
3933 break;
3937 static const struct got_error *
3938 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3940 const struct got_error *err = NULL;
3941 struct tog_log_view_state *s = &view->state.log;
3942 int eos, nscroll;
3944 if (s->thread_args.load_all) {
3945 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3946 s->thread_args.load_all = 0;
3947 else if (s->thread_args.log_complete) {
3948 err = log_move_cursor_down(view, s->commits->ncommits);
3949 s->thread_args.load_all = 0;
3951 if (err)
3952 return err;
3955 eos = nscroll = view->nlines - 1;
3956 if (view_is_hsplit_top(view))
3957 --eos; /* border */
3959 if (view->gline)
3960 return log_goto_line(view, eos);
3962 switch (ch) {
3963 case '&':
3964 err = limit_log_view(view);
3965 break;
3966 case 'q':
3967 s->quit = 1;
3968 break;
3969 case '0':
3970 case '$':
3971 case KEY_RIGHT:
3972 case 'l':
3973 case KEY_LEFT:
3974 case 'h':
3975 horizontal_scroll_input(view, ch);
3976 break;
3977 case 'k':
3978 case KEY_UP:
3979 case '<':
3980 case ',':
3981 case CTRL('p'):
3982 log_move_cursor_up(view, 0, 0);
3983 break;
3984 case 'g':
3985 case '=':
3986 case KEY_HOME:
3987 log_move_cursor_up(view, 0, 1);
3988 view->count = 0;
3989 break;
3990 case CTRL('u'):
3991 case 'u':
3992 nscroll /= 2;
3993 /* FALL THROUGH */
3994 case KEY_PPAGE:
3995 case CTRL('b'):
3996 case 'b':
3997 log_move_cursor_up(view, nscroll, 0);
3998 break;
3999 case 'j':
4000 case KEY_DOWN:
4001 case '>':
4002 case '.':
4003 case CTRL('n'):
4004 err = log_move_cursor_down(view, 0);
4005 break;
4006 case '@':
4007 s->use_committer = !s->use_committer;
4008 view->action = s->use_committer ?
4009 "show committer" : "show commit author";
4010 break;
4011 case 'G':
4012 case '*':
4013 case KEY_END: {
4014 /* We don't know yet how many commits, so we're forced to
4015 * traverse them all. */
4016 view->count = 0;
4017 s->thread_args.load_all = 1;
4018 if (!s->thread_args.log_complete)
4019 return trigger_log_thread(view, 0);
4020 err = log_move_cursor_down(view, s->commits->ncommits);
4021 s->thread_args.load_all = 0;
4022 break;
4024 case CTRL('d'):
4025 case 'd':
4026 nscroll /= 2;
4027 /* FALL THROUGH */
4028 case KEY_NPAGE:
4029 case CTRL('f'):
4030 case 'f':
4031 case ' ':
4032 err = log_move_cursor_down(view, nscroll);
4033 break;
4034 case KEY_RESIZE:
4035 if (s->selected > view->nlines - 2)
4036 s->selected = view->nlines - 2;
4037 if (s->selected > s->commits->ncommits - 1)
4038 s->selected = s->commits->ncommits - 1;
4039 select_commit(s);
4040 if (s->commits->ncommits < view->nlines - 1 &&
4041 !s->thread_args.log_complete) {
4042 s->thread_args.commits_needed += (view->nlines - 1) -
4043 s->commits->ncommits;
4044 err = trigger_log_thread(view, 1);
4046 break;
4047 case KEY_ENTER:
4048 case '\r':
4049 view->count = 0;
4050 if (s->selected_entry == NULL)
4051 break;
4052 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4053 break;
4054 case 'T':
4055 view->count = 0;
4056 if (s->selected_entry == NULL)
4057 break;
4058 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4059 break;
4060 case KEY_BACKSPACE:
4061 case CTRL('l'):
4062 case 'B':
4063 view->count = 0;
4064 if (ch == KEY_BACKSPACE &&
4065 got_path_is_root_dir(s->in_repo_path))
4066 break;
4067 err = stop_log_thread(s);
4068 if (err)
4069 return err;
4070 if (ch == KEY_BACKSPACE) {
4071 char *parent_path;
4072 err = got_path_dirname(&parent_path, s->in_repo_path);
4073 if (err)
4074 return err;
4075 free(s->in_repo_path);
4076 s->in_repo_path = parent_path;
4077 s->thread_args.in_repo_path = s->in_repo_path;
4078 } else if (ch == CTRL('l')) {
4079 struct got_object_id *start_id;
4080 err = got_repo_match_object_id(&start_id, NULL,
4081 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4082 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4083 if (err) {
4084 if (s->head_ref_name == NULL ||
4085 err->code != GOT_ERR_NOT_REF)
4086 return err;
4087 /* Try to cope with deleted references. */
4088 free(s->head_ref_name);
4089 s->head_ref_name = NULL;
4090 err = got_repo_match_object_id(&start_id,
4091 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4092 &tog_refs, s->repo);
4093 if (err)
4094 return err;
4096 free(s->start_id);
4097 s->start_id = start_id;
4098 s->thread_args.start_id = s->start_id;
4099 } else /* 'B' */
4100 s->log_branches = !s->log_branches;
4102 if (s->thread_args.pack_fds == NULL) {
4103 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4104 if (err)
4105 return err;
4107 err = got_repo_open(&s->thread_args.repo,
4108 got_repo_get_path(s->repo), NULL,
4109 s->thread_args.pack_fds);
4110 if (err)
4111 return err;
4112 tog_free_refs();
4113 err = tog_load_refs(s->repo, 0);
4114 if (err)
4115 return err;
4116 err = got_commit_graph_open(&s->thread_args.graph,
4117 s->in_repo_path, !s->log_branches);
4118 if (err)
4119 return err;
4120 err = got_commit_graph_iter_start(s->thread_args.graph,
4121 s->start_id, s->repo, NULL, NULL);
4122 if (err)
4123 return err;
4124 free_commits(&s->real_commits);
4125 free_commits(&s->limit_commits);
4126 s->first_displayed_entry = NULL;
4127 s->last_displayed_entry = NULL;
4128 s->selected_entry = NULL;
4129 s->selected = 0;
4130 s->thread_args.log_complete = 0;
4131 s->quit = 0;
4132 s->thread_args.commits_needed = view->lines;
4133 s->matched_entry = NULL;
4134 s->search_entry = NULL;
4135 view->offset = 0;
4136 break;
4137 case 'R':
4138 view->count = 0;
4139 err = view_request_new(new_view, view, TOG_VIEW_REF);
4140 break;
4141 default:
4142 view->count = 0;
4143 break;
4146 return err;
4149 static const struct got_error *
4150 apply_unveil(const char *repo_path, const char *worktree_path)
4152 const struct got_error *error;
4154 #ifdef PROFILE
4155 if (unveil("gmon.out", "rwc") != 0)
4156 return got_error_from_errno2("unveil", "gmon.out");
4157 #endif
4158 if (repo_path && unveil(repo_path, "r") != 0)
4159 return got_error_from_errno2("unveil", repo_path);
4161 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4162 return got_error_from_errno2("unveil", worktree_path);
4164 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4165 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4167 error = got_privsep_unveil_exec_helpers();
4168 if (error != NULL)
4169 return error;
4171 if (unveil(NULL, NULL) != 0)
4172 return got_error_from_errno("unveil");
4174 return NULL;
4177 static const struct got_error *
4178 init_mock_term(const char *test_script_path)
4180 const struct got_error *err = NULL;
4182 if (test_script_path == NULL || *test_script_path == '\0')
4183 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4185 tog_io.f = fopen(test_script_path, "re");
4186 if (tog_io.f == NULL) {
4187 err = got_error_from_errno_fmt("fopen: %s",
4188 test_script_path);
4189 goto done;
4192 /* test mode, we don't want any output */
4193 tog_io.cout = fopen("/dev/null", "w+");
4194 if (tog_io.cout == NULL) {
4195 err = got_error_from_errno("fopen: /dev/null");
4196 goto done;
4199 tog_io.cin = fopen("/dev/tty", "r+");
4200 if (tog_io.cin == NULL) {
4201 err = got_error_from_errno("fopen: /dev/tty");
4202 goto done;
4205 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4206 err = got_error_from_errno("fseeko");
4207 goto done;
4210 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4211 err = got_error_msg(GOT_ERR_IO,
4212 "newterm: failed to initialise curses");
4214 using_mock_io = 1;
4216 done:
4217 if (err)
4218 tog_io_close();
4219 return err;
4222 static void
4223 init_curses(void)
4226 * Override default signal handlers before starting ncurses.
4227 * This should prevent ncurses from installing its own
4228 * broken cleanup() signal handler.
4230 signal(SIGWINCH, tog_sigwinch);
4231 signal(SIGPIPE, tog_sigpipe);
4232 signal(SIGCONT, tog_sigcont);
4233 signal(SIGINT, tog_sigint);
4234 signal(SIGTERM, tog_sigterm);
4236 if (using_mock_io) /* In test mode we use a fake terminal */
4237 return;
4239 initscr();
4241 cbreak();
4242 halfdelay(1); /* Fast refresh while initial view is loading. */
4243 noecho();
4244 nonl();
4245 intrflush(stdscr, FALSE);
4246 keypad(stdscr, TRUE);
4247 curs_set(0);
4248 if (getenv("TOG_COLORS") != NULL) {
4249 start_color();
4250 use_default_colors();
4253 return;
4256 static const struct got_error *
4257 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4258 struct got_repository *repo, struct got_worktree *worktree)
4260 const struct got_error *err = NULL;
4262 if (argc == 0) {
4263 *in_repo_path = strdup("/");
4264 if (*in_repo_path == NULL)
4265 return got_error_from_errno("strdup");
4266 return NULL;
4269 if (worktree) {
4270 const char *prefix = got_worktree_get_path_prefix(worktree);
4271 char *p;
4273 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4274 if (err)
4275 return err;
4276 if (asprintf(in_repo_path, "%s%s%s", prefix,
4277 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4278 p) == -1) {
4279 err = got_error_from_errno("asprintf");
4280 *in_repo_path = NULL;
4282 free(p);
4283 } else
4284 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4286 return err;
4289 static const struct got_error *
4290 cmd_log(int argc, char *argv[])
4292 const struct got_error *error;
4293 struct got_repository *repo = NULL;
4294 struct got_worktree *worktree = NULL;
4295 struct got_object_id *start_id = NULL;
4296 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4297 char *start_commit = NULL, *label = NULL;
4298 struct got_reference *ref = NULL;
4299 const char *head_ref_name = NULL;
4300 int ch, log_branches = 0;
4301 struct tog_view *view;
4302 int *pack_fds = NULL;
4304 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4305 switch (ch) {
4306 case 'b':
4307 log_branches = 1;
4308 break;
4309 case 'c':
4310 start_commit = optarg;
4311 break;
4312 case 'r':
4313 repo_path = realpath(optarg, NULL);
4314 if (repo_path == NULL)
4315 return got_error_from_errno2("realpath",
4316 optarg);
4317 break;
4318 default:
4319 usage_log();
4320 /* NOTREACHED */
4324 argc -= optind;
4325 argv += optind;
4327 if (argc > 1)
4328 usage_log();
4330 error = got_repo_pack_fds_open(&pack_fds);
4331 if (error != NULL)
4332 goto done;
4334 if (repo_path == NULL) {
4335 cwd = getcwd(NULL, 0);
4336 if (cwd == NULL)
4337 return got_error_from_errno("getcwd");
4338 error = got_worktree_open(&worktree, cwd);
4339 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4340 goto done;
4341 if (worktree)
4342 repo_path =
4343 strdup(got_worktree_get_repo_path(worktree));
4344 else
4345 repo_path = strdup(cwd);
4346 if (repo_path == NULL) {
4347 error = got_error_from_errno("strdup");
4348 goto done;
4352 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4353 if (error != NULL)
4354 goto done;
4356 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4357 repo, worktree);
4358 if (error)
4359 goto done;
4361 init_curses();
4363 error = apply_unveil(got_repo_get_path(repo),
4364 worktree ? got_worktree_get_root_path(worktree) : NULL);
4365 if (error)
4366 goto done;
4368 /* already loaded by tog_log_with_path()? */
4369 if (TAILQ_EMPTY(&tog_refs)) {
4370 error = tog_load_refs(repo, 0);
4371 if (error)
4372 goto done;
4375 if (start_commit == NULL) {
4376 error = got_repo_match_object_id(&start_id, &label,
4377 worktree ? got_worktree_get_head_ref_name(worktree) :
4378 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4379 if (error)
4380 goto done;
4381 head_ref_name = label;
4382 } else {
4383 error = got_ref_open(&ref, repo, start_commit, 0);
4384 if (error == NULL)
4385 head_ref_name = got_ref_get_name(ref);
4386 else if (error->code != GOT_ERR_NOT_REF)
4387 goto done;
4388 error = got_repo_match_object_id(&start_id, NULL,
4389 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4390 if (error)
4391 goto done;
4394 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4395 if (view == NULL) {
4396 error = got_error_from_errno("view_open");
4397 goto done;
4399 error = open_log_view(view, start_id, repo, head_ref_name,
4400 in_repo_path, log_branches);
4401 if (error)
4402 goto done;
4403 if (worktree) {
4404 /* Release work tree lock. */
4405 got_worktree_close(worktree);
4406 worktree = NULL;
4408 error = view_loop(view);
4409 done:
4410 free(in_repo_path);
4411 free(repo_path);
4412 free(cwd);
4413 free(start_id);
4414 free(label);
4415 if (ref)
4416 got_ref_close(ref);
4417 if (repo) {
4418 const struct got_error *close_err = got_repo_close(repo);
4419 if (error == NULL)
4420 error = close_err;
4422 if (worktree)
4423 got_worktree_close(worktree);
4424 if (pack_fds) {
4425 const struct got_error *pack_err =
4426 got_repo_pack_fds_close(pack_fds);
4427 if (error == NULL)
4428 error = pack_err;
4430 tog_free_refs();
4431 return error;
4434 __dead static void
4435 usage_diff(void)
4437 endwin();
4438 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4439 "object1 object2\n", getprogname());
4440 exit(1);
4443 static int
4444 match_line(const char *line, regex_t *regex, size_t nmatch,
4445 regmatch_t *regmatch)
4447 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4450 static struct tog_color *
4451 match_color(struct tog_colors *colors, const char *line)
4453 struct tog_color *tc = NULL;
4455 STAILQ_FOREACH(tc, colors, entry) {
4456 if (match_line(line, &tc->regex, 0, NULL))
4457 return tc;
4460 return NULL;
4463 static const struct got_error *
4464 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4465 WINDOW *window, int skipcol, regmatch_t *regmatch)
4467 const struct got_error *err = NULL;
4468 char *exstr = NULL;
4469 wchar_t *wline = NULL;
4470 int rme, rms, n, width, scrollx;
4471 int width0 = 0, width1 = 0, width2 = 0;
4472 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4474 *wtotal = 0;
4476 rms = regmatch->rm_so;
4477 rme = regmatch->rm_eo;
4479 err = expand_tab(&exstr, line);
4480 if (err)
4481 return err;
4483 /* Split the line into 3 segments, according to match offsets. */
4484 seg0 = strndup(exstr, rms);
4485 if (seg0 == NULL) {
4486 err = got_error_from_errno("strndup");
4487 goto done;
4489 seg1 = strndup(exstr + rms, rme - rms);
4490 if (seg1 == NULL) {
4491 err = got_error_from_errno("strndup");
4492 goto done;
4494 seg2 = strdup(exstr + rme);
4495 if (seg2 == NULL) {
4496 err = got_error_from_errno("strndup");
4497 goto done;
4500 /* draw up to matched token if we haven't scrolled past it */
4501 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4502 col_tab_align, 1);
4503 if (err)
4504 goto done;
4505 n = MAX(width0 - skipcol, 0);
4506 if (n) {
4507 free(wline);
4508 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4509 wlimit, col_tab_align, 1);
4510 if (err)
4511 goto done;
4512 waddwstr(window, &wline[scrollx]);
4513 wlimit -= width;
4514 *wtotal += width;
4517 if (wlimit > 0) {
4518 int i = 0, w = 0;
4519 size_t wlen;
4521 free(wline);
4522 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4523 col_tab_align, 1);
4524 if (err)
4525 goto done;
4526 wlen = wcslen(wline);
4527 while (i < wlen) {
4528 width = wcwidth(wline[i]);
4529 if (width == -1) {
4530 /* should not happen, tabs are expanded */
4531 err = got_error(GOT_ERR_RANGE);
4532 goto done;
4534 if (width0 + w + width > skipcol)
4535 break;
4536 w += width;
4537 i++;
4539 /* draw (visible part of) matched token (if scrolled into it) */
4540 if (width1 - w > 0) {
4541 wattron(window, A_STANDOUT);
4542 waddwstr(window, &wline[i]);
4543 wattroff(window, A_STANDOUT);
4544 wlimit -= (width1 - w);
4545 *wtotal += (width1 - w);
4549 if (wlimit > 0) { /* draw rest of line */
4550 free(wline);
4551 if (skipcol > width0 + width1) {
4552 err = format_line(&wline, &width2, &scrollx, seg2,
4553 skipcol - (width0 + width1), wlimit,
4554 col_tab_align, 1);
4555 if (err)
4556 goto done;
4557 waddwstr(window, &wline[scrollx]);
4558 } else {
4559 err = format_line(&wline, &width2, NULL, seg2, 0,
4560 wlimit, col_tab_align, 1);
4561 if (err)
4562 goto done;
4563 waddwstr(window, wline);
4565 *wtotal += width2;
4567 done:
4568 free(wline);
4569 free(exstr);
4570 free(seg0);
4571 free(seg1);
4572 free(seg2);
4573 return err;
4576 static int
4577 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4579 FILE *f = NULL;
4580 int *eof, *first, *selected;
4582 if (view->type == TOG_VIEW_DIFF) {
4583 struct tog_diff_view_state *s = &view->state.diff;
4585 first = &s->first_displayed_line;
4586 selected = first;
4587 eof = &s->eof;
4588 f = s->f;
4589 } else if (view->type == TOG_VIEW_HELP) {
4590 struct tog_help_view_state *s = &view->state.help;
4592 first = &s->first_displayed_line;
4593 selected = first;
4594 eof = &s->eof;
4595 f = s->f;
4596 } else if (view->type == TOG_VIEW_BLAME) {
4597 struct tog_blame_view_state *s = &view->state.blame;
4599 first = &s->first_displayed_line;
4600 selected = &s->selected_line;
4601 eof = &s->eof;
4602 f = s->blame.f;
4603 } else
4604 return 0;
4606 /* Center gline in the middle of the page like vi(1). */
4607 if (*lineno < view->gline - (view->nlines - 3) / 2)
4608 return 0;
4609 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4610 rewind(f);
4611 *eof = 0;
4612 *first = 1;
4613 *lineno = 0;
4614 *nprinted = 0;
4615 return 0;
4618 *selected = view->gline <= (view->nlines - 3) / 2 ?
4619 view->gline : (view->nlines - 3) / 2 + 1;
4620 view->gline = 0;
4622 return 1;
4625 static const struct got_error *
4626 draw_file(struct tog_view *view, const char *header)
4628 struct tog_diff_view_state *s = &view->state.diff;
4629 regmatch_t *regmatch = &view->regmatch;
4630 const struct got_error *err;
4631 int nprinted = 0;
4632 char *line;
4633 size_t linesize = 0;
4634 ssize_t linelen;
4635 wchar_t *wline;
4636 int width;
4637 int max_lines = view->nlines;
4638 int nlines = s->nlines;
4639 off_t line_offset;
4641 s->lineno = s->first_displayed_line - 1;
4642 line_offset = s->lines[s->first_displayed_line - 1].offset;
4643 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4644 return got_error_from_errno("fseek");
4646 werase(view->window);
4648 if (view->gline > s->nlines - 1)
4649 view->gline = s->nlines - 1;
4651 if (header) {
4652 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4653 1 : view->gline - (view->nlines - 3) / 2 :
4654 s->lineno + s->selected_line;
4656 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4657 return got_error_from_errno("asprintf");
4658 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4659 0, 0);
4660 free(line);
4661 if (err)
4662 return err;
4664 if (view_needs_focus_indication(view))
4665 wstandout(view->window);
4666 waddwstr(view->window, wline);
4667 free(wline);
4668 wline = NULL;
4669 while (width++ < view->ncols)
4670 waddch(view->window, ' ');
4671 if (view_needs_focus_indication(view))
4672 wstandend(view->window);
4674 if (max_lines <= 1)
4675 return NULL;
4676 max_lines--;
4679 s->eof = 0;
4680 view->maxx = 0;
4681 line = NULL;
4682 while (max_lines > 0 && nprinted < max_lines) {
4683 enum got_diff_line_type linetype;
4684 attr_t attr = 0;
4686 linelen = getline(&line, &linesize, s->f);
4687 if (linelen == -1) {
4688 if (feof(s->f)) {
4689 s->eof = 1;
4690 break;
4692 free(line);
4693 return got_ferror(s->f, GOT_ERR_IO);
4696 if (++s->lineno < s->first_displayed_line)
4697 continue;
4698 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4699 continue;
4700 if (s->lineno == view->hiline)
4701 attr = A_STANDOUT;
4703 /* Set view->maxx based on full line length. */
4704 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4705 view->x ? 1 : 0);
4706 if (err) {
4707 free(line);
4708 return err;
4710 view->maxx = MAX(view->maxx, width);
4711 free(wline);
4712 wline = NULL;
4714 linetype = s->lines[s->lineno].type;
4715 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4716 linetype < GOT_DIFF_LINE_CONTEXT)
4717 attr |= COLOR_PAIR(linetype);
4718 if (attr)
4719 wattron(view->window, attr);
4720 if (s->first_displayed_line + nprinted == s->matched_line &&
4721 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4722 err = add_matched_line(&width, line, view->ncols, 0,
4723 view->window, view->x, regmatch);
4724 if (err) {
4725 free(line);
4726 return err;
4728 } else {
4729 int skip;
4730 err = format_line(&wline, &width, &skip, line,
4731 view->x, view->ncols, 0, view->x ? 1 : 0);
4732 if (err) {
4733 free(line);
4734 return err;
4736 waddwstr(view->window, &wline[skip]);
4737 free(wline);
4738 wline = NULL;
4740 if (s->lineno == view->hiline) {
4741 /* highlight full gline length */
4742 while (width++ < view->ncols)
4743 waddch(view->window, ' ');
4744 } else {
4745 if (width <= view->ncols - 1)
4746 waddch(view->window, '\n');
4748 if (attr)
4749 wattroff(view->window, attr);
4750 if (++nprinted == 1)
4751 s->first_displayed_line = s->lineno;
4753 free(line);
4754 if (nprinted >= 1)
4755 s->last_displayed_line = s->first_displayed_line +
4756 (nprinted - 1);
4757 else
4758 s->last_displayed_line = s->first_displayed_line;
4760 view_border(view);
4762 if (s->eof) {
4763 while (nprinted < view->nlines) {
4764 waddch(view->window, '\n');
4765 nprinted++;
4768 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4769 view->ncols, 0, 0);
4770 if (err) {
4771 return err;
4774 wstandout(view->window);
4775 waddwstr(view->window, wline);
4776 free(wline);
4777 wline = NULL;
4778 wstandend(view->window);
4781 return NULL;
4784 static char *
4785 get_datestr(time_t *time, char *datebuf)
4787 struct tm mytm, *tm;
4788 char *p, *s;
4790 tm = gmtime_r(time, &mytm);
4791 if (tm == NULL)
4792 return NULL;
4793 s = asctime_r(tm, datebuf);
4794 if (s == NULL)
4795 return NULL;
4796 p = strchr(s, '\n');
4797 if (p)
4798 *p = '\0';
4799 return s;
4802 static const struct got_error *
4803 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4804 off_t off, uint8_t type)
4806 struct got_diff_line *p;
4808 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4809 if (p == NULL)
4810 return got_error_from_errno("reallocarray");
4811 *lines = p;
4812 (*lines)[*nlines].offset = off;
4813 (*lines)[*nlines].type = type;
4814 (*nlines)++;
4816 return NULL;
4819 static const struct got_error *
4820 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4821 struct got_diff_line *s_lines, size_t s_nlines)
4823 struct got_diff_line *p;
4824 char buf[BUFSIZ];
4825 size_t i, r;
4827 if (fseeko(src, 0L, SEEK_SET) == -1)
4828 return got_error_from_errno("fseeko");
4830 for (;;) {
4831 r = fread(buf, 1, sizeof(buf), src);
4832 if (r == 0) {
4833 if (ferror(src))
4834 return got_error_from_errno("fread");
4835 if (feof(src))
4836 break;
4838 if (fwrite(buf, 1, r, dst) != r)
4839 return got_ferror(dst, GOT_ERR_IO);
4842 if (s_nlines == 0 && *d_nlines == 0)
4843 return NULL;
4846 * If commit info was in dst, increment line offsets
4847 * of the appended diff content, but skip s_lines[0]
4848 * because offset zero is already in *d_lines.
4850 if (*d_nlines > 0) {
4851 for (i = 1; i < s_nlines; ++i)
4852 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4854 if (s_nlines > 0) {
4855 --s_nlines;
4856 ++s_lines;
4860 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4861 if (p == NULL) {
4862 /* d_lines is freed in close_diff_view() */
4863 return got_error_from_errno("reallocarray");
4866 *d_lines = p;
4868 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4869 *d_nlines += s_nlines;
4871 return NULL;
4874 static const struct got_error *
4875 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4876 struct got_object_id *commit_id, struct got_reflist_head *refs,
4877 struct got_repository *repo, int ignore_ws, int force_text_diff,
4878 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4880 const struct got_error *err = NULL;
4881 char datebuf[26], *datestr;
4882 struct got_commit_object *commit;
4883 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4884 time_t committer_time;
4885 const char *author, *committer;
4886 char *refs_str = NULL;
4887 struct got_pathlist_entry *pe;
4888 off_t outoff = 0;
4889 int n;
4891 if (refs) {
4892 err = build_refs_str(&refs_str, refs, commit_id, repo);
4893 if (err)
4894 return err;
4897 err = got_object_open_as_commit(&commit, repo, commit_id);
4898 if (err)
4899 return err;
4901 err = got_object_id_str(&id_str, commit_id);
4902 if (err) {
4903 err = got_error_from_errno("got_object_id_str");
4904 goto done;
4907 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4908 if (err)
4909 goto done;
4911 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4912 refs_str ? refs_str : "", refs_str ? ")" : "");
4913 if (n < 0) {
4914 err = got_error_from_errno("fprintf");
4915 goto done;
4917 outoff += n;
4918 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4919 if (err)
4920 goto done;
4922 n = fprintf(outfile, "from: %s\n",
4923 got_object_commit_get_author(commit));
4924 if (n < 0) {
4925 err = got_error_from_errno("fprintf");
4926 goto done;
4928 outoff += n;
4929 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4930 if (err)
4931 goto done;
4933 author = got_object_commit_get_author(commit);
4934 committer = got_object_commit_get_committer(commit);
4935 if (strcmp(author, committer) != 0) {
4936 n = fprintf(outfile, "via: %s\n", committer);
4937 if (n < 0) {
4938 err = got_error_from_errno("fprintf");
4939 goto done;
4941 outoff += n;
4942 err = add_line_metadata(lines, nlines, outoff,
4943 GOT_DIFF_LINE_AUTHOR);
4944 if (err)
4945 goto done;
4947 committer_time = got_object_commit_get_committer_time(commit);
4948 datestr = get_datestr(&committer_time, datebuf);
4949 if (datestr) {
4950 n = fprintf(outfile, "date: %s UTC\n", datestr);
4951 if (n < 0) {
4952 err = got_error_from_errno("fprintf");
4953 goto done;
4955 outoff += n;
4956 err = add_line_metadata(lines, nlines, outoff,
4957 GOT_DIFF_LINE_DATE);
4958 if (err)
4959 goto done;
4961 if (got_object_commit_get_nparents(commit) > 1) {
4962 const struct got_object_id_queue *parent_ids;
4963 struct got_object_qid *qid;
4964 int pn = 1;
4965 parent_ids = got_object_commit_get_parent_ids(commit);
4966 STAILQ_FOREACH(qid, parent_ids, entry) {
4967 err = got_object_id_str(&id_str, &qid->id);
4968 if (err)
4969 goto done;
4970 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4971 if (n < 0) {
4972 err = got_error_from_errno("fprintf");
4973 goto done;
4975 outoff += n;
4976 err = add_line_metadata(lines, nlines, outoff,
4977 GOT_DIFF_LINE_META);
4978 if (err)
4979 goto done;
4980 free(id_str);
4981 id_str = NULL;
4985 err = got_object_commit_get_logmsg(&logmsg, commit);
4986 if (err)
4987 goto done;
4988 s = logmsg;
4989 while ((line = strsep(&s, "\n")) != NULL) {
4990 n = fprintf(outfile, "%s\n", line);
4991 if (n < 0) {
4992 err = got_error_from_errno("fprintf");
4993 goto done;
4995 outoff += n;
4996 err = add_line_metadata(lines, nlines, outoff,
4997 GOT_DIFF_LINE_LOGMSG);
4998 if (err)
4999 goto done;
5002 TAILQ_FOREACH(pe, dsa->paths, entry) {
5003 struct got_diff_changed_path *cp = pe->data;
5004 int pad = dsa->max_path_len - pe->path_len + 1;
5006 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5007 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5008 dsa->rm_cols + 1, cp->rm);
5009 if (n < 0) {
5010 err = got_error_from_errno("fprintf");
5011 goto done;
5013 outoff += n;
5014 err = add_line_metadata(lines, nlines, outoff,
5015 GOT_DIFF_LINE_CHANGES);
5016 if (err)
5017 goto done;
5020 fputc('\n', outfile);
5021 outoff++;
5022 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5023 if (err)
5024 goto done;
5026 n = fprintf(outfile,
5027 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5028 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5029 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5030 if (n < 0) {
5031 err = got_error_from_errno("fprintf");
5032 goto done;
5034 outoff += n;
5035 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5036 if (err)
5037 goto done;
5039 fputc('\n', outfile);
5040 outoff++;
5041 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5042 done:
5043 free(id_str);
5044 free(logmsg);
5045 free(refs_str);
5046 got_object_commit_close(commit);
5047 if (err) {
5048 free(*lines);
5049 *lines = NULL;
5050 *nlines = 0;
5052 return err;
5055 static const struct got_error *
5056 create_diff(struct tog_diff_view_state *s)
5058 const struct got_error *err = NULL;
5059 FILE *f = NULL, *tmp_diff_file = NULL;
5060 int obj_type;
5061 struct got_diff_line *lines = NULL;
5062 struct got_pathlist_head changed_paths;
5064 TAILQ_INIT(&changed_paths);
5066 free(s->lines);
5067 s->lines = malloc(sizeof(*s->lines));
5068 if (s->lines == NULL)
5069 return got_error_from_errno("malloc");
5070 s->nlines = 0;
5072 f = got_opentemp();
5073 if (f == NULL) {
5074 err = got_error_from_errno("got_opentemp");
5075 goto done;
5077 tmp_diff_file = got_opentemp();
5078 if (tmp_diff_file == NULL) {
5079 err = got_error_from_errno("got_opentemp");
5080 goto done;
5082 if (s->f && fclose(s->f) == EOF) {
5083 err = got_error_from_errno("fclose");
5084 goto done;
5086 s->f = f;
5088 if (s->id1)
5089 err = got_object_get_type(&obj_type, s->repo, s->id1);
5090 else
5091 err = got_object_get_type(&obj_type, s->repo, s->id2);
5092 if (err)
5093 goto done;
5095 switch (obj_type) {
5096 case GOT_OBJ_TYPE_BLOB:
5097 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5098 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5099 s->label1, s->label2, tog_diff_algo, s->diff_context,
5100 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5101 s->f);
5102 break;
5103 case GOT_OBJ_TYPE_TREE:
5104 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5105 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5106 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5107 s->force_text_diff, NULL, s->repo, s->f);
5108 break;
5109 case GOT_OBJ_TYPE_COMMIT: {
5110 const struct got_object_id_queue *parent_ids;
5111 struct got_object_qid *pid;
5112 struct got_commit_object *commit2;
5113 struct got_reflist_head *refs;
5114 size_t nlines = 0;
5115 struct got_diffstat_cb_arg dsa = {
5116 0, 0, 0, 0, 0, 0,
5117 &changed_paths,
5118 s->ignore_whitespace,
5119 s->force_text_diff,
5120 tog_diff_algo
5123 lines = malloc(sizeof(*lines));
5124 if (lines == NULL) {
5125 err = got_error_from_errno("malloc");
5126 goto done;
5129 /* build diff first in tmp file then append to commit info */
5130 err = got_diff_objects_as_commits(&lines, &nlines,
5131 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5132 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5133 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5134 if (err)
5135 break;
5137 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5138 if (err)
5139 goto done;
5140 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5141 /* Show commit info if we're diffing to a parent/root commit. */
5142 if (s->id1 == NULL) {
5143 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5144 refs, s->repo, s->ignore_whitespace,
5145 s->force_text_diff, &dsa, s->f);
5146 if (err)
5147 goto done;
5148 } else {
5149 parent_ids = got_object_commit_get_parent_ids(commit2);
5150 STAILQ_FOREACH(pid, parent_ids, entry) {
5151 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5152 err = write_commit_info(&s->lines,
5153 &s->nlines, s->id2, refs, s->repo,
5154 s->ignore_whitespace,
5155 s->force_text_diff, &dsa, s->f);
5156 if (err)
5157 goto done;
5158 break;
5162 got_object_commit_close(commit2);
5164 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5165 lines, nlines);
5166 break;
5168 default:
5169 err = got_error(GOT_ERR_OBJ_TYPE);
5170 break;
5172 done:
5173 free(lines);
5174 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5175 if (s->f && fflush(s->f) != 0 && err == NULL)
5176 err = got_error_from_errno("fflush");
5177 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5178 err = got_error_from_errno("fclose");
5179 return err;
5182 static void
5183 diff_view_indicate_progress(struct tog_view *view)
5185 mvwaddstr(view->window, 0, 0, "diffing...");
5186 update_panels();
5187 doupdate();
5190 static const struct got_error *
5191 search_start_diff_view(struct tog_view *view)
5193 struct tog_diff_view_state *s = &view->state.diff;
5195 s->matched_line = 0;
5196 return NULL;
5199 static void
5200 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5201 size_t *nlines, int **first, int **last, int **match, int **selected)
5203 struct tog_diff_view_state *s = &view->state.diff;
5205 *f = s->f;
5206 *nlines = s->nlines;
5207 *line_offsets = NULL;
5208 *match = &s->matched_line;
5209 *first = &s->first_displayed_line;
5210 *last = &s->last_displayed_line;
5211 *selected = &s->selected_line;
5214 static const struct got_error *
5215 search_next_view_match(struct tog_view *view)
5217 const struct got_error *err = NULL;
5218 FILE *f;
5219 int lineno;
5220 char *line = NULL;
5221 size_t linesize = 0;
5222 ssize_t linelen;
5223 off_t *line_offsets;
5224 size_t nlines = 0;
5225 int *first, *last, *match, *selected;
5227 if (!view->search_setup)
5228 return got_error_msg(GOT_ERR_NOT_IMPL,
5229 "view search not supported");
5230 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5231 &match, &selected);
5233 if (!view->searching) {
5234 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5235 return NULL;
5238 if (*match) {
5239 if (view->searching == TOG_SEARCH_FORWARD)
5240 lineno = *first + 1;
5241 else
5242 lineno = *first - 1;
5243 } else
5244 lineno = *first - 1 + *selected;
5246 while (1) {
5247 off_t offset;
5249 if (lineno <= 0 || lineno > nlines) {
5250 if (*match == 0) {
5251 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5252 break;
5255 if (view->searching == TOG_SEARCH_FORWARD)
5256 lineno = 1;
5257 else
5258 lineno = nlines;
5261 offset = view->type == TOG_VIEW_DIFF ?
5262 view->state.diff.lines[lineno - 1].offset :
5263 line_offsets[lineno - 1];
5264 if (fseeko(f, offset, SEEK_SET) != 0) {
5265 free(line);
5266 return got_error_from_errno("fseeko");
5268 linelen = getline(&line, &linesize, f);
5269 if (linelen != -1) {
5270 char *exstr;
5271 err = expand_tab(&exstr, line);
5272 if (err)
5273 break;
5274 if (match_line(exstr, &view->regex, 1,
5275 &view->regmatch)) {
5276 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5277 *match = lineno;
5278 free(exstr);
5279 break;
5281 free(exstr);
5283 if (view->searching == TOG_SEARCH_FORWARD)
5284 lineno++;
5285 else
5286 lineno--;
5288 free(line);
5290 if (*match) {
5291 *first = *match;
5292 *selected = 1;
5295 return err;
5298 static const struct got_error *
5299 close_diff_view(struct tog_view *view)
5301 const struct got_error *err = NULL;
5302 struct tog_diff_view_state *s = &view->state.diff;
5304 free(s->id1);
5305 s->id1 = NULL;
5306 free(s->id2);
5307 s->id2 = NULL;
5308 if (s->f && fclose(s->f) == EOF)
5309 err = got_error_from_errno("fclose");
5310 s->f = NULL;
5311 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5312 err = got_error_from_errno("fclose");
5313 s->f1 = NULL;
5314 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5315 err = got_error_from_errno("fclose");
5316 s->f2 = NULL;
5317 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5318 err = got_error_from_errno("close");
5319 s->fd1 = -1;
5320 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5321 err = got_error_from_errno("close");
5322 s->fd2 = -1;
5323 free(s->lines);
5324 s->lines = NULL;
5325 s->nlines = 0;
5326 return err;
5329 static const struct got_error *
5330 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5331 struct got_object_id *id2, const char *label1, const char *label2,
5332 int diff_context, int ignore_whitespace, int force_text_diff,
5333 struct tog_view *parent_view, struct got_repository *repo)
5335 const struct got_error *err;
5336 struct tog_diff_view_state *s = &view->state.diff;
5338 memset(s, 0, sizeof(*s));
5339 s->fd1 = -1;
5340 s->fd2 = -1;
5342 if (id1 != NULL && id2 != NULL) {
5343 int type1, type2;
5345 err = got_object_get_type(&type1, repo, id1);
5346 if (err)
5347 goto done;
5348 err = got_object_get_type(&type2, repo, id2);
5349 if (err)
5350 goto done;
5352 if (type1 != type2) {
5353 err = got_error(GOT_ERR_OBJ_TYPE);
5354 goto done;
5357 s->first_displayed_line = 1;
5358 s->last_displayed_line = view->nlines;
5359 s->selected_line = 1;
5360 s->repo = repo;
5361 s->id1 = id1;
5362 s->id2 = id2;
5363 s->label1 = label1;
5364 s->label2 = label2;
5366 if (id1) {
5367 s->id1 = got_object_id_dup(id1);
5368 if (s->id1 == NULL) {
5369 err = got_error_from_errno("got_object_id_dup");
5370 goto done;
5372 } else
5373 s->id1 = NULL;
5375 s->id2 = got_object_id_dup(id2);
5376 if (s->id2 == NULL) {
5377 err = got_error_from_errno("got_object_id_dup");
5378 goto done;
5381 s->f1 = got_opentemp();
5382 if (s->f1 == NULL) {
5383 err = got_error_from_errno("got_opentemp");
5384 goto done;
5387 s->f2 = got_opentemp();
5388 if (s->f2 == NULL) {
5389 err = got_error_from_errno("got_opentemp");
5390 goto done;
5393 s->fd1 = got_opentempfd();
5394 if (s->fd1 == -1) {
5395 err = got_error_from_errno("got_opentempfd");
5396 goto done;
5399 s->fd2 = got_opentempfd();
5400 if (s->fd2 == -1) {
5401 err = got_error_from_errno("got_opentempfd");
5402 goto done;
5405 s->diff_context = diff_context;
5406 s->ignore_whitespace = ignore_whitespace;
5407 s->force_text_diff = force_text_diff;
5408 s->parent_view = parent_view;
5409 s->repo = repo;
5411 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5412 int rc;
5414 rc = init_pair(GOT_DIFF_LINE_MINUS,
5415 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5416 if (rc != ERR)
5417 rc = init_pair(GOT_DIFF_LINE_PLUS,
5418 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5419 if (rc != ERR)
5420 rc = init_pair(GOT_DIFF_LINE_HUNK,
5421 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5422 if (rc != ERR)
5423 rc = init_pair(GOT_DIFF_LINE_META,
5424 get_color_value("TOG_COLOR_DIFF_META"), -1);
5425 if (rc != ERR)
5426 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5427 get_color_value("TOG_COLOR_DIFF_META"), -1);
5428 if (rc != ERR)
5429 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5430 get_color_value("TOG_COLOR_DIFF_META"), -1);
5431 if (rc != ERR)
5432 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5433 get_color_value("TOG_COLOR_DIFF_META"), -1);
5434 if (rc != ERR)
5435 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5436 get_color_value("TOG_COLOR_AUTHOR"), -1);
5437 if (rc != ERR)
5438 rc = init_pair(GOT_DIFF_LINE_DATE,
5439 get_color_value("TOG_COLOR_DATE"), -1);
5440 if (rc == ERR) {
5441 err = got_error(GOT_ERR_RANGE);
5442 goto done;
5446 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5447 view_is_splitscreen(view))
5448 show_log_view(parent_view); /* draw border */
5449 diff_view_indicate_progress(view);
5451 err = create_diff(s);
5453 view->show = show_diff_view;
5454 view->input = input_diff_view;
5455 view->reset = reset_diff_view;
5456 view->close = close_diff_view;
5457 view->search_start = search_start_diff_view;
5458 view->search_setup = search_setup_diff_view;
5459 view->search_next = search_next_view_match;
5460 done:
5461 if (err) {
5462 if (view->close == NULL)
5463 close_diff_view(view);
5464 view_close(view);
5466 return err;
5469 static const struct got_error *
5470 show_diff_view(struct tog_view *view)
5472 const struct got_error *err;
5473 struct tog_diff_view_state *s = &view->state.diff;
5474 char *id_str1 = NULL, *id_str2, *header;
5475 const char *label1, *label2;
5477 if (s->id1) {
5478 err = got_object_id_str(&id_str1, s->id1);
5479 if (err)
5480 return err;
5481 label1 = s->label1 ? s->label1 : id_str1;
5482 } else
5483 label1 = "/dev/null";
5485 err = got_object_id_str(&id_str2, s->id2);
5486 if (err)
5487 return err;
5488 label2 = s->label2 ? s->label2 : id_str2;
5490 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5491 err = got_error_from_errno("asprintf");
5492 free(id_str1);
5493 free(id_str2);
5494 return err;
5496 free(id_str1);
5497 free(id_str2);
5499 err = draw_file(view, header);
5500 free(header);
5501 return err;
5504 static const struct got_error *
5505 set_selected_commit(struct tog_diff_view_state *s,
5506 struct commit_queue_entry *entry)
5508 const struct got_error *err;
5509 const struct got_object_id_queue *parent_ids;
5510 struct got_commit_object *selected_commit;
5511 struct got_object_qid *pid;
5513 free(s->id2);
5514 s->id2 = got_object_id_dup(entry->id);
5515 if (s->id2 == NULL)
5516 return got_error_from_errno("got_object_id_dup");
5518 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5519 if (err)
5520 return err;
5521 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5522 free(s->id1);
5523 pid = STAILQ_FIRST(parent_ids);
5524 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5525 got_object_commit_close(selected_commit);
5526 return NULL;
5529 static const struct got_error *
5530 reset_diff_view(struct tog_view *view)
5532 struct tog_diff_view_state *s = &view->state.diff;
5534 view->count = 0;
5535 wclear(view->window);
5536 s->first_displayed_line = 1;
5537 s->last_displayed_line = view->nlines;
5538 s->matched_line = 0;
5539 diff_view_indicate_progress(view);
5540 return create_diff(s);
5543 static void
5544 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5546 int start, i;
5548 i = start = s->first_displayed_line - 1;
5550 while (s->lines[i].type != type) {
5551 if (i == 0)
5552 i = s->nlines - 1;
5553 if (--i == start)
5554 return; /* do nothing, requested type not in file */
5557 s->selected_line = 1;
5558 s->first_displayed_line = i;
5561 static void
5562 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5564 int start, i;
5566 i = start = s->first_displayed_line + 1;
5568 while (s->lines[i].type != type) {
5569 if (i == s->nlines - 1)
5570 i = 0;
5571 if (++i == start)
5572 return; /* do nothing, requested type not in file */
5575 s->selected_line = 1;
5576 s->first_displayed_line = i;
5579 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5580 int, int, int);
5581 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5582 int, int);
5584 static const struct got_error *
5585 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5587 const struct got_error *err = NULL;
5588 struct tog_diff_view_state *s = &view->state.diff;
5589 struct tog_log_view_state *ls;
5590 struct commit_queue_entry *old_selected_entry;
5591 char *line = NULL;
5592 size_t linesize = 0;
5593 ssize_t linelen;
5594 int i, nscroll = view->nlines - 1, up = 0;
5596 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5598 switch (ch) {
5599 case '0':
5600 case '$':
5601 case KEY_RIGHT:
5602 case 'l':
5603 case KEY_LEFT:
5604 case 'h':
5605 horizontal_scroll_input(view, ch);
5606 break;
5607 case 'a':
5608 case 'w':
5609 if (ch == 'a') {
5610 s->force_text_diff = !s->force_text_diff;
5611 view->action = s->force_text_diff ?
5612 "force ASCII text enabled" :
5613 "force ASCII text disabled";
5615 else if (ch == 'w') {
5616 s->ignore_whitespace = !s->ignore_whitespace;
5617 view->action = s->ignore_whitespace ?
5618 "ignore whitespace enabled" :
5619 "ignore whitespace disabled";
5621 err = reset_diff_view(view);
5622 break;
5623 case 'g':
5624 case KEY_HOME:
5625 s->first_displayed_line = 1;
5626 view->count = 0;
5627 break;
5628 case 'G':
5629 case KEY_END:
5630 view->count = 0;
5631 if (s->eof)
5632 break;
5634 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5635 s->eof = 1;
5636 break;
5637 case 'k':
5638 case KEY_UP:
5639 case CTRL('p'):
5640 if (s->first_displayed_line > 1)
5641 s->first_displayed_line--;
5642 else
5643 view->count = 0;
5644 break;
5645 case CTRL('u'):
5646 case 'u':
5647 nscroll /= 2;
5648 /* FALL THROUGH */
5649 case KEY_PPAGE:
5650 case CTRL('b'):
5651 case 'b':
5652 if (s->first_displayed_line == 1) {
5653 view->count = 0;
5654 break;
5656 i = 0;
5657 while (i++ < nscroll && s->first_displayed_line > 1)
5658 s->first_displayed_line--;
5659 break;
5660 case 'j':
5661 case KEY_DOWN:
5662 case CTRL('n'):
5663 if (!s->eof)
5664 s->first_displayed_line++;
5665 else
5666 view->count = 0;
5667 break;
5668 case CTRL('d'):
5669 case 'd':
5670 nscroll /= 2;
5671 /* FALL THROUGH */
5672 case KEY_NPAGE:
5673 case CTRL('f'):
5674 case 'f':
5675 case ' ':
5676 if (s->eof) {
5677 view->count = 0;
5678 break;
5680 i = 0;
5681 while (!s->eof && i++ < nscroll) {
5682 linelen = getline(&line, &linesize, s->f);
5683 s->first_displayed_line++;
5684 if (linelen == -1) {
5685 if (feof(s->f)) {
5686 s->eof = 1;
5687 } else
5688 err = got_ferror(s->f, GOT_ERR_IO);
5689 break;
5692 free(line);
5693 break;
5694 case '(':
5695 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5696 break;
5697 case ')':
5698 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5699 break;
5700 case '{':
5701 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5702 break;
5703 case '}':
5704 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5705 break;
5706 case '[':
5707 if (s->diff_context > 0) {
5708 s->diff_context--;
5709 s->matched_line = 0;
5710 diff_view_indicate_progress(view);
5711 err = create_diff(s);
5712 if (s->first_displayed_line + view->nlines - 1 >
5713 s->nlines) {
5714 s->first_displayed_line = 1;
5715 s->last_displayed_line = view->nlines;
5717 } else
5718 view->count = 0;
5719 break;
5720 case ']':
5721 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5722 s->diff_context++;
5723 s->matched_line = 0;
5724 diff_view_indicate_progress(view);
5725 err = create_diff(s);
5726 } else
5727 view->count = 0;
5728 break;
5729 case '<':
5730 case ',':
5731 case 'K':
5732 up = 1;
5733 /* FALL THROUGH */
5734 case '>':
5735 case '.':
5736 case 'J':
5737 if (s->parent_view == NULL) {
5738 view->count = 0;
5739 break;
5741 s->parent_view->count = view->count;
5743 if (s->parent_view->type == TOG_VIEW_LOG) {
5744 ls = &s->parent_view->state.log;
5745 old_selected_entry = ls->selected_entry;
5747 err = input_log_view(NULL, s->parent_view,
5748 up ? KEY_UP : KEY_DOWN);
5749 if (err)
5750 break;
5751 view->count = s->parent_view->count;
5753 if (old_selected_entry == ls->selected_entry)
5754 break;
5756 err = set_selected_commit(s, ls->selected_entry);
5757 if (err)
5758 break;
5759 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5760 struct tog_blame_view_state *bs;
5761 struct got_object_id *id, *prev_id;
5763 bs = &s->parent_view->state.blame;
5764 prev_id = get_annotation_for_line(bs->blame.lines,
5765 bs->blame.nlines, bs->last_diffed_line);
5767 err = input_blame_view(&view, s->parent_view,
5768 up ? KEY_UP : KEY_DOWN);
5769 if (err)
5770 break;
5771 view->count = s->parent_view->count;
5773 if (prev_id == NULL)
5774 break;
5775 id = get_selected_commit_id(bs->blame.lines,
5776 bs->blame.nlines, bs->first_displayed_line,
5777 bs->selected_line);
5778 if (id == NULL)
5779 break;
5781 if (!got_object_id_cmp(prev_id, id))
5782 break;
5784 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5785 if (err)
5786 break;
5788 s->first_displayed_line = 1;
5789 s->last_displayed_line = view->nlines;
5790 s->matched_line = 0;
5791 view->x = 0;
5793 diff_view_indicate_progress(view);
5794 err = create_diff(s);
5795 break;
5796 default:
5797 view->count = 0;
5798 break;
5801 return err;
5804 static const struct got_error *
5805 cmd_diff(int argc, char *argv[])
5807 const struct got_error *error;
5808 struct got_repository *repo = NULL;
5809 struct got_worktree *worktree = NULL;
5810 struct got_object_id *id1 = NULL, *id2 = NULL;
5811 char *repo_path = NULL, *cwd = NULL;
5812 char *id_str1 = NULL, *id_str2 = NULL;
5813 char *label1 = NULL, *label2 = NULL;
5814 int diff_context = 3, ignore_whitespace = 0;
5815 int ch, force_text_diff = 0;
5816 const char *errstr;
5817 struct tog_view *view;
5818 int *pack_fds = NULL;
5820 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5821 switch (ch) {
5822 case 'a':
5823 force_text_diff = 1;
5824 break;
5825 case 'C':
5826 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5827 &errstr);
5828 if (errstr != NULL)
5829 errx(1, "number of context lines is %s: %s",
5830 errstr, errstr);
5831 break;
5832 case 'r':
5833 repo_path = realpath(optarg, NULL);
5834 if (repo_path == NULL)
5835 return got_error_from_errno2("realpath",
5836 optarg);
5837 got_path_strip_trailing_slashes(repo_path);
5838 break;
5839 case 'w':
5840 ignore_whitespace = 1;
5841 break;
5842 default:
5843 usage_diff();
5844 /* NOTREACHED */
5848 argc -= optind;
5849 argv += optind;
5851 if (argc == 0) {
5852 usage_diff(); /* TODO show local worktree changes */
5853 } else if (argc == 2) {
5854 id_str1 = argv[0];
5855 id_str2 = argv[1];
5856 } else
5857 usage_diff();
5859 error = got_repo_pack_fds_open(&pack_fds);
5860 if (error)
5861 goto done;
5863 if (repo_path == NULL) {
5864 cwd = getcwd(NULL, 0);
5865 if (cwd == NULL)
5866 return got_error_from_errno("getcwd");
5867 error = got_worktree_open(&worktree, cwd);
5868 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5869 goto done;
5870 if (worktree)
5871 repo_path =
5872 strdup(got_worktree_get_repo_path(worktree));
5873 else
5874 repo_path = strdup(cwd);
5875 if (repo_path == NULL) {
5876 error = got_error_from_errno("strdup");
5877 goto done;
5881 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5882 if (error)
5883 goto done;
5885 init_curses();
5887 error = apply_unveil(got_repo_get_path(repo), NULL);
5888 if (error)
5889 goto done;
5891 error = tog_load_refs(repo, 0);
5892 if (error)
5893 goto done;
5895 error = got_repo_match_object_id(&id1, &label1, id_str1,
5896 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5897 if (error)
5898 goto done;
5900 error = got_repo_match_object_id(&id2, &label2, id_str2,
5901 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5902 if (error)
5903 goto done;
5905 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5906 if (view == NULL) {
5907 error = got_error_from_errno("view_open");
5908 goto done;
5910 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5911 ignore_whitespace, force_text_diff, NULL, repo);
5912 if (error)
5913 goto done;
5914 error = view_loop(view);
5915 done:
5916 free(label1);
5917 free(label2);
5918 free(repo_path);
5919 free(cwd);
5920 if (repo) {
5921 const struct got_error *close_err = got_repo_close(repo);
5922 if (error == NULL)
5923 error = close_err;
5925 if (worktree)
5926 got_worktree_close(worktree);
5927 if (pack_fds) {
5928 const struct got_error *pack_err =
5929 got_repo_pack_fds_close(pack_fds);
5930 if (error == NULL)
5931 error = pack_err;
5933 tog_free_refs();
5934 return error;
5937 __dead static void
5938 usage_blame(void)
5940 endwin();
5941 fprintf(stderr,
5942 "usage: %s blame [-c commit] [-r repository-path] path\n",
5943 getprogname());
5944 exit(1);
5947 struct tog_blame_line {
5948 int annotated;
5949 struct got_object_id *id;
5952 static const struct got_error *
5953 draw_blame(struct tog_view *view)
5955 struct tog_blame_view_state *s = &view->state.blame;
5956 struct tog_blame *blame = &s->blame;
5957 regmatch_t *regmatch = &view->regmatch;
5958 const struct got_error *err;
5959 int lineno = 0, nprinted = 0;
5960 char *line = NULL;
5961 size_t linesize = 0;
5962 ssize_t linelen;
5963 wchar_t *wline;
5964 int width;
5965 struct tog_blame_line *blame_line;
5966 struct got_object_id *prev_id = NULL;
5967 char *id_str;
5968 struct tog_color *tc;
5970 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5971 if (err)
5972 return err;
5974 rewind(blame->f);
5975 werase(view->window);
5977 if (asprintf(&line, "commit %s", id_str) == -1) {
5978 err = got_error_from_errno("asprintf");
5979 free(id_str);
5980 return err;
5983 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5984 free(line);
5985 line = NULL;
5986 if (err)
5987 return err;
5988 if (view_needs_focus_indication(view))
5989 wstandout(view->window);
5990 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5991 if (tc)
5992 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5993 waddwstr(view->window, wline);
5994 while (width++ < view->ncols)
5995 waddch(view->window, ' ');
5996 if (tc)
5997 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5998 if (view_needs_focus_indication(view))
5999 wstandend(view->window);
6000 free(wline);
6001 wline = NULL;
6003 if (view->gline > blame->nlines)
6004 view->gline = blame->nlines;
6006 if (tog_io.wait_for_ui) {
6007 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6008 int rc;
6010 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6011 if (rc)
6012 return got_error_set_errno(rc, "pthread_cond_wait");
6013 tog_io.wait_for_ui = 0;
6016 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6017 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6018 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6019 free(id_str);
6020 return got_error_from_errno("asprintf");
6022 free(id_str);
6023 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6024 free(line);
6025 line = NULL;
6026 if (err)
6027 return err;
6028 waddwstr(view->window, wline);
6029 free(wline);
6030 wline = NULL;
6031 if (width < view->ncols - 1)
6032 waddch(view->window, '\n');
6034 s->eof = 0;
6035 view->maxx = 0;
6036 while (nprinted < view->nlines - 2) {
6037 linelen = getline(&line, &linesize, blame->f);
6038 if (linelen == -1) {
6039 if (feof(blame->f)) {
6040 s->eof = 1;
6041 break;
6043 free(line);
6044 return got_ferror(blame->f, GOT_ERR_IO);
6046 if (++lineno < s->first_displayed_line)
6047 continue;
6048 if (view->gline && !gotoline(view, &lineno, &nprinted))
6049 continue;
6051 /* Set view->maxx based on full line length. */
6052 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6053 if (err) {
6054 free(line);
6055 return err;
6057 free(wline);
6058 wline = NULL;
6059 view->maxx = MAX(view->maxx, width);
6061 if (nprinted == s->selected_line - 1)
6062 wstandout(view->window);
6064 if (blame->nlines > 0) {
6065 blame_line = &blame->lines[lineno - 1];
6066 if (blame_line->annotated && prev_id &&
6067 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6068 !(nprinted == s->selected_line - 1)) {
6069 waddstr(view->window, " ");
6070 } else if (blame_line->annotated) {
6071 char *id_str;
6072 err = got_object_id_str(&id_str,
6073 blame_line->id);
6074 if (err) {
6075 free(line);
6076 return err;
6078 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6079 if (tc)
6080 wattr_on(view->window,
6081 COLOR_PAIR(tc->colorpair), NULL);
6082 wprintw(view->window, "%.8s", id_str);
6083 if (tc)
6084 wattr_off(view->window,
6085 COLOR_PAIR(tc->colorpair), NULL);
6086 free(id_str);
6087 prev_id = blame_line->id;
6088 } else {
6089 waddstr(view->window, "........");
6090 prev_id = NULL;
6092 } else {
6093 waddstr(view->window, "........");
6094 prev_id = NULL;
6097 if (nprinted == s->selected_line - 1)
6098 wstandend(view->window);
6099 waddstr(view->window, " ");
6101 if (view->ncols <= 9) {
6102 width = 9;
6103 } else if (s->first_displayed_line + nprinted ==
6104 s->matched_line &&
6105 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6106 err = add_matched_line(&width, line, view->ncols - 9, 9,
6107 view->window, view->x, regmatch);
6108 if (err) {
6109 free(line);
6110 return err;
6112 width += 9;
6113 } else {
6114 int skip;
6115 err = format_line(&wline, &width, &skip, line,
6116 view->x, view->ncols - 9, 9, 1);
6117 if (err) {
6118 free(line);
6119 return err;
6121 waddwstr(view->window, &wline[skip]);
6122 width += 9;
6123 free(wline);
6124 wline = NULL;
6127 if (width <= view->ncols - 1)
6128 waddch(view->window, '\n');
6129 if (++nprinted == 1)
6130 s->first_displayed_line = lineno;
6132 free(line);
6133 s->last_displayed_line = lineno;
6135 view_border(view);
6137 return NULL;
6140 static const struct got_error *
6141 blame_cb(void *arg, int nlines, int lineno,
6142 struct got_commit_object *commit, struct got_object_id *id)
6144 const struct got_error *err = NULL;
6145 struct tog_blame_cb_args *a = arg;
6146 struct tog_blame_line *line;
6147 int errcode;
6149 if (nlines != a->nlines ||
6150 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6151 return got_error(GOT_ERR_RANGE);
6153 errcode = pthread_mutex_lock(&tog_mutex);
6154 if (errcode)
6155 return got_error_set_errno(errcode, "pthread_mutex_lock");
6157 if (*a->quit) { /* user has quit the blame view */
6158 err = got_error(GOT_ERR_ITER_COMPLETED);
6159 goto done;
6162 if (lineno == -1)
6163 goto done; /* no change in this commit */
6165 line = &a->lines[lineno - 1];
6166 if (line->annotated)
6167 goto done;
6169 line->id = got_object_id_dup(id);
6170 if (line->id == NULL) {
6171 err = got_error_from_errno("got_object_id_dup");
6172 goto done;
6174 line->annotated = 1;
6175 done:
6176 errcode = pthread_mutex_unlock(&tog_mutex);
6177 if (errcode)
6178 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6179 return err;
6182 static void *
6183 blame_thread(void *arg)
6185 const struct got_error *err, *close_err;
6186 struct tog_blame_thread_args *ta = arg;
6187 struct tog_blame_cb_args *a = ta->cb_args;
6188 int errcode, fd1 = -1, fd2 = -1;
6189 FILE *f1 = NULL, *f2 = NULL;
6191 fd1 = got_opentempfd();
6192 if (fd1 == -1)
6193 return (void *)got_error_from_errno("got_opentempfd");
6195 fd2 = got_opentempfd();
6196 if (fd2 == -1) {
6197 err = got_error_from_errno("got_opentempfd");
6198 goto done;
6201 f1 = got_opentemp();
6202 if (f1 == NULL) {
6203 err = (void *)got_error_from_errno("got_opentemp");
6204 goto done;
6206 f2 = got_opentemp();
6207 if (f2 == NULL) {
6208 err = (void *)got_error_from_errno("got_opentemp");
6209 goto done;
6212 err = block_signals_used_by_main_thread();
6213 if (err)
6214 goto done;
6216 err = got_blame(ta->path, a->commit_id, ta->repo,
6217 tog_diff_algo, blame_cb, ta->cb_args,
6218 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6219 if (err && err->code == GOT_ERR_CANCELLED)
6220 err = NULL;
6222 errcode = pthread_mutex_lock(&tog_mutex);
6223 if (errcode) {
6224 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6225 goto done;
6228 close_err = got_repo_close(ta->repo);
6229 if (err == NULL)
6230 err = close_err;
6231 ta->repo = NULL;
6232 *ta->complete = 1;
6234 if (tog_io.wait_for_ui) {
6235 errcode = pthread_cond_signal(&ta->blame_complete);
6236 if (errcode && err == NULL)
6237 err = got_error_set_errno(errcode,
6238 "pthread_cond_signal");
6241 errcode = pthread_mutex_unlock(&tog_mutex);
6242 if (errcode && err == NULL)
6243 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6245 done:
6246 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6247 err = got_error_from_errno("close");
6248 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6249 err = got_error_from_errno("close");
6250 if (f1 && fclose(f1) == EOF && err == NULL)
6251 err = got_error_from_errno("fclose");
6252 if (f2 && fclose(f2) == EOF && err == NULL)
6253 err = got_error_from_errno("fclose");
6255 return (void *)err;
6258 static struct got_object_id *
6259 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6260 int first_displayed_line, int selected_line)
6262 struct tog_blame_line *line;
6264 if (nlines <= 0)
6265 return NULL;
6267 line = &lines[first_displayed_line - 1 + selected_line - 1];
6268 if (!line->annotated)
6269 return NULL;
6271 return line->id;
6274 static struct got_object_id *
6275 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6276 int lineno)
6278 struct tog_blame_line *line;
6280 if (nlines <= 0 || lineno >= nlines)
6281 return NULL;
6283 line = &lines[lineno - 1];
6284 if (!line->annotated)
6285 return NULL;
6287 return line->id;
6290 static const struct got_error *
6291 stop_blame(struct tog_blame *blame)
6293 const struct got_error *err = NULL;
6294 int i;
6296 if (blame->thread) {
6297 int errcode;
6298 errcode = pthread_mutex_unlock(&tog_mutex);
6299 if (errcode)
6300 return got_error_set_errno(errcode,
6301 "pthread_mutex_unlock");
6302 errcode = pthread_join(blame->thread, (void **)&err);
6303 if (errcode)
6304 return got_error_set_errno(errcode, "pthread_join");
6305 errcode = pthread_mutex_lock(&tog_mutex);
6306 if (errcode)
6307 return got_error_set_errno(errcode,
6308 "pthread_mutex_lock");
6309 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6310 err = NULL;
6311 blame->thread = 0; //NULL;
6313 if (blame->thread_args.repo) {
6314 const struct got_error *close_err;
6315 close_err = got_repo_close(blame->thread_args.repo);
6316 if (err == NULL)
6317 err = close_err;
6318 blame->thread_args.repo = NULL;
6320 if (blame->f) {
6321 if (fclose(blame->f) == EOF && err == NULL)
6322 err = got_error_from_errno("fclose");
6323 blame->f = NULL;
6325 if (blame->lines) {
6326 for (i = 0; i < blame->nlines; i++)
6327 free(blame->lines[i].id);
6328 free(blame->lines);
6329 blame->lines = NULL;
6331 free(blame->cb_args.commit_id);
6332 blame->cb_args.commit_id = NULL;
6333 if (blame->pack_fds) {
6334 const struct got_error *pack_err =
6335 got_repo_pack_fds_close(blame->pack_fds);
6336 if (err == NULL)
6337 err = pack_err;
6338 blame->pack_fds = NULL;
6340 return err;
6343 static const struct got_error *
6344 cancel_blame_view(void *arg)
6346 const struct got_error *err = NULL;
6347 int *done = arg;
6348 int errcode;
6350 errcode = pthread_mutex_lock(&tog_mutex);
6351 if (errcode)
6352 return got_error_set_errno(errcode,
6353 "pthread_mutex_unlock");
6355 if (*done)
6356 err = got_error(GOT_ERR_CANCELLED);
6358 errcode = pthread_mutex_unlock(&tog_mutex);
6359 if (errcode)
6360 return got_error_set_errno(errcode,
6361 "pthread_mutex_lock");
6363 return err;
6366 static const struct got_error *
6367 run_blame(struct tog_view *view)
6369 struct tog_blame_view_state *s = &view->state.blame;
6370 struct tog_blame *blame = &s->blame;
6371 const struct got_error *err = NULL;
6372 struct got_commit_object *commit = NULL;
6373 struct got_blob_object *blob = NULL;
6374 struct got_repository *thread_repo = NULL;
6375 struct got_object_id *obj_id = NULL;
6376 int obj_type, fd = -1;
6377 int *pack_fds = NULL;
6379 err = got_object_open_as_commit(&commit, s->repo,
6380 &s->blamed_commit->id);
6381 if (err)
6382 return err;
6384 fd = got_opentempfd();
6385 if (fd == -1) {
6386 err = got_error_from_errno("got_opentempfd");
6387 goto done;
6390 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6391 if (err)
6392 goto done;
6394 err = got_object_get_type(&obj_type, s->repo, obj_id);
6395 if (err)
6396 goto done;
6398 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6399 err = got_error(GOT_ERR_OBJ_TYPE);
6400 goto done;
6403 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6404 if (err)
6405 goto done;
6406 blame->f = got_opentemp();
6407 if (blame->f == NULL) {
6408 err = got_error_from_errno("got_opentemp");
6409 goto done;
6411 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6412 &blame->line_offsets, blame->f, blob);
6413 if (err)
6414 goto done;
6415 if (blame->nlines == 0) {
6416 s->blame_complete = 1;
6417 goto done;
6420 /* Don't include \n at EOF in the blame line count. */
6421 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6422 blame->nlines--;
6424 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6425 if (blame->lines == NULL) {
6426 err = got_error_from_errno("calloc");
6427 goto done;
6430 err = got_repo_pack_fds_open(&pack_fds);
6431 if (err)
6432 goto done;
6433 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6434 pack_fds);
6435 if (err)
6436 goto done;
6438 blame->pack_fds = pack_fds;
6439 blame->cb_args.view = view;
6440 blame->cb_args.lines = blame->lines;
6441 blame->cb_args.nlines = blame->nlines;
6442 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6443 if (blame->cb_args.commit_id == NULL) {
6444 err = got_error_from_errno("got_object_id_dup");
6445 goto done;
6447 blame->cb_args.quit = &s->done;
6449 blame->thread_args.path = s->path;
6450 blame->thread_args.repo = thread_repo;
6451 blame->thread_args.cb_args = &blame->cb_args;
6452 blame->thread_args.complete = &s->blame_complete;
6453 blame->thread_args.cancel_cb = cancel_blame_view;
6454 blame->thread_args.cancel_arg = &s->done;
6455 s->blame_complete = 0;
6457 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6458 s->first_displayed_line = 1;
6459 s->last_displayed_line = view->nlines;
6460 s->selected_line = 1;
6462 s->matched_line = 0;
6464 done:
6465 if (commit)
6466 got_object_commit_close(commit);
6467 if (fd != -1 && close(fd) == -1 && err == NULL)
6468 err = got_error_from_errno("close");
6469 if (blob)
6470 got_object_blob_close(blob);
6471 free(obj_id);
6472 if (err)
6473 stop_blame(blame);
6474 return err;
6477 static const struct got_error *
6478 open_blame_view(struct tog_view *view, char *path,
6479 struct got_object_id *commit_id, struct got_repository *repo)
6481 const struct got_error *err = NULL;
6482 struct tog_blame_view_state *s = &view->state.blame;
6484 STAILQ_INIT(&s->blamed_commits);
6486 s->path = strdup(path);
6487 if (s->path == NULL)
6488 return got_error_from_errno("strdup");
6490 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6491 if (err) {
6492 free(s->path);
6493 return err;
6496 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6497 s->first_displayed_line = 1;
6498 s->last_displayed_line = view->nlines;
6499 s->selected_line = 1;
6500 s->blame_complete = 0;
6501 s->repo = repo;
6502 s->commit_id = commit_id;
6503 memset(&s->blame, 0, sizeof(s->blame));
6505 STAILQ_INIT(&s->colors);
6506 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6507 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6508 get_color_value("TOG_COLOR_COMMIT"));
6509 if (err)
6510 return err;
6513 view->show = show_blame_view;
6514 view->input = input_blame_view;
6515 view->reset = reset_blame_view;
6516 view->close = close_blame_view;
6517 view->search_start = search_start_blame_view;
6518 view->search_setup = search_setup_blame_view;
6519 view->search_next = search_next_view_match;
6521 if (using_mock_io) {
6522 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6523 int rc;
6525 rc = pthread_cond_init(&bta->blame_complete, NULL);
6526 if (rc)
6527 return got_error_set_errno(rc, "pthread_cond_init");
6530 return run_blame(view);
6533 static const struct got_error *
6534 close_blame_view(struct tog_view *view)
6536 const struct got_error *err = NULL;
6537 struct tog_blame_view_state *s = &view->state.blame;
6539 if (s->blame.thread)
6540 err = stop_blame(&s->blame);
6542 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6543 struct got_object_qid *blamed_commit;
6544 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6545 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6546 got_object_qid_free(blamed_commit);
6549 if (using_mock_io) {
6550 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6551 int rc;
6553 rc = pthread_cond_destroy(&bta->blame_complete);
6554 if (rc && err == NULL)
6555 err = got_error_set_errno(rc, "pthread_cond_destroy");
6558 free(s->path);
6559 free_colors(&s->colors);
6560 return err;
6563 static const struct got_error *
6564 search_start_blame_view(struct tog_view *view)
6566 struct tog_blame_view_state *s = &view->state.blame;
6568 s->matched_line = 0;
6569 return NULL;
6572 static void
6573 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6574 size_t *nlines, int **first, int **last, int **match, int **selected)
6576 struct tog_blame_view_state *s = &view->state.blame;
6578 *f = s->blame.f;
6579 *nlines = s->blame.nlines;
6580 *line_offsets = s->blame.line_offsets;
6581 *match = &s->matched_line;
6582 *first = &s->first_displayed_line;
6583 *last = &s->last_displayed_line;
6584 *selected = &s->selected_line;
6587 static const struct got_error *
6588 show_blame_view(struct tog_view *view)
6590 const struct got_error *err = NULL;
6591 struct tog_blame_view_state *s = &view->state.blame;
6592 int errcode;
6594 if (s->blame.thread == 0 && !s->blame_complete) {
6595 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6596 &s->blame.thread_args);
6597 if (errcode)
6598 return got_error_set_errno(errcode, "pthread_create");
6600 if (!using_mock_io)
6601 halfdelay(1); /* fast refresh while annotating */
6604 if (s->blame_complete && !using_mock_io)
6605 halfdelay(10); /* disable fast refresh */
6607 err = draw_blame(view);
6609 view_border(view);
6610 return err;
6613 static const struct got_error *
6614 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6615 struct got_repository *repo, struct got_object_id *id)
6617 struct tog_view *log_view;
6618 const struct got_error *err = NULL;
6620 *new_view = NULL;
6622 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6623 if (log_view == NULL)
6624 return got_error_from_errno("view_open");
6626 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6627 if (err)
6628 view_close(log_view);
6629 else
6630 *new_view = log_view;
6632 return err;
6635 static const struct got_error *
6636 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6638 const struct got_error *err = NULL, *thread_err = NULL;
6639 struct tog_view *diff_view;
6640 struct tog_blame_view_state *s = &view->state.blame;
6641 int eos, nscroll, begin_y = 0, begin_x = 0;
6643 eos = nscroll = view->nlines - 2;
6644 if (view_is_hsplit_top(view))
6645 --eos; /* border */
6647 switch (ch) {
6648 case '0':
6649 case '$':
6650 case KEY_RIGHT:
6651 case 'l':
6652 case KEY_LEFT:
6653 case 'h':
6654 horizontal_scroll_input(view, ch);
6655 break;
6656 case 'q':
6657 s->done = 1;
6658 break;
6659 case 'g':
6660 case KEY_HOME:
6661 s->selected_line = 1;
6662 s->first_displayed_line = 1;
6663 view->count = 0;
6664 break;
6665 case 'G':
6666 case KEY_END:
6667 if (s->blame.nlines < eos) {
6668 s->selected_line = s->blame.nlines;
6669 s->first_displayed_line = 1;
6670 } else {
6671 s->selected_line = eos;
6672 s->first_displayed_line = s->blame.nlines - (eos - 1);
6674 view->count = 0;
6675 break;
6676 case 'k':
6677 case KEY_UP:
6678 case CTRL('p'):
6679 if (s->selected_line > 1)
6680 s->selected_line--;
6681 else if (s->selected_line == 1 &&
6682 s->first_displayed_line > 1)
6683 s->first_displayed_line--;
6684 else
6685 view->count = 0;
6686 break;
6687 case CTRL('u'):
6688 case 'u':
6689 nscroll /= 2;
6690 /* FALL THROUGH */
6691 case KEY_PPAGE:
6692 case CTRL('b'):
6693 case 'b':
6694 if (s->first_displayed_line == 1) {
6695 if (view->count > 1)
6696 nscroll += nscroll;
6697 s->selected_line = MAX(1, s->selected_line - nscroll);
6698 view->count = 0;
6699 break;
6701 if (s->first_displayed_line > nscroll)
6702 s->first_displayed_line -= nscroll;
6703 else
6704 s->first_displayed_line = 1;
6705 break;
6706 case 'j':
6707 case KEY_DOWN:
6708 case CTRL('n'):
6709 if (s->selected_line < eos && s->first_displayed_line +
6710 s->selected_line <= s->blame.nlines)
6711 s->selected_line++;
6712 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6713 s->first_displayed_line++;
6714 else
6715 view->count = 0;
6716 break;
6717 case 'c':
6718 case 'p': {
6719 struct got_object_id *id = NULL;
6721 view->count = 0;
6722 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6723 s->first_displayed_line, s->selected_line);
6724 if (id == NULL)
6725 break;
6726 if (ch == 'p') {
6727 struct got_commit_object *commit, *pcommit;
6728 struct got_object_qid *pid;
6729 struct got_object_id *blob_id = NULL;
6730 int obj_type;
6731 err = got_object_open_as_commit(&commit,
6732 s->repo, id);
6733 if (err)
6734 break;
6735 pid = STAILQ_FIRST(
6736 got_object_commit_get_parent_ids(commit));
6737 if (pid == NULL) {
6738 got_object_commit_close(commit);
6739 break;
6741 /* Check if path history ends here. */
6742 err = got_object_open_as_commit(&pcommit,
6743 s->repo, &pid->id);
6744 if (err)
6745 break;
6746 err = got_object_id_by_path(&blob_id, s->repo,
6747 pcommit, s->path);
6748 got_object_commit_close(pcommit);
6749 if (err) {
6750 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6751 err = NULL;
6752 got_object_commit_close(commit);
6753 break;
6755 err = got_object_get_type(&obj_type, s->repo,
6756 blob_id);
6757 free(blob_id);
6758 /* Can't blame non-blob type objects. */
6759 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6760 got_object_commit_close(commit);
6761 break;
6763 err = got_object_qid_alloc(&s->blamed_commit,
6764 &pid->id);
6765 got_object_commit_close(commit);
6766 } else {
6767 if (got_object_id_cmp(id,
6768 &s->blamed_commit->id) == 0)
6769 break;
6770 err = got_object_qid_alloc(&s->blamed_commit,
6771 id);
6773 if (err)
6774 break;
6775 s->done = 1;
6776 thread_err = stop_blame(&s->blame);
6777 s->done = 0;
6778 if (thread_err)
6779 break;
6780 STAILQ_INSERT_HEAD(&s->blamed_commits,
6781 s->blamed_commit, entry);
6782 err = run_blame(view);
6783 if (err)
6784 break;
6785 break;
6787 case 'C': {
6788 struct got_object_qid *first;
6790 view->count = 0;
6791 first = STAILQ_FIRST(&s->blamed_commits);
6792 if (!got_object_id_cmp(&first->id, s->commit_id))
6793 break;
6794 s->done = 1;
6795 thread_err = stop_blame(&s->blame);
6796 s->done = 0;
6797 if (thread_err)
6798 break;
6799 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6800 got_object_qid_free(s->blamed_commit);
6801 s->blamed_commit =
6802 STAILQ_FIRST(&s->blamed_commits);
6803 err = run_blame(view);
6804 if (err)
6805 break;
6806 break;
6808 case 'L':
6809 view->count = 0;
6810 s->id_to_log = get_selected_commit_id(s->blame.lines,
6811 s->blame.nlines, s->first_displayed_line, s->selected_line);
6812 if (s->id_to_log)
6813 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6814 break;
6815 case KEY_ENTER:
6816 case '\r': {
6817 struct got_object_id *id = NULL;
6818 struct got_object_qid *pid;
6819 struct got_commit_object *commit = NULL;
6821 view->count = 0;
6822 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6823 s->first_displayed_line, s->selected_line);
6824 if (id == NULL)
6825 break;
6826 err = got_object_open_as_commit(&commit, s->repo, id);
6827 if (err)
6828 break;
6829 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6830 if (*new_view) {
6831 /* traversed from diff view, release diff resources */
6832 err = close_diff_view(*new_view);
6833 if (err)
6834 break;
6835 diff_view = *new_view;
6836 } else {
6837 if (view_is_parent_view(view))
6838 view_get_split(view, &begin_y, &begin_x);
6840 diff_view = view_open(0, 0, begin_y, begin_x,
6841 TOG_VIEW_DIFF);
6842 if (diff_view == NULL) {
6843 got_object_commit_close(commit);
6844 err = got_error_from_errno("view_open");
6845 break;
6848 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6849 id, NULL, NULL, 3, 0, 0, view, s->repo);
6850 got_object_commit_close(commit);
6851 if (err) {
6852 view_close(diff_view);
6853 break;
6855 s->last_diffed_line = s->first_displayed_line - 1 +
6856 s->selected_line;
6857 if (*new_view)
6858 break; /* still open from active diff view */
6859 if (view_is_parent_view(view) &&
6860 view->mode == TOG_VIEW_SPLIT_HRZN) {
6861 err = view_init_hsplit(view, begin_y);
6862 if (err)
6863 break;
6866 view->focussed = 0;
6867 diff_view->focussed = 1;
6868 diff_view->mode = view->mode;
6869 diff_view->nlines = view->lines - begin_y;
6870 if (view_is_parent_view(view)) {
6871 view_transfer_size(diff_view, view);
6872 err = view_close_child(view);
6873 if (err)
6874 break;
6875 err = view_set_child(view, diff_view);
6876 if (err)
6877 break;
6878 view->focus_child = 1;
6879 } else
6880 *new_view = diff_view;
6881 if (err)
6882 break;
6883 break;
6885 case CTRL('d'):
6886 case 'd':
6887 nscroll /= 2;
6888 /* FALL THROUGH */
6889 case KEY_NPAGE:
6890 case CTRL('f'):
6891 case 'f':
6892 case ' ':
6893 if (s->last_displayed_line >= s->blame.nlines &&
6894 s->selected_line >= MIN(s->blame.nlines,
6895 view->nlines - 2)) {
6896 view->count = 0;
6897 break;
6899 if (s->last_displayed_line >= s->blame.nlines &&
6900 s->selected_line < view->nlines - 2) {
6901 s->selected_line +=
6902 MIN(nscroll, s->last_displayed_line -
6903 s->first_displayed_line - s->selected_line + 1);
6905 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6906 s->first_displayed_line += nscroll;
6907 else
6908 s->first_displayed_line =
6909 s->blame.nlines - (view->nlines - 3);
6910 break;
6911 case KEY_RESIZE:
6912 if (s->selected_line > view->nlines - 2) {
6913 s->selected_line = MIN(s->blame.nlines,
6914 view->nlines - 2);
6916 break;
6917 default:
6918 view->count = 0;
6919 break;
6921 return thread_err ? thread_err : err;
6924 static const struct got_error *
6925 reset_blame_view(struct tog_view *view)
6927 const struct got_error *err;
6928 struct tog_blame_view_state *s = &view->state.blame;
6930 view->count = 0;
6931 s->done = 1;
6932 err = stop_blame(&s->blame);
6933 s->done = 0;
6934 if (err)
6935 return err;
6936 return run_blame(view);
6939 static const struct got_error *
6940 cmd_blame(int argc, char *argv[])
6942 const struct got_error *error;
6943 struct got_repository *repo = NULL;
6944 struct got_worktree *worktree = NULL;
6945 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6946 char *link_target = NULL;
6947 struct got_object_id *commit_id = NULL;
6948 struct got_commit_object *commit = NULL;
6949 char *commit_id_str = NULL;
6950 int ch;
6951 struct tog_view *view = NULL;
6952 int *pack_fds = NULL;
6954 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6955 switch (ch) {
6956 case 'c':
6957 commit_id_str = optarg;
6958 break;
6959 case 'r':
6960 repo_path = realpath(optarg, NULL);
6961 if (repo_path == NULL)
6962 return got_error_from_errno2("realpath",
6963 optarg);
6964 break;
6965 default:
6966 usage_blame();
6967 /* NOTREACHED */
6971 argc -= optind;
6972 argv += optind;
6974 if (argc != 1)
6975 usage_blame();
6977 error = got_repo_pack_fds_open(&pack_fds);
6978 if (error != NULL)
6979 goto done;
6981 if (repo_path == NULL) {
6982 cwd = getcwd(NULL, 0);
6983 if (cwd == NULL)
6984 return got_error_from_errno("getcwd");
6985 error = got_worktree_open(&worktree, cwd);
6986 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6987 goto done;
6988 if (worktree)
6989 repo_path =
6990 strdup(got_worktree_get_repo_path(worktree));
6991 else
6992 repo_path = strdup(cwd);
6993 if (repo_path == NULL) {
6994 error = got_error_from_errno("strdup");
6995 goto done;
6999 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7000 if (error != NULL)
7001 goto done;
7003 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7004 worktree);
7005 if (error)
7006 goto done;
7008 init_curses();
7010 error = apply_unveil(got_repo_get_path(repo), NULL);
7011 if (error)
7012 goto done;
7014 error = tog_load_refs(repo, 0);
7015 if (error)
7016 goto done;
7018 if (commit_id_str == NULL) {
7019 struct got_reference *head_ref;
7020 error = got_ref_open(&head_ref, repo, worktree ?
7021 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7022 if (error != NULL)
7023 goto done;
7024 error = got_ref_resolve(&commit_id, repo, head_ref);
7025 got_ref_close(head_ref);
7026 } else {
7027 error = got_repo_match_object_id(&commit_id, NULL,
7028 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7030 if (error != NULL)
7031 goto done;
7033 error = got_object_open_as_commit(&commit, repo, commit_id);
7034 if (error)
7035 goto done;
7037 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7038 commit, repo);
7039 if (error)
7040 goto done;
7042 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7043 if (view == NULL) {
7044 error = got_error_from_errno("view_open");
7045 goto done;
7047 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7048 commit_id, repo);
7049 if (error != NULL) {
7050 if (view->close == NULL)
7051 close_blame_view(view);
7052 view_close(view);
7053 goto done;
7055 if (worktree) {
7056 /* Release work tree lock. */
7057 got_worktree_close(worktree);
7058 worktree = NULL;
7060 error = view_loop(view);
7061 done:
7062 free(repo_path);
7063 free(in_repo_path);
7064 free(link_target);
7065 free(cwd);
7066 free(commit_id);
7067 if (commit)
7068 got_object_commit_close(commit);
7069 if (worktree)
7070 got_worktree_close(worktree);
7071 if (repo) {
7072 const struct got_error *close_err = got_repo_close(repo);
7073 if (error == NULL)
7074 error = close_err;
7076 if (pack_fds) {
7077 const struct got_error *pack_err =
7078 got_repo_pack_fds_close(pack_fds);
7079 if (error == NULL)
7080 error = pack_err;
7082 tog_free_refs();
7083 return error;
7086 static const struct got_error *
7087 draw_tree_entries(struct tog_view *view, const char *parent_path)
7089 struct tog_tree_view_state *s = &view->state.tree;
7090 const struct got_error *err = NULL;
7091 struct got_tree_entry *te;
7092 wchar_t *wline;
7093 char *index = NULL;
7094 struct tog_color *tc;
7095 int width, n, nentries, scrollx, i = 1;
7096 int limit = view->nlines;
7098 s->ndisplayed = 0;
7099 if (view_is_hsplit_top(view))
7100 --limit; /* border */
7102 werase(view->window);
7104 if (limit == 0)
7105 return NULL;
7107 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7108 0, 0);
7109 if (err)
7110 return err;
7111 if (view_needs_focus_indication(view))
7112 wstandout(view->window);
7113 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7114 if (tc)
7115 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7116 waddwstr(view->window, wline);
7117 free(wline);
7118 wline = NULL;
7119 while (width++ < view->ncols)
7120 waddch(view->window, ' ');
7121 if (tc)
7122 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7123 if (view_needs_focus_indication(view))
7124 wstandend(view->window);
7125 if (--limit <= 0)
7126 return NULL;
7128 i += s->selected;
7129 if (s->first_displayed_entry) {
7130 i += got_tree_entry_get_index(s->first_displayed_entry);
7131 if (s->tree != s->root)
7132 ++i; /* account for ".." entry */
7134 nentries = got_object_tree_get_nentries(s->tree);
7135 if (asprintf(&index, "[%d/%d] %s",
7136 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7137 return got_error_from_errno("asprintf");
7138 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7139 free(index);
7140 if (err)
7141 return err;
7142 waddwstr(view->window, wline);
7143 free(wline);
7144 wline = NULL;
7145 if (width < view->ncols - 1)
7146 waddch(view->window, '\n');
7147 if (--limit <= 0)
7148 return NULL;
7149 waddch(view->window, '\n');
7150 if (--limit <= 0)
7151 return NULL;
7153 if (s->first_displayed_entry == NULL) {
7154 te = got_object_tree_get_first_entry(s->tree);
7155 if (s->selected == 0) {
7156 if (view->focussed)
7157 wstandout(view->window);
7158 s->selected_entry = NULL;
7160 waddstr(view->window, " ..\n"); /* parent directory */
7161 if (s->selected == 0 && view->focussed)
7162 wstandend(view->window);
7163 s->ndisplayed++;
7164 if (--limit <= 0)
7165 return NULL;
7166 n = 1;
7167 } else {
7168 n = 0;
7169 te = s->first_displayed_entry;
7172 view->maxx = 0;
7173 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7174 char *line = NULL, *id_str = NULL, *link_target = NULL;
7175 const char *modestr = "";
7176 mode_t mode;
7178 te = got_object_tree_get_entry(s->tree, i);
7179 mode = got_tree_entry_get_mode(te);
7181 if (s->show_ids) {
7182 err = got_object_id_str(&id_str,
7183 got_tree_entry_get_id(te));
7184 if (err)
7185 return got_error_from_errno(
7186 "got_object_id_str");
7188 if (got_object_tree_entry_is_submodule(te))
7189 modestr = "$";
7190 else if (S_ISLNK(mode)) {
7191 int i;
7193 err = got_tree_entry_get_symlink_target(&link_target,
7194 te, s->repo);
7195 if (err) {
7196 free(id_str);
7197 return err;
7199 for (i = 0; i < strlen(link_target); i++) {
7200 if (!isprint((unsigned char)link_target[i]))
7201 link_target[i] = '?';
7203 modestr = "@";
7205 else if (S_ISDIR(mode))
7206 modestr = "/";
7207 else if (mode & S_IXUSR)
7208 modestr = "*";
7209 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7210 got_tree_entry_get_name(te), modestr,
7211 link_target ? " -> ": "",
7212 link_target ? link_target : "") == -1) {
7213 free(id_str);
7214 free(link_target);
7215 return got_error_from_errno("asprintf");
7217 free(id_str);
7218 free(link_target);
7220 /* use full line width to determine view->maxx */
7221 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7222 if (err) {
7223 free(line);
7224 break;
7226 view->maxx = MAX(view->maxx, width);
7227 free(wline);
7228 wline = NULL;
7230 err = format_line(&wline, &width, &scrollx, line, view->x,
7231 view->ncols, 0, 0);
7232 if (err) {
7233 free(line);
7234 break;
7236 if (n == s->selected) {
7237 if (view->focussed)
7238 wstandout(view->window);
7239 s->selected_entry = te;
7241 tc = match_color(&s->colors, line);
7242 if (tc)
7243 wattr_on(view->window,
7244 COLOR_PAIR(tc->colorpair), NULL);
7245 waddwstr(view->window, &wline[scrollx]);
7246 if (tc)
7247 wattr_off(view->window,
7248 COLOR_PAIR(tc->colorpair), NULL);
7249 if (width < view->ncols)
7250 waddch(view->window, '\n');
7251 if (n == s->selected && view->focussed)
7252 wstandend(view->window);
7253 free(line);
7254 free(wline);
7255 wline = NULL;
7256 n++;
7257 s->ndisplayed++;
7258 s->last_displayed_entry = te;
7259 if (--limit <= 0)
7260 break;
7263 return err;
7266 static void
7267 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7269 struct got_tree_entry *te;
7270 int isroot = s->tree == s->root;
7271 int i = 0;
7273 if (s->first_displayed_entry == NULL)
7274 return;
7276 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7277 while (i++ < maxscroll) {
7278 if (te == NULL) {
7279 if (!isroot)
7280 s->first_displayed_entry = NULL;
7281 break;
7283 s->first_displayed_entry = te;
7284 te = got_tree_entry_get_prev(s->tree, te);
7288 static const struct got_error *
7289 tree_scroll_down(struct tog_view *view, int maxscroll)
7291 struct tog_tree_view_state *s = &view->state.tree;
7292 struct got_tree_entry *next, *last;
7293 int n = 0;
7295 if (s->first_displayed_entry)
7296 next = got_tree_entry_get_next(s->tree,
7297 s->first_displayed_entry);
7298 else
7299 next = got_object_tree_get_first_entry(s->tree);
7301 last = s->last_displayed_entry;
7302 while (next && n++ < maxscroll) {
7303 if (last) {
7304 s->last_displayed_entry = last;
7305 last = got_tree_entry_get_next(s->tree, last);
7307 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7308 s->first_displayed_entry = next;
7309 next = got_tree_entry_get_next(s->tree, next);
7313 return NULL;
7316 static const struct got_error *
7317 tree_entry_path(char **path, struct tog_parent_trees *parents,
7318 struct got_tree_entry *te)
7320 const struct got_error *err = NULL;
7321 struct tog_parent_tree *pt;
7322 size_t len = 2; /* for leading slash and NUL */
7324 TAILQ_FOREACH(pt, parents, entry)
7325 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7326 + 1 /* slash */;
7327 if (te)
7328 len += strlen(got_tree_entry_get_name(te));
7330 *path = calloc(1, len);
7331 if (path == NULL)
7332 return got_error_from_errno("calloc");
7334 (*path)[0] = '/';
7335 pt = TAILQ_LAST(parents, tog_parent_trees);
7336 while (pt) {
7337 const char *name = got_tree_entry_get_name(pt->selected_entry);
7338 if (strlcat(*path, name, len) >= len) {
7339 err = got_error(GOT_ERR_NO_SPACE);
7340 goto done;
7342 if (strlcat(*path, "/", len) >= len) {
7343 err = got_error(GOT_ERR_NO_SPACE);
7344 goto done;
7346 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7348 if (te) {
7349 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7350 err = got_error(GOT_ERR_NO_SPACE);
7351 goto done;
7354 done:
7355 if (err) {
7356 free(*path);
7357 *path = NULL;
7359 return err;
7362 static const struct got_error *
7363 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7364 struct got_tree_entry *te, struct tog_parent_trees *parents,
7365 struct got_object_id *commit_id, struct got_repository *repo)
7367 const struct got_error *err = NULL;
7368 char *path;
7369 struct tog_view *blame_view;
7371 *new_view = NULL;
7373 err = tree_entry_path(&path, parents, te);
7374 if (err)
7375 return err;
7377 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7378 if (blame_view == NULL) {
7379 err = got_error_from_errno("view_open");
7380 goto done;
7383 err = open_blame_view(blame_view, path, commit_id, repo);
7384 if (err) {
7385 if (err->code == GOT_ERR_CANCELLED)
7386 err = NULL;
7387 view_close(blame_view);
7388 } else
7389 *new_view = blame_view;
7390 done:
7391 free(path);
7392 return err;
7395 static const struct got_error *
7396 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7397 struct tog_tree_view_state *s)
7399 struct tog_view *log_view;
7400 const struct got_error *err = NULL;
7401 char *path;
7403 *new_view = NULL;
7405 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7406 if (log_view == NULL)
7407 return got_error_from_errno("view_open");
7409 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7410 if (err)
7411 return err;
7413 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7414 path, 0);
7415 if (err)
7416 view_close(log_view);
7417 else
7418 *new_view = log_view;
7419 free(path);
7420 return err;
7423 static const struct got_error *
7424 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7425 const char *head_ref_name, struct got_repository *repo)
7427 const struct got_error *err = NULL;
7428 char *commit_id_str = NULL;
7429 struct tog_tree_view_state *s = &view->state.tree;
7430 struct got_commit_object *commit = NULL;
7432 TAILQ_INIT(&s->parents);
7433 STAILQ_INIT(&s->colors);
7435 s->commit_id = got_object_id_dup(commit_id);
7436 if (s->commit_id == NULL) {
7437 err = got_error_from_errno("got_object_id_dup");
7438 goto done;
7441 err = got_object_open_as_commit(&commit, repo, commit_id);
7442 if (err)
7443 goto done;
7446 * The root is opened here and will be closed when the view is closed.
7447 * Any visited subtrees and their path-wise parents are opened and
7448 * closed on demand.
7450 err = got_object_open_as_tree(&s->root, repo,
7451 got_object_commit_get_tree_id(commit));
7452 if (err)
7453 goto done;
7454 s->tree = s->root;
7456 err = got_object_id_str(&commit_id_str, commit_id);
7457 if (err != NULL)
7458 goto done;
7460 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7461 err = got_error_from_errno("asprintf");
7462 goto done;
7465 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7466 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7467 if (head_ref_name) {
7468 s->head_ref_name = strdup(head_ref_name);
7469 if (s->head_ref_name == NULL) {
7470 err = got_error_from_errno("strdup");
7471 goto done;
7474 s->repo = repo;
7476 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7477 err = add_color(&s->colors, "\\$$",
7478 TOG_COLOR_TREE_SUBMODULE,
7479 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7480 if (err)
7481 goto done;
7482 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7483 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7484 if (err)
7485 goto done;
7486 err = add_color(&s->colors, "/$",
7487 TOG_COLOR_TREE_DIRECTORY,
7488 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7489 if (err)
7490 goto done;
7492 err = add_color(&s->colors, "\\*$",
7493 TOG_COLOR_TREE_EXECUTABLE,
7494 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7495 if (err)
7496 goto done;
7498 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7499 get_color_value("TOG_COLOR_COMMIT"));
7500 if (err)
7501 goto done;
7504 view->show = show_tree_view;
7505 view->input = input_tree_view;
7506 view->close = close_tree_view;
7507 view->search_start = search_start_tree_view;
7508 view->search_next = search_next_tree_view;
7509 done:
7510 free(commit_id_str);
7511 if (commit)
7512 got_object_commit_close(commit);
7513 if (err) {
7514 if (view->close == NULL)
7515 close_tree_view(view);
7516 view_close(view);
7518 return err;
7521 static const struct got_error *
7522 close_tree_view(struct tog_view *view)
7524 struct tog_tree_view_state *s = &view->state.tree;
7526 free_colors(&s->colors);
7527 free(s->tree_label);
7528 s->tree_label = NULL;
7529 free(s->commit_id);
7530 s->commit_id = NULL;
7531 free(s->head_ref_name);
7532 s->head_ref_name = NULL;
7533 while (!TAILQ_EMPTY(&s->parents)) {
7534 struct tog_parent_tree *parent;
7535 parent = TAILQ_FIRST(&s->parents);
7536 TAILQ_REMOVE(&s->parents, parent, entry);
7537 if (parent->tree != s->root)
7538 got_object_tree_close(parent->tree);
7539 free(parent);
7542 if (s->tree != NULL && s->tree != s->root)
7543 got_object_tree_close(s->tree);
7544 if (s->root)
7545 got_object_tree_close(s->root);
7546 return NULL;
7549 static const struct got_error *
7550 search_start_tree_view(struct tog_view *view)
7552 struct tog_tree_view_state *s = &view->state.tree;
7554 s->matched_entry = NULL;
7555 return NULL;
7558 static int
7559 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7561 regmatch_t regmatch;
7563 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7564 0) == 0;
7567 static const struct got_error *
7568 search_next_tree_view(struct tog_view *view)
7570 struct tog_tree_view_state *s = &view->state.tree;
7571 struct got_tree_entry *te = NULL;
7573 if (!view->searching) {
7574 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7575 return NULL;
7578 if (s->matched_entry) {
7579 if (view->searching == TOG_SEARCH_FORWARD) {
7580 if (s->selected_entry)
7581 te = got_tree_entry_get_next(s->tree,
7582 s->selected_entry);
7583 else
7584 te = got_object_tree_get_first_entry(s->tree);
7585 } else {
7586 if (s->selected_entry == NULL)
7587 te = got_object_tree_get_last_entry(s->tree);
7588 else
7589 te = got_tree_entry_get_prev(s->tree,
7590 s->selected_entry);
7592 } else {
7593 if (s->selected_entry)
7594 te = s->selected_entry;
7595 else if (view->searching == TOG_SEARCH_FORWARD)
7596 te = got_object_tree_get_first_entry(s->tree);
7597 else
7598 te = got_object_tree_get_last_entry(s->tree);
7601 while (1) {
7602 if (te == NULL) {
7603 if (s->matched_entry == NULL) {
7604 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7605 return NULL;
7607 if (view->searching == TOG_SEARCH_FORWARD)
7608 te = got_object_tree_get_first_entry(s->tree);
7609 else
7610 te = got_object_tree_get_last_entry(s->tree);
7613 if (match_tree_entry(te, &view->regex)) {
7614 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7615 s->matched_entry = te;
7616 break;
7619 if (view->searching == TOG_SEARCH_FORWARD)
7620 te = got_tree_entry_get_next(s->tree, te);
7621 else
7622 te = got_tree_entry_get_prev(s->tree, te);
7625 if (s->matched_entry) {
7626 s->first_displayed_entry = s->matched_entry;
7627 s->selected = 0;
7630 return NULL;
7633 static const struct got_error *
7634 show_tree_view(struct tog_view *view)
7636 const struct got_error *err = NULL;
7637 struct tog_tree_view_state *s = &view->state.tree;
7638 char *parent_path;
7640 err = tree_entry_path(&parent_path, &s->parents, NULL);
7641 if (err)
7642 return err;
7644 err = draw_tree_entries(view, parent_path);
7645 free(parent_path);
7647 view_border(view);
7648 return err;
7651 static const struct got_error *
7652 tree_goto_line(struct tog_view *view, int nlines)
7654 const struct got_error *err = NULL;
7655 struct tog_tree_view_state *s = &view->state.tree;
7656 struct got_tree_entry **fte, **lte, **ste;
7657 int g, last, first = 1, i = 1;
7658 int root = s->tree == s->root;
7659 int off = root ? 1 : 2;
7661 g = view->gline;
7662 view->gline = 0;
7664 if (g == 0)
7665 g = 1;
7666 else if (g > got_object_tree_get_nentries(s->tree))
7667 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7669 fte = &s->first_displayed_entry;
7670 lte = &s->last_displayed_entry;
7671 ste = &s->selected_entry;
7673 if (*fte != NULL) {
7674 first = got_tree_entry_get_index(*fte);
7675 first += off; /* account for ".." */
7677 last = got_tree_entry_get_index(*lte);
7678 last += off;
7680 if (g >= first && g <= last && g - first < nlines) {
7681 s->selected = g - first;
7682 return NULL; /* gline is on the current page */
7685 if (*ste != NULL) {
7686 i = got_tree_entry_get_index(*ste);
7687 i += off;
7690 if (i < g) {
7691 err = tree_scroll_down(view, g - i);
7692 if (err)
7693 return err;
7694 if (got_tree_entry_get_index(*lte) >=
7695 got_object_tree_get_nentries(s->tree) - 1 &&
7696 first + s->selected < g &&
7697 s->selected < s->ndisplayed - 1) {
7698 first = got_tree_entry_get_index(*fte);
7699 first += off;
7700 s->selected = g - first;
7702 } else if (i > g)
7703 tree_scroll_up(s, i - g);
7705 if (g < nlines &&
7706 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7707 s->selected = g - 1;
7709 return NULL;
7712 static const struct got_error *
7713 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7715 const struct got_error *err = NULL;
7716 struct tog_tree_view_state *s = &view->state.tree;
7717 struct got_tree_entry *te;
7718 int n, nscroll = view->nlines - 3;
7720 if (view->gline)
7721 return tree_goto_line(view, nscroll);
7723 switch (ch) {
7724 case '0':
7725 case '$':
7726 case KEY_RIGHT:
7727 case 'l':
7728 case KEY_LEFT:
7729 case 'h':
7730 horizontal_scroll_input(view, ch);
7731 break;
7732 case 'i':
7733 s->show_ids = !s->show_ids;
7734 view->count = 0;
7735 break;
7736 case 'L':
7737 view->count = 0;
7738 if (!s->selected_entry)
7739 break;
7740 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7741 break;
7742 case 'R':
7743 view->count = 0;
7744 err = view_request_new(new_view, view, TOG_VIEW_REF);
7745 break;
7746 case 'g':
7747 case '=':
7748 case KEY_HOME:
7749 s->selected = 0;
7750 view->count = 0;
7751 if (s->tree == s->root)
7752 s->first_displayed_entry =
7753 got_object_tree_get_first_entry(s->tree);
7754 else
7755 s->first_displayed_entry = NULL;
7756 break;
7757 case 'G':
7758 case '*':
7759 case KEY_END: {
7760 int eos = view->nlines - 3;
7762 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7763 --eos; /* border */
7764 s->selected = 0;
7765 view->count = 0;
7766 te = got_object_tree_get_last_entry(s->tree);
7767 for (n = 0; n < eos; n++) {
7768 if (te == NULL) {
7769 if (s->tree != s->root) {
7770 s->first_displayed_entry = NULL;
7771 n++;
7773 break;
7775 s->first_displayed_entry = te;
7776 te = got_tree_entry_get_prev(s->tree, te);
7778 if (n > 0)
7779 s->selected = n - 1;
7780 break;
7782 case 'k':
7783 case KEY_UP:
7784 case CTRL('p'):
7785 if (s->selected > 0) {
7786 s->selected--;
7787 break;
7789 tree_scroll_up(s, 1);
7790 if (s->selected_entry == NULL ||
7791 (s->tree == s->root && s->selected_entry ==
7792 got_object_tree_get_first_entry(s->tree)))
7793 view->count = 0;
7794 break;
7795 case CTRL('u'):
7796 case 'u':
7797 nscroll /= 2;
7798 /* FALL THROUGH */
7799 case KEY_PPAGE:
7800 case CTRL('b'):
7801 case 'b':
7802 if (s->tree == s->root) {
7803 if (got_object_tree_get_first_entry(s->tree) ==
7804 s->first_displayed_entry)
7805 s->selected -= MIN(s->selected, nscroll);
7806 } else {
7807 if (s->first_displayed_entry == NULL)
7808 s->selected -= MIN(s->selected, nscroll);
7810 tree_scroll_up(s, MAX(0, nscroll));
7811 if (s->selected_entry == NULL ||
7812 (s->tree == s->root && s->selected_entry ==
7813 got_object_tree_get_first_entry(s->tree)))
7814 view->count = 0;
7815 break;
7816 case 'j':
7817 case KEY_DOWN:
7818 case CTRL('n'):
7819 if (s->selected < s->ndisplayed - 1) {
7820 s->selected++;
7821 break;
7823 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7824 == NULL) {
7825 /* can't scroll any further */
7826 view->count = 0;
7827 break;
7829 tree_scroll_down(view, 1);
7830 break;
7831 case CTRL('d'):
7832 case 'd':
7833 nscroll /= 2;
7834 /* FALL THROUGH */
7835 case KEY_NPAGE:
7836 case CTRL('f'):
7837 case 'f':
7838 case ' ':
7839 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7840 == NULL) {
7841 /* can't scroll any further; move cursor down */
7842 if (s->selected < s->ndisplayed - 1)
7843 s->selected += MIN(nscroll,
7844 s->ndisplayed - s->selected - 1);
7845 else
7846 view->count = 0;
7847 break;
7849 tree_scroll_down(view, nscroll);
7850 break;
7851 case KEY_ENTER:
7852 case '\r':
7853 case KEY_BACKSPACE:
7854 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7855 struct tog_parent_tree *parent;
7856 /* user selected '..' */
7857 if (s->tree == s->root) {
7858 view->count = 0;
7859 break;
7861 parent = TAILQ_FIRST(&s->parents);
7862 TAILQ_REMOVE(&s->parents, parent,
7863 entry);
7864 got_object_tree_close(s->tree);
7865 s->tree = parent->tree;
7866 s->first_displayed_entry =
7867 parent->first_displayed_entry;
7868 s->selected_entry =
7869 parent->selected_entry;
7870 s->selected = parent->selected;
7871 if (s->selected > view->nlines - 3) {
7872 err = offset_selection_down(view);
7873 if (err)
7874 break;
7876 free(parent);
7877 } else if (S_ISDIR(got_tree_entry_get_mode(
7878 s->selected_entry))) {
7879 struct got_tree_object *subtree;
7880 view->count = 0;
7881 err = got_object_open_as_tree(&subtree, s->repo,
7882 got_tree_entry_get_id(s->selected_entry));
7883 if (err)
7884 break;
7885 err = tree_view_visit_subtree(s, subtree);
7886 if (err) {
7887 got_object_tree_close(subtree);
7888 break;
7890 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7891 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7892 break;
7893 case KEY_RESIZE:
7894 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7895 s->selected = view->nlines - 4;
7896 view->count = 0;
7897 break;
7898 default:
7899 view->count = 0;
7900 break;
7903 return err;
7906 __dead static void
7907 usage_tree(void)
7909 endwin();
7910 fprintf(stderr,
7911 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7912 getprogname());
7913 exit(1);
7916 static const struct got_error *
7917 cmd_tree(int argc, char *argv[])
7919 const struct got_error *error;
7920 struct got_repository *repo = NULL;
7921 struct got_worktree *worktree = NULL;
7922 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7923 struct got_object_id *commit_id = NULL;
7924 struct got_commit_object *commit = NULL;
7925 const char *commit_id_arg = NULL;
7926 char *label = NULL;
7927 struct got_reference *ref = NULL;
7928 const char *head_ref_name = NULL;
7929 int ch;
7930 struct tog_view *view;
7931 int *pack_fds = NULL;
7933 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7934 switch (ch) {
7935 case 'c':
7936 commit_id_arg = optarg;
7937 break;
7938 case 'r':
7939 repo_path = realpath(optarg, NULL);
7940 if (repo_path == NULL)
7941 return got_error_from_errno2("realpath",
7942 optarg);
7943 break;
7944 default:
7945 usage_tree();
7946 /* NOTREACHED */
7950 argc -= optind;
7951 argv += optind;
7953 if (argc > 1)
7954 usage_tree();
7956 error = got_repo_pack_fds_open(&pack_fds);
7957 if (error != NULL)
7958 goto done;
7960 if (repo_path == NULL) {
7961 cwd = getcwd(NULL, 0);
7962 if (cwd == NULL)
7963 return got_error_from_errno("getcwd");
7964 error = got_worktree_open(&worktree, cwd);
7965 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7966 goto done;
7967 if (worktree)
7968 repo_path =
7969 strdup(got_worktree_get_repo_path(worktree));
7970 else
7971 repo_path = strdup(cwd);
7972 if (repo_path == NULL) {
7973 error = got_error_from_errno("strdup");
7974 goto done;
7978 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7979 if (error != NULL)
7980 goto done;
7982 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7983 repo, worktree);
7984 if (error)
7985 goto done;
7987 init_curses();
7989 error = apply_unveil(got_repo_get_path(repo), NULL);
7990 if (error)
7991 goto done;
7993 error = tog_load_refs(repo, 0);
7994 if (error)
7995 goto done;
7997 if (commit_id_arg == NULL) {
7998 error = got_repo_match_object_id(&commit_id, &label,
7999 worktree ? got_worktree_get_head_ref_name(worktree) :
8000 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8001 if (error)
8002 goto done;
8003 head_ref_name = label;
8004 } else {
8005 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8006 if (error == NULL)
8007 head_ref_name = got_ref_get_name(ref);
8008 else if (error->code != GOT_ERR_NOT_REF)
8009 goto done;
8010 error = got_repo_match_object_id(&commit_id, NULL,
8011 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8012 if (error)
8013 goto done;
8016 error = got_object_open_as_commit(&commit, repo, commit_id);
8017 if (error)
8018 goto done;
8020 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8021 if (view == NULL) {
8022 error = got_error_from_errno("view_open");
8023 goto done;
8025 error = open_tree_view(view, commit_id, head_ref_name, repo);
8026 if (error)
8027 goto done;
8028 if (!got_path_is_root_dir(in_repo_path)) {
8029 error = tree_view_walk_path(&view->state.tree, commit,
8030 in_repo_path);
8031 if (error)
8032 goto done;
8035 if (worktree) {
8036 /* Release work tree lock. */
8037 got_worktree_close(worktree);
8038 worktree = NULL;
8040 error = view_loop(view);
8041 done:
8042 free(repo_path);
8043 free(cwd);
8044 free(commit_id);
8045 free(label);
8046 if (ref)
8047 got_ref_close(ref);
8048 if (repo) {
8049 const struct got_error *close_err = got_repo_close(repo);
8050 if (error == NULL)
8051 error = close_err;
8053 if (pack_fds) {
8054 const struct got_error *pack_err =
8055 got_repo_pack_fds_close(pack_fds);
8056 if (error == NULL)
8057 error = pack_err;
8059 tog_free_refs();
8060 return error;
8063 static const struct got_error *
8064 ref_view_load_refs(struct tog_ref_view_state *s)
8066 struct got_reflist_entry *sre;
8067 struct tog_reflist_entry *re;
8069 s->nrefs = 0;
8070 TAILQ_FOREACH(sre, &tog_refs, entry) {
8071 if (strncmp(got_ref_get_name(sre->ref),
8072 "refs/got/", 9) == 0 &&
8073 strncmp(got_ref_get_name(sre->ref),
8074 "refs/got/backup/", 16) != 0)
8075 continue;
8077 re = malloc(sizeof(*re));
8078 if (re == NULL)
8079 return got_error_from_errno("malloc");
8081 re->ref = got_ref_dup(sre->ref);
8082 if (re->ref == NULL)
8083 return got_error_from_errno("got_ref_dup");
8084 re->idx = s->nrefs++;
8085 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8088 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8089 return NULL;
8092 static void
8093 ref_view_free_refs(struct tog_ref_view_state *s)
8095 struct tog_reflist_entry *re;
8097 while (!TAILQ_EMPTY(&s->refs)) {
8098 re = TAILQ_FIRST(&s->refs);
8099 TAILQ_REMOVE(&s->refs, re, entry);
8100 got_ref_close(re->ref);
8101 free(re);
8105 static const struct got_error *
8106 open_ref_view(struct tog_view *view, struct got_repository *repo)
8108 const struct got_error *err = NULL;
8109 struct tog_ref_view_state *s = &view->state.ref;
8111 s->selected_entry = 0;
8112 s->repo = repo;
8114 TAILQ_INIT(&s->refs);
8115 STAILQ_INIT(&s->colors);
8117 err = ref_view_load_refs(s);
8118 if (err)
8119 goto done;
8121 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8122 err = add_color(&s->colors, "^refs/heads/",
8123 TOG_COLOR_REFS_HEADS,
8124 get_color_value("TOG_COLOR_REFS_HEADS"));
8125 if (err)
8126 goto done;
8128 err = add_color(&s->colors, "^refs/tags/",
8129 TOG_COLOR_REFS_TAGS,
8130 get_color_value("TOG_COLOR_REFS_TAGS"));
8131 if (err)
8132 goto done;
8134 err = add_color(&s->colors, "^refs/remotes/",
8135 TOG_COLOR_REFS_REMOTES,
8136 get_color_value("TOG_COLOR_REFS_REMOTES"));
8137 if (err)
8138 goto done;
8140 err = add_color(&s->colors, "^refs/got/backup/",
8141 TOG_COLOR_REFS_BACKUP,
8142 get_color_value("TOG_COLOR_REFS_BACKUP"));
8143 if (err)
8144 goto done;
8147 view->show = show_ref_view;
8148 view->input = input_ref_view;
8149 view->close = close_ref_view;
8150 view->search_start = search_start_ref_view;
8151 view->search_next = search_next_ref_view;
8152 done:
8153 if (err) {
8154 if (view->close == NULL)
8155 close_ref_view(view);
8156 view_close(view);
8158 return err;
8161 static const struct got_error *
8162 close_ref_view(struct tog_view *view)
8164 struct tog_ref_view_state *s = &view->state.ref;
8166 ref_view_free_refs(s);
8167 free_colors(&s->colors);
8169 return NULL;
8172 static const struct got_error *
8173 resolve_reflist_entry(struct got_object_id **commit_id,
8174 struct tog_reflist_entry *re, struct got_repository *repo)
8176 const struct got_error *err = NULL;
8177 struct got_object_id *obj_id;
8178 struct got_tag_object *tag = NULL;
8179 int obj_type;
8181 *commit_id = NULL;
8183 err = got_ref_resolve(&obj_id, repo, re->ref);
8184 if (err)
8185 return err;
8187 err = got_object_get_type(&obj_type, repo, obj_id);
8188 if (err)
8189 goto done;
8191 switch (obj_type) {
8192 case GOT_OBJ_TYPE_COMMIT:
8193 *commit_id = obj_id;
8194 break;
8195 case GOT_OBJ_TYPE_TAG:
8196 err = got_object_open_as_tag(&tag, repo, obj_id);
8197 if (err)
8198 goto done;
8199 free(obj_id);
8200 err = got_object_get_type(&obj_type, repo,
8201 got_object_tag_get_object_id(tag));
8202 if (err)
8203 goto done;
8204 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8205 err = got_error(GOT_ERR_OBJ_TYPE);
8206 goto done;
8208 *commit_id = got_object_id_dup(
8209 got_object_tag_get_object_id(tag));
8210 if (*commit_id == NULL) {
8211 err = got_error_from_errno("got_object_id_dup");
8212 goto done;
8214 break;
8215 default:
8216 err = got_error(GOT_ERR_OBJ_TYPE);
8217 break;
8220 done:
8221 if (tag)
8222 got_object_tag_close(tag);
8223 if (err) {
8224 free(*commit_id);
8225 *commit_id = NULL;
8227 return err;
8230 static const struct got_error *
8231 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8232 struct tog_reflist_entry *re, struct got_repository *repo)
8234 struct tog_view *log_view;
8235 const struct got_error *err = NULL;
8236 struct got_object_id *commit_id = NULL;
8238 *new_view = NULL;
8240 err = resolve_reflist_entry(&commit_id, re, repo);
8241 if (err) {
8242 if (err->code != GOT_ERR_OBJ_TYPE)
8243 return err;
8244 else
8245 return NULL;
8248 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8249 if (log_view == NULL) {
8250 err = got_error_from_errno("view_open");
8251 goto done;
8254 err = open_log_view(log_view, commit_id, repo,
8255 got_ref_get_name(re->ref), "", 0);
8256 done:
8257 if (err)
8258 view_close(log_view);
8259 else
8260 *new_view = log_view;
8261 free(commit_id);
8262 return err;
8265 static void
8266 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8268 struct tog_reflist_entry *re;
8269 int i = 0;
8271 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8272 return;
8274 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8275 while (i++ < maxscroll) {
8276 if (re == NULL)
8277 break;
8278 s->first_displayed_entry = re;
8279 re = TAILQ_PREV(re, tog_reflist_head, entry);
8283 static const struct got_error *
8284 ref_scroll_down(struct tog_view *view, int maxscroll)
8286 struct tog_ref_view_state *s = &view->state.ref;
8287 struct tog_reflist_entry *next, *last;
8288 int n = 0;
8290 if (s->first_displayed_entry)
8291 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8292 else
8293 next = TAILQ_FIRST(&s->refs);
8295 last = s->last_displayed_entry;
8296 while (next && n++ < maxscroll) {
8297 if (last) {
8298 s->last_displayed_entry = last;
8299 last = TAILQ_NEXT(last, entry);
8301 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8302 s->first_displayed_entry = next;
8303 next = TAILQ_NEXT(next, entry);
8307 return NULL;
8310 static const struct got_error *
8311 search_start_ref_view(struct tog_view *view)
8313 struct tog_ref_view_state *s = &view->state.ref;
8315 s->matched_entry = NULL;
8316 return NULL;
8319 static int
8320 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8322 regmatch_t regmatch;
8324 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8325 0) == 0;
8328 static const struct got_error *
8329 search_next_ref_view(struct tog_view *view)
8331 struct tog_ref_view_state *s = &view->state.ref;
8332 struct tog_reflist_entry *re = NULL;
8334 if (!view->searching) {
8335 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8336 return NULL;
8339 if (s->matched_entry) {
8340 if (view->searching == TOG_SEARCH_FORWARD) {
8341 if (s->selected_entry)
8342 re = TAILQ_NEXT(s->selected_entry, entry);
8343 else
8344 re = TAILQ_PREV(s->selected_entry,
8345 tog_reflist_head, entry);
8346 } else {
8347 if (s->selected_entry == NULL)
8348 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8349 else
8350 re = TAILQ_PREV(s->selected_entry,
8351 tog_reflist_head, entry);
8353 } else {
8354 if (s->selected_entry)
8355 re = s->selected_entry;
8356 else if (view->searching == TOG_SEARCH_FORWARD)
8357 re = TAILQ_FIRST(&s->refs);
8358 else
8359 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8362 while (1) {
8363 if (re == NULL) {
8364 if (s->matched_entry == NULL) {
8365 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8366 return NULL;
8368 if (view->searching == TOG_SEARCH_FORWARD)
8369 re = TAILQ_FIRST(&s->refs);
8370 else
8371 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8374 if (match_reflist_entry(re, &view->regex)) {
8375 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8376 s->matched_entry = re;
8377 break;
8380 if (view->searching == TOG_SEARCH_FORWARD)
8381 re = TAILQ_NEXT(re, entry);
8382 else
8383 re = TAILQ_PREV(re, tog_reflist_head, entry);
8386 if (s->matched_entry) {
8387 s->first_displayed_entry = s->matched_entry;
8388 s->selected = 0;
8391 return NULL;
8394 static const struct got_error *
8395 show_ref_view(struct tog_view *view)
8397 const struct got_error *err = NULL;
8398 struct tog_ref_view_state *s = &view->state.ref;
8399 struct tog_reflist_entry *re;
8400 char *line = NULL;
8401 wchar_t *wline;
8402 struct tog_color *tc;
8403 int width, n, scrollx;
8404 int limit = view->nlines;
8406 werase(view->window);
8408 s->ndisplayed = 0;
8409 if (view_is_hsplit_top(view))
8410 --limit; /* border */
8412 if (limit == 0)
8413 return NULL;
8415 re = s->first_displayed_entry;
8417 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8418 s->nrefs) == -1)
8419 return got_error_from_errno("asprintf");
8421 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8422 if (err) {
8423 free(line);
8424 return err;
8426 if (view_needs_focus_indication(view))
8427 wstandout(view->window);
8428 waddwstr(view->window, wline);
8429 while (width++ < view->ncols)
8430 waddch(view->window, ' ');
8431 if (view_needs_focus_indication(view))
8432 wstandend(view->window);
8433 free(wline);
8434 wline = NULL;
8435 free(line);
8436 line = NULL;
8437 if (--limit <= 0)
8438 return NULL;
8440 n = 0;
8441 view->maxx = 0;
8442 while (re && limit > 0) {
8443 char *line = NULL;
8444 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8446 if (s->show_date) {
8447 struct got_commit_object *ci;
8448 struct got_tag_object *tag;
8449 struct got_object_id *id;
8450 struct tm tm;
8451 time_t t;
8453 err = got_ref_resolve(&id, s->repo, re->ref);
8454 if (err)
8455 return err;
8456 err = got_object_open_as_tag(&tag, s->repo, id);
8457 if (err) {
8458 if (err->code != GOT_ERR_OBJ_TYPE) {
8459 free(id);
8460 return err;
8462 err = got_object_open_as_commit(&ci, s->repo,
8463 id);
8464 if (err) {
8465 free(id);
8466 return err;
8468 t = got_object_commit_get_committer_time(ci);
8469 got_object_commit_close(ci);
8470 } else {
8471 t = got_object_tag_get_tagger_time(tag);
8472 got_object_tag_close(tag);
8474 free(id);
8475 if (gmtime_r(&t, &tm) == NULL)
8476 return got_error_from_errno("gmtime_r");
8477 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8478 return got_error(GOT_ERR_NO_SPACE);
8480 if (got_ref_is_symbolic(re->ref)) {
8481 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8482 ymd : "", got_ref_get_name(re->ref),
8483 got_ref_get_symref_target(re->ref)) == -1)
8484 return got_error_from_errno("asprintf");
8485 } else if (s->show_ids) {
8486 struct got_object_id *id;
8487 char *id_str;
8488 err = got_ref_resolve(&id, s->repo, re->ref);
8489 if (err)
8490 return err;
8491 err = got_object_id_str(&id_str, id);
8492 if (err) {
8493 free(id);
8494 return err;
8496 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8497 got_ref_get_name(re->ref), id_str) == -1) {
8498 err = got_error_from_errno("asprintf");
8499 free(id);
8500 free(id_str);
8501 return err;
8503 free(id);
8504 free(id_str);
8505 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8506 got_ref_get_name(re->ref)) == -1)
8507 return got_error_from_errno("asprintf");
8509 /* use full line width to determine view->maxx */
8510 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8511 if (err) {
8512 free(line);
8513 return err;
8515 view->maxx = MAX(view->maxx, width);
8516 free(wline);
8517 wline = NULL;
8519 err = format_line(&wline, &width, &scrollx, line, view->x,
8520 view->ncols, 0, 0);
8521 if (err) {
8522 free(line);
8523 return err;
8525 if (n == s->selected) {
8526 if (view->focussed)
8527 wstandout(view->window);
8528 s->selected_entry = re;
8530 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8531 if (tc)
8532 wattr_on(view->window,
8533 COLOR_PAIR(tc->colorpair), NULL);
8534 waddwstr(view->window, &wline[scrollx]);
8535 if (tc)
8536 wattr_off(view->window,
8537 COLOR_PAIR(tc->colorpair), NULL);
8538 if (width < view->ncols)
8539 waddch(view->window, '\n');
8540 if (n == s->selected && view->focussed)
8541 wstandend(view->window);
8542 free(line);
8543 free(wline);
8544 wline = NULL;
8545 n++;
8546 s->ndisplayed++;
8547 s->last_displayed_entry = re;
8549 limit--;
8550 re = TAILQ_NEXT(re, entry);
8553 view_border(view);
8554 return err;
8557 static const struct got_error *
8558 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8559 struct tog_reflist_entry *re, struct got_repository *repo)
8561 const struct got_error *err = NULL;
8562 struct got_object_id *commit_id = NULL;
8563 struct tog_view *tree_view;
8565 *new_view = NULL;
8567 err = resolve_reflist_entry(&commit_id, re, repo);
8568 if (err) {
8569 if (err->code != GOT_ERR_OBJ_TYPE)
8570 return err;
8571 else
8572 return NULL;
8576 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8577 if (tree_view == NULL) {
8578 err = got_error_from_errno("view_open");
8579 goto done;
8582 err = open_tree_view(tree_view, commit_id,
8583 got_ref_get_name(re->ref), repo);
8584 if (err)
8585 goto done;
8587 *new_view = tree_view;
8588 done:
8589 free(commit_id);
8590 return err;
8593 static const struct got_error *
8594 ref_goto_line(struct tog_view *view, int nlines)
8596 const struct got_error *err = NULL;
8597 struct tog_ref_view_state *s = &view->state.ref;
8598 int g, idx = s->selected_entry->idx;
8600 g = view->gline;
8601 view->gline = 0;
8603 if (g == 0)
8604 g = 1;
8605 else if (g > s->nrefs)
8606 g = s->nrefs;
8608 if (g >= s->first_displayed_entry->idx + 1 &&
8609 g <= s->last_displayed_entry->idx + 1 &&
8610 g - s->first_displayed_entry->idx - 1 < nlines) {
8611 s->selected = g - s->first_displayed_entry->idx - 1;
8612 return NULL;
8615 if (idx + 1 < g) {
8616 err = ref_scroll_down(view, g - idx - 1);
8617 if (err)
8618 return err;
8619 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8620 s->first_displayed_entry->idx + s->selected < g &&
8621 s->selected < s->ndisplayed - 1)
8622 s->selected = g - s->first_displayed_entry->idx - 1;
8623 } else if (idx + 1 > g)
8624 ref_scroll_up(s, idx - g + 1);
8626 if (g < nlines && s->first_displayed_entry->idx == 0)
8627 s->selected = g - 1;
8629 return NULL;
8633 static const struct got_error *
8634 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8636 const struct got_error *err = NULL;
8637 struct tog_ref_view_state *s = &view->state.ref;
8638 struct tog_reflist_entry *re;
8639 int n, nscroll = view->nlines - 1;
8641 if (view->gline)
8642 return ref_goto_line(view, nscroll);
8644 switch (ch) {
8645 case '0':
8646 case '$':
8647 case KEY_RIGHT:
8648 case 'l':
8649 case KEY_LEFT:
8650 case 'h':
8651 horizontal_scroll_input(view, ch);
8652 break;
8653 case 'i':
8654 s->show_ids = !s->show_ids;
8655 view->count = 0;
8656 break;
8657 case 'm':
8658 s->show_date = !s->show_date;
8659 view->count = 0;
8660 break;
8661 case 'o':
8662 s->sort_by_date = !s->sort_by_date;
8663 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8664 view->count = 0;
8665 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8666 got_ref_cmp_by_commit_timestamp_descending :
8667 tog_ref_cmp_by_name, s->repo);
8668 if (err)
8669 break;
8670 got_reflist_object_id_map_free(tog_refs_idmap);
8671 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8672 &tog_refs, s->repo);
8673 if (err)
8674 break;
8675 ref_view_free_refs(s);
8676 err = ref_view_load_refs(s);
8677 break;
8678 case KEY_ENTER:
8679 case '\r':
8680 view->count = 0;
8681 if (!s->selected_entry)
8682 break;
8683 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8684 break;
8685 case 'T':
8686 view->count = 0;
8687 if (!s->selected_entry)
8688 break;
8689 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8690 break;
8691 case 'g':
8692 case '=':
8693 case KEY_HOME:
8694 s->selected = 0;
8695 view->count = 0;
8696 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8697 break;
8698 case 'G':
8699 case '*':
8700 case KEY_END: {
8701 int eos = view->nlines - 1;
8703 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8704 --eos; /* border */
8705 s->selected = 0;
8706 view->count = 0;
8707 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8708 for (n = 0; n < eos; n++) {
8709 if (re == NULL)
8710 break;
8711 s->first_displayed_entry = re;
8712 re = TAILQ_PREV(re, tog_reflist_head, entry);
8714 if (n > 0)
8715 s->selected = n - 1;
8716 break;
8718 case 'k':
8719 case KEY_UP:
8720 case CTRL('p'):
8721 if (s->selected > 0) {
8722 s->selected--;
8723 break;
8725 ref_scroll_up(s, 1);
8726 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8727 view->count = 0;
8728 break;
8729 case CTRL('u'):
8730 case 'u':
8731 nscroll /= 2;
8732 /* FALL THROUGH */
8733 case KEY_PPAGE:
8734 case CTRL('b'):
8735 case 'b':
8736 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8737 s->selected -= MIN(nscroll, s->selected);
8738 ref_scroll_up(s, MAX(0, nscroll));
8739 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8740 view->count = 0;
8741 break;
8742 case 'j':
8743 case KEY_DOWN:
8744 case CTRL('n'):
8745 if (s->selected < s->ndisplayed - 1) {
8746 s->selected++;
8747 break;
8749 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8750 /* can't scroll any further */
8751 view->count = 0;
8752 break;
8754 ref_scroll_down(view, 1);
8755 break;
8756 case CTRL('d'):
8757 case 'd':
8758 nscroll /= 2;
8759 /* FALL THROUGH */
8760 case KEY_NPAGE:
8761 case CTRL('f'):
8762 case 'f':
8763 case ' ':
8764 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8765 /* can't scroll any further; move cursor down */
8766 if (s->selected < s->ndisplayed - 1)
8767 s->selected += MIN(nscroll,
8768 s->ndisplayed - s->selected - 1);
8769 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8770 s->selected += s->ndisplayed - s->selected - 1;
8771 view->count = 0;
8772 break;
8774 ref_scroll_down(view, nscroll);
8775 break;
8776 case CTRL('l'):
8777 view->count = 0;
8778 tog_free_refs();
8779 err = tog_load_refs(s->repo, s->sort_by_date);
8780 if (err)
8781 break;
8782 ref_view_free_refs(s);
8783 err = ref_view_load_refs(s);
8784 break;
8785 case KEY_RESIZE:
8786 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8787 s->selected = view->nlines - 2;
8788 break;
8789 default:
8790 view->count = 0;
8791 break;
8794 return err;
8797 __dead static void
8798 usage_ref(void)
8800 endwin();
8801 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8802 getprogname());
8803 exit(1);
8806 static const struct got_error *
8807 cmd_ref(int argc, char *argv[])
8809 const struct got_error *error;
8810 struct got_repository *repo = NULL;
8811 struct got_worktree *worktree = NULL;
8812 char *cwd = NULL, *repo_path = NULL;
8813 int ch;
8814 struct tog_view *view;
8815 int *pack_fds = NULL;
8817 while ((ch = getopt(argc, argv, "r:")) != -1) {
8818 switch (ch) {
8819 case 'r':
8820 repo_path = realpath(optarg, NULL);
8821 if (repo_path == NULL)
8822 return got_error_from_errno2("realpath",
8823 optarg);
8824 break;
8825 default:
8826 usage_ref();
8827 /* NOTREACHED */
8831 argc -= optind;
8832 argv += optind;
8834 if (argc > 1)
8835 usage_ref();
8837 error = got_repo_pack_fds_open(&pack_fds);
8838 if (error != NULL)
8839 goto done;
8841 if (repo_path == NULL) {
8842 cwd = getcwd(NULL, 0);
8843 if (cwd == NULL)
8844 return got_error_from_errno("getcwd");
8845 error = got_worktree_open(&worktree, cwd);
8846 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8847 goto done;
8848 if (worktree)
8849 repo_path =
8850 strdup(got_worktree_get_repo_path(worktree));
8851 else
8852 repo_path = strdup(cwd);
8853 if (repo_path == NULL) {
8854 error = got_error_from_errno("strdup");
8855 goto done;
8859 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8860 if (error != NULL)
8861 goto done;
8863 init_curses();
8865 error = apply_unveil(got_repo_get_path(repo), NULL);
8866 if (error)
8867 goto done;
8869 error = tog_load_refs(repo, 0);
8870 if (error)
8871 goto done;
8873 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8874 if (view == NULL) {
8875 error = got_error_from_errno("view_open");
8876 goto done;
8879 error = open_ref_view(view, repo);
8880 if (error)
8881 goto done;
8883 if (worktree) {
8884 /* Release work tree lock. */
8885 got_worktree_close(worktree);
8886 worktree = NULL;
8888 error = view_loop(view);
8889 done:
8890 free(repo_path);
8891 free(cwd);
8892 if (repo) {
8893 const struct got_error *close_err = got_repo_close(repo);
8894 if (close_err)
8895 error = close_err;
8897 if (pack_fds) {
8898 const struct got_error *pack_err =
8899 got_repo_pack_fds_close(pack_fds);
8900 if (error == NULL)
8901 error = pack_err;
8903 tog_free_refs();
8904 return error;
8907 static const struct got_error*
8908 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8909 const char *str)
8911 size_t len;
8913 if (win == NULL)
8914 win = stdscr;
8916 len = strlen(str);
8917 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8919 if (focus)
8920 wstandout(win);
8921 if (mvwprintw(win, y, x, "%s", str) == ERR)
8922 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8923 if (focus)
8924 wstandend(win);
8926 return NULL;
8929 static const struct got_error *
8930 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8932 off_t *p;
8934 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8935 if (p == NULL) {
8936 free(*line_offsets);
8937 *line_offsets = NULL;
8938 return got_error_from_errno("reallocarray");
8941 *line_offsets = p;
8942 (*line_offsets)[*nlines] = off;
8943 ++(*nlines);
8944 return NULL;
8947 static const struct got_error *
8948 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8950 *ret = 0;
8952 for (;n > 0; --n, ++km) {
8953 char *t0, *t, *k;
8954 size_t len = 1;
8956 if (km->keys == NULL)
8957 continue;
8959 t = t0 = strdup(km->keys);
8960 if (t0 == NULL)
8961 return got_error_from_errno("strdup");
8963 len += strlen(t);
8964 while ((k = strsep(&t, " ")) != NULL)
8965 len += strlen(k) > 1 ? 2 : 0;
8966 free(t0);
8967 *ret = MAX(*ret, len);
8970 return NULL;
8974 * Write keymap section headers, keys, and key info in km to f.
8975 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8976 * wrap control and symbolic keys in guillemets, else use <>.
8978 static const struct got_error *
8979 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8981 int n, len = width;
8983 if (km->keys) {
8984 static const char *u8_glyph[] = {
8985 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8986 "\xe2\x80\xba" /* U+203A (utf8 >) */
8988 char *t0, *t, *k;
8989 int cs, s, first = 1;
8991 cs = got_locale_is_utf8();
8993 t = t0 = strdup(km->keys);
8994 if (t0 == NULL)
8995 return got_error_from_errno("strdup");
8997 len = strlen(km->keys);
8998 while ((k = strsep(&t, " ")) != NULL) {
8999 s = strlen(k) > 1; /* control or symbolic key */
9000 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9001 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9002 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9003 if (n < 0) {
9004 free(t0);
9005 return got_error_from_errno("fprintf");
9007 first = 0;
9008 len += s ? 2 : 0;
9009 *off += n;
9011 free(t0);
9013 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9014 if (n < 0)
9015 return got_error_from_errno("fprintf");
9016 *off += n;
9018 return NULL;
9021 static const struct got_error *
9022 format_help(struct tog_help_view_state *s)
9024 const struct got_error *err = NULL;
9025 off_t off = 0;
9026 int i, max, n, show = s->all;
9027 static const struct tog_key_map km[] = {
9028 #define KEYMAP_(info, type) { NULL, (info), type }
9029 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9030 GENERATE_HELP
9031 #undef KEYMAP_
9032 #undef KEY_
9035 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9036 if (err)
9037 return err;
9039 n = nitems(km);
9040 err = max_key_str(&max, km, n);
9041 if (err)
9042 return err;
9044 for (i = 0; i < n; ++i) {
9045 if (km[i].keys == NULL) {
9046 show = s->all;
9047 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9048 km[i].type == s->type || s->all)
9049 show = 1;
9051 if (show) {
9052 err = format_help_line(&off, s->f, &km[i], max);
9053 if (err)
9054 return err;
9055 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9056 if (err)
9057 return err;
9060 fputc('\n', s->f);
9061 ++off;
9062 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9063 return err;
9066 static const struct got_error *
9067 create_help(struct tog_help_view_state *s)
9069 FILE *f;
9070 const struct got_error *err;
9072 free(s->line_offsets);
9073 s->line_offsets = NULL;
9074 s->nlines = 0;
9076 f = got_opentemp();
9077 if (f == NULL)
9078 return got_error_from_errno("got_opentemp");
9079 s->f = f;
9081 err = format_help(s);
9082 if (err)
9083 return err;
9085 if (s->f && fflush(s->f) != 0)
9086 return got_error_from_errno("fflush");
9088 return NULL;
9091 static const struct got_error *
9092 search_start_help_view(struct tog_view *view)
9094 view->state.help.matched_line = 0;
9095 return NULL;
9098 static void
9099 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9100 size_t *nlines, int **first, int **last, int **match, int **selected)
9102 struct tog_help_view_state *s = &view->state.help;
9104 *f = s->f;
9105 *nlines = s->nlines;
9106 *line_offsets = s->line_offsets;
9107 *match = &s->matched_line;
9108 *first = &s->first_displayed_line;
9109 *last = &s->last_displayed_line;
9110 *selected = &s->selected_line;
9113 static const struct got_error *
9114 show_help_view(struct tog_view *view)
9116 struct tog_help_view_state *s = &view->state.help;
9117 const struct got_error *err;
9118 regmatch_t *regmatch = &view->regmatch;
9119 wchar_t *wline;
9120 char *line;
9121 ssize_t linelen;
9122 size_t linesz = 0;
9123 int width, nprinted = 0, rc = 0;
9124 int eos = view->nlines;
9126 if (view_is_hsplit_top(view))
9127 --eos; /* account for border */
9129 s->lineno = 0;
9130 rewind(s->f);
9131 werase(view->window);
9133 if (view->gline > s->nlines - 1)
9134 view->gline = s->nlines - 1;
9136 err = win_draw_center(view->window, 0, 0, view->ncols,
9137 view_needs_focus_indication(view),
9138 "tog help (press q to return to tog)");
9139 if (err)
9140 return err;
9141 if (eos <= 1)
9142 return NULL;
9143 waddstr(view->window, "\n\n");
9144 eos -= 2;
9146 s->eof = 0;
9147 view->maxx = 0;
9148 line = NULL;
9149 while (eos > 0 && nprinted < eos) {
9150 attr_t attr = 0;
9152 linelen = getline(&line, &linesz, s->f);
9153 if (linelen == -1) {
9154 if (!feof(s->f)) {
9155 free(line);
9156 return got_ferror(s->f, GOT_ERR_IO);
9158 s->eof = 1;
9159 break;
9161 if (++s->lineno < s->first_displayed_line)
9162 continue;
9163 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9164 continue;
9165 if (s->lineno == view->hiline)
9166 attr = A_STANDOUT;
9168 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9169 view->x ? 1 : 0);
9170 if (err) {
9171 free(line);
9172 return err;
9174 view->maxx = MAX(view->maxx, width);
9175 free(wline);
9176 wline = NULL;
9178 if (attr)
9179 wattron(view->window, attr);
9180 if (s->first_displayed_line + nprinted == s->matched_line &&
9181 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9182 err = add_matched_line(&width, line, view->ncols - 1, 0,
9183 view->window, view->x, regmatch);
9184 if (err) {
9185 free(line);
9186 return err;
9188 } else {
9189 int skip;
9191 err = format_line(&wline, &width, &skip, line,
9192 view->x, view->ncols, 0, view->x ? 1 : 0);
9193 if (err) {
9194 free(line);
9195 return err;
9197 waddwstr(view->window, &wline[skip]);
9198 free(wline);
9199 wline = NULL;
9201 if (s->lineno == view->hiline) {
9202 while (width++ < view->ncols)
9203 waddch(view->window, ' ');
9204 } else {
9205 if (width < view->ncols)
9206 waddch(view->window, '\n');
9208 if (attr)
9209 wattroff(view->window, attr);
9210 if (++nprinted == 1)
9211 s->first_displayed_line = s->lineno;
9213 free(line);
9214 if (nprinted > 0)
9215 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9216 else
9217 s->last_displayed_line = s->first_displayed_line;
9219 view_border(view);
9221 if (s->eof) {
9222 rc = waddnstr(view->window,
9223 "See the tog(1) manual page for full documentation",
9224 view->ncols - 1);
9225 if (rc == ERR)
9226 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9227 } else {
9228 wmove(view->window, view->nlines - 1, 0);
9229 wclrtoeol(view->window);
9230 wstandout(view->window);
9231 rc = waddnstr(view->window, "scroll down for more...",
9232 view->ncols - 1);
9233 if (rc == ERR)
9234 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9235 if (getcurx(view->window) < view->ncols - 6) {
9236 rc = wprintw(view->window, "[%.0f%%]",
9237 100.00 * s->last_displayed_line / s->nlines);
9238 if (rc == ERR)
9239 return got_error_msg(GOT_ERR_IO, "wprintw");
9241 wstandend(view->window);
9244 return NULL;
9247 static const struct got_error *
9248 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9250 struct tog_help_view_state *s = &view->state.help;
9251 const struct got_error *err = NULL;
9252 char *line = NULL;
9253 ssize_t linelen;
9254 size_t linesz = 0;
9255 int eos, nscroll;
9257 eos = nscroll = view->nlines;
9258 if (view_is_hsplit_top(view))
9259 --eos; /* border */
9261 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9263 switch (ch) {
9264 case '0':
9265 case '$':
9266 case KEY_RIGHT:
9267 case 'l':
9268 case KEY_LEFT:
9269 case 'h':
9270 horizontal_scroll_input(view, ch);
9271 break;
9272 case 'g':
9273 case KEY_HOME:
9274 s->first_displayed_line = 1;
9275 view->count = 0;
9276 break;
9277 case 'G':
9278 case KEY_END:
9279 view->count = 0;
9280 if (s->eof)
9281 break;
9282 s->first_displayed_line = (s->nlines - eos) + 3;
9283 s->eof = 1;
9284 break;
9285 case 'k':
9286 case KEY_UP:
9287 if (s->first_displayed_line > 1)
9288 --s->first_displayed_line;
9289 else
9290 view->count = 0;
9291 break;
9292 case CTRL('u'):
9293 case 'u':
9294 nscroll /= 2;
9295 /* FALL THROUGH */
9296 case KEY_PPAGE:
9297 case CTRL('b'):
9298 case 'b':
9299 if (s->first_displayed_line == 1) {
9300 view->count = 0;
9301 break;
9303 while (--nscroll > 0 && s->first_displayed_line > 1)
9304 s->first_displayed_line--;
9305 break;
9306 case 'j':
9307 case KEY_DOWN:
9308 case CTRL('n'):
9309 if (!s->eof)
9310 ++s->first_displayed_line;
9311 else
9312 view->count = 0;
9313 break;
9314 case CTRL('d'):
9315 case 'd':
9316 nscroll /= 2;
9317 /* FALL THROUGH */
9318 case KEY_NPAGE:
9319 case CTRL('f'):
9320 case 'f':
9321 case ' ':
9322 if (s->eof) {
9323 view->count = 0;
9324 break;
9326 while (!s->eof && --nscroll > 0) {
9327 linelen = getline(&line, &linesz, s->f);
9328 s->first_displayed_line++;
9329 if (linelen == -1) {
9330 if (feof(s->f))
9331 s->eof = 1;
9332 else
9333 err = got_ferror(s->f, GOT_ERR_IO);
9334 break;
9337 free(line);
9338 break;
9339 default:
9340 view->count = 0;
9341 break;
9344 return err;
9347 static const struct got_error *
9348 close_help_view(struct tog_view *view)
9350 struct tog_help_view_state *s = &view->state.help;
9352 free(s->line_offsets);
9353 s->line_offsets = NULL;
9354 if (fclose(s->f) == EOF)
9355 return got_error_from_errno("fclose");
9357 return NULL;
9360 static const struct got_error *
9361 reset_help_view(struct tog_view *view)
9363 struct tog_help_view_state *s = &view->state.help;
9366 if (s->f && fclose(s->f) == EOF)
9367 return got_error_from_errno("fclose");
9369 wclear(view->window);
9370 view->count = 0;
9371 view->x = 0;
9372 s->all = !s->all;
9373 s->first_displayed_line = 1;
9374 s->last_displayed_line = view->nlines;
9375 s->matched_line = 0;
9377 return create_help(s);
9380 static const struct got_error *
9381 open_help_view(struct tog_view *view, struct tog_view *parent)
9383 const struct got_error *err = NULL;
9384 struct tog_help_view_state *s = &view->state.help;
9386 s->type = (enum tog_keymap_type)parent->type;
9387 s->first_displayed_line = 1;
9388 s->last_displayed_line = view->nlines;
9389 s->selected_line = 1;
9391 view->show = show_help_view;
9392 view->input = input_help_view;
9393 view->reset = reset_help_view;
9394 view->close = close_help_view;
9395 view->search_start = search_start_help_view;
9396 view->search_setup = search_setup_help_view;
9397 view->search_next = search_next_view_match;
9399 err = create_help(s);
9400 return err;
9403 static const struct got_error *
9404 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9405 enum tog_view_type request, int y, int x)
9407 const struct got_error *err = NULL;
9409 *new_view = NULL;
9411 switch (request) {
9412 case TOG_VIEW_DIFF:
9413 if (view->type == TOG_VIEW_LOG) {
9414 struct tog_log_view_state *s = &view->state.log;
9416 err = open_diff_view_for_commit(new_view, y, x,
9417 s->selected_entry->commit, s->selected_entry->id,
9418 view, s->repo);
9419 } else
9420 return got_error_msg(GOT_ERR_NOT_IMPL,
9421 "parent/child view pair not supported");
9422 break;
9423 case TOG_VIEW_BLAME:
9424 if (view->type == TOG_VIEW_TREE) {
9425 struct tog_tree_view_state *s = &view->state.tree;
9427 err = blame_tree_entry(new_view, y, x,
9428 s->selected_entry, &s->parents, s->commit_id,
9429 s->repo);
9430 } else
9431 return got_error_msg(GOT_ERR_NOT_IMPL,
9432 "parent/child view pair not supported");
9433 break;
9434 case TOG_VIEW_LOG:
9435 if (view->type == TOG_VIEW_BLAME)
9436 err = log_annotated_line(new_view, y, x,
9437 view->state.blame.repo, view->state.blame.id_to_log);
9438 else if (view->type == TOG_VIEW_TREE)
9439 err = log_selected_tree_entry(new_view, y, x,
9440 &view->state.tree);
9441 else if (view->type == TOG_VIEW_REF)
9442 err = log_ref_entry(new_view, y, x,
9443 view->state.ref.selected_entry,
9444 view->state.ref.repo);
9445 else
9446 return got_error_msg(GOT_ERR_NOT_IMPL,
9447 "parent/child view pair not supported");
9448 break;
9449 case TOG_VIEW_TREE:
9450 if (view->type == TOG_VIEW_LOG)
9451 err = browse_commit_tree(new_view, y, x,
9452 view->state.log.selected_entry,
9453 view->state.log.in_repo_path,
9454 view->state.log.head_ref_name,
9455 view->state.log.repo);
9456 else if (view->type == TOG_VIEW_REF)
9457 err = browse_ref_tree(new_view, y, x,
9458 view->state.ref.selected_entry,
9459 view->state.ref.repo);
9460 else
9461 return got_error_msg(GOT_ERR_NOT_IMPL,
9462 "parent/child view pair not supported");
9463 break;
9464 case TOG_VIEW_REF:
9465 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9466 if (*new_view == NULL)
9467 return got_error_from_errno("view_open");
9468 if (view->type == TOG_VIEW_LOG)
9469 err = open_ref_view(*new_view, view->state.log.repo);
9470 else if (view->type == TOG_VIEW_TREE)
9471 err = open_ref_view(*new_view, view->state.tree.repo);
9472 else
9473 err = got_error_msg(GOT_ERR_NOT_IMPL,
9474 "parent/child view pair not supported");
9475 if (err)
9476 view_close(*new_view);
9477 break;
9478 case TOG_VIEW_HELP:
9479 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9480 if (*new_view == NULL)
9481 return got_error_from_errno("view_open");
9482 err = open_help_view(*new_view, view);
9483 if (err)
9484 view_close(*new_view);
9485 break;
9486 default:
9487 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9490 return err;
9494 * If view was scrolled down to move the selected line into view when opening a
9495 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9497 static void
9498 offset_selection_up(struct tog_view *view)
9500 switch (view->type) {
9501 case TOG_VIEW_BLAME: {
9502 struct tog_blame_view_state *s = &view->state.blame;
9503 if (s->first_displayed_line == 1) {
9504 s->selected_line = MAX(s->selected_line - view->offset,
9505 1);
9506 break;
9508 if (s->first_displayed_line > view->offset)
9509 s->first_displayed_line -= view->offset;
9510 else
9511 s->first_displayed_line = 1;
9512 s->selected_line += view->offset;
9513 break;
9515 case TOG_VIEW_LOG:
9516 log_scroll_up(&view->state.log, view->offset);
9517 view->state.log.selected += view->offset;
9518 break;
9519 case TOG_VIEW_REF:
9520 ref_scroll_up(&view->state.ref, view->offset);
9521 view->state.ref.selected += view->offset;
9522 break;
9523 case TOG_VIEW_TREE:
9524 tree_scroll_up(&view->state.tree, view->offset);
9525 view->state.tree.selected += view->offset;
9526 break;
9527 default:
9528 break;
9531 view->offset = 0;
9535 * If the selected line is in the section of screen covered by the bottom split,
9536 * scroll down offset lines to move it into view and index its new position.
9538 static const struct got_error *
9539 offset_selection_down(struct tog_view *view)
9541 const struct got_error *err = NULL;
9542 const struct got_error *(*scrolld)(struct tog_view *, int);
9543 int *selected = NULL;
9544 int header, offset;
9546 switch (view->type) {
9547 case TOG_VIEW_BLAME: {
9548 struct tog_blame_view_state *s = &view->state.blame;
9549 header = 3;
9550 scrolld = NULL;
9551 if (s->selected_line > view->nlines - header) {
9552 offset = abs(view->nlines - s->selected_line - header);
9553 s->first_displayed_line += offset;
9554 s->selected_line -= offset;
9555 view->offset = offset;
9557 break;
9559 case TOG_VIEW_LOG: {
9560 struct tog_log_view_state *s = &view->state.log;
9561 scrolld = &log_scroll_down;
9562 header = view_is_parent_view(view) ? 3 : 2;
9563 selected = &s->selected;
9564 break;
9566 case TOG_VIEW_REF: {
9567 struct tog_ref_view_state *s = &view->state.ref;
9568 scrolld = &ref_scroll_down;
9569 header = 3;
9570 selected = &s->selected;
9571 break;
9573 case TOG_VIEW_TREE: {
9574 struct tog_tree_view_state *s = &view->state.tree;
9575 scrolld = &tree_scroll_down;
9576 header = 5;
9577 selected = &s->selected;
9578 break;
9580 default:
9581 selected = NULL;
9582 scrolld = NULL;
9583 header = 0;
9584 break;
9587 if (selected && *selected > view->nlines - header) {
9588 offset = abs(view->nlines - *selected - header);
9589 view->offset = offset;
9590 if (scrolld && offset) {
9591 err = scrolld(view, offset);
9592 *selected -= offset;
9596 return err;
9599 static void
9600 list_commands(FILE *fp)
9602 size_t i;
9604 fprintf(fp, "commands:");
9605 for (i = 0; i < nitems(tog_commands); i++) {
9606 const struct tog_cmd *cmd = &tog_commands[i];
9607 fprintf(fp, " %s", cmd->name);
9609 fputc('\n', fp);
9612 __dead static void
9613 usage(int hflag, int status)
9615 FILE *fp = (status == 0) ? stdout : stderr;
9617 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9618 getprogname());
9619 if (hflag) {
9620 fprintf(fp, "lazy usage: %s path\n", getprogname());
9621 list_commands(fp);
9623 exit(status);
9626 static char **
9627 make_argv(int argc, ...)
9629 va_list ap;
9630 char **argv;
9631 int i;
9633 va_start(ap, argc);
9635 argv = calloc(argc, sizeof(char *));
9636 if (argv == NULL)
9637 err(1, "calloc");
9638 for (i = 0; i < argc; i++) {
9639 argv[i] = strdup(va_arg(ap, char *));
9640 if (argv[i] == NULL)
9641 err(1, "strdup");
9644 va_end(ap);
9645 return argv;
9649 * Try to convert 'tog path' into a 'tog log path' command.
9650 * The user could simply have mistyped the command rather than knowingly
9651 * provided a path. So check whether argv[0] can in fact be resolved
9652 * to a path in the HEAD commit and print a special error if not.
9653 * This hack is for mpi@ <3
9655 static const struct got_error *
9656 tog_log_with_path(int argc, char *argv[])
9658 const struct got_error *error = NULL, *close_err;
9659 const struct tog_cmd *cmd = NULL;
9660 struct got_repository *repo = NULL;
9661 struct got_worktree *worktree = NULL;
9662 struct got_object_id *commit_id = NULL, *id = NULL;
9663 struct got_commit_object *commit = NULL;
9664 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9665 char *commit_id_str = NULL, **cmd_argv = NULL;
9666 int *pack_fds = NULL;
9668 cwd = getcwd(NULL, 0);
9669 if (cwd == NULL)
9670 return got_error_from_errno("getcwd");
9672 error = got_repo_pack_fds_open(&pack_fds);
9673 if (error != NULL)
9674 goto done;
9676 error = got_worktree_open(&worktree, cwd);
9677 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9678 goto done;
9680 if (worktree)
9681 repo_path = strdup(got_worktree_get_repo_path(worktree));
9682 else
9683 repo_path = strdup(cwd);
9684 if (repo_path == NULL) {
9685 error = got_error_from_errno("strdup");
9686 goto done;
9689 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9690 if (error != NULL)
9691 goto done;
9693 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9694 repo, worktree);
9695 if (error)
9696 goto done;
9698 error = tog_load_refs(repo, 0);
9699 if (error)
9700 goto done;
9701 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9702 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9703 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9704 if (error)
9705 goto done;
9707 if (worktree) {
9708 got_worktree_close(worktree);
9709 worktree = NULL;
9712 error = got_object_open_as_commit(&commit, repo, commit_id);
9713 if (error)
9714 goto done;
9716 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9717 if (error) {
9718 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9719 goto done;
9720 fprintf(stderr, "%s: '%s' is no known command or path\n",
9721 getprogname(), argv[0]);
9722 usage(1, 1);
9723 /* not reached */
9726 error = got_object_id_str(&commit_id_str, commit_id);
9727 if (error)
9728 goto done;
9730 cmd = &tog_commands[0]; /* log */
9731 argc = 4;
9732 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9733 error = cmd->cmd_main(argc, cmd_argv);
9734 done:
9735 if (repo) {
9736 close_err = got_repo_close(repo);
9737 if (error == NULL)
9738 error = close_err;
9740 if (commit)
9741 got_object_commit_close(commit);
9742 if (worktree)
9743 got_worktree_close(worktree);
9744 if (pack_fds) {
9745 const struct got_error *pack_err =
9746 got_repo_pack_fds_close(pack_fds);
9747 if (error == NULL)
9748 error = pack_err;
9750 free(id);
9751 free(commit_id_str);
9752 free(commit_id);
9753 free(cwd);
9754 free(repo_path);
9755 free(in_repo_path);
9756 if (cmd_argv) {
9757 int i;
9758 for (i = 0; i < argc; i++)
9759 free(cmd_argv[i]);
9760 free(cmd_argv);
9762 tog_free_refs();
9763 return error;
9766 int
9767 main(int argc, char *argv[])
9769 const struct got_error *io_err, *error = NULL;
9770 const struct tog_cmd *cmd = NULL;
9771 int ch, hflag = 0, Vflag = 0;
9772 char **cmd_argv = NULL;
9773 static const struct option longopts[] = {
9774 { "version", no_argument, NULL, 'V' },
9775 { NULL, 0, NULL, 0}
9777 char *diff_algo_str = NULL;
9778 const char *test_script_path;
9780 setlocale(LC_CTYPE, "");
9783 * Test mode init must happen before pledge() because "tty" will
9784 * not allow TTY-related ioctls to occur via regular files.
9786 test_script_path = getenv("TOG_TEST_SCRIPT");
9787 if (test_script_path != NULL) {
9788 error = init_mock_term(test_script_path);
9789 if (error) {
9790 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9791 return 1;
9795 #if !defined(PROFILE)
9796 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9797 NULL) == -1)
9798 err(1, "pledge");
9799 #endif
9801 if (!isatty(STDIN_FILENO))
9802 errx(1, "standard input is not a tty");
9804 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9805 switch (ch) {
9806 case 'h':
9807 hflag = 1;
9808 break;
9809 case 'V':
9810 Vflag = 1;
9811 break;
9812 default:
9813 usage(hflag, 1);
9814 /* NOTREACHED */
9818 argc -= optind;
9819 argv += optind;
9820 optind = 1;
9821 optreset = 1;
9823 if (Vflag) {
9824 got_version_print_str();
9825 return 0;
9828 if (argc == 0) {
9829 if (hflag)
9830 usage(hflag, 0);
9831 /* Build an argument vector which runs a default command. */
9832 cmd = &tog_commands[0];
9833 argc = 1;
9834 cmd_argv = make_argv(argc, cmd->name);
9835 } else {
9836 size_t i;
9838 /* Did the user specify a command? */
9839 for (i = 0; i < nitems(tog_commands); i++) {
9840 if (strncmp(tog_commands[i].name, argv[0],
9841 strlen(argv[0])) == 0) {
9842 cmd = &tog_commands[i];
9843 break;
9848 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9849 if (diff_algo_str) {
9850 if (strcasecmp(diff_algo_str, "patience") == 0)
9851 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9852 if (strcasecmp(diff_algo_str, "myers") == 0)
9853 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9856 if (cmd == NULL) {
9857 if (argc != 1)
9858 usage(0, 1);
9859 /* No command specified; try log with a path */
9860 error = tog_log_with_path(argc, argv);
9861 } else {
9862 if (hflag)
9863 cmd->cmd_usage();
9864 else
9865 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9868 if (using_mock_io) {
9869 io_err = tog_io_close();
9870 if (error == NULL)
9871 error = io_err;
9873 endwin();
9874 if (cmd_argv) {
9875 int i;
9876 for (i = 0; i < argc; i++)
9877 free(cmd_argv[i]);
9878 free(cmd_argv);
9881 if (error && error->code != GOT_ERR_CANCELLED &&
9882 error->code != GOT_ERR_EOF &&
9883 error->code != GOT_ERR_PRIVSEP_EXIT &&
9884 error->code != GOT_ERR_PRIVSEP_PIPE &&
9885 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9886 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9887 return 0;